port latest changes from SAMBA_3_0 tree
[tprouty/samba.git] / source / python / py_lsa.c
1 /* 
2    Python wrappers for DCERPC/SMB client routines.
3
4    Copyright (C) Tim Potter, 2002
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20
21 #include "python/py_lsa.h"
22
23 PyObject *new_lsa_policy_hnd_object(struct cli_state *cli, TALLOC_CTX *mem_ctx,
24                                     POLICY_HND *pol)
25 {
26         lsa_policy_hnd_object *o;
27
28         o = PyObject_New(lsa_policy_hnd_object, &lsa_policy_hnd_type);
29
30         o->cli = cli;
31         o->mem_ctx = mem_ctx;
32         memcpy(&o->pol, pol, sizeof(POLICY_HND));
33
34         return (PyObject*)o;
35 }
36
37 /* 
38  * Exceptions raised by this module 
39  */
40
41 PyObject *lsa_error;            /* This indicates a non-RPC related error
42                                    such as name lookup failure */
43
44 PyObject *lsa_ntstatus;         /* This exception is raised when a RPC call
45                                    returns a status code other than
46                                    NT_STATUS_OK */
47
48 /*
49  * Open/close lsa handles
50  */
51
52 static PyObject *lsa_open_policy(PyObject *self, PyObject *args, 
53                                 PyObject *kw) 
54 {
55         static char *kwlist[] = { "servername", "creds", "access", NULL };
56         char *server, *errstr;
57         PyObject *creds = NULL, *result = NULL;
58         uint32 desired_access = MAXIMUM_ALLOWED_ACCESS;
59         struct cli_state *cli = NULL;
60         NTSTATUS ntstatus;
61         TALLOC_CTX *mem_ctx = NULL;
62         POLICY_HND hnd;
63
64         if (!PyArg_ParseTupleAndKeywords(
65                     args, kw, "s|Oi", kwlist, &server, &creds, &desired_access))
66                 return NULL;
67
68         if (creds && creds != Py_None && !PyDict_Check(creds)) {
69                 PyErr_SetString(PyExc_TypeError, 
70                                 "credentials must be dictionary or None");
71                 return NULL;
72         }
73
74         if (server[0] != '\\' || server[1] != '\\') {
75                 PyErr_SetString(PyExc_ValueError, "UNC name required");
76                 return NULL;
77         }
78
79         server += 2;
80
81         if (!(cli = open_pipe_creds(server, creds, PI_LSARPC, &errstr))) {
82                 PyErr_SetString(lsa_error, errstr);
83                 free(errstr);
84                 return NULL;
85         }
86
87         if (!(mem_ctx = talloc_init("lsa_open_policy"))) {
88                 PyErr_SetString(lsa_error, "unable to init talloc context\n");
89                 goto done;
90         }
91
92         ntstatus = cli_lsa_open_policy(cli, mem_ctx, True,
93                                        SEC_RIGHTS_MAXIMUM_ALLOWED, &hnd);
94
95         if (!NT_STATUS_IS_OK(ntstatus)) {
96                 PyErr_SetObject(lsa_ntstatus, py_ntstatus_tuple(ntstatus));
97                 goto done;
98         }
99
100         result = new_lsa_policy_hnd_object(cli, mem_ctx, &hnd);
101
102 done:
103         if (!result) {
104                 if (cli)
105                         cli_shutdown(cli);
106
107                 if (mem_ctx)
108                         talloc_destroy(mem_ctx);
109         }
110
111         return result;
112 }
113
114 static PyObject *lsa_close(PyObject *self, PyObject *args, PyObject *kw) 
115 {
116         PyObject *po;
117         lsa_policy_hnd_object *hnd;
118         NTSTATUS result;
119
120         /* Parse parameters */
121
122         if (!PyArg_ParseTuple(args, "O!", &lsa_policy_hnd_type, &po))
123                 return NULL;
124
125         hnd = (lsa_policy_hnd_object *)po;
126
127         /* Call rpc function */
128
129         result = cli_lsa_close(hnd->cli, hnd->mem_ctx, &hnd->pol);
130
131         /* Cleanup samba stuff */
132
133         cli_shutdown(hnd->cli);
134         talloc_destroy(hnd->mem_ctx);
135
136         /* Return value */
137
138         Py_INCREF(Py_None);
139         return Py_None; 
140 }
141
142 static PyObject *lsa_lookup_names(PyObject *self, PyObject *args)
143 {
144         PyObject *py_names, *result;
145         NTSTATUS ntstatus;
146         lsa_policy_hnd_object *hnd = (lsa_policy_hnd_object *)self;
147         int num_names, i;
148         const char **names;
149         DOM_SID *sids;
150         uint32 *name_types;
151
152         if (!PyArg_ParseTuple(args, "O", &py_names))
153                 return NULL;
154
155         if (!PyList_Check(py_names) && !PyString_Check(py_names)) {
156                 PyErr_SetString(PyExc_TypeError, "must be list or string");
157                 return NULL;
158         }
159
160         if (PyList_Check(py_names)) {
161
162                 /* Convert list to char ** array */
163
164                 num_names = PyList_Size(py_names);
165                 names = (const char **)talloc(
166                         hnd->mem_ctx, num_names * sizeof(char *));
167                 
168                 for (i = 0; i < num_names; i++) {
169                         PyObject *obj = PyList_GetItem(py_names, i);
170                         
171                         names[i] = talloc_strdup(hnd->mem_ctx, PyString_AsString(obj));
172                 }
173
174         } else {
175
176                 /* Just a single element */
177
178                 num_names = 1;
179                 names = (const char **)talloc(hnd->mem_ctx, sizeof(char *));
180
181                 names[0] = PyString_AsString(py_names);
182         }
183
184         ntstatus = cli_lsa_lookup_names(hnd->cli, hnd->mem_ctx, &hnd->pol,
185                                         num_names, names, &sids, &name_types);
186
187         if (!NT_STATUS_IS_OK(ntstatus) && NT_STATUS_V(ntstatus) != 0x107) {
188                 PyErr_SetObject(lsa_ntstatus, py_ntstatus_tuple(ntstatus));
189                 return NULL;
190         }
191
192         result = PyList_New(num_names);
193
194         for (i = 0; i < num_names; i++) {
195                 PyObject *sid_obj, *obj;
196
197                 py_from_SID(&sid_obj, &sids[i]);
198
199                 obj = Py_BuildValue("(Oi)", sid_obj, name_types[i]);
200
201                 PyList_SetItem(result, i, obj);
202         }
203         
204         return result;
205 }
206
207 static PyObject *lsa_lookup_sids(PyObject *self, PyObject *args, 
208                                  PyObject *kw) 
209 {
210         PyObject *py_sids, *result;
211         NTSTATUS ntstatus;
212         int num_sids, i;
213         char **domains, **names;
214         uint32 *types;
215         lsa_policy_hnd_object *hnd = (lsa_policy_hnd_object *)self;
216         TALLOC_CTX *mem_ctx = NULL;
217         DOM_SID *sids;
218
219         if (!PyArg_ParseTuple(args, "O", &py_sids))
220                 return NULL;
221
222         if (!PyList_Check(py_sids) && !PyString_Check(py_sids)) {
223                 PyErr_SetString(PyExc_TypeError, "must be list or string");
224                 return NULL;
225         }
226
227         if (!(mem_ctx = talloc_init("lsa_open_policy"))) {
228                 PyErr_SetString(lsa_error, "unable to init talloc context\n");
229                 goto done;
230         }
231
232         if (PyList_Check(py_sids)) {
233
234                 /* Convert dictionary to char ** array */
235                 
236                 num_sids = PyList_Size(py_sids);
237                 sids = (DOM_SID *)talloc(mem_ctx, num_sids * sizeof(DOM_SID));
238                 
239                 memset(sids, 0, num_sids * sizeof(DOM_SID));
240                 
241                 for (i = 0; i < num_sids; i++) {
242                         PyObject *obj = PyList_GetItem(py_sids, i);
243                         
244                         if (!string_to_sid(&sids[i], PyString_AsString(obj))) {
245                                 PyErr_SetString(PyExc_ValueError, "string_to_sid failed");
246                                 result = NULL;
247                                 goto done;
248                         }
249                 }
250
251         } else {
252
253                 /* Just a single element */
254
255                 num_sids = 1;
256                 sids = (DOM_SID *)talloc(mem_ctx, sizeof(DOM_SID));
257
258                 if (!string_to_sid(&sids[0], PyString_AsString(py_sids))) {
259                         PyErr_SetString(PyExc_ValueError, "string_to_sid failed");
260                         result = NULL;
261                         goto done;
262                 }
263         }
264
265         ntstatus = cli_lsa_lookup_sids(hnd->cli, mem_ctx, &hnd->pol,
266                                        num_sids, sids, &domains, &names, 
267                                        &types);
268
269         if (!NT_STATUS_IS_OK(ntstatus)) {
270                 PyErr_SetObject(lsa_ntstatus, py_ntstatus_tuple(ntstatus));
271                 result = NULL;
272                 goto done;
273         }
274
275         result = PyList_New(num_sids);
276
277         for (i = 0; i < num_sids; i++) {
278                 PyObject *obj;
279
280                 obj = Py_BuildValue("{sssssi}", "username", names[i],
281                                     "domain", domains[i], "name_type", 
282                                     types[i]);
283
284                 PyList_SetItem(result, i, obj);
285         }
286
287  done:
288         if (mem_ctx)
289                 talloc_destroy(mem_ctx);
290
291         return result;
292 }
293
294 static PyObject *lsa_enum_trust_dom(PyObject *self, PyObject *args)
295 {
296         lsa_policy_hnd_object *hnd = (lsa_policy_hnd_object *)self;
297         NTSTATUS ntstatus;
298         uint32 enum_ctx = 0, num_domains, i;
299         char **domain_names;
300         DOM_SID *domain_sids;
301         PyObject *result;
302
303         if (!PyArg_ParseTuple(args, ""))
304                 return NULL;
305         
306         ntstatus = cli_lsa_enum_trust_dom(
307                 hnd->cli, hnd->mem_ctx, &hnd->pol, &enum_ctx,
308                 &num_domains, &domain_names, &domain_sids);
309
310         if (!NT_STATUS_IS_OK(ntstatus)) {
311                 PyErr_SetObject(lsa_ntstatus, py_ntstatus_tuple(ntstatus));
312                 return NULL;
313         }
314
315         result = PyList_New(num_domains);
316
317         for (i = 0; i < num_domains; i++) {
318                 fstring sid_str;
319
320                 sid_to_string(sid_str, &domain_sids[i]);
321                 PyList_SetItem(
322                         result, i, 
323                         Py_BuildValue("(ss)", domain_names[i], sid_str));
324         }
325
326         return result;
327 }
328
329 /*
330  * Method dispatch tables
331  */
332
333 static PyMethodDef lsa_hnd_methods[] = {
334
335         /* SIDs<->names */
336
337         { "lookup_sids", (PyCFunction)lsa_lookup_sids, 
338           METH_VARARGS | METH_KEYWORDS,
339           "Convert sids to names." },
340
341         { "lookup_names", (PyCFunction)lsa_lookup_names, 
342           METH_VARARGS | METH_KEYWORDS,
343           "Convert names to sids." },
344
345         /* Trusted domains */
346
347         { "enum_trusted_domains", (PyCFunction)lsa_enum_trust_dom, 
348           METH_VARARGS, 
349           "Enumerate trusted domains." },
350
351         { NULL }
352 };
353
354 static void py_lsa_policy_hnd_dealloc(PyObject* self)
355 {
356         PyObject_Del(self);
357 }
358
359 static PyObject *py_lsa_policy_hnd_getattr(PyObject *self, char *attrname)
360 {
361         return Py_FindMethod(lsa_hnd_methods, self, attrname);
362 }
363
364 PyTypeObject lsa_policy_hnd_type = {
365         PyObject_HEAD_INIT(NULL)
366         0,
367         "LSA Policy Handle",
368         sizeof(lsa_policy_hnd_object),
369         0,
370         py_lsa_policy_hnd_dealloc, /*tp_dealloc*/
371         0,          /*tp_print*/
372         py_lsa_policy_hnd_getattr,          /*tp_getattr*/
373         0,          /*tp_setattr*/
374         0,          /*tp_compare*/
375         0,          /*tp_repr*/
376         0,          /*tp_as_number*/
377         0,          /*tp_as_sequence*/
378         0,          /*tp_as_mapping*/
379         0,          /*tp_hash */
380 };
381
382 static PyMethodDef lsa_methods[] = {
383
384         /* Open/close lsa handles */
385         
386         { "open_policy", (PyCFunction)lsa_open_policy, 
387           METH_VARARGS | METH_KEYWORDS, 
388           "Open a policy handle" },
389         
390         { "close", (PyCFunction)lsa_close, 
391           METH_VARARGS, 
392           "Close a policy handle" },
393
394         /* Other stuff - this should really go into a samba config module
395            but for the moment let's leave it here. */
396
397         { "setup_logging", (PyCFunction)py_setup_logging, 
398           METH_VARARGS | METH_KEYWORDS, 
399           "Set up debug logging.\n"
400 "\n"
401 "Initialises Samba's debug logging system.  One argument is expected which\n"
402 "is a boolean specifying whether debugging is interactive and sent to stdout\n"
403 "or logged to a file.\n"
404 "\n"
405 "Example:\n"
406 "\n"
407 ">>> spoolss.setup_logging(interactive = 1)" },
408
409         { "get_debuglevel", (PyCFunction)get_debuglevel, 
410           METH_VARARGS, 
411           "Set the current debug level.\n"
412 "\n"
413 "Example:\n"
414 "\n"
415 ">>> spoolss.get_debuglevel()\n"
416 "0" },
417
418         { "set_debuglevel", (PyCFunction)set_debuglevel, 
419           METH_VARARGS, 
420           "Get the current debug level.\n"
421 "\n"
422 "Example:\n"
423 "\n"
424 ">>> spoolss.set_debuglevel(10)" },
425
426         { NULL }
427 };
428
429 static struct const_vals {
430         char *name;
431         uint32 value;
432 } module_const_vals[] = {
433         { NULL }
434 };
435
436 static void const_init(PyObject *dict)
437 {
438         struct const_vals *tmp;
439         PyObject *obj;
440
441         for (tmp = module_const_vals; tmp->name; tmp++) {
442                 obj = PyInt_FromLong(tmp->value);
443                 PyDict_SetItemString(dict, tmp->name, obj);
444                 Py_DECREF(obj);
445         }
446 }
447
448 /*
449  * Module initialisation 
450  */
451
452 void initlsa(void)
453 {
454         PyObject *module, *dict;
455
456         /* Initialise module */
457
458         module = Py_InitModule("lsa", lsa_methods);
459         dict = PyModule_GetDict(module);
460
461         lsa_error = PyErr_NewException("lsa.error", NULL, NULL);
462         PyDict_SetItemString(dict, "error", lsa_error);
463
464         lsa_ntstatus = PyErr_NewException("lsa.ntstatus", NULL, NULL);
465         PyDict_SetItemString(dict, "ntstatus", lsa_ntstatus);
466
467         /* Initialise policy handle object */
468
469         lsa_policy_hnd_type.ob_type = &PyType_Type;
470
471         /* Initialise constants */
472
473         const_init(dict);
474
475         /* Do samba initialisation */
476
477         py_samba_init();
478
479         setup_logging("lsa", True);
480         DEBUGLEVEL = 10;
481 }