pidl: handle hyper attribute for wireshark
[kai/samba-autobuild/.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);
14 use Parse::Pidl::Util qw(has_property ParseExpr unmake_str);
15 use Parse::Pidl::NDR qw(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 => "", constants => {},
26                      module_methods => [], module_objects => [], ready_types => [],
27                                  module_imports => {}, type_imports => {},
28                                  patch_type_calls => [], prereadycode => [],
29                                  postreadycode => []};
30         bless($self, $class);
31 }
32
33 sub pidl_hdr ($$)
34 {
35         my $self = shift;
36         $self->{res_hdr} .= shift;
37 }
38
39 sub pidl($$)
40 {
41         my ($self, $d) = @_;
42         if ($d) {
43                 if ((!($d =~ /^#/))) {
44                         $self->{res} .= $self->{tabs};
45                 }
46                 $self->{res} .= $d;
47         }
48         $self->{res} .= "\n";
49 }
50
51 sub indent($)
52 {
53         my ($self) = @_;
54         $self->{tabs} .= "\t";
55 }
56
57 sub deindent($)
58 {
59         my ($self) = @_;
60         $self->{tabs} = substr($self->{tabs}, 0, -1);
61 }
62
63 sub PrettifyTypeName($$)
64 {
65         my ($name, $basename) = @_;
66
67         $basename =~ s/^.*\.([^.]+)$/\1/;
68
69         $name =~ s/^$basename\_//;
70
71
72         return $name;
73 }
74
75 sub Import
76 {
77         my $self = shift;
78         my @imports = @_;
79         foreach (@imports) {
80                 $_ = unmake_str($_);
81                 s/\.idl$//;
82                 $self->pidl_hdr("#include \"librpc/gen_ndr/$_\.h\"\n");
83                 $self->register_module_import("samba.dcerpc.$_");
84         }
85 }
86
87 sub Const($$)
88 {
89     my ($self, $const) = @_;
90         $self->register_constant($const->{NAME}, $const->{DTYPE}, $const->{VALUE});
91 }
92
93 sub register_constant($$$$)
94 {
95         my ($self, $name, $type, $value) = @_;
96
97         $self->{constants}->{$name} = [$type, $value];
98 }
99
100 sub EnumAndBitmapConsts($$$)
101 {
102         my ($self, $name, $d) = @_;
103
104         return unless (defined($d->{ELEMENTS}));
105
106         foreach my $e (@{$d->{ELEMENTS}}) {
107                 $e =~ /^([A-Za-z0-9_]+)/;
108                 my $cname = $1;
109                 
110                 $self->register_constant($cname, $d, $cname);
111         }
112 }
113
114 sub FromUnionToPythonFunction($$$$)
115 {
116         my ($self, $mem_ctx, $type, $switch, $name) = @_;
117
118         $self->pidl("PyObject *ret;");
119         $self->pidl("");
120
121         $self->pidl("switch ($switch) {");
122         $self->indent;
123
124         foreach my $e (@{$type->{ELEMENTS}}) {
125                 $self->pidl("$e->{CASE}:");
126
127                 $self->indent;
128
129                 if ($e->{NAME}) {
130                         $self->ConvertObjectToPython($mem_ctx, {}, $e, "$name->$e->{NAME}", "ret", "return NULL;");
131                 } else {
132                         $self->pidl("ret = Py_None;");
133                         $self->pidl("Py_INCREF(ret);");
134                 }
135
136                 $self->pidl("return ret;");
137                 $self->pidl("");
138
139                 $self->deindent;
140         }
141
142         $self->deindent;
143         $self->pidl("}");
144
145         $self->pidl("PyErr_SetString(PyExc_TypeError, \"unknown union level\");");
146         $self->pidl("return NULL;");
147 }
148
149 sub FromPythonToUnionFunction($$$$$)
150 {
151         my ($self, $type, $typename, $switch, $mem_ctx, $name) = @_;
152
153         my $has_default = 0;
154
155         $self->pidl("$typename *ret = talloc_zero($mem_ctx, $typename);");
156
157         $self->pidl("switch ($switch) {");
158         $self->indent;
159
160         foreach my $e (@{$type->{ELEMENTS}}) {
161                 $self->pidl("$e->{CASE}:");
162                 if ($e->{CASE} eq "default") { $has_default = 1; }
163                 $self->indent;
164                 if ($e->{NAME}) {
165                         $self->ConvertObjectFromPython({}, $mem_ctx, $e, $name, "ret->$e->{NAME}", "talloc_free(ret); return NULL;");
166                 }
167                 $self->pidl("break;");
168                 $self->deindent;
169                 $self->pidl("");
170         }
171
172         if (!$has_default) {
173                 $self->pidl("default:");
174                 $self->indent;
175                 $self->pidl("PyErr_SetString(PyExc_TypeError, \"invalid union level value\");");
176                 $self->pidl("talloc_free(ret);");
177                 $self->pidl("ret = NULL;");
178                 $self->deindent;
179         }
180
181         $self->deindent;
182         $self->pidl("}");
183         $self->pidl("");
184         $self->pidl("return ret;");
185 }
186
187 sub PythonStruct($$$$$$)
188 {
189         my ($self, $modulename, $prettyname, $name, $cname, $d) = @_;
190
191         my $env = GenerateStructEnv($d, "object");
192
193         $self->pidl("");
194
195         my $getsetters = "NULL";
196
197         if ($#{$d->{ELEMENTS}} > -1) {
198                 foreach my $e (@{$d->{ELEMENTS}}) {
199                         my $varname = "object->$e->{NAME}";
200                         $self->pidl("static PyObject *py_$name\_get_$e->{NAME}(PyObject *obj, void *closure)");
201                         $self->pidl("{");
202                         $self->indent;
203                         $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(obj);");
204                         $self->pidl("PyObject *py_$e->{NAME};");
205                         $self->ConvertObjectToPython("py_talloc_get_mem_ctx(obj)", $env, $e, $varname, "py_$e->{NAME}", "return NULL;");
206                         $self->pidl("return py_$e->{NAME};");
207                         $self->deindent;
208                         $self->pidl("}");
209                         $self->pidl("");
210
211                         $self->pidl("static int py_$name\_set_$e->{NAME}(PyObject *py_obj, PyObject *value, void *closure)");
212                         $self->pidl("{");
213                         $self->indent;
214                         $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(py_obj);");
215                         my $mem_ctx = "py_talloc_get_mem_ctx(py_obj)";
216                         my $l = $e->{LEVELS}[0];
217                         my $nl = GetNextLevel($e, $l);
218                         if ($l->{TYPE} eq "POINTER" and 
219                                 not ($nl->{TYPE} eq "ARRAY" and ($nl->{IS_FIXED} or is_charset_array($e, $nl))) and
220                                 not ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE}))) {
221                                 $self->pidl("talloc_unlink(py_talloc_get_mem_ctx(py_obj), $varname);");
222                         }
223                         $self->ConvertObjectFromPython($env, $mem_ctx, $e, "value", $varname, "return -1;");
224                         $self->pidl("return 0;");
225                         $self->deindent;
226                         $self->pidl("}");
227                         $self->pidl("");
228                 }
229
230                 $getsetters = "py_$name\_getsetters";
231                 $self->pidl("static PyGetSetDef ".$getsetters."[] = {");
232                 $self->indent;
233                 foreach my $e (@{$d->{ELEMENTS}}) {
234                         $self->pidl("{ discard_const_p(char, \"$e->{NAME}\"), py_$name\_get_$e->{NAME}, py_$name\_set_$e->{NAME} },");
235                 }
236                 $self->pidl("{ NULL }");
237                 $self->deindent;
238                 $self->pidl("};");
239                 $self->pidl("");
240         }
241
242         $self->pidl("static PyObject *py_$name\_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
243         $self->pidl("{");
244         $self->indent;
245         $self->pidl("return py_talloc_new($cname, type);");
246         $self->deindent;
247         $self->pidl("}");
248         $self->pidl("");
249
250         my $py_methods = "NULL";
251
252         # If the struct is not public there ndr_pull/ndr_push functions will 
253         # be static so not callable from here
254         if (has_property($d, "public")) {
255                 $self->pidl("static PyObject *py_$name\_ndr_pack(PyObject *py_obj)");
256                 $self->pidl("{");
257                 $self->indent;
258                 $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(py_obj);");
259                 $self->pidl("DATA_BLOB blob;");
260                 $self->pidl("enum ndr_err_code err;");
261                 $self->pidl("err = ndr_push_struct_blob(&blob, py_talloc_get_mem_ctx(py_obj), object, (ndr_push_flags_fn_t)ndr_push_$name);");
262                 $self->pidl("if (err != NDR_ERR_SUCCESS) {");
263                 $self->indent;
264                 $self->pidl("PyErr_SetNdrError(err);");
265                 $self->pidl("return NULL;");
266                 $self->deindent;
267                 $self->pidl("}");
268                 $self->pidl("");
269                 $self->pidl("return PyString_FromStringAndSize((char *)blob.data, blob.length);");
270                 $self->deindent;
271                 $self->pidl("}");
272                 $self->pidl("");
273
274                 $self->pidl("static PyObject *py_$name\_ndr_unpack(PyObject *py_obj, PyObject *args)");
275                 $self->pidl("{");
276                 $self->indent;
277                 $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(py_obj);");
278                 $self->pidl("DATA_BLOB blob;");
279                 $self->pidl("enum ndr_err_code err;");
280                 $self->pidl("if (!PyArg_ParseTuple(args, \"s#:__ndr_unpack__\", &blob.data, &blob.length))");
281                 $self->pidl("\treturn NULL;");
282                 $self->pidl("");
283                 $self->pidl("err = ndr_pull_struct_blob_all(&blob, py_talloc_get_mem_ctx(py_obj), object, (ndr_pull_flags_fn_t)ndr_pull_$name);");
284                 $self->pidl("if (err != NDR_ERR_SUCCESS) {");
285                 $self->indent;
286                 $self->pidl("PyErr_SetNdrError(err);");
287                 $self->pidl("return NULL;");
288                 $self->deindent;
289                 $self->pidl("}");
290                 $self->pidl("");
291                 $self->pidl("Py_RETURN_NONE;");
292                 $self->deindent;
293                 $self->pidl("}");
294                 $self->pidl("");
295
296                 $self->pidl("static PyObject *py_$name\_ndr_print(PyObject *py_obj)");
297                 $self->pidl("{");
298                 $self->indent;
299                 $self->pidl("$cname *object = ($cname *)py_talloc_get_ptr(py_obj);");
300                 $self->pidl("PyObject *ret;");
301                 $self->pidl("char *retstr;");
302                 $self->pidl("");
303                 $self->pidl("retstr = ndr_print_struct_string(py_talloc_get_mem_ctx(py_obj), (ndr_print_fn_t)ndr_print_$name, \"$name\", object);");
304                 $self->pidl("ret = PyString_FromString(retstr);");
305                 $self->pidl("talloc_free(retstr);");
306                 $self->pidl("");
307                 $self->pidl("return ret;");
308                 $self->deindent;
309                 $self->pidl("}");
310                 $self->pidl("");
311
312                 $py_methods = "py_$name\_methods";
313                 $self->pidl("static PyMethodDef $py_methods\[] = {");
314                 $self->indent;
315                 $self->pidl("{ \"__ndr_pack__\", (PyCFunction)py_$name\_ndr_pack, METH_NOARGS, \"S.ndr_pack(object) -> blob\\nNDR pack\" },");
316                 $self->pidl("{ \"__ndr_unpack__\", (PyCFunction)py_$name\_ndr_unpack, METH_VARARGS, \"S.ndr_unpack(class, blob) -> None\\nNDR unpack\" },");
317                 $self->pidl("{ \"__ndr_print__\", (PyCFunction)py_$name\_ndr_print, METH_VARARGS, \"S.ndr_print(object) -> None\\nNDR print\" },");
318                 $self->pidl("{ NULL, NULL, 0, NULL }");
319                 $self->deindent;
320                 $self->pidl("};");
321                 $self->pidl("");
322         }
323
324         $self->pidl_hdr("staticforward PyTypeObject $name\_Type;\n");
325         $self->pidl("");
326         my $docstring = $self->DocString($d, $name);
327         my $typeobject = "$name\_Type";
328         $self->pidl("static PyTypeObject $typeobject = {");
329         $self->indent;
330         $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
331         $self->pidl(".tp_name = \"$modulename.$prettyname\",");
332         $self->pidl(".tp_getset = $getsetters,");
333         if ($docstring) {
334                 $self->pidl(".tp_doc = $docstring,");
335         }
336         $self->pidl(".tp_methods = $py_methods,");
337         $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
338         $self->pidl(".tp_basicsize = sizeof(py_talloc_Object),");
339         $self->pidl(".tp_new = py_$name\_new,");
340         $self->deindent;
341         $self->pidl("};");
342
343         $self->pidl("");
344
345         my $talloc_typename = $self->import_type_variable("talloc", "Object");
346         $self->register_module_prereadycode(["$name\_Type.tp_base = $talloc_typename;", ""]);
347
348         return "&$typeobject";
349 }
350
351 sub get_metadata_var($)
352 {
353         my ($e) = @_;
354         sub get_var($) { my $x = shift; $x =~ s/\*//g; return $x; }
355
356          if (has_property($e, "length_is")) {
357                 return get_var($e->{PROPERTIES}->{length_is});
358          } elsif (has_property($e, "size_is")) {
359                 return get_var($e->{PROPERTIES}->{size_is});
360          }
361
362          return undef;
363 }
364
365 sub find_metadata_args($)
366 {
367         my ($fn) = @_;
368         my $metadata_args = { in => {}, out => {} };
369
370         # Determine arguments that are metadata for other arguments (size_is/length_is)
371         foreach my $e (@{$fn->{ELEMENTS}}) {
372                 foreach my $dir (@{$e->{DIRECTION}}) {
373                          my $main = get_metadata_var($e);
374                          if ($main) { 
375                                  $metadata_args->{$dir}->{$main} = $e->{NAME}; 
376                          }
377                  }
378         }
379
380         return $metadata_args;
381 }
382
383 sub PythonFunctionUnpackOut($$$)
384 {
385         my ($self, $fn, $fnname) = @_;
386
387         my $outfnname = "unpack_$fnname\_args_out";
388         my $signature = "";
389
390         my $metadata_args = find_metadata_args($fn);
391
392         my $env = GenerateFunctionOutEnv($fn, "r->");
393         my $result_size = 0;
394
395         $self->pidl("static PyObject *$outfnname(struct $fn->{NAME} *r)");
396         $self->pidl("{");
397         $self->indent;
398         $self->pidl("PyObject *result;");
399         foreach my $e (@{$fn->{ELEMENTS}}) {
400                 next unless (grep(/out/,@{$e->{DIRECTION}}));
401                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or 
402                          ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
403                 $self->pidl("PyObject *py_$e->{NAME};");
404                 $result_size++;
405         }
406
407         if ($fn->{RETURN_TYPE}) {
408                 $result_size++ unless ($fn->{RETURN_TYPE} eq "WERROR" or $fn->{RETURN_TYPE} eq "NTSTATUS");
409         }
410
411         my $i = 0;
412
413         if ($result_size > 1) {
414                 $self->pidl("result = PyTuple_New($result_size);");
415                 $signature .= "(";
416         } elsif ($result_size == 0) {
417                 $self->pidl("result = Py_None;");
418                 $self->pidl("Py_INCREF(result);");
419                 $signature .= "None";
420         }
421
422         foreach my $e (@{$fn->{ELEMENTS}}) {
423                 next if ($metadata_args->{out}->{$e->{NAME}});
424                 my $py_name = "py_$e->{NAME}";
425                 if (grep(/out/,@{$e->{DIRECTION}})) {
426                         $self->ConvertObjectToPython("r", $env, $e, "r->out.$e->{NAME}", $py_name, "return NULL;");
427                         if ($result_size > 1) {
428                                 $self->pidl("PyTuple_SetItem(result, $i, $py_name);");
429                                 $i++;
430                                 $signature .= "$e->{NAME}, ";
431                         } else {
432                                 $self->pidl("result = $py_name;");
433                                 $signature .= $e->{NAME};
434                         }
435                 }
436         }
437
438         if (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "NTSTATUS") {
439                 $self->handle_ntstatus("r->out.result", "NULL", undef);
440         } elsif (defined($fn->{RETURN_TYPE}) and $fn->{RETURN_TYPE} eq "WERROR") {
441                 $self->handle_werror("r->out.result", "NULL", undef);
442         } elsif (defined($fn->{RETURN_TYPE})) {
443                 my $conv = $self->ConvertObjectToPythonData("r", $fn->{RETURN_TYPE}, "r->out.result", $fn);
444                 if ($result_size > 1) {
445                         $self->pidl("PyTuple_SetItem(result, $i, $conv);");
446                 } else {
447                         $self->pidl("result = $conv;");
448                 }
449                 $signature .= "result";
450         }
451
452         if (substr($signature, -2) eq ", ") {
453                 $signature = substr($signature, 0, -2);
454         }
455         if ($result_size > 1) {
456                 $signature .= ")";
457         }
458
459         $self->pidl("return result;");
460         $self->deindent;
461         $self->pidl("}");
462         $self->pidl("");
463
464         return ($outfnname, $signature);
465 }
466
467 sub PythonFunctionPackIn($$$)
468 {
469         my ($self, $fn, $fnname) = @_;
470         my $metadata_args = find_metadata_args($fn);
471
472         my $infnname = "pack_$fnname\_args_in";
473
474         $self->pidl("static bool $infnname(PyObject *args, PyObject *kwargs, struct $fn->{NAME} *r)");
475         $self->pidl("{");
476         $self->indent;
477         my $args_format = "";
478         my $args_string = "";
479         my $args_names = "";
480         my $signature = "";
481
482         foreach my $e (@{$fn->{ELEMENTS}}) {
483                 next unless (grep(/in/,@{$e->{DIRECTION}}));
484                 next if (($metadata_args->{in}->{$e->{NAME}} and grep(/in/, @{$e->{DIRECTION}})) or 
485                                  ($metadata_args->{out}->{$e->{NAME}}) and grep(/out/, @{$e->{DIRECTION}}));
486                 $self->pidl("PyObject *py_$e->{NAME};");
487                 $args_format .= "O";
488                 $args_string .= ", &py_$e->{NAME}";
489                 $args_names .= "\"$e->{NAME}\", ";
490                 $signature .= "$e->{NAME}, ";
491         }
492         if (substr($signature, -2) eq ", ") {
493                 $signature = substr($signature, 0, -2);
494         }
495         $self->pidl("const char *kwnames[] = {");
496         $self->indent;
497         $self->pidl($args_names . "NULL");
498         $self->deindent;
499         $self->pidl("};");
500
501         $self->pidl("");
502         $self->pidl("if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"$args_format:$fn->{NAME}\", discard_const_p(char *, kwnames)$args_string)) {");
503         $self->indent;
504         $self->pidl("return false;");
505         $self->deindent;
506         $self->pidl("}");
507         $self->pidl("");
508
509         my $env = GenerateFunctionInEnv($fn, "r->");
510
511         my $fail = "return false;";
512         foreach my $e (@{$fn->{ELEMENTS}}) {
513                 next unless (grep(/in/,@{$e->{DIRECTION}}));
514                 if ($metadata_args->{in}->{$e->{NAME}}) {
515                         my $py_var = "py_".$metadata_args->{in}->{$e->{NAME}};
516                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
517                         my $val = "PyList_GET_SIZE($py_var)";
518                         if ($e->{LEVELS}[0]->{TYPE} eq "POINTER") {
519                                 $self->pidl("r->in.$e->{NAME} = talloc_ptrtype(r, r->in.$e->{NAME});");
520                                 $self->pidl("*r->in.$e->{NAME} = $val;");
521                         } else {
522                                 $self->pidl("r->in.$e->{NAME} = $val;");
523                         }
524                 } else {
525                         $self->ConvertObjectFromPython($env, "r", $e, "py_$e->{NAME}", "r->in.$e->{NAME}", $fail);
526                 }
527         }
528         $self->pidl("return true;");
529         $self->deindent;
530         $self->pidl("}");
531         $self->pidl("");
532         return ($infnname, $signature);
533 }
534
535 sub PythonFunction($$$)
536 {
537         my ($self, $fn, $iface, $prettyname) = @_;
538
539         my $fnname = "py_$fn->{NAME}";
540         my $docstring = $self->DocString($fn, $fn->{NAME});
541
542         my ($infn, $insignature) = $self->PythonFunctionPackIn($fn, $fnname);
543         my ($outfn, $outsignature) = $self->PythonFunctionUnpackOut($fn, $fnname);
544         my $signature = "S.$prettyname($insignature) -> $outsignature";
545         if ($docstring) {
546                 $docstring = "\"$signature\\n\\n\"$docstring";
547         } else {
548                 $docstring = "\"$signature\"";
549         }
550
551         return ($infn, $outfn, $docstring);
552 }
553
554 sub handle_werror($$$$)
555 {
556         my ($self, $var, $retval, $mem_ctx) = @_;
557
558         $self->pidl("if (!W_ERROR_IS_OK($var)) {");
559         $self->indent;
560         $self->pidl("PyErr_SetWERROR($var);");
561         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
562         $self->pidl("return $retval;");
563         $self->deindent;
564         $self->pidl("}");
565         $self->pidl("");
566 }
567
568 sub handle_ntstatus($$$$)
569 {
570         my ($self, $var, $retval, $mem_ctx) = @_;
571
572         $self->pidl("if (NT_STATUS_IS_ERR($var)) {");
573         $self->indent;
574         $self->pidl("PyErr_SetNTSTATUS($var);");
575         $self->pidl("talloc_free($mem_ctx);") if ($mem_ctx);
576         $self->pidl("return $retval;");
577         $self->deindent;
578         $self->pidl("}");
579         $self->pidl("");
580 }
581
582 sub PythonType($$$$)
583 {
584         my ($self, $modulename, $d, $interface, $basename) = @_;
585
586         my $actual_ctype = $d;
587         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
588                 $actual_ctype = $actual_ctype->{DATA};
589         }
590
591         if ($actual_ctype->{TYPE} eq "STRUCT") {
592                 my $typeobject;
593                 my $fn_name = PrettifyTypeName($d->{NAME}, $basename);
594
595                 if ($d->{TYPE} eq "STRUCT") {
596                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d);
597                 } else {
598                         $typeobject = $self->PythonStruct($modulename, $fn_name, $d->{NAME}, mapTypeName($d), $d->{DATA});
599                 }
600
601                 $self->register_module_typeobject($fn_name, $typeobject);
602         }
603
604         if ($d->{TYPE} eq "ENUM" or $d->{TYPE} eq "BITMAP") {
605                 $self->EnumAndBitmapConsts($d->{NAME}, $d);
606         }
607
608         if ($d->{TYPE} eq "TYPEDEF" and ($d->{DATA}->{TYPE} eq "ENUM" or $d->{DATA}->{TYPE} eq "BITMAP")) {
609                 $self->EnumAndBitmapConsts($d->{NAME}, $d->{DATA});
610         }
611
612         if ($actual_ctype->{TYPE} eq "UNION" and defined($actual_ctype->{ELEMENTS})) {
613                 $self->pidl("PyObject *py_import_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, " .mapTypeName($d) . " *in)");
614                 $self->pidl("{");
615                 $self->indent;
616                 $self->FromUnionToPythonFunction("mem_ctx", $actual_ctype, "level", "in") if ($actual_ctype->{TYPE} eq "UNION");
617                 $self->deindent;
618                 $self->pidl("}");
619                 $self->pidl("");
620
621                 $self->pidl(mapTypeName($d) . " *py_export_$d->{NAME}(TALLOC_CTX *mem_ctx, int level, PyObject *in)");
622                 $self->pidl("{");
623                 $self->indent;
624                 $self->FromPythonToUnionFunction($actual_ctype, mapTypeName($d), "level", "mem_ctx", "in") if ($actual_ctype->{TYPE} eq "UNION");
625                 $self->deindent;
626                 $self->pidl("}");
627                 $self->pidl("");
628         }
629 }
630
631 sub DocString($$$)
632 {
633         my ($self, $d, $name) = @_;
634         if (has_property($d, "helpstring")) {
635                 my $docstring = uc("py_doc_$name");
636                 $self->pidl("#define $docstring ".has_property($d, "helpstring"));
637                 return $docstring;
638         }
639
640         return undef;
641 }
642
643 sub Interface($$$)
644 {
645         my($self,$interface,$basename) = @_;
646
647         if (has_property($interface, "pyhelper")) {
648                 $self->pidl("#include \"".unmake_str($interface->{PROPERTIES}->{pyhelper})."\"\n");
649         }
650
651         $self->Const($_) foreach (@{$interface->{CONSTS}});
652
653         foreach my $d (@{$interface->{TYPES}}) {
654                 next if has_property($d, "nopython");
655
656                 $self->PythonType($basename, $d, $interface, $basename);
657         }
658
659         if (defined $interface->{PROPERTIES}->{uuid}) {
660                 $self->pidl_hdr("staticforward PyTypeObject $interface->{NAME}_InterfaceType;\n");
661                 $self->pidl("");
662
663                 my @fns = ();
664
665                 foreach my $d (@{$interface->{FUNCTIONS}}) {
666                         next if has_property($d, "noopnum");
667                         next if has_property($d, "nopython");
668                         next if has_property($d, "todo");
669
670                         my $skip = 0;
671                         foreach my $e (@{$d->{ELEMENTS}}) {
672                                 if (ContainsPipe($e, $e->{LEVELS}[0])) {
673                                         $skip = 1;
674                                         last;
675                                 }
676                         }
677                         next if $skip;
678
679                         my $prettyname = $d->{NAME};
680
681                         $prettyname =~ s/^$interface->{NAME}_//;
682                         $prettyname =~ s/^$basename\_//;
683
684                         my ($infn, $outfn, $fndocstring) = $self->PythonFunction($d, $interface->{NAME}, $prettyname);
685
686                         push (@fns, [$infn, $outfn, "dcerpc_$d->{NAME}_r", $prettyname, $fndocstring, $d->{OPNUM}]);
687                 }
688
689                 $self->pidl("const struct PyNdrRpcMethodDef py_ndr_$interface->{NAME}\_methods[] = {");
690                 $self->indent;
691                 foreach my $d (@fns) {
692                         my ($infn, $outfn, $callfn, $prettyname, $docstring, $opnum) = @$d;
693                         $self->pidl("{ \"$prettyname\", $docstring, (py_dcerpc_call_fn)$callfn, (py_data_pack_fn)$infn, (py_data_unpack_fn)$outfn, $opnum, &ndr_table_$interface->{NAME} },");
694                 }
695                 $self->pidl("{ NULL }");
696                 $self->deindent;
697                 $self->pidl("};");
698                 $self->pidl("");
699
700                 $self->pidl("static PyObject *interface_$interface->{NAME}_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)");
701                 $self->pidl("{");
702                 $self->indent;
703                 $self->pidl("return py_dcerpc_interface_init_helper(type, args, kwargs, &ndr_table_$interface->{NAME});");
704                 $self->deindent;
705                 $self->pidl("}");
706         
707                 $self->pidl("");
708
709                 my $signature = 
710 "\"$interface->{NAME}(binding, lp_ctx=None, credentials=None) -> connection\\n\"
711 \"\\n\"
712 \"binding should be a DCE/RPC binding string (for example: ncacn_ip_tcp:127.0.0.1)\\n\"
713 \"lp_ctx should be a path to a smb.conf file or a param.LoadParm object\\n\"
714 \"credentials should be a credentials.Credentials object.\\n\\n\"";
715
716                 my $docstring = $self->DocString($interface, $interface->{NAME});
717
718                 if ($docstring) {
719                         $docstring = "$signature$docstring";
720                 } else {
721                         $docstring = $signature;
722                 }
723
724                 my $if_typename = "$interface->{NAME}_InterfaceType";
725
726                 $self->pidl("static PyTypeObject $if_typename = {");
727                 $self->indent;
728                 $self->pidl("PyObject_HEAD_INIT(NULL) 0,");
729                 $self->pidl(".tp_name = \"$basename.$interface->{NAME}\",");
730                 $self->pidl(".tp_basicsize = sizeof(dcerpc_InterfaceObject),");
731                 $self->pidl(".tp_doc = $docstring,");
732                 $self->pidl(".tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,");
733                 $self->pidl(".tp_new = interface_$interface->{NAME}_new,");
734                 $self->deindent;
735                 $self->pidl("};");
736
737                 $self->pidl("");
738
739                 $self->register_module_typeobject($interface->{NAME}, "&$if_typename");
740                 my $dcerpc_typename = $self->import_type_variable("samba.dcerpc.base", "ClientConnection");
741                 $self->register_module_prereadycode(["$if_typename.tp_base = $dcerpc_typename;", ""]);
742                 $self->register_module_postreadycode(["if (!PyInterface_AddNdrRpcMethods(&$if_typename, py_ndr_$interface->{NAME}\_methods))", "\treturn;", ""]);
743         }
744
745         $self->pidl_hdr("\n");
746 }
747
748 sub register_module_method($$$$$)
749 {
750         my ($self, $fn_name, $pyfn_name, $flags, $doc) = @_;
751
752         push (@{$self->{module_methods}}, [$fn_name, $pyfn_name, $flags, $doc])
753 }
754
755 sub register_module_typeobject($$$)
756 {
757         my ($self, $name, $py_name) = @_;
758
759         $self->register_module_object($name, "(PyObject *)(void *)$py_name");
760
761         $self->check_ready_type($py_name);
762
763         $self->register_patch_type_call($name, $py_name);
764 }
765
766 sub check_ready_type($$)
767 {
768         my ($self, $py_name) = @_;
769         push (@{$self->{ready_types}}, $py_name) unless (grep(/^$py_name$/,@{$self->{ready_types}}));
770 }
771
772 sub register_module_import($$)
773 {
774         my ($self, $module_path) = @_;
775
776         my $var_name = $module_path;
777         $var_name =~ s/\./_/g;
778         $var_name = "dep_$var_name";
779
780         $self->{module_imports}->{$var_name} = $module_path;
781
782         return $var_name;
783 }
784
785 sub import_type_variable($$$)
786 {
787         my ($self, $module, $name) = @_;
788
789         $self->register_module_import($module);
790         unless (defined($self->{type_imports}->{$name})) {
791                 $self->{type_imports}->{$name} = $module;
792         }
793         return "$name\_Type";
794 }
795
796 sub use_type_variable($$)
797 {
798         my ($self, $orig_ctype) = @_;
799         # FIXME: Have a global lookup table for types that look different on the 
800         # wire than they are named in C?
801         if ($orig_ctype->{NAME} eq "dom_sid2" or $orig_ctype->{NAME} eq "dom_sid28") {
802                 $orig_ctype->{NAME} = "dom_sid";
803         }
804         my $ctype = resolveType($orig_ctype);
805         unless (defined($ctype->{BASEFILE})) {
806                 return undef;
807         }
808         # If this is an external type, make sure we do the right imports.
809         if (($ctype->{BASEFILE} ne $self->{BASENAME})) {
810                 return $self->import_type_variable("samba.dcerpc.$ctype->{BASEFILE}", $ctype->{NAME});
811         }
812         return "&$ctype->{NAME}_Type";
813 }
814
815 sub register_patch_type_call($$$)
816 {
817         my ($self, $typename, $cvar) = @_;
818
819         push(@{$self->{patch_type_calls}}, [$typename, $cvar]);
820
821 }
822
823 sub register_module_prereadycode($$)
824 {
825         my ($self, $code) = @_;
826
827         push (@{$self->{prereadycode}}, @$code);
828 }
829
830 sub register_module_postreadycode($$)
831 {
832         my ($self, $code) = @_;
833
834         push (@{$self->{postreadycode}}, @$code);
835 }
836
837 sub register_module_object($$$)
838 {
839         my ($self, $name, $py_name) = @_;
840
841         push (@{$self->{module_objects}}, [$name, $py_name])
842 }
843
844 sub assign($$$)
845 {
846         my ($self, $dest, $src) = @_;
847         if ($dest =~ /^\&/ and $src eq "NULL") {
848                 $self->pidl("memset($dest, 0, sizeof(" . get_value_of($dest) . "));");
849         } elsif ($dest =~ /^\&/) {
850                 my $destvar = get_value_of($dest);
851                 $self->pidl("$destvar = *$src;");
852         } else {
853                 $self->pidl("$dest = $src;");
854         }
855 }
856
857 sub ConvertObjectFromPythonData($$$$$$;$)
858 {
859         my ($self, $mem_ctx, $cvar, $ctype, $target, $fail, $location) = @_;
860
861         fatal($location, "undef type for $cvar") unless(defined($ctype));
862
863         $ctype = resolveType($ctype);
864
865         my $actual_ctype = $ctype;
866         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
867                 $actual_ctype = $actual_ctype->{DATA};
868         }
869
870         if ($actual_ctype->{TYPE} eq "ENUM" or $actual_ctype->{TYPE} eq "BITMAP") {
871                 $self->pidl("if (PyLong_Check($cvar)) {");
872                 $self->indent;
873                 $self->pidl("$target = PyLong_AsLongLong($cvar);");
874                 $self->deindent;
875                 $self->pidl("} else if (PyInt_Check($cvar)) {");
876                 $self->indent;
877                 $self->pidl("$target = PyInt_AsLong($cvar);");
878                 $self->deindent;
879                 $self->pidl("} else {");
880                 $self->indent;
881                 $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
882                 $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name);");
883                 $self->pidl($fail);
884                 $self->deindent;
885                 $self->pidl("}");
886                 return;
887         }
888         if ($actual_ctype->{TYPE} eq "SCALAR" ) {
889                 if (expandAlias($actual_ctype->{NAME}) =~ /^(u?int64|hyper|dlong|udlong|udlongr|NTTIME_hyper|NTTIME|NTTIME_1sec)$/) {
890                         $self->pidl("if (PyLong_Check($cvar)) {");
891                         $self->indent;
892                         $self->pidl("$target = PyLong_AsLongLong($cvar);");
893                         $self->deindent;
894                         $self->pidl("} else if (PyInt_Check($cvar)) {");
895                         $self->indent;
896                         $self->pidl("$target = PyInt_AsLong($cvar);");
897                         $self->deindent;
898                         $self->pidl("} else {");
899                         $self->indent;
900                         $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected type %s or %s\",\\");
901                         $self->pidl("  PyInt_Type.tp_name, PyLong_Type.tp_name);");
902                         $self->pidl($fail);
903                         $self->deindent;
904                         $self->pidl("}");
905                         return;
906                 }
907                 if (expandAlias($actual_ctype->{NAME}) =~ /^(char|u?int[0-9]*|time_t|uid_t|gid_t)$/) {
908                         $self->pidl("PY_CHECK_TYPE(&PyInt_Type, $cvar, $fail);");
909                         $self->pidl("$target = PyInt_AsLong($cvar);");
910                         return;
911                 }
912         }
913
914         if ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
915                 my $ctype_name = $self->use_type_variable($ctype);
916                 unless (defined ($ctype_name)) {
917                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
918                         $self->pidl("PyErr_SetString(PyExc_TypeError, \"Can not convert C Type " . mapTypeName($ctype) . " from Python\");");
919                         return;
920                 }
921                 $self->pidl("PY_CHECK_TYPE($ctype_name, $cvar, $fail);");
922                 $self->pidl("if (talloc_reference($mem_ctx, py_talloc_get_mem_ctx($cvar)) == NULL) {");
923                 $self->indent;
924                 $self->pidl("PyErr_NoMemory();");
925                 $self->pidl("$fail");
926                 $self->deindent;
927                 $self->pidl("}");
928                 $self->assign($target, "(".mapTypeName($ctype)." *)py_talloc_get_ptr($cvar)");
929                 return;
930         }
931
932         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "DATA_BLOB") {
933                 $self->pidl("$target = data_blob_talloc($mem_ctx, PyString_AS_STRING($cvar), PyString_GET_SIZE($cvar));");
934                 return;
935         }
936
937         if ($actual_ctype->{TYPE} eq "SCALAR" and 
938                 ($actual_ctype->{NAME} eq "string" or $actual_ctype->{NAME} eq "nbt_string" or $actual_ctype->{NAME} eq "nbt_name" or $actual_ctype->{NAME} eq "wrepl_nbt_name")) {
939                 $self->pidl("$target = talloc_strdup($mem_ctx, PyString_AS_STRING($cvar));");
940                 return;
941         }
942
943         if ($actual_ctype->{TYPE} eq "SCALAR" and ($actual_ctype->{NAME} eq "dns_string" or $actual_ctype->{NAME} eq "dns_name")) {
944                 $self->pidl("$target = talloc_strdup($mem_ctx, PyString_AS_STRING($cvar));");
945                 return;
946         }
947
948         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "ipv4address") {
949                 $self->pidl("$target = PyString_AS_STRING($cvar);");
950                 return;
951         }
952
953         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "ipv6address") {
954                 $self->pidl("$target = PyString_AsString($cvar);");
955                 return;
956         }
957
958         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "dnsp_name") {
959                 $self->pidl("$target = PyString_AS_STRING($cvar);");
960                 return;
961         }
962
963         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "dnsp_string") {
964                 $self->pidl("$target = PyString_AS_STRING($cvar);");
965                 return;
966         }
967
968         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "NTSTATUS") {
969                 $self->pidl("$target = NT_STATUS(PyInt_AsLong($cvar));");
970                 return;
971         }
972
973         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "WERROR") {
974                 $self->pidl("$target = W_ERROR(PyInt_AsLong($cvar));");
975                 return;
976         }
977
978         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "string_array") {
979                 $self->pidl("$target = PyCObject_AsVoidPtr($cvar);");
980                 return;
981         }
982
983         if ($actual_ctype->{TYPE} eq "SCALAR" and $actual_ctype->{NAME} eq "pointer") {
984                 $self->assign($target, "PyCObject_AsVoidPtr($cvar)");
985                 return;
986         }
987
988         fatal($location, "unknown type `$actual_ctype->{TYPE}' for ".mapTypeName($ctype) . ": $cvar");
989
990 }
991
992 sub ConvertObjectFromPythonLevel($$$$$$$$)
993 {
994         my ($self, $env, $mem_ctx, $py_var, $e, $l, $var_name, $fail) = @_;
995         my $nl = GetNextLevel($e, $l);
996         if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
997                 $nl = GetNextLevel($e, $nl);
998         }
999         my $pl = GetPrevLevel($e, $l);
1000         if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
1001                 $pl = GetPrevLevel($e, $pl);
1002         }
1003
1004         if ($l->{TYPE} eq "POINTER") {
1005                 if ($l->{POINTER_TYPE} ne "ref") {
1006                         $self->pidl("if ($py_var == Py_None) {");
1007                         $self->indent;
1008                         $self->pidl("$var_name = NULL;");
1009                         $self->deindent;
1010                         $self->pidl("} else {");
1011                         $self->indent;
1012                 }
1013                 # if we want to handle more than one level of pointer in python interfaces
1014                 # then this is where we would need to allocate it
1015                 if ($l->{POINTER_TYPE} eq "ref") {
1016                         $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
1017                 } elsif ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::is_scalar($nl->{DATA_TYPE})
1018                          and not Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1019                         $self->pidl("$var_name = talloc_ptrtype($mem_ctx, $var_name);");
1020                 } else {
1021                         $self->pidl("$var_name = NULL;");
1022                 }
1023                 unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1024                         $var_name = get_value_of($var_name);
1025                 }
1026                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail);
1027                 if ($l->{POINTER_TYPE} ne "ref") {
1028                         $self->deindent;
1029                         $self->pidl("}");
1030                 }
1031         } elsif ($l->{TYPE} eq "ARRAY") {
1032                 if ($pl && $pl->{TYPE} eq "POINTER") {
1033                         $var_name = get_pointer_to($var_name);
1034                 }
1035
1036                 if (is_charset_array($e, $l)) {
1037                         $self->pidl("if (PyUnicode_Check($py_var)) {");
1038                         $self->indent;
1039                         # FIXME: Use Unix charset setting rather than utf-8
1040                         $self->pidl($var_name . " = PyString_AS_STRING(PyUnicode_AsEncodedString($py_var, \"utf-8\", \"ignore\"));");
1041                         $self->deindent;
1042                         $self->pidl("} else if (PyString_Check($py_var)) {");
1043                         $self->indent;
1044                         $self->pidl($var_name . " = PyString_AS_STRING($py_var);");
1045                         $self->deindent;
1046                         $self->pidl("} else {");
1047                         $self->indent;
1048                         $self->pidl("PyErr_Format(PyExc_TypeError, \"Expected string or unicode object, got %s\", Py_TYPE($py_var)->tp_name);");
1049                         $self->pidl("$fail");
1050                         $self->deindent;
1051                         $self->pidl("}");
1052                 } else {
1053                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
1054                         $self->pidl("PY_CHECK_TYPE(&PyList_Type, $py_var, $fail);");
1055                         $self->pidl("{");
1056                         $self->indent;
1057                         $self->pidl("int $counter;");
1058                         if (ArrayDynamicallyAllocated($e, $l)) {
1059                                 $self->pidl("$var_name = talloc_array_ptrtype($mem_ctx, $var_name, PyList_GET_SIZE($py_var));");
1060                                 $self->pidl("if (!$var_name) { $fail; }");
1061                                 $self->pidl("talloc_set_name_const($var_name, \"ARRAY: $var_name\");");
1062                         }
1063                         $self->pidl("for ($counter = 0; $counter < PyList_GET_SIZE($py_var); $counter++) {");
1064                         $self->indent;
1065                         $self->ConvertObjectFromPythonLevel($env, $var_name, "PyList_GET_ITEM($py_var, $counter)", $e, $nl, $var_name."[$counter]", $fail);
1066                         $self->deindent;
1067                         $self->pidl("}");
1068                         $self->deindent;
1069                         $self->pidl("}");
1070                 }
1071         } elsif ($l->{TYPE} eq "DATA") {
1072                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
1073                         $var_name = get_pointer_to($var_name);
1074                 }
1075                 $self->ConvertObjectFromPythonData($mem_ctx, $py_var, $l->{DATA_TYPE}, $var_name, $fail, $e->{ORIGINAL});
1076         } elsif ($l->{TYPE} eq "SWITCH") {
1077                 $var_name = get_pointer_to($var_name);
1078                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
1079                 my $switch_ptr = "$e->{NAME}_switch_$l->{LEVEL_INDEX}";
1080                 $self->pidl("{");
1081                 $self->indent;
1082                 my $union_type = mapTypeName($nl->{DATA_TYPE});
1083                 $self->pidl("$union_type *$switch_ptr;");
1084                 $self->pidl("$switch_ptr = py_export_" . $nl->{DATA_TYPE} . "($mem_ctx, $switch, $py_var);");
1085                 $self->fail_on_null($switch_ptr, $fail);
1086                 $self->assign($var_name, "$switch_ptr");
1087                 $self->deindent;
1088                 $self->pidl("}");
1089         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
1090                 $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $py_var, $e, $nl, $var_name, $fail);
1091         } else {
1092                 fatal($e->{ORIGINAL}, "unknown level type $l->{TYPE}");
1093         }
1094 }
1095
1096 sub ConvertObjectFromPython($$$$$$$)
1097 {
1098         my ($self, $env, $mem_ctx, $ctype, $cvar, $target, $fail) = @_;
1099
1100         $self->ConvertObjectFromPythonLevel($env, $mem_ctx, $cvar, $ctype, $ctype->{LEVELS}[0], $target, $fail);
1101 }
1102
1103 sub ConvertScalarToPython($$$)
1104 {
1105         my ($self, $ctypename, $cvar) = @_;
1106
1107         die("expected string for $cvar, not $ctypename") if (ref($ctypename) eq "HASH");
1108
1109         $ctypename = expandAlias($ctypename);
1110
1111         if ($ctypename =~ /^(u?int64|hyper|dlong|udlong|udlongr|NTTIME_hyper|NTTIME|NTTIME_1sec)$/) {
1112                 return "PyLong_FromLongLong($cvar)";
1113         }
1114
1115         if ($ctypename =~ /^(char|u?int[0-9]*|time_t|uid_t|gid_t)$/) {
1116                 return "PyInt_FromLong($cvar)";
1117         }
1118
1119         if ($ctypename eq "DATA_BLOB") {
1120                 return "PyString_FromStringAndSize((char *)($cvar).data, ($cvar).length)";
1121         }
1122
1123         if ($ctypename eq "NTSTATUS") {
1124                 return "PyErr_FromNTSTATUS($cvar)";
1125         }
1126
1127         if ($ctypename eq "WERROR") {
1128                 return "PyErr_FromWERROR($cvar)";
1129         }
1130
1131         if (($ctypename eq "string" or $ctypename eq "nbt_string" or $ctypename eq "nbt_name" or $ctypename eq "wrepl_nbt_name")) {
1132                 return "PyString_FromStringOrNULL($cvar)";
1133         }
1134
1135         if (($ctypename eq "dns_string" or $ctypename eq "dns_name")) {
1136                 return "PyString_FromStringOrNULL($cvar)";
1137         }
1138
1139         # Not yet supported
1140         if ($ctypename eq "string_array") { return "PyCObject_FromTallocPtr($cvar)"; }
1141         if ($ctypename eq "ipv4address") { return "PyString_FromStringOrNULL($cvar)"; }
1142         if ($ctypename eq "ipv6address") { return "PyString_FromStringOrNULL($cvar)"; }
1143         if ($ctypename eq "dnsp_name") { return "PyString_FromStringOrNULL($cvar)"; }
1144         if ($ctypename eq "dnsp_string") { return "PyString_FromStringOrNULL($cvar)"; }
1145         if ($ctypename eq "pointer") {
1146                 return "PyCObject_FromTallocPtr($cvar)";
1147         }
1148
1149         die("Unknown scalar type $ctypename");
1150 }
1151
1152 sub ConvertObjectToPythonData($$$$$;$)
1153 {
1154         my ($self, $mem_ctx, $ctype, $cvar, $location) = @_;
1155
1156         die("undef type for $cvar") unless(defined($ctype));
1157
1158         $ctype = resolveType($ctype);
1159
1160         my $actual_ctype = $ctype;
1161         if ($actual_ctype->{TYPE} eq "TYPEDEF") {
1162                 $actual_ctype = $actual_ctype->{DATA};
1163         } 
1164         
1165         if ($actual_ctype->{TYPE} eq "ENUM") {
1166                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::enum_type_fn($actual_ctype), $cvar);
1167         } elsif ($actual_ctype->{TYPE} eq "BITMAP") {
1168                 return $self->ConvertScalarToPython(Parse::Pidl::Typelist::bitmap_type_fn($actual_ctype), $cvar);
1169         } elsif ($actual_ctype->{TYPE} eq "SCALAR") {
1170                 return $self->ConvertScalarToPython($actual_ctype->{NAME}, $cvar);
1171         } elsif ($actual_ctype->{TYPE} eq "UNION") {
1172                 fatal($ctype, "union without discriminant: " . mapTypeName($ctype) . ": $cvar");
1173         } elsif ($actual_ctype->{TYPE} eq "STRUCT" or $actual_ctype->{TYPE} eq "INTERFACE") {
1174                 my $ctype_name = $self->use_type_variable($ctype);
1175                 unless (defined($ctype_name)) {
1176                         error($location, "Unable to determine origin of type `" . mapTypeName($ctype) . "'");
1177                         return "NULL"; # FIXME!
1178                 }
1179                 return "py_talloc_reference_ex($ctype_name, $mem_ctx, $cvar)";
1180         }
1181
1182         fatal($location, "unknown type $actual_ctype->{TYPE} for ".mapTypeName($ctype) . ": $cvar");
1183 }
1184
1185 sub fail_on_null($$$)
1186 {
1187         my ($self, $var, $fail) = @_;
1188         $self->pidl("if ($var == NULL) {");
1189         $self->indent;
1190         $self->pidl($fail);
1191         $self->deindent;
1192         $self->pidl("}");
1193 }
1194
1195 sub ConvertObjectToPythonLevel($$$$$$)
1196 {
1197         my ($self, $mem_ctx, $env, $e, $l, $var_name, $py_var, $fail) = @_;
1198         my $nl = GetNextLevel($e, $l);
1199         if ($nl and $nl->{TYPE} eq "SUBCONTEXT") {
1200                 $nl = GetNextLevel($e, $nl);
1201         }
1202         my $pl = GetPrevLevel($e, $l);
1203         if ($pl and $pl->{TYPE} eq "SUBCONTEXT") {
1204                 $pl = GetPrevLevel($e, $pl);
1205         }
1206
1207         if ($l->{TYPE} eq "POINTER") {
1208                 if ($l->{POINTER_TYPE} ne "ref") {
1209                         $self->pidl("if ($var_name == NULL) {");
1210                         $self->indent;
1211                         $self->pidl("$py_var = Py_None;");
1212                         $self->pidl("Py_INCREF($py_var);");
1213                         $self->deindent;
1214                         $self->pidl("} else {");
1215                         $self->indent;
1216                 }
1217                 my $var_name2 = $var_name;
1218                 unless ($nl->{TYPE} eq "DATA" and Parse::Pidl::Typelist::scalar_is_reference($nl->{DATA_TYPE})) {
1219                         $var_name2 = get_value_of($var_name);
1220                 }
1221                 $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name2, $py_var, $fail);
1222                 if ($l->{POINTER_TYPE} ne "ref") {
1223                         $self->deindent;
1224                         $self->pidl("}");
1225                 }
1226         } elsif ($l->{TYPE} eq "ARRAY") {
1227                 if ($pl && $pl->{TYPE} eq "POINTER") {
1228                         $var_name = get_pointer_to($var_name);
1229                 }
1230
1231                 if (is_charset_array($e, $l)) {
1232                         # FIXME: Use Unix charset setting rather than utf-8
1233                         $self->pidl("if ($var_name == NULL) {");
1234                         $self->indent;
1235                         $self->pidl("$py_var = Py_None;");
1236                         $self->pidl("Py_INCREF($py_var);");
1237                         $self->deindent;
1238                         $self->pidl("} else {");
1239                         $self->indent;
1240                         $self->pidl("$py_var = PyUnicode_Decode($var_name, strlen($var_name), \"utf-8\", \"ignore\");");
1241                         $self->deindent;
1242                         $self->pidl("}");
1243                 } else {
1244                         die("No SIZE_IS for array $var_name") unless (defined($l->{SIZE_IS}));
1245                         my $length = $l->{SIZE_IS};
1246                         if (defined($l->{LENGTH_IS})) {
1247                                 $length = $l->{LENGTH_IS};
1248                         }
1249
1250                         $length = ParseExpr($length, $env, $e);
1251                         $self->pidl("$py_var = PyList_New($length);");
1252                         $self->fail_on_null($py_var, $fail);
1253                         $self->pidl("{");
1254                         $self->indent;
1255                         my $counter = "$e->{NAME}_cntr_$l->{LEVEL_INDEX}";
1256                         $self->pidl("int $counter;");
1257                         $self->pidl("for ($counter = 0; $counter < $length; $counter++) {");
1258                         $self->indent;
1259                         my $member_var = "py_$e->{NAME}_$l->{LEVEL_INDEX}";
1260                         $self->pidl("PyObject *$member_var;");
1261                         $self->ConvertObjectToPythonLevel($var_name, $env, $e, $nl, $var_name."[$counter]", $member_var, $fail);
1262                         $self->pidl("PyList_SetItem($py_var, $counter, $member_var);");
1263                         $self->deindent;
1264                         $self->pidl("}");
1265                         $self->deindent;
1266                         $self->pidl("}");
1267                 }
1268         } elsif ($l->{TYPE} eq "SWITCH") {
1269                 $var_name = get_pointer_to($var_name);
1270                 my $switch = ParseExpr($l->{SWITCH_IS}, $env, $e);
1271                 $self->pidl("$py_var = py_import_" . $nl->{DATA_TYPE} . "($mem_ctx, $switch, $var_name);");
1272                 $self->fail_on_null($py_var, $fail);
1273
1274         } elsif ($l->{TYPE} eq "DATA") {
1275                 if (not Parse::Pidl::Typelist::is_scalar($l->{DATA_TYPE})) {
1276                         $var_name = get_pointer_to($var_name);
1277                 }
1278                 my $conv = $self->ConvertObjectToPythonData($mem_ctx, $l->{DATA_TYPE}, $var_name, $e->{ORIGINAL});
1279                 $self->pidl("$py_var = $conv;");
1280         } elsif ($l->{TYPE} eq "SUBCONTEXT") {
1281                 $self->ConvertObjectToPythonLevel($mem_ctx, $env, $e, $nl, $var_name, $py_var, $fail);
1282         } else {
1283                 fatal($e->{ORIGINAL}, "Unknown level type $l->{TYPE} $var_name");
1284         }
1285 }
1286
1287 sub ConvertObjectToPython($$$$$$)
1288 {
1289         my ($self, $mem_ctx, $env, $ctype, $cvar, $py_var, $fail) = @_;
1290
1291         $self->ConvertObjectToPythonLevel($mem_ctx, $env, $ctype, $ctype->{LEVELS}[0], $cvar, $py_var, $fail);
1292 }
1293
1294 sub Parse($$$$$)
1295 {
1296     my($self,$basename,$ndr,$ndr_hdr,$hdr) = @_;
1297
1298         $self->{BASENAME} = $basename;
1299
1300     $self->pidl_hdr("
1301 /* Python wrapper functions auto-generated by pidl */
1302 #include <Python.h>
1303 #include \"includes.h\"
1304 #include <pytalloc.h>
1305 #include \"librpc/rpc/pyrpc.h\"
1306 #include \"librpc/rpc/pyrpc_util.h\"
1307 #include \"$hdr\"
1308 #include \"$ndr_hdr\"
1309
1310 ");
1311
1312         foreach my $x (@$ndr) {
1313                 ($x->{TYPE} eq "IMPORT") && $self->Import(@{$x->{PATHS}});
1314             ($x->{TYPE} eq "INTERFACE") && $self->Interface($x, $basename);
1315         }
1316         
1317         $self->pidl("static PyMethodDef $basename\_methods[] = {");
1318         $self->indent;
1319         foreach (@{$self->{module_methods}}) {
1320                 my ($fn_name, $pyfn_name, $flags, $doc) = @$_;
1321                 $self->pidl("{ \"$fn_name\", (PyCFunction)$pyfn_name, $flags, $doc },");
1322         }
1323
1324         $self->pidl("{ NULL, NULL, 0, NULL }");
1325         $self->deindent;
1326         $self->pidl("};");
1327
1328         $self->pidl("");
1329
1330         $self->pidl_hdr("void init$basename(void);");
1331         $self->pidl("void init$basename(void)");
1332         $self->pidl("{");
1333         $self->indent;
1334         $self->pidl("PyObject *m;");
1335         foreach (keys %{$self->{module_imports}}) {
1336                 $self->pidl("PyObject *$_;");
1337         }
1338         $self->pidl("");
1339
1340         foreach (keys %{$self->{module_imports}}) {
1341                 my $var_name = $_;
1342                 my $module_path = $self->{module_imports}->{$var_name};
1343                 $self->pidl("$var_name = PyImport_ImportModule(\"$module_path\");");
1344                 $self->pidl("if ($var_name == NULL)");
1345                 $self->pidl("\treturn;");
1346                 $self->pidl("");
1347         }
1348
1349         foreach (keys %{$self->{type_imports}}) {
1350                 my $type_var = "$_\_Type";
1351                 my $module_path = $self->{type_imports}->{$_};
1352                 $self->pidl_hdr("static PyTypeObject *$type_var;\n");
1353                 my $pretty_name = PrettifyTypeName($_, $module_path);
1354                 my $module_var = "dep_$module_path";
1355                 $module_var =~ s/\./_/g;
1356                 $self->pidl("$type_var = (PyTypeObject *)PyObject_GetAttrString($module_var, \"$pretty_name\");");
1357                 $self->pidl("if ($type_var == NULL)");
1358                 $self->pidl("\treturn;");
1359                 $self->pidl("");
1360         }
1361
1362         $self->pidl($_) foreach (@{$self->{prereadycode}});
1363
1364         foreach (@{$self->{ready_types}}) {
1365                 $self->pidl("if (PyType_Ready($_) < 0)");
1366                 $self->pidl("\treturn;");
1367         }
1368
1369         $self->pidl($_) foreach (@{$self->{postreadycode}});
1370
1371         foreach (@{$self->{patch_type_calls}}) {
1372                 my ($typename, $cvar) = @$_;
1373                 $self->pidl("#ifdef PY_".uc($typename)."_PATCH");
1374                 $self->pidl("PY_".uc($typename)."_PATCH($cvar);");
1375                 $self->pidl("#endif");
1376         }
1377
1378         $self->pidl("");
1379
1380         $self->pidl("m = Py_InitModule3(\"$basename\", $basename\_methods, \"$basename DCE/RPC\");");
1381         $self->pidl("if (m == NULL)");
1382         $self->pidl("\treturn;");
1383         $self->pidl("");
1384         foreach my $name (keys %{$self->{constants}}) {
1385                 my $py_obj;
1386                 my ($ctype, $cvar) = @{$self->{constants}->{$name}};
1387                 if ($cvar =~ /^[0-9]+$/ or $cvar =~ /^0x[0-9a-fA-F]+$/) {
1388                         $py_obj = "PyInt_FromLong($cvar)";
1389                 } elsif ($cvar =~ /^".*"$/) {
1390                         $py_obj = "PyString_FromString($cvar)";
1391                 } else {
1392                         $py_obj = $self->ConvertObjectToPythonData("NULL", expandAlias($ctype), $cvar, undef);
1393                 }
1394
1395                 $self->pidl("PyModule_AddObject(m, \"$name\", $py_obj);");
1396         }
1397
1398         foreach (@{$self->{module_objects}}) {
1399                 my ($object_name, $c_name) = @$_;
1400                 $self->pidl("Py_INCREF($c_name);");
1401                 $self->pidl("PyModule_AddObject(m, \"$object_name\", $c_name);");
1402         }
1403
1404         $self->pidl("#ifdef PY_MOD_".uc($basename)."_PATCH");
1405         $self->pidl("PY_MOD_".uc($basename)."_PATCH(m);");
1406         $self->pidl("#endif");
1407
1408         $self->pidl("");
1409         $self->deindent;
1410         $self->pidl("}");
1411     return ($self->{res_hdr} . $self->{res});
1412 }
1413
1414 1;