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/>.
26 #include "python/py3compat.h"
27 #include "libcli/smb/smbXcli_base.h"
28 #include "libsmb/libsmb.h"
29 #include "libcli/security/security.h"
30 #include "system/select.h"
31 #include "source4/libcli/util/pyerrors.h"
32 #include "auth/credentials/pycredentials.h"
34 #include "libsmb/clirap.h"
36 #define LIST_ATTRIBUTE_MASK \
37 (FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN)
39 static PyTypeObject *get_pytype(const char *module, const char *type)
44 mod = PyImport_ImportModule(module);
46 PyErr_Format(PyExc_RuntimeError,
47 "Unable to import %s to check type %s",
51 result = (PyTypeObject *)PyObject_GetAttrString(mod, type);
54 PyErr_Format(PyExc_RuntimeError,
55 "Unable to find type %s in module %s",
63 * We're using "const char * const *" for keywords,
64 * PyArg_ParseTupleAndKeywords expects a "char **". Confine the
65 * inevitable warnings to just one place.
67 static int ParseTupleAndKeywords(PyObject *args, PyObject *kw,
68 const char *format, const char * const *keywords,
71 char **_keywords = discard_const_p(char *, keywords);
74 va_start(a, keywords);
75 ret = PyArg_VaParseTupleAndKeywords(args, kw, format,
83 struct py_cli_oplock_break {
90 struct cli_state *cli;
92 struct tevent_context *ev;
93 int (*req_wait_fn)(struct tevent_context *ev,
94 struct tevent_req *req);
95 struct py_cli_thread *thread_state;
97 struct tevent_req *oplock_waiter;
98 struct py_cli_oplock_break *oplock_breaks;
99 struct py_tevent_cond *oplock_cond;
106 struct py_cli_thread {
109 * Pipe to make the poll thread wake up in our destructor, so
110 * that we can exit and join the thread.
112 int shutdown_pipe[2];
113 struct tevent_fd *shutdown_fde;
118 * Thread state to release the GIL during the poll(2) syscall
120 PyThreadState *py_threadstate;
123 static void *py_cli_state_poll_thread(void *private_data)
125 struct py_cli_state *self = (struct py_cli_state *)private_data;
126 struct py_cli_thread *t = self->thread_state;
127 PyGILState_STATE gstate;
129 gstate = PyGILState_Ensure();
131 while (!t->do_shutdown) {
133 ret = tevent_loop_once(self->ev);
136 PyGILState_Release(gstate);
140 static void py_cli_state_trace_callback(enum tevent_trace_point point,
143 struct py_cli_state *self = (struct py_cli_state *)private_data;
144 struct py_cli_thread *t = self->thread_state;
147 case TEVENT_TRACE_BEFORE_WAIT:
148 assert(t->py_threadstate == NULL);
149 t->py_threadstate = PyEval_SaveThread();
151 case TEVENT_TRACE_AFTER_WAIT:
152 assert(t->py_threadstate != NULL);
153 PyEval_RestoreThread(t->py_threadstate);
154 t->py_threadstate = NULL;
161 static void py_cli_state_shutdown_handler(struct tevent_context *ev,
162 struct tevent_fd *fde,
166 struct py_cli_state *self = (struct py_cli_state *)private_data;
167 struct py_cli_thread *t = self->thread_state;
169 if ((flags & TEVENT_FD_READ) == 0) {
172 TALLOC_FREE(t->shutdown_fde);
173 t->do_shutdown = true;
176 static int py_cli_thread_destructor(struct py_cli_thread *t)
184 * This will wake the poll thread from the poll(2)
186 written = write(t->shutdown_pipe[1], &c, 1);
187 } while ((written == -1) && (errno == EINTR));
190 * Allow the poll thread to do its own cleanup under the GIL
192 Py_BEGIN_ALLOW_THREADS
193 ret = pthread_join(t->id, NULL);
197 if (t->shutdown_pipe[0] != -1) {
198 close(t->shutdown_pipe[0]);
199 t->shutdown_pipe[0] = -1;
201 if (t->shutdown_pipe[1] != -1) {
202 close(t->shutdown_pipe[1]);
203 t->shutdown_pipe[1] = -1;
208 static int py_tevent_cond_req_wait(struct tevent_context *ev,
209 struct tevent_req *req);
211 static bool py_cli_state_setup_mt_ev(struct py_cli_state *self)
213 struct py_cli_thread *t = NULL;
216 self->ev = tevent_context_init_byname(NULL, "poll_mt");
217 if (self->ev == NULL) {
220 samba_tevent_set_debug(self->ev, "pylibsmb_tevent_mt");
221 tevent_set_trace_callback(self->ev, py_cli_state_trace_callback, self);
223 self->req_wait_fn = py_tevent_cond_req_wait;
225 self->thread_state = talloc_zero(NULL, struct py_cli_thread);
226 if (self->thread_state == NULL) {
229 t = self->thread_state;
231 ret = pipe(t->shutdown_pipe);
235 t->shutdown_fde = tevent_add_fd(
236 self->ev, self->ev, t->shutdown_pipe[0], TEVENT_FD_READ,
237 py_cli_state_shutdown_handler, self);
238 if (t->shutdown_fde == NULL) {
242 PyEval_InitThreads();
244 ret = pthread_create(&t->id, NULL, py_cli_state_poll_thread, self);
248 talloc_set_destructor(self->thread_state, py_cli_thread_destructor);
253 TALLOC_FREE(t->shutdown_fde);
255 if (t->shutdown_pipe[0] != -1) {
256 close(t->shutdown_pipe[0]);
257 t->shutdown_pipe[0] = -1;
259 if (t->shutdown_pipe[1] != -1) {
260 close(t->shutdown_pipe[1]);
261 t->shutdown_pipe[1] = -1;
265 TALLOC_FREE(self->thread_state);
266 TALLOC_FREE(self->ev);
270 struct py_tevent_cond {
271 pthread_mutex_t mutex;
276 static void py_tevent_signalme(struct tevent_req *req);
278 static int py_tevent_cond_wait(struct py_tevent_cond *cond)
282 result = pthread_mutex_init(&cond->mutex, NULL);
286 result = pthread_cond_init(&cond->cond, NULL);
291 result = pthread_mutex_lock(&cond->mutex);
296 cond->is_done = false;
298 while (!cond->is_done) {
300 Py_BEGIN_ALLOW_THREADS
301 result = pthread_cond_wait(&cond->cond, &cond->mutex);
310 ret = pthread_mutex_unlock(&cond->mutex);
313 ret = pthread_cond_destroy(&cond->cond);
316 ret = pthread_mutex_destroy(&cond->mutex);
322 static int py_tevent_cond_req_wait(struct tevent_context *ev,
323 struct tevent_req *req)
325 struct py_tevent_cond cond;
326 tevent_req_set_callback(req, py_tevent_signalme, &cond);
327 return py_tevent_cond_wait(&cond);
330 static void py_tevent_cond_signal(struct py_tevent_cond *cond)
334 ret = pthread_mutex_lock(&cond->mutex);
337 cond->is_done = true;
339 ret = pthread_cond_signal(&cond->cond);
341 ret = pthread_mutex_unlock(&cond->mutex);
345 static void py_tevent_signalme(struct tevent_req *req)
347 struct py_tevent_cond *cond = (struct py_tevent_cond *)
348 tevent_req_callback_data_void(req);
350 py_tevent_cond_signal(cond);
355 static int py_tevent_req_wait(struct tevent_context *ev,
356 struct tevent_req *req);
358 static bool py_cli_state_setup_ev(struct py_cli_state *self)
360 self->ev = tevent_context_init(NULL);
361 if (self->ev == NULL) {
365 samba_tevent_set_debug(self->ev, "pylibsmb_tevent");
367 self->req_wait_fn = py_tevent_req_wait;
372 static int py_tevent_req_wait(struct tevent_context *ev,
373 struct tevent_req *req)
375 while (tevent_req_is_in_progress(req)) {
378 ret = tevent_loop_once(ev);
386 static bool py_tevent_req_wait_exc(struct py_cli_state *self,
387 struct tevent_req *req)
395 ret = self->req_wait_fn(self->ev, req);
399 PyErr_SetFromErrno(PyExc_RuntimeError);
405 static PyObject *py_cli_state_new(PyTypeObject *type, PyObject *args,
408 struct py_cli_state *self;
410 self = (struct py_cli_state *)type->tp_alloc(type, 0);
415 self->is_smb1 = false;
417 self->thread_state = NULL;
418 self->oplock_waiter = NULL;
419 self->oplock_cond = NULL;
420 self->oplock_breaks = NULL;
421 return (PyObject *)self;
424 static void py_cli_got_oplock_break(struct tevent_req *req);
426 static int py_cli_state_init(struct py_cli_state *self, PyObject *args,
431 PyObject *creds = NULL;
432 struct cli_credentials *cli_creds;
433 PyObject *py_lp = Py_None;
434 PyObject *py_multi_threaded = Py_False;
435 bool multi_threaded = false;
436 PyObject *py_sign = Py_False;
438 int signing_state = SMB_SIGNING_DEFAULT;
439 PyObject *py_force_smb1 = Py_False;
440 bool force_smb1 = false;
441 struct tevent_req *req;
445 static const char *kwlist[] = {
446 "host", "share", "lp", "creds",
447 "multi_threaded", "sign", "force_smb1",
451 PyTypeObject *py_type_Credentials = get_pytype(
452 "samba.credentials", "Credentials");
453 if (py_type_Credentials == NULL) {
457 ret = ParseTupleAndKeywords(
458 args, kwds, "ssO|O!OOO", kwlist,
459 &host, &share, &py_lp,
460 py_type_Credentials, &creds,
465 Py_DECREF(py_type_Credentials);
471 multi_threaded = PyObject_IsTrue(py_multi_threaded);
472 sign = PyObject_IsTrue(py_sign);
473 force_smb1 = PyObject_IsTrue(py_force_smb1);
476 signing_state = SMB_SIGNING_REQUIRED;
481 * As most of the cli_*_send() function
482 * don't support SMB2 (it's only plugged
483 * into the sync wrapper functions currently)
484 * we have a way to force SMB1.
486 flags = CLI_FULL_CONNECTION_FORCE_SMB1;
489 if (multi_threaded) {
491 ret = py_cli_state_setup_mt_ev(self);
496 PyErr_SetString(PyExc_RuntimeError,
497 "No PTHREAD support available");
501 PyErr_SetString(PyExc_RuntimeError,
502 "multi_threaded is only possible on "
507 ret = py_cli_state_setup_ev(self);
514 cli_creds = cli_credentials_init_anon(NULL);
516 cli_creds = PyCredentials_AsCliCredentials(creds);
519 req = cli_full_connection_creds_send(
520 NULL, self->ev, "myname", host, NULL, 0, share, "?????",
521 cli_creds, flags, signing_state);
522 if (!py_tevent_req_wait_exc(self, req)) {
525 status = cli_full_connection_creds_recv(req, &self->cli);
528 if (!NT_STATUS_IS_OK(status)) {
529 PyErr_SetNTSTATUS(status);
533 if (smbXcli_conn_protocol(self->cli->conn) < PROTOCOL_SMB2_02) {
534 self->is_smb1 = true;
538 * Oplocks require a multi threaded connection
540 if (self->thread_state == NULL) {
544 self->oplock_waiter = cli_smb_oplock_break_waiter_send(
545 self->ev, self->ev, self->cli);
546 if (self->oplock_waiter == NULL) {
550 tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
555 static void py_cli_got_oplock_break(struct tevent_req *req)
557 struct py_cli_state *self = (struct py_cli_state *)
558 tevent_req_callback_data_void(req);
559 struct py_cli_oplock_break b;
560 struct py_cli_oplock_break *tmp;
564 status = cli_smb_oplock_break_waiter_recv(req, &b.fnum, &b.level);
566 self->oplock_waiter = NULL;
568 if (!NT_STATUS_IS_OK(status)) {
572 num_breaks = talloc_array_length(self->oplock_breaks);
573 tmp = talloc_realloc(self->ev, self->oplock_breaks,
574 struct py_cli_oplock_break, num_breaks+1);
578 self->oplock_breaks = tmp;
579 self->oplock_breaks[num_breaks] = b;
581 if (self->oplock_cond != NULL) {
582 py_tevent_cond_signal(self->oplock_cond);
585 self->oplock_waiter = cli_smb_oplock_break_waiter_send(
586 self->ev, self->ev, self->cli);
587 if (self->oplock_waiter == NULL) {
590 tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
594 static PyObject *py_cli_get_oplock_break(struct py_cli_state *self,
597 size_t num_oplock_breaks;
599 if (!PyArg_ParseTuple(args, "")) {
603 if (self->thread_state == NULL) {
604 PyErr_SetString(PyExc_RuntimeError,
605 "get_oplock_break() only possible on "
606 "a multi_threaded connection");
610 if (self->oplock_cond != NULL) {
612 PyErr_SetFromErrno(PyExc_RuntimeError);
616 num_oplock_breaks = talloc_array_length(self->oplock_breaks);
618 if (num_oplock_breaks == 0) {
619 struct py_tevent_cond cond;
622 self->oplock_cond = &cond;
623 ret = py_tevent_cond_wait(&cond);
624 self->oplock_cond = NULL;
628 PyErr_SetFromErrno(PyExc_RuntimeError);
633 num_oplock_breaks = talloc_array_length(self->oplock_breaks);
634 if (num_oplock_breaks > 0) {
637 result = Py_BuildValue(
639 "fnum", self->oplock_breaks[0].fnum,
640 "level", self->oplock_breaks[0].level);
642 memmove(&self->oplock_breaks[0], &self->oplock_breaks[1],
643 sizeof(self->oplock_breaks[0]) *
644 (num_oplock_breaks - 1));
645 self->oplock_breaks = talloc_realloc(
646 NULL, self->oplock_breaks, struct py_cli_oplock_break,
647 num_oplock_breaks - 1);
654 static void py_cli_state_dealloc(struct py_cli_state *self)
656 TALLOC_FREE(self->thread_state);
657 TALLOC_FREE(self->oplock_waiter);
658 TALLOC_FREE(self->ev);
660 if (self->cli != NULL) {
661 cli_shutdown(self->cli);
664 Py_TYPE(self)->tp_free((PyObject *)self);
667 static PyObject *py_cli_settimeout(struct py_cli_state *self, PyObject *args)
669 unsigned int nmsecs = 0;
670 unsigned int omsecs = 0;
672 if (!PyArg_ParseTuple(args, "I", &nmsecs)) {
676 omsecs = cli_set_timeout(self->cli, nmsecs);
678 return PyInt_FromLong(omsecs);
681 static PyObject *py_cli_create(struct py_cli_state *self, PyObject *args,
685 unsigned CreateFlags = 0;
686 unsigned DesiredAccess = FILE_GENERIC_READ;
687 unsigned FileAttributes = 0;
688 unsigned ShareAccess = 0;
689 unsigned CreateDisposition = FILE_OPEN;
690 unsigned CreateOptions = 0;
691 unsigned ImpersonationLevel = SMB2_IMPERSONATION_IMPERSONATION;
692 unsigned SecurityFlags = 0;
694 struct tevent_req *req;
697 static const char *kwlist[] = {
698 "Name", "CreateFlags", "DesiredAccess", "FileAttributes",
699 "ShareAccess", "CreateDisposition", "CreateOptions",
700 "ImpersonationLevel", "SecurityFlags", NULL };
702 if (!ParseTupleAndKeywords(
703 args, kwds, "s|IIIIIIII", kwlist,
704 &fname, &CreateFlags, &DesiredAccess, &FileAttributes,
705 &ShareAccess, &CreateDisposition, &CreateOptions,
706 &ImpersonationLevel, &SecurityFlags)) {
710 req = cli_ntcreate_send(NULL, self->ev, self->cli, fname, CreateFlags,
711 DesiredAccess, FileAttributes, ShareAccess,
712 CreateDisposition, CreateOptions,
713 ImpersonationLevel, SecurityFlags);
714 if (!py_tevent_req_wait_exc(self, req)) {
717 status = cli_ntcreate_recv(req, &fnum, NULL);
720 if (!NT_STATUS_IS_OK(status)) {
721 PyErr_SetNTSTATUS(status);
724 return Py_BuildValue("I", (unsigned)fnum);
727 static PyObject *py_cli_close(struct py_cli_state *self, PyObject *args)
729 struct tevent_req *req;
733 if (!PyArg_ParseTuple(args, "i", &fnum)) {
737 req = cli_close_send(NULL, self->ev, self->cli, fnum);
738 if (!py_tevent_req_wait_exc(self, req)) {
741 status = cli_close_recv(req);
744 if (!NT_STATUS_IS_OK(status)) {
745 PyErr_SetNTSTATUS(status);
758 * cli_push() helper to write a chunk of data to a remote file
760 static size_t push_data(uint8_t *buf, size_t n, void *priv)
762 struct push_state *state = (struct push_state *)priv;
763 char *curr_ptr = NULL;
767 if (state->nread >= state->total_data) {
771 curr_ptr = state->data + state->nread;
772 remaining = state->total_data - state->nread;
773 copied_bytes = MIN(remaining, n);
775 memcpy(buf, curr_ptr, copied_bytes);
776 state->nread += copied_bytes;
781 * Writes a file with the contents specified
783 static PyObject *py_smb_savefile(struct py_cli_state *self, PyObject *args,
787 const char *filename = NULL;
791 struct tevent_req *req = NULL;
792 struct push_state state;
794 if (!PyArg_ParseTuple(args, "s"PYARG_BYTES_LEN":savefile", &filename,
799 /* create a new file handle for writing to */
800 req = cli_ntcreate_send(NULL, self->ev, self->cli, filename, 0,
801 FILE_WRITE_DATA, FILE_ATTRIBUTE_NORMAL,
802 FILE_SHARE_READ|FILE_SHARE_WRITE,
803 FILE_OVERWRITE_IF, FILE_NON_DIRECTORY_FILE,
804 SMB2_IMPERSONATION_IMPERSONATION, 0);
805 if (!py_tevent_req_wait_exc(self, req)) {
808 status = cli_ntcreate_recv(req, &fnum, NULL);
810 PyErr_NTSTATUS_IS_ERR_RAISE(status);
812 /* write the new file contents */
815 state.total_data = size;
817 req = cli_push_send(NULL, self->ev, self->cli, fnum, 0, 0, 0,
819 if (!py_tevent_req_wait_exc(self, req)) {
822 status = cli_push_recv(req);
824 PyErr_NTSTATUS_IS_ERR_RAISE(status);
826 /* close the file handle */
827 req = cli_close_send(NULL, self->ev, self->cli, fnum);
828 if (!py_tevent_req_wait_exc(self, req)) {
831 status = cli_close_recv(req);
832 PyErr_NTSTATUS_IS_ERR_RAISE(status);
837 static PyObject *py_cli_write(struct py_cli_state *self, PyObject *args,
844 unsigned long long offset;
845 struct tevent_req *req;
849 static const char *kwlist[] = {
850 "fnum", "buffer", "offset", "mode", NULL };
852 if (!ParseTupleAndKeywords(
853 args, kwds, "I" PYARG_BYTES_LEN "K|I", kwlist,
854 &fnum, &buf, &buflen, &offset, &mode)) {
858 req = cli_write_send(NULL, self->ev, self->cli, fnum, mode,
859 (uint8_t *)buf, offset, buflen);
860 if (!py_tevent_req_wait_exc(self, req)) {
863 status = cli_write_recv(req, &written);
866 if (!NT_STATUS_IS_OK(status)) {
867 PyErr_SetNTSTATUS(status);
870 return Py_BuildValue("K", (unsigned long long)written);
874 * Returns the size of the given file
876 static NTSTATUS py_smb_filesize(struct py_cli_state *self, uint16_t fnum,
882 uint8_t *rdata = NULL;
883 struct tevent_req *req = NULL;
885 req = cli_qfileinfo_send(NULL, self->ev, self->cli, fnum,
886 SMB_QUERY_FILE_ALL_INFO, 68,
888 if (!py_tevent_req_wait_exc(self, req)) {
889 return NT_STATUS_INTERNAL_ERROR;
891 status = cli_qfileinfo_recv(req, NULL, NULL, &rdata, NULL);
892 if (NT_STATUS_IS_OK(status)) {
893 *size = IVAL2_TO_SMB_BIG_UINT(rdata, 48);
898 status = cli_qfileinfo_basic(self->cli, fnum, NULL, size,
899 NULL, NULL, NULL, NULL, NULL);
905 * Loads the specified file's contents and returns it
907 static PyObject *py_smb_loadfile(struct py_cli_state *self, PyObject *args,
911 const char *filename = NULL;
912 struct tevent_req *req = NULL;
917 PyObject *result = NULL;
919 if (!PyArg_ParseTuple(args, "s:loadfile", &filename)) {
923 /* get a read file handle */
924 req = cli_ntcreate_send(NULL, self->ev, self->cli, filename, 0,
925 FILE_READ_DATA, FILE_ATTRIBUTE_NORMAL,
926 FILE_SHARE_READ, FILE_OPEN, 0,
927 SMB2_IMPERSONATION_IMPERSONATION, 0);
928 if (!py_tevent_req_wait_exc(self, req)) {
931 status = cli_ntcreate_recv(req, &fnum, NULL);
933 PyErr_NTSTATUS_IS_ERR_RAISE(status);
935 /* get a buffer to hold the file contents */
936 status = py_smb_filesize(self, fnum, &size);
937 PyErr_NTSTATUS_IS_ERR_RAISE(status);
939 result = PyBytes_FromStringAndSize(NULL, size);
940 if (result == NULL) {
944 /* read the file contents */
945 buf = PyBytes_AS_STRING(result);
946 req = cli_pull_send(NULL, self->ev, self->cli, fnum, 0, size,
947 size, cli_read_sink, &buf);
948 if (!py_tevent_req_wait_exc(self, req)) {
952 status = cli_pull_recv(req, &nread);
954 if (!NT_STATUS_IS_OK(status)) {
956 PyErr_SetNTSTATUS(status);
960 /* close the file handle */
961 req = cli_close_send(NULL, self->ev, self->cli, fnum);
962 if (!py_tevent_req_wait_exc(self, req)) {
966 status = cli_close_recv(req);
968 if (!NT_STATUS_IS_OK(status)) {
970 PyErr_SetNTSTATUS(status);
974 /* sanity-check we read the expected number of bytes */
977 PyErr_Format(PyExc_IOError,
978 "read invalid - got %zu requested %zu",
984 if (_PyBytes_Resize(&result, nread) < 0) {
992 static PyObject *py_cli_read(struct py_cli_state *self, PyObject *args,
996 unsigned long long offset;
998 struct tevent_req *req;
1004 static const char *kwlist[] = {
1005 "fnum", "offset", "size", NULL };
1007 if (!ParseTupleAndKeywords(
1008 args, kwds, "IKI", kwlist, &fnum, &offset,
1013 result = PyBytes_FromStringAndSize(NULL, size);
1014 if (result == NULL) {
1017 buf = PyBytes_AS_STRING(result);
1019 req = cli_read_send(NULL, self->ev, self->cli, fnum,
1021 if (!py_tevent_req_wait_exc(self, req)) {
1025 status = cli_read_recv(req, &received);
1028 if (!NT_STATUS_IS_OK(status)) {
1030 PyErr_SetNTSTATUS(status);
1034 if (received > size) {
1036 PyErr_Format(PyExc_IOError,
1037 "read invalid - got %zu requested %u",
1042 if (received < size) {
1043 if (_PyBytes_Resize(&result, received) < 0) {
1051 static PyObject *py_cli_ftruncate(struct py_cli_state *self, PyObject *args,
1055 unsigned long long size;
1056 struct tevent_req *req;
1059 static const char *kwlist[] = {
1060 "fnum", "size", NULL };
1062 if (!ParseTupleAndKeywords(
1063 args, kwds, "IK", kwlist, &fnum, &size)) {
1067 req = cli_ftruncate_send(NULL, self->ev, self->cli, fnum, size);
1068 if (!py_tevent_req_wait_exc(self, req)) {
1071 status = cli_ftruncate_recv(req);
1074 if (!NT_STATUS_IS_OK(status)) {
1075 PyErr_SetNTSTATUS(status);
1081 static PyObject *py_cli_delete_on_close(struct py_cli_state *self,
1085 unsigned fnum, flag;
1086 struct tevent_req *req;
1089 static const char *kwlist[] = {
1090 "fnum", "flag", NULL };
1092 if (!ParseTupleAndKeywords(
1093 args, kwds, "II", kwlist, &fnum, &flag)) {
1097 req = cli_nt_delete_on_close_send(NULL, self->ev, self->cli, fnum,
1099 if (!py_tevent_req_wait_exc(self, req)) {
1102 status = cli_nt_delete_on_close_recv(req);
1105 if (!NT_STATUS_IS_OK(status)) {
1106 PyErr_SetNTSTATUS(status);
1113 * Helper to add directory listing entries to an overall Python list
1115 static NTSTATUS list_helper(const char *mntpoint, struct file_info *finfo,
1116 const char *mask, void *state)
1118 PyObject *result = (PyObject *)state;
1119 PyObject *file = NULL;
1122 /* suppress '.' and '..' in the results we return */
1123 if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
1124 return NT_STATUS_OK;
1128 * Build a dictionary representing the file info.
1129 * Note: Windows does not always return short_name (so it may be None)
1131 file = Py_BuildValue("{s:s,s:i,s:s,s:O,s:l}",
1132 "name", finfo->name,
1133 "attrib", (int)finfo->mode,
1134 "short_name", finfo->short_name,
1135 "size", PyLong_FromUnsignedLongLong(finfo->size),
1137 convert_timespec_to_time_t(finfo->mtime_ts));
1140 return NT_STATUS_NO_MEMORY;
1143 ret = PyList_Append(result, file);
1145 return NT_STATUS_INTERNAL_ERROR;
1148 return NT_STATUS_OK;
1151 static NTSTATUS do_listing(struct py_cli_state *self,
1152 const char *base_dir, const char *user_mask,
1154 NTSTATUS (*callback_fn)(const char *,
1156 const char *, void *),
1160 unsigned int info_level = SMB_FIND_FILE_BOTH_DIRECTORY_INFO;
1161 struct file_info *finfos = NULL;
1163 size_t num_finfos = 0;
1166 if (user_mask == NULL) {
1167 mask = talloc_asprintf(NULL, "%s\\*", base_dir);
1169 mask = talloc_asprintf(NULL, "%s\\%s", base_dir, user_mask);
1173 return NT_STATUS_NO_MEMORY;
1177 if (self->is_smb1) {
1178 struct tevent_req *req = NULL;
1180 req = cli_list_send(NULL, self->ev, self->cli, mask, attribute,
1182 if (!py_tevent_req_wait_exc(self, req)) {
1183 return NT_STATUS_INTERNAL_ERROR;
1185 status = cli_list_recv(req, NULL, &finfos, &num_finfos);
1188 status = cli_list(self->cli, mask, attribute, callback_fn,
1193 if (!NT_STATUS_IS_OK(status)) {
1197 /* invoke the callback for the async results (SMBv1 connections) */
1198 for (i = 0; i < num_finfos; i++) {
1199 status = callback_fn(base_dir, &finfos[i], user_mask,
1201 if (!NT_STATUS_IS_OK(status)) {
1202 TALLOC_FREE(finfos);
1207 TALLOC_FREE(finfos);
1211 static PyObject *py_cli_list(struct py_cli_state *self,
1216 char *user_mask = NULL;
1217 unsigned int attribute = LIST_ATTRIBUTE_MASK;
1220 const char *kwlist[] = { "directory", "mask", "attribs", NULL };
1222 if (!ParseTupleAndKeywords(args, kwds, "z|sH:list", kwlist,
1223 &base_dir, &user_mask, &attribute)) {
1227 result = Py_BuildValue("[]");
1228 if (result == NULL) {
1232 status = do_listing(self, base_dir, user_mask, attribute,
1233 list_helper, result);
1235 if (!NT_STATUS_IS_OK(status)) {
1237 PyErr_SetNTSTATUS(status);
1247 static NTSTATUS unlink_file(struct py_cli_state *self, const char *filename)
1250 uint16_t attrs = (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
1252 if (self->is_smb1) {
1253 struct tevent_req *req = NULL;
1255 req = cli_unlink_send(NULL, self->ev, self->cli, filename,
1257 if (!py_tevent_req_wait_exc(self, req)) {
1258 return NT_STATUS_INTERNAL_ERROR;
1260 status = cli_unlink_recv(req);
1263 status = cli_unlink(self->cli, filename, attrs);
1269 static PyObject *py_smb_unlink(struct py_cli_state *self, PyObject *args)
1272 const char *filename = NULL;
1274 if (!PyArg_ParseTuple(args, "s:unlink", &filename)) {
1278 status = unlink_file(self, filename);
1279 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1285 * Delete an empty directory
1287 static NTSTATUS remove_dir(struct py_cli_state *self, const char *dirname)
1291 if (self->is_smb1) {
1292 struct tevent_req *req = NULL;
1294 req = cli_rmdir_send(NULL, self->ev, self->cli, dirname);
1295 if (!py_tevent_req_wait_exc(self, req)) {
1296 return NT_STATUS_INTERNAL_ERROR;
1298 status = cli_rmdir_recv(req);
1301 status = cli_rmdir(self->cli, dirname);
1306 static PyObject *py_smb_rmdir(struct py_cli_state *self, PyObject *args)
1309 const char *dirname;
1311 if (!PyArg_ParseTuple(args, "s:rmdir", &dirname)) {
1315 status = remove_dir(self, dirname);
1316 PyErr_NTSTATUS_IS_ERR_RAISE(status);
1322 * Create a directory
1324 static PyObject *py_smb_mkdir(struct py_cli_state *self, PyObject *args)
1327 const char *dirname;
1329 if (!PyArg_ParseTuple(args, "s:mkdir", &dirname)) {
1333 if (self->is_smb1) {
1334 struct tevent_req *req = NULL;
1336 req = cli_mkdir_send(NULL, self->ev, self->cli, dirname);
1337 if (!py_tevent_req_wait_exc(self, req)) {
1340 status = cli_mkdir_recv(req);
1343 status = cli_mkdir(self->cli, dirname);
1345 PyErr_NTSTATUS_IS_ERR_RAISE(status);
1351 * Checks existence of a directory
1353 static bool check_dir_path(struct py_cli_state *self, const char *path)
1357 if (self->is_smb1) {
1358 struct tevent_req *req = NULL;
1360 req = cli_chkpath_send(NULL, self->ev, self->cli, path);
1361 if (!py_tevent_req_wait_exc(self, req)) {
1364 status = cli_chkpath_recv(req);
1367 status = cli_chkpath(self->cli, path);
1370 return NT_STATUS_IS_OK(status);
1373 static PyObject *py_smb_chkpath(struct py_cli_state *self, PyObject *args)
1378 if (!PyArg_ParseTuple(args, "s:chkpath", &path)) {
1382 dir_exists = check_dir_path(self, path);
1383 return PyBool_FromLong(dir_exists);
1386 struct deltree_state {
1387 struct py_cli_state *self;
1388 const char *full_dirpath;
1391 static NTSTATUS delete_dir_tree(struct py_cli_state *self,
1392 const char *dirpath);
1395 * Deletes a single item in the directory tree. This could be either a file
1396 * or a directory. This function gets invoked as a callback for every item in
1397 * the given directory's listings.
1399 static NTSTATUS delete_tree_callback(const char *mntpoint,
1400 struct file_info *finfo,
1401 const char *mask, void *priv)
1403 char *filepath = NULL;
1404 struct deltree_state *state = priv;
1407 /* skip '.' or '..' directory listings */
1408 if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
1409 return NT_STATUS_OK;
1412 /* get the absolute filepath */
1413 filepath = talloc_asprintf(NULL, "%s\\%s", state->full_dirpath,
1415 if (filepath == NULL) {
1416 return NT_STATUS_NO_MEMORY;
1419 if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
1421 /* recursively delete the sub-directory and its contents */
1422 status = delete_dir_tree(state->self, filepath);
1424 status = unlink_file(state->self, filepath);
1427 TALLOC_FREE(filepath);
1432 * Removes a directory and all its contents
1434 static NTSTATUS delete_dir_tree(struct py_cli_state *self,
1435 const char *filepath)
1438 const char *mask = "*";
1439 struct deltree_state state = { 0 };
1441 /* go through the directory's contents, deleting each item */
1443 state.full_dirpath = filepath;
1444 status = do_listing(self, filepath, mask, LIST_ATTRIBUTE_MASK,
1445 delete_tree_callback, &state);
1447 /* remove the directory itself */
1448 if (NT_STATUS_IS_OK(status)) {
1449 status = remove_dir(self, filepath);
1454 static PyObject *py_smb_deltree(struct py_cli_state *self, PyObject *args)
1457 const char *filepath = NULL;
1460 if (!PyArg_ParseTuple(args, "s:deltree", &filepath)) {
1464 /* check whether we're removing a directory or a file */
1465 dir_exists = check_dir_path(self, filepath);
1468 status = delete_dir_tree(self, filepath);
1470 status = unlink_file(self, filepath);
1473 PyErr_NTSTATUS_IS_ERR_RAISE(status);
1478 static PyMethodDef py_cli_state_methods[] = {
1479 { "settimeout", (PyCFunction)py_cli_settimeout, METH_VARARGS,
1480 "settimeout(new_timeout_msecs) => return old_timeout_msecs" },
1481 { "create", (PyCFunction)py_cli_create, METH_VARARGS|METH_KEYWORDS,
1483 { "close", (PyCFunction)py_cli_close, METH_VARARGS,
1484 "Close a file handle" },
1485 { "write", (PyCFunction)py_cli_write, METH_VARARGS|METH_KEYWORDS,
1486 "Write to a file handle" },
1487 { "read", (PyCFunction)py_cli_read, METH_VARARGS|METH_KEYWORDS,
1488 "Read from a file handle" },
1489 { "truncate", (PyCFunction)py_cli_ftruncate,
1490 METH_VARARGS|METH_KEYWORDS,
1491 "Truncate a file" },
1492 { "delete_on_close", (PyCFunction)py_cli_delete_on_close,
1493 METH_VARARGS|METH_KEYWORDS,
1494 "Set/Reset the delete on close flag" },
1495 { "list", (PyCFunction)py_cli_list, METH_VARARGS|METH_KEYWORDS,
1496 "list(directory, mask='*', attribs=DEFAULT_ATTRS) -> "
1497 "directory contents as a dictionary\n"
1498 "\t\tDEFAULT_ATTRS: FILE_ATTRIBUTE_SYSTEM | "
1499 "FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_ARCHIVE\n\n"
1500 "\t\tList contents of a directory. The keys are, \n"
1501 "\t\t\tname: Long name of the directory item\n"
1502 "\t\t\tshort_name: Short name of the directory item\n"
1503 "\t\t\tsize: File size in bytes\n"
1504 "\t\t\tattrib: Attributes\n"
1505 "\t\t\tmtime: Modification time\n" },
1506 { "get_oplock_break", (PyCFunction)py_cli_get_oplock_break,
1507 METH_VARARGS, "Wait for an oplock break" },
1508 { "unlink", (PyCFunction)py_smb_unlink,
1510 "unlink(path) -> None\n\n \t\tDelete a file." },
1511 { "mkdir", (PyCFunction)py_smb_mkdir, METH_VARARGS,
1512 "mkdir(path) -> None\n\n \t\tCreate a directory." },
1513 { "rmdir", (PyCFunction)py_smb_rmdir, METH_VARARGS,
1514 "rmdir(path) -> None\n\n \t\tDelete a directory." },
1515 { "chkpath", (PyCFunction)py_smb_chkpath, METH_VARARGS,
1516 "chkpath(dir_path) -> True or False\n\n"
1517 "\t\tReturn true if directory exists, false otherwise." },
1518 { "savefile", (PyCFunction)py_smb_savefile, METH_VARARGS,
1519 "savefile(path, str) -> None\n\n"
1520 "\t\tWrite " PY_DESC_PY3_BYTES " str to file." },
1521 { "loadfile", (PyCFunction)py_smb_loadfile, METH_VARARGS,
1522 "loadfile(path) -> file contents as a " PY_DESC_PY3_BYTES
1523 "\n\n\t\tRead contents of a file." },
1524 { "deltree", (PyCFunction)py_smb_deltree, METH_VARARGS,
1525 "deltree(path) -> None\n\n"
1526 "\t\tDelete a directory and all its contents." },
1527 { NULL, NULL, 0, NULL }
1530 static PyTypeObject py_cli_state_type = {
1531 PyVarObject_HEAD_INIT(NULL, 0)
1532 .tp_name = "libsmb_samba_internal.Conn",
1533 .tp_basicsize = sizeof(struct py_cli_state),
1534 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
1535 .tp_doc = "libsmb connection",
1536 .tp_new = py_cli_state_new,
1537 .tp_init = (initproc)py_cli_state_init,
1538 .tp_dealloc = (destructor)py_cli_state_dealloc,
1539 .tp_methods = py_cli_state_methods,
1542 static PyMethodDef py_libsmb_methods[] = {
1546 void initlibsmb_samba_internal(void);
1548 static struct PyModuleDef moduledef = {
1549 PyModuleDef_HEAD_INIT,
1550 .m_name = "libsmb_samba_internal",
1551 .m_doc = "libsmb wrapper",
1553 .m_methods = py_libsmb_methods,
1556 MODULE_INIT_FUNC(libsmb_samba_internal)
1560 talloc_stackframe();
1562 m = PyModule_Create(&moduledef);
1566 if (PyType_Ready(&py_cli_state_type) < 0) {
1569 Py_INCREF(&py_cli_state_type);
1570 PyModule_AddObject(m, "Conn", (PyObject *)&py_cli_state_type);
1572 #define ADD_FLAGS(val) PyModule_AddObject(m, #val, PyInt_FromLong(val))
1574 ADD_FLAGS(FILE_ATTRIBUTE_READONLY);
1575 ADD_FLAGS(FILE_ATTRIBUTE_HIDDEN);
1576 ADD_FLAGS(FILE_ATTRIBUTE_SYSTEM);
1577 ADD_FLAGS(FILE_ATTRIBUTE_VOLUME);
1578 ADD_FLAGS(FILE_ATTRIBUTE_DIRECTORY);
1579 ADD_FLAGS(FILE_ATTRIBUTE_ARCHIVE);
1580 ADD_FLAGS(FILE_ATTRIBUTE_DEVICE);
1581 ADD_FLAGS(FILE_ATTRIBUTE_NORMAL);
1582 ADD_FLAGS(FILE_ATTRIBUTE_TEMPORARY);
1583 ADD_FLAGS(FILE_ATTRIBUTE_SPARSE);
1584 ADD_FLAGS(FILE_ATTRIBUTE_REPARSE_POINT);
1585 ADD_FLAGS(FILE_ATTRIBUTE_COMPRESSED);
1586 ADD_FLAGS(FILE_ATTRIBUTE_OFFLINE);
1587 ADD_FLAGS(FILE_ATTRIBUTE_NONINDEXED);
1588 ADD_FLAGS(FILE_ATTRIBUTE_ENCRYPTED);
1589 ADD_FLAGS(FILE_ATTRIBUTE_ALL_MASK);