s4:auth: Enforce machine authentication policy for NTLM authentication
[Samba.git] / source3 / libsmb / pylibsmb.c
blobbace98ddd3a89cc9d1959f2862541b99c0bae6b2
1 /*
2 * Unix SMB/CIFS implementation.
4 * SMB client Python bindings used internally by Samba (for things like
5 * samba-tool). These Python bindings may change without warning, and so
6 * should not be used outside of the Samba codebase.
8 * Copyright (C) Volker Lendecke 2012
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 Template code to use this library:
27 -------------------------
28 from samba.samba3 import libsmb_samba_internal as libsmb
29 from samba.samba3 import param as s3param
30 from samba import (credentials,NTSTATUSError)
32 lp = s3param.get_context()
33 lp.load("/etc/samba/smb.conf");
35 creds = credentials.Credentials()
36 creds.guess(lp)
37 creds.set_username("administrator")
38 creds.set_password("1234")
40 c = libsmb.Conn("127.0.0.1",
41 "tmp",
42 lp,
43 creds,
44 multi_threaded=True)
45 -------------------------
48 #include <Python.h>
49 #include "includes.h"
50 #include "python/py3compat.h"
51 #include "python/modules.h"
52 #include "libcli/smb/smbXcli_base.h"
53 #include "libcli/smb/smb2_negotiate_context.h"
54 #include "libcli/smb/reparse_symlink.h"
55 #include "libsmb/libsmb.h"
56 #include "libcli/security/security.h"
57 #include "system/select.h"
58 #include "source4/libcli/util/pyerrors.h"
59 #include "auth/credentials/pycredentials.h"
60 #include "trans2.h"
61 #include "libsmb/clirap.h"
62 #include "librpc/rpc/pyrpc_util.h"
64 #define LIST_ATTRIBUTE_MASK \
65 (FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN)
67 static PyTypeObject *dom_sid_Type = NULL;
69 static PyTypeObject *get_pytype(const char *module, const char *type)
71 PyObject *mod;
72 PyTypeObject *result;
74 mod = PyImport_ImportModule(module);
75 if (mod == NULL) {
76 PyErr_Format(PyExc_RuntimeError,
77 "Unable to import %s to check type %s",
78 module, type);
79 return NULL;
81 result = (PyTypeObject *)PyObject_GetAttrString(mod, type);
82 Py_DECREF(mod);
83 if (result == NULL) {
84 PyErr_Format(PyExc_RuntimeError,
85 "Unable to find type %s in module %s",
86 module, type);
87 return NULL;
89 return result;
93 * We're using "const char * const *" for keywords,
94 * PyArg_ParseTupleAndKeywords expects a "char **". Confine the
95 * inevitable warnings to just one place.
97 static int ParseTupleAndKeywords(PyObject *args, PyObject *kw,
98 const char *format, const char * const *keywords,
99 ...)
101 char **_keywords = discard_const_p(char *, keywords);
102 va_list a;
103 int ret;
104 va_start(a, keywords);
105 ret = PyArg_VaParseTupleAndKeywords(args, kw, format,
106 _keywords, a);
107 va_end(a);
108 return ret;
111 struct py_cli_thread;
113 struct py_cli_oplock_break {
114 uint16_t fnum;
115 uint8_t level;
118 struct py_cli_state {
119 PyObject_HEAD
120 struct cli_state *cli;
121 struct tevent_context *ev;
122 int (*req_wait_fn)(struct tevent_context *ev,
123 struct tevent_req *req);
124 struct py_cli_thread *thread_state;
126 struct tevent_req *oplock_waiter;
127 struct py_cli_oplock_break *oplock_breaks;
128 struct py_tevent_cond *oplock_cond;
131 #ifdef HAVE_PTHREAD
133 #include <pthread.h>
135 struct py_cli_thread {
138 * Pipe to make the poll thread wake up in our destructor, so
139 * that we can exit and join the thread.
141 int shutdown_pipe[2];
142 struct tevent_fd *shutdown_fde;
143 bool do_shutdown;
144 pthread_t id;
147 * Thread state to release the GIL during the poll(2) syscall
149 PyThreadState *py_threadstate;
152 static void *py_cli_state_poll_thread(void *private_data)
154 struct py_cli_state *self = (struct py_cli_state *)private_data;
155 struct py_cli_thread *t = self->thread_state;
156 PyGILState_STATE gstate;
158 gstate = PyGILState_Ensure();
160 while (!t->do_shutdown) {
161 int ret;
162 ret = tevent_loop_once(self->ev);
163 assert(ret == 0);
165 PyGILState_Release(gstate);
166 return NULL;
169 static void py_cli_state_trace_callback(enum tevent_trace_point point,
170 void *private_data)
172 struct py_cli_state *self = (struct py_cli_state *)private_data;
173 struct py_cli_thread *t = self->thread_state;
175 switch(point) {
176 case TEVENT_TRACE_BEFORE_WAIT:
177 assert(t->py_threadstate == NULL);
178 t->py_threadstate = PyEval_SaveThread();
179 break;
180 case TEVENT_TRACE_AFTER_WAIT:
181 assert(t->py_threadstate != NULL);
182 PyEval_RestoreThread(t->py_threadstate);
183 t->py_threadstate = NULL;
184 break;
185 default:
186 break;
190 static void py_cli_state_shutdown_handler(struct tevent_context *ev,
191 struct tevent_fd *fde,
192 uint16_t flags,
193 void *private_data)
195 struct py_cli_state *self = (struct py_cli_state *)private_data;
196 struct py_cli_thread *t = self->thread_state;
198 if ((flags & TEVENT_FD_READ) == 0) {
199 return;
201 TALLOC_FREE(t->shutdown_fde);
202 t->do_shutdown = true;
205 static int py_cli_thread_destructor(struct py_cli_thread *t)
207 char c = 0;
208 ssize_t written;
209 int ret;
211 do {
213 * This will wake the poll thread from the poll(2)
215 written = write(t->shutdown_pipe[1], &c, 1);
216 } while ((written == -1) && (errno == EINTR));
219 * Allow the poll thread to do its own cleanup under the GIL
221 Py_BEGIN_ALLOW_THREADS
222 ret = pthread_join(t->id, NULL);
223 Py_END_ALLOW_THREADS
224 assert(ret == 0);
226 if (t->shutdown_pipe[0] != -1) {
227 close(t->shutdown_pipe[0]);
228 t->shutdown_pipe[0] = -1;
230 if (t->shutdown_pipe[1] != -1) {
231 close(t->shutdown_pipe[1]);
232 t->shutdown_pipe[1] = -1;
234 return 0;
237 static int py_tevent_cond_req_wait(struct tevent_context *ev,
238 struct tevent_req *req);
240 static bool py_cli_state_setup_mt_ev(struct py_cli_state *self)
242 struct py_cli_thread *t = NULL;
243 int ret;
245 self->ev = tevent_context_init_byname(NULL, "poll_mt");
246 if (self->ev == NULL) {
247 goto fail;
249 samba_tevent_set_debug(self->ev, "pylibsmb_tevent_mt");
250 tevent_set_trace_callback(self->ev, py_cli_state_trace_callback, self);
252 self->req_wait_fn = py_tevent_cond_req_wait;
254 self->thread_state = talloc_zero(NULL, struct py_cli_thread);
255 if (self->thread_state == NULL) {
256 goto fail;
258 t = self->thread_state;
260 ret = pipe(t->shutdown_pipe);
261 if (ret == -1) {
262 goto fail;
264 t->shutdown_fde = tevent_add_fd(
265 self->ev, self->ev, t->shutdown_pipe[0], TEVENT_FD_READ,
266 py_cli_state_shutdown_handler, self);
267 if (t->shutdown_fde == NULL) {
268 goto fail;
271 PyEval_InitThreads();
273 ret = pthread_create(&t->id, NULL, py_cli_state_poll_thread, self);
274 if (ret != 0) {
275 goto fail;
277 talloc_set_destructor(self->thread_state, py_cli_thread_destructor);
278 return true;
280 fail:
281 if (t != NULL) {
282 TALLOC_FREE(t->shutdown_fde);
284 if (t->shutdown_pipe[0] != -1) {
285 close(t->shutdown_pipe[0]);
286 t->shutdown_pipe[0] = -1;
288 if (t->shutdown_pipe[1] != -1) {
289 close(t->shutdown_pipe[1]);
290 t->shutdown_pipe[1] = -1;
294 TALLOC_FREE(self->thread_state);
295 TALLOC_FREE(self->ev);
296 return false;
299 struct py_tevent_cond {
300 pthread_mutex_t mutex;
301 pthread_cond_t cond;
302 bool is_done;
305 static void py_tevent_signalme(struct tevent_req *req);
307 static int py_tevent_cond_wait(struct py_tevent_cond *cond)
309 int ret, result;
311 result = pthread_mutex_init(&cond->mutex, NULL);
312 if (result != 0) {
313 goto fail;
315 result = pthread_cond_init(&cond->cond, NULL);
316 if (result != 0) {
317 goto fail_mutex;
320 result = pthread_mutex_lock(&cond->mutex);
321 if (result != 0) {
322 goto fail_cond;
325 cond->is_done = false;
327 while (!cond->is_done) {
329 Py_BEGIN_ALLOW_THREADS
330 result = pthread_cond_wait(&cond->cond, &cond->mutex);
331 Py_END_ALLOW_THREADS
333 if (result != 0) {
334 goto fail_unlock;
338 fail_unlock:
339 ret = pthread_mutex_unlock(&cond->mutex);
340 assert(ret == 0);
341 fail_cond:
342 ret = pthread_cond_destroy(&cond->cond);
343 assert(ret == 0);
344 fail_mutex:
345 ret = pthread_mutex_destroy(&cond->mutex);
346 assert(ret == 0);
347 fail:
348 return result;
351 static int py_tevent_cond_req_wait(struct tevent_context *ev,
352 struct tevent_req *req)
354 struct py_tevent_cond cond;
355 tevent_req_set_callback(req, py_tevent_signalme, &cond);
356 return py_tevent_cond_wait(&cond);
359 static void py_tevent_cond_signal(struct py_tevent_cond *cond)
361 int ret;
363 ret = pthread_mutex_lock(&cond->mutex);
364 assert(ret == 0);
366 cond->is_done = true;
368 ret = pthread_cond_signal(&cond->cond);
369 assert(ret == 0);
370 ret = pthread_mutex_unlock(&cond->mutex);
371 assert(ret == 0);
374 static void py_tevent_signalme(struct tevent_req *req)
376 struct py_tevent_cond *cond = (struct py_tevent_cond *)
377 tevent_req_callback_data_void(req);
379 py_tevent_cond_signal(cond);
382 #endif
384 static int py_tevent_req_wait(struct tevent_context *ev,
385 struct tevent_req *req);
387 static bool py_cli_state_setup_ev(struct py_cli_state *self)
389 self->ev = tevent_context_init(NULL);
390 if (self->ev == NULL) {
391 return false;
394 samba_tevent_set_debug(self->ev, "pylibsmb_tevent");
396 self->req_wait_fn = py_tevent_req_wait;
398 return true;
401 static int py_tevent_req_wait(struct tevent_context *ev,
402 struct tevent_req *req)
404 while (tevent_req_is_in_progress(req)) {
405 int ret;
407 ret = tevent_loop_once(ev);
408 if (ret != 0) {
409 return ret;
412 return 0;
415 static bool py_tevent_req_wait_exc(struct py_cli_state *self,
416 struct tevent_req *req)
418 int ret;
420 if (req == NULL) {
421 PyErr_NoMemory();
422 return false;
424 ret = self->req_wait_fn(self->ev, req);
425 if (ret != 0) {
426 TALLOC_FREE(req);
427 errno = ret;
428 PyErr_SetFromErrno(PyExc_RuntimeError);
429 return false;
431 return true;
434 static PyObject *py_cli_state_new(PyTypeObject *type, PyObject *args,
435 PyObject *kwds)
437 struct py_cli_state *self;
439 self = (struct py_cli_state *)type->tp_alloc(type, 0);
440 if (self == NULL) {
441 return NULL;
443 self->cli = NULL;
444 self->ev = NULL;
445 self->thread_state = NULL;
446 self->oplock_waiter = NULL;
447 self->oplock_cond = NULL;
448 self->oplock_breaks = NULL;
449 return (PyObject *)self;
452 static struct smb2_negotiate_contexts *py_cli_get_negotiate_contexts(
453 TALLOC_CTX *mem_ctx, PyObject *list)
455 struct smb2_negotiate_contexts *ctxs = NULL;
456 Py_ssize_t i, len;
457 int ret;
459 ret = PyList_Check(list);
460 if (!ret) {
461 goto fail;
464 len = PyList_Size(list);
465 if (len == 0) {
466 goto fail;
469 ctxs = talloc_zero(mem_ctx, struct smb2_negotiate_contexts);
470 if (ctxs == NULL) {
471 goto fail;
474 for (i=0; i<len; i++) {
475 NTSTATUS status;
477 PyObject *t = PyList_GetItem(list, i);
478 Py_ssize_t tlen;
480 PyObject *ptype = NULL;
481 long type;
483 PyObject *pdata = NULL;
484 DATA_BLOB data = { .data = NULL, };
486 if (t == NULL) {
487 goto fail;
490 ret = PyTuple_Check(t);
491 if (!ret) {
492 goto fail;
495 tlen = PyTuple_Size(t);
496 if (tlen != 2) {
497 goto fail;
500 ptype = PyTuple_GetItem(t, 0);
501 if (ptype == NULL) {
502 goto fail;
504 type = PyLong_AsLong(ptype);
505 if ((type < 0) || (type > UINT16_MAX)) {
506 goto fail;
509 pdata = PyTuple_GetItem(t, 1);
511 ret = PyBytes_Check(pdata);
512 if (!ret) {
513 goto fail;
516 data.data = (uint8_t *)PyBytes_AsString(pdata);
517 data.length = PyBytes_Size(pdata);
519 status = smb2_negotiate_context_add(
520 ctxs, ctxs, type, data.data, data.length);
521 if (!NT_STATUS_IS_OK(status)) {
522 goto fail;
525 return ctxs;
527 fail:
528 TALLOC_FREE(ctxs);
529 return NULL;
532 static void py_cli_got_oplock_break(struct tevent_req *req);
534 static int py_cli_state_init(struct py_cli_state *self, PyObject *args,
535 PyObject *kwds)
537 NTSTATUS status;
538 char *host, *share;
539 PyObject *creds = NULL;
540 struct cli_credentials *cli_creds;
541 PyObject *py_lp = Py_None;
542 PyObject *py_multi_threaded = Py_False;
543 bool multi_threaded = false;
544 PyObject *py_force_smb1 = Py_False;
545 bool force_smb1 = false;
546 PyObject *py_ipc = Py_False;
547 PyObject *py_posix = Py_False;
548 PyObject *py_negotiate_contexts = NULL;
549 struct smb2_negotiate_contexts *negotiate_contexts = NULL;
550 bool use_ipc = false;
551 bool request_posix = false;
552 struct tevent_req *req;
553 bool ret;
554 int flags = 0;
556 static const char *kwlist[] = {
557 "host", "share", "lp", "creds",
558 "multi_threaded", "force_smb1",
559 "ipc",
560 "posix",
561 "negotiate_contexts",
562 NULL
565 PyTypeObject *py_type_Credentials = get_pytype(
566 "samba.credentials", "Credentials");
567 if (py_type_Credentials == NULL) {
568 return -1;
571 ret = ParseTupleAndKeywords(
572 args, kwds, "ssO|O!OOOOO", kwlist,
573 &host, &share, &py_lp,
574 py_type_Credentials, &creds,
575 &py_multi_threaded,
576 &py_force_smb1,
577 &py_ipc,
578 &py_posix,
579 &py_negotiate_contexts);
581 Py_DECREF(py_type_Credentials);
583 if (!ret) {
584 return -1;
587 multi_threaded = PyObject_IsTrue(py_multi_threaded);
588 force_smb1 = PyObject_IsTrue(py_force_smb1);
590 if (force_smb1) {
592 * As most of the cli_*_send() function
593 * don't support SMB2 (it's only plugged
594 * into the sync wrapper functions currently)
595 * we have a way to force SMB1.
597 flags = CLI_FULL_CONNECTION_FORCE_SMB1;
600 use_ipc = PyObject_IsTrue(py_ipc);
601 if (use_ipc) {
602 flags |= CLI_FULL_CONNECTION_IPC;
605 request_posix = PyObject_IsTrue(py_posix);
606 if (request_posix) {
607 flags |= CLI_FULL_CONNECTION_REQUEST_POSIX;
610 if (py_negotiate_contexts != NULL) {
611 negotiate_contexts = py_cli_get_negotiate_contexts(
612 talloc_tos(), py_negotiate_contexts);
613 if (negotiate_contexts == NULL) {
614 return -1;
618 if (multi_threaded) {
619 #ifdef HAVE_PTHREAD
620 ret = py_cli_state_setup_mt_ev(self);
621 if (!ret) {
622 return -1;
624 #else
625 PyErr_SetString(PyExc_RuntimeError,
626 "No PTHREAD support available");
627 return -1;
628 #endif
629 } else {
630 ret = py_cli_state_setup_ev(self);
631 if (!ret) {
632 return -1;
636 if (creds == NULL) {
637 cli_creds = cli_credentials_init_anon(NULL);
638 } else {
639 cli_creds = PyCredentials_AsCliCredentials(creds);
642 req = cli_full_connection_creds_send(
643 NULL, self->ev, "myname", host, NULL, 0, share, "?????",
644 cli_creds, flags,
645 negotiate_contexts);
646 if (!py_tevent_req_wait_exc(self, req)) {
647 return -1;
649 status = cli_full_connection_creds_recv(req, &self->cli);
650 TALLOC_FREE(req);
652 if (!NT_STATUS_IS_OK(status)) {
653 PyErr_SetNTSTATUS(status);
654 return -1;
658 * Oplocks require a multi threaded connection
660 if (self->thread_state == NULL) {
661 return 0;
664 self->oplock_waiter = cli_smb_oplock_break_waiter_send(
665 self->ev, self->ev, self->cli);
666 if (self->oplock_waiter == NULL) {
667 PyErr_NoMemory();
668 return -1;
670 tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
671 self);
672 return 0;
675 static void py_cli_got_oplock_break(struct tevent_req *req)
677 struct py_cli_state *self = (struct py_cli_state *)
678 tevent_req_callback_data_void(req);
679 struct py_cli_oplock_break b;
680 struct py_cli_oplock_break *tmp;
681 size_t num_breaks;
682 NTSTATUS status;
684 status = cli_smb_oplock_break_waiter_recv(req, &b.fnum, &b.level);
685 TALLOC_FREE(req);
686 self->oplock_waiter = NULL;
688 if (!NT_STATUS_IS_OK(status)) {
689 return;
692 num_breaks = talloc_array_length(self->oplock_breaks);
693 tmp = talloc_realloc(self->ev, self->oplock_breaks,
694 struct py_cli_oplock_break, num_breaks+1);
695 if (tmp == NULL) {
696 return;
698 self->oplock_breaks = tmp;
699 self->oplock_breaks[num_breaks] = b;
701 if (self->oplock_cond != NULL) {
702 py_tevent_cond_signal(self->oplock_cond);
705 self->oplock_waiter = cli_smb_oplock_break_waiter_send(
706 self->ev, self->ev, self->cli);
707 if (self->oplock_waiter == NULL) {
708 return;
710 tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
711 self);
714 static PyObject *py_cli_get_oplock_break(struct py_cli_state *self,
715 PyObject *args)
717 size_t num_oplock_breaks;
719 if (!PyArg_ParseTuple(args, "")) {
720 return NULL;
723 if (self->thread_state == NULL) {
724 PyErr_SetString(PyExc_RuntimeError,
725 "get_oplock_break() only possible on "
726 "a multi_threaded connection");
727 return NULL;
730 if (self->oplock_cond != NULL) {
731 errno = EBUSY;
732 PyErr_SetFromErrno(PyExc_RuntimeError);
733 return NULL;
736 num_oplock_breaks = talloc_array_length(self->oplock_breaks);
738 if (num_oplock_breaks == 0) {
739 struct py_tevent_cond cond;
740 int ret;
742 self->oplock_cond = &cond;
743 ret = py_tevent_cond_wait(&cond);
744 self->oplock_cond = NULL;
746 if (ret != 0) {
747 errno = ret;
748 PyErr_SetFromErrno(PyExc_RuntimeError);
749 return NULL;
753 num_oplock_breaks = talloc_array_length(self->oplock_breaks);
754 if (num_oplock_breaks > 0) {
755 PyObject *result;
757 result = Py_BuildValue(
758 "{s:i,s:i}",
759 "fnum", self->oplock_breaks[0].fnum,
760 "level", self->oplock_breaks[0].level);
762 memmove(&self->oplock_breaks[0], &self->oplock_breaks[1],
763 sizeof(self->oplock_breaks[0]) *
764 (num_oplock_breaks - 1));
765 self->oplock_breaks = talloc_realloc(
766 NULL, self->oplock_breaks, struct py_cli_oplock_break,
767 num_oplock_breaks - 1);
769 return result;
771 Py_RETURN_NONE;
774 static void py_cli_state_dealloc(struct py_cli_state *self)
776 TALLOC_FREE(self->thread_state);
777 TALLOC_FREE(self->oplock_waiter);
778 TALLOC_FREE(self->ev);
780 if (self->cli != NULL) {
781 cli_shutdown(self->cli);
782 self->cli = NULL;
784 Py_TYPE(self)->tp_free((PyObject *)self);
787 static PyObject *py_cli_settimeout(struct py_cli_state *self, PyObject *args)
789 unsigned int nmsecs = 0;
790 unsigned int omsecs = 0;
792 if (!PyArg_ParseTuple(args, "I", &nmsecs)) {
793 return NULL;
796 omsecs = cli_set_timeout(self->cli, nmsecs);
798 return PyLong_FromLong(omsecs);
801 static PyObject *py_cli_echo(struct py_cli_state *self,
802 PyObject *Py_UNUSED(ignored))
804 DATA_BLOB data = data_blob_string_const("keepalive");
805 struct tevent_req *req = NULL;
806 NTSTATUS status;
808 req = cli_echo_send(NULL, self->ev, self->cli, 1, data);
809 if (!py_tevent_req_wait_exc(self, req)) {
810 return NULL;
812 status = cli_echo_recv(req);
813 TALLOC_FREE(req);
814 PyErr_NTSTATUS_NOT_OK_RAISE(status);
816 Py_RETURN_NONE;
819 static PyObject *py_cli_create(struct py_cli_state *self, PyObject *args,
820 PyObject *kwds)
822 char *fname;
823 unsigned CreateFlags = 0;
824 unsigned DesiredAccess = FILE_GENERIC_READ;
825 unsigned FileAttributes = 0;
826 unsigned ShareAccess = 0;
827 unsigned CreateDisposition = FILE_OPEN;
828 unsigned CreateOptions = 0;
829 unsigned ImpersonationLevel = SMB2_IMPERSONATION_IMPERSONATION;
830 unsigned SecurityFlags = 0;
831 uint16_t fnum;
832 struct tevent_req *req;
833 NTSTATUS status;
835 static const char *kwlist[] = {
836 "Name", "CreateFlags", "DesiredAccess", "FileAttributes",
837 "ShareAccess", "CreateDisposition", "CreateOptions",
838 "ImpersonationLevel", "SecurityFlags", NULL };
840 if (!ParseTupleAndKeywords(
841 args, kwds, "s|IIIIIIII", kwlist,
842 &fname, &CreateFlags, &DesiredAccess, &FileAttributes,
843 &ShareAccess, &CreateDisposition, &CreateOptions,
844 &ImpersonationLevel, &SecurityFlags)) {
845 return NULL;
848 req = cli_ntcreate_send(NULL, self->ev, self->cli, fname, CreateFlags,
849 DesiredAccess, FileAttributes, ShareAccess,
850 CreateDisposition, CreateOptions,
851 ImpersonationLevel, SecurityFlags);
852 if (!py_tevent_req_wait_exc(self, req)) {
853 return NULL;
855 status = cli_ntcreate_recv(req, &fnum, NULL);
856 TALLOC_FREE(req);
858 if (!NT_STATUS_IS_OK(status)) {
859 PyErr_SetNTSTATUS(status);
860 return NULL;
862 return Py_BuildValue("I", (unsigned)fnum);
865 static struct smb2_create_blobs *py_cli_get_create_contexts(
866 TALLOC_CTX *mem_ctx, PyObject *list)
868 struct smb2_create_blobs *ctxs = NULL;
869 Py_ssize_t i, len;
870 int ret;
872 ret = PyList_Check(list);
873 if (!ret) {
874 goto fail;
877 len = PyList_Size(list);
878 if (len == 0) {
879 goto fail;
882 ctxs = talloc_zero(mem_ctx, struct smb2_create_blobs);
883 if (ctxs == NULL) {
884 goto fail;
887 for (i=0; i<len; i++) {
888 NTSTATUS status;
890 PyObject *t = NULL;
891 Py_ssize_t tlen;
893 PyObject *pname = NULL;
894 char *name = NULL;
896 PyObject *pdata = NULL;
897 DATA_BLOB data = { .data = NULL, };
899 t = PyList_GetItem(list, i);
900 if (t == NULL) {
901 goto fail;
904 ret = PyTuple_Check(t);
905 if (!ret) {
906 goto fail;
909 tlen = PyTuple_Size(t);
910 if (tlen != 2) {
911 goto fail;
914 pname = PyTuple_GetItem(t, 0);
915 if (pname == NULL) {
916 goto fail;
918 ret = PyBytes_Check(pname);
919 if (!ret) {
920 goto fail;
922 name = PyBytes_AsString(pname);
924 pdata = PyTuple_GetItem(t, 1);
925 if (pdata == NULL) {
926 goto fail;
928 ret = PyBytes_Check(pdata);
929 if (!ret) {
930 goto fail;
932 data = (DATA_BLOB) {
933 .data = (uint8_t *)PyBytes_AsString(pdata),
934 .length = PyBytes_Size(pdata),
936 status = smb2_create_blob_add(ctxs, ctxs, name, data);
937 if (!NT_STATUS_IS_OK(status)) {
938 goto fail;
941 return ctxs;
943 fail:
944 TALLOC_FREE(ctxs);
945 return NULL;
948 static PyObject *py_cli_create_contexts(const struct smb2_create_blobs *blobs)
950 PyObject *py_blobs = NULL;
951 uint32_t i;
953 if (blobs == NULL) {
954 Py_RETURN_NONE;
957 py_blobs = PyList_New(blobs->num_blobs);
958 if (py_blobs == NULL) {
959 return NULL;
962 for (i=0; i<blobs->num_blobs; i++) {
963 struct smb2_create_blob *blob = &blobs->blobs[i];
964 PyObject *py_blob = NULL;
965 int ret;
967 py_blob = Py_BuildValue(
968 "(yy#)",
969 blob->tag,
970 blob->data.data,
971 (int)blob->data.length);
972 if (py_blob == NULL) {
973 goto fail;
976 ret = PyList_SetItem(py_blobs, i, py_blob);
977 if (ret == -1) {
978 Py_XDECREF(py_blob);
979 goto fail;
982 return py_blobs;
984 fail:
985 Py_XDECREF(py_blobs);
986 return NULL;
989 static PyObject *py_cli_create_returns(const struct smb_create_returns *r)
991 PyObject *v = NULL;
993 v = Py_BuildValue(
994 "{sLsLsLsLsLsLsLsLsLsL}",
995 "oplock_level",
996 (unsigned long long)r->oplock_level,
997 "flags",
998 (unsigned long long)r->flags,
999 "create_action",
1000 (unsigned long long)r->create_action,
1001 "creation_time",
1002 (unsigned long long)r->creation_time,
1003 "last_access_time",
1004 (unsigned long long)r->last_access_time,
1005 "last_write_time",
1006 (unsigned long long)r->last_write_time,
1007 "change_time",
1008 (unsigned long long)r->change_time,
1009 "allocation_size",
1010 (unsigned long long)r->allocation_size,
1011 "end_of_file",
1012 (unsigned long long)r->end_of_file,
1013 "file_attributes",
1014 (unsigned long long)r->file_attributes);
1015 return v;
1018 static PyObject *py_cli_symlink_error(const struct symlink_reparse_struct *s)
1020 char *subst_utf8 = NULL, *print_utf8 = NULL;
1021 size_t subst_utf8_len, print_utf8_len;
1022 PyObject *v = NULL;
1023 bool ok = true;
1026 * Python wants utf-8, regardless of our unix charset (which
1027 * most likely is utf-8 these days, but you never know).
1030 ok = convert_string_talloc(
1031 talloc_tos(),
1032 CH_UNIX,
1033 CH_UTF8,
1034 s->substitute_name,
1035 strlen(s->substitute_name),
1036 &subst_utf8,
1037 &subst_utf8_len);
1038 if (!ok) {
1039 goto fail;
1042 ok = convert_string_talloc(
1043 talloc_tos(),
1044 CH_UNIX,
1045 CH_UTF8,
1046 s->print_name,
1047 strlen(s->print_name),
1048 &print_utf8,
1049 &print_utf8_len);
1050 if (!ok) {
1051 goto fail;
1054 v = Py_BuildValue(
1055 "{sLsssssL}",
1056 "unparsed_path_length",
1057 (unsigned long long)s->unparsed_path_length,
1058 "substitute_name",
1059 subst_utf8,
1060 "print_name",
1061 print_utf8,
1062 "flags",
1063 (unsigned long long)s->flags);
1065 fail:
1066 TALLOC_FREE(subst_utf8);
1067 TALLOC_FREE(print_utf8);
1068 return v;
1071 static PyObject *py_cli_create_ex(
1072 struct py_cli_state *self, PyObject *args, PyObject *kwds)
1074 char *fname = NULL;
1075 unsigned CreateFlags = 0;
1076 unsigned DesiredAccess = FILE_GENERIC_READ;
1077 unsigned FileAttributes = 0;
1078 unsigned ShareAccess = 0;
1079 unsigned CreateDisposition = FILE_OPEN;
1080 unsigned CreateOptions = 0;
1081 unsigned ImpersonationLevel = SMB2_IMPERSONATION_IMPERSONATION;
1082 unsigned SecurityFlags = 0;
1083 PyObject *py_create_contexts_in = NULL;
1084 PyObject *py_create_contexts_out = NULL;
1085 struct smb2_create_blobs *create_contexts_in = NULL;
1086 struct smb2_create_blobs create_contexts_out = { .num_blobs = 0 };
1087 struct smb_create_returns cr = { .create_action = 0, };
1088 struct symlink_reparse_struct *symlink = NULL;
1089 PyObject *py_cr = NULL;
1090 uint16_t fnum;
1091 struct tevent_req *req;
1092 NTSTATUS status;
1093 int ret;
1094 bool ok;
1095 PyObject *v = NULL;
1097 static const char *kwlist[] = {
1098 "Name",
1099 "CreateFlags",
1100 "DesiredAccess",
1101 "FileAttributes",
1102 "ShareAccess",
1103 "CreateDisposition",
1104 "CreateOptions",
1105 "ImpersonationLevel",
1106 "SecurityFlags",
1107 "CreateContexts",
1108 NULL };
1110 ret = ParseTupleAndKeywords(
1111 args,
1112 kwds,
1113 "s|IIIIIIIIO",
1114 kwlist,
1115 &fname,
1116 &CreateFlags,
1117 &DesiredAccess,
1118 &FileAttributes,
1119 &ShareAccess,
1120 &CreateDisposition,
1121 &CreateOptions,
1122 &ImpersonationLevel,
1123 &SecurityFlags,
1124 &py_create_contexts_in);
1125 if (!ret) {
1126 return NULL;
1129 if (py_create_contexts_in != NULL) {
1130 create_contexts_in = py_cli_get_create_contexts(
1131 NULL, py_create_contexts_in);
1132 if (create_contexts_in == NULL) {
1133 errno = EINVAL;
1134 PyErr_SetFromErrno(PyExc_RuntimeError);
1135 return NULL;
1139 if (smbXcli_conn_protocol(self->cli->conn) >= PROTOCOL_SMB2_02) {
1140 struct cli_smb2_create_flags cflags = {
1141 .batch_oplock = (CreateFlags & REQUEST_BATCH_OPLOCK),
1142 .exclusive_oplock = (CreateFlags & REQUEST_OPLOCK),
1145 req = cli_smb2_create_fnum_send(
1146 NULL,
1147 self->ev,
1148 self->cli,
1149 fname,
1150 cflags,
1151 ImpersonationLevel,
1152 DesiredAccess,
1153 FileAttributes,
1154 ShareAccess,
1155 CreateDisposition,
1156 CreateOptions,
1157 create_contexts_in);
1158 } else {
1159 req = cli_ntcreate_send(
1160 NULL,
1161 self->ev,
1162 self->cli,
1163 fname,
1164 CreateFlags,
1165 DesiredAccess,
1166 FileAttributes,
1167 ShareAccess,
1168 CreateDisposition,
1169 CreateOptions,
1170 ImpersonationLevel,
1171 SecurityFlags);
1174 TALLOC_FREE(create_contexts_in);
1176 ok = py_tevent_req_wait_exc(self, req);
1177 if (!ok) {
1178 return NULL;
1181 if (smbXcli_conn_protocol(self->cli->conn) >= PROTOCOL_SMB2_02) {
1182 status = cli_smb2_create_fnum_recv(
1183 req,
1184 &fnum,
1185 &cr,
1186 NULL,
1187 &create_contexts_out,
1188 &symlink);
1189 } else {
1190 status = cli_ntcreate_recv(req, &fnum, &cr);
1193 TALLOC_FREE(req);
1195 if (!NT_STATUS_IS_OK(status)) {
1196 goto fail;
1199 SMB_ASSERT(symlink == NULL);
1201 py_create_contexts_out = py_cli_create_contexts(&create_contexts_out);
1202 TALLOC_FREE(create_contexts_out.blobs);
1203 if (py_create_contexts_out == NULL) {
1204 goto nomem;
1207 py_cr = py_cli_create_returns(&cr);
1208 if (py_cr == NULL) {
1209 goto nomem;
1212 v = PyTuple_New(3);
1213 if (v == NULL) {
1214 goto nomem;
1216 ret = PyTuple_SetItem(v, 0, Py_BuildValue("I", (unsigned)fnum));
1217 if (ret == -1) {
1218 status = NT_STATUS_INTERNAL_ERROR;
1219 goto fail;
1221 ret = PyTuple_SetItem(v, 1, py_cr);
1222 if (ret == -1) {
1223 status = NT_STATUS_INTERNAL_ERROR;
1224 goto fail;
1226 ret = PyTuple_SetItem(v, 2, py_create_contexts_out);
1227 if (ret == -1) {
1228 status = NT_STATUS_INTERNAL_ERROR;
1229 goto fail;
1232 return v;
1233 nomem:
1234 status = NT_STATUS_NO_MEMORY;
1235 fail:
1236 Py_XDECREF(py_create_contexts_out);
1237 Py_XDECREF(py_cr);
1238 Py_XDECREF(v);
1240 if (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK) &&
1241 (symlink != NULL)) {
1242 PyErr_SetObject(
1243 PyObject_GetAttrString(
1244 PyImport_ImportModule("samba"),
1245 "NTSTATUSError"),
1246 Py_BuildValue(
1247 "I,s,O",
1248 NT_STATUS_V(status),
1249 get_friendly_nt_error_msg(status),
1250 py_cli_symlink_error(symlink)));
1251 } else {
1252 PyErr_SetNTSTATUS(status);
1254 return NULL;
1257 static PyObject *py_cli_close(struct py_cli_state *self, PyObject *args)
1259 struct tevent_req *req;
1260 int fnum;
1261 NTSTATUS status;
1263 if (!PyArg_ParseTuple(args, "i", &fnum)) {
1264 return NULL;
1267 req = cli_close_send(NULL, self->ev, self->cli, fnum);
1268 if (!py_tevent_req_wait_exc(self, req)) {
1269 return NULL;
1271 status = cli_close_recv(req);
1272 TALLOC_FREE(req);
1274 if (!NT_STATUS_IS_OK(status)) {
1275 PyErr_SetNTSTATUS(status);
1276 return NULL;
1278 Py_RETURN_NONE;
1281 static PyObject *py_cli_rename(
1282 struct py_cli_state *self, PyObject *args, PyObject *kwds)
1284 char *fname_src = NULL, *fname_dst = NULL;
1285 int replace = false;
1286 struct tevent_req *req = NULL;
1287 NTSTATUS status;
1288 bool ok;
1290 static const char *kwlist[] = { "src", "dst", "replace", NULL };
1292 ok = ParseTupleAndKeywords(
1293 args, kwds, "ss|p", kwlist, &fname_src, &fname_dst, &replace);
1294 if (!ok) {
1295 return NULL;
1298 req = cli_rename_send(
1299 NULL, self->ev, self->cli, fname_src, fname_dst, replace);
1300 if (!py_tevent_req_wait_exc(self, req)) {
1301 return NULL;
1303 status = cli_rename_recv(req);
1304 TALLOC_FREE(req);
1306 if (!NT_STATUS_IS_OK(status)) {
1307 PyErr_SetNTSTATUS(status);
1308 return NULL;
1310 Py_RETURN_NONE;
1314 struct push_state {
1315 char *data;
1316 off_t nread;
1317 off_t total_data;
1321 * cli_push() helper to write a chunk of data to a remote file
1323 static size_t push_data(uint8_t *buf, size_t n, void *priv)
1325 struct push_state *state = (struct push_state *)priv;
1326 char *curr_ptr = NULL;
1327 off_t remaining;
1328 size_t copied_bytes;
1330 if (state->nread >= state->total_data) {
1331 return 0;
1334 curr_ptr = state->data + state->nread;
1335 remaining = state->total_data - state->nread;
1336 copied_bytes = MIN(remaining, n);
1338 memcpy(buf, curr_ptr, copied_bytes);
1339 state->nread += copied_bytes;
1340 return copied_bytes;
1344 * Writes a file with the contents specified
1346 static PyObject *py_smb_savefile(struct py_cli_state *self, PyObject *args)
1348 uint16_t fnum;
1349 const char *filename = NULL;
1350 char *data = NULL;
1351 Py_ssize_t size = 0;
1352 NTSTATUS status;
1353 struct tevent_req *req = NULL;
1354 struct push_state state;
1356 if (!PyArg_ParseTuple(args, "s"PYARG_BYTES_LEN":savefile", &filename,
1357 &data, &size)) {
1358 return NULL;
1361 /* create a new file handle for writing to */
1362 req = cli_ntcreate_send(NULL, self->ev, self->cli, filename, 0,
1363 FILE_WRITE_DATA, FILE_ATTRIBUTE_NORMAL,
1364 FILE_SHARE_READ|FILE_SHARE_WRITE,
1365 FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE,
1366 SMB2_IMPERSONATION_IMPERSONATION, 0);
1367 if (!py_tevent_req_wait_exc(self, req)) {
1368 return NULL;
1370 status = cli_ntcreate_recv(req, &fnum, NULL);
1371 TALLOC_FREE(req);
1372 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1374 /* write the new file contents */
1375 state.data = data;
1376 state.nread = 0;
1377 state.total_data = size;
1379 req = cli_push_send(NULL, self->ev, self->cli, fnum, 0, 0, 0,
1380 push_data, &state);
1381 if (!py_tevent_req_wait_exc(self, req)) {
1382 return NULL;
1384 status = cli_push_recv(req);
1385 TALLOC_FREE(req);
1386 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1388 /* close the file handle */
1389 req = cli_close_send(NULL, self->ev, self->cli, fnum);
1390 if (!py_tevent_req_wait_exc(self, req)) {
1391 return NULL;
1393 status = cli_close_recv(req);
1394 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1396 Py_RETURN_NONE;
1399 static PyObject *py_cli_write(struct py_cli_state *self, PyObject *args,
1400 PyObject *kwds)
1402 int fnum;
1403 unsigned mode = 0;
1404 char *buf;
1405 Py_ssize_t buflen;
1406 unsigned long long offset;
1407 struct tevent_req *req;
1408 NTSTATUS status;
1409 size_t written;
1411 static const char *kwlist[] = {
1412 "fnum", "buffer", "offset", "mode", NULL };
1414 if (!ParseTupleAndKeywords(
1415 args, kwds, "i" PYARG_BYTES_LEN "K|I", kwlist,
1416 &fnum, &buf, &buflen, &offset, &mode)) {
1417 return NULL;
1420 req = cli_write_send(NULL, self->ev, self->cli, fnum, mode,
1421 (uint8_t *)buf, offset, buflen);
1422 if (!py_tevent_req_wait_exc(self, req)) {
1423 return NULL;
1425 status = cli_write_recv(req, &written);
1426 TALLOC_FREE(req);
1428 if (!NT_STATUS_IS_OK(status)) {
1429 PyErr_SetNTSTATUS(status);
1430 return NULL;
1432 return Py_BuildValue("K", (unsigned long long)written);
1436 * Returns the size of the given file
1438 static NTSTATUS py_smb_filesize(struct py_cli_state *self, uint16_t fnum,
1439 off_t *size)
1441 NTSTATUS status;
1442 struct tevent_req *req = NULL;
1444 req = cli_qfileinfo_basic_send(NULL, self->ev, self->cli, fnum);
1445 if (!py_tevent_req_wait_exc(self, req)) {
1446 return NT_STATUS_INTERNAL_ERROR;
1448 status = cli_qfileinfo_basic_recv(
1449 req, NULL, size, NULL, NULL, NULL, NULL, NULL);
1450 TALLOC_FREE(req);
1451 return status;
1455 * Loads the specified file's contents and returns it
1457 static PyObject *py_smb_loadfile(struct py_cli_state *self, PyObject *args)
1459 NTSTATUS status;
1460 const char *filename = NULL;
1461 struct tevent_req *req = NULL;
1462 uint16_t fnum;
1463 off_t size;
1464 char *buf = NULL;
1465 off_t nread = 0;
1466 PyObject *result = NULL;
1468 if (!PyArg_ParseTuple(args, "s:loadfile", &filename)) {
1469 return NULL;
1472 /* get a read file handle */
1473 req = cli_ntcreate_send(NULL, self->ev, self->cli, filename, 0,
1474 FILE_READ_DATA | FILE_READ_ATTRIBUTES,
1475 FILE_ATTRIBUTE_NORMAL,
1476 FILE_SHARE_READ, FILE_OPEN, 0,
1477 SMB2_IMPERSONATION_IMPERSONATION, 0);
1478 if (!py_tevent_req_wait_exc(self, req)) {
1479 return NULL;
1481 status = cli_ntcreate_recv(req, &fnum, NULL);
1482 TALLOC_FREE(req);
1483 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1485 /* get a buffer to hold the file contents */
1486 status = py_smb_filesize(self, fnum, &size);
1487 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1489 result = PyBytes_FromStringAndSize(NULL, size);
1490 if (result == NULL) {
1491 return NULL;
1494 /* read the file contents */
1495 buf = PyBytes_AS_STRING(result);
1496 req = cli_pull_send(NULL, self->ev, self->cli, fnum, 0, size,
1497 size, cli_read_sink, &buf);
1498 if (!py_tevent_req_wait_exc(self, req)) {
1499 Py_XDECREF(result);
1500 return NULL;
1502 status = cli_pull_recv(req, &nread);
1503 TALLOC_FREE(req);
1504 if (!NT_STATUS_IS_OK(status)) {
1505 Py_XDECREF(result);
1506 PyErr_SetNTSTATUS(status);
1507 return NULL;
1510 /* close the file handle */
1511 req = cli_close_send(NULL, self->ev, self->cli, fnum);
1512 if (!py_tevent_req_wait_exc(self, req)) {
1513 Py_XDECREF(result);
1514 return NULL;
1516 status = cli_close_recv(req);
1517 TALLOC_FREE(req);
1518 if (!NT_STATUS_IS_OK(status)) {
1519 Py_XDECREF(result);
1520 PyErr_SetNTSTATUS(status);
1521 return NULL;
1524 /* sanity-check we read the expected number of bytes */
1525 if (nread > size) {
1526 Py_XDECREF(result);
1527 PyErr_Format(PyExc_IOError,
1528 "read invalid - got %zu requested %zu",
1529 nread, size);
1530 return NULL;
1533 if (nread < size) {
1534 if (_PyBytes_Resize(&result, nread) < 0) {
1535 return NULL;
1539 return result;
1542 static PyObject *py_cli_read(struct py_cli_state *self, PyObject *args,
1543 PyObject *kwds)
1545 int fnum;
1546 unsigned long long offset;
1547 unsigned size;
1548 struct tevent_req *req;
1549 NTSTATUS status;
1550 char *buf;
1551 size_t received;
1552 PyObject *result;
1554 static const char *kwlist[] = {
1555 "fnum", "offset", "size", NULL };
1557 if (!ParseTupleAndKeywords(
1558 args, kwds, "iKI", kwlist, &fnum, &offset,
1559 &size)) {
1560 return NULL;
1563 result = PyBytes_FromStringAndSize(NULL, size);
1564 if (result == NULL) {
1565 return NULL;
1567 buf = PyBytes_AS_STRING(result);
1569 req = cli_read_send(NULL, self->ev, self->cli, fnum,
1570 buf, offset, size);
1571 if (!py_tevent_req_wait_exc(self, req)) {
1572 Py_XDECREF(result);
1573 return NULL;
1575 status = cli_read_recv(req, &received);
1576 TALLOC_FREE(req);
1578 if (!NT_STATUS_IS_OK(status)) {
1579 Py_XDECREF(result);
1580 PyErr_SetNTSTATUS(status);
1581 return NULL;
1584 if (received > size) {
1585 Py_XDECREF(result);
1586 PyErr_Format(PyExc_IOError,
1587 "read invalid - got %zu requested %u",
1588 received, size);
1589 return NULL;
1592 if (received < size) {
1593 if (_PyBytes_Resize(&result, received) < 0) {
1594 return NULL;
1598 return result;
1601 static PyObject *py_cli_ftruncate(struct py_cli_state *self, PyObject *args,
1602 PyObject *kwds)
1604 int fnum;
1605 unsigned long long size;
1606 struct tevent_req *req;
1607 NTSTATUS status;
1609 static const char *kwlist[] = {
1610 "fnum", "size", NULL };
1612 if (!ParseTupleAndKeywords(
1613 args, kwds, "IK", kwlist, &fnum, &size)) {
1614 return NULL;
1617 req = cli_ftruncate_send(NULL, self->ev, self->cli, fnum, size);
1618 if (!py_tevent_req_wait_exc(self, req)) {
1619 return NULL;
1621 status = cli_ftruncate_recv(req);
1622 TALLOC_FREE(req);
1624 if (!NT_STATUS_IS_OK(status)) {
1625 PyErr_SetNTSTATUS(status);
1626 return NULL;
1628 Py_RETURN_NONE;
1631 static PyObject *py_cli_delete_on_close(struct py_cli_state *self,
1632 PyObject *args,
1633 PyObject *kwds)
1635 unsigned fnum, flag;
1636 struct tevent_req *req;
1637 NTSTATUS status;
1639 static const char *kwlist[] = {
1640 "fnum", "flag", NULL };
1642 if (!ParseTupleAndKeywords(
1643 args, kwds, "II", kwlist, &fnum, &flag)) {
1644 return NULL;
1647 req = cli_nt_delete_on_close_send(NULL, self->ev, self->cli, fnum,
1648 flag);
1649 if (!py_tevent_req_wait_exc(self, req)) {
1650 return NULL;
1652 status = cli_nt_delete_on_close_recv(req);
1653 TALLOC_FREE(req);
1655 if (!NT_STATUS_IS_OK(status)) {
1656 PyErr_SetNTSTATUS(status);
1657 return NULL;
1659 Py_RETURN_NONE;
1662 struct py_cli_notify_state {
1663 PyObject_HEAD
1664 struct py_cli_state *py_cli_state;
1665 struct tevent_req *req;
1668 static void py_cli_notify_state_dealloc(struct py_cli_notify_state *self)
1670 TALLOC_FREE(self->req);
1671 Py_CLEAR(self->py_cli_state);
1672 Py_TYPE(self)->tp_free(self);
1675 static PyTypeObject py_cli_notify_state_type;
1677 static PyObject *py_cli_notify(struct py_cli_state *self,
1678 PyObject *args,
1679 PyObject *kwds)
1681 static const char *kwlist[] = {
1682 "fnum",
1683 "buffer_size",
1684 "completion_filter",
1685 "recursive",
1686 NULL
1688 unsigned fnum = 0;
1689 unsigned buffer_size = 0;
1690 unsigned completion_filter = 0;
1691 PyObject *py_recursive = Py_False;
1692 bool recursive = false;
1693 struct tevent_req *req = NULL;
1694 struct tevent_queue *send_queue = NULL;
1695 struct tevent_req *flush_req = NULL;
1696 bool ok;
1697 struct py_cli_notify_state *py_notify_state = NULL;
1698 struct timeval endtime;
1700 ok = ParseTupleAndKeywords(args,
1701 kwds,
1702 "IIIO",
1703 kwlist,
1704 &fnum,
1705 &buffer_size,
1706 &completion_filter,
1707 &py_recursive);
1708 if (!ok) {
1709 return NULL;
1712 recursive = PyObject_IsTrue(py_recursive);
1714 req = cli_notify_send(NULL,
1715 self->ev,
1716 self->cli,
1717 fnum,
1718 buffer_size,
1719 completion_filter,
1720 recursive);
1721 if (req == NULL) {
1722 PyErr_NoMemory();
1723 return NULL;
1727 * Just wait for the request being submitted to
1728 * the kernel/socket/wire.
1730 send_queue = smbXcli_conn_send_queue(self->cli->conn);
1731 flush_req = tevent_queue_wait_send(req,
1732 self->ev,
1733 send_queue);
1734 endtime = timeval_current_ofs_msec(self->cli->timeout);
1735 ok = tevent_req_set_endtime(flush_req,
1736 self->ev,
1737 endtime);
1738 if (!ok) {
1739 TALLOC_FREE(req);
1740 PyErr_NoMemory();
1741 return NULL;
1743 ok = py_tevent_req_wait_exc(self, flush_req);
1744 if (!ok) {
1745 TALLOC_FREE(req);
1746 return NULL;
1748 TALLOC_FREE(flush_req);
1750 py_notify_state = (struct py_cli_notify_state *)
1751 py_cli_notify_state_type.tp_alloc(&py_cli_notify_state_type, 0);
1752 if (py_notify_state == NULL) {
1753 TALLOC_FREE(req);
1754 PyErr_NoMemory();
1755 return NULL;
1757 Py_INCREF(self);
1758 py_notify_state->py_cli_state = self;
1759 py_notify_state->req = req;
1761 return (PyObject *)py_notify_state;
1764 static PyObject *py_cli_notify_get_changes(struct py_cli_notify_state *self,
1765 PyObject *args,
1766 PyObject *kwds)
1768 struct py_cli_state *py_cli_state = self->py_cli_state;
1769 struct tevent_req *req = self->req;
1770 uint32_t i;
1771 uint32_t num_changes = 0;
1772 struct notify_change *changes = NULL;
1773 PyObject *result = NULL;
1774 NTSTATUS status;
1775 bool ok;
1776 static const char *kwlist[] = {
1777 "wait",
1778 NULL
1780 PyObject *py_wait = Py_False;
1781 bool wait = false;
1782 bool pending;
1784 ok = ParseTupleAndKeywords(args,
1785 kwds,
1786 "O",
1787 kwlist,
1788 &py_wait);
1789 if (!ok) {
1790 return NULL;
1793 wait = PyObject_IsTrue(py_wait);
1795 if (req == NULL) {
1796 PyErr_SetString(PyExc_RuntimeError,
1797 "TODO req == NULL "
1798 "- missing change notify request?");
1799 return NULL;
1802 pending = tevent_req_is_in_progress(req);
1803 if (pending && !wait) {
1804 Py_RETURN_NONE;
1807 if (pending) {
1808 struct timeval endtime;
1810 endtime = timeval_current_ofs_msec(py_cli_state->cli->timeout);
1811 ok = tevent_req_set_endtime(req,
1812 py_cli_state->ev,
1813 endtime);
1814 if (!ok) {
1815 TALLOC_FREE(req);
1816 PyErr_NoMemory();
1817 return NULL;
1821 ok = py_tevent_req_wait_exc(py_cli_state, req);
1822 self->req = NULL;
1823 Py_CLEAR(self->py_cli_state);
1824 if (!ok) {
1825 return NULL;
1828 status = cli_notify_recv(req, req, &num_changes, &changes);
1829 if (!NT_STATUS_IS_OK(status)) {
1830 TALLOC_FREE(req);
1831 PyErr_SetNTSTATUS(status);
1832 return NULL;
1835 result = Py_BuildValue("[]");
1836 if (result == NULL) {
1837 TALLOC_FREE(req);
1838 return NULL;
1841 for (i = 0; i < num_changes; i++) {
1842 PyObject *change = NULL;
1843 int ret;
1845 change = Py_BuildValue("{s:s,s:I}",
1846 "name", changes[i].name,
1847 "action", changes[i].action);
1848 if (change == NULL) {
1849 Py_XDECREF(result);
1850 TALLOC_FREE(req);
1851 return NULL;
1854 ret = PyList_Append(result, change);
1855 Py_DECREF(change);
1856 if (ret == -1) {
1857 Py_XDECREF(result);
1858 TALLOC_FREE(req);
1859 return NULL;
1863 TALLOC_FREE(req);
1864 return result;
1867 static PyMethodDef py_cli_notify_state_methods[] = {
1869 .ml_name = "get_changes",
1870 .ml_meth = (PyCFunction)py_cli_notify_get_changes,
1871 .ml_flags = METH_VARARGS|METH_KEYWORDS,
1872 .ml_doc = "Wait for change notifications: \n"
1873 "N.get_changes(wait=BOOLEAN) -> "
1874 "change notifications as a dictionary\n"
1875 "\t\tList contents of a directory. The keys are, \n"
1876 "\t\t\tname: name of changed object\n"
1877 "\t\t\taction: type of the change\n"
1878 "None is returned if there's no response jet and "
1879 "wait=False is passed"
1882 .ml_name = NULL
1886 static PyTypeObject py_cli_notify_state_type = {
1887 PyVarObject_HEAD_INIT(NULL, 0)
1888 .tp_name = "libsmb_samba_cwrapper.Notify",
1889 .tp_basicsize = sizeof(struct py_cli_notify_state),
1890 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1891 .tp_doc = "notify request",
1892 .tp_dealloc = (destructor)py_cli_notify_state_dealloc,
1893 .tp_methods = py_cli_notify_state_methods,
1897 * Helper to add posix directory listing entries to an overall Python list
1899 static NTSTATUS list_posix_helper(struct file_info *finfo,
1900 const char *mask, void *state)
1902 PyObject *result = (PyObject *)state;
1903 PyObject *file = NULL;
1904 PyObject *size = NULL;
1905 int ret;
1907 size = PyLong_FromUnsignedLongLong(finfo->size);
1909 * Build a dictionary representing the file info.
1910 * Note: Windows does not always return short_name (so it may be None)
1912 file = Py_BuildValue("{s:s,s:i,s:s,s:O,s:l,s:i,s:i,s:i,s:s,s:s}",
1913 "name", finfo->name,
1914 "attrib", (int)finfo->attr,
1915 "short_name", finfo->short_name,
1916 "size", size,
1917 "mtime",
1918 convert_timespec_to_time_t(finfo->mtime_ts),
1919 "perms", finfo->st_ex_mode,
1920 "ino", finfo->ino,
1921 "dev", finfo->st_ex_dev,
1922 "owner_sid",
1923 dom_sid_string(finfo, &finfo->owner_sid),
1924 "group_sid",
1925 dom_sid_string(finfo, &finfo->group_sid));
1927 Py_CLEAR(size);
1929 if (file == NULL) {
1930 return NT_STATUS_NO_MEMORY;
1933 ret = PyList_Append(result, file);
1934 Py_CLEAR(file);
1935 if (ret == -1) {
1936 return NT_STATUS_INTERNAL_ERROR;
1939 return NT_STATUS_OK;
1943 * Helper to add directory listing entries to an overall Python list
1945 static NTSTATUS list_helper(struct file_info *finfo,
1946 const char *mask, void *state)
1948 PyObject *result = (PyObject *)state;
1949 PyObject *file = NULL;
1950 PyObject *size = NULL;
1951 int ret;
1953 /* suppress '.' and '..' in the results we return */
1954 if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
1955 return NT_STATUS_OK;
1957 size = PyLong_FromUnsignedLongLong(finfo->size);
1959 * Build a dictionary representing the file info.
1960 * Note: Windows does not always return short_name (so it may be None)
1962 file = Py_BuildValue("{s:s,s:i,s:s,s:O,s:l}",
1963 "name", finfo->name,
1964 "attrib", (int)finfo->attr,
1965 "short_name", finfo->short_name,
1966 "size", size,
1967 "mtime",
1968 convert_timespec_to_time_t(finfo->mtime_ts));
1970 Py_CLEAR(size);
1972 if (file == NULL) {
1973 return NT_STATUS_NO_MEMORY;
1976 if (finfo->attr & FILE_ATTRIBUTE_REPARSE_POINT) {
1977 unsigned long tag = finfo->reparse_tag;
1979 ret = PyDict_SetItemString(
1980 file,
1981 "reparse_tag",
1982 PyLong_FromUnsignedLong(tag));
1983 if (ret == -1) {
1984 return NT_STATUS_INTERNAL_ERROR;
1988 ret = PyList_Append(result, file);
1989 Py_CLEAR(file);
1990 if (ret == -1) {
1991 return NT_STATUS_INTERNAL_ERROR;
1994 return NT_STATUS_OK;
1997 struct do_listing_state {
1998 const char *mask;
1999 NTSTATUS (*callback_fn)(
2000 struct file_info *finfo,
2001 const char *mask,
2002 void *private_data);
2003 void *private_data;
2004 NTSTATUS status;
2007 static void do_listing_cb(struct tevent_req *subreq)
2009 struct do_listing_state *state = tevent_req_callback_data_void(subreq);
2010 struct file_info *finfo = NULL;
2012 state->status = cli_list_recv(subreq, NULL, &finfo);
2013 if (!NT_STATUS_IS_OK(state->status)) {
2014 return;
2016 state->callback_fn(finfo, state->mask, state->private_data);
2017 TALLOC_FREE(finfo);
2020 static NTSTATUS do_listing(struct py_cli_state *self,
2021 const char *base_dir, const char *user_mask,
2022 uint16_t attribute,
2023 unsigned int info_level,
2024 bool posix,
2025 NTSTATUS (*callback_fn)(struct file_info *,
2026 const char *, void *),
2027 void *priv)
2029 char *mask = NULL;
2030 struct do_listing_state state = {
2031 .mask = mask,
2032 .callback_fn = callback_fn,
2033 .private_data = priv,
2035 struct tevent_req *req = NULL;
2036 NTSTATUS status;
2038 if (user_mask == NULL) {
2039 mask = talloc_asprintf(NULL, "%s\\*", base_dir);
2040 } else {
2041 mask = talloc_asprintf(NULL, "%s\\%s", base_dir, user_mask);
2044 if (mask == NULL) {
2045 return NT_STATUS_NO_MEMORY;
2047 dos_format(mask);
2049 req = cli_list_send(NULL, self->ev, self->cli, mask, attribute,
2050 info_level, posix);
2051 if (req == NULL) {
2052 status = NT_STATUS_NO_MEMORY;
2053 goto done;
2055 tevent_req_set_callback(req, do_listing_cb, &state);
2057 if (!py_tevent_req_wait_exc(self, req)) {
2058 return NT_STATUS_INTERNAL_ERROR;
2060 TALLOC_FREE(req);
2062 status = state.status;
2063 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MORE_FILES)) {
2064 status = NT_STATUS_OK;
2067 done:
2068 TALLOC_FREE(mask);
2069 return status;
2072 static PyObject *py_cli_list(struct py_cli_state *self,
2073 PyObject *args,
2074 PyObject *kwds)
2076 char *base_dir;
2077 char *user_mask = NULL;
2078 unsigned int attribute = LIST_ATTRIBUTE_MASK;
2079 unsigned int info_level = 0;
2080 bool posix = false;
2081 NTSTATUS status;
2082 enum protocol_types proto = smbXcli_conn_protocol(self->cli->conn);
2083 PyObject *result = NULL;
2084 const char *kwlist[] = { "directory", "mask", "attribs", "posix",
2085 "info_level", NULL };
2086 NTSTATUS (*callback_fn)(struct file_info *, const char *, void *) =
2087 &list_helper;
2089 if (!ParseTupleAndKeywords(args, kwds, "z|sIpI:list", kwlist,
2090 &base_dir, &user_mask, &attribute,
2091 &posix, &info_level)) {
2092 return NULL;
2095 result = Py_BuildValue("[]");
2096 if (result == NULL) {
2097 return NULL;
2100 if (!info_level) {
2101 if (proto >= PROTOCOL_SMB2_02) {
2102 info_level = SMB2_FIND_ID_BOTH_DIRECTORY_INFO;
2103 } else {
2104 info_level = SMB_FIND_FILE_BOTH_DIRECTORY_INFO;
2108 if (posix) {
2109 callback_fn = &list_posix_helper;
2111 status = do_listing(self, base_dir, user_mask, attribute,
2112 info_level, posix, callback_fn, result);
2114 if (!NT_STATUS_IS_OK(status)) {
2115 Py_XDECREF(result);
2116 PyErr_SetNTSTATUS(status);
2117 return NULL;
2120 return result;
2123 static PyObject *py_smb_unlink(struct py_cli_state *self, PyObject *args)
2125 NTSTATUS status;
2126 const char *filename = NULL;
2127 struct tevent_req *req = NULL;
2128 const uint32_t attrs = (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
2130 if (!PyArg_ParseTuple(args, "s:unlink", &filename)) {
2131 return NULL;
2134 req = cli_unlink_send(NULL, self->ev, self->cli, filename, attrs);
2135 if (!py_tevent_req_wait_exc(self, req)) {
2136 return NULL;
2138 status = cli_unlink_recv(req);
2139 TALLOC_FREE(req);
2140 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2142 Py_RETURN_NONE;
2145 static PyObject *py_smb_rmdir(struct py_cli_state *self, PyObject *args)
2147 NTSTATUS status;
2148 struct tevent_req *req = NULL;
2149 const char *dirname = NULL;
2151 if (!PyArg_ParseTuple(args, "s:rmdir", &dirname)) {
2152 return NULL;
2155 req = cli_rmdir_send(NULL, self->ev, self->cli, dirname);
2156 if (!py_tevent_req_wait_exc(self, req)) {
2157 return NULL;
2159 status = cli_rmdir_recv(req);
2160 TALLOC_FREE(req);
2161 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2163 Py_RETURN_NONE;
2167 * Create a directory
2169 static PyObject *py_smb_mkdir(struct py_cli_state *self, PyObject *args)
2171 NTSTATUS status;
2172 const char *dirname = NULL;
2173 struct tevent_req *req = NULL;
2175 if (!PyArg_ParseTuple(args, "s:mkdir", &dirname)) {
2176 return NULL;
2179 req = cli_mkdir_send(NULL, self->ev, self->cli, dirname);
2180 if (!py_tevent_req_wait_exc(self, req)) {
2181 return NULL;
2183 status = cli_mkdir_recv(req);
2184 TALLOC_FREE(req);
2185 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2187 Py_RETURN_NONE;
2191 * Does a whoami call
2193 static PyObject *py_smb_posix_whoami(struct py_cli_state *self,
2194 PyObject *Py_UNUSED(ignored))
2196 TALLOC_CTX *frame = talloc_stackframe();
2197 NTSTATUS status;
2198 struct tevent_req *req = NULL;
2199 uint64_t uid;
2200 uint64_t gid;
2201 uint32_t num_gids;
2202 uint64_t *gids = NULL;
2203 uint32_t num_sids;
2204 struct dom_sid *sids = NULL;
2205 bool guest;
2206 PyObject *py_gids = NULL;
2207 PyObject *py_sids = NULL;
2208 PyObject *py_guest = NULL;
2209 PyObject *py_ret = NULL;
2210 Py_ssize_t i;
2212 req = cli_posix_whoami_send(frame, self->ev, self->cli);
2213 if (!py_tevent_req_wait_exc(self, req)) {
2214 goto fail;
2216 status = cli_posix_whoami_recv(req,
2217 frame,
2218 &uid,
2219 &gid,
2220 &num_gids,
2221 &gids,
2222 &num_sids,
2223 &sids,
2224 &guest);
2225 if (!NT_STATUS_IS_OK(status)) {
2226 PyErr_SetNTSTATUS(status);
2227 goto fail;
2229 if (num_gids > PY_SSIZE_T_MAX) {
2230 PyErr_SetString(PyExc_OverflowError, "posix_whoami: Too many GIDs");
2231 goto fail;
2233 if (num_sids > PY_SSIZE_T_MAX) {
2234 PyErr_SetString(PyExc_OverflowError, "posix_whoami: Too many SIDs");
2235 goto fail;
2238 py_gids = PyList_New(num_gids);
2239 if (!py_gids) {
2240 goto fail;
2242 for (i = 0; i < num_gids; ++i) {
2243 int ret;
2244 PyObject *py_item = PyLong_FromUnsignedLongLong(gids[i]);
2245 if (!py_item) {
2246 goto fail2;
2249 ret = PyList_SetItem(py_gids, i, py_item);
2250 if (ret) {
2251 goto fail2;
2254 py_sids = PyList_New(num_sids);
2255 if (!py_sids) {
2256 goto fail2;
2258 for (i = 0; i < num_sids; ++i) {
2259 int ret;
2260 struct dom_sid *sid;
2261 PyObject *py_item;
2263 sid = dom_sid_dup(frame, &sids[i]);
2264 if (!sid) {
2265 PyErr_NoMemory();
2266 goto fail3;
2269 py_item = pytalloc_steal(dom_sid_Type, sid);
2270 if (!py_item) {
2271 PyErr_NoMemory();
2272 goto fail3;
2275 ret = PyList_SetItem(py_sids, i, py_item);
2276 if (ret) {
2277 goto fail3;
2281 py_guest = guest ? Py_True : Py_False;
2283 py_ret = Py_BuildValue("KKNNO",
2284 uid,
2285 gid,
2286 py_gids,
2287 py_sids,
2288 py_guest);
2289 if (!py_ret) {
2290 goto fail3;
2293 TALLOC_FREE(frame);
2294 return py_ret;
2296 fail3:
2297 Py_CLEAR(py_sids);
2299 fail2:
2300 Py_CLEAR(py_gids);
2302 fail:
2303 TALLOC_FREE(frame);
2304 return NULL;
2308 * Checks existence of a directory
2310 static bool check_dir_path(struct py_cli_state *self, const char *path)
2312 NTSTATUS status;
2313 struct tevent_req *req = NULL;
2315 req = cli_chkpath_send(NULL, self->ev, self->cli, path);
2316 if (!py_tevent_req_wait_exc(self, req)) {
2317 return false;
2319 status = cli_chkpath_recv(req);
2320 TALLOC_FREE(req);
2322 return NT_STATUS_IS_OK(status);
2325 static PyObject *py_smb_chkpath(struct py_cli_state *self, PyObject *args)
2327 const char *path = NULL;
2328 bool dir_exists;
2330 if (!PyArg_ParseTuple(args, "s:chkpath", &path)) {
2331 return NULL;
2334 dir_exists = check_dir_path(self, path);
2335 return PyBool_FromLong(dir_exists);
2338 static PyObject *py_smb_have_posix(struct py_cli_state *self,
2339 PyObject *Py_UNUSED(ignored))
2341 bool posix = smbXcli_conn_have_posix(self->cli->conn);
2343 if (posix) {
2344 Py_RETURN_TRUE;
2346 Py_RETURN_FALSE;
2349 static PyObject *py_smb_protocol(struct py_cli_state *self,
2350 PyObject *Py_UNUSED(ignored))
2352 enum protocol_types proto = smbXcli_conn_protocol(self->cli->conn);
2353 PyObject *result = PyLong_FromLong(proto);
2354 return result;
2357 static PyObject *py_smb_get_sd(struct py_cli_state *self, PyObject *args)
2359 int fnum;
2360 unsigned sinfo;
2361 struct tevent_req *req = NULL;
2362 struct security_descriptor *sd = NULL;
2363 NTSTATUS status;
2365 if (!PyArg_ParseTuple(args, "iI:get_acl", &fnum, &sinfo)) {
2366 return NULL;
2369 req = cli_query_security_descriptor_send(
2370 NULL, self->ev, self->cli, fnum, sinfo);
2371 if (!py_tevent_req_wait_exc(self, req)) {
2372 return NULL;
2374 status = cli_query_security_descriptor_recv(req, NULL, &sd);
2375 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2377 return py_return_ndr_struct(
2378 "samba.dcerpc.security", "descriptor", sd, sd);
2381 static PyObject *py_smb_set_sd(struct py_cli_state *self, PyObject *args)
2383 PyObject *py_sd = NULL;
2384 struct tevent_req *req = NULL;
2385 struct security_descriptor *sd = NULL;
2386 uint16_t fnum;
2387 unsigned int sinfo;
2388 NTSTATUS status;
2390 if (!PyArg_ParseTuple(args, "iOI:set_sd", &fnum, &py_sd, &sinfo)) {
2391 return NULL;
2394 sd = pytalloc_get_type(py_sd, struct security_descriptor);
2395 if (!sd) {
2396 PyErr_Format(PyExc_TypeError,
2397 "Expected dcerpc.security.descriptor as argument, got %s",
2398 pytalloc_get_name(py_sd));
2399 return NULL;
2402 req = cli_set_security_descriptor_send(
2403 NULL, self->ev, self->cli, fnum, sinfo, sd);
2404 if (!py_tevent_req_wait_exc(self, req)) {
2405 return NULL;
2408 status = cli_set_security_descriptor_recv(req);
2409 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2411 Py_RETURN_NONE;
2414 static PyObject *py_smb_smb1_posix(
2415 struct py_cli_state *self, PyObject *Py_UNUSED(ignored))
2417 NTSTATUS status;
2418 struct tevent_req *req = NULL;
2419 uint16_t major, minor;
2420 uint32_t caplow, caphigh;
2421 PyObject *result = NULL;
2423 req = cli_unix_extensions_version_send(NULL, self->ev, self->cli);
2424 if (!py_tevent_req_wait_exc(self, req)) {
2425 return NULL;
2427 status = cli_unix_extensions_version_recv(
2428 req, &major, &minor, &caplow, &caphigh);
2429 TALLOC_FREE(req);
2430 if (!NT_STATUS_IS_OK(status)) {
2431 PyErr_SetNTSTATUS(status);
2432 return NULL;
2435 req = cli_set_unix_extensions_capabilities_send(
2436 NULL, self->ev, self->cli, major, minor, caplow, caphigh);
2437 if (!py_tevent_req_wait_exc(self, req)) {
2438 return NULL;
2440 status = cli_set_unix_extensions_capabilities_recv(req);
2441 TALLOC_FREE(req);
2442 if (!NT_STATUS_IS_OK(status)) {
2443 PyErr_SetNTSTATUS(status);
2444 return NULL;
2447 result = Py_BuildValue(
2448 "[IIII]",
2449 (unsigned)minor,
2450 (unsigned)major,
2451 (unsigned)caplow,
2452 (unsigned)caphigh);
2453 return result;
2456 static PyObject *py_smb_smb1_readlink(
2457 struct py_cli_state *self, PyObject *args)
2459 NTSTATUS status;
2460 const char *filename = NULL;
2461 struct tevent_req *req = NULL;
2462 char *target = NULL;
2463 PyObject *result = NULL;
2465 if (!PyArg_ParseTuple(args, "s:smb1_readlink", &filename)) {
2466 return NULL;
2469 req = cli_posix_readlink_send(NULL, self->ev, self->cli, filename);
2470 if (!py_tevent_req_wait_exc(self, req)) {
2471 return NULL;
2473 status = cli_posix_readlink_recv(req, NULL, &target);
2474 TALLOC_FREE(req);
2475 if (!NT_STATUS_IS_OK(status)) {
2476 PyErr_SetNTSTATUS(status);
2477 return NULL;
2480 result = PyBytes_FromString(target);
2481 TALLOC_FREE(target);
2482 return result;
2485 static PyObject *py_smb_smb1_symlink(
2486 struct py_cli_state *self, PyObject *args)
2488 NTSTATUS status;
2489 const char *target = NULL, *newname = NULL;
2490 struct tevent_req *req = NULL;
2492 if (!PyArg_ParseTuple(args, "ss:smb1_symlink", &target, &newname)) {
2493 return NULL;
2496 req = cli_posix_symlink_send(
2497 NULL, self->ev, self->cli, target, newname);
2498 if (!py_tevent_req_wait_exc(self, req)) {
2499 return NULL;
2501 status = cli_posix_symlink_recv(req);
2502 TALLOC_FREE(req);
2503 if (!NT_STATUS_IS_OK(status)) {
2504 PyErr_SetNTSTATUS(status);
2505 return NULL;
2508 Py_RETURN_NONE;
2511 static PyObject *py_cli_fsctl(
2512 struct py_cli_state *self, PyObject *args, PyObject *kwds)
2514 int fnum, ctl_code;
2515 int max_out = 0;
2516 char *buf = NULL;
2517 Py_ssize_t buflen;
2518 DATA_BLOB in = { .data = NULL, };
2519 DATA_BLOB out = { .data = NULL, };
2520 struct tevent_req *req = NULL;
2521 PyObject *result = NULL;
2522 static const char *kwlist[] = {
2523 "fnum", "ctl_code", "in", "max_out", NULL,
2525 NTSTATUS status;
2526 bool ok;
2528 ok = ParseTupleAndKeywords(
2529 args,
2530 kwds,
2531 "ii" PYARG_BYTES_LEN "i",
2532 kwlist,
2533 &fnum,
2534 &ctl_code,
2535 &buf,
2536 &buflen,
2537 &max_out);
2538 if (!ok) {
2539 return NULL;
2542 in = (DATA_BLOB) { .data = (uint8_t *)buf, .length = buflen, };
2544 req = cli_fsctl_send(
2545 NULL, self->ev, self->cli, fnum, ctl_code, &in, max_out);
2547 if (!py_tevent_req_wait_exc(self, req)) {
2548 return NULL;
2551 status = cli_fsctl_recv(req, NULL, &out);
2552 if (!NT_STATUS_IS_OK(status)) {
2553 PyErr_SetNTSTATUS(status);
2554 return NULL;
2557 result = PyBytes_FromStringAndSize((char *)out.data, out.length);
2558 data_blob_free(&out);
2559 return result;
2562 static PyMethodDef py_cli_state_methods[] = {
2563 { "settimeout", (PyCFunction)py_cli_settimeout, METH_VARARGS,
2564 "settimeout(new_timeout_msecs) => return old_timeout_msecs" },
2565 { "echo", (PyCFunction)py_cli_echo, METH_NOARGS,
2566 "Ping the server connection" },
2567 { "create", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_create),
2568 METH_VARARGS|METH_KEYWORDS,
2569 "Open a file" },
2570 { "create_ex",
2571 PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_create_ex),
2572 METH_VARARGS|METH_KEYWORDS,
2573 "Open a file, SMB2 version returning create contexts" },
2574 { "close", (PyCFunction)py_cli_close, METH_VARARGS,
2575 "Close a file handle" },
2576 { "write", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_write),
2577 METH_VARARGS|METH_KEYWORDS,
2578 "Write to a file handle" },
2579 { "read", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_read),
2580 METH_VARARGS|METH_KEYWORDS,
2581 "Read from a file handle" },
2582 { "truncate", PY_DISCARD_FUNC_SIG(PyCFunction,
2583 py_cli_ftruncate),
2584 METH_VARARGS|METH_KEYWORDS,
2585 "Truncate a file" },
2586 { "delete_on_close", PY_DISCARD_FUNC_SIG(PyCFunction,
2587 py_cli_delete_on_close),
2588 METH_VARARGS|METH_KEYWORDS,
2589 "Set/Reset the delete on close flag" },
2590 { "notify", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_notify),
2591 METH_VARARGS|METH_KEYWORDS,
2592 "Wait for change notifications: \n"
2593 "notify(fnum, buffer_size, completion_filter...) -> "
2594 "libsmb_samba_internal.Notify request handle\n" },
2595 { "list", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_list),
2596 METH_VARARGS|METH_KEYWORDS,
2597 "list(directory, mask='*', attribs=DEFAULT_ATTRS) -> "
2598 "directory contents as a dictionary\n"
2599 "\t\tDEFAULT_ATTRS: FILE_ATTRIBUTE_SYSTEM | "
2600 "FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_ARCHIVE\n\n"
2601 "\t\tList contents of a directory. The keys are, \n"
2602 "\t\t\tname: Long name of the directory item\n"
2603 "\t\t\tshort_name: Short name of the directory item\n"
2604 "\t\t\tsize: File size in bytes\n"
2605 "\t\t\tattrib: Attributes\n"
2606 "\t\t\tmtime: Modification time\n" },
2607 { "get_oplock_break", (PyCFunction)py_cli_get_oplock_break,
2608 METH_VARARGS, "Wait for an oplock break" },
2609 { "unlink", (PyCFunction)py_smb_unlink,
2610 METH_VARARGS,
2611 "unlink(path) -> None\n\n \t\tDelete a file." },
2612 { "mkdir", (PyCFunction)py_smb_mkdir, METH_VARARGS,
2613 "mkdir(path) -> None\n\n \t\tCreate a directory." },
2614 { "posix_whoami", (PyCFunction)py_smb_posix_whoami, METH_NOARGS,
2615 "posix_whoami() -> (uid, gid, gids, sids, guest)" },
2616 { "rmdir", (PyCFunction)py_smb_rmdir, METH_VARARGS,
2617 "rmdir(path) -> None\n\n \t\tDelete a directory." },
2618 { "rename",
2619 PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_rename),
2620 METH_VARARGS|METH_KEYWORDS,
2621 "rename(src,dst) -> None\n\n \t\tRename a file." },
2622 { "chkpath", (PyCFunction)py_smb_chkpath, METH_VARARGS,
2623 "chkpath(dir_path) -> True or False\n\n"
2624 "\t\tReturn true if directory exists, false otherwise." },
2625 { "savefile", (PyCFunction)py_smb_savefile, METH_VARARGS,
2626 "savefile(path, bytes) -> None\n\n"
2627 "\t\tWrite bytes to file." },
2628 { "loadfile", (PyCFunction)py_smb_loadfile, METH_VARARGS,
2629 "loadfile(path) -> file contents as a bytes object"
2630 "\n\n\t\tRead contents of a file." },
2631 { "get_sd", (PyCFunction)py_smb_get_sd, METH_VARARGS,
2632 "get_sd(fnum[, security_info=0]) -> security_descriptor object\n\n"
2633 "\t\tGet security descriptor for opened file." },
2634 { "set_sd", (PyCFunction)py_smb_set_sd, METH_VARARGS,
2635 "set_sd(fnum, security_descriptor[, security_info=0]) -> None\n\n"
2636 "\t\tSet security descriptor for opened file." },
2637 { "protocol",
2638 (PyCFunction)py_smb_protocol,
2639 METH_NOARGS,
2640 "protocol() -> Number"
2642 { "have_posix",
2643 (PyCFunction)py_smb_have_posix,
2644 METH_NOARGS,
2645 "have_posix() -> True/False\n\n"
2646 "\t\tReturn if the server has posix extensions"
2648 { "smb1_posix",
2649 (PyCFunction)py_smb_smb1_posix,
2650 METH_NOARGS,
2651 "Negotiate SMB1 posix extensions",
2653 { "smb1_readlink",
2654 (PyCFunction)py_smb_smb1_readlink,
2655 METH_VARARGS,
2656 "smb1_readlink(path) -> link target",
2658 { "smb1_symlink",
2659 (PyCFunction)py_smb_smb1_symlink,
2660 METH_VARARGS,
2661 "smb1_symlink(target, newname) -> None",
2663 { "fsctl",
2664 (PyCFunction)py_cli_fsctl,
2665 METH_VARARGS|METH_KEYWORDS,
2666 "fsctl(fnum, ctl_code, in_bytes, max_out) -> out_bytes",
2668 { NULL, NULL, 0, NULL }
2671 static PyTypeObject py_cli_state_type = {
2672 PyVarObject_HEAD_INIT(NULL, 0)
2673 .tp_name = "libsmb_samba_cwrapper.LibsmbCConn",
2674 .tp_basicsize = sizeof(struct py_cli_state),
2675 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2676 .tp_doc = "libsmb cwrapper connection",
2677 .tp_new = py_cli_state_new,
2678 .tp_init = (initproc)py_cli_state_init,
2679 .tp_dealloc = (destructor)py_cli_state_dealloc,
2680 .tp_methods = py_cli_state_methods,
2683 static PyMethodDef py_libsmb_methods[] = {
2684 {0},
2687 void initlibsmb_samba_cwrapper(void);
2689 static struct PyModuleDef moduledef = {
2690 PyModuleDef_HEAD_INIT,
2691 .m_name = "libsmb_samba_cwrapper",
2692 .m_doc = "libsmb wrapper",
2693 .m_size = -1,
2694 .m_methods = py_libsmb_methods,
2697 MODULE_INIT_FUNC(libsmb_samba_cwrapper)
2699 PyObject *m = NULL;
2700 PyObject *mod = NULL;
2702 talloc_stackframe();
2704 if (PyType_Ready(&py_cli_state_type) < 0) {
2705 return NULL;
2707 if (PyType_Ready(&py_cli_notify_state_type) < 0) {
2708 return NULL;
2711 m = PyModule_Create(&moduledef);
2712 if (m == NULL) {
2713 return m;
2716 /* Import dom_sid type from dcerpc.security */
2717 mod = PyImport_ImportModule("samba.dcerpc.security");
2718 if (mod == NULL) {
2719 return NULL;
2722 dom_sid_Type = (PyTypeObject *)PyObject_GetAttrString(mod, "dom_sid");
2723 if (dom_sid_Type == NULL) {
2724 Py_DECREF(mod);
2725 return NULL;
2728 Py_INCREF(&py_cli_state_type);
2729 PyModule_AddObject(m, "LibsmbCConn", (PyObject *)&py_cli_state_type);
2731 #define ADD_FLAGS(val) PyModule_AddObject(m, #val, PyLong_FromLong(val))
2733 ADD_FLAGS(PROTOCOL_NONE);
2734 ADD_FLAGS(PROTOCOL_CORE);
2735 ADD_FLAGS(PROTOCOL_COREPLUS);
2736 ADD_FLAGS(PROTOCOL_LANMAN1);
2737 ADD_FLAGS(PROTOCOL_LANMAN2);
2738 ADD_FLAGS(PROTOCOL_NT1);
2739 ADD_FLAGS(PROTOCOL_SMB2_02);
2740 ADD_FLAGS(PROTOCOL_SMB2_10);
2741 ADD_FLAGS(PROTOCOL_SMB3_00);
2742 ADD_FLAGS(PROTOCOL_SMB3_02);
2743 ADD_FLAGS(PROTOCOL_SMB3_11);
2745 ADD_FLAGS(FILE_ATTRIBUTE_READONLY);
2746 ADD_FLAGS(FILE_ATTRIBUTE_HIDDEN);
2747 ADD_FLAGS(FILE_ATTRIBUTE_SYSTEM);
2748 ADD_FLAGS(FILE_ATTRIBUTE_VOLUME);
2749 ADD_FLAGS(FILE_ATTRIBUTE_DIRECTORY);
2750 ADD_FLAGS(FILE_ATTRIBUTE_ARCHIVE);
2751 ADD_FLAGS(FILE_ATTRIBUTE_DEVICE);
2752 ADD_FLAGS(FILE_ATTRIBUTE_NORMAL);
2753 ADD_FLAGS(FILE_ATTRIBUTE_TEMPORARY);
2754 ADD_FLAGS(FILE_ATTRIBUTE_SPARSE);
2755 ADD_FLAGS(FILE_ATTRIBUTE_REPARSE_POINT);
2756 ADD_FLAGS(FILE_ATTRIBUTE_COMPRESSED);
2757 ADD_FLAGS(FILE_ATTRIBUTE_OFFLINE);
2758 ADD_FLAGS(FILE_ATTRIBUTE_NONINDEXED);
2759 ADD_FLAGS(FILE_ATTRIBUTE_ENCRYPTED);
2760 ADD_FLAGS(FILE_ATTRIBUTE_ALL_MASK);
2762 ADD_FLAGS(FILE_DIRECTORY_FILE);
2763 ADD_FLAGS(FILE_WRITE_THROUGH);
2764 ADD_FLAGS(FILE_SEQUENTIAL_ONLY);
2765 ADD_FLAGS(FILE_NO_INTERMEDIATE_BUFFERING);
2766 ADD_FLAGS(FILE_SYNCHRONOUS_IO_ALERT);
2767 ADD_FLAGS(FILE_SYNCHRONOUS_IO_NONALERT);
2768 ADD_FLAGS(FILE_NON_DIRECTORY_FILE);
2769 ADD_FLAGS(FILE_CREATE_TREE_CONNECTION);
2770 ADD_FLAGS(FILE_COMPLETE_IF_OPLOCKED);
2771 ADD_FLAGS(FILE_NO_EA_KNOWLEDGE);
2772 ADD_FLAGS(FILE_EIGHT_DOT_THREE_ONLY);
2773 ADD_FLAGS(FILE_RANDOM_ACCESS);
2774 ADD_FLAGS(FILE_DELETE_ON_CLOSE);
2775 ADD_FLAGS(FILE_OPEN_BY_FILE_ID);
2776 ADD_FLAGS(FILE_OPEN_FOR_BACKUP_INTENT);
2777 ADD_FLAGS(FILE_NO_COMPRESSION);
2778 ADD_FLAGS(FILE_RESERVER_OPFILTER);
2779 ADD_FLAGS(FILE_OPEN_REPARSE_POINT);
2780 ADD_FLAGS(FILE_OPEN_NO_RECALL);
2781 ADD_FLAGS(FILE_OPEN_FOR_FREE_SPACE_QUERY);
2783 ADD_FLAGS(FILE_SHARE_READ);
2784 ADD_FLAGS(FILE_SHARE_WRITE);
2785 ADD_FLAGS(FILE_SHARE_DELETE);
2787 /* change notify completion filter flags */
2788 ADD_FLAGS(FILE_NOTIFY_CHANGE_FILE_NAME);
2789 ADD_FLAGS(FILE_NOTIFY_CHANGE_DIR_NAME);
2790 ADD_FLAGS(FILE_NOTIFY_CHANGE_ATTRIBUTES);
2791 ADD_FLAGS(FILE_NOTIFY_CHANGE_SIZE);
2792 ADD_FLAGS(FILE_NOTIFY_CHANGE_LAST_WRITE);
2793 ADD_FLAGS(FILE_NOTIFY_CHANGE_LAST_ACCESS);
2794 ADD_FLAGS(FILE_NOTIFY_CHANGE_CREATION);
2795 ADD_FLAGS(FILE_NOTIFY_CHANGE_EA);
2796 ADD_FLAGS(FILE_NOTIFY_CHANGE_SECURITY);
2797 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_NAME);
2798 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_SIZE);
2799 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_WRITE);
2800 ADD_FLAGS(FILE_NOTIFY_CHANGE_NAME);
2801 ADD_FLAGS(FILE_NOTIFY_CHANGE_ALL);
2803 /* change notify action results */
2804 ADD_FLAGS(NOTIFY_ACTION_ADDED);
2805 ADD_FLAGS(NOTIFY_ACTION_REMOVED);
2806 ADD_FLAGS(NOTIFY_ACTION_MODIFIED);
2807 ADD_FLAGS(NOTIFY_ACTION_OLD_NAME);
2808 ADD_FLAGS(NOTIFY_ACTION_NEW_NAME);
2809 ADD_FLAGS(NOTIFY_ACTION_ADDED_STREAM);
2810 ADD_FLAGS(NOTIFY_ACTION_REMOVED_STREAM);
2811 ADD_FLAGS(NOTIFY_ACTION_MODIFIED_STREAM);
2813 /* CreateDisposition values */
2814 ADD_FLAGS(FILE_SUPERSEDE);
2815 ADD_FLAGS(FILE_OPEN);
2816 ADD_FLAGS(FILE_CREATE);
2817 ADD_FLAGS(FILE_OPEN_IF);
2818 ADD_FLAGS(FILE_OVERWRITE);
2819 ADD_FLAGS(FILE_OVERWRITE_IF);
2821 ADD_FLAGS(FSCTL_DFS_GET_REFERRALS);
2822 ADD_FLAGS(FSCTL_DFS_GET_REFERRALS_EX);
2823 ADD_FLAGS(FSCTL_REQUEST_OPLOCK_LEVEL_1);
2824 ADD_FLAGS(FSCTL_REQUEST_OPLOCK_LEVEL_2);
2825 ADD_FLAGS(FSCTL_REQUEST_BATCH_OPLOCK);
2826 ADD_FLAGS(FSCTL_OPLOCK_BREAK_ACKNOWLEDGE);
2827 ADD_FLAGS(FSCTL_OPBATCH_ACK_CLOSE_PENDING);
2828 ADD_FLAGS(FSCTL_OPLOCK_BREAK_NOTIFY);
2829 ADD_FLAGS(FSCTL_GET_COMPRESSION);
2830 ADD_FLAGS(FSCTL_FILESYS_GET_STATISTICS);
2831 ADD_FLAGS(FSCTL_GET_NTFS_VOLUME_DATA);
2832 ADD_FLAGS(FSCTL_IS_VOLUME_DIRTY);
2833 ADD_FLAGS(FSCTL_FIND_FILES_BY_SID);
2834 ADD_FLAGS(FSCTL_SET_OBJECT_ID);
2835 ADD_FLAGS(FSCTL_GET_OBJECT_ID);
2836 ADD_FLAGS(FSCTL_DELETE_OBJECT_ID);
2837 ADD_FLAGS(FSCTL_SET_REPARSE_POINT);
2838 ADD_FLAGS(FSCTL_GET_REPARSE_POINT);
2839 ADD_FLAGS(FSCTL_DELETE_REPARSE_POINT);
2840 ADD_FLAGS(FSCTL_SET_OBJECT_ID_EXTENDED);
2841 ADD_FLAGS(FSCTL_CREATE_OR_GET_OBJECT_ID);
2842 ADD_FLAGS(FSCTL_SET_SPARSE);
2843 ADD_FLAGS(FSCTL_SET_ZERO_DATA);
2844 ADD_FLAGS(FSCTL_SET_ZERO_ON_DEALLOCATION);
2845 ADD_FLAGS(FSCTL_READ_FILE_USN_DATA);
2846 ADD_FLAGS(FSCTL_WRITE_USN_CLOSE_RECORD);
2847 ADD_FLAGS(FSCTL_QUERY_ALLOCATED_RANGES);
2848 ADD_FLAGS(FSCTL_QUERY_ON_DISK_VOLUME_INFO);
2849 ADD_FLAGS(FSCTL_QUERY_SPARING_INFO);
2850 ADD_FLAGS(FSCTL_FILE_LEVEL_TRIM);
2851 ADD_FLAGS(FSCTL_OFFLOAD_READ);
2852 ADD_FLAGS(FSCTL_OFFLOAD_WRITE);
2853 ADD_FLAGS(FSCTL_SET_INTEGRITY_INFORMATION);
2854 ADD_FLAGS(FSCTL_DUP_EXTENTS_TO_FILE);
2855 ADD_FLAGS(FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX);
2856 ADD_FLAGS(FSCTL_STORAGE_QOS_CONTROL);
2857 ADD_FLAGS(FSCTL_SVHDX_SYNC_TUNNEL_REQUEST);
2858 ADD_FLAGS(FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT);
2859 ADD_FLAGS(FSCTL_PIPE_PEEK);
2860 ADD_FLAGS(FSCTL_NAMED_PIPE_READ_WRITE);
2861 ADD_FLAGS(FSCTL_PIPE_TRANSCEIVE);
2862 ADD_FLAGS(FSCTL_PIPE_WAIT);
2863 ADD_FLAGS(FSCTL_GET_SHADOW_COPY_DATA);
2864 ADD_FLAGS(FSCTL_SRV_ENUM_SNAPS);
2865 ADD_FLAGS(FSCTL_SRV_REQUEST_RESUME_KEY);
2866 ADD_FLAGS(FSCTL_SRV_COPYCHUNK);
2867 ADD_FLAGS(FSCTL_SRV_COPYCHUNK_WRITE);
2868 ADD_FLAGS(FSCTL_SRV_READ_HASH);
2869 ADD_FLAGS(FSCTL_LMR_REQ_RESILIENCY);
2870 ADD_FLAGS(FSCTL_LMR_SET_LINK_TRACKING_INFORMATION);
2871 ADD_FLAGS(FSCTL_QUERY_NETWORK_INTERFACE_INFO);
2873 ADD_FLAGS(SYMLINK_ERROR_TAG);
2874 ADD_FLAGS(SYMLINK_FLAG_RELATIVE);
2875 ADD_FLAGS(SYMLINK_ADMIN);
2876 ADD_FLAGS(SYMLINK_UNTRUSTED);
2877 ADD_FLAGS(SYMLINK_TRUST_UNKNOWN);
2878 ADD_FLAGS(SYMLINK_TRUST_MASK);
2880 ADD_FLAGS(IO_REPARSE_TAG_SYMLINK);
2881 ADD_FLAGS(IO_REPARSE_TAG_MOUNT_POINT);
2882 ADD_FLAGS(IO_REPARSE_TAG_HSM);
2883 ADD_FLAGS(IO_REPARSE_TAG_SIS);
2884 ADD_FLAGS(IO_REPARSE_TAG_DFS);
2885 ADD_FLAGS(IO_REPARSE_TAG_NFS);
2887 #define ADD_STRING(val) PyModule_AddObject(m, #val, PyBytes_FromString(val))
2889 ADD_STRING(SMB2_CREATE_TAG_EXTA);
2890 ADD_STRING(SMB2_CREATE_TAG_MXAC);
2891 ADD_STRING(SMB2_CREATE_TAG_SECD);
2892 ADD_STRING(SMB2_CREATE_TAG_DHNQ);
2893 ADD_STRING(SMB2_CREATE_TAG_DHNC);
2894 ADD_STRING(SMB2_CREATE_TAG_ALSI);
2895 ADD_STRING(SMB2_CREATE_TAG_TWRP);
2896 ADD_STRING(SMB2_CREATE_TAG_QFID);
2897 ADD_STRING(SMB2_CREATE_TAG_RQLS);
2898 ADD_STRING(SMB2_CREATE_TAG_DH2Q);
2899 ADD_STRING(SMB2_CREATE_TAG_DH2C);
2900 ADD_STRING(SMB2_CREATE_TAG_AAPL);
2901 ADD_STRING(SMB2_CREATE_TAG_APP_INSTANCE_ID);
2902 ADD_STRING(SVHDX_OPEN_DEVICE_CONTEXT);
2903 ADD_STRING(SMB2_CREATE_TAG_POSIX);
2904 ADD_FLAGS(SMB2_FIND_POSIX_INFORMATION);
2905 ADD_FLAGS(FILE_SUPERSEDE);
2906 ADD_FLAGS(FILE_OPEN);
2907 ADD_FLAGS(FILE_CREATE);
2908 ADD_FLAGS(FILE_OPEN_IF);
2909 ADD_FLAGS(FILE_OVERWRITE);
2910 ADD_FLAGS(FILE_OVERWRITE_IF);
2911 ADD_FLAGS(FILE_DIRECTORY_FILE);
2913 return m;