python: Port the samba.net module to Python 3
[nivanova/samba-autobuild/.git] / source4 / libnet / py_net.c
1 /*
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4
5    Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2008-2010
6    Copyright (C) Kamen Mazdrashki <kamen.mazdrashki@postpath.com> 2009
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include <Python.h>
23 #include "python/py3compat.h"
24 #include "includes.h"
25 #include <pyldb.h>
26 #include <pytalloc.h>
27 #include "libnet.h"
28 #include "auth/credentials/pycredentials.h"
29 #include "libcli/security/security.h"
30 #include "lib/events/events.h"
31 #include "param/pyparam.h"
32 #include "auth/gensec/gensec.h"
33 #include "librpc/rpc/pyrpc_util.h"
34 #include "libcli/resolve/resolve.h"
35 #include "libcli/finddc.h"
36 #include "dsdb/samdb/samdb.h"
37 #include "py_net.h"
38 #include "librpc/rpc/pyrpc_util.h"
39
40 static void PyErr_SetDsExtendedError(enum drsuapi_DsExtendedError ext_err, const char *error_description)
41 {
42         PyObject *error = PyObject_GetAttrString(PyImport_ImportModule("samba"),
43                                                  "DsExtendedError");
44         if (error_description == NULL) {
45                 switch (ext_err) {
46                         /* Copied out of ndr_drsuapi.c:ndr_print_drsuapi_DsExtendedError() */
47                         case DRSUAPI_EXOP_ERR_NONE:
48                                 error_description = "DRSUAPI_EXOP_ERR_NONE";
49                                 break;
50                         case DRSUAPI_EXOP_ERR_SUCCESS:
51                                 error_description = "DRSUAPI_EXOP_ERR_SUCCESS";
52                                 break;
53                         case DRSUAPI_EXOP_ERR_UNKNOWN_OP:
54                                 error_description = "DRSUAPI_EXOP_ERR_UNKNOWN_OP";
55                                 break;
56                         case DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER:
57                                 error_description = "DRSUAPI_EXOP_ERR_FSMO_NOT_OWNER";
58                                 break;
59                         case DRSUAPI_EXOP_ERR_UPDATE_ERR:
60                                 error_description = "DRSUAPI_EXOP_ERR_UPDATE_ERR";
61                                 break;
62                         case DRSUAPI_EXOP_ERR_EXCEPTION:
63                                 error_description = "DRSUAPI_EXOP_ERR_EXCEPTION";
64                                 break;
65                         case DRSUAPI_EXOP_ERR_UNKNOWN_CALLER:
66                                 error_description = "DRSUAPI_EXOP_ERR_UNKNOWN_CALLER";
67                                 break;
68                         case DRSUAPI_EXOP_ERR_RID_ALLOC:
69                                 error_description = "DRSUAPI_EXOP_ERR_RID_ALLOC";
70                                 break;
71                         case DRSUAPI_EXOP_ERR_FSMO_OWNER_DELETED:
72                                 error_description = "DRSUAPI_EXOP_ERR_FSMO_OWNER_DELETED";
73                                 break;
74                         case DRSUAPI_EXOP_ERR_FMSO_PENDING_OP:
75                                 error_description = "DRSUAPI_EXOP_ERR_FMSO_PENDING_OP";
76                                 break;
77                         case DRSUAPI_EXOP_ERR_MISMATCH:
78                                 error_description = "DRSUAPI_EXOP_ERR_MISMATCH";
79                                 break;
80                         case DRSUAPI_EXOP_ERR_COULDNT_CONTACT:
81                                 error_description = "DRSUAPI_EXOP_ERR_COULDNT_CONTACT";
82                                 break;
83                         case DRSUAPI_EXOP_ERR_FSMO_REFUSING_ROLES:
84                                 error_description = "DRSUAPI_EXOP_ERR_FSMO_REFUSING_ROLES";
85                                 break;
86                         case DRSUAPI_EXOP_ERR_DIR_ERROR:
87                                 error_description = "DRSUAPI_EXOP_ERR_DIR_ERROR";
88                                 break;
89                         case DRSUAPI_EXOP_ERR_FSMO_MISSING_SETTINGS:
90                                 error_description = "DRSUAPI_EXOP_ERR_FSMO_MISSING_SETTINGS";
91                                 break;
92                         case DRSUAPI_EXOP_ERR_ACCESS_DENIED:
93                                 error_description = "DRSUAPI_EXOP_ERR_ACCESS_DENIED";
94                                 break;
95                         case DRSUAPI_EXOP_ERR_PARAM_ERROR:
96                                 error_description = "DRSUAPI_EXOP_ERR_PARAM_ERROR";
97                                 break;
98                 }
99         }
100         PyErr_SetObject(error,
101                         Py_BuildValue(discard_const_p(char, "(i,s)"),
102                                       ext_err,
103                                       error_description));
104 }
105
106 static PyObject *py_net_join_member(py_net_Object *self, PyObject *args, PyObject *kwargs)
107 {
108         struct libnet_Join_member r;
109         int _level = 0;
110         NTSTATUS status;
111         PyObject *result;
112         TALLOC_CTX *mem_ctx;
113         const char *kwnames[] = { "domain_name", "netbios_name", "level", "machinepass", NULL };
114
115         ZERO_STRUCT(r);
116
117         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ssi|z:Join", discard_const_p(char *, kwnames),
118                                          &r.in.domain_name, &r.in.netbios_name, 
119                                          &_level,
120                                          &r.in.account_pass)) {
121                 return NULL;
122         }
123         r.in.level = _level;
124
125         mem_ctx = talloc_new(self->mem_ctx);
126         if (mem_ctx == NULL) {
127                 PyErr_NoMemory();
128                 return NULL;
129         }
130
131         status = libnet_Join_member(self->libnet_ctx, mem_ctx, &r);
132         if (NT_STATUS_IS_ERR(status)) {
133                 PyErr_SetNTSTATUS_and_string(status,
134                                              r.out.error_string
135                                              ? r.out.error_string
136                                              : nt_errstr(status));
137                 talloc_free(mem_ctx);
138                 return NULL;
139         }
140
141         result = Py_BuildValue("sss", r.out.join_password,
142                                dom_sid_string(mem_ctx, r.out.domain_sid),
143                                r.out.domain_name);
144
145         talloc_free(mem_ctx);
146
147         return result;
148 }
149
150 static const char py_net_join_member_doc[] = "join_member(domain_name, netbios_name, level) -> (join_password, domain_sid, domain_name)\n\n" \
151 "Join the domain with the specified name.";
152
153 static PyObject *py_net_change_password(py_net_Object *self, PyObject *args, PyObject *kwargs)
154 {
155         union libnet_ChangePassword r;
156         NTSTATUS status;
157         TALLOC_CTX *mem_ctx;
158         struct tevent_context *ev;
159         const char *kwnames[] = { "newpassword", NULL };
160
161         ZERO_STRUCT(r);
162
163         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s:change_password",
164                                         discard_const_p(char *, kwnames),
165                                         &r.generic.in.newpassword)) {
166                 return NULL;
167         }
168
169         r.generic.level = LIBNET_CHANGE_PASSWORD_GENERIC;
170         r.generic.in.account_name = cli_credentials_get_username(self->libnet_ctx->cred);
171         r.generic.in.domain_name = cli_credentials_get_domain(self->libnet_ctx->cred);
172         r.generic.in.oldpassword = cli_credentials_get_password(self->libnet_ctx->cred);
173
174         /* FIXME: we really need to get a context from the caller or we may end
175          * up with 2 event contexts */
176         ev = s4_event_context_init(NULL);
177
178         mem_ctx = talloc_new(ev);
179         if (mem_ctx == NULL) {
180                 PyErr_NoMemory();
181                 return NULL;
182         }
183
184         status = libnet_ChangePassword(self->libnet_ctx, mem_ctx, &r);
185         if (NT_STATUS_IS_ERR(status)) {
186                 PyErr_SetNTSTATUS_and_string(status,
187                                              r.generic.out.error_string
188                                              ? r.generic.out.error_string
189                                              : nt_errstr(status));
190                 talloc_free(mem_ctx);
191                 return NULL;
192         }
193
194         talloc_free(mem_ctx);
195
196         Py_RETURN_NONE;
197 }
198
199 static const char py_net_change_password_doc[] = "change_password(newpassword) -> True\n\n" \
200 "Change password for a user. You must supply credential with enough rights to do this.\n\n" \
201 "Sample usage is:\n" \
202 "net.change_password(newpassword=<new_password>)\n";
203
204
205 static PyObject *py_net_set_password(py_net_Object *self, PyObject *args, PyObject *kwargs)
206 {
207         union libnet_SetPassword r;
208         NTSTATUS status;
209         TALLOC_CTX *mem_ctx;
210         struct tevent_context *ev;
211         const char *kwnames[] = { "account_name", "domain_name", "newpassword", NULL };
212
213         ZERO_STRUCT(r);
214
215         r.generic.level = LIBNET_SET_PASSWORD_GENERIC;
216
217         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "sss:set_password",
218                                         discard_const_p(char *, kwnames),
219                                          &r.generic.in.account_name,
220                                          &r.generic.in.domain_name,
221                                          &r.generic.in.newpassword)) {
222                 return NULL;
223         }
224
225         /* FIXME: we really need to get a context from the caller or we may end
226          * up with 2 event contexts */
227         ev = s4_event_context_init(NULL);
228
229         mem_ctx = talloc_new(ev);
230         if (mem_ctx == NULL) {
231                 PyErr_NoMemory();
232                 return NULL;
233         }
234
235         status = libnet_SetPassword(self->libnet_ctx, mem_ctx, &r);
236         if (NT_STATUS_IS_ERR(status)) {
237                 PyErr_SetNTSTATUS_and_string(status,
238                                              r.generic.out.error_string
239                                              ? r.generic.out.error_string
240                                              : nt_errstr(status));
241                 talloc_free(mem_ctx);
242                 return NULL;
243         }
244
245         talloc_free(mem_ctx);
246
247         Py_RETURN_NONE;
248 }
249
250 static const char py_net_set_password_doc[] = "set_password(account_name, domain_name, newpassword) -> True\n\n" \
251 "Set password for a user. You must supply credential with enough rights to do this.\n\n" \
252 "Sample usage is:\n" \
253 "net.set_password(account_name=account_name, domain_name=domain_name, newpassword=new_pass)\n";
254
255
256 static PyObject *py_net_time(py_net_Object *self, PyObject *args, PyObject *kwargs)
257 {
258         const char *kwnames[] = { "server_name", NULL };
259         union libnet_RemoteTOD r;
260         NTSTATUS status;
261         TALLOC_CTX *mem_ctx;
262         char timestr[64];
263         PyObject *ret;
264         struct tm *tm;
265
266         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s",
267                 discard_const_p(char *, kwnames), &r.generic.in.server_name))
268                 return NULL;
269
270         r.generic.level                 = LIBNET_REMOTE_TOD_GENERIC;
271
272         mem_ctx = talloc_new(NULL);
273         if (mem_ctx == NULL) {
274                 PyErr_NoMemory();
275                 return NULL;
276         }
277
278         status = libnet_RemoteTOD(self->libnet_ctx, mem_ctx, &r);
279         if (!NT_STATUS_IS_OK(status)) {
280                 PyErr_SetNTSTATUS_and_string(status,
281                                              r.generic.out.error_string
282                                              ? r.generic.out.error_string
283                                              : nt_errstr(status));
284                 talloc_free(mem_ctx);
285                 return NULL;
286         }
287
288         ZERO_STRUCT(timestr);
289         tm = localtime(&r.generic.out.time);
290         strftime(timestr, sizeof(timestr)-1, "%c %Z",tm);
291         
292         ret = PyStr_FromString(timestr);
293
294         talloc_free(mem_ctx);
295
296         return ret;
297 }
298
299 static const char py_net_time_doc[] = "time(server_name) -> timestr\n"
300 "Retrieve the remote time on a server";
301
302 static PyObject *py_net_user_create(py_net_Object *self, PyObject *args, PyObject *kwargs)
303 {
304         const char *kwnames[] = { "username", NULL };
305         NTSTATUS status;
306         TALLOC_CTX *mem_ctx;
307         struct libnet_CreateUser r;
308
309         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", discard_const_p(char *, kwnames), 
310                                                                          &r.in.user_name))
311                 return NULL;
312
313         r.in.domain_name = cli_credentials_get_domain(self->libnet_ctx->cred);
314
315         mem_ctx = talloc_new(NULL);
316         if (mem_ctx == NULL) {
317                 PyErr_NoMemory();
318                 return NULL;
319         }
320
321         status = libnet_CreateUser(self->libnet_ctx, mem_ctx, &r);
322         if (!NT_STATUS_IS_OK(status)) {
323                 PyErr_SetNTSTATUS_and_string(status,
324                                              r.out.error_string
325                                              ? r.out.error_string
326                                              : nt_errstr(status));
327                 talloc_free(mem_ctx);
328                 return NULL;
329         }
330
331         talloc_free(mem_ctx);
332         
333         Py_RETURN_NONE;
334 }
335
336 static const char py_net_create_user_doc[] = "create_user(username)\n"
337 "Create a new user.";
338
339 static PyObject *py_net_user_delete(py_net_Object *self, PyObject *args, PyObject *kwargs)
340 {
341         const char *kwnames[] = { "username", NULL };
342         NTSTATUS status;
343         TALLOC_CTX *mem_ctx;
344         struct libnet_DeleteUser r;
345
346         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s", discard_const_p(char *, kwnames), 
347                                                                          &r.in.user_name))
348                 return NULL;
349
350         r.in.domain_name = cli_credentials_get_domain(self->libnet_ctx->cred);
351
352         mem_ctx = talloc_new(NULL);
353         if (mem_ctx == NULL) {
354                 PyErr_NoMemory();
355                 return NULL;
356         }
357
358         status = libnet_DeleteUser(self->libnet_ctx, mem_ctx, &r);
359         if (!NT_STATUS_IS_OK(status)) {
360                 PyErr_SetNTSTATUS_and_string(status,
361                                            r.out.error_string
362                                           ? r.out.error_string
363                                           : nt_errstr(status));
364                 talloc_free(mem_ctx);
365                 return NULL;
366         }
367
368         talloc_free(mem_ctx);
369         
370         Py_RETURN_NONE;
371 }
372
373 static const char py_net_delete_user_doc[] = "delete_user(username)\n"
374 "Delete a user.";
375
376 struct replicate_state {
377         void *vampire_state;
378         dcerpc_InterfaceObject *drs_pipe;
379         struct libnet_BecomeDC_StoreChunk chunk;
380         DATA_BLOB gensec_skey;
381         struct libnet_BecomeDC_Partition partition;
382         struct libnet_BecomeDC_Forest forest;
383         struct libnet_BecomeDC_DestDSA dest_dsa;
384 };
385
386 /*
387   setup for replicate_chunk() calls
388  */
389 static PyObject *py_net_replicate_init(py_net_Object *self, PyObject *args, PyObject *kwargs)
390 {
391         const char *kwnames[] = { "samdb", "lp", "drspipe", "invocation_id", NULL };
392         PyObject *py_ldb, *py_lp, *py_drspipe, *py_invocation_id;
393         struct ldb_context *samdb;
394         struct loadparm_context *lp;
395         struct replicate_state *s;
396         NTSTATUS status;
397
398         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOOO",
399                                          discard_const_p(char *, kwnames),
400                                          &py_ldb, &py_lp, &py_drspipe,
401                                          &py_invocation_id)) {
402                 return NULL;
403         }
404
405         s = talloc_zero(NULL, struct replicate_state);
406         if (!s) return NULL;
407
408         lp = lpcfg_from_py_object(s, py_lp);
409         if (lp == NULL) {
410                 PyErr_SetString(PyExc_TypeError, "Expected lp object");
411                 talloc_free(s);
412                 return NULL;
413         }
414
415         samdb = pyldb_Ldb_AsLdbContext(py_ldb);
416         if (samdb == NULL) {
417                 PyErr_SetString(PyExc_TypeError, "Expected ldb object");
418                 talloc_free(s);
419                 return NULL;
420         }
421         if (!py_check_dcerpc_type(py_invocation_id, "samba.dcerpc.misc", "GUID")) {
422                 
423                 talloc_free(s);
424                 return NULL;
425         }
426         s->dest_dsa.invocation_id = *pytalloc_get_type(py_invocation_id, struct GUID);
427
428         s->drs_pipe = (dcerpc_InterfaceObject *)(py_drspipe);
429
430         s->vampire_state = libnet_vampire_replicate_init(s, samdb, lp);
431         if (s->vampire_state == NULL) {
432                 PyErr_SetString(PyExc_TypeError, "Failed to initialise vampire_state");
433                 talloc_free(s);
434                 return NULL;
435         }
436
437         status = gensec_session_key(s->drs_pipe->pipe->conn->security_state.generic_state,
438                                     s,
439                                     &s->gensec_skey);
440         if (!NT_STATUS_IS_OK(status)) {
441                 char *error_string = talloc_asprintf(s,
442                                                      "Unable to get session key from drspipe: %s",
443                                                      nt_errstr(status));
444                 PyErr_SetNTSTATUS_and_string(status, error_string);
445                 talloc_free(s);
446                 return NULL;
447         }
448
449         s->forest.dns_name = samdb_dn_to_dns_domain(s, ldb_get_root_basedn(samdb));
450         s->forest.root_dn_str = ldb_dn_get_linearized(ldb_get_root_basedn(samdb));
451         s->forest.config_dn_str = ldb_dn_get_linearized(ldb_get_config_basedn(samdb));
452         s->forest.schema_dn_str = ldb_dn_get_linearized(ldb_get_schema_basedn(samdb));
453
454         s->chunk.gensec_skey = &s->gensec_skey;
455         s->chunk.partition = &s->partition;
456         s->chunk.forest = &s->forest;
457         s->chunk.dest_dsa = &s->dest_dsa;
458
459         return pytalloc_GenericObject_steal(s);
460 }
461
462
463 /*
464   process one replication chunk
465  */
466 static PyObject *py_net_replicate_chunk(py_net_Object *self, PyObject *args, PyObject *kwargs)
467 {
468         const char *kwnames[] = { "state", "level", "ctr",
469                                   "schema", "req_level", "req",
470                                   NULL };
471         PyObject *py_state, *py_ctr, *py_schema = Py_None, *py_req = Py_None;
472         struct replicate_state *s;
473         unsigned level;
474         unsigned req_level = 0;
475         WERROR (*chunk_handler)(void *private_data, const struct libnet_BecomeDC_StoreChunk *c);
476         WERROR werr;
477         enum drsuapi_DsExtendedError extended_ret = DRSUAPI_EXOP_ERR_NONE;
478         enum drsuapi_DsExtendedOperation exop = DRSUAPI_EXOP_NONE;
479
480         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OIO|OIO",
481                                          discard_const_p(char *, kwnames),
482                                          &py_state, &level, &py_ctr,
483                                          &py_schema, &req_level, &py_req)) {
484                 return NULL;
485         }
486
487         s = pytalloc_get_type(py_state, struct replicate_state);
488         if (!s) {
489                 return NULL;
490         }
491
492         switch (level) {
493         case 1:
494                 if (!py_check_dcerpc_type(py_ctr, "samba.dcerpc.drsuapi", "DsGetNCChangesCtr1")) {
495                         return NULL;
496                 }
497                 s->chunk.ctr1                         = pytalloc_get_ptr(py_ctr);
498                 if (s->chunk.ctr1->naming_context != NULL) {
499                         s->partition.nc = *s->chunk.ctr1->naming_context;
500                 }
501                 extended_ret = s->chunk.ctr1->extended_ret;
502                 s->partition.more_data                = s->chunk.ctr1->more_data;
503                 s->partition.source_dsa_guid          = s->chunk.ctr1->source_dsa_guid;
504                 s->partition.source_dsa_invocation_id = s->chunk.ctr1->source_dsa_invocation_id;
505                 s->partition.highwatermark            = s->chunk.ctr1->new_highwatermark;
506                 break;
507         case 6:
508                 if (!py_check_dcerpc_type(py_ctr, "samba.dcerpc.drsuapi", "DsGetNCChangesCtr6")) {
509                         return NULL;
510                 }
511                 s->chunk.ctr6                         = pytalloc_get_ptr(py_ctr);
512                 if (s->chunk.ctr6->naming_context != NULL) {
513                         s->partition.nc = *s->chunk.ctr6->naming_context;
514                 }
515                 extended_ret = s->chunk.ctr6->extended_ret;
516                 s->partition.more_data                = s->chunk.ctr6->more_data;
517                 s->partition.source_dsa_guid          = s->chunk.ctr6->source_dsa_guid;
518                 s->partition.source_dsa_invocation_id = s->chunk.ctr6->source_dsa_invocation_id;
519                 s->partition.highwatermark            = s->chunk.ctr6->new_highwatermark;
520                 break;
521         default:
522                 PyErr_Format(PyExc_TypeError, "Bad level %u in replicate_chunk", level);
523                 return NULL;
524         }
525
526         s->chunk.req5 = NULL;
527         s->chunk.req8 = NULL;
528         s->chunk.req10 = NULL;
529         if (py_req) {
530                 switch (req_level) {
531                 case 0:
532                         break;
533                 case 5:
534                         if (!py_check_dcerpc_type(py_req, "samba.dcerpc.drsuapi", "DsGetNCChangesRequest5")) {
535                                 return NULL;
536                         }
537
538                         s->chunk.req5 = pytalloc_get_ptr(py_req);
539                         exop = s->chunk.req5->extended_op;
540                         break;
541                 case 8:
542                         if (!py_check_dcerpc_type(py_req, "samba.dcerpc.drsuapi", "DsGetNCChangesRequest8")) {
543                                 return NULL;
544                         }
545
546                         s->chunk.req8 = pytalloc_get_ptr(py_req);
547                         exop = s->chunk.req8->extended_op;
548                         break;
549                 case 10:
550                         if (!py_check_dcerpc_type(py_req, "samba.dcerpc.drsuapi", "DsGetNCChangesRequest10")) {
551                                 return NULL;
552                         }
553
554                         s->chunk.req10 = pytalloc_get_ptr(py_req);
555                         exop = s->chunk.req10->extended_op;
556                         break;
557                 default:
558                         PyErr_Format(PyExc_TypeError, "Bad req_level %u in replicate_chunk", req_level);
559                         return NULL;
560                 }
561         }
562
563         if (exop != DRSUAPI_EXOP_NONE && extended_ret != DRSUAPI_EXOP_ERR_SUCCESS) {
564                 PyErr_SetDsExtendedError(extended_ret, NULL);
565                 return NULL;
566         }
567
568         s->chunk.req_level = req_level;
569
570         chunk_handler = libnet_vampire_cb_store_chunk;
571         if (py_schema) {
572                 if (!PyBool_Check(py_schema)) {
573                         PyErr_SetString(PyExc_TypeError, "Expected boolean schema");
574                         return NULL;
575                 }
576                 if (py_schema == Py_True) {
577                         chunk_handler = libnet_vampire_cb_schema_chunk;
578                 }
579         }
580
581         s->chunk.ctr_level = level;
582
583         werr = chunk_handler(s->vampire_state, &s->chunk);
584         if (!W_ERROR_IS_OK(werr)) {
585                 char *error_string
586                         = talloc_asprintf(NULL,
587                                           "Failed to process 'chunk' of DRS replicated objects: %s",
588                                           win_errstr(werr));
589                 PyErr_SetWERROR_and_string(werr, error_string);
590                 TALLOC_FREE(error_string);
591                 return NULL;
592         }
593
594         Py_RETURN_NONE;
595 }
596
597
598 /*
599   find a DC given a domain name and server type
600  */
601 static PyObject *py_net_finddc(py_net_Object *self, PyObject *args, PyObject *kwargs)
602 {
603         const char *domain = NULL, *address = NULL;
604         unsigned server_type;
605         NTSTATUS status;
606         struct finddcs *io;
607         TALLOC_CTX *mem_ctx;
608         PyObject *ret;
609         const char * const kwnames[] = { "flags", "domain", "address", NULL };
610
611         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "I|zz",
612                                          discard_const_p(char *, kwnames),
613                                          &server_type, &domain, &address)) {
614                 return NULL;
615         }
616
617         mem_ctx = talloc_new(self->mem_ctx);
618
619         io = talloc_zero(mem_ctx, struct finddcs);
620         if (domain != NULL) {
621                 io->in.domain_name = domain;
622         }
623         if (address != NULL) {
624                 io->in.server_address = address;
625         }
626         io->in.minimum_dc_flags = server_type;
627
628         status = finddcs_cldap(io, io,
629                                lpcfg_resolve_context(self->libnet_ctx->lp_ctx), self->ev);
630         if (NT_STATUS_IS_ERR(status)) {
631                 PyErr_SetNTSTATUS(status);
632                 talloc_free(mem_ctx);
633                 return NULL;
634         }
635
636         ret = py_return_ndr_struct("samba.dcerpc.nbt", "NETLOGON_SAM_LOGON_RESPONSE_EX",
637                                    io, &io->out.netlogon.data.nt5_ex);
638         talloc_free(mem_ctx);
639
640         return ret;
641 }
642
643
644 static const char py_net_replicate_init_doc[] = "replicate_init(samdb, lp, drspipe)\n"
645                                          "Setup for replicate_chunk calls.";
646
647 static const char py_net_replicate_chunk_doc[] = "replicate_chunk(state, level, ctr, schema)\n"
648                                          "Process replication for one chunk";
649
650 static const char py_net_finddc_doc[] = "finddc(flags=server_type, domain=None, address=None)\n"
651                                          "Find a DC with the specified 'server_type' bits. The 'domain' and/or 'address' have to be used as additional search criteria. Returns the whole netlogon struct";
652
653 static PyMethodDef net_obj_methods[] = {
654         {"join_member", (PyCFunction)py_net_join_member, METH_VARARGS|METH_KEYWORDS, py_net_join_member_doc},
655         {"change_password", (PyCFunction)py_net_change_password, METH_VARARGS|METH_KEYWORDS, py_net_change_password_doc},
656         {"set_password", (PyCFunction)py_net_set_password, METH_VARARGS|METH_KEYWORDS, py_net_set_password_doc},
657         {"time", (PyCFunction)py_net_time, METH_VARARGS|METH_KEYWORDS, py_net_time_doc},
658         {"create_user", (PyCFunction)py_net_user_create, METH_VARARGS|METH_KEYWORDS, py_net_create_user_doc},
659         {"delete_user", (PyCFunction)py_net_user_delete, METH_VARARGS|METH_KEYWORDS, py_net_delete_user_doc},
660         {"replicate_init", (PyCFunction)py_net_replicate_init, METH_VARARGS|METH_KEYWORDS, py_net_replicate_init_doc},
661         {"replicate_chunk", (PyCFunction)py_net_replicate_chunk, METH_VARARGS|METH_KEYWORDS, py_net_replicate_chunk_doc},
662         {"finddc", (PyCFunction)py_net_finddc, METH_KEYWORDS, py_net_finddc_doc},
663         { NULL }
664 };
665
666 static void py_net_dealloc(py_net_Object *self)
667 {
668         talloc_free(self->mem_ctx);
669         PyObject_Del(self);
670 }
671
672 static PyObject *net_obj_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
673 {
674         PyObject *py_creds, *py_lp = Py_None;
675         const char *kwnames[] = { "creds", "lp", "server", NULL };
676         py_net_Object *ret;
677         struct loadparm_context *lp;
678         const char *server_address = NULL;
679
680         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|Oz",
681                                          discard_const_p(char *, kwnames), &py_creds, &py_lp,
682                                          &server_address))
683                 return NULL;
684
685         ret = PyObject_New(py_net_Object, type);
686         if (ret == NULL) {
687                 return NULL;
688         }
689
690         /* FIXME: we really need to get a context from the caller or we may end
691          * up with 2 event contexts */
692         ret->ev = s4_event_context_init(NULL);
693         ret->mem_ctx = talloc_new(ret->ev);
694
695         lp = lpcfg_from_py_object(ret->mem_ctx, py_lp);
696         if (lp == NULL) {
697                 Py_DECREF(ret);
698                 return NULL;
699         }
700
701         ret->libnet_ctx = libnet_context_init(ret->ev, lp);
702         if (ret->libnet_ctx == NULL) {
703                 PyErr_SetString(PyExc_RuntimeError, "Unable to initialize net");
704                 Py_DECREF(ret);
705                 return NULL;
706         }
707
708         ret->libnet_ctx->server_address = server_address;
709
710         ret->libnet_ctx->cred = cli_credentials_from_py_object(py_creds);
711         if (ret->libnet_ctx->cred == NULL) {
712                 PyErr_SetString(PyExc_TypeError, "Expected credentials object");
713                 Py_DECREF(ret);
714                 return NULL;
715         }
716
717         return (PyObject *)ret;
718 }
719
720
721 PyTypeObject py_net_Type = {
722         PyVarObject_HEAD_INIT(NULL, 0)
723         .tp_name = "net.Net",
724         .tp_basicsize = sizeof(py_net_Object),
725         .tp_dealloc = (destructor)py_net_dealloc,
726         .tp_methods = net_obj_methods,
727         .tp_new = net_obj_new,
728 };
729
730 static struct PyModuleDef moduledef = {
731         PyModuleDef_HEAD_INIT,
732         .m_name = "net",
733         .m_size = -1,
734 };
735
736 MODULE_INIT_FUNC(net)
737 {
738         PyObject *m;
739
740         if (PyType_Ready(&py_net_Type) < 0)
741                 return NULL;
742
743         m = PyModule_Create(&moduledef);
744         if (m == NULL)
745                 return NULL;
746
747         Py_INCREF(&py_net_Type);
748         PyModule_AddObject(m, "Net", (PyObject *)&py_net_Type);
749         PyModule_AddIntConstant(m, "LIBNET_JOINDOMAIN_AUTOMATIC", LIBNET_JOINDOMAIN_AUTOMATIC);
750         PyModule_AddIntConstant(m, "LIBNET_JOINDOMAIN_SPECIFIED", LIBNET_JOINDOMAIN_SPECIFIED);
751         PyModule_AddIntConstant(m, "LIBNET_JOIN_AUTOMATIC", LIBNET_JOIN_AUTOMATIC);
752         PyModule_AddIntConstant(m, "LIBNET_JOIN_SPECIFIED", LIBNET_JOIN_SPECIFIED);
753
754         return m;
755 }