pidl/Python: fix talloc hierachy in FromPythonToUnionFunction()
[metze/samba/wip.git] / pidl / lib / Parse / Pidl / Samba4 / Python.pm
1 ###################################################
2 # Python function wrapper generator
3 # Copyright jelmer@samba.org 2007-2008
4 # released under the GNU GPL
5
6 package Parse::Pidl::Samba4::Python;
7
8 use Exporter;
9 @ISA = qw(Exporter);
10
11 use strict;
12 use Parse::Pidl qw(warning fatal error);
13 use Parse::Pidl::Typelist qw(hasType resolveType getType mapTypeName expandAlias bitmap_type_fn enum_type_fn);
14 use Parse::Pidl::Util qw(has_property ParseExpr unmake_str);
15 use Parse::Pidl::NDR qw(ReturnTypeElement GetPrevLevel GetNextLevel ContainsDeferred ContainsPipe is_charset_array);
16 use Parse::Pidl::CUtil qw(get_value_of get_pointer_to);
17 use Parse::Pidl::Samba4 qw(ArrayDynamicallyAllocated);
18 use Parse::Pidl::Samba4::Header qw(GenerateFunctionInEnv GenerateFunctionOutEnv EnvSubstituteValue GenerateStructEnv);
19
20 use vars qw($VERSION);
21 $VERSION = '0.01';
22
23 sub new($) {
24         my ($class) = @_;
25         my $self = { res => "", res_hdr => "", tabs => "",
26                                  constants => [], constants_uniq => {},
27                                  module_methods => [],
28                                  module_objects => [], module_objects_uniq => {},
29                                  ready_types => [],
30                                  module_imports => [], module_imports_uniq => {},
31                                  type_imports => [], type_imports_uniq => {},
32                                  patch_type_calls => [], prereadycode => [],
33                                  postreadycode => []};
34         bless($self, $class);
35 }
36
37 sub pidl_hdr ($$)
38 {
39         my $self = shift;
40         $self->{res_hdr} .= shift;
41 }
42
43 sub pidl($$)
44 {
45         my ($self, $d) = @_;
46         if ($d) {
47                 if ((!($d =~ /^#/))) {
48                         $self->{res} .= $self->{tabs};
49                 }
50                 $self->{res} .= $d;
51         }
52         $self->{res} .= "\n";
53 }
54
55 sub indent($)
56 {
57         my ($self) = @_;
58         $self->{tabs} .= "\t";
59 }
60
61 sub deindent($)
62 {
63         my ($self) = @_;
64         $self->{tabs} = substr($self->{tabs}, 0, -1);
65 }
66
67 sub PrettifyTypeName($$)
68 {
69         my ($name, $basename) = @_;
70
71         $basename =~ s/^.*\.([^.]+)$/\1/;
72
73         $name =~ s/^$basename\_//;
74
75
76         return $name;
77 }
78
79 sub Import
80 {
81         my $self = shift;
82         my @imports = @_;
83         foreach (@imports) {
84                 $_ = unmake_str($_);
85                 s/\.idl$//;
86                 $self->pidl_hdr("#include \"librpc/gen_ndr/$_\.h\"\n");
87                 $self->register_module_import("samba.dcerpc.$_");
88         }
89 }
90
91 sub Const($$)
92 {
93     my ($self, $const) = @_;
94         $self->register_constant($const->{NAME}, $const->{DTYPE}, $const->{VALUE});
95 }
96
97 sub register_constant($$$$)
98 {
99         my ($self, $name, $type, $value) = @_;
100
101         unless (defined $self->{constants_uniq}->{$name}) {
102                 my $h = {"key" => $name, "val" => [$type, $value]};
103                 push @{$self->{constants}}, $h;
104                 $self->{constants_uniq}->{$name} = $h;
105         }
106 }
107
108 sub EnumAndBitmapConsts($$$)
109 {
110         my ($self, $name, $d) = @_;
111
112         return unless (defined($d->{ELEMENTS}));
113
114         foreach my $e (@{$d->{ELEMENTS}}) {
115                 $e =~ /^([A-Za-z0-9_]+)/;
116                 my $cname = $1;
117
118                 $self->register_constant($cname, $d, $cname);
119         }
120 }
121
122 sub FromUnionToPythonFunction($$$$)
123 {
124         my ($self, $mem_ctx, $type, $switch, $name) = @_;
125
126         my $has_default = 0;
127
128         $self->pidl("PyObject *ret = NULL;");
129         $self->pidl("");
130
131         $self->pidl("switch ($switch) {");
132
133         foreach my $e (@{$type->{ELEMENTS}}) {
134                 $self->pidl("$e->{CASE}:");
135                 if ($e->{CASE} eq "default") { $has_default = 1; }
136
137                 $self->indent;
138
139                 if ($e->{NAME}) {
140                         $self->ConvertObjectToPython($mem_ctx, {}, $e, "$name->$e->{NAME}", "ret", "return NULL;");
141                 } else {
142                         $self->pidl("ret = Py_None;");
143                         $self->pidl("Py_INCREF(ret);");
144                 }
145
146                 $self->pidl("break;");
147                 $self->pidl("");
148
149                 $self->deindent;
150         }
151
152         if (!$has_default) {
153                 $self->pidl("default:");
154                 $self->indent;
155                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"unknown union level\");");
156                 $self->pidl("ret = NULL;");
157                 $self->pidl("break;");
158                 $self->deindent;
159         }
160
161         $self->pidl("}");
162         $self->pidl("");
163         $self->pidl("return ret;");
164 }
165
166 sub FromPythonToUnionFunction($$$$$)
167 {
168         my ($self, $type, $typename, $switch, $mem_ctx, $name) = @_;
169
170         my $has_default = 0;
171
172         $self->pidl("$typename *ret = talloc_zero($mem_ctx, $typename);");
173
174         $self->pidl("switch ($switch) {");
175         $self->indent;
176
177         foreach my $e (@{$type->{ELEMENTS}}) {
178                 $self->pidl("$e->{CASE}:");
179                 if ($e->{CASE} eq "default") { $has_default = 1; }
180                 $self->indent;
181                 if ($e->{NAME}) {
182                         $self->ConvertObjectFromPython({}, "ret", $e, $name, "ret->$e->{NAME}", "talloc_free(ret); return NULL;");
183                 }
184                 $self->pidl("break;");
185                 $self->deindent;
186                 $self->pidl("");
187         }
188
189         if (!$has_default) {
190                 $self->pidl("default:");
191                 $self->indent;
192                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"invalid union level value\");");
193                 $self->pidl("talloc_free(ret);");
194                 $self->pidl("ret = NULL;");
195                 $self->deindent;
196         }
197
198         $self->deindent;
199         $self->pidl("}");
200         $self->pidl("");
201         $self->pidl("return ret;");
202 }
203
204 sub PythonElementGetSet($$$$$$) {
205         my ($self, $name, $cname, $ename, $e, $env) = @_;
206
207         my $varname = "object->$ename";
208         $self->pidl("static PyObject *py_$name\_get_$e->{NAME}(PyObject *obj, void *closure)");
209         $self->pidl("{");
210         $self->indent;
211         $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(obj);");
212         $self->pidl("PyObject *py_$e->{NAME};");
213         $self->ConvertObjectToPython("pytalloc_get_mem_ctx(obj)", $env, $e, $varname, "py_$e->{NAME}", "return NULL;");
214         $self->pidl("return py_$e->{NAME};");
215         $self->deindent;
216         $self->pidl("}");
217         $self->pidl("");
218
219         $self->pidl("static int py_$name\_set_$e->{NAME}(PyObject *py_obj, PyObject *value, void *closure)");
220         $self->pidl("{");
221         $self->indent;
222         $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
223         my $mem_ctx = "pytalloc_get_mem_ctx(py_obj)";
224         my $l = $e->{LEVELS}[0];
225         my $nl = GetNextLevel($e, $l);
226         if ($l->{TYPE} eq "POINTER" and
227                 not ($nl->{TYPE} eq "ARRAY" and ($nl->{IS_FIXED} or is_charset_array($e, $nl))) and
228                 not ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE}))) {
229                 $self->pidl("talloc_unlink($mem_ctx, discard_const($varname));");
230         }
231         $self->ConvertObjectFromPython($env, $mem_ctx, $e, "value", $varname, "return -1;");
232         $self->pidl("return 0;");
233         $self->deindent;
234         $self->pidl("}");
235         $self->pidl("");
236 }
237
238 sub PythonStruct($$$$$$)
239 {
240         my ($self, $modulename, $prettyname, $name, $cname, $d) = @_;
241
242         my $env = GenerateStructEnv($d, "object");
243
244         $self->pidl("");
245
246         my $getsetters = "NULL";
247
248         if ($#{$d->{ELEMENTS}} > -1) {
249                 foreach my $e (@{$d->{ELEMENTS}}) {
250                         $self->PythonElementGetSet($name, $cname, $e->{NAME}, $e, $env);
251                 }
252
253                 $getsetters = "py_$name\_getsetters";
254                 $self->pidl("static PyGetSetDef ".$getsetters."[] = {");
255                 $self->indent;
256                 foreach my $e (@{$d->{ELEMENTS}}) {
257                         my $etype = "";
258                         if (ref($e->{TYPE}) eq "HASH") {
259                                 $etype = $e->{TYPE}->{NAME};
260                         } else {
261                                 $etype = $e->{TYPE};
262                         }
263                         $self->pidl("{");
264                         $self->indent;
265                         $self->pidl(".name = discard_const_p(char, \"$e->{NAME}\"),");
266                         $self->pidl(".get = py_$name\_get_$e->{NAME},");
267                         $self->pidl(".set = py_$name\_set_$e->{NAME},");
268                         $self->pidl(".doc = discard_const_p(char, \"PIDL-generated element of base type $etype\")");
269                         $self->deindent;
270                         $self->pidl("},");
271                 }
272                 $self->pidl("{ .name = NULL }");
273                 $self->deindent;
274                 $self->pidl("};");
275                 $self->pidl("");
276         }
277
278         $self->pidl("static PyObject *py_$name\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
279         $self->pidl("{");
280         $self->indent;
281         $self->pidl("return pytalloc_new($cname, type);");
282         $self->deindent;
283         $self->pidl("}");
284         $self->pidl("");
285
286         my $py_methods = "NULL";
287
288         # If the struct is not public there ndr_pull/ndr_push functions will
289         # be static so not callable from here
290         if (has_property($d, "public")) {
291                 $self->pidl("static PyObject *py_$name\_ndr_pack(PyObject *py_obj)");
292                 $self->pidl("{");
293                 $self->indent;
294                 $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
295                 $self->pidl("PyObject *ret = NULL;");
296                 $self->pidl("DATA_BLOB blob;");
297                 $self->pidl("enum ndr_err_code err;");
298                 $self->pidl("TALLOC_CTX *tmp_ctx = talloc_new(pytalloc_get_mem_ctx(py_obj));");
299                 $self->pidl("if (tmp_ctx == NULL) {");
300                 $self->indent;
301                 $self->pidl("PyErr_SetNdrError(NDR_ERR_ALLOC);");
302                 $self->pidl("return NULL;");
303                 $self->deindent;
304                 $self->pidl("}");
305                 $self->pidl("err = ndr_push_struct_blob(&blob, tmp_ctx, object, (ndr_push_flags_fn_t)ndr_push_$name);");
306                 $self->pidl("if (!NDR_ERR_CODE_IS_SUCCESS(err)) {");
307                 $self->indent;
308                 $self->pidl("TALLOC_FREE(tmp_ctx);");
309                 $self->pidl("PyErr_SetNdrError(err);");
310                 $self->pidl("return NULL;");
311                 $self->deindent;
312                 $self->pidl("}");
313                 $self->pidl("");
314                 $self->pidl("ret = PyBytes_FromStringAndSize((char *)blob.data, blob.length);");
315                 $self->pidl("TALLOC_FREE(tmp_ctx);");
316                 $self->pidl("return ret;");
317                 $self->deindent;
318                 $self->pidl("}");
319                 $self->pidl("");
320
321                 $self->pidl("static PyObject *py_$name\_ndr_unpack(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
322                 $self->pidl("{");
323                 $self->indent;
324                 $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
325                 $self->pidl("DATA_BLOB blob;");
326                 $self->pidl("Py_ssize_t blob_length = 0;");
327                 $self->pidl("enum ndr_err_code err;");
328                 $self->pidl("const char * const kwnames[] = { \"data_blob\", \"allow_remaining\", NULL };");
329                 $self->pidl("PyObject *allow_remaining_obj = NULL;");
330                 $self->pidl("bool allow_remaining = false;");
331                 $self->pidl("");
332                 $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, PYARG_BYTES_LEN \"|O:__ndr_unpack__\",");
333                 $self->indent;
334                 $self->pidl("discard_const_p(char *, kwnames),");
335                 $self->pidl("&blob.data, &blob_length,");
336                 $self->pidl("&allow_remaining_obj)) {");
337                 $self->deindent;
338                 $self->indent;
339                 $self->pidl("return NULL;");
340                 $self->deindent;
341                 $self->pidl("}");
342                 $self->pidl("blob.length = blob_length;");
343                 $self->pidl("");
344                 $self->pidl("if (allow_remaining_obj && PyObject_IsTrue(allow_remaining_obj)) {");
345                 $self->indent;
346                 $self->pidl("allow_remaining = true;");
347                 $self->deindent;
348                 $self->pidl("}");
349                 $self->pidl("");
350                 $self->pidl("if (allow_remaining) {");
351                 $self->indent;
352                 $self->pidl("err = ndr_pull_struct_blob(&blob, pytalloc_get_mem_ctx(py_obj), object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
353                 $self->deindent;
354                 $self->pidl("} else {");
355                 $self->indent;
356                 $self->pidl("err = ndr_pull_struct_blob_all(&blob, pytalloc_get_mem_ctx(py_obj), object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
357                 $self->deindent;
358                 $self->pidl("}");
359                 $self->pidl("if (!NDR_ERR_CODE_IS_SUCCESS(err)) {");
360                 $self->indent;
361                 $self->pidl("PyErr_SetNdrError(err);");
362                 $self->pidl("return NULL;");
363                 $self->deindent;
364                 $self->pidl("}");
365                 $self->pidl("");
366                 $self->pidl("Py_RETURN_NONE;");
367                 $self->deindent;
368                 $self->pidl("}");
369                 $self->pidl("");
370
371                 $self->pidl("static PyObject *py_$name\_ndr_print(PyObject *py_obj)");
372                 $self->pidl("{");
373                 $self->indent;
374                 $self->pidl("$cname *object = ($cname *)pytalloc_get_ptr(py_obj);");
375                 $self->pidl("PyObject *ret;");
376                 $self->pidl("char *retstr;");
377                 $self->pidl("");
378                 $self->pidl("retstr = ndr_print_struct_string(pytalloc_get_mem_ctx(py_obj), (ndr_print_fn_t)ndr_print_$name, \"$name\", object);");
379                 $self->pidl("ret = PyStr_FromString(retstr);");
380                 $self->pidl("talloc_free(retstr);");
381                 $self->pidl("");
382                 $self->pidl("return ret;");
383                 $self->deindent;
384                 $self->pidl("}");
385                 $self->pidl("");
386
387                 $py_methods = "py_$name\_methods";
388                 $self->pidl("static PyMethodDef $py_methods\[] = {");
389                 $self->indent;
390                 $self->pidl("{ \"__ndr_pack__\", (PyCFunction)py_$name\_ndr_pack, METH_NOARGS, \"S.ndr_pack(object) -> blob\\nNDR pack\" },");
391                 $self->pidl("{ \"__ndr_unpack__\", (PyCFunction)py_$name\_ndr_unpack, METH_VARARGS|METH_KEYWORDS, \"S.ndr_unpack(class, blob, allow_remaining=False) -> None\\nNDR unpack\" },");
392                 $self->pidl("{ \"__ndr_print__\", (PyCFunction)py_$name\_ndr_print, METH_NOARGS, \"S.ndr_print(object) -> None\\nNDR print\" },");
393                 $self->pidl("{ NULL, NULL, 0, NULL }");
394                 $self->deindent;
395                 $self->pidl("};");
396                 $self->pidl("");
397         }
398
399         $self->pidl_hdr("static PyTypeObject $name\_Type;\n");
400         $self->pidl("");
401         my $docstring = $self->DocString($d, $name);
402         my $typeobject = "$name\_Type";
403         $self->pidl("static PyTypeObject $typeobject = {");
404         $self->indent;
405         $self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
406         $self->pidl(".tp_name = \"$modulename.$prettyname\",");
407         $self->pidl(".tp_getset = $getsetters,");
408         if ($docstring) {
409                 $self->pidl(".tp_doc = $docstring,");
410         }
411         $self->pidl(".tp_methods = $py_methods,");
412         $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
413         $self->pidl(".tp_new = py_$name\_new,");
414         $self->deindent;
415         $self->pidl("};");
416
417         $self->pidl("");
418
419         my $talloc_typename = $self->import_type_variable("talloc", "BaseObject");
420         $self->register_module_prereadycode(["$name\_Type.tp_base = $talloc_typename;",
421                                              "$name\_Type.tp_basicsize = pytalloc_BaseObject_size();",
422                                              ""]);
423
424         return "&$typeobject";
425 }
426
427 sub PythonFunctionStruct($$$$)
428 {
429         my ($self, $modulename, $fn, $iface, $prettyname) = @_;
430
431         my $inenv = GenerateFunctionInEnv($fn, "object->");
432         my $outenv = GenerateFunctionOutEnv($fn, "object->");
433
434         my $name = "$fn->{NAME}";
435         my $cname = "struct $name";
436
437         $self->pidl("");
438
439         my $getsetters = "NULL";
440
441         foreach my $e (@{$fn->{ELEMENTS}}) {
442                 if (grep(/in/,@{$e->{DIRECTION}})) {
443                         my $inname = "$name\_in";
444                         my $ename = "in.$e->{NAME}";
445                         $self->PythonElementGetSet($inname, $cname, $ename, $e, $inenv);
446                 }
447                 if (grep(/out/,@{$e->{DIRECTION}})) {
448                         my $outname = "$name\_out";
449                         my $ename = "out.$e->{NAME}";
450                         $self->PythonElementGetSet($outname, $cname, $ename, $e, $outenv);
451                 }
452         }
453
454         if (defined($fn->{RETURN_TYPE})) {
455                 my $e = ReturnTypeElement($fn);
456                 my $ename = "out.result";
457                 $self->PythonElementGetSet($name, $cname, $ename, $e, $outenv);
458         }
459
460         $getsetters = "py_$name\_getsetters";
461         $self->pidl("static PyGetSetDef ".$getsetters."[] = {");
462         $self->indent;
463         foreach my $e (@{$fn->{ELEMENTS}}) {
464                 if (grep(/in/,@{$e->{DIRECTION}})) {
465                         $self->pidl("{");
466                         $self->indent;
467                         $self->pidl(".name = discard_const_p(char, \"in_$e->{NAME}\"),");
468                         $self->pidl(".get = py_$name\_in_get_$e->{NAME},");
469                         $self->pidl(".set = py_$name\_in_set_$e->{NAME},");
470                         $self->pidl(".doc = discard_const_p(char, \"PIDL-generated element of base type $e->{TYPE}\")");
471                         $self->deindent;
472                         $self->pidl("},");
473                 }
474                 if (grep(/out/,@{$e->{DIRECTION}})) {
475                         $self->pidl("{");
476                         $self->indent;
477                         $self->pidl(".name = discard_const_p(char, \"out_$e->{NAME}\"),");
478                         $self->pidl(".get = py_$name\_out_get_$e->{NAME},");
479                         $self->pidl(".set = py_$name\_out_set_$e->{NAME},");
480                         $self->pidl(".doc = discard_const_p(char, \"PIDL-generated element of base type $e->{TYPE}\")");
481                         $self->deindent;
482                         $self->pidl("},");
483                 }
484         }
485         if (defined($fn->{RETURN_TYPE})) {
486                 $self->pidl("{");
487                 $self->indent;
488                 $self->pidl(".name = discard_const_p(char, \"result\"),");
489                 $self->pidl(".get = py_$name\_get_result,");
490                 $self->pidl(".set = py_$name\_set_result,");
491                 $self->pidl(".doc = discard_const_p(char, \"PIDL-generated element of type $fn->{RETURN_TYPE}\")");
492                 $self->deindent;
493                 $self->pidl("},");
494         }
495         $self->pidl("{ .name = NULL }");
496         $self->deindent;
497         $self->pidl("};");
498         $self->pidl("");
499
500         $self->pidl("static PyObject *py_$name\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
501         $self->pidl("{");
502         $self->indent;
503         $self->pidl("return pytalloc_new($cname, type);");
504         $self->deindent;
505         $self->pidl("}");
506         $self->pidl("");
507
508         my $py_methods = "NULL";
509
510         my $ndr_call = "const struct ndr_interface_call *call = NULL;";
511         my $object_ptr = "$cname *object = ($cname *)pytalloc_get_ptr(py_obj);";
512
513         $self->pidl("static PyObject *py_$name\_ndr_opnum(PyTypeObject *type)");
514         $self->pidl("{");
515         $self->indent;
516         $self->pidl("");
517         $self->pidl("");
518         $self->pidl("return PyInt_FromLong($fn->{OPNUM});");
519         $self->deindent;
520         $self->pidl("}");
521         $self->pidl("");
522
523         $self->pidl("static PyObject *py_$name\_ndr_pack(PyObject *py_obj, int ndr_inout_flags, uint32_t ndr_push_flags)");
524         $self->pidl("{");
525         $self->indent;
526         $self->pidl("$ndr_call");
527         $self->pidl("$object_ptr");
528         $self->pidl("PyObject *ret = NULL;");
529         $self->pidl("struct ndr_push *push = NULL;");
530         $self->pidl("DATA_BLOB blob;");
531         $self->pidl("enum ndr_err_code err;");
532         $self->pidl("");
533         $self->pidl("if (ndr_table_$iface\.num_calls < " . ($fn->{OPNUM}+1) .
534                     ") {");
535         $self->indent;
536         $self->pidl("PyErr_SetString(PyExc_TypeError, \"Internal Error, ndr_interface_call missing for py_$name\_ndr_pack\");");
537         $self->pidl("return NULL;");
538         $self->deindent;
539         $self->pidl("}");
540         $self->pidl("call = &ndr_table_$iface\.calls[$fn->{OPNUM}];");
541         $self->pidl("");
542         $self->pidl("push = ndr_push_init_ctx(pytalloc_get_mem_ctx(py_obj));");
543         $self->pidl("if (push == NULL) {");
544         $self->indent;
545         $self->pidl("PyErr_SetNdrError(NDR_ERR_ALLOC);");
546         $self->pidl("return NULL;");
547         $self->deindent;
548         $self->pidl("}");
549         $self->pidl("");
550         $self->pidl("push->flags |= ndr_push_flags;");
551         $self->pidl("");
552         $self->pidl("err = call->ndr_push(push, ndr_inout_flags, object);");
553         $self->pidl("if (!NDR_ERR_CODE_IS_SUCCESS(err)) {");
554         $self->indent;
555         $self->pidl("TALLOC_FREE(push);");
556         $self->pidl("PyErr_SetNdrError(err);");
557         $self->pidl("return NULL;");
558         $self->deindent;
559         $self->pidl("}");
560         $self->pidl("blob = ndr_push_blob(push);");
561         $self->pidl("ret = PyBytes_FromStringAndSize((char *)blob.data, blob.length);");
562         $self->pidl("TALLOC_FREE(push);");
563         $self->pidl("return ret;");
564         $self->deindent;
565         $self->pidl("}");
566         $self->pidl("");
567
568         $self->pidl("static PyObject *py_$name\_ndr_pack_in(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
569         $self->pidl("{");
570         $self->indent;
571         $self->pidl("const char * const kwnames[] = { \"bigendian\", \"ndr64\", NULL };");
572         $self->pidl("PyObject *bigendian_obj = NULL;");
573         $self->pidl("PyObject *ndr64_obj = NULL;");
574         $self->pidl("uint32_t ndr_push_flags = 0;");
575         $self->pidl("");
576         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"|OO:__ndr_pack_in__\",");
577         $self->indent;
578         $self->pidl("discard_const_p(char *, kwnames),");
579         $self->pidl("&bigendian_obj,");
580         $self->pidl("&ndr64_obj)) {");
581         $self->deindent;
582         $self->indent;
583         $self->pidl("return NULL;");
584         $self->deindent;
585         $self->pidl("}");
586         $self->pidl("");
587         $self->pidl("if (bigendian_obj && PyObject_IsTrue(bigendian_obj)) {");
588         $self->indent;
589         $self->pidl("ndr_push_flags |= LIBNDR_FLAG_BIGENDIAN;");
590         $self->deindent;
591         $self->pidl("}");
592         $self->pidl("if (ndr64_obj && PyObject_IsTrue(ndr64_obj)) {");
593         $self->indent;
594         $self->pidl("ndr_push_flags |= LIBNDR_FLAG_NDR64;");
595         $self->deindent;
596         $self->pidl("}");
597         $self->pidl("");
598         $self->pidl("return py_$name\_ndr_pack(py_obj, NDR_IN, ndr_push_flags);");
599         $self->deindent;
600         $self->pidl("}");
601         $self->pidl("");
602
603         $self->pidl("static PyObject *py_$name\_ndr_pack_out(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
604         $self->pidl("{");
605         $self->indent;
606         $self->pidl("const char * const kwnames[] = { \"bigendian\", \"ndr64\", NULL };");
607         $self->pidl("PyObject *bigendian_obj = NULL;");
608         $self->pidl("PyObject *ndr64_obj = NULL;");
609         $self->pidl("uint32_t ndr_push_flags = 0;");
610         $self->pidl("");
611         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"|OO:__ndr_pack_out__\",");
612         $self->indent;
613         $self->pidl("discard_const_p(char *, kwnames),");
614         $self->pidl("&bigendian_obj,");
615         $self->pidl("&ndr64_obj)) {");
616         $self->deindent;
617         $self->indent;
618         $self->pidl("return NULL;");
619         $self->deindent;
620         $self->pidl("}");
621         $self->pidl("");
622         $self->pidl("if (bigendian_obj && PyObject_IsTrue(bigendian_obj)) {");
623         $self->indent;
624         $self->pidl("ndr_push_flags |= LIBNDR_FLAG_BIGENDIAN;");
625         $self->deindent;
626         $self->pidl("}");
627         $self->pidl("if (ndr64_obj && PyObject_IsTrue(ndr64_obj)) {");
628         $self->indent;
629         $self->pidl("ndr_push_flags |= LIBNDR_FLAG_NDR64;");
630         $self->deindent;
631         $self->pidl("}");
632         $self->pidl("");
633         $self->pidl("return py_$name\_ndr_pack(py_obj, NDR_OUT, ndr_push_flags);");
634         $self->deindent;
635         $self->pidl("}");
636         $self->pidl("");
637
638         $self->pidl("static PyObject *py_$name\_ndr_unpack(PyObject *py_obj, const DATA_BLOB *blob, int ndr_inout_flags, uint32_t ndr_pull_flags, bool allow_remaining)");
639         $self->pidl("{");
640         $self->indent;
641         $self->pidl("$ndr_call");
642         $self->pidl("$object_ptr");
643         $self->pidl("struct ndr_pull *pull = NULL;");
644         $self->pidl("enum ndr_err_code err;");
645         $self->pidl("");
646         $self->pidl("if (ndr_table_$iface\.num_calls < " . ($fn->{OPNUM}+1) .
647                     ") {");
648         $self->indent;
649         $self->pidl("PyErr_SetString(PyExc_TypeError, \"Internal Error, ndr_interface_call missing for py_$name\_ndr_unpack\");");
650         $self->pidl("return NULL;");
651         $self->deindent;
652         $self->pidl("}");
653         $self->pidl("call = &ndr_table_$iface\.calls[$fn->{OPNUM}];");
654         $self->pidl("");
655         $self->pidl("pull = ndr_pull_init_blob(blob, object);");
656         $self->pidl("if (pull == NULL) {");
657         $self->indent;
658         $self->pidl("PyErr_SetNdrError(NDR_ERR_ALLOC);");
659         $self->pidl("return NULL;");
660         $self->deindent;
661         $self->pidl("}");
662         $self->pidl("");
663         $self->pidl("pull->flags |= ndr_pull_flags;");
664         $self->pidl("");
665         $self->pidl("err = call->ndr_pull(pull, ndr_inout_flags, object);");
666         $self->pidl("if (!NDR_ERR_CODE_IS_SUCCESS(err)) {");
667         $self->indent;
668         $self->pidl("TALLOC_FREE(pull);");
669         $self->pidl("PyErr_SetNdrError(err);");
670         $self->pidl("return NULL;");
671         $self->deindent;
672         $self->pidl("}");
673         $self->pidl("if (!allow_remaining) {");
674         $self->indent;
675         $self->pidl("uint32_t highest_ofs;");
676         $self->pidl("");
677         $self->pidl("if (pull->offset > pull->relative_highest_offset) {");
678         $self->indent;
679         $self->pidl("highest_ofs = pull->offset;");
680         $self->deindent;
681         $self->pidl("} else {");
682         $self->indent;
683         $self->pidl("highest_ofs = pull->relative_highest_offset;");
684         $self->deindent;
685         $self->pidl("}");
686         $self->pidl("if (highest_ofs < pull->data_size) {");
687         $self->indent;
688         $self->pidl("err = ndr_pull_error(pull, NDR_ERR_UNREAD_BYTES,");
689         $self->indent;
690         $self->pidl("\"not all bytes consumed ofs[%u] size[%u]\",");
691         $self->pidl("highest_ofs, pull->data_size);");
692         $self->deindent;
693         $self->pidl("TALLOC_FREE(pull);");
694         $self->pidl("PyErr_SetNdrError(err);");
695         $self->pidl("return NULL;");
696         $self->deindent;
697         $self->pidl("}");
698         $self->deindent;
699         $self->pidl("}");
700         $self->pidl("");
701         $self->pidl("TALLOC_FREE(pull);");
702         $self->pidl("Py_RETURN_NONE;");
703         $self->deindent;
704         $self->pidl("}");
705         $self->pidl("");
706
707         $self->pidl("static PyObject *py_$name\_ndr_unpack_in(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
708         $self->pidl("{");
709         $self->indent;
710         $self->pidl("DATA_BLOB blob;");
711         $self->pidl("Py_ssize_t blob_length = 0;");
712         $self->pidl("const char * const kwnames[] = { \"data_blob\", \"bigendian\", \"ndr64\", \"allow_remaining\", NULL };");
713         $self->pidl("PyObject *bigendian_obj = NULL;");
714         $self->pidl("PyObject *ndr64_obj = NULL;");
715         $self->pidl("uint32_t ndr_pull_flags = LIBNDR_FLAG_REF_ALLOC;");
716         $self->pidl("PyObject *allow_remaining_obj = NULL;");
717         $self->pidl("bool allow_remaining = false;");
718         $self->pidl("");
719         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, PYARG_BYTES_LEN \"|OOO:__ndr_unpack_in__\",");
720         $self->indent;
721         $self->pidl("discard_const_p(char *, kwnames),");
722         $self->pidl("&blob.data, &blob_length,");
723         $self->pidl("&bigendian_obj,");
724         $self->pidl("&ndr64_obj,");
725         $self->pidl("&allow_remaining_obj)) {");
726         $self->deindent;
727         $self->indent;
728         $self->pidl("return NULL;");
729         $self->deindent;
730         $self->pidl("}");
731         $self->pidl("blob.length = blob_length;");
732         $self->pidl("");
733         $self->pidl("if (bigendian_obj && PyObject_IsTrue(bigendian_obj)) {");
734         $self->indent;
735         $self->pidl("ndr_pull_flags |= LIBNDR_FLAG_BIGENDIAN;");
736         $self->deindent;
737         $self->pidl("}");
738         $self->pidl("if (ndr64_obj && PyObject_IsTrue(ndr64_obj)) {");
739         $self->indent;
740         $self->pidl("ndr_pull_flags |= LIBNDR_FLAG_NDR64;");
741         $self->deindent;
742         $self->pidl("}");
743         $self->pidl("");
744         $self->pidl("if (allow_remaining_obj && PyObject_IsTrue(allow_remaining_obj)) {");
745         $self->indent;
746         $self->pidl("allow_remaining = true;");
747         $self->deindent;
748         $self->pidl("}");
749         $self->pidl("");
750         $self->pidl("return py_$name\_ndr_unpack(py_obj, &blob, NDR_IN, ndr_pull_flags, allow_remaining);");
751         $self->deindent;
752         $self->pidl("}");
753         $self->pidl("");
754
755         $self->pidl("static PyObject *py_$name\_ndr_unpack_out(PyObject *py_obj, PyObject *args, PyObject *kwargs)");
756         $self->pidl("{");
757         $self->indent;
758         $self->pidl("DATA_BLOB blob;");
759         $self->pidl("Py_ssize_t blob_length = 0;");
760         $self->pidl("const char * const kwnames[] = { \"data_blob\", \"bigendian\", \"ndr64\", \"allow_remaining\", NULL };");
761         $self->pidl("PyObject *bigendian_obj = NULL;");
762         $self->pidl("PyObject *ndr64_obj = NULL;");
763         $self->pidl("uint32_t ndr_pull_flags = LIBNDR_FLAG_REF_ALLOC;");
764         $self->pidl("PyObject *allow_remaining_obj = NULL;");
765         $self->pidl("bool allow_remaining = false;");
766         $self->pidl("");
767         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, PYARG_BYTES_LEN \"|OOO:__ndr_unpack_out__\",");
768         $self->indent;
769         $self->pidl("discard_const_p(char *, kwnames),");
770         $self->pidl("&blob.data, &blob_length,");
771         $self->pidl("&bigendian_obj,");
772         $self->pidl("&ndr64_obj,");
773         $self->pidl("&allow_remaining_obj)) {");
774         $self->deindent;
775         $self->indent;
776         $self->pidl("return NULL;");
777         $self->deindent;
778         $self->pidl("}");
779         $self->pidl("blob.length = blob_length;");
780         $self->pidl("");
781         $self->pidl("if (bigendian_obj && PyObject_IsTrue(bigendian_obj)) {");
782         $self->indent;
783         $self->pidl("ndr_pull_flags |= LIBNDR_FLAG_BIGENDIAN;");
784         $self->deindent;
785         $self->pidl("}");
786         $self->pidl("if (ndr64_obj && PyObject_IsTrue(ndr64_obj)) {");
787         $self->indent;
788         $self->pidl("ndr_pull_flags |= LIBNDR_FLAG_NDR64;");
789         $self->deindent;
790         $self->pidl("}");
791         $self->pidl("");
792         $self->pidl("if (allow_remaining_obj && PyObject_IsTrue(allow_remaining_obj)) {");
793         $self->indent;
794         $self->pidl("allow_remaining = true;");
795         $self->deindent;
796         $self->pidl("}");
797         $self->pidl("");
798         $self->pidl("return py_$name\_ndr_unpack(py_obj, &blob, NDR_OUT, ndr_pull_flags, allow_remaining);");
799         $self->deindent;
800         $self->pidl("}");
801         $self->pidl("");
802
803         $self->pidl("static PyObject *py_$name\_ndr_print(PyObject *py_obj, const char *name, int ndr_inout_flags)");
804         $self->pidl("{");
805         $self->indent;
806         $self->pidl("$ndr_call");
807         $self->pidl("$object_ptr");
808         $self->pidl("PyObject *ret;");
809         $self->pidl("char *retstr;");
810         $self->pidl("");
811         $self->pidl("if (ndr_table_$iface\.num_calls < " . ($fn->{OPNUM}+1) .
812                     ") {");
813         $self->indent;
814         $self->pidl("PyErr_SetString(PyExc_TypeError, \"Internal Error, ndr_interface_call missing for py_$name\_ndr_print\");");
815         $self->pidl("return NULL;");
816         $self->deindent;
817         $self->pidl("}");
818         $self->pidl("call = &ndr_table_$iface\.calls[$fn->{OPNUM}];");
819         $self->pidl("");
820         $self->pidl("retstr = ndr_print_function_string(pytalloc_get_mem_ctx(py_obj), call->ndr_print, name, ndr_inout_flags, object);");
821         $self->pidl("ret = PyStr_FromString(retstr);");
822         $self->pidl("TALLOC_FREE(retstr);");
823         $self->pidl("");
824         $self->pidl("return ret;");
825         $self->deindent;
826         $self->pidl("}");
827         $self->pidl("");
828
829         $self->pidl("static PyObject *py_$name\_ndr_print_in(PyObject *py_obj, PyObject *py_obj2)");
830         $self->pidl("{");
831         $self->indent;
832         $self->pidl("return py_$name\_ndr_print(py_obj, \"$name\_in\", NDR_IN);");
833         $self->deindent;
834         $self->pidl("}");
835         $self->pidl("");
836
837         $self->pidl("static PyObject *py_$name\_ndr_print_out(PyObject *py_obj, PyObject *py_obj2)");
838         $self->pidl("{");
839         $self->indent;
840         $self->pidl("return py_$name\_ndr_print(py_obj, \"$name\_out\", NDR_OUT);");
841         $self->deindent;
842         $self->pidl("}");
843         $self->pidl("");
844
845         $py_methods = "py_$name\_methods";
846         $self->pidl("static PyMethodDef $py_methods\[] = {");
847         $self->indent;
848         $self->pidl("{ \"opnum\", (PyCFunction)py_$name\_ndr_opnum, METH_NOARGS|METH_CLASS,");
849         $self->indent;
850         $self->pidl("\"$modulename.$prettyname.opnum() -> ".sprintf("%d (0x%02x)", $fn->{OPNUM}, $fn->{OPNUM})." \" },");
851         $self->deindent;
852         $self->pidl("{ \"__ndr_pack_in__\", (PyCFunction)py_$name\_ndr_pack_in, METH_VARARGS|METH_KEYWORDS,");
853         $self->indent;
854         $self->pidl("\"S.ndr_pack_in(object, bigendian=False, ndr64=False) -> blob\\nNDR pack input\" },");
855         $self->deindent;
856         $self->pidl("{ \"__ndr_pack_out__\", (PyCFunction)py_$name\_ndr_pack_out, METH_VARARGS|METH_KEYWORDS,");
857         $self->indent;
858         $self->pidl("\"S.ndr_pack_out(object, bigendian=False, ndr64=False) -> blob\\nNDR pack output\" },");
859         $self->deindent;
860         $self->pidl("{ \"__ndr_unpack_in__\", (PyCFunction)py_$name\_ndr_unpack_in, METH_VARARGS|METH_KEYWORDS,");
861         $self->indent;
862         $self->pidl("\"S.ndr_unpack_in(class, blob, bigendian=False, ndr64=False, allow_remaining=False) -> None\\nNDR unpack input\" },");
863         $self->deindent;
864         $self->pidl("{ \"__ndr_unpack_out__\", (PyCFunction)py_$name\_ndr_unpack_out, METH_VARARGS|METH_KEYWORDS,");
865         $self->indent;
866         $self->pidl("\"S.ndr_unpack_out(class, blob, bigendian=False, ndr64=False, allow_remaining=False) -> None\\nNDR unpack output\" },");
867         $self->deindent;
868         $self->pidl("{ \"__ndr_print_in__\", (PyCFunction)py_$name\_ndr_print_in, METH_NOARGS, \"S.ndr_print_in(object) -> None\\nNDR print input\" },");
869         $self->pidl("{ \"__ndr_print_out__\", (PyCFunction)py_$name\_ndr_print_out, METH_NOARGS, \"S.ndr_print_out(object) -> None\\nNDR print output\" },");
870         $self->pidl("{ NULL, NULL, 0, NULL }");
871         $self->deindent;
872         $self->pidl("};");
873         $self->pidl("");
874
875         $self->pidl_hdr("static PyTypeObject $name\_Type;\n");
876         $self->pidl("");
877         my $docstring = $self->DocString($fn, $name);
878         my $typeobject = "$name\_Type";
879         $self->pidl("static PyTypeObject $typeobject = {");
880         $self->indent;
881         $self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
882         $self->pidl(".tp_name = \"$modulename.$prettyname\",");
883         $self->pidl(".tp_getset = $getsetters,");
884         if ($docstring) {
885                 $self->pidl(".tp_doc = $docstring,");
886         }
887         $self->pidl(".tp_methods = $py_methods,");
888         $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
889         $self->pidl(".tp_new = py_$name\_new,");
890         $self->deindent;
891         $self->pidl("};");
892
893         $self->pidl("");
894
895         my $talloc_typename = $self->import_type_variable("talloc", "BaseObject");
896         $self->register_module_prereadycode(["$name\_Type.tp_base = $talloc_typename;",
897                                              "$name\_Type.tp_basicsize = pytalloc_BaseObject_size();",
898                                              ""]);
899
900         return "&$typeobject";
901 }
902
903 sub get_metadata_var($)
904 {
905         my ($e) = @_;
906         sub get_var($) { my $x = shift; $x =~ s/\*//g; return $x; }
907
908          if (has_property($e, "length_is")) {
909                 return get_var($e->{PROPERTIES}->{length_is});
910          } elsif (has_property($e, "size_is")) {
911                 return get_var($e->{PROPERTIES}->{size_is});
912          }
913
914          return undef;
915 }
916
917 sub find_metadata_args($)
918 {
919         my ($fn) = @_;
920         my $metadata_args = { in => {}, out => {} };
921
922         # Determine arguments that are metadata for other arguments (size_is/length_is)
923         foreach my $e (@{$fn->{ELEMENTS}}) {
924                 foreach my $dir (@{$e->{DIRECTION}}) {
925                          my $main = get_metadata_var($e);
926                          if ($main) {
927                                  $metadata_args->{$dir}->{$main} = $e->{NAME};
928                          }
929                  }
930         }
931
932         return $metadata_args;
933 }
934
935 sub PythonFunctionUnpackOut($$$)
936 {
937         my ($self, $fn, $fnname) = @_;
938
939         my $outfnname = "unpack_$fnname\_args_out";
940         my $signature = "";
941
942         my $metadata_args = find_metadata_args($fn);
943
944         my $env = GenerateFunctionOutEnv($fn, "r->");
945         my $result_size = 0;
946
947         $self->pidl("static PyObject *$outfnname(struct $fn->{NAME} *r)");
948         $self->pidl("{");
949         $self->indent;
950         $self->pidl("PyObject *result = NULL;");
951         foreach my $e (@{$fn->{ELEMENTS}}) {
952                 next unless (grep(/out/,@{$e->{DIRECTION}}));
953                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or
954                          ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
955                 $self->pidl("PyObject *py_$e->{NAME} = NULL;");
956                 $result_size++;
957         }
958
959         if ($fn->{RETURN_TYPE}) {
960                 if ($fn->{RETURN_TYPE} ne "WERROR" and $fn->{RETURN_TYPE} ne "NTSTATUS") {
961                         $self->pidl("PyObject *py_result = NULL;");
962                         $result_size++;
963                 }
964         }
965
966         my $i = 0;
967
968         my $fail = "return NULL;";
969
970         if ($result_size > 1) {
971                 $self->pidl("int ret;");
972                 $self->pidl("");
973                 $self->pidl("result = PyTuple_New($result_size);");
974                 $self->fail_on_null("result", $fail);
975                 $fail = "Py_DECREF(result); " . $fail;
976
977                 $signature .= "(";
978         } elsif ($result_size == 0) {
979                 $self->pidl("");
980                 $self->pidl("result = Py_None;");
981                 $self->pidl("Py_INCREF(result);");
982                 $signature .= "None";
983         }
984
985         $self->pidl("");
986
987         foreach my $e (@{$fn->{ELEMENTS}}) {
988                 next if ($metadata_args->{out}->{$e->{NAME}});
989                 my $py_name = "py_$e->{NAME}";
990                 if (grep(/out/,@{$e->{DIRECTION}})) {
991                         $self->ConvertObjectToPython("r", $env, $e, "r->out.$e->{NAME}", $py_name, $fail);
992                         if ($result_size > 1) {
993                                 $self->pidl("ret = PyTuple_SetItem(result, $i, $py_name);");
994                                 $self->pidl("if (ret != 0) {");
995                                 $self->indent;
996                                 $self->pidl($fail);
997                                 $self->deindent;
998                                 $self->pidl("}");
999                                 $i++;
1000                                 $signature .= "$e->{NAME}, ";
1001                         } else {
1002                                 $self->pidl("result = $py_name;");
1003                                 $signature .= $e->{NAME};
1004                         }
1005                         $self->pidl("");
1006                 }
1007         }
1008
1009         if (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "NTSTATUS") {
1010                 $self->handle_ntstatus("r->out.result", "NULL", undef);
1011                 $self->pidl("");
1012         } elsif (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "WERROR") {
1013                 $self->handle_werror("r->out.result", "NULL", undef);
1014                 $self->pidl("");
1015         } elsif (defined($fn->{RETURN_TYPE})) {
1016                 my $conv = $self->ConvertObjectToPythonData("r", $fn->{RETURN_TYPE}, "r->out.result", $fn);
1017                 $self->pidl("py_result = $conv;");
1018                 $self->fail_on_null("py_result", $fail);
1019                 if ($result_size > 1) {
1020                         $self->pidl("ret = PyTuple_SetItem(result, $i, py_result);");
1021                         $self->pidl("if (ret != 0) {");
1022                         $self->indent;
1023                         $self->pidl($fail);
1024                         $self->deindent;
1025                         $self->pidl("}");
1026                 } else {
1027                         $self->pidl("result = py_result;");
1028                 }
1029                 $self->pidl("");
1030                 $signature .= "result";
1031         }
1032
1033         if (substr($signature, -2) eq ", ") {
1034                 $signature = substr($signature, 0, -2);
1035         }
1036         if ($result_size > 1) {
1037                 $signature .= ")";
1038         }
1039
1040         $self->pidl("return result;");
1041         $self->deindent;
1042         $self->pidl("}");
1043         $self->pidl("");
1044
1045         return ($outfnname, $signature);
1046 }
1047
1048 sub PythonFunctionPackIn($$$)
1049 {
1050         my ($self, $fn, $fnname) = @_;
1051         my $metadata_args = find_metadata_args($fn);
1052
1053         my $infnname = "pack_$fnname\_args_in";
1054
1055         $self->pidl("static bool $infnname(PyObject *args, PyObject *kwargs, struct $fn->{NAME} *r)");
1056         $self->pidl("{");
1057         $self->indent;
1058         my $args_format = "";
1059         my $args_string = "";
1060         my $args_names = "";
1061         my $signature = "";
1062
1063         foreach my $e (@{$fn->{ELEMENTS}}) {
1064                 next unless (grep(/in/,@{$e->{DIRECTION}}));
1065                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or
1066                                  ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
1067                 $self->pidl("PyObject *py_$e->{NAME};");
1068                 $args_format .= "O";
1069                 $args_string .= ", &py_$e->{NAME}";
1070                 $args_names .= "\"$e->{NAME}\", ";
1071                 $signature .= "$e->{NAME}, ";
1072         }
1073         if (substr($signature, -2) eq ", ") {
1074                 $signature = substr($signature, 0, -2);
1075         }
1076         $self->pidl("const char *kwnames[] = {");
1077         $self->indent;
1078         $self->pidl($args_names . "NULL");
1079         $self->deindent;
1080         $self->pidl("};");
1081
1082         $self->pidl("");
1083         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"$args_format:$fn->{NAME}\", discard_const_p(char *, kwnames)$args_string)) {");
1084         $self->indent;
1085         $self->pidl("return false;");
1086         $self->deindent;
1087         $self->pidl("}");
1088         $self->pidl("");
1089
1090         my $env = GenerateFunctionInEnv($fn, "r->");
1091
1092         my $fail = "return false;";
1093         foreach my $e (@{$fn->{ELEMENTS}}) {
1094                 next unless (grep(/in/,@{$e->{DIRECTION}}));
1095                 if ($metadata_args->{in}->{$e->{NAME}}) {
1096                         my $py_var = "py_".$metadata_args->{in}->{$e->{NAME}};
1097                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
1098                         my $val = "PyList_GET_SIZE($py_var)";
1099                         if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
1100                                 $self->pidl("r->in.$e->{NAME} = talloc_ptrtype(r, r->in.$e->{NAME});");
1101                                 $self->pidl("if (r->in.$e->{NAME} == NULL) {");
1102                                 $self->indent;
1103                                 $self->pidl("PyErr_NoMemory();");
1104                                 $self->pidl($fail);
1105                                 $self->deindent;
1106                                 $self->pidl("}");
1107                                 $self->pidl("*r->in.$e->{NAME} = $val;");
1108                         } else {
1109                                 $self->pidl("r->in.$e->{NAME} = $val;");
1110                         }
1111                 } else {
1112                         $self->ConvertObjectFromPython($env, "r", $e, "py_$e->{NAME}", "r->in.$e->{NAME}", $fail);
1113                 }
1114         }
1115         $self->pidl("return true;");
1116         $self->deindent;
1117         $self->pidl("}");
1118         $self->pidl("");
1119         return ($infnname, $signature);
1120 }
1121
1122 sub PythonFunction($$$)
1123 {
1124         my ($self, $fn, $iface, $prettyname) = @_;
1125
1126         my $fnname = "py_$fn->{NAME}";
1127         my $docstring = $self->DocString($fn, $fn->{NAME});
1128
1129         my ($infn, $insignature) = $self->PythonFunctionPackIn($fn, $fnname);
1130         my ($outfn, $outsignature) = $self->PythonFunctionUnpackOut($fn, $fnname);
1131         my $signature = "S.$prettyname($insignature) -> $outsignature";
1132         if ($docstring) {
1133                 $docstring = "\"$signature\\n\\n\"$docstring";
1134         } else {
1135                 $docstring = "\"$signature\"";
1136         }
1137
1138         return ($infn, $outfn, $docstring);
1139 }
1140
1141 sub handle_werror($$$$)
1142 {
1143         my ($self, $var, $retval, $mem_ctx) = @_;
1144
1145         $self->pidl("if (!W_ERROR_IS_OK($var)) {");
1146         $self->indent;
1147         $self->pidl("PyErr_SetWERROR($var);");
1148         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
1149         $self->pidl("return $retval;");
1150         $self->deindent;
1151         $self->pidl("}");
1152         $self->pidl("");
1153 }
1154
1155 sub handle_ntstatus($$$$)
1156 {
1157         my ($self, $var, $retval, $mem_ctx) = @_;
1158
1159         $self->pidl("if (NT_STATUS_IS_ERR($var)) {");
1160         $self->indent;
1161         $self->pidl("PyErr_SetNTSTATUS($var);");
1162         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
1163         $self->pidl("return $retval;");
1164         $self->deindent;
1165         $self->pidl("}");
1166         $self->pidl("");
1167 }
1168
1169 sub PythonType($$$$)
1170 {
1171         my ($self, $modulename, $d, $interface, $basename) = @_;
1172
1173         my $actual_ctype = $d;
1174         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
1175                 $actual_ctype = $actual_ctype->{DATA};
1176         }
1177
1178         if ($actual_ctype->{TYPE} eq "STRUCT") {
1179                 my $typeobject;
1180                 my $fn_name = PrettifyTypeName($d->{NAME}, $basename);
1181
1182                 if ($d->{TYPE} eq "STRUCT") {
1183                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d);
1184                 } else {
1185                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d->{DATA});
1186                 }
1187
1188                 $self->register_module_typeobject($fn_name, $typeobject, $d->{ORIGINAL});
1189         }
1190
1191         if ($d->{TYPE} eq "ENUM" or $d->{TYPE} eq "BITMAP") {
1192                 $self->EnumAndBitmapConsts($d->{NAME}, $d);
1193         }
1194
1195         if ($d->{TYPE} eq "TYPEDEF" and ($d->{DATA}->{TYPE} eq "ENUM" or $d->{DATA}->{TYPE} eq "BITMAP")) {
1196                 $self->EnumAndBitmapConsts($d->{NAME}, $d->{DATA});
1197         }
1198
1199         if ($actual_ctype->{TYPE} eq "UNION" and defined($actual_ctype->{ELEMENTS})) {
1200                 my $prettyname = PrettifyTypeName($d->{NAME}, $basename);
1201                 my $typeobject = "$d->{NAME}\_Type";
1202                 my $docstring = $self->DocString($d, $d->{NAME});
1203                 my $cname = "union $d->{NAME}";
1204
1205                 $self->pidl("static PyObject *py_import_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, " .mapTypeName($d) . " *in)");
1206                 $self->pidl("{");
1207                 $self->indent;
1208                 $self->FromUnionToPythonFunction("mem_ctx", $actual_ctype, "level", "in") if ($actual_ctype->{TYPE} eq "UNION");
1209                 $self->deindent;
1210                 $self->pidl("}");
1211                 $self->pidl("");
1212
1213                 $self->pidl("static ".mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in)");
1214                 $self->pidl("{");
1215                 $self->indent;
1216                 $self->FromPythonToUnionFunction($actual_ctype, mapTypeName($d), "level", "mem_ctx", "in") if ($actual_ctype->{TYPE} eq "UNION");
1217                 $self->deindent;
1218                 $self->pidl("}");
1219                 $self->pidl("");
1220
1221                 my $getsetters = "NULL";
1222                 my $py_methods = "NULL";
1223                 my $typename = mapTypeName($d);
1224
1225                 $self->pidl("static PyObject *py_$d->{NAME}\_import(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
1226                 $self->pidl("{");
1227                 $self->indent;
1228                 $self->pidl("const char * const kwnames[] = { \"mem_ctx\", \"level\", \"in\", NULL };");
1229                 $self->pidl("PyObject *mem_ctx_obj = NULL;");
1230                 $self->pidl("TALLOC_CTX *mem_ctx = NULL;");
1231                 $self->pidl("int level = 0;");
1232                 $self->pidl("PyObject *in_obj = NULL;");
1233                 $self->pidl("$typename *in = NULL;");
1234                 $self->pidl("");
1235                 $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"OiO:import\",");
1236                 $self->indent;
1237                 $self->pidl("discard_const_p(char *, kwnames),");
1238                 $self->pidl("&mem_ctx_obj,");
1239                 $self->pidl("&level,");
1240                 $self->pidl("&in_obj)) {");
1241                 $self->deindent;
1242                 $self->indent;
1243                 $self->pidl("return NULL;");
1244                 $self->deindent;
1245                 $self->pidl("}");
1246                 $self->pidl("mem_ctx = pytalloc_get_ptr(mem_ctx_obj);");
1247                 $self->pidl("if (mem_ctx == NULL) {");
1248                 $self->indent;
1249                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"mem_ctx is NULL)!\");");
1250                 $self->pidl("return NULL;");
1251                 $self->deindent;
1252                 $self->pidl("}");
1253                 $self->pidl("in = ($typename *)pytalloc_get_ptr(in_obj);");
1254                 $self->pidl("if (in == NULL) {");
1255                 $self->indent;
1256                 $self->pidl("PyErr_Format(PyExc_TypeError, \"in needs to be a pointer to $typename!\");");
1257                 $self->pidl("return NULL;");
1258                 $self->deindent;
1259                 $self->pidl("}");
1260                 $self->pidl("");
1261                 $self->pidl("return py_import_$d->{NAME}(mem_ctx, level, in);");
1262                 $self->deindent;
1263                 $self->pidl("}");
1264                 $self->pidl("");
1265
1266                 $self->pidl("static PyObject *py_$d->{NAME}\_export(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
1267                 $self->pidl("{");
1268                 $self->indent;
1269                 $self->pidl("const char * const kwnames[] = { \"mem_ctx\", \"level\", \"in\", NULL };");
1270                 $self->pidl("PyObject *mem_ctx_obj = NULL;");
1271                 $self->pidl("TALLOC_CTX *mem_ctx = NULL;");
1272                 $self->pidl("int level = 0;");
1273                 $self->pidl("PyObject *in = NULL;");
1274                 $self->pidl("$typename *out = NULL;");
1275                 $self->pidl("");
1276                 $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"OiO:import\",");
1277                 $self->indent;
1278                 $self->pidl("discard_const_p(char *, kwnames),");
1279                 $self->pidl("&mem_ctx_obj,");
1280                 $self->pidl("&level,");
1281                 $self->pidl("&in)) {");
1282                 $self->deindent;
1283                 $self->indent;
1284                 $self->pidl("return NULL;");
1285                 $self->deindent;
1286                 $self->pidl("}");
1287                 $self->pidl("mem_ctx = pytalloc_get_ptr(mem_ctx_obj);");
1288                 $self->pidl("if (mem_ctx == NULL) {");
1289                 $self->indent;
1290                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"mem_ctx is NULL)!\");");
1291                 $self->pidl("return NULL;");
1292                 $self->deindent;
1293                 $self->pidl("}");
1294                 $self->pidl("");
1295                 $self->pidl("out = py_export_$d->{NAME}(mem_ctx, level, in);");
1296                 $self->pidl("if (out == NULL) {");
1297                 $self->indent;
1298                 $self->pidl("return NULL;");
1299                 $self->deindent;
1300                 $self->pidl("}");
1301                 $self->pidl("");
1302                 $self->pidl("return pytalloc_GenericObject_reference(out);");
1303                 $self->deindent;
1304                 $self->pidl("}");
1305                 $self->pidl("");
1306
1307                 $py_methods = "py_$d->{NAME}_methods";
1308                 $self->pidl("static PyMethodDef $py_methods\[] = {");
1309                 $self->indent;
1310                 $self->pidl("{ \"__import__\", (PyCFunction)py_$d->{NAME}\_import,");
1311                 $self->indent;
1312                 $self->pidl("METH_VARARGS|METH_KEYWORDS|METH_CLASS,");
1313                 $self->pidl("\"T.__import__(mem_ctx, level, in) => ret.\" },");
1314                 $self->deindent;
1315                 $self->pidl("{ \"__export__\", (PyCFunction)py_$d->{NAME}\_export,");
1316                 $self->indent;
1317                 $self->pidl("METH_VARARGS|METH_KEYWORDS|METH_CLASS,");
1318                 $self->pidl("\"T.__export__(mem_ctx, level, in) => ret.\" },");
1319                 $self->deindent;
1320                 $self->pidl("{ NULL, NULL, 0, NULL }");
1321                 $self->deindent;
1322                 $self->pidl("};");
1323                 $self->pidl("");
1324
1325                 $self->pidl("static PyObject *py_$d->{NAME}\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
1326                 $self->pidl("{");
1327                 $self->indent;
1328                 $self->pidl("PyErr_Format(PyExc_TypeError, \"New %s Objects are not supported\", type->tp_name);");
1329                 $self->pidl("return NULL;");
1330                 $self->deindent;
1331                 $self->pidl("}");
1332                 $self->pidl("");
1333
1334                 $self->pidl("");
1335                 $self->pidl_hdr("static PyTypeObject $typeobject;\n");
1336                 $self->pidl("static PyTypeObject $typeobject = {");
1337                 $self->indent;
1338                 $self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
1339                 $self->pidl(".tp_name = \"$modulename.$prettyname\",");
1340                 $self->pidl(".tp_getset = $getsetters,");
1341                 if ($docstring) {
1342                         $self->pidl(".tp_doc = $docstring,");
1343                 }
1344                 $self->pidl(".tp_methods = $py_methods,");
1345                 $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
1346                 $self->pidl(".tp_new = py_$d->{NAME}\_new,");
1347                 $self->deindent;
1348                 $self->pidl("};");
1349
1350                 $self->pidl("");
1351
1352                 my $talloc_typename = $self->import_type_variable("talloc", "BaseObject");
1353                 $self->register_module_prereadycode(["$typeobject.tp_base = $talloc_typename;",
1354                                                      "$typeobject.tp_basicsize = pytalloc_BaseObject_size();",
1355                                                      ""]);
1356
1357                 $self->register_module_typeobject($prettyname, "&$typeobject", $d->{ORIGINAL});
1358         }
1359 }
1360
1361 sub DocString($$$)
1362 {
1363         my ($self, $d, $name) = @_;
1364         if (has_property($d, "helpstring")) {
1365                 my $docstring = uc("py_doc_$name");
1366                 $self->pidl("#define $docstring ".has_property($d, "helpstring"));
1367                 return $docstring;
1368         }
1369
1370         return undef;
1371 }
1372
1373 sub Interface($$$)
1374 {
1375         my($self,$interface,$basename) = @_;
1376
1377         if (has_property($interface, "pyhelper")) {
1378                 $self->pidl("#include \"".unmake_str($interface->{PROPERTIES}->{pyhelper})."\"\n");
1379         }
1380
1381         $self->Const($_) foreach (@{$interface->{CONSTS}});
1382
1383         foreach my $d (@{$interface->{TYPES}}) {
1384                 next if has_property($d, "nopython");
1385
1386                 $self->PythonType($basename, $d, $interface, $basename);
1387         }
1388
1389         if (defined $interface->{PROPERTIES}->{uuid}) {
1390                 $self->pidl_hdr("static PyTypeObject $interface->{NAME}_InterfaceType;\n");
1391                 $self->pidl("");
1392
1393                 my @fns = ();
1394
1395                 foreach my $d (@{$interface->{FUNCTIONS}}) {
1396                         next if has_property($d, "noopnum");
1397                         next if has_property($d, "nopython");
1398                         next if has_property($d, "todo");
1399
1400                         my $skip = 0;
1401                         foreach my $e (@{$d->{ELEMENTS}}) {
1402                                 if (ContainsPipe($e, $e->{LEVELS}[0])) {
1403                                         $skip = 1;
1404                                         last;
1405                                 }
1406                         }
1407                         next if $skip;
1408
1409                         my $prettyname = $d->{NAME};
1410
1411                         $prettyname =~ s/^$interface->{NAME}_//;
1412                         $prettyname =~ s/^$basename\_//;
1413
1414                         my $typeobject = $self->PythonFunctionStruct($basename, $d, $interface->{NAME}, $prettyname);
1415                         $self->register_module_typeobject($prettyname, $typeobject, $d->{ORIGINAL});
1416
1417                         my ($infn, $outfn, $fndocstring) = $self->PythonFunction($d, $interface->{NAME}, $prettyname);
1418
1419                         push (@fns, [$infn, $outfn, "dcerpc_$d->{NAME}_r", $prettyname, $fndocstring, $d->{OPNUM}]);
1420                 }
1421
1422                 $self->pidl("const struct PyNdrRpcMethodDef py_ndr_$interface->{NAME}\_methods[] = {");
1423                 $self->indent;
1424                 foreach my $d (@fns) {
1425                         my ($infn, $outfn, $callfn, $prettyname, $docstring, $opnum) = @$d;
1426                         $self->pidl("{ \"$prettyname\", $docstring, (py_dcerpc_call_fn)$callfn, (py_data_pack_fn)$infn, (py_data_unpack_fn)$outfn, $opnum, &ndr_table_$interface->{NAME} },");
1427                 }
1428                 $self->pidl("{ NULL }");
1429                 $self->deindent;
1430                 $self->pidl("};");
1431                 $self->pidl("");
1432
1433                 $self->pidl("static PyObject *interface_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
1434                 $self->pidl("{");
1435                 $self->indent;
1436                 $self->pidl("return py_dcerpc_interface_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME});");
1437                 $self->deindent;
1438                 $self->pidl("}");
1439
1440                 $self->pidl("");
1441
1442                 my $signature =
1443 "\"$interface->{NAME}(binding, lp_ctx=None, credentials=None) -> connection\\n\"
1444 \"\\n\"
1445 \"binding should be a DCE/RPC binding string (for example: ncacn_ip_tcp:127.0.0.1)\\n\"
1446 \"lp_ctx should be a path to a smb.conf file or a param.LoadParm object\\n\"
1447 \"credentials should be a credentials.Credentials object.\\n\\n\"";
1448
1449                 my $docstring = $self->DocString($interface, $interface->{NAME});
1450
1451                 if ($docstring) {
1452                         $docstring = "$signature$docstring";
1453                 } else {
1454                         $docstring = $signature;
1455                 }
1456
1457                 my $if_typename = "$interface->{NAME}_InterfaceType";
1458
1459                 $self->pidl("static PyTypeObject $if_typename = {");
1460                 $self->indent;
1461                 $self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
1462                 $self->pidl(".tp_name = \"$basename.$interface->{NAME}\",");
1463                 $self->pidl(".tp_basicsize = sizeof(dcerpc_InterfaceObject),");
1464                 $self->pidl(".tp_doc = $docstring,");
1465                 $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
1466                 $self->pidl(".tp_new = interface_$interface->{NAME}_new,");
1467                 $self->deindent;
1468                 $self->pidl("};");
1469
1470                 $self->pidl("");
1471
1472                 $self->register_module_typeobject($interface->{NAME}, "&$if_typename", $interface->{ORIGINAL});
1473                 my $dcerpc_typename = $self->import_type_variable("samba.dcerpc.base", "ClientConnection");
1474                 $self->register_module_prereadycode(["$if_typename.tp_base = $dcerpc_typename;", ""]);
1475                 $self->register_module_postreadycode(["if (!PyInterface_AddNdrRpcMethods(&$if_typename, py_ndr_$interface->{NAME}\_methods))", "\treturn NULL;", ""]);
1476
1477
1478                 $self->pidl("static PyObject *syntax_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
1479                 $self->pidl("{");
1480                 $self->indent;
1481                 $self->pidl("return py_dcerpc_syntax_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME}.syntax_id);");
1482                 $self->deindent;
1483                 $self->pidl("}");
1484
1485                 $self->pidl("");
1486
1487                 my $signature = "\"$interface->{NAME}_abstract_syntax()\\n\"";
1488
1489                 my $docstring = $self->DocString($interface, $interface->{NAME}."_syntax");
1490
1491                 if ($docstring) {
1492                         $docstring = "$signature$docstring";
1493                 } else {
1494                         $docstring = $signature;
1495                 }
1496
1497                 my $syntax_typename = "$interface->{NAME}_SyntaxType";
1498
1499                 $self->pidl("static PyTypeObject $syntax_typename = {");
1500                 $self->indent;
1501                 $self->pidl("PyVarObject_HEAD_INIT(NULL, 0)");
1502                 $self->pidl(".tp_name = \"$basename.$interface->{NAME}_abstract_syntax\",");
1503                 $self->pidl(".tp_doc = $docstring,");
1504                 $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
1505                 $self->pidl(".tp_new = syntax_$interface->{NAME}_new,");
1506                 $self->deindent;
1507                 $self->pidl("};");
1508
1509                 $self->pidl("");
1510
1511                 $self->register_module_typeobject("$interface->{NAME}_abstract_syntax", "&$syntax_typename", $interface->{ORIGINAL});
1512                 if (not defined($self->existing_module_object("abstract_syntax"))) {
1513                         # Only the first syntax gets registered with the legacy
1514                         # "abstract_syntax" name
1515                         $self->register_module_typeobject("abstract_syntax", "&$syntax_typename", $interface->{ORIGINAL});
1516                 }
1517                 my $ndr_typename = $self->import_type_variable("samba.dcerpc.misc", "ndr_syntax_id");
1518                 $self->register_module_prereadycode(["$syntax_typename.tp_base = $ndr_typename;",
1519                                                      "$syntax_typename.tp_basicsize = pytalloc_BaseObject_size();",
1520                                                      ""]);
1521         }
1522
1523         $self->pidl_hdr("\n");
1524 }
1525
1526 sub register_module_method($$$$$)
1527 {
1528         my ($self, $fn_name, $pyfn_name, $flags, $doc) = @_;
1529
1530         push (@{$self->{module_methods}}, [$fn_name, $pyfn_name, $flags, $doc])
1531 }
1532
1533 sub register_module_typeobject($$$$)
1534 {
1535         my ($self, $name, $py_name, $location) = @_;
1536
1537         $self->register_module_object($name, "(PyObject *)(void *)$py_name", $location);
1538
1539         $self->check_ready_type($py_name);
1540
1541         $self->register_patch_type_call($name, $py_name);
1542 }
1543
1544 sub check_ready_type($$)
1545 {
1546         my ($self, $py_name) = @_;
1547         push (@{$self->{ready_types}}, $py_name) unless (grep(/^$py_name$/,@{$self->{ready_types}}));
1548 }
1549
1550 sub register_module_import($$)
1551 {
1552         my ($self, $module_path) = @_;
1553
1554         my $var_name = $module_path;
1555         $var_name =~ s/\./_/g;
1556         $var_name = "dep_$var_name";
1557
1558         unless (defined $self->{module_imports_uniq}->{$var_name}) {
1559                 my $h = { "key" => $var_name, "val" => $module_path};
1560                 push @{$self->{module_imports}}, $h;
1561                 $self->{module_imports_uniq}->{$var_name} = $h;
1562         }
1563         return $var_name;
1564 }
1565
1566 sub import_type_variable($$$)
1567 {
1568         my ($self, $module, $name) = @_;
1569
1570         $self->register_module_import($module);
1571         unless (defined $self->{type_imports_uniq}->{$name}) {
1572                 my $h = { "key" => $name, "val" => $module};
1573                 push @{$self->{type_imports}}, $h;
1574                 $self->{type_imports_uniq}->{$name} = $h;
1575         }
1576         return "$name\_Type";
1577 }
1578
1579 sub use_type_variable($$)
1580 {
1581         my ($self, $orig_ctype) = @_;
1582         # FIXME: Have a global lookup table for types that look different on the
1583         # wire than they are named in C?
1584         if ($orig_ctype->{NAME} eq "dom_sid2" or
1585             $orig_ctype->{NAME} eq "dom_sid28" or
1586             $orig_ctype->{NAME} eq "dom_sid0") {
1587                 $orig_ctype->{NAME} = "dom_sid";
1588         }
1589         if ($orig_ctype->{NAME} eq "spoolss_security_descriptor") {
1590                 $orig_ctype->{NAME} = "security_descriptor";
1591         }
1592
1593         my $ctype = resolveType($orig_ctype);
1594         unless (defined($ctype->{BASEFILE})) {
1595                 return undef;
1596         }
1597         # If this is an external type, make sure we do the right imports.
1598         if (($ctype->{BASEFILE} ne $self->{BASENAME})) {
1599                 return $self->import_type_variable("samba.dcerpc.$ctype->{BASEFILE}", $ctype->{NAME});
1600         }
1601         return "&$ctype->{NAME}_Type";
1602 }
1603
1604 sub register_patch_type_call($$$)
1605 {
1606         my ($self, $typename, $cvar) = @_;
1607
1608         push(@{$self->{patch_type_calls}}, [$typename, $cvar]);
1609
1610 }
1611
1612 sub register_module_prereadycode($$)
1613 {
1614         my ($self, $code) = @_;
1615
1616         push (@{$self->{prereadycode}}, @$code);
1617 }
1618
1619 sub register_module_postreadycode($$)
1620 {
1621         my ($self, $code) = @_;
1622
1623         push (@{$self->{postreadycode}}, @$code);
1624 }
1625
1626 sub existing_module_object($$)
1627 {
1628         my ($self, $name) = @_;
1629
1630         if (defined($self->{module_object_uniq}->{$name})) {
1631                 return $self->{module_object_uniq}->{$name};
1632         }
1633
1634         return undef;
1635 }
1636
1637 sub register_module_object($$$$)
1638 {
1639         my ($self, $name, $py_name, $location) = @_;
1640
1641         my $existing = $self->existing_module_object($name);
1642         fatal($location, "module_object($name, $py_name) registered twice! $existing.") if defined($existing);
1643
1644         push (@{$self->{module_objects}}, [$name, $py_name]);
1645         $self->{module_object_uniq}->{$name} = $py_name;
1646 }
1647
1648 sub assign($$$)
1649 {
1650         my ($self, $dest, $src) = @_;
1651         if ($dest =~ /^\&/ and $src eq "NULL") {
1652                 $self->pidl("memset($dest, 0, sizeof(" . get_value_of($dest) . "));");
1653         } elsif ($dest =~ /^\&/) {
1654                 my $destvar = get_value_of($dest);
1655                 $self->pidl("$destvar = *$src;");
1656         } else {
1657                 $self->pidl("$dest = $src;");
1658         }
1659 }
1660
1661 sub ConvertStringFromPythonData($$$$$)
1662 {
1663         my ($self, $mem_ctx, $py_var, $target, $fail) = @_;
1664
1665         $self->pidl("{");
1666         $self->indent;
1667         $self->pidl("const char *test_str;");
1668         $self->pidl("const char *talloc_str;");
1669         $self->pidl("PyObject *unicode = NULL;");
1670         $self->pidl("if (PyUnicode_Check($py_var)) {");
1671         $self->indent;
1672         # FIXME: Use Unix charset setting rather than utf-8
1673         $self->pidl("unicode = PyUnicode_AsEncodedString($py_var, \"utf-8\", \"ignore\");");
1674         $self->pidl("if (unicode == NULL) {");
1675         $self->indent;
1676         $self->pidl("PyErr_NoMemory();");
1677         $self->pidl("$fail");
1678         $self->deindent;
1679         $self->pidl("}");
1680
1681         $self->pidl("test_str = PyBytes_AS_STRING(unicode);");
1682         $self->deindent;
1683         $self->pidl("} else if (PyBytes_Check($py_var)) {");
1684         $self->indent;
1685         $self->pidl("test_str = PyBytes_AS_STRING($py_var);");
1686         $self->deindent;
1687         $self->pidl("} else {");
1688         $self->indent;
1689         $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected string or unicode object, got %s\", Py_TYPE($py_var)->tp_name);");
1690         $self->pidl("$fail");
1691         $self->deindent;
1692         $self->pidl("}");
1693         $self->pidl("talloc_str = talloc_strdup($mem_ctx, test_str);");
1694         $self->pidl("if (unicode != NULL) {");
1695         $self->indent;
1696         $self->pidl("Py_DECREF(unicode);");
1697         $self->deindent;
1698         $self->pidl("}");
1699         $self->pidl("if (talloc_str == NULL) {");
1700         $self->indent;
1701         $self->pidl("PyErr_NoMemory();");
1702         $self->pidl("$fail");
1703         $self->deindent;
1704         $self->pidl("}");
1705         $self->pidl("$target = talloc_str;");
1706         $self->deindent;
1707         $self->pidl("}");
1708 }
1709
1710 sub ConvertObjectFromPythonData($$$$$$;$$)
1711 {
1712         my ($self, $mem_ctx, $cvar, $ctype, $target, $fail, $location, $switch) = @_;
1713
1714         fatal($location, "undef type for $cvar") unless(defined($ctype));
1715
1716         $ctype = resolveType($ctype);
1717
1718         my $actual_ctype = $ctype;
1719         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
1720                 $actual_ctype = $actual_ctype->{DATA};
1721         }
1722
1723         # We need to cover ENUMs, BITMAPS and SCALAR values here, as
1724         # all could otherwise be assigned invalid integer values
1725         my $ctype_alias = "";
1726         my $uint_max = "";
1727         if ($actual_ctype->{TYPE} eq "ENUM") {
1728                 # Importantly, ENUM values are unsigned in pidl, and
1729                 # typically map to uint32
1730                 $ctype_alias = enum_type_fn($actual_ctype);
1731         } elsif ($actual_ctype->{TYPE} eq "BITMAP") {
1732                 $ctype_alias = bitmap_type_fn($actual_ctype);
1733         } elsif ($actual_ctype->{TYPE} eq "SCALAR") {
1734                 $ctype_alias = expandAlias($actual_ctype->{NAME});
1735         }
1736
1737         # This is the unsigned Python Integer -> C integer validation
1738         # case.  The signed case is below.
1739         if ($ctype_alias  =~ /^(uint[0-9]*|hyper|udlong|udlongr
1740                                 |NTTIME_hyper|NTTIME|NTTIME_1sec
1741                                 |uid_t|gid_t)$/x) {
1742                 $self->pidl("{");
1743                 $self->indent;
1744                 $self->pidl("const unsigned long long uint_max = ndr_sizeof2uintmax(sizeof($target));");
1745                 $self->pidl("if (PyLong_Check($cvar)) {");
1746                 $self->indent;
1747                 $self->pidl("unsigned long long test_var;");
1748                 $self->pidl("test_var = PyLong_AsUnsignedLongLong($cvar);");
1749                 $self->pidl("if (PyErr_Occurred() != NULL) {");
1750                 $self->indent;
1751                 $self->pidl($fail);
1752                 $self->deindent;
1753                 $self->pidl("}");
1754                 $self->pidl("if (test_var > uint_max) {");
1755                 $self->indent;
1756                 $self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range 0 - %llu, got %llu\",\\");
1757                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name, uint_max, test_var);");
1758                 $self->pidl($fail);
1759                 $self->deindent;
1760                 $self->pidl("}");
1761                 $self->pidl("$target = test_var;");
1762                 $self->deindent;
1763                 $self->pidl("} else if (PyInt_Check($cvar)) {");
1764                 $self->indent;
1765                 $self->pidl("long test_var;");
1766                 $self->pidl("test_var = PyInt_AsLong($cvar);");
1767                 $self->pidl("if (test_var < 0 || (unsigned long long)test_var > uint_max) {");
1768                 $self->indent;
1769                 $self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range 0 - %llu, got %ld\",\\");
1770                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name, uint_max, test_var);");
1771                 $self->pidl($fail);
1772                 $self->deindent;
1773                 $self->pidl("}");
1774                 $self->pidl("$target = test_var;");
1775                 $self->deindent;
1776                 $self->pidl("} else {");
1777                 $self->indent;
1778                 $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
1779                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name);");
1780                 $self->pidl($fail);
1781                 $self->deindent;
1782                 $self->pidl("}");
1783                 $self->deindent;
1784                 $self->pidl("}");
1785                 return;
1786         }
1787
1788         # Confirm the signed python integer fits in the C type
1789         # correctly.  It is subtly different from the unsigned case
1790         # above, so while it looks like a duplicate, it is not
1791         # actually a duplicate.
1792         if ($ctype_alias  =~ /^(dlong|char|int[0-9]*|time_t)$/x) {
1793                 $self->pidl("{");
1794                 $self->indent;
1795                 $self->pidl("const long long int_max = ndr_sizeof2intmax(sizeof($target));");
1796                 $self->pidl("const long long int_min = -int_max - 1;");
1797                 $self->pidl("if (PyLong_Check($cvar)) {");
1798                 $self->indent;
1799                 $self->pidl("long long test_var;");
1800                 $self->pidl("test_var = PyLong_AsLongLong($cvar);");
1801                 $self->pidl("if (PyErr_Occurred() != NULL) {");
1802                 $self->indent;
1803                 $self->pidl($fail);
1804                 $self->deindent;
1805                 $self->pidl("}");
1806                 $self->pidl("if (test_var < int_min || test_var > int_max) {");
1807                 $self->indent;
1808                 $self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range %lld - %lld, got %lld\",\\");
1809                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name, int_min, int_max, test_var);");
1810                 $self->pidl($fail);
1811                 $self->deindent;
1812                 $self->pidl("}");
1813                 $self->pidl("$target = test_var;");
1814                 $self->deindent;
1815                 $self->pidl("} else if (PyInt_Check($cvar)) {");
1816                 $self->indent;
1817                 $self->pidl("long test_var;");
1818                 $self->pidl("test_var = PyInt_AsLong($cvar);");
1819                 $self->pidl("if (test_var < int_min || test_var > int_max) {");
1820                 $self->indent;
1821                 $self->pidl("PyErr_Format(PyExc_OverflowError, \"Expected type %s or %s within range %lld - %lld, got %ld\",\\");
1822                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name, int_min, int_max, test_var);");
1823                 $self->pidl($fail);
1824                 $self->deindent;
1825                 $self->pidl("}");
1826                 $self->pidl("$target = test_var;");
1827                 $self->deindent;
1828                 $self->pidl("} else {");
1829                 $self->indent;
1830                 $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
1831                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name);");
1832                 $self->pidl($fail);
1833                 $self->deindent;
1834                 $self->pidl("}");
1835                 $self->deindent;
1836                 $self->pidl("}");
1837                 return;
1838         }
1839
1840         if ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
1841                 my $ctype_name = $self->use_type_variable($ctype);
1842                 unless (defined ($ctype_name)) {
1843                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
1844                         $self->pidl("PyErr_SetString(PyExc_TypeError, \"Can not convert C Type " . mapTypeName($ctype) . " from Python\");");
1845                         return;
1846                 }
1847                 $self->pidl("PY_CHECK_TYPE($ctype_name, $cvar, $fail);");
1848                 $self->pidl("if (talloc_reference($mem_ctx, pytalloc_get_mem_ctx($cvar)) == NULL) {");
1849                 $self->indent;
1850                 $self->pidl("PyErr_NoMemory();");
1851                 $self->pidl("$fail");
1852                 $self->deindent;
1853                 $self->pidl("}");
1854                 $self->assign($target, "(".mapTypeName($ctype)." *)pytalloc_get_ptr($cvar)");
1855                 return;
1856         }
1857
1858         if ($actual_ctype->{TYPE} eq "UNION") {
1859                 my $ctype_name = $self->use_type_variable($ctype);
1860                 unless (defined ($ctype_name)) {
1861                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
1862                         $self->pidl("PyErr_SetString(PyExc_TypeError, \"Can not convert C Type " . mapTypeName($ctype) . " from Python\");");
1863                         return;
1864                 }
1865                 my $export = "pyrpc_export_union($ctype_name, $mem_ctx, $switch, $cvar, \"".mapTypeName($ctype)."\")";
1866                 $self->assign($target, "(".mapTypeName($ctype)." *)$export");
1867                 return;
1868         }
1869
1870         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "DATA_BLOB") {
1871                 $self->pidl("$target = data_blob_talloc($mem_ctx, PyBytes_AS_STRING($cvar), PyBytes_GET_SIZE($cvar));");
1872                 return;
1873         }
1874
1875         if ($actual_ctype->{TYPE} eq "SCALAR" and
1876                 ($actual_ctype->{NAME} eq "string"
1877                  or $actual_ctype->{NAME} eq "nbt_string"
1878                  or $actual_ctype->{NAME} eq "nbt_name"
1879                  or $actual_ctype->{NAME} eq "wrepl_nbt_name"
1880                  or $actual_ctype->{NAME} eq "dns_string"
1881                  or $actual_ctype->{NAME} eq "dnsp_string"
1882                  or $actual_ctype->{NAME} eq "dns_name"
1883                  or $actual_ctype->{NAME} eq "ipv4address"
1884                  or $actual_ctype->{NAME} eq "ipv6address"
1885                  or $actual_ctype->{NAME} eq "dnsp_name")) {
1886                 $self->ConvertStringFromPythonData($mem_ctx, $cvar, $target, $fail);
1887                 return;
1888         }
1889
1890         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "NTSTATUS") {
1891                 $self->pidl("$target = NT_STATUS(PyInt_AsLong($cvar));");
1892                 return;
1893         }
1894
1895         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "WERROR") {
1896                 $self->pidl("$target = W_ERROR(PyInt_AsLong($cvar));");
1897                 return;
1898         }
1899
1900         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "HRESULT") {
1901                 $self->pidl("$target = HRES_ERROR(PyInt_AsLong($cvar));");
1902                 return;
1903         }
1904
1905         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "string_array") {
1906                 $self->pidl("$target = pytalloc_get_ptr($cvar);");
1907                 return;
1908         }
1909
1910         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "pointer") {
1911                 $self->assign($target, "pytalloc_get_ptr($cvar)");
1912                 return;
1913         }
1914
1915         fatal($location, "unknown type `$actual_ctype->{TYPE}' for ".mapTypeName($ctype) . ": $cvar");
1916
1917 }
1918
1919 sub ConvertObjectFromPythonLevel($$$$$$$$$)
1920 {
1921         my ($self, $env, $mem_ctx, $py_var, $e, $l, $var_name, $fail, $recurse) = @_;
1922         my $nl = GetNextLevel($e, $l);
1923         if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
1924                 $nl = GetNextLevel($e, $nl);
1925         }
1926         my $pl = GetPrevLevel($e, $l);
1927         if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
1928                 $pl = GetPrevLevel($e, $pl);
1929         }
1930
1931         if ($recurse == 0) {
1932                 $self->pidl("if ($py_var == NULL) {");
1933                 $self->indent;
1934                 $self->pidl("PyErr_Format(PyExc_AttributeError, \"Cannot delete NDR object: " .
1935                     mapTypeName($var_name) . "\");");
1936                 $self->pidl($fail);
1937                 $self->deindent;
1938                 $self->pidl("}");
1939         }
1940         $recurse = $recurse + 1;
1941
1942         if ($l->{TYPE} eq "POINTER") {
1943                 my $need_deindent = 0;
1944                 my $need_deref = 0;
1945
1946                 if ($l->{POINTER_TYPE} ne "ref") {
1947                         $self->pidl("if ($py_var == Py_None) {");
1948                         $self->indent;
1949                         $self->pidl("$var_name = NULL;");
1950                         $self->deindent;
1951                         $self->pidl("} else {");
1952                         $self->indent;
1953                         $need_deindent = 1;
1954                         if ($nl->{TYPE} eq "POINTER") {
1955                                 $need_deref = 1;
1956                         }
1957                 }
1958
1959                 if ($l->{POINTER_TYPE} eq "ref" or $need_deref == 1) {
1960                         $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
1961                         $self->pidl("if ($var_name == NULL) {");
1962                         $self->indent;
1963                         $self->pidl("PyErr_NoMemory();");
1964                         $self->pidl($fail);
1965                         $self->deindent;
1966                         $self->pidl("}");
1967                 } elsif ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::is_scalar($nl->{DATA_TYPE})
1968                          and not Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1969                         $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
1970                         $self->pidl("if ($var_name == NULL) {");
1971                         $self->indent;
1972                         $self->pidl("PyErr_NoMemory();");
1973                         $self->pidl($fail);
1974                         $self->deindent;
1975                         $self->pidl("}");
1976                 } else {
1977                         $self->pidl("$var_name = NULL;");
1978                 }
1979                 if ($need_deref == 1) {
1980                         my $ndr_pointer_typename = $self->import_type_variable("samba.dcerpc.base", "ndr_pointer");
1981                         $self->pidl("$py_var = py_dcerpc_ndr_pointer_deref($ndr_pointer_typename, $py_var);");
1982                 }
1983                 unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1984                         $var_name = get_value_of($var_name);
1985                 }
1986                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail, $recurse);
1987                 if ($need_deindent == 1) {
1988                         $self->deindent;
1989                         $self->pidl("}");
1990                 }
1991         } elsif ($l->{TYPE} eq "ARRAY") {
1992                 if ($pl && $pl->{TYPE} eq "POINTER") {
1993                         $var_name = get_pointer_to($var_name);
1994                 }
1995
1996                 if (is_charset_array($e, $l)) {
1997                         $self->ConvertStringFromPythonData($mem_ctx, $py_var, $var_name, $fail);
1998                 } else {
1999                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
2000                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
2001                         $self->pidl("{");
2002                         $self->indent;
2003                         $self->pidl("int $counter;");
2004                         if (ArrayDynamicallyAllocated($e, $l)) {
2005                                 $self->pidl("$var_name = talloc_array_ptrtype($mem_ctx, $var_name, PyList_GET_SIZE($py_var));");
2006                                 $self->pidl("if (!$var_name) { $fail; }");
2007                                 $self->pidl("talloc_set_name_const($var_name, \"ARRAY: $var_name\");");
2008                         } else {
2009                                 $self->pidl("if (ARRAY_SIZE($var_name) != PyList_GET_SIZE($py_var)) {");
2010                                 $self->indent;
2011                                 $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected list of type %s, length %zu, got %zd\", Py_TYPE($py_var)->tp_name, ARRAY_SIZE($var_name),  PyList_GET_SIZE($py_var));");
2012                                 $self->pidl("$fail");
2013                                 $self->deindent;
2014                                 $self->pidl("}");
2015                         }
2016                         $self->pidl("for ($counter = 0; $counter < PyList_GET_SIZE($py_var); $counter++) {");
2017                         $self->indent;
2018                         $self->ConvertObjectFromPythonLevel($env, $var_name, "PyList_GET_ITEM($py_var, $counter)", $e, $nl, $var_name."[$counter]", $fail, 0);
2019                         $self->deindent;
2020                         $self->pidl("}");
2021                         $self->deindent;
2022                         $self->pidl("}");
2023                 }
2024         } elsif ($l->{TYPE} eq "DATA") {
2025                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
2026                         $var_name = get_pointer_to($var_name);
2027                 }
2028                 $self->ConvertObjectFromPythonData($mem_ctx, $py_var, $l->{DATA_TYPE}, $var_name, $fail, $e->{ORIGINAL});
2029         } elsif ($l->{TYPE} eq "SWITCH") {
2030                 $var_name = get_pointer_to($var_name);
2031                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
2032                 my $switch_ptr = "$e->{NAME}_switch_$l->{LEVEL_INDEX}";
2033                 $self->pidl("{");
2034                 $self->indent;
2035                 my $union_type = mapTypeName($nl->{DATA_TYPE});
2036                 $self->pidl("$union_type *$switch_ptr;");
2037                 $self->ConvertObjectFromPythonData($mem_ctx, $py_var, $nl->{DATA_TYPE}, $switch_ptr, $fail, $e->{ORIGINAL}, $switch);
2038                 $self->fail_on_null($switch_ptr, $fail);
2039                 $self->assign($var_name, "$switch_ptr");
2040                 $self->deindent;
2041                 $self->pidl("}");
2042         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
2043                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail, $recurse);
2044         } else {
2045                 fatal($e->{ORIGINAL}, "unknown level type $l->{TYPE}");
2046         }
2047 }
2048
2049 sub ConvertObjectFromPython($$$$$$$)
2050 {
2051         my ($self, $env, $mem_ctx, $ctype, $cvar, $target, $fail) = @_;
2052         my $recurse = 0;
2053
2054         $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $cvar, $ctype, $ctype->{LEVELS}[0], $target, $fail, $recurse);
2055 }
2056
2057 sub ConvertScalarToPython($$$$)
2058 {
2059         my ($self, $ctypename, $cvar, $mem_ctx) = @_;
2060
2061         die("expected string for $cvar, not $ctypename") if (ref($ctypename) eq "HASH");
2062
2063         $ctypename = expandAlias($ctypename);
2064
2065         if ($ctypename =~ /^(int64|dlong)$/) {
2066                 return "ndr_PyLong_FromLongLong($cvar)";
2067         }
2068
2069         if ($ctypename =~ /^(uint64|hyper|NTTIME_hyper|NTTIME|NTTIME_1sec|udlong|udlongr|uid_t|gid_t)$/) {
2070                 return "ndr_PyLong_FromUnsignedLongLong($cvar)";
2071         }
2072
2073         if ($ctypename =~ /^(char|int|int8|int16|int32|time_t)$/) {
2074                 return "PyInt_FromLong($cvar)";
2075         }
2076
2077         # Needed to ensure unsigned values in a 32 or 16 bit enum is
2078         # cast correctly to a uint32_t, not sign extended to a a
2079         # possibly 64 bit unsigned long.  (enums are signed in C,
2080         # unsigned in NDR)
2081         if ($ctypename =~ /^(uint32|uint3264)$/) {
2082                 return "ndr_PyLong_FromUnsignedLongLong((uint32_t)$cvar)";
2083         }
2084
2085         if ($ctypename =~ /^(uint|uint8|uint16|uint1632)$/) {
2086                 return "PyInt_FromLong((uint16_t)$cvar)";
2087         }
2088
2089         if ($ctypename eq "DATA_BLOB") {
2090                 return "PyBytes_FromStringAndSize((char *)($cvar).data, ($cvar).length)";
2091         }
2092
2093         if ($ctypename eq "NTSTATUS") {
2094                 return "PyErr_FromNTSTATUS($cvar)";
2095         }
2096
2097         if ($ctypename eq "WERROR") {
2098                 return "PyErr_FromWERROR($cvar)";
2099         }
2100
2101         if ($ctypename eq "HRESULT") {
2102                 return "PyErr_FromHRESULT($cvar)";
2103         }
2104
2105         if (($ctypename eq "string" or $ctypename eq "nbt_string" or $ctypename eq "nbt_name" or $ctypename eq "wrepl_nbt_name")) {
2106                 return "PyString_FromStringOrNULL($cvar)";
2107         }
2108
2109         if (($ctypename eq "dns_string" or $ctypename eq "dns_name")) {
2110                 return "PyString_FromStringOrNULL($cvar)";
2111         }
2112
2113         # Not yet supported
2114         if ($ctypename eq "string_array") {
2115                 return "pytalloc_GenericObject_reference_ex($mem_ctx, $cvar)";
2116         }
2117         if ($ctypename eq "ipv4address") { return "PyString_FromStringOrNULL($cvar)"; }
2118         if ($ctypename eq "ipv6address") { return "PyString_FromStringOrNULL($cvar)"; }
2119         if ($ctypename eq "dnsp_name") { return "PyString_FromStringOrNULL($cvar)"; }
2120         if ($ctypename eq "dnsp_string") { return "PyString_FromStringOrNULL($cvar)"; }
2121         if ($ctypename eq "pointer") {
2122                 return "pytalloc_GenericObject_reference_ex($mem_ctx, $cvar)";
2123         }
2124
2125         die("Unknown scalar type $ctypename");
2126 }
2127
2128 sub ConvertObjectToPythonData($$$$$;$$)
2129 {
2130         my ($self, $mem_ctx, $ctype, $cvar, $location, $switch) = @_;
2131
2132         die("undef type for $cvar") unless(defined($ctype));
2133
2134         $ctype = resolveType($ctype);
2135
2136         my $actual_ctype = $ctype;
2137         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
2138                 $actual_ctype = $actual_ctype->{DATA};
2139         }
2140
2141         if ($actual_ctype->{TYPE} eq "ENUM") {
2142                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::enum_type_fn($actual_ctype), $cvar, $mem_ctx);
2143         } elsif ($actual_ctype->{TYPE} eq "BITMAP") {
2144                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::bitmap_type_fn($actual_ctype), $cvar, $mem_ctx);
2145         } elsif ($actual_ctype->{TYPE} eq "SCALAR") {
2146                 return $self->ConvertScalarToPython($actual_ctype->{NAME}, $cvar, $mem_ctx);
2147         } elsif ($actual_ctype->{TYPE} eq "UNION") {
2148                 my $ctype_name = $self->use_type_variable($ctype);
2149                 unless (defined($ctype_name)) {
2150                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
2151                         return "NULL"; # FIXME!
2152                 }
2153                 return "pyrpc_import_union($ctype_name, $mem_ctx, $switch, $cvar, \"".mapTypeName($ctype)."\")";
2154         } elsif ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
2155                 my $ctype_name = $self->use_type_variable($ctype);
2156                 unless (defined($ctype_name)) {
2157                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
2158                         return "NULL"; # FIXME!
2159                 }
2160                 return "pytalloc_reference_ex($ctype_name, $mem_ctx, $cvar)";
2161         }
2162
2163         fatal($location, "unknown type $actual_ctype->{TYPE} for ".mapTypeName($ctype) . ": $cvar");
2164 }
2165
2166 sub fail_on_null($$$)
2167 {
2168         my ($self, $var, $fail) = @_;
2169         $self->pidl("if ($var == NULL) {");
2170         $self->indent;
2171         $self->pidl($fail);
2172         $self->deindent;
2173         $self->pidl("}");
2174 }
2175
2176 sub ConvertObjectToPythonLevel($$$$$$$)
2177 {
2178         my ($self, $mem_ctx, $env, $e, $l, $var_name, $py_var, $fail, $recurse) = @_;
2179         my $nl = GetNextLevel($e, $l);
2180         if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
2181                 $nl = GetNextLevel($e, $nl);
2182         }
2183         my $pl = GetPrevLevel($e, $l);
2184         if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
2185                 $pl = GetPrevLevel($e, $pl);
2186         }
2187
2188         if ($l->{TYPE} eq "POINTER") {
2189                 my $need_wrap = 0;
2190                 if ($l->{POINTER_TYPE} ne "ref" and $nl->{TYPE} eq "POINTER") {
2191                         $need_wrap = 1;
2192                 }
2193                 if ($l->{POINTER_TYPE} ne "ref") {
2194                         if ($recurse == 0) {
2195                                 $self->pidl("if ($var_name == NULL) {");
2196                                 $self->indent;
2197                                 $self->pidl("$py_var = Py_None;");
2198                                 $self->pidl("Py_INCREF($py_var);");
2199                                 $self->deindent;
2200                                 $self->pidl("} else {");
2201                                 $self->indent;
2202                         } else {
2203                                 $self->pidl("{");
2204                                 $self->indent;
2205                         }
2206                         $recurse = $recurse + 1;
2207                 }
2208                 my $var_name2 = $var_name;
2209                 my $recurse2 = $recurse;
2210                 unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
2211                         $var_name2 = get_value_of($var_name);
2212                         $recurse2 = 0;
2213                 }
2214                 $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name2, $py_var, $fail, $recurse2);
2215                 if ($l->{POINTER_TYPE} ne "ref") {
2216                         $self->deindent;
2217                         $self->pidl("}");
2218                 }
2219                 if ($need_wrap) {
2220                         my $py_var_wrap = undef;
2221                         $need_wrap = 1;
2222                         $self->pidl("{");
2223                         $self->indent;
2224                         $py_var_wrap = "py_$e->{NAME}_level_$l->{LEVEL_INDEX}";
2225                         $self->pidl("PyObject *$py_var_wrap = $py_var;");
2226                         my $ndr_pointer_typename = $self->import_type_variable("samba.dcerpc.base", "ndr_pointer");
2227                         $self->pidl("$py_var = py_dcerpc_ndr_pointer_wrap($ndr_pointer_typename, $py_var_wrap);");
2228                         $self->pidl("Py_XDECREF($py_var_wrap);");
2229                         $self->deindent;
2230                         $self->pidl("}");
2231                 }
2232         } elsif ($l->{TYPE} eq "ARRAY") {
2233                 if ($pl && $pl->{TYPE} eq "POINTER") {
2234                         $var_name = get_pointer_to($var_name);
2235                 }
2236
2237                 if (is_charset_array($e, $l)) {
2238                         # FIXME: Use Unix charset setting rather than utf-8
2239                         $self->pidl("if ($var_name == NULL) {");
2240                         $self->indent;
2241                         $self->pidl("$py_var = Py_None;");
2242                         $self->pidl("Py_INCREF($py_var);");
2243                         $self->deindent;
2244                         $self->pidl("} else {");
2245                         $self->indent;
2246                         $self->pidl("$py_var = PyUnicode_Decode($var_name, strlen($var_name), \"utf-8\", \"ignore\");");
2247                         $self->fail_on_null($py_var, $fail);
2248                         $self->deindent;
2249                         $self->pidl("}");
2250                 } else {
2251                         die("No SIZE_IS for array $var_name") unless (defined($l->{SIZE_IS}));
2252                         my $length = $l->{SIZE_IS};
2253                         if (defined($l->{LENGTH_IS})) {
2254                                 $length = $l->{LENGTH_IS};
2255                         }
2256
2257                         $length = ParseExpr($length, $env, $e);
2258                         $self->pidl("$py_var = PyList_New($length);");
2259                         $self->fail_on_null($py_var, $fail);
2260                         my $fail2 = "Py_DECREF($py_var); $fail";
2261                         $self->pidl("{");
2262                         $self->indent;
2263                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
2264                         $self->pidl("int $counter;");
2265                         $self->pidl("for ($counter = 0; $counter < ($length); $counter++) {");
2266                         $self->indent;
2267                         my $member_var = "py_$e->{NAME}_$l->{LEVEL_INDEX}";
2268                         my $ret_var = "ret_$e->{NAME}_$l->{LEVEL_INDEX}";
2269                         $self->pidl("PyObject *$member_var;");
2270                         $self->pidl("int $ret_var;");
2271                         $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name."[$counter]", $member_var, $fail2, $recurse);
2272                         $self->pidl("$ret_var = PyList_SetItem($py_var, $counter, $member_var);");
2273                         $self->pidl("if ($ret_var != 0) {");
2274                         $self->indent;
2275                         $self->pidl($fail2);
2276                         $self->deindent;
2277                         $self->pidl("}");
2278                         $self->deindent;
2279                         $self->pidl("}");
2280                         $self->deindent;
2281                         $self->pidl("}");
2282                 }
2283         } elsif ($l->{TYPE} eq "SWITCH") {
2284                 $var_name = get_pointer_to($var_name);
2285                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
2286                 my $conv = $self->ConvertObjectToPythonData($mem_ctx, $nl->{DATA_TYPE}, $var_name, $e->{ORIGINAL}, $switch);
2287                 $self->pidl("$py_var = $conv;");
2288                 $self->fail_on_null($py_var, $fail);
2289
2290         } elsif ($l->{TYPE} eq "DATA") {
2291                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
2292                         $var_name = get_pointer_to($var_name);
2293                 }
2294                 my $conv = $self->ConvertObjectToPythonData($mem_ctx, $l->{DATA_TYPE}, $var_name, $e->{ORIGINAL});
2295                 $self->pidl("$py_var = $conv;");
2296                 $self->fail_on_null($py_var, $fail);
2297         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
2298                 $self->ConvertObjectToPythonLevel($mem_ctx, $env, $e, $nl, $var_name, $py_var, $fail, $recurse);
2299         } else {
2300                 fatal($e->{ORIGINAL}, "Unknown level type $l->{TYPE} $var_name");
2301         }
2302 }
2303
2304 sub ConvertObjectToPython($$$$$$)
2305 {
2306         my ($self, $mem_ctx, $env, $ctype, $cvar, $py_var, $fail) = @_;
2307         my $recurse = 0;
2308
2309         $self->ConvertObjectToPythonLevel($mem_ctx, $env, $ctype, $ctype->{LEVELS}[0], $cvar, $py_var, $fail, $recurse);
2310 }
2311
2312 sub Parse($$$$$)
2313 {
2314     my($self,$basename,$ndr,$ndr_hdr,$hdr) = @_;
2315
2316         $self->{BASENAME} = $basename;
2317
2318     $self->pidl_hdr("
2319 /* Python wrapper functions auto-generated by pidl */
2320 #define PY_SSIZE_T_CLEAN 1 /* We use Py_ssize_t for PyArg_ParseTupleAndKeywords */
2321 #include <Python.h>
2322 #include \"python/py3compat.h\"
2323 #include \"includes.h\"
2324 #include <pytalloc.h>
2325 #include \"librpc/rpc/pyrpc.h\"
2326 #include \"librpc/rpc/pyrpc_util.h\"
2327 #include \"$hdr\"
2328 #include \"$ndr_hdr\"
2329
2330 /*
2331  * These functions are here to ensure they can be optimized out by
2332  * the compiler based on the constant input values
2333  */
2334
2335 static inline unsigned long long ndr_sizeof2uintmax(size_t var_size)
2336 {
2337         switch (var_size) {
2338         case 8:
2339                 return UINT64_MAX;
2340         case 4:
2341                 return UINT32_MAX;
2342         case 2:
2343                 return UINT16_MAX;
2344         case 1:
2345                 return UINT8_MAX;
2346         }
2347
2348         return 0;
2349 }
2350
2351 static inline long long ndr_sizeof2intmax(size_t var_size)
2352 {
2353         switch (var_size) {
2354         case 8:
2355                 return INT64_MAX;
2356         case 4:
2357                 return INT32_MAX;
2358         case 2:
2359                 return INT16_MAX;
2360         case 1:
2361                 return INT8_MAX;
2362         }
2363
2364         return 0;
2365 }
2366
2367 static inline PyObject *ndr_PyLong_FromLongLong(long long v)
2368 {
2369         if (v > LONG_MAX || v < LONG_MIN) {
2370                 return PyLong_FromLongLong(v);
2371         } else {
2372                 return PyInt_FromLong(v);
2373         }
2374 }
2375
2376 static inline PyObject *ndr_PyLong_FromUnsignedLongLong(unsigned long long v)
2377 {
2378         if (v > LONG_MAX) {
2379                 return PyLong_FromUnsignedLongLong(v);
2380         } else {
2381                 return PyInt_FromLong(v);
2382         }
2383 }
2384
2385 ");
2386
2387         foreach my $x (@$ndr) {
2388                 ($x->{TYPE} eq "IMPORT") && $self->Import(@{$x->{PATHS}});
2389             ($x->{TYPE} eq "INTERFACE") && $self->Interface($x, $basename);
2390         }
2391
2392         $self->pidl("static PyMethodDef $basename\_methods[] = {");
2393         $self->indent;
2394         foreach (@{$self->{module_methods}}) {
2395                 my ($fn_name, $pyfn_name, $flags, $doc) = @$_;
2396                 $self->pidl("{ \"$fn_name\", (PyCFunction)$pyfn_name, $flags, $doc },");
2397         }
2398
2399         $self->pidl("{ NULL, NULL, 0, NULL }");
2400         $self->deindent;
2401         $self->pidl("};");
2402
2403         $self->pidl("");
2404
2405         $self->pidl("static struct PyModuleDef moduledef = {");
2406         $self->indent;
2407         $self->pidl("PyModuleDef_HEAD_INIT,");
2408         $self->pidl(".m_name = \"$basename\",");
2409         $self->pidl(".m_doc = \"$basename DCE/RPC\",");
2410         $self->pidl(".m_size = -1,");
2411         $self->pidl(".m_methods = $basename\_methods,");
2412         $self->deindent;
2413         $self->pidl("};");
2414
2415         $self->pidl("MODULE_INIT_FUNC($basename)");
2416         $self->pidl("{");
2417         $self->indent;
2418         $self->pidl("PyObject *m = NULL;");
2419         foreach my $h (@{$self->{module_imports}}) {
2420                 $self->pidl("PyObject *$h->{'key'} = NULL;");
2421         }
2422         $self->pidl("");
2423
2424         foreach my $h (@{$self->{module_imports}}) {
2425                 my $var_name = $h->{'key'};
2426                 my $module_path = $h->{'val'};
2427                 $self->pidl("$var_name = PyImport_ImportModule(\"$module_path\");");
2428                 $self->pidl("if ($var_name == NULL)");
2429                 $self->pidl("\tgoto out;");
2430                 $self->pidl("");
2431         }
2432
2433         foreach my $h (@{$self->{type_imports}}) {
2434                 my $type_var = "$h->{'key'}\_Type";
2435                 my $module_path = $h->{'val'};
2436                 $self->pidl_hdr("static PyTypeObject *$type_var;\n");
2437                 my $pretty_name = PrettifyTypeName($h->{'key'}, $module_path);
2438                 my $module_var = "dep_$module_path";
2439                 $module_var =~ s/\./_/g;
2440                 $self->pidl("$type_var = (PyTypeObject *)PyObject_GetAttrString($module_var, \"$pretty_name\");");
2441                 $self->pidl("if ($type_var == NULL)");
2442                 $self->pidl("\tgoto out;");
2443                 $self->pidl("");
2444         }
2445
2446         $self->pidl($_) foreach (@{$self->{prereadycode}});
2447
2448         foreach (@{$self->{ready_types}}) {
2449                 $self->pidl("if (PyType_Ready($_) < 0)");
2450                 $self->pidl("\tgoto out;");
2451         }
2452
2453         $self->pidl($_) foreach (@{$self->{postreadycode}});
2454
2455         foreach (@{$self->{patch_type_calls}}) {
2456                 my ($typename, $cvar) = @$_;
2457                 $self->pidl("#ifdef PY_".uc($typename)."_PATCH");
2458                 $self->pidl("PY_".uc($typename)."_PATCH($cvar);");
2459                 $self->pidl("#endif");
2460         }
2461
2462         $self->pidl("");
2463
2464         $self->pidl("m = PyModule_Create(&moduledef);");
2465         $self->pidl("if (m == NULL)");
2466         $self->pidl("\tgoto out;");
2467         $self->pidl("");
2468         foreach my $h (@{$self->{constants}}) {
2469                 my $pretty_name = PrettifyTypeName($h->{'key'}, $basename);
2470                 my $py_obj;
2471                 my ($ctype, $cvar) = @{$h->{'val'}};
2472                 if ($cvar =~ /^[0-9]+$/ or $cvar =~ /^0x[0-9a-fA-F]+$/) {
2473                         $py_obj = "ndr_PyLong_FromUnsignedLongLong($cvar)";
2474                 } elsif ($cvar =~ /^".*"$/) {
2475                         $py_obj = "PyStr_FromString($cvar)";
2476                 } else {
2477                         $py_obj = $self->ConvertObjectToPythonData("NULL", expandAlias($ctype), $cvar, undef);
2478                 }
2479
2480                 $self->pidl("PyModule_AddObject(m, \"$pretty_name\", $py_obj);");
2481         }
2482
2483         foreach (@{$self->{module_objects}}) {
2484                 my ($object_name, $c_name) = @$_;
2485                 $self->pidl("Py_INCREF($c_name);");
2486                 $self->pidl("PyModule_AddObject(m, \"$object_name\", $c_name);");
2487         }
2488
2489         $self->pidl("#ifdef PY_MOD_".uc($basename)."_PATCH");
2490         $self->pidl("PY_MOD_".uc($basename)."_PATCH(m);");
2491         $self->pidl("#endif");
2492         $self->pidl("out:");
2493         foreach my $h (@{$self->{module_imports}}) {
2494                 my $mod_var = $h->{'key'};
2495                 $self->pidl("Py_XDECREF($mod_var);");
2496         }
2497         $self->pidl("return m;");
2498         $self->pidl("");
2499         $self->deindent;
2500         $self->pidl("}");
2501     return ($self->{res_hdr} . $self->{res});
2502 }
2503
2504 1;