2 * Unix SMB/CIFS implementation.
3 * Samba-internal work in progress Python binding for libsmbclient
5 * Copyright (C) Volker Lendecke 2012
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "python/py3compat.h"
24 #include "libcli/smb/smbXcli_base.h"
25 #include "libsmb/libsmb.h"
26 #include "libcli/security/security.h"
27 #include "system/select.h"
28 #include "source4/libcli/util/pyerrors.h"
29 #include "auth/credentials/pycredentials.h"
31 #include "libsmb/clirap.h"
33 static PyTypeObject *get_pytype(const char *module, const char *type)
38 mod = PyImport_ImportModule(module);
40 PyErr_Format(PyExc_RuntimeError,
41 "Unable to import %s to check type %s",
45 result = (PyTypeObject *)PyObject_GetAttrString(mod, type);
48 PyErr_Format(PyExc_RuntimeError,
49 "Unable to find type %s in module %s",
57 * We're using "const char * const *" for keywords,
58 * PyArg_ParseTupleAndKeywords expects a "char **". Confine the
59 * inevitable warnings to just one place.
61 static int ParseTupleAndKeywords(PyObject *args, PyObject *kw,
62 const char *format, const char * const *keywords,
65 char **_keywords = discard_const_p(char *, keywords);
68 va_start(a, keywords);
69 ret = PyArg_VaParseTupleAndKeywords(args, kw, format,
77 struct py_cli_oplock_break {
84 struct cli_state *cli;
86 struct tevent_context *ev;
87 int (*req_wait_fn)(struct tevent_context *ev,
88 struct tevent_req *req);
89 struct py_cli_thread *thread_state;
91 struct tevent_req *oplock_waiter;
92 struct py_cli_oplock_break *oplock_breaks;
93 struct py_tevent_cond *oplock_cond;
100 struct py_cli_thread {
103 * Pipe to make the poll thread wake up in our destructor, so
104 * that we can exit and join the thread.
106 int shutdown_pipe[2];
107 struct tevent_fd *shutdown_fde;
112 * Thread state to release the GIL during the poll(2) syscall
114 PyThreadState *py_threadstate;
117 static void *py_cli_state_poll_thread(void *private_data)
119 struct py_cli_state *self = (struct py_cli_state *)private_data;
120 struct py_cli_thread *t = self->thread_state;
121 PyGILState_STATE gstate;
123 gstate = PyGILState_Ensure();
125 while (!t->do_shutdown) {
127 ret = tevent_loop_once(self->ev);
130 PyGILState_Release(gstate);
134 static void py_cli_state_trace_callback(enum tevent_trace_point point,
137 struct py_cli_state *self = (struct py_cli_state *)private_data;
138 struct py_cli_thread *t = self->thread_state;
141 case TEVENT_TRACE_BEFORE_WAIT:
142 assert(t->py_threadstate == NULL);
143 t->py_threadstate = PyEval_SaveThread();
145 case TEVENT_TRACE_AFTER_WAIT:
146 assert(t->py_threadstate != NULL);
147 PyEval_RestoreThread(t->py_threadstate);
148 t->py_threadstate = NULL;
155 static void py_cli_state_shutdown_handler(struct tevent_context *ev,
156 struct tevent_fd *fde,
160 struct py_cli_state *self = (struct py_cli_state *)private_data;
161 struct py_cli_thread *t = self->thread_state;
163 if ((flags & TEVENT_FD_READ) == 0) {
166 TALLOC_FREE(t->shutdown_fde);
167 t->do_shutdown = true;
170 static int py_cli_thread_destructor(struct py_cli_thread *t)
178 * This will wake the poll thread from the poll(2)
180 written = write(t->shutdown_pipe[1], &c, 1);
181 } while ((written == -1) && (errno == EINTR));
184 * Allow the poll thread to do its own cleanup under the GIL
186 Py_BEGIN_ALLOW_THREADS
187 ret = pthread_join(t->id, NULL);
191 if (t->shutdown_pipe[0] != -1) {
192 close(t->shutdown_pipe[0]);
193 t->shutdown_pipe[0] = -1;
195 if (t->shutdown_pipe[1] != -1) {
196 close(t->shutdown_pipe[1]);
197 t->shutdown_pipe[1] = -1;
202 static int py_tevent_cond_req_wait(struct tevent_context *ev,
203 struct tevent_req *req);
205 static bool py_cli_state_setup_mt_ev(struct py_cli_state *self)
207 struct py_cli_thread *t = NULL;
210 self->ev = tevent_context_init_byname(NULL, "poll_mt");
211 if (self->ev == NULL) {
214 samba_tevent_set_debug(self->ev, "pylibsmb_tevent_mt");
215 tevent_set_trace_callback(self->ev, py_cli_state_trace_callback, self);
217 self->req_wait_fn = py_tevent_cond_req_wait;
219 self->thread_state = talloc_zero(NULL, struct py_cli_thread);
220 if (self->thread_state == NULL) {
223 t = self->thread_state;
225 ret = pipe(t->shutdown_pipe);
229 t->shutdown_fde = tevent_add_fd(
230 self->ev, self->ev, t->shutdown_pipe[0], TEVENT_FD_READ,
231 py_cli_state_shutdown_handler, self);
232 if (t->shutdown_fde == NULL) {
236 PyEval_InitThreads();
238 ret = pthread_create(&t->id, NULL, py_cli_state_poll_thread, self);
242 talloc_set_destructor(self->thread_state, py_cli_thread_destructor);
247 TALLOC_FREE(t->shutdown_fde);
249 if (t->shutdown_pipe[0] != -1) {
250 close(t->shutdown_pipe[0]);
251 t->shutdown_pipe[0] = -1;
253 if (t->shutdown_pipe[1] != -1) {
254 close(t->shutdown_pipe[1]);
255 t->shutdown_pipe[1] = -1;
259 TALLOC_FREE(self->thread_state);
260 TALLOC_FREE(self->ev);
264 struct py_tevent_cond {
265 pthread_mutex_t mutex;
270 static void py_tevent_signalme(struct tevent_req *req);
272 static int py_tevent_cond_wait(struct py_tevent_cond *cond)
276 result = pthread_mutex_init(&cond->mutex, NULL);
280 result = pthread_cond_init(&cond->cond, NULL);
285 result = pthread_mutex_lock(&cond->mutex);
290 cond->is_done = false;
292 while (!cond->is_done) {
294 Py_BEGIN_ALLOW_THREADS
295 result = pthread_cond_wait(&cond->cond, &cond->mutex);
304 ret = pthread_mutex_unlock(&cond->mutex);
307 ret = pthread_cond_destroy(&cond->cond);
310 ret = pthread_mutex_destroy(&cond->mutex);
316 static int py_tevent_cond_req_wait(struct tevent_context *ev,
317 struct tevent_req *req)
319 struct py_tevent_cond cond;
320 tevent_req_set_callback(req, py_tevent_signalme, &cond);
321 return py_tevent_cond_wait(&cond);
324 static void py_tevent_cond_signal(struct py_tevent_cond *cond)
328 ret = pthread_mutex_lock(&cond->mutex);
331 cond->is_done = true;
333 ret = pthread_cond_signal(&cond->cond);
335 ret = pthread_mutex_unlock(&cond->mutex);
339 static void py_tevent_signalme(struct tevent_req *req)
341 struct py_tevent_cond *cond = (struct py_tevent_cond *)
342 tevent_req_callback_data_void(req);
344 py_tevent_cond_signal(cond);
349 static int py_tevent_req_wait(struct tevent_context *ev,
350 struct tevent_req *req);
352 static bool py_cli_state_setup_ev(struct py_cli_state *self)
354 self->ev = tevent_context_init(NULL);
355 if (self->ev == NULL) {
359 samba_tevent_set_debug(self->ev, "pylibsmb_tevent");
361 self->req_wait_fn = py_tevent_req_wait;
366 static int py_tevent_req_wait(struct tevent_context *ev,
367 struct tevent_req *req)
369 while (tevent_req_is_in_progress(req)) {
372 ret = tevent_loop_once(ev);
380 static bool py_tevent_req_wait_exc(struct py_cli_state *self,
381 struct tevent_req *req)
389 ret = self->req_wait_fn(self->ev, req);
393 PyErr_SetFromErrno(PyExc_RuntimeError);
399 static PyObject *py_cli_state_new(PyTypeObject *type, PyObject *args,
402 struct py_cli_state *self;
404 self = (struct py_cli_state *)type->tp_alloc(type, 0);
409 self->is_smb1 = false;
411 self->thread_state = NULL;
412 self->oplock_waiter = NULL;
413 self->oplock_cond = NULL;
414 self->oplock_breaks = NULL;
415 return (PyObject *)self;
418 static void py_cli_got_oplock_break(struct tevent_req *req);
420 static int py_cli_state_init(struct py_cli_state *self, PyObject *args,
425 PyObject *creds = NULL;
426 struct cli_credentials *cli_creds;
427 PyObject *py_lp = Py_None;
428 PyObject *py_multi_threaded = Py_False;
429 bool multi_threaded = false;
430 PyObject *py_sign = Py_False;
432 int signing_state = SMB_SIGNING_DEFAULT;
433 PyObject *py_force_smb1 = Py_False;
434 bool force_smb1 = false;
435 struct tevent_req *req;
439 static const char *kwlist[] = {
440 "host", "share", "lp", "credentials",
441 "multi_threaded", "sign", "force_smb1",
445 PyTypeObject *py_type_Credentials = get_pytype(
446 "samba.credentials", "Credentials");
447 if (py_type_Credentials == NULL) {
451 ret = ParseTupleAndKeywords(
452 args, kwds, "ssO|O!OOO", kwlist,
453 &host, &share, &py_lp,
454 py_type_Credentials, &creds,
459 Py_DECREF(py_type_Credentials);
465 multi_threaded = PyObject_IsTrue(py_multi_threaded);
466 sign = PyObject_IsTrue(py_sign);
467 force_smb1 = PyObject_IsTrue(py_force_smb1);
470 signing_state = SMB_SIGNING_REQUIRED;
475 * As most of the cli_*_send() function
476 * don't support SMB2 (it's only plugged
477 * into the sync wrapper functions currently)
478 * we have a way to force SMB1.
480 flags = CLI_FULL_CONNECTION_FORCE_SMB1;
483 if (multi_threaded) {
485 ret = py_cli_state_setup_mt_ev(self);
490 PyErr_SetString(PyExc_RuntimeError,
491 "No PTHREAD support available");
495 PyErr_SetString(PyExc_RuntimeError,
496 "multi_threaded is only possible on "
501 ret = py_cli_state_setup_ev(self);
508 cli_creds = cli_credentials_init_anon(NULL);
510 cli_creds = PyCredentials_AsCliCredentials(creds);
513 req = cli_full_connection_creds_send(
514 NULL, self->ev, "myname", host, NULL, 0, share, "?????",
515 cli_creds, flags, signing_state);
516 if (!py_tevent_req_wait_exc(self, req)) {
519 status = cli_full_connection_creds_recv(req, &self->cli);
522 if (!NT_STATUS_IS_OK(status)) {
523 PyErr_SetNTSTATUS(status);
527 if (smbXcli_conn_protocol(self->cli->conn) < PROTOCOL_SMB2_02) {
528 self->is_smb1 = true;
532 * Oplocks require a multi threaded connection
534 if (self->thread_state == NULL) {
538 self->oplock_waiter = cli_smb_oplock_break_waiter_send(
539 self->ev, self->ev, self->cli);
540 if (self->oplock_waiter == NULL) {
544 tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
549 static void py_cli_got_oplock_break(struct tevent_req *req)
551 struct py_cli_state *self = (struct py_cli_state *)
552 tevent_req_callback_data_void(req);
553 struct py_cli_oplock_break b;
554 struct py_cli_oplock_break *tmp;
558 status = cli_smb_oplock_break_waiter_recv(req, &b.fnum, &b.level);
560 self->oplock_waiter = NULL;
562 if (!NT_STATUS_IS_OK(status)) {
566 num_breaks = talloc_array_length(self->oplock_breaks);
567 tmp = talloc_realloc(self->ev, self->oplock_breaks,
568 struct py_cli_oplock_break, num_breaks+1);
572 self->oplock_breaks = tmp;
573 self->oplock_breaks[num_breaks] = b;
575 if (self->oplock_cond != NULL) {
576 py_tevent_cond_signal(self->oplock_cond);
579 self->oplock_waiter = cli_smb_oplock_break_waiter_send(
580 self->ev, self->ev, self->cli);
581 if (self->oplock_waiter == NULL) {
584 tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
588 static PyObject *py_cli_get_oplock_break(struct py_cli_state *self,
591 size_t num_oplock_breaks;
593 if (!PyArg_ParseTuple(args, "")) {
597 if (self->thread_state == NULL) {
598 PyErr_SetString(PyExc_RuntimeError,
599 "get_oplock_break() only possible on "
600 "a multi_threaded connection");
604 if (self->oplock_cond != NULL) {
606 PyErr_SetFromErrno(PyExc_RuntimeError);
610 num_oplock_breaks = talloc_array_length(self->oplock_breaks);
612 if (num_oplock_breaks == 0) {
613 struct py_tevent_cond cond;
616 self->oplock_cond = &cond;
617 ret = py_tevent_cond_wait(&cond);
618 self->oplock_cond = NULL;
622 PyErr_SetFromErrno(PyExc_RuntimeError);
627 num_oplock_breaks = talloc_array_length(self->oplock_breaks);
628 if (num_oplock_breaks > 0) {
631 result = Py_BuildValue(
633 "fnum", self->oplock_breaks[0].fnum,
634 "level", self->oplock_breaks[0].level);
636 memmove(&self->oplock_breaks[0], &self->oplock_breaks[1],
637 sizeof(self->oplock_breaks[0]) *
638 (num_oplock_breaks - 1));
639 self->oplock_breaks = talloc_realloc(
640 NULL, self->oplock_breaks, struct py_cli_oplock_break,
641 num_oplock_breaks - 1);
648 static void py_cli_state_dealloc(struct py_cli_state *self)
650 TALLOC_FREE(self->thread_state);
651 TALLOC_FREE(self->oplock_waiter);
652 TALLOC_FREE(self->ev);
654 if (self->cli != NULL) {
655 cli_shutdown(self->cli);
658 Py_TYPE(self)->tp_free((PyObject *)self);
661 static PyObject *py_cli_settimeout(struct py_cli_state *self, PyObject *args)
663 unsigned int nmsecs = 0;
664 unsigned int omsecs = 0;
666 if (!PyArg_ParseTuple(args, "I", &nmsecs)) {
670 omsecs = cli_set_timeout(self->cli, nmsecs);
672 return PyInt_FromLong(omsecs);
675 static PyObject *py_cli_create(struct py_cli_state *self, PyObject *args,
679 unsigned CreateFlags = 0;
680 unsigned DesiredAccess = FILE_GENERIC_READ;
681 unsigned FileAttributes = 0;
682 unsigned ShareAccess = 0;
683 unsigned CreateDisposition = FILE_OPEN;
684 unsigned CreateOptions = 0;
685 unsigned ImpersonationLevel = SMB2_IMPERSONATION_IMPERSONATION;
686 unsigned SecurityFlags = 0;
688 struct tevent_req *req;
691 static const char *kwlist[] = {
692 "Name", "CreateFlags", "DesiredAccess", "FileAttributes",
693 "ShareAccess", "CreateDisposition", "CreateOptions",
694 "ImpersonationLevel", "SecurityFlags", NULL };
696 if (!ParseTupleAndKeywords(
697 args, kwds, "s|IIIIIIII", kwlist,
698 &fname, &CreateFlags, &DesiredAccess, &FileAttributes,
699 &ShareAccess, &CreateDisposition, &CreateOptions,
700 &ImpersonationLevel, &SecurityFlags)) {
704 req = cli_ntcreate_send(NULL, self->ev, self->cli, fname, CreateFlags,
705 DesiredAccess, FileAttributes, ShareAccess,
706 CreateDisposition, CreateOptions,
707 ImpersonationLevel, SecurityFlags);
708 if (!py_tevent_req_wait_exc(self, req)) {
711 status = cli_ntcreate_recv(req, &fnum, NULL);
714 if (!NT_STATUS_IS_OK(status)) {
715 PyErr_SetNTSTATUS(status);
718 return Py_BuildValue("I", (unsigned)fnum);
721 static PyObject *py_cli_close(struct py_cli_state *self, PyObject *args)
723 struct tevent_req *req;
727 if (!PyArg_ParseTuple(args, "i", &fnum)) {
731 req = cli_close_send(NULL, self->ev, self->cli, fnum);
732 if (!py_tevent_req_wait_exc(self, req)) {
735 status = cli_close_recv(req);
738 if (!NT_STATUS_IS_OK(status)) {
739 PyErr_SetNTSTATUS(status);
752 * cli_push() helper to write a chunk of data to a remote file
754 static size_t push_data(uint8_t *buf, size_t n, void *priv)
756 struct push_state *state = (struct push_state *)priv;
757 char *curr_ptr = NULL;
761 if (state->nread >= state->total_data) {
765 curr_ptr = state->data + state->nread;
766 remaining = state->total_data - state->nread;
767 copied_bytes = MIN(remaining, n);
769 memcpy(buf, curr_ptr, copied_bytes);
770 state->nread += copied_bytes;
775 * Writes a file with the contents specified
777 static PyObject *py_smb_savefile(struct py_cli_state *self, PyObject *args,
781 const char *filename = NULL;
785 struct tevent_req *req = NULL;
786 struct push_state state;
788 if (!PyArg_ParseTuple(args, "s"PYARG_BYTES_LEN":savefile", &filename,
793 /* create a new file handle for writing to */
794 req = cli_ntcreate_send(NULL, self->ev, self->cli, filename, 0,
795 FILE_WRITE_DATA, FILE_ATTRIBUTE_NORMAL,
796 FILE_SHARE_READ|FILE_SHARE_WRITE,
797 FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE,
798 SMB2_IMPERSONATION_IMPERSONATION, 0);
799 if (!py_tevent_req_wait_exc(self, req)) {
802 status = cli_ntcreate_recv(req, &fnum, NULL);
804 PyErr_NTSTATUS_IS_ERR_RAISE(status);
806 /* write the new file contents */
809 state.total_data = size;
811 req = cli_push_send(NULL, self->ev, self->cli, fnum, 0, 0, 0,
813 if (!py_tevent_req_wait_exc(self, req)) {
816 status = cli_push_recv(req);
818 PyErr_NTSTATUS_IS_ERR_RAISE(status);
820 /* close the file handle */
821 req = cli_close_send(NULL, self->ev, self->cli, fnum);
822 if (!py_tevent_req_wait_exc(self, req)) {
825 status = cli_close_recv(req);
826 PyErr_NTSTATUS_IS_ERR_RAISE(status);
831 static PyObject *py_cli_write(struct py_cli_state *self, PyObject *args,
838 unsigned long long offset;
839 struct tevent_req *req;
843 static const char *kwlist[] = {
844 "fnum", "buffer", "offset", "mode", NULL };
846 if (!ParseTupleAndKeywords(
847 args, kwds, "I" PYARG_BYTES_LEN "K|I", kwlist,
848 &fnum, &buf, &buflen, &offset, &mode)) {
852 req = cli_write_send(NULL, self->ev, self->cli, fnum, mode,
853 (uint8_t *)buf, offset, buflen);
854 if (!py_tevent_req_wait_exc(self, req)) {
857 status = cli_write_recv(req, &written);
860 if (!NT_STATUS_IS_OK(status)) {
861 PyErr_SetNTSTATUS(status);
864 return Py_BuildValue("K", (unsigned long long)written);
868 * Returns the size of the given file
870 static NTSTATUS py_smb_filesize(struct py_cli_state *self, uint16_t fnum,
876 uint8_t *rdata = NULL;
877 struct tevent_req *req = NULL;
879 req = cli_qfileinfo_send(NULL, self->ev, self->cli, fnum,
880 SMB_QUERY_FILE_ALL_INFO, 68,
882 if (!py_tevent_req_wait_exc(self, req)) {
883 return NT_STATUS_INTERNAL_ERROR;
885 status = cli_qfileinfo_recv(req, NULL, NULL, &rdata, NULL);
886 if (NT_STATUS_IS_OK(status)) {
887 *size = IVAL2_TO_SMB_BIG_UINT(rdata, 48);
892 status = cli_qfileinfo_basic(self->cli, fnum, NULL, size,
893 NULL, NULL, NULL, NULL, NULL);
899 * Loads the specified file's contents and returns it
901 static PyObject *py_smb_loadfile(struct py_cli_state *self, PyObject *args,
905 const char *filename = NULL;
906 struct tevent_req *req = NULL;
911 PyObject *result = NULL;
913 if (!PyArg_ParseTuple(args, "s:loadfile", &filename)) {
917 /* get a read file handle */
918 req = cli_ntcreate_send(NULL, self->ev, self->cli, filename, 0,
919 FILE_READ_DATA, FILE_ATTRIBUTE_NORMAL,
920 FILE_SHARE_READ, FILE_OPEN, 0,
921 SMB2_IMPERSONATION_IMPERSONATION, 0);
922 if (!py_tevent_req_wait_exc(self, req)) {
925 status = cli_ntcreate_recv(req, &fnum, NULL);
927 PyErr_NTSTATUS_IS_ERR_RAISE(status);
929 /* get a buffer to hold the file contents */
930 status = py_smb_filesize(self, fnum, &size);
931 PyErr_NTSTATUS_IS_ERR_RAISE(status);
933 result = PyBytes_FromStringAndSize(NULL, size);
934 if (result == NULL) {
938 /* read the file contents */
939 buf = PyBytes_AS_STRING(result);
940 req = cli_pull_send(NULL, self->ev, self->cli, fnum, 0, size,
941 size, cli_read_sink, &buf);
942 if (!py_tevent_req_wait_exc(self, req)) {
946 status = cli_pull_recv(req, &nread);
948 if (!NT_STATUS_IS_OK(status)) {
950 PyErr_SetNTSTATUS(status);
954 /* close the file handle */
955 req = cli_close_send(NULL, self->ev, self->cli, fnum);
956 if (!py_tevent_req_wait_exc(self, req)) {
960 status = cli_close_recv(req);
962 if (!NT_STATUS_IS_OK(status)) {
964 PyErr_SetNTSTATUS(status);
968 /* sanity-check we read the expected number of bytes */
971 PyErr_Format(PyExc_IOError,
972 "read invalid - got %zu requested %zu",
978 if (_PyBytes_Resize(&result, nread) < 0) {
986 static PyObject *py_cli_read(struct py_cli_state *self, PyObject *args,
990 unsigned long long offset;
992 struct tevent_req *req;
998 static const char *kwlist[] = {
999 "fnum", "offset", "size", NULL };
1001 if (!ParseTupleAndKeywords(
1002 args, kwds, "IKI", kwlist, &fnum, &offset,
1007 result = PyBytes_FromStringAndSize(NULL, size);
1008 if (result == NULL) {
1011 buf = PyBytes_AS_STRING(result);
1013 req = cli_read_send(NULL, self->ev, self->cli, fnum,
1015 if (!py_tevent_req_wait_exc(self, req)) {
1019 status = cli_read_recv(req, &received);
1022 if (!NT_STATUS_IS_OK(status)) {
1024 PyErr_SetNTSTATUS(status);
1028 if (received > size) {
1030 PyErr_Format(PyExc_IOError,
1031 "read invalid - got %zu requested %u",
1036 if (received < size) {
1037 if (_PyBytes_Resize(&result, received) < 0) {
1045 static PyObject *py_cli_ftruncate(struct py_cli_state *self, PyObject *args,
1049 unsigned long long size;
1050 struct tevent_req *req;
1053 static const char *kwlist[] = {
1054 "fnum", "size", NULL };
1056 if (!ParseTupleAndKeywords(
1057 args, kwds, "IK", kwlist, &fnum, &size)) {
1061 req = cli_ftruncate_send(NULL, self->ev, self->cli, fnum, size);
1062 if (!py_tevent_req_wait_exc(self, req)) {
1065 status = cli_ftruncate_recv(req);
1068 if (!NT_STATUS_IS_OK(status)) {
1069 PyErr_SetNTSTATUS(status);
1075 static PyObject *py_cli_delete_on_close(struct py_cli_state *self,
1079 unsigned fnum, flag;
1080 struct tevent_req *req;
1083 static const char *kwlist[] = {
1084 "fnum", "flag", NULL };
1086 if (!ParseTupleAndKeywords(
1087 args, kwds, "II", kwlist, &fnum, &flag)) {
1091 req = cli_nt_delete_on_close_send(NULL, self->ev, self->cli, fnum,
1093 if (!py_tevent_req_wait_exc(self, req)) {
1096 status = cli_nt_delete_on_close_recv(req);
1099 if (!NT_STATUS_IS_OK(status)) {
1100 PyErr_SetNTSTATUS(status);
1107 * Helper to add directory listing entries to an overall Python list
1109 static NTSTATUS list_helper(const char *mntpoint, struct file_info *finfo,
1110 const char *mask, void *state)
1112 PyObject *result = (PyObject *)state;
1113 PyObject *file = NULL;
1116 /* suppress '.' and '..' in the results we return */
1117 if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
1118 return NT_STATUS_OK;
1122 * Build a dictionary representing the file info.
1123 * Note: Windows does not always return short_name (so it may be None)
1125 file = Py_BuildValue("{s:s,s:i,s:s,s:O,s:l}",
1126 "name", finfo->name,
1127 "attrib", (int)finfo->mode,
1128 "short_name", finfo->short_name,
1129 "size", PyLong_FromUnsignedLongLong(finfo->size),
1131 convert_timespec_to_time_t(finfo->mtime_ts));
1134 return NT_STATUS_NO_MEMORY;
1137 ret = PyList_Append(result, file);
1139 return NT_STATUS_INTERNAL_ERROR;
1142 return NT_STATUS_OK;
1145 static NTSTATUS do_listing(struct py_cli_state *self,
1146 const char *base_dir, const char *user_mask,
1148 NTSTATUS (*callback_fn)(const char *,
1150 const char *, void *),
1154 unsigned info_level = SMB_FIND_FILE_BOTH_DIRECTORY_INFO;
1155 struct file_info *finfos = NULL;
1157 size_t num_finfos = 0;
1160 if (user_mask == NULL) {
1161 mask = talloc_asprintf(NULL, "%s\\*", base_dir);
1163 mask = talloc_asprintf(NULL, "%s\\%s", base_dir, user_mask);
1167 return NT_STATUS_NO_MEMORY;
1171 if (self->is_smb1) {
1172 struct tevent_req *req = NULL;
1174 req = cli_list_send(NULL, self->ev, self->cli, mask, attribute,
1176 if (!py_tevent_req_wait_exc(self, req)) {
1177 return NT_STATUS_INTERNAL_ERROR;
1179 status = cli_list_recv(req, NULL, &finfos, &num_finfos);
1182 status = cli_list(self->cli, mask, attribute, callback_fn,
1187 if (!NT_STATUS_IS_OK(status)) {
1191 /* invoke the callback for the async results (SMBv1 connections) */
1192 for (i = 0; i < num_finfos; i++) {
1193 status = callback_fn(base_dir, &finfos[i], user_mask,
1195 if (!NT_STATUS_IS_OK(status)) {
1196 TALLOC_FREE(finfos);
1201 TALLOC_FREE(finfos);
1205 static PyObject *py_cli_list(struct py_cli_state *self,
1210 char *user_mask = NULL;
1211 unsigned attribute =
1212 FILE_ATTRIBUTE_DIRECTORY |
1213 FILE_ATTRIBUTE_SYSTEM |
1214 FILE_ATTRIBUTE_HIDDEN;
1217 const char *kwlist[] = { "directory", "mask", "attribs", NULL };
1219 if (!ParseTupleAndKeywords(args, kwds, "z|sH:list", kwlist,
1220 &base_dir, &user_mask, &attribute)) {
1224 result = Py_BuildValue("[]");
1225 if (result == NULL) {
1229 status = do_listing(self, base_dir, user_mask, attribute,
1230 list_helper, result);
1232 if (!NT_STATUS_IS_OK(status)) {
1234 PyErr_SetNTSTATUS(status);
1244 static NTSTATUS unlink_file(struct py_cli_state *self, const char *filename)
1247 uint16_t attrs = (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
1249 if (self->is_smb1) {
1250 struct tevent_req *req = NULL;
1252 req = cli_unlink_send(NULL, self->ev, self->cli, filename,
1254 if (!py_tevent_req_wait_exc(self, req)) {
1255 return NT_STATUS_INTERNAL_ERROR;
1257 status = cli_unlink_recv(req);
1260 status = cli_unlink(self->cli, filename, attrs);
1266 static PyObject *py_smb_unlink(struct py_cli_state *self, PyObject *args)
1269 const char *filename = NULL;
1271 if (!PyArg_ParseTuple(args, "s:unlink", &filename)) {
1275 status = unlink_file(self, filename);
1276 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1282 * Delete an empty directory
1284 static NTSTATUS remove_dir(struct py_cli_state *self, const char *dirname)
1288 if (self->is_smb1) {
1289 struct tevent_req *req = NULL;
1291 req = cli_rmdir_send(NULL, self->ev, self->cli, dirname);
1292 if (!py_tevent_req_wait_exc(self, req)) {
1293 return NT_STATUS_INTERNAL_ERROR;
1295 status = cli_rmdir_recv(req);
1298 status = cli_rmdir(self->cli, dirname);
1303 static PyObject *py_smb_rmdir(struct py_cli_state *self, PyObject *args)
1306 const char *dirname;
1308 if (!PyArg_ParseTuple(args, "s:rmdir", &dirname)) {
1312 status = remove_dir(self, dirname);
1313 PyErr_NTSTATUS_IS_ERR_RAISE(status);
1319 * Create a directory
1321 static PyObject *py_smb_mkdir(struct py_cli_state *self, PyObject *args)
1324 const char *dirname;
1326 if (!PyArg_ParseTuple(args, "s:mkdir", &dirname)) {
1330 if (self->is_smb1) {
1331 struct tevent_req *req = NULL;
1333 req = cli_mkdir_send(NULL, self->ev, self->cli, dirname);
1334 if (!py_tevent_req_wait_exc(self, req)) {
1337 status = cli_mkdir_recv(req);
1340 status = cli_mkdir(self->cli, dirname);
1342 PyErr_NTSTATUS_IS_ERR_RAISE(status);
1348 * Checks existence of a directory
1350 static bool check_dir_path(struct py_cli_state *self, const char *path)
1354 if (self->is_smb1) {
1355 struct tevent_req *req = NULL;
1357 req = cli_chkpath_send(NULL, self->ev, self->cli, path);
1358 if (!py_tevent_req_wait_exc(self, req)) {
1361 status = cli_chkpath_recv(req);
1364 status = cli_chkpath(self->cli, path);
1367 return NT_STATUS_IS_OK(status);
1370 static PyObject *py_smb_chkpath(struct py_cli_state *self, PyObject *args)
1375 if (!PyArg_ParseTuple(args, "s:chkpath", &path)) {
1379 dir_exists = check_dir_path(self, path);
1380 return PyBool_FromLong(dir_exists);
1383 static PyMethodDef py_cli_state_methods[] = {
1384 { "settimeout", (PyCFunction)py_cli_settimeout, METH_VARARGS,
1385 "settimeout(new_timeout_msecs) => return old_timeout_msecs" },
1386 { "create", (PyCFunction)py_cli_create, METH_VARARGS|METH_KEYWORDS,
1388 { "close", (PyCFunction)py_cli_close, METH_VARARGS,
1389 "Close a file handle" },
1390 { "write", (PyCFunction)py_cli_write, METH_VARARGS|METH_KEYWORDS,
1391 "Write to a file handle" },
1392 { "read", (PyCFunction)py_cli_read, METH_VARARGS|METH_KEYWORDS,
1393 "Read from a file handle" },
1394 { "truncate", (PyCFunction)py_cli_ftruncate,
1395 METH_VARARGS|METH_KEYWORDS,
1396 "Truncate a file" },
1397 { "delete_on_close", (PyCFunction)py_cli_delete_on_close,
1398 METH_VARARGS|METH_KEYWORDS,
1399 "Set/Reset the delete on close flag" },
1400 { "list", (PyCFunction)py_cli_list, METH_VARARGS|METH_KEYWORDS,
1401 "list(directory, mask='*', attribs=DEFAULT_ATTRS) -> "
1402 "directory contents as a dictionary\n"
1403 "\t\tDEFAULT_ATTRS: FILE_ATTRIBUTE_SYSTEM | "
1404 "FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_ARCHIVE\n\n"
1405 "\t\tList contents of a directory. The keys are, \n"
1406 "\t\t\tname: Long name of the directory item\n"
1407 "\t\t\tshort_name: Short name of the directory item\n"
1408 "\t\t\tsize: File size in bytes\n"
1409 "\t\t\tattrib: Attributes\n"
1410 "\t\t\tmtime: Modification time\n" },
1411 { "get_oplock_break", (PyCFunction)py_cli_get_oplock_break,
1412 METH_VARARGS, "Wait for an oplock break" },
1413 { "unlink", (PyCFunction)py_smb_unlink,
1415 "unlink(path) -> None\n\n \t\tDelete a file." },
1416 { "mkdir", (PyCFunction)py_smb_mkdir, METH_VARARGS,
1417 "mkdir(path) -> None\n\n \t\tCreate a directory." },
1418 { "rmdir", (PyCFunction)py_smb_rmdir, METH_VARARGS,
1419 "rmdir(path) -> None\n\n \t\tDelete a directory." },
1420 { "chkpath", (PyCFunction)py_smb_chkpath, METH_VARARGS,
1421 "chkpath(dir_path) -> True or False\n\n"
1422 "\t\tReturn true if directory exists, false otherwise." },
1423 { "savefile", (PyCFunction)py_smb_savefile, METH_VARARGS,
1424 "savefile(path, str) -> None\n\n"
1425 "\t\tWrite " PY_DESC_PY3_BYTES " str to file." },
1426 { "loadfile", (PyCFunction)py_smb_loadfile, METH_VARARGS,
1427 "loadfile(path) -> file contents as a " PY_DESC_PY3_BYTES
1428 "\n\n\t\tRead contents of a file." },
1429 { NULL, NULL, 0, NULL }
1432 static PyTypeObject py_cli_state_type = {
1433 PyVarObject_HEAD_INIT(NULL, 0)
1434 .tp_name = "libsmb_samba_internal.Conn",
1435 .tp_basicsize = sizeof(struct py_cli_state),
1436 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1437 .tp_doc = "libsmb connection",
1438 .tp_new = py_cli_state_new,
1439 .tp_init = (initproc)py_cli_state_init,
1440 .tp_dealloc = (destructor)py_cli_state_dealloc,
1441 .tp_methods = py_cli_state_methods,
1444 static PyMethodDef py_libsmb_methods[] = {
1448 void initlibsmb_samba_internal(void);
1450 static struct PyModuleDef moduledef = {
1451 PyModuleDef_HEAD_INIT,
1452 .m_name = "libsmb_samba_internal",
1453 .m_doc = "libsmb wrapper",
1455 .m_methods = py_libsmb_methods,
1458 MODULE_INIT_FUNC(libsmb_samba_internal)
1462 talloc_stackframe();
1464 m = PyModule_Create(&moduledef);
1468 if (PyType_Ready(&py_cli_state_type) < 0) {
1471 Py_INCREF(&py_cli_state_type);
1472 PyModule_AddObject(m, "Conn", (PyObject *)&py_cli_state_type);