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