pylibsmb: Get reparse tag when listing directories
[Samba.git] / source3 / libsmb / pylibsmb.c
blob159e3c9d3432115db72dd9886c1a92643fb7f8cf
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 "{sLsLsLsLsLsLsLsLsL}",
995 "oplock_level",
996 (unsigned long long)r->oplock_level,
997 "create_action",
998 (unsigned long long)r->create_action,
999 "creation_time",
1000 (unsigned long long)r->creation_time,
1001 "last_access_time",
1002 (unsigned long long)r->last_access_time,
1003 "last_write_time",
1004 (unsigned long long)r->last_write_time,
1005 "change_time",
1006 (unsigned long long)r->change_time,
1007 "allocation_size",
1008 (unsigned long long)r->allocation_size,
1009 "end_of_file",
1010 (unsigned long long)r->end_of_file,
1011 "file_attributes",
1012 (unsigned long long)r->file_attributes);
1013 return v;
1016 static PyObject *py_cli_symlink_error(const struct symlink_reparse_struct *s)
1018 char *subst_utf8 = NULL, *print_utf8 = NULL;
1019 size_t subst_utf8_len, print_utf8_len;
1020 PyObject *v = NULL;
1021 bool ok = true;
1024 * Python wants utf-8, regardless of our unix charset (which
1025 * most likely is utf-8 these days, but you never know).
1028 ok = convert_string_talloc(
1029 talloc_tos(),
1030 CH_UNIX,
1031 CH_UTF8,
1032 s->substitute_name,
1033 strlen(s->substitute_name),
1034 &subst_utf8,
1035 &subst_utf8_len);
1036 if (!ok) {
1037 goto fail;
1040 ok = convert_string_talloc(
1041 talloc_tos(),
1042 CH_UNIX,
1043 CH_UTF8,
1044 s->print_name,
1045 strlen(s->print_name),
1046 &print_utf8,
1047 &print_utf8_len);
1048 if (!ok) {
1049 goto fail;
1052 v = Py_BuildValue(
1053 "{sLsssssL}",
1054 "unparsed_path_length",
1055 (unsigned long long)s->unparsed_path_length,
1056 "substitute_name",
1057 subst_utf8,
1058 "print_name",
1059 print_utf8,
1060 "flags",
1061 (unsigned long long)s->flags);
1063 fail:
1064 TALLOC_FREE(subst_utf8);
1065 TALLOC_FREE(print_utf8);
1066 return v;
1069 static PyObject *py_cli_create_ex(
1070 struct py_cli_state *self, PyObject *args, PyObject *kwds)
1072 char *fname = NULL;
1073 unsigned CreateFlags = 0;
1074 unsigned DesiredAccess = FILE_GENERIC_READ;
1075 unsigned FileAttributes = 0;
1076 unsigned ShareAccess = 0;
1077 unsigned CreateDisposition = FILE_OPEN;
1078 unsigned CreateOptions = 0;
1079 unsigned ImpersonationLevel = SMB2_IMPERSONATION_IMPERSONATION;
1080 unsigned SecurityFlags = 0;
1081 PyObject *py_create_contexts_in = NULL;
1082 PyObject *py_create_contexts_out = NULL;
1083 struct smb2_create_blobs *create_contexts_in = NULL;
1084 struct smb2_create_blobs create_contexts_out = { .num_blobs = 0 };
1085 struct smb_create_returns cr = { .create_action = 0, };
1086 struct symlink_reparse_struct *symlink = NULL;
1087 PyObject *py_cr = NULL;
1088 uint16_t fnum;
1089 struct tevent_req *req;
1090 NTSTATUS status;
1091 int ret;
1092 bool ok;
1093 PyObject *v = NULL;
1095 static const char *kwlist[] = {
1096 "Name",
1097 "CreateFlags",
1098 "DesiredAccess",
1099 "FileAttributes",
1100 "ShareAccess",
1101 "CreateDisposition",
1102 "CreateOptions",
1103 "ImpersonationLevel",
1104 "SecurityFlags",
1105 "CreateContexts",
1106 NULL };
1108 ret = ParseTupleAndKeywords(
1109 args,
1110 kwds,
1111 "s|IIIIIIIIO",
1112 kwlist,
1113 &fname,
1114 &CreateFlags,
1115 &DesiredAccess,
1116 &FileAttributes,
1117 &ShareAccess,
1118 &CreateDisposition,
1119 &CreateOptions,
1120 &ImpersonationLevel,
1121 &SecurityFlags,
1122 &py_create_contexts_in);
1123 if (!ret) {
1124 return NULL;
1127 if (py_create_contexts_in != NULL) {
1128 create_contexts_in = py_cli_get_create_contexts(
1129 NULL, py_create_contexts_in);
1130 if (create_contexts_in == NULL) {
1131 errno = EINVAL;
1132 PyErr_SetFromErrno(PyExc_RuntimeError);
1133 return NULL;
1137 if (smbXcli_conn_protocol(self->cli->conn) >= PROTOCOL_SMB2_02) {
1138 req = cli_smb2_create_fnum_send(
1139 NULL,
1140 self->ev,
1141 self->cli,
1142 fname,
1143 CreateFlags,
1144 ImpersonationLevel,
1145 DesiredAccess,
1146 FileAttributes,
1147 ShareAccess,
1148 CreateDisposition,
1149 CreateOptions,
1150 create_contexts_in);
1151 } else {
1152 req = cli_ntcreate_send(
1153 NULL,
1154 self->ev,
1155 self->cli,
1156 fname,
1157 CreateFlags,
1158 DesiredAccess,
1159 FileAttributes,
1160 ShareAccess,
1161 CreateDisposition,
1162 CreateOptions,
1163 ImpersonationLevel,
1164 SecurityFlags);
1167 TALLOC_FREE(create_contexts_in);
1169 ok = py_tevent_req_wait_exc(self, req);
1170 if (!ok) {
1171 return NULL;
1174 if (smbXcli_conn_protocol(self->cli->conn) >= PROTOCOL_SMB2_02) {
1175 status = cli_smb2_create_fnum_recv(
1176 req,
1177 &fnum,
1178 &cr,
1179 NULL,
1180 &create_contexts_out,
1181 &symlink);
1182 } else {
1183 status = cli_ntcreate_recv(req, &fnum, &cr);
1186 TALLOC_FREE(req);
1188 if (!NT_STATUS_IS_OK(status)) {
1189 goto fail;
1192 SMB_ASSERT(symlink == NULL);
1194 py_create_contexts_out = py_cli_create_contexts(&create_contexts_out);
1195 TALLOC_FREE(create_contexts_out.blobs);
1196 if (py_create_contexts_out == NULL) {
1197 goto nomem;
1200 py_cr = py_cli_create_returns(&cr);
1201 if (py_cr == NULL) {
1202 goto nomem;
1205 v = PyTuple_New(3);
1206 if (v == NULL) {
1207 goto nomem;
1209 ret = PyTuple_SetItem(v, 0, Py_BuildValue("I", (unsigned)fnum));
1210 if (ret == -1) {
1211 status = NT_STATUS_INTERNAL_ERROR;
1212 goto fail;
1214 ret = PyTuple_SetItem(v, 1, py_cr);
1215 if (ret == -1) {
1216 status = NT_STATUS_INTERNAL_ERROR;
1217 goto fail;
1219 ret = PyTuple_SetItem(v, 2, py_create_contexts_out);
1220 if (ret == -1) {
1221 status = NT_STATUS_INTERNAL_ERROR;
1222 goto fail;
1225 return v;
1226 nomem:
1227 status = NT_STATUS_NO_MEMORY;
1228 fail:
1229 Py_XDECREF(py_create_contexts_out);
1230 Py_XDECREF(py_cr);
1231 Py_XDECREF(v);
1233 if (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK) &&
1234 (symlink != NULL)) {
1235 PyErr_SetObject(
1236 PyObject_GetAttrString(
1237 PyImport_ImportModule("samba"),
1238 "NTSTATUSError"),
1239 Py_BuildValue(
1240 "I,s,O",
1241 NT_STATUS_V(status),
1242 get_friendly_nt_error_msg(status),
1243 py_cli_symlink_error(symlink)));
1244 } else {
1245 PyErr_SetNTSTATUS(status);
1247 return NULL;
1250 static PyObject *py_cli_close(struct py_cli_state *self, PyObject *args)
1252 struct tevent_req *req;
1253 int fnum;
1254 NTSTATUS status;
1256 if (!PyArg_ParseTuple(args, "i", &fnum)) {
1257 return NULL;
1260 req = cli_close_send(NULL, self->ev, self->cli, fnum);
1261 if (!py_tevent_req_wait_exc(self, req)) {
1262 return NULL;
1264 status = cli_close_recv(req);
1265 TALLOC_FREE(req);
1267 if (!NT_STATUS_IS_OK(status)) {
1268 PyErr_SetNTSTATUS(status);
1269 return NULL;
1271 Py_RETURN_NONE;
1274 static PyObject *py_cli_rename(
1275 struct py_cli_state *self, PyObject *args, PyObject *kwds)
1277 char *fname_src = NULL, *fname_dst = NULL;
1278 int replace = false;
1279 struct tevent_req *req = NULL;
1280 NTSTATUS status;
1281 bool ok;
1283 static const char *kwlist[] = { "src", "dst", "replace", NULL };
1285 ok = ParseTupleAndKeywords(
1286 args, kwds, "ss|p", kwlist, &fname_src, &fname_dst, &replace);
1287 if (!ok) {
1288 return NULL;
1291 req = cli_rename_send(
1292 NULL, self->ev, self->cli, fname_src, fname_dst, replace);
1293 if (!py_tevent_req_wait_exc(self, req)) {
1294 return NULL;
1296 status = cli_rename_recv(req);
1297 TALLOC_FREE(req);
1299 if (!NT_STATUS_IS_OK(status)) {
1300 PyErr_SetNTSTATUS(status);
1301 return NULL;
1303 Py_RETURN_NONE;
1307 struct push_state {
1308 char *data;
1309 off_t nread;
1310 off_t total_data;
1314 * cli_push() helper to write a chunk of data to a remote file
1316 static size_t push_data(uint8_t *buf, size_t n, void *priv)
1318 struct push_state *state = (struct push_state *)priv;
1319 char *curr_ptr = NULL;
1320 off_t remaining;
1321 size_t copied_bytes;
1323 if (state->nread >= state->total_data) {
1324 return 0;
1327 curr_ptr = state->data + state->nread;
1328 remaining = state->total_data - state->nread;
1329 copied_bytes = MIN(remaining, n);
1331 memcpy(buf, curr_ptr, copied_bytes);
1332 state->nread += copied_bytes;
1333 return copied_bytes;
1337 * Writes a file with the contents specified
1339 static PyObject *py_smb_savefile(struct py_cli_state *self, PyObject *args)
1341 uint16_t fnum;
1342 const char *filename = NULL;
1343 char *data = NULL;
1344 Py_ssize_t size = 0;
1345 NTSTATUS status;
1346 struct tevent_req *req = NULL;
1347 struct push_state state;
1349 if (!PyArg_ParseTuple(args, "s"PYARG_BYTES_LEN":savefile", &filename,
1350 &data, &size)) {
1351 return NULL;
1354 /* create a new file handle for writing to */
1355 req = cli_ntcreate_send(NULL, self->ev, self->cli, filename, 0,
1356 FILE_WRITE_DATA, FILE_ATTRIBUTE_NORMAL,
1357 FILE_SHARE_READ|FILE_SHARE_WRITE,
1358 FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE,
1359 SMB2_IMPERSONATION_IMPERSONATION, 0);
1360 if (!py_tevent_req_wait_exc(self, req)) {
1361 return NULL;
1363 status = cli_ntcreate_recv(req, &fnum, NULL);
1364 TALLOC_FREE(req);
1365 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1367 /* write the new file contents */
1368 state.data = data;
1369 state.nread = 0;
1370 state.total_data = size;
1372 req = cli_push_send(NULL, self->ev, self->cli, fnum, 0, 0, 0,
1373 push_data, &state);
1374 if (!py_tevent_req_wait_exc(self, req)) {
1375 return NULL;
1377 status = cli_push_recv(req);
1378 TALLOC_FREE(req);
1379 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1381 /* close the file handle */
1382 req = cli_close_send(NULL, self->ev, self->cli, fnum);
1383 if (!py_tevent_req_wait_exc(self, req)) {
1384 return NULL;
1386 status = cli_close_recv(req);
1387 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1389 Py_RETURN_NONE;
1392 static PyObject *py_cli_write(struct py_cli_state *self, PyObject *args,
1393 PyObject *kwds)
1395 int fnum;
1396 unsigned mode = 0;
1397 char *buf;
1398 Py_ssize_t buflen;
1399 unsigned long long offset;
1400 struct tevent_req *req;
1401 NTSTATUS status;
1402 size_t written;
1404 static const char *kwlist[] = {
1405 "fnum", "buffer", "offset", "mode", NULL };
1407 if (!ParseTupleAndKeywords(
1408 args, kwds, "i" PYARG_BYTES_LEN "K|I", kwlist,
1409 &fnum, &buf, &buflen, &offset, &mode)) {
1410 return NULL;
1413 req = cli_write_send(NULL, self->ev, self->cli, fnum, mode,
1414 (uint8_t *)buf, offset, buflen);
1415 if (!py_tevent_req_wait_exc(self, req)) {
1416 return NULL;
1418 status = cli_write_recv(req, &written);
1419 TALLOC_FREE(req);
1421 if (!NT_STATUS_IS_OK(status)) {
1422 PyErr_SetNTSTATUS(status);
1423 return NULL;
1425 return Py_BuildValue("K", (unsigned long long)written);
1429 * Returns the size of the given file
1431 static NTSTATUS py_smb_filesize(struct py_cli_state *self, uint16_t fnum,
1432 off_t *size)
1434 NTSTATUS status;
1435 struct tevent_req *req = NULL;
1437 req = cli_qfileinfo_basic_send(NULL, self->ev, self->cli, fnum);
1438 if (!py_tevent_req_wait_exc(self, req)) {
1439 return NT_STATUS_INTERNAL_ERROR;
1441 status = cli_qfileinfo_basic_recv(
1442 req, NULL, size, NULL, NULL, NULL, NULL, NULL);
1443 TALLOC_FREE(req);
1444 return status;
1448 * Loads the specified file's contents and returns it
1450 static PyObject *py_smb_loadfile(struct py_cli_state *self, PyObject *args)
1452 NTSTATUS status;
1453 const char *filename = NULL;
1454 struct tevent_req *req = NULL;
1455 uint16_t fnum;
1456 off_t size;
1457 char *buf = NULL;
1458 off_t nread = 0;
1459 PyObject *result = NULL;
1461 if (!PyArg_ParseTuple(args, "s:loadfile", &filename)) {
1462 return NULL;
1465 /* get a read file handle */
1466 req = cli_ntcreate_send(NULL, self->ev, self->cli, filename, 0,
1467 FILE_READ_DATA | FILE_READ_ATTRIBUTES,
1468 FILE_ATTRIBUTE_NORMAL,
1469 FILE_SHARE_READ, FILE_OPEN, 0,
1470 SMB2_IMPERSONATION_IMPERSONATION, 0);
1471 if (!py_tevent_req_wait_exc(self, req)) {
1472 return NULL;
1474 status = cli_ntcreate_recv(req, &fnum, NULL);
1475 TALLOC_FREE(req);
1476 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1478 /* get a buffer to hold the file contents */
1479 status = py_smb_filesize(self, fnum, &size);
1480 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1482 result = PyBytes_FromStringAndSize(NULL, size);
1483 if (result == NULL) {
1484 return NULL;
1487 /* read the file contents */
1488 buf = PyBytes_AS_STRING(result);
1489 req = cli_pull_send(NULL, self->ev, self->cli, fnum, 0, size,
1490 size, cli_read_sink, &buf);
1491 if (!py_tevent_req_wait_exc(self, req)) {
1492 Py_XDECREF(result);
1493 return NULL;
1495 status = cli_pull_recv(req, &nread);
1496 TALLOC_FREE(req);
1497 if (!NT_STATUS_IS_OK(status)) {
1498 Py_XDECREF(result);
1499 PyErr_SetNTSTATUS(status);
1500 return NULL;
1503 /* close the file handle */
1504 req = cli_close_send(NULL, self->ev, self->cli, fnum);
1505 if (!py_tevent_req_wait_exc(self, req)) {
1506 Py_XDECREF(result);
1507 return NULL;
1509 status = cli_close_recv(req);
1510 TALLOC_FREE(req);
1511 if (!NT_STATUS_IS_OK(status)) {
1512 Py_XDECREF(result);
1513 PyErr_SetNTSTATUS(status);
1514 return NULL;
1517 /* sanity-check we read the expected number of bytes */
1518 if (nread > size) {
1519 Py_XDECREF(result);
1520 PyErr_Format(PyExc_IOError,
1521 "read invalid - got %zu requested %zu",
1522 nread, size);
1523 return NULL;
1526 if (nread < size) {
1527 if (_PyBytes_Resize(&result, nread) < 0) {
1528 return NULL;
1532 return result;
1535 static PyObject *py_cli_read(struct py_cli_state *self, PyObject *args,
1536 PyObject *kwds)
1538 int fnum;
1539 unsigned long long offset;
1540 unsigned size;
1541 struct tevent_req *req;
1542 NTSTATUS status;
1543 char *buf;
1544 size_t received;
1545 PyObject *result;
1547 static const char *kwlist[] = {
1548 "fnum", "offset", "size", NULL };
1550 if (!ParseTupleAndKeywords(
1551 args, kwds, "iKI", kwlist, &fnum, &offset,
1552 &size)) {
1553 return NULL;
1556 result = PyBytes_FromStringAndSize(NULL, size);
1557 if (result == NULL) {
1558 return NULL;
1560 buf = PyBytes_AS_STRING(result);
1562 req = cli_read_send(NULL, self->ev, self->cli, fnum,
1563 buf, offset, size);
1564 if (!py_tevent_req_wait_exc(self, req)) {
1565 Py_XDECREF(result);
1566 return NULL;
1568 status = cli_read_recv(req, &received);
1569 TALLOC_FREE(req);
1571 if (!NT_STATUS_IS_OK(status)) {
1572 Py_XDECREF(result);
1573 PyErr_SetNTSTATUS(status);
1574 return NULL;
1577 if (received > size) {
1578 Py_XDECREF(result);
1579 PyErr_Format(PyExc_IOError,
1580 "read invalid - got %zu requested %u",
1581 received, size);
1582 return NULL;
1585 if (received < size) {
1586 if (_PyBytes_Resize(&result, received) < 0) {
1587 return NULL;
1591 return result;
1594 static PyObject *py_cli_ftruncate(struct py_cli_state *self, PyObject *args,
1595 PyObject *kwds)
1597 int fnum;
1598 unsigned long long size;
1599 struct tevent_req *req;
1600 NTSTATUS status;
1602 static const char *kwlist[] = {
1603 "fnum", "size", NULL };
1605 if (!ParseTupleAndKeywords(
1606 args, kwds, "IK", kwlist, &fnum, &size)) {
1607 return NULL;
1610 req = cli_ftruncate_send(NULL, self->ev, self->cli, fnum, size);
1611 if (!py_tevent_req_wait_exc(self, req)) {
1612 return NULL;
1614 status = cli_ftruncate_recv(req);
1615 TALLOC_FREE(req);
1617 if (!NT_STATUS_IS_OK(status)) {
1618 PyErr_SetNTSTATUS(status);
1619 return NULL;
1621 Py_RETURN_NONE;
1624 static PyObject *py_cli_delete_on_close(struct py_cli_state *self,
1625 PyObject *args,
1626 PyObject *kwds)
1628 unsigned fnum, flag;
1629 struct tevent_req *req;
1630 NTSTATUS status;
1632 static const char *kwlist[] = {
1633 "fnum", "flag", NULL };
1635 if (!ParseTupleAndKeywords(
1636 args, kwds, "II", kwlist, &fnum, &flag)) {
1637 return NULL;
1640 req = cli_nt_delete_on_close_send(NULL, self->ev, self->cli, fnum,
1641 flag);
1642 if (!py_tevent_req_wait_exc(self, req)) {
1643 return NULL;
1645 status = cli_nt_delete_on_close_recv(req);
1646 TALLOC_FREE(req);
1648 if (!NT_STATUS_IS_OK(status)) {
1649 PyErr_SetNTSTATUS(status);
1650 return NULL;
1652 Py_RETURN_NONE;
1655 struct py_cli_notify_state {
1656 PyObject_HEAD
1657 struct py_cli_state *py_cli_state;
1658 struct tevent_req *req;
1661 static void py_cli_notify_state_dealloc(struct py_cli_notify_state *self)
1663 TALLOC_FREE(self->req);
1664 if (self->py_cli_state != NULL) {
1665 Py_DECREF(self->py_cli_state);
1666 self->py_cli_state = NULL;
1668 Py_TYPE(self)->tp_free(self);
1671 static PyTypeObject py_cli_notify_state_type;
1673 static PyObject *py_cli_notify(struct py_cli_state *self,
1674 PyObject *args,
1675 PyObject *kwds)
1677 static const char *kwlist[] = {
1678 "fnum",
1679 "buffer_size",
1680 "completion_filter",
1681 "recursive",
1682 NULL
1684 unsigned fnum = 0;
1685 unsigned buffer_size = 0;
1686 unsigned completion_filter = 0;
1687 PyObject *py_recursive = Py_False;
1688 bool recursive = false;
1689 struct tevent_req *req = NULL;
1690 struct tevent_queue *send_queue = NULL;
1691 struct tevent_req *flush_req = NULL;
1692 bool ok;
1693 struct py_cli_notify_state *py_notify_state = NULL;
1694 struct timeval endtime;
1696 ok = ParseTupleAndKeywords(args,
1697 kwds,
1698 "IIIO",
1699 kwlist,
1700 &fnum,
1701 &buffer_size,
1702 &completion_filter,
1703 &py_recursive);
1704 if (!ok) {
1705 return NULL;
1708 recursive = PyObject_IsTrue(py_recursive);
1710 req = cli_notify_send(NULL,
1711 self->ev,
1712 self->cli,
1713 fnum,
1714 buffer_size,
1715 completion_filter,
1716 recursive);
1717 if (req == NULL) {
1718 PyErr_NoMemory();
1719 return NULL;
1723 * Just wait for the request being submitted to
1724 * the kernel/socket/wire.
1726 send_queue = smbXcli_conn_send_queue(self->cli->conn);
1727 flush_req = tevent_queue_wait_send(req,
1728 self->ev,
1729 send_queue);
1730 endtime = timeval_current_ofs_msec(self->cli->timeout);
1731 ok = tevent_req_set_endtime(flush_req,
1732 self->ev,
1733 endtime);
1734 if (!ok) {
1735 TALLOC_FREE(req);
1736 PyErr_NoMemory();
1737 return NULL;
1739 ok = py_tevent_req_wait_exc(self, flush_req);
1740 if (!ok) {
1741 TALLOC_FREE(req);
1742 return NULL;
1744 TALLOC_FREE(flush_req);
1746 py_notify_state = (struct py_cli_notify_state *)
1747 py_cli_notify_state_type.tp_alloc(&py_cli_notify_state_type, 0);
1748 if (py_notify_state == NULL) {
1749 TALLOC_FREE(req);
1750 PyErr_NoMemory();
1751 return NULL;
1753 Py_INCREF(self);
1754 py_notify_state->py_cli_state = self;
1755 py_notify_state->req = req;
1757 return (PyObject *)py_notify_state;
1760 static PyObject *py_cli_notify_get_changes(struct py_cli_notify_state *self,
1761 PyObject *args,
1762 PyObject *kwds)
1764 struct py_cli_state *py_cli_state = self->py_cli_state;
1765 struct tevent_req *req = self->req;
1766 uint32_t i;
1767 uint32_t num_changes = 0;
1768 struct notify_change *changes = NULL;
1769 PyObject *result = NULL;
1770 NTSTATUS status;
1771 bool ok;
1772 static const char *kwlist[] = {
1773 "wait",
1774 NULL
1776 PyObject *py_wait = Py_False;
1777 bool wait = false;
1778 bool pending;
1780 ok = ParseTupleAndKeywords(args,
1781 kwds,
1782 "O",
1783 kwlist,
1784 &py_wait);
1785 if (!ok) {
1786 return NULL;
1789 wait = PyObject_IsTrue(py_wait);
1791 if (req == NULL) {
1792 PyErr_SetString(PyExc_RuntimeError,
1793 "TODO req == NULL "
1794 "- missing change notify request?");
1795 return NULL;
1798 pending = tevent_req_is_in_progress(req);
1799 if (pending && !wait) {
1800 Py_RETURN_NONE;
1803 if (pending) {
1804 struct timeval endtime;
1806 endtime = timeval_current_ofs_msec(py_cli_state->cli->timeout);
1807 ok = tevent_req_set_endtime(req,
1808 py_cli_state->ev,
1809 endtime);
1810 if (!ok) {
1811 TALLOC_FREE(req);
1812 PyErr_NoMemory();
1813 return NULL;
1817 ok = py_tevent_req_wait_exc(py_cli_state, req);
1818 self->req = NULL;
1819 Py_DECREF(self->py_cli_state);
1820 self->py_cli_state = NULL;
1821 if (!ok) {
1822 return NULL;
1825 status = cli_notify_recv(req, req, &num_changes, &changes);
1826 if (!NT_STATUS_IS_OK(status)) {
1827 TALLOC_FREE(req);
1828 PyErr_SetNTSTATUS(status);
1829 return NULL;
1832 result = Py_BuildValue("[]");
1833 if (result == NULL) {
1834 TALLOC_FREE(req);
1835 return NULL;
1838 for (i = 0; i < num_changes; i++) {
1839 PyObject *change = NULL;
1840 int ret;
1842 change = Py_BuildValue("{s:s,s:I}",
1843 "name", changes[i].name,
1844 "action", changes[i].action);
1845 if (change == NULL) {
1846 Py_XDECREF(result);
1847 TALLOC_FREE(req);
1848 return NULL;
1851 ret = PyList_Append(result, change);
1852 Py_DECREF(change);
1853 if (ret == -1) {
1854 Py_XDECREF(result);
1855 TALLOC_FREE(req);
1856 return NULL;
1860 TALLOC_FREE(req);
1861 return result;
1864 static PyMethodDef py_cli_notify_state_methods[] = {
1866 .ml_name = "get_changes",
1867 .ml_meth = (PyCFunction)py_cli_notify_get_changes,
1868 .ml_flags = METH_VARARGS|METH_KEYWORDS,
1869 .ml_doc = "Wait for change notifications: \n"
1870 "N.get_changes(wait=BOOLEAN) -> "
1871 "change notifications as a dictionary\n"
1872 "\t\tList contents of a directory. The keys are, \n"
1873 "\t\t\tname: name of changed object\n"
1874 "\t\t\taction: type of the change\n"
1875 "None is returned if there's no response jet and "
1876 "wait=False is passed"
1879 .ml_name = NULL
1883 static PyTypeObject py_cli_notify_state_type = {
1884 PyVarObject_HEAD_INIT(NULL, 0)
1885 .tp_name = "libsmb_samba_cwrapper.Notify",
1886 .tp_basicsize = sizeof(struct py_cli_notify_state),
1887 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1888 .tp_doc = "notify request",
1889 .tp_dealloc = (destructor)py_cli_notify_state_dealloc,
1890 .tp_methods = py_cli_notify_state_methods,
1894 * Helper to add posix directory listing entries to an overall Python list
1896 static NTSTATUS list_posix_helper(struct file_info *finfo,
1897 const char *mask, void *state)
1899 PyObject *result = (PyObject *)state;
1900 PyObject *file = NULL;
1901 PyObject *size = NULL;
1902 int ret;
1904 size = PyLong_FromUnsignedLongLong(finfo->size);
1906 * Build a dictionary representing the file info.
1907 * Note: Windows does not always return short_name (so it may be None)
1909 file = Py_BuildValue("{s:s,s:i,s:s,s:O,s:l,s:i,s:i,s:i,s:s,s:s}",
1910 "name", finfo->name,
1911 "attrib", (int)finfo->attr,
1912 "short_name", finfo->short_name,
1913 "size", size,
1914 "mtime",
1915 convert_timespec_to_time_t(finfo->mtime_ts),
1916 "perms", finfo->st_ex_mode,
1917 "ino", finfo->ino,
1918 "dev", finfo->st_ex_dev,
1919 "owner_sid",
1920 dom_sid_string(finfo, &finfo->owner_sid),
1921 "group_sid",
1922 dom_sid_string(finfo, &finfo->group_sid));
1924 Py_CLEAR(size);
1926 if (file == NULL) {
1927 return NT_STATUS_NO_MEMORY;
1930 ret = PyList_Append(result, file);
1931 Py_CLEAR(file);
1932 if (ret == -1) {
1933 return NT_STATUS_INTERNAL_ERROR;
1936 return NT_STATUS_OK;
1940 * Helper to add directory listing entries to an overall Python list
1942 static NTSTATUS list_helper(struct file_info *finfo,
1943 const char *mask, void *state)
1945 PyObject *result = (PyObject *)state;
1946 PyObject *file = NULL;
1947 PyObject *size = NULL;
1948 int ret;
1950 /* suppress '.' and '..' in the results we return */
1951 if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
1952 return NT_STATUS_OK;
1954 size = PyLong_FromUnsignedLongLong(finfo->size);
1956 * Build a dictionary representing the file info.
1957 * Note: Windows does not always return short_name (so it may be None)
1959 file = Py_BuildValue("{s:s,s:i,s:s,s:O,s:l}",
1960 "name", finfo->name,
1961 "attrib", (int)finfo->attr,
1962 "short_name", finfo->short_name,
1963 "size", size,
1964 "mtime",
1965 convert_timespec_to_time_t(finfo->mtime_ts));
1967 Py_CLEAR(size);
1969 if (file == NULL) {
1970 return NT_STATUS_NO_MEMORY;
1973 if (finfo->attr & FILE_ATTRIBUTE_REPARSE_POINT) {
1974 unsigned long tag = finfo->reparse_tag;
1976 ret = PyDict_SetItemString(
1977 file,
1978 "reparse_tag",
1979 PyLong_FromUnsignedLong(tag));
1980 if (ret == -1) {
1981 return NT_STATUS_INTERNAL_ERROR;
1985 ret = PyList_Append(result, file);
1986 Py_CLEAR(file);
1987 if (ret == -1) {
1988 return NT_STATUS_INTERNAL_ERROR;
1991 return NT_STATUS_OK;
1994 struct do_listing_state {
1995 const char *mask;
1996 NTSTATUS (*callback_fn)(
1997 struct file_info *finfo,
1998 const char *mask,
1999 void *private_data);
2000 void *private_data;
2001 NTSTATUS status;
2004 static void do_listing_cb(struct tevent_req *subreq)
2006 struct do_listing_state *state = tevent_req_callback_data_void(subreq);
2007 struct file_info *finfo = NULL;
2009 state->status = cli_list_recv(subreq, NULL, &finfo);
2010 if (!NT_STATUS_IS_OK(state->status)) {
2011 return;
2013 state->callback_fn(finfo, state->mask, state->private_data);
2014 TALLOC_FREE(finfo);
2017 static NTSTATUS do_listing(struct py_cli_state *self,
2018 const char *base_dir, const char *user_mask,
2019 uint16_t attribute,
2020 unsigned int info_level,
2021 bool posix,
2022 NTSTATUS (*callback_fn)(struct file_info *,
2023 const char *, void *),
2024 void *priv)
2026 char *mask = NULL;
2027 struct do_listing_state state = {
2028 .mask = mask,
2029 .callback_fn = callback_fn,
2030 .private_data = priv,
2032 struct tevent_req *req = NULL;
2033 NTSTATUS status;
2035 if (user_mask == NULL) {
2036 mask = talloc_asprintf(NULL, "%s\\*", base_dir);
2037 } else {
2038 mask = talloc_asprintf(NULL, "%s\\%s", base_dir, user_mask);
2041 if (mask == NULL) {
2042 return NT_STATUS_NO_MEMORY;
2044 dos_format(mask);
2046 req = cli_list_send(NULL, self->ev, self->cli, mask, attribute,
2047 info_level, posix);
2048 if (req == NULL) {
2049 status = NT_STATUS_NO_MEMORY;
2050 goto done;
2052 tevent_req_set_callback(req, do_listing_cb, &state);
2054 if (!py_tevent_req_wait_exc(self, req)) {
2055 return NT_STATUS_INTERNAL_ERROR;
2057 TALLOC_FREE(req);
2059 status = state.status;
2060 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MORE_FILES)) {
2061 status = NT_STATUS_OK;
2064 done:
2065 TALLOC_FREE(mask);
2066 return status;
2069 static PyObject *py_cli_list(struct py_cli_state *self,
2070 PyObject *args,
2071 PyObject *kwds)
2073 char *base_dir;
2074 char *user_mask = NULL;
2075 unsigned int attribute = LIST_ATTRIBUTE_MASK;
2076 unsigned int info_level = 0;
2077 bool posix = false;
2078 NTSTATUS status;
2079 enum protocol_types proto = smbXcli_conn_protocol(self->cli->conn);
2080 PyObject *result = NULL;
2081 const char *kwlist[] = { "directory", "mask", "attribs", "posix",
2082 "info_level", NULL };
2083 NTSTATUS (*callback_fn)(struct file_info *, const char *, void *) =
2084 &list_helper;
2086 if (!ParseTupleAndKeywords(args, kwds, "z|sIpI:list", kwlist,
2087 &base_dir, &user_mask, &attribute,
2088 &posix, &info_level)) {
2089 return NULL;
2092 result = Py_BuildValue("[]");
2093 if (result == NULL) {
2094 return NULL;
2097 if (!info_level) {
2098 if (proto >= PROTOCOL_SMB2_02) {
2099 info_level = SMB2_FIND_ID_BOTH_DIRECTORY_INFO;
2100 } else {
2101 info_level = SMB_FIND_FILE_BOTH_DIRECTORY_INFO;
2105 if (posix) {
2106 callback_fn = &list_posix_helper;
2108 status = do_listing(self, base_dir, user_mask, attribute,
2109 info_level, posix, callback_fn, result);
2111 if (!NT_STATUS_IS_OK(status)) {
2112 Py_XDECREF(result);
2113 PyErr_SetNTSTATUS(status);
2114 return NULL;
2117 return result;
2120 static PyObject *py_smb_unlink(struct py_cli_state *self, PyObject *args)
2122 NTSTATUS status;
2123 const char *filename = NULL;
2124 struct tevent_req *req = NULL;
2125 const uint32_t attrs = (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
2127 if (!PyArg_ParseTuple(args, "s:unlink", &filename)) {
2128 return NULL;
2131 req = cli_unlink_send(NULL, self->ev, self->cli, filename, attrs);
2132 if (!py_tevent_req_wait_exc(self, req)) {
2133 return NULL;
2135 status = cli_unlink_recv(req);
2136 TALLOC_FREE(req);
2137 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2139 Py_RETURN_NONE;
2142 static PyObject *py_smb_rmdir(struct py_cli_state *self, PyObject *args)
2144 NTSTATUS status;
2145 struct tevent_req *req = NULL;
2146 const char *dirname = NULL;
2148 if (!PyArg_ParseTuple(args, "s:rmdir", &dirname)) {
2149 return NULL;
2152 req = cli_rmdir_send(NULL, self->ev, self->cli, dirname);
2153 if (!py_tevent_req_wait_exc(self, req)) {
2154 return NULL;
2156 status = cli_rmdir_recv(req);
2157 TALLOC_FREE(req);
2158 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2160 Py_RETURN_NONE;
2164 * Create a directory
2166 static PyObject *py_smb_mkdir(struct py_cli_state *self, PyObject *args)
2168 NTSTATUS status;
2169 const char *dirname = NULL;
2170 struct tevent_req *req = NULL;
2172 if (!PyArg_ParseTuple(args, "s:mkdir", &dirname)) {
2173 return NULL;
2176 req = cli_mkdir_send(NULL, self->ev, self->cli, dirname);
2177 if (!py_tevent_req_wait_exc(self, req)) {
2178 return NULL;
2180 status = cli_mkdir_recv(req);
2181 TALLOC_FREE(req);
2182 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2184 Py_RETURN_NONE;
2188 * Does a whoami call
2190 static PyObject *py_smb_posix_whoami(struct py_cli_state *self,
2191 PyObject *Py_UNUSED(ignored))
2193 TALLOC_CTX *frame = talloc_stackframe();
2194 NTSTATUS status;
2195 struct tevent_req *req = NULL;
2196 uint64_t uid;
2197 uint64_t gid;
2198 uint32_t num_gids;
2199 uint64_t *gids = NULL;
2200 uint32_t num_sids;
2201 struct dom_sid *sids = NULL;
2202 bool guest;
2203 PyObject *py_gids = NULL;
2204 PyObject *py_sids = NULL;
2205 PyObject *py_guest = NULL;
2206 PyObject *py_ret = NULL;
2207 Py_ssize_t i;
2209 req = cli_posix_whoami_send(frame, self->ev, self->cli);
2210 if (!py_tevent_req_wait_exc(self, req)) {
2211 goto fail;
2213 status = cli_posix_whoami_recv(req,
2214 frame,
2215 &uid,
2216 &gid,
2217 &num_gids,
2218 &gids,
2219 &num_sids,
2220 &sids,
2221 &guest);
2222 if (!NT_STATUS_IS_OK(status)) {
2223 PyErr_SetNTSTATUS(status);
2224 goto fail;
2226 if (num_gids > PY_SSIZE_T_MAX) {
2227 PyErr_SetString(PyExc_OverflowError, "posix_whoami: Too many GIDs");
2228 goto fail;
2230 if (num_sids > PY_SSIZE_T_MAX) {
2231 PyErr_SetString(PyExc_OverflowError, "posix_whoami: Too many SIDs");
2232 goto fail;
2235 py_gids = PyList_New(num_gids);
2236 if (!py_gids) {
2237 goto fail;
2239 for (i = 0; i < num_gids; ++i) {
2240 int ret;
2241 PyObject *py_item = PyLong_FromUnsignedLongLong(gids[i]);
2242 if (!py_item) {
2243 goto fail2;
2246 ret = PyList_SetItem(py_gids, i, py_item);
2247 if (ret) {
2248 goto fail2;
2251 py_sids = PyList_New(num_sids);
2252 if (!py_sids) {
2253 goto fail2;
2255 for (i = 0; i < num_sids; ++i) {
2256 int ret;
2257 struct dom_sid *sid;
2258 PyObject *py_item;
2260 sid = dom_sid_dup(frame, &sids[i]);
2261 if (!sid) {
2262 PyErr_NoMemory();
2263 goto fail3;
2266 py_item = pytalloc_steal(dom_sid_Type, sid);
2267 if (!py_item) {
2268 PyErr_NoMemory();
2269 goto fail3;
2272 ret = PyList_SetItem(py_sids, i, py_item);
2273 if (ret) {
2274 goto fail3;
2278 py_guest = guest ? Py_True : Py_False;
2280 py_ret = Py_BuildValue("KKNNO",
2281 uid,
2282 gid,
2283 py_gids,
2284 py_sids,
2285 py_guest);
2286 if (!py_ret) {
2287 goto fail3;
2290 TALLOC_FREE(frame);
2291 return py_ret;
2293 fail3:
2294 Py_CLEAR(py_sids);
2296 fail2:
2297 Py_CLEAR(py_gids);
2299 fail:
2300 TALLOC_FREE(frame);
2301 return NULL;
2305 * Checks existence of a directory
2307 static bool check_dir_path(struct py_cli_state *self, const char *path)
2309 NTSTATUS status;
2310 struct tevent_req *req = NULL;
2312 req = cli_chkpath_send(NULL, self->ev, self->cli, path);
2313 if (!py_tevent_req_wait_exc(self, req)) {
2314 return false;
2316 status = cli_chkpath_recv(req);
2317 TALLOC_FREE(req);
2319 return NT_STATUS_IS_OK(status);
2322 static PyObject *py_smb_chkpath(struct py_cli_state *self, PyObject *args)
2324 const char *path = NULL;
2325 bool dir_exists;
2327 if (!PyArg_ParseTuple(args, "s:chkpath", &path)) {
2328 return NULL;
2331 dir_exists = check_dir_path(self, path);
2332 return PyBool_FromLong(dir_exists);
2335 static PyObject *py_smb_have_posix(struct py_cli_state *self,
2336 PyObject *Py_UNUSED(ignored))
2338 bool posix = smbXcli_conn_have_posix(self->cli->conn);
2340 if (posix) {
2341 Py_RETURN_TRUE;
2343 Py_RETURN_FALSE;
2346 static PyObject *py_smb_protocol(struct py_cli_state *self,
2347 PyObject *Py_UNUSED(ignored))
2349 enum protocol_types proto = smbXcli_conn_protocol(self->cli->conn);
2350 PyObject *result = PyLong_FromLong(proto);
2351 return result;
2354 static PyObject *py_smb_get_sd(struct py_cli_state *self, PyObject *args)
2356 int fnum;
2357 unsigned sinfo;
2358 struct tevent_req *req = NULL;
2359 struct security_descriptor *sd = NULL;
2360 NTSTATUS status;
2362 if (!PyArg_ParseTuple(args, "iI:get_acl", &fnum, &sinfo)) {
2363 return NULL;
2366 req = cli_query_security_descriptor_send(
2367 NULL, self->ev, self->cli, fnum, sinfo);
2368 if (!py_tevent_req_wait_exc(self, req)) {
2369 return NULL;
2371 status = cli_query_security_descriptor_recv(req, NULL, &sd);
2372 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2374 return py_return_ndr_struct(
2375 "samba.dcerpc.security", "descriptor", sd, sd);
2378 static PyObject *py_smb_set_sd(struct py_cli_state *self, PyObject *args)
2380 PyObject *py_sd = NULL;
2381 struct tevent_req *req = NULL;
2382 struct security_descriptor *sd = NULL;
2383 uint16_t fnum;
2384 unsigned int sinfo;
2385 NTSTATUS status;
2387 if (!PyArg_ParseTuple(args, "iOI:set_sd", &fnum, &py_sd, &sinfo)) {
2388 return NULL;
2391 sd = pytalloc_get_type(py_sd, struct security_descriptor);
2392 if (!sd) {
2393 PyErr_Format(PyExc_TypeError,
2394 "Expected dcerpc.security.descriptor as argument, got %s",
2395 pytalloc_get_name(py_sd));
2396 return NULL;
2399 req = cli_set_security_descriptor_send(
2400 NULL, self->ev, self->cli, fnum, sinfo, sd);
2401 if (!py_tevent_req_wait_exc(self, req)) {
2402 return NULL;
2405 status = cli_set_security_descriptor_recv(req);
2406 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2408 Py_RETURN_NONE;
2411 static PyObject *py_smb_smb1_posix(
2412 struct py_cli_state *self, PyObject *Py_UNUSED(ignored))
2414 NTSTATUS status;
2415 struct tevent_req *req = NULL;
2416 uint16_t major, minor;
2417 uint32_t caplow, caphigh;
2418 PyObject *result = NULL;
2420 req = cli_unix_extensions_version_send(NULL, self->ev, self->cli);
2421 if (!py_tevent_req_wait_exc(self, req)) {
2422 return NULL;
2424 status = cli_unix_extensions_version_recv(
2425 req, &major, &minor, &caplow, &caphigh);
2426 TALLOC_FREE(req);
2427 if (!NT_STATUS_IS_OK(status)) {
2428 PyErr_SetNTSTATUS(status);
2429 return NULL;
2432 req = cli_set_unix_extensions_capabilities_send(
2433 NULL, self->ev, self->cli, major, minor, caplow, caphigh);
2434 if (!py_tevent_req_wait_exc(self, req)) {
2435 return NULL;
2437 status = cli_set_unix_extensions_capabilities_recv(req);
2438 TALLOC_FREE(req);
2439 if (!NT_STATUS_IS_OK(status)) {
2440 PyErr_SetNTSTATUS(status);
2441 return NULL;
2444 result = Py_BuildValue(
2445 "[IIII]",
2446 (unsigned)minor,
2447 (unsigned)major,
2448 (unsigned)caplow,
2449 (unsigned)caphigh);
2450 return result;
2453 static PyObject *py_smb_smb1_readlink(
2454 struct py_cli_state *self, PyObject *args)
2456 NTSTATUS status;
2457 const char *filename = NULL;
2458 struct tevent_req *req = NULL;
2459 char *target = NULL;
2460 PyObject *result = NULL;
2462 if (!PyArg_ParseTuple(args, "s:smb1_readlink", &filename)) {
2463 return NULL;
2466 req = cli_posix_readlink_send(NULL, self->ev, self->cli, filename);
2467 if (!py_tevent_req_wait_exc(self, req)) {
2468 return NULL;
2470 status = cli_posix_readlink_recv(req, NULL, &target);
2471 TALLOC_FREE(req);
2472 if (!NT_STATUS_IS_OK(status)) {
2473 PyErr_SetNTSTATUS(status);
2474 return NULL;
2477 result = PyBytes_FromString(target);
2478 TALLOC_FREE(target);
2479 return result;
2482 static PyObject *py_smb_smb1_symlink(
2483 struct py_cli_state *self, PyObject *args)
2485 NTSTATUS status;
2486 const char *target = NULL, *newname = NULL;
2487 struct tevent_req *req = NULL;
2489 if (!PyArg_ParseTuple(args, "ss:smb1_symlink", &target, &newname)) {
2490 return NULL;
2493 req = cli_posix_symlink_send(
2494 NULL, self->ev, self->cli, target, newname);
2495 if (!py_tevent_req_wait_exc(self, req)) {
2496 return NULL;
2498 status = cli_posix_symlink_recv(req);
2499 TALLOC_FREE(req);
2500 if (!NT_STATUS_IS_OK(status)) {
2501 PyErr_SetNTSTATUS(status);
2502 return NULL;
2505 Py_RETURN_NONE;
2508 static PyObject *py_cli_fsctl(
2509 struct py_cli_state *self, PyObject *args, PyObject *kwds)
2511 int fnum, ctl_code;
2512 int max_out = 0;
2513 char *buf = NULL;
2514 Py_ssize_t buflen;
2515 DATA_BLOB in = { .data = NULL, };
2516 DATA_BLOB out = { .data = NULL, };
2517 struct tevent_req *req = NULL;
2518 PyObject *result = NULL;
2519 static const char *kwlist[] = {
2520 "fnum", "ctl_code", "in", "max_out", NULL,
2522 NTSTATUS status;
2523 bool ok;
2525 ok = ParseTupleAndKeywords(
2526 args,
2527 kwds,
2528 "ii" PYARG_BYTES_LEN "i",
2529 kwlist,
2530 &fnum,
2531 &ctl_code,
2532 &buf,
2533 &buflen,
2534 &max_out);
2535 if (!ok) {
2536 return NULL;
2539 in = (DATA_BLOB) { .data = (uint8_t *)buf, .length = buflen, };
2541 req = cli_fsctl_send(
2542 NULL, self->ev, self->cli, fnum, ctl_code, &in, max_out);
2544 if (!py_tevent_req_wait_exc(self, req)) {
2545 return NULL;
2548 status = cli_fsctl_recv(req, NULL, &out);
2549 if (!NT_STATUS_IS_OK(status)) {
2550 PyErr_SetNTSTATUS(status);
2551 return NULL;
2554 result = PyBytes_FromStringAndSize((char *)out.data, out.length);
2555 data_blob_free(&out);
2556 return result;
2559 static PyMethodDef py_cli_state_methods[] = {
2560 { "settimeout", (PyCFunction)py_cli_settimeout, METH_VARARGS,
2561 "settimeout(new_timeout_msecs) => return old_timeout_msecs" },
2562 { "echo", (PyCFunction)py_cli_echo, METH_NOARGS,
2563 "Ping the server connection" },
2564 { "create", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_create),
2565 METH_VARARGS|METH_KEYWORDS,
2566 "Open a file" },
2567 { "create_ex",
2568 PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_create_ex),
2569 METH_VARARGS|METH_KEYWORDS,
2570 "Open a file, SMB2 version returning create contexts" },
2571 { "close", (PyCFunction)py_cli_close, METH_VARARGS,
2572 "Close a file handle" },
2573 { "write", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_write),
2574 METH_VARARGS|METH_KEYWORDS,
2575 "Write to a file handle" },
2576 { "read", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_read),
2577 METH_VARARGS|METH_KEYWORDS,
2578 "Read from a file handle" },
2579 { "truncate", PY_DISCARD_FUNC_SIG(PyCFunction,
2580 py_cli_ftruncate),
2581 METH_VARARGS|METH_KEYWORDS,
2582 "Truncate a file" },
2583 { "delete_on_close", PY_DISCARD_FUNC_SIG(PyCFunction,
2584 py_cli_delete_on_close),
2585 METH_VARARGS|METH_KEYWORDS,
2586 "Set/Reset the delete on close flag" },
2587 { "notify", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_notify),
2588 METH_VARARGS|METH_KEYWORDS,
2589 "Wait for change notifications: \n"
2590 "notify(fnum, buffer_size, completion_filter...) -> "
2591 "libsmb_samba_internal.Notify request handle\n" },
2592 { "list", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_list),
2593 METH_VARARGS|METH_KEYWORDS,
2594 "list(directory, mask='*', attribs=DEFAULT_ATTRS) -> "
2595 "directory contents as a dictionary\n"
2596 "\t\tDEFAULT_ATTRS: FILE_ATTRIBUTE_SYSTEM | "
2597 "FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_ARCHIVE\n\n"
2598 "\t\tList contents of a directory. The keys are, \n"
2599 "\t\t\tname: Long name of the directory item\n"
2600 "\t\t\tshort_name: Short name of the directory item\n"
2601 "\t\t\tsize: File size in bytes\n"
2602 "\t\t\tattrib: Attributes\n"
2603 "\t\t\tmtime: Modification time\n" },
2604 { "get_oplock_break", (PyCFunction)py_cli_get_oplock_break,
2605 METH_VARARGS, "Wait for an oplock break" },
2606 { "unlink", (PyCFunction)py_smb_unlink,
2607 METH_VARARGS,
2608 "unlink(path) -> None\n\n \t\tDelete a file." },
2609 { "mkdir", (PyCFunction)py_smb_mkdir, METH_VARARGS,
2610 "mkdir(path) -> None\n\n \t\tCreate a directory." },
2611 { "posix_whoami", (PyCFunction)py_smb_posix_whoami, METH_NOARGS,
2612 "posix_whoami() -> (uid, gid, gids, sids, guest)" },
2613 { "rmdir", (PyCFunction)py_smb_rmdir, METH_VARARGS,
2614 "rmdir(path) -> None\n\n \t\tDelete a directory." },
2615 { "rename",
2616 PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_rename),
2617 METH_VARARGS|METH_KEYWORDS,
2618 "rename(src,dst) -> None\n\n \t\tRename a file." },
2619 { "chkpath", (PyCFunction)py_smb_chkpath, METH_VARARGS,
2620 "chkpath(dir_path) -> True or False\n\n"
2621 "\t\tReturn true if directory exists, false otherwise." },
2622 { "savefile", (PyCFunction)py_smb_savefile, METH_VARARGS,
2623 "savefile(path, bytes) -> None\n\n"
2624 "\t\tWrite bytes to file." },
2625 { "loadfile", (PyCFunction)py_smb_loadfile, METH_VARARGS,
2626 "loadfile(path) -> file contents as a bytes object"
2627 "\n\n\t\tRead contents of a file." },
2628 { "get_sd", (PyCFunction)py_smb_get_sd, METH_VARARGS,
2629 "get_sd(fnum[, security_info=0]) -> security_descriptor object\n\n"
2630 "\t\tGet security descriptor for opened file." },
2631 { "set_sd", (PyCFunction)py_smb_set_sd, METH_VARARGS,
2632 "set_sd(fnum, security_descriptor[, security_info=0]) -> None\n\n"
2633 "\t\tSet security descriptor for opened file." },
2634 { "protocol",
2635 (PyCFunction)py_smb_protocol,
2636 METH_NOARGS,
2637 "protocol() -> Number"
2639 { "have_posix",
2640 (PyCFunction)py_smb_have_posix,
2641 METH_NOARGS,
2642 "have_posix() -> True/False\n\n"
2643 "\t\tReturn if the server has posix extensions"
2645 { "smb1_posix",
2646 (PyCFunction)py_smb_smb1_posix,
2647 METH_NOARGS,
2648 "Negotiate SMB1 posix extensions",
2650 { "smb1_readlink",
2651 (PyCFunction)py_smb_smb1_readlink,
2652 METH_VARARGS,
2653 "smb1_readlink(path) -> link target",
2655 { "smb1_symlink",
2656 (PyCFunction)py_smb_smb1_symlink,
2657 METH_VARARGS,
2658 "smb1_symlink(target, newname) -> None",
2660 { "fsctl",
2661 (PyCFunction)py_cli_fsctl,
2662 METH_VARARGS|METH_KEYWORDS,
2663 "fsctl(fnum, ctl_code, in_bytes, max_out) -> out_bytes",
2665 { NULL, NULL, 0, NULL }
2668 static PyTypeObject py_cli_state_type = {
2669 PyVarObject_HEAD_INIT(NULL, 0)
2670 .tp_name = "libsmb_samba_cwrapper.LibsmbCConn",
2671 .tp_basicsize = sizeof(struct py_cli_state),
2672 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2673 .tp_doc = "libsmb cwrapper connection",
2674 .tp_new = py_cli_state_new,
2675 .tp_init = (initproc)py_cli_state_init,
2676 .tp_dealloc = (destructor)py_cli_state_dealloc,
2677 .tp_methods = py_cli_state_methods,
2680 static PyMethodDef py_libsmb_methods[] = {
2681 {0},
2684 void initlibsmb_samba_cwrapper(void);
2686 static struct PyModuleDef moduledef = {
2687 PyModuleDef_HEAD_INIT,
2688 .m_name = "libsmb_samba_cwrapper",
2689 .m_doc = "libsmb wrapper",
2690 .m_size = -1,
2691 .m_methods = py_libsmb_methods,
2694 MODULE_INIT_FUNC(libsmb_samba_cwrapper)
2696 PyObject *m = NULL;
2697 PyObject *mod = NULL;
2699 talloc_stackframe();
2701 if (PyType_Ready(&py_cli_state_type) < 0) {
2702 return NULL;
2704 if (PyType_Ready(&py_cli_notify_state_type) < 0) {
2705 return NULL;
2708 m = PyModule_Create(&moduledef);
2709 if (m == NULL) {
2710 return m;
2713 /* Import dom_sid type from dcerpc.security */
2714 mod = PyImport_ImportModule("samba.dcerpc.security");
2715 if (mod == NULL) {
2716 return NULL;
2719 dom_sid_Type = (PyTypeObject *)PyObject_GetAttrString(mod, "dom_sid");
2720 if (dom_sid_Type == NULL) {
2721 Py_DECREF(mod);
2722 return NULL;
2725 Py_INCREF(&py_cli_state_type);
2726 PyModule_AddObject(m, "LibsmbCConn", (PyObject *)&py_cli_state_type);
2728 #define ADD_FLAGS(val) PyModule_AddObject(m, #val, PyLong_FromLong(val))
2730 ADD_FLAGS(PROTOCOL_NONE);
2731 ADD_FLAGS(PROTOCOL_CORE);
2732 ADD_FLAGS(PROTOCOL_COREPLUS);
2733 ADD_FLAGS(PROTOCOL_LANMAN1);
2734 ADD_FLAGS(PROTOCOL_LANMAN2);
2735 ADD_FLAGS(PROTOCOL_NT1);
2736 ADD_FLAGS(PROTOCOL_SMB2_02);
2737 ADD_FLAGS(PROTOCOL_SMB2_10);
2738 ADD_FLAGS(PROTOCOL_SMB3_00);
2739 ADD_FLAGS(PROTOCOL_SMB3_02);
2740 ADD_FLAGS(PROTOCOL_SMB3_11);
2742 ADD_FLAGS(FILE_ATTRIBUTE_READONLY);
2743 ADD_FLAGS(FILE_ATTRIBUTE_HIDDEN);
2744 ADD_FLAGS(FILE_ATTRIBUTE_SYSTEM);
2745 ADD_FLAGS(FILE_ATTRIBUTE_VOLUME);
2746 ADD_FLAGS(FILE_ATTRIBUTE_DIRECTORY);
2747 ADD_FLAGS(FILE_ATTRIBUTE_ARCHIVE);
2748 ADD_FLAGS(FILE_ATTRIBUTE_DEVICE);
2749 ADD_FLAGS(FILE_ATTRIBUTE_NORMAL);
2750 ADD_FLAGS(FILE_ATTRIBUTE_TEMPORARY);
2751 ADD_FLAGS(FILE_ATTRIBUTE_SPARSE);
2752 ADD_FLAGS(FILE_ATTRIBUTE_REPARSE_POINT);
2753 ADD_FLAGS(FILE_ATTRIBUTE_COMPRESSED);
2754 ADD_FLAGS(FILE_ATTRIBUTE_OFFLINE);
2755 ADD_FLAGS(FILE_ATTRIBUTE_NONINDEXED);
2756 ADD_FLAGS(FILE_ATTRIBUTE_ENCRYPTED);
2757 ADD_FLAGS(FILE_ATTRIBUTE_ALL_MASK);
2759 ADD_FLAGS(FILE_DIRECTORY_FILE);
2760 ADD_FLAGS(FILE_WRITE_THROUGH);
2761 ADD_FLAGS(FILE_SEQUENTIAL_ONLY);
2762 ADD_FLAGS(FILE_NO_INTERMEDIATE_BUFFERING);
2763 ADD_FLAGS(FILE_SYNCHRONOUS_IO_ALERT);
2764 ADD_FLAGS(FILE_SYNCHRONOUS_IO_NONALERT);
2765 ADD_FLAGS(FILE_NON_DIRECTORY_FILE);
2766 ADD_FLAGS(FILE_CREATE_TREE_CONNECTION);
2767 ADD_FLAGS(FILE_COMPLETE_IF_OPLOCKED);
2768 ADD_FLAGS(FILE_NO_EA_KNOWLEDGE);
2769 ADD_FLAGS(FILE_EIGHT_DOT_THREE_ONLY);
2770 ADD_FLAGS(FILE_RANDOM_ACCESS);
2771 ADD_FLAGS(FILE_DELETE_ON_CLOSE);
2772 ADD_FLAGS(FILE_OPEN_BY_FILE_ID);
2773 ADD_FLAGS(FILE_OPEN_FOR_BACKUP_INTENT);
2774 ADD_FLAGS(FILE_NO_COMPRESSION);
2775 ADD_FLAGS(FILE_RESERVER_OPFILTER);
2776 ADD_FLAGS(FILE_OPEN_REPARSE_POINT);
2777 ADD_FLAGS(FILE_OPEN_NO_RECALL);
2778 ADD_FLAGS(FILE_OPEN_FOR_FREE_SPACE_QUERY);
2780 ADD_FLAGS(FILE_SHARE_READ);
2781 ADD_FLAGS(FILE_SHARE_WRITE);
2782 ADD_FLAGS(FILE_SHARE_DELETE);
2784 /* change notify completion filter flags */
2785 ADD_FLAGS(FILE_NOTIFY_CHANGE_FILE_NAME);
2786 ADD_FLAGS(FILE_NOTIFY_CHANGE_DIR_NAME);
2787 ADD_FLAGS(FILE_NOTIFY_CHANGE_ATTRIBUTES);
2788 ADD_FLAGS(FILE_NOTIFY_CHANGE_SIZE);
2789 ADD_FLAGS(FILE_NOTIFY_CHANGE_LAST_WRITE);
2790 ADD_FLAGS(FILE_NOTIFY_CHANGE_LAST_ACCESS);
2791 ADD_FLAGS(FILE_NOTIFY_CHANGE_CREATION);
2792 ADD_FLAGS(FILE_NOTIFY_CHANGE_EA);
2793 ADD_FLAGS(FILE_NOTIFY_CHANGE_SECURITY);
2794 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_NAME);
2795 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_SIZE);
2796 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_WRITE);
2797 ADD_FLAGS(FILE_NOTIFY_CHANGE_NAME);
2798 ADD_FLAGS(FILE_NOTIFY_CHANGE_ALL);
2800 /* change notify action results */
2801 ADD_FLAGS(NOTIFY_ACTION_ADDED);
2802 ADD_FLAGS(NOTIFY_ACTION_REMOVED);
2803 ADD_FLAGS(NOTIFY_ACTION_MODIFIED);
2804 ADD_FLAGS(NOTIFY_ACTION_OLD_NAME);
2805 ADD_FLAGS(NOTIFY_ACTION_NEW_NAME);
2806 ADD_FLAGS(NOTIFY_ACTION_ADDED_STREAM);
2807 ADD_FLAGS(NOTIFY_ACTION_REMOVED_STREAM);
2808 ADD_FLAGS(NOTIFY_ACTION_MODIFIED_STREAM);
2810 /* CreateDisposition values */
2811 ADD_FLAGS(FILE_SUPERSEDE);
2812 ADD_FLAGS(FILE_OPEN);
2813 ADD_FLAGS(FILE_CREATE);
2814 ADD_FLAGS(FILE_OPEN_IF);
2815 ADD_FLAGS(FILE_OVERWRITE);
2816 ADD_FLAGS(FILE_OVERWRITE_IF);
2818 ADD_FLAGS(FSCTL_DFS_GET_REFERRALS);
2819 ADD_FLAGS(FSCTL_DFS_GET_REFERRALS_EX);
2820 ADD_FLAGS(FSCTL_REQUEST_OPLOCK_LEVEL_1);
2821 ADD_FLAGS(FSCTL_REQUEST_OPLOCK_LEVEL_2);
2822 ADD_FLAGS(FSCTL_REQUEST_BATCH_OPLOCK);
2823 ADD_FLAGS(FSCTL_OPLOCK_BREAK_ACKNOWLEDGE);
2824 ADD_FLAGS(FSCTL_OPBATCH_ACK_CLOSE_PENDING);
2825 ADD_FLAGS(FSCTL_OPLOCK_BREAK_NOTIFY);
2826 ADD_FLAGS(FSCTL_GET_COMPRESSION);
2827 ADD_FLAGS(FSCTL_FILESYS_GET_STATISTICS);
2828 ADD_FLAGS(FSCTL_GET_NTFS_VOLUME_DATA);
2829 ADD_FLAGS(FSCTL_IS_VOLUME_DIRTY);
2830 ADD_FLAGS(FSCTL_FIND_FILES_BY_SID);
2831 ADD_FLAGS(FSCTL_SET_OBJECT_ID);
2832 ADD_FLAGS(FSCTL_GET_OBJECT_ID);
2833 ADD_FLAGS(FSCTL_DELETE_OBJECT_ID);
2834 ADD_FLAGS(FSCTL_SET_REPARSE_POINT);
2835 ADD_FLAGS(FSCTL_GET_REPARSE_POINT);
2836 ADD_FLAGS(FSCTL_DELETE_REPARSE_POINT);
2837 ADD_FLAGS(FSCTL_SET_OBJECT_ID_EXTENDED);
2838 ADD_FLAGS(FSCTL_CREATE_OR_GET_OBJECT_ID);
2839 ADD_FLAGS(FSCTL_SET_SPARSE);
2840 ADD_FLAGS(FSCTL_SET_ZERO_DATA);
2841 ADD_FLAGS(FSCTL_SET_ZERO_ON_DEALLOCATION);
2842 ADD_FLAGS(FSCTL_READ_FILE_USN_DATA);
2843 ADD_FLAGS(FSCTL_WRITE_USN_CLOSE_RECORD);
2844 ADD_FLAGS(FSCTL_QUERY_ALLOCATED_RANGES);
2845 ADD_FLAGS(FSCTL_QUERY_ON_DISK_VOLUME_INFO);
2846 ADD_FLAGS(FSCTL_QUERY_SPARING_INFO);
2847 ADD_FLAGS(FSCTL_FILE_LEVEL_TRIM);
2848 ADD_FLAGS(FSCTL_OFFLOAD_READ);
2849 ADD_FLAGS(FSCTL_OFFLOAD_WRITE);
2850 ADD_FLAGS(FSCTL_SET_INTEGRITY_INFORMATION);
2851 ADD_FLAGS(FSCTL_DUP_EXTENTS_TO_FILE);
2852 ADD_FLAGS(FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX);
2853 ADD_FLAGS(FSCTL_STORAGE_QOS_CONTROL);
2854 ADD_FLAGS(FSCTL_SVHDX_SYNC_TUNNEL_REQUEST);
2855 ADD_FLAGS(FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT);
2856 ADD_FLAGS(FSCTL_PIPE_PEEK);
2857 ADD_FLAGS(FSCTL_NAMED_PIPE_READ_WRITE);
2858 ADD_FLAGS(FSCTL_PIPE_TRANSCEIVE);
2859 ADD_FLAGS(FSCTL_PIPE_WAIT);
2860 ADD_FLAGS(FSCTL_GET_SHADOW_COPY_DATA);
2861 ADD_FLAGS(FSCTL_SRV_ENUM_SNAPS);
2862 ADD_FLAGS(FSCTL_SRV_REQUEST_RESUME_KEY);
2863 ADD_FLAGS(FSCTL_SRV_COPYCHUNK);
2864 ADD_FLAGS(FSCTL_SRV_COPYCHUNK_WRITE);
2865 ADD_FLAGS(FSCTL_SRV_READ_HASH);
2866 ADD_FLAGS(FSCTL_LMR_REQ_RESILIENCY);
2867 ADD_FLAGS(FSCTL_LMR_SET_LINK_TRACKING_INFORMATION);
2868 ADD_FLAGS(FSCTL_QUERY_NETWORK_INTERFACE_INFO);
2870 ADD_FLAGS(SYMLINK_ERROR_TAG);
2871 ADD_FLAGS(SYMLINK_FLAG_RELATIVE);
2872 ADD_FLAGS(SYMLINK_ADMIN);
2873 ADD_FLAGS(SYMLINK_UNTRUSTED);
2874 ADD_FLAGS(SYMLINK_TRUST_UNKNOWN);
2875 ADD_FLAGS(SYMLINK_TRUST_MASK);
2877 #define ADD_STRING(val) PyModule_AddObject(m, #val, PyBytes_FromString(val))
2879 ADD_STRING(SMB2_CREATE_TAG_EXTA);
2880 ADD_STRING(SMB2_CREATE_TAG_MXAC);
2881 ADD_STRING(SMB2_CREATE_TAG_SECD);
2882 ADD_STRING(SMB2_CREATE_TAG_DHNQ);
2883 ADD_STRING(SMB2_CREATE_TAG_DHNC);
2884 ADD_STRING(SMB2_CREATE_TAG_ALSI);
2885 ADD_STRING(SMB2_CREATE_TAG_TWRP);
2886 ADD_STRING(SMB2_CREATE_TAG_QFID);
2887 ADD_STRING(SMB2_CREATE_TAG_RQLS);
2888 ADD_STRING(SMB2_CREATE_TAG_DH2Q);
2889 ADD_STRING(SMB2_CREATE_TAG_DH2C);
2890 ADD_STRING(SMB2_CREATE_TAG_AAPL);
2891 ADD_STRING(SMB2_CREATE_TAG_APP_INSTANCE_ID);
2892 ADD_STRING(SVHDX_OPEN_DEVICE_CONTEXT);
2893 ADD_STRING(SMB2_CREATE_TAG_POSIX);
2894 ADD_FLAGS(SMB2_FIND_POSIX_INFORMATION);
2895 ADD_FLAGS(FILE_SUPERSEDE);
2896 ADD_FLAGS(FILE_OPEN);
2897 ADD_FLAGS(FILE_CREATE);
2898 ADD_FLAGS(FILE_OPEN_IF);
2899 ADD_FLAGS(FILE_OVERWRITE);
2900 ADD_FLAGS(FILE_OVERWRITE_IF);
2901 ADD_FLAGS(FILE_DIRECTORY_FILE);
2903 return m;