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()
37 creds.set_username("administrator")
38 creds.set_password("1234")
40 c = libsmb.Conn("127.0.0.1",
45 -------------------------
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"
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)
74 mod = PyImport_ImportModule(module);
76 PyErr_Format(PyExc_RuntimeError,
77 "Unable to import %s to check type %s",
81 result = (PyTypeObject *)PyObject_GetAttrString(mod, type);
84 PyErr_Format(PyExc_RuntimeError,
85 "Unable to find type %s in module %s",
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,
101 char **_keywords = discard_const_p(char *, keywords);
104 va_start(a, keywords);
105 ret = PyArg_VaParseTupleAndKeywords(args, kw, format,
111 struct py_cli_thread;
113 struct py_cli_oplock_break {
118 struct py_cli_state {
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;
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;
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) {
162 ret = tevent_loop_once(self->ev);
165 PyGILState_Release(gstate);
169 static void py_cli_state_trace_callback(enum tevent_trace_point point,
172 struct py_cli_state *self = (struct py_cli_state *)private_data;
173 struct py_cli_thread *t = self->thread_state;
176 case TEVENT_TRACE_BEFORE_WAIT:
177 assert(t->py_threadstate == NULL);
178 t->py_threadstate = PyEval_SaveThread();
180 case TEVENT_TRACE_AFTER_WAIT:
181 assert(t->py_threadstate != NULL);
182 PyEval_RestoreThread(t->py_threadstate);
183 t->py_threadstate = NULL;
190 static void py_cli_state_shutdown_handler(struct tevent_context *ev,
191 struct tevent_fd *fde,
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) {
201 TALLOC_FREE(t->shutdown_fde);
202 t->do_shutdown = true;
205 static int py_cli_thread_destructor(struct py_cli_thread *t)
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);
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;
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;
245 self->ev = tevent_context_init_byname(NULL, "poll_mt");
246 if (self->ev == NULL) {
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) {
258 t = self->thread_state;
260 ret = pipe(t->shutdown_pipe);
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) {
271 PyEval_InitThreads();
273 ret = pthread_create(&t->id, NULL, py_cli_state_poll_thread, self);
277 talloc_set_destructor(self->thread_state, py_cli_thread_destructor);
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);
299 struct py_tevent_cond {
300 pthread_mutex_t mutex;
305 static void py_tevent_signalme(struct tevent_req *req);
307 static int py_tevent_cond_wait(struct py_tevent_cond *cond)
311 result = pthread_mutex_init(&cond->mutex, NULL);
315 result = pthread_cond_init(&cond->cond, NULL);
320 result = pthread_mutex_lock(&cond->mutex);
325 cond->is_done = false;
327 while (!cond->is_done) {
329 Py_BEGIN_ALLOW_THREADS
330 result = pthread_cond_wait(&cond->cond, &cond->mutex);
339 ret = pthread_mutex_unlock(&cond->mutex);
342 ret = pthread_cond_destroy(&cond->cond);
345 ret = pthread_mutex_destroy(&cond->mutex);
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)
363 ret = pthread_mutex_lock(&cond->mutex);
366 cond->is_done = true;
368 ret = pthread_cond_signal(&cond->cond);
370 ret = pthread_mutex_unlock(&cond->mutex);
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);
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) {
394 samba_tevent_set_debug(self->ev, "pylibsmb_tevent");
396 self->req_wait_fn = py_tevent_req_wait;
401 static int py_tevent_req_wait(struct tevent_context *ev,
402 struct tevent_req *req)
404 while (tevent_req_is_in_progress(req)) {
407 ret = tevent_loop_once(ev);
415 static bool py_tevent_req_wait_exc(struct py_cli_state *self,
416 struct tevent_req *req)
424 ret = self->req_wait_fn(self->ev, req);
428 PyErr_SetFromErrno(PyExc_RuntimeError);
434 static PyObject *py_cli_state_new(PyTypeObject *type, PyObject *args,
437 struct py_cli_state *self;
439 self = (struct py_cli_state *)type->tp_alloc(type, 0);
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;
459 ret = PyList_Check(list);
464 len = PyList_Size(list);
469 ctxs = talloc_zero(mem_ctx, struct smb2_negotiate_contexts);
474 for (i=0; i<len; i++) {
477 PyObject *t = PyList_GetItem(list, i);
480 PyObject *ptype = NULL;
483 PyObject *pdata = NULL;
484 DATA_BLOB data = { .data = NULL, };
490 ret = PyTuple_Check(t);
495 tlen = PyTuple_Size(t);
500 ptype = PyTuple_GetItem(t, 0);
504 type = PyLong_AsLong(ptype);
505 if ((type < 0) || (type > UINT16_MAX)) {
509 pdata = PyTuple_GetItem(t, 1);
511 ret = PyBytes_Check(pdata);
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)) {
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,
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;
556 static const char *kwlist[] = {
557 "host", "share", "lp", "creds",
558 "multi_threaded", "force_smb1",
561 "negotiate_contexts",
565 PyTypeObject *py_type_Credentials = get_pytype(
566 "samba.credentials", "Credentials");
567 if (py_type_Credentials == NULL) {
571 ret = ParseTupleAndKeywords(
572 args, kwds, "ssO|O!OOOOO", kwlist,
573 &host, &share, &py_lp,
574 py_type_Credentials, &creds,
579 &py_negotiate_contexts);
581 Py_DECREF(py_type_Credentials);
587 multi_threaded = PyObject_IsTrue(py_multi_threaded);
588 force_smb1 = PyObject_IsTrue(py_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);
602 flags |= CLI_FULL_CONNECTION_IPC;
605 request_posix = PyObject_IsTrue(py_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) {
618 if (multi_threaded) {
620 ret = py_cli_state_setup_mt_ev(self);
625 PyErr_SetString(PyExc_RuntimeError,
626 "No PTHREAD support available");
630 ret = py_cli_state_setup_ev(self);
637 cli_creds = cli_credentials_init_anon(NULL);
639 cli_creds = PyCredentials_AsCliCredentials(creds);
642 req = cli_full_connection_creds_send(
643 NULL, self->ev, "myname", host, NULL, 0, share, "?????",
646 if (!py_tevent_req_wait_exc(self, req)) {
649 status = cli_full_connection_creds_recv(req, &self->cli);
652 if (!NT_STATUS_IS_OK(status)) {
653 PyErr_SetNTSTATUS(status);
658 * Oplocks require a multi threaded connection
660 if (self->thread_state == NULL) {
664 self->oplock_waiter = cli_smb_oplock_break_waiter_send(
665 self->ev, self->ev, self->cli);
666 if (self->oplock_waiter == NULL) {
670 tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
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;
684 status = cli_smb_oplock_break_waiter_recv(req, &b.fnum, &b.level);
686 self->oplock_waiter = NULL;
688 if (!NT_STATUS_IS_OK(status)) {
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);
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) {
710 tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
714 static PyObject *py_cli_get_oplock_break(struct py_cli_state *self,
717 size_t num_oplock_breaks;
719 if (!PyArg_ParseTuple(args, "")) {
723 if (self->thread_state == NULL) {
724 PyErr_SetString(PyExc_RuntimeError,
725 "get_oplock_break() only possible on "
726 "a multi_threaded connection");
730 if (self->oplock_cond != NULL) {
732 PyErr_SetFromErrno(PyExc_RuntimeError);
736 num_oplock_breaks = talloc_array_length(self->oplock_breaks);
738 if (num_oplock_breaks == 0) {
739 struct py_tevent_cond cond;
742 self->oplock_cond = &cond;
743 ret = py_tevent_cond_wait(&cond);
744 self->oplock_cond = NULL;
748 PyErr_SetFromErrno(PyExc_RuntimeError);
753 num_oplock_breaks = talloc_array_length(self->oplock_breaks);
754 if (num_oplock_breaks > 0) {
757 result = Py_BuildValue(
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);
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);
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)) {
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;
808 req = cli_echo_send(NULL, self->ev, self->cli, 1, data);
809 if (!py_tevent_req_wait_exc(self, req)) {
812 status = cli_echo_recv(req);
814 PyErr_NTSTATUS_NOT_OK_RAISE(status);
819 static PyObject *py_cli_create(struct py_cli_state *self, PyObject *args,
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;
832 struct tevent_req *req;
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)) {
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)) {
855 status = cli_ntcreate_recv(req, &fnum, NULL);
858 if (!NT_STATUS_IS_OK(status)) {
859 PyErr_SetNTSTATUS(status);
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;
872 ret = PyList_Check(list);
877 len = PyList_Size(list);
882 ctxs = talloc_zero(mem_ctx, struct smb2_create_blobs);
887 for (i=0; i<len; i++) {
893 PyObject *pname = NULL;
896 PyObject *pdata = NULL;
897 DATA_BLOB data = { .data = NULL, };
899 t = PyList_GetItem(list, i);
904 ret = PyTuple_Check(t);
909 tlen = PyTuple_Size(t);
914 pname = PyTuple_GetItem(t, 0);
918 ret = PyBytes_Check(pname);
922 name = PyBytes_AsString(pname);
924 pdata = PyTuple_GetItem(t, 1);
928 ret = PyBytes_Check(pdata);
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)) {
948 static PyObject *py_cli_create_contexts(const struct smb2_create_blobs *blobs)
950 PyObject *py_blobs = NULL;
957 py_blobs = PyList_New(blobs->num_blobs);
958 if (py_blobs == NULL) {
962 for (i=0; i<blobs->num_blobs; i++) {
963 struct smb2_create_blob *blob = &blobs->blobs[i];
964 PyObject *py_blob = NULL;
967 py_blob = Py_BuildValue(
971 (int)blob->data.length);
972 if (py_blob == NULL) {
976 ret = PyList_SetItem(py_blobs, i, py_blob);
985 Py_XDECREF(py_blobs);
989 static PyObject *py_cli_create_returns(const struct smb_create_returns *r)
994 "{sLsLsLsLsLsLsLsLsL}",
996 (unsigned long long)r->oplock_level,
998 (unsigned long long)r->create_action,
1000 (unsigned long long)r->creation_time,
1002 (unsigned long long)r->last_access_time,
1004 (unsigned long long)r->last_write_time,
1006 (unsigned long long)r->change_time,
1008 (unsigned long long)r->allocation_size,
1010 (unsigned long long)r->end_of_file,
1012 (unsigned long long)r->file_attributes);
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;
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(
1033 strlen(s->substitute_name),
1040 ok = convert_string_talloc(
1045 strlen(s->print_name),
1054 "unparsed_path_length",
1055 (unsigned long long)s->unparsed_path_length,
1061 (unsigned long long)s->flags);
1064 TALLOC_FREE(subst_utf8);
1065 TALLOC_FREE(print_utf8);
1069 static PyObject *py_cli_create_ex(
1070 struct py_cli_state *self, PyObject *args, PyObject *kwds)
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;
1089 struct tevent_req *req;
1095 static const char *kwlist[] = {
1101 "CreateDisposition",
1103 "ImpersonationLevel",
1108 ret = ParseTupleAndKeywords(
1120 &ImpersonationLevel,
1122 &py_create_contexts_in);
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) {
1132 PyErr_SetFromErrno(PyExc_RuntimeError);
1137 if (smbXcli_conn_protocol(self->cli->conn) >= PROTOCOL_SMB2_02) {
1138 req = cli_smb2_create_fnum_send(
1150 create_contexts_in);
1152 req = cli_ntcreate_send(
1167 TALLOC_FREE(create_contexts_in);
1169 ok = py_tevent_req_wait_exc(self, req);
1174 if (smbXcli_conn_protocol(self->cli->conn) >= PROTOCOL_SMB2_02) {
1175 status = cli_smb2_create_fnum_recv(
1180 &create_contexts_out,
1183 status = cli_ntcreate_recv(req, &fnum, &cr);
1188 if (!NT_STATUS_IS_OK(status)) {
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) {
1200 py_cr = py_cli_create_returns(&cr);
1201 if (py_cr == NULL) {
1209 ret = PyTuple_SetItem(v, 0, Py_BuildValue("I", (unsigned)fnum));
1211 status = NT_STATUS_INTERNAL_ERROR;
1214 ret = PyTuple_SetItem(v, 1, py_cr);
1216 status = NT_STATUS_INTERNAL_ERROR;
1219 ret = PyTuple_SetItem(v, 2, py_create_contexts_out);
1221 status = NT_STATUS_INTERNAL_ERROR;
1227 status = NT_STATUS_NO_MEMORY;
1229 Py_XDECREF(py_create_contexts_out);
1233 if (NT_STATUS_EQUAL(status, NT_STATUS_STOPPED_ON_SYMLINK) &&
1234 (symlink != NULL)) {
1236 PyObject_GetAttrString(
1237 PyImport_ImportModule("samba"),
1241 NT_STATUS_V(status),
1242 get_friendly_nt_error_msg(status),
1243 py_cli_symlink_error(symlink)));
1245 PyErr_SetNTSTATUS(status);
1250 static PyObject *py_cli_close(struct py_cli_state *self, PyObject *args)
1252 struct tevent_req *req;
1256 if (!PyArg_ParseTuple(args, "i", &fnum)) {
1260 req = cli_close_send(NULL, self->ev, self->cli, fnum);
1261 if (!py_tevent_req_wait_exc(self, req)) {
1264 status = cli_close_recv(req);
1267 if (!NT_STATUS_IS_OK(status)) {
1268 PyErr_SetNTSTATUS(status);
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;
1283 static const char *kwlist[] = { "src", "dst", "replace", NULL };
1285 ok = ParseTupleAndKeywords(
1286 args, kwds, "ss|p", kwlist, &fname_src, &fname_dst, &replace);
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)) {
1296 status = cli_rename_recv(req);
1299 if (!NT_STATUS_IS_OK(status)) {
1300 PyErr_SetNTSTATUS(status);
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;
1321 size_t copied_bytes;
1323 if (state->nread >= state->total_data) {
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)
1342 const char *filename = NULL;
1344 Py_ssize_t size = 0;
1346 struct tevent_req *req = NULL;
1347 struct push_state state;
1349 if (!PyArg_ParseTuple(args, "s"PYARG_BYTES_LEN":savefile", &filename,
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)) {
1363 status = cli_ntcreate_recv(req, &fnum, NULL);
1365 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1367 /* write the new file contents */
1370 state.total_data = size;
1372 req = cli_push_send(NULL, self->ev, self->cli, fnum, 0, 0, 0,
1374 if (!py_tevent_req_wait_exc(self, req)) {
1377 status = cli_push_recv(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)) {
1386 status = cli_close_recv(req);
1387 PyErr_NTSTATUS_NOT_OK_RAISE(status);
1392 static PyObject *py_cli_write(struct py_cli_state *self, PyObject *args,
1399 unsigned long long offset;
1400 struct tevent_req *req;
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)) {
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)) {
1418 status = cli_write_recv(req, &written);
1421 if (!NT_STATUS_IS_OK(status)) {
1422 PyErr_SetNTSTATUS(status);
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,
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);
1448 * Loads the specified file's contents and returns it
1450 static PyObject *py_smb_loadfile(struct py_cli_state *self, PyObject *args)
1453 const char *filename = NULL;
1454 struct tevent_req *req = NULL;
1459 PyObject *result = NULL;
1461 if (!PyArg_ParseTuple(args, "s:loadfile", &filename)) {
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)) {
1474 status = cli_ntcreate_recv(req, &fnum, NULL);
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) {
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)) {
1495 status = cli_pull_recv(req, &nread);
1497 if (!NT_STATUS_IS_OK(status)) {
1499 PyErr_SetNTSTATUS(status);
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)) {
1509 status = cli_close_recv(req);
1511 if (!NT_STATUS_IS_OK(status)) {
1513 PyErr_SetNTSTATUS(status);
1517 /* sanity-check we read the expected number of bytes */
1520 PyErr_Format(PyExc_IOError,
1521 "read invalid - got %zu requested %zu",
1527 if (_PyBytes_Resize(&result, nread) < 0) {
1535 static PyObject *py_cli_read(struct py_cli_state *self, PyObject *args,
1539 unsigned long long offset;
1541 struct tevent_req *req;
1547 static const char *kwlist[] = {
1548 "fnum", "offset", "size", NULL };
1550 if (!ParseTupleAndKeywords(
1551 args, kwds, "iKI", kwlist, &fnum, &offset,
1556 result = PyBytes_FromStringAndSize(NULL, size);
1557 if (result == NULL) {
1560 buf = PyBytes_AS_STRING(result);
1562 req = cli_read_send(NULL, self->ev, self->cli, fnum,
1564 if (!py_tevent_req_wait_exc(self, req)) {
1568 status = cli_read_recv(req, &received);
1571 if (!NT_STATUS_IS_OK(status)) {
1573 PyErr_SetNTSTATUS(status);
1577 if (received > size) {
1579 PyErr_Format(PyExc_IOError,
1580 "read invalid - got %zu requested %u",
1585 if (received < size) {
1586 if (_PyBytes_Resize(&result, received) < 0) {
1594 static PyObject *py_cli_ftruncate(struct py_cli_state *self, PyObject *args,
1598 unsigned long long size;
1599 struct tevent_req *req;
1602 static const char *kwlist[] = {
1603 "fnum", "size", NULL };
1605 if (!ParseTupleAndKeywords(
1606 args, kwds, "IK", kwlist, &fnum, &size)) {
1610 req = cli_ftruncate_send(NULL, self->ev, self->cli, fnum, size);
1611 if (!py_tevent_req_wait_exc(self, req)) {
1614 status = cli_ftruncate_recv(req);
1617 if (!NT_STATUS_IS_OK(status)) {
1618 PyErr_SetNTSTATUS(status);
1624 static PyObject *py_cli_delete_on_close(struct py_cli_state *self,
1628 unsigned fnum, flag;
1629 struct tevent_req *req;
1632 static const char *kwlist[] = {
1633 "fnum", "flag", NULL };
1635 if (!ParseTupleAndKeywords(
1636 args, kwds, "II", kwlist, &fnum, &flag)) {
1640 req = cli_nt_delete_on_close_send(NULL, self->ev, self->cli, fnum,
1642 if (!py_tevent_req_wait_exc(self, req)) {
1645 status = cli_nt_delete_on_close_recv(req);
1648 if (!NT_STATUS_IS_OK(status)) {
1649 PyErr_SetNTSTATUS(status);
1655 struct py_cli_notify_state {
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,
1677 static const char *kwlist[] = {
1680 "completion_filter",
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;
1693 struct py_cli_notify_state *py_notify_state = NULL;
1694 struct timeval endtime;
1696 ok = ParseTupleAndKeywords(args,
1708 recursive = PyObject_IsTrue(py_recursive);
1710 req = cli_notify_send(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,
1730 endtime = timeval_current_ofs_msec(self->cli->timeout);
1731 ok = tevent_req_set_endtime(flush_req,
1739 ok = py_tevent_req_wait_exc(self, flush_req);
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) {
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,
1764 struct py_cli_state *py_cli_state = self->py_cli_state;
1765 struct tevent_req *req = self->req;
1767 uint32_t num_changes = 0;
1768 struct notify_change *changes = NULL;
1769 PyObject *result = NULL;
1772 static const char *kwlist[] = {
1776 PyObject *py_wait = Py_False;
1780 ok = ParseTupleAndKeywords(args,
1789 wait = PyObject_IsTrue(py_wait);
1792 PyErr_SetString(PyExc_RuntimeError,
1794 "- missing change notify request?");
1798 pending = tevent_req_is_in_progress(req);
1799 if (pending && !wait) {
1804 struct timeval endtime;
1806 endtime = timeval_current_ofs_msec(py_cli_state->cli->timeout);
1807 ok = tevent_req_set_endtime(req,
1817 ok = py_tevent_req_wait_exc(py_cli_state, req);
1819 Py_DECREF(self->py_cli_state);
1820 self->py_cli_state = NULL;
1825 status = cli_notify_recv(req, req, &num_changes, &changes);
1826 if (!NT_STATUS_IS_OK(status)) {
1828 PyErr_SetNTSTATUS(status);
1832 result = Py_BuildValue("[]");
1833 if (result == NULL) {
1838 for (i = 0; i < num_changes; i++) {
1839 PyObject *change = NULL;
1842 change = Py_BuildValue("{s:s,s:I}",
1843 "name", changes[i].name,
1844 "action", changes[i].action);
1845 if (change == NULL) {
1851 ret = PyList_Append(result, change);
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"
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 directory listing entries to an overall Python list
1896 static NTSTATUS list_helper(struct file_info *finfo,
1897 const char *mask, void *state)
1899 PyObject *result = (PyObject *)state;
1900 PyObject *file = NULL;
1901 PyObject *size = NULL;
1904 /* suppress '.' and '..' in the results we return */
1905 if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
1906 return NT_STATUS_OK;
1908 size = PyLong_FromUnsignedLongLong(finfo->size);
1910 * Build a dictionary representing the file info.
1911 * Note: Windows does not always return short_name (so it may be None)
1913 file = Py_BuildValue("{s:s,s:i,s:s,s:O,s:l}",
1914 "name", finfo->name,
1915 "attrib", (int)finfo->attr,
1916 "short_name", finfo->short_name,
1919 convert_timespec_to_time_t(finfo->mtime_ts));
1924 return NT_STATUS_NO_MEMORY;
1927 ret = PyList_Append(result, file);
1930 return NT_STATUS_INTERNAL_ERROR;
1933 return NT_STATUS_OK;
1936 struct do_listing_state {
1938 NTSTATUS (*callback_fn)(
1939 struct file_info *finfo,
1941 void *private_data);
1946 static void do_listing_cb(struct tevent_req *subreq)
1948 struct do_listing_state *state = tevent_req_callback_data_void(subreq);
1949 struct file_info *finfo = NULL;
1951 state->status = cli_list_recv(subreq, NULL, &finfo);
1952 if (!NT_STATUS_IS_OK(state->status)) {
1955 state->callback_fn(finfo, state->mask, state->private_data);
1959 static NTSTATUS do_listing(struct py_cli_state *self,
1960 const char *base_dir, const char *user_mask,
1962 NTSTATUS (*callback_fn)(struct file_info *,
1963 const char *, void *),
1967 unsigned int info_level = SMB_FIND_FILE_BOTH_DIRECTORY_INFO;
1968 struct do_listing_state state = {
1970 .callback_fn = callback_fn,
1971 .private_data = priv,
1973 struct tevent_req *req = NULL;
1976 if (user_mask == NULL) {
1977 mask = talloc_asprintf(NULL, "%s\\*", base_dir);
1979 mask = talloc_asprintf(NULL, "%s\\%s", base_dir, user_mask);
1983 return NT_STATUS_NO_MEMORY;
1987 req = cli_list_send(NULL, self->ev, self->cli, mask, attribute,
1990 status = NT_STATUS_NO_MEMORY;
1993 tevent_req_set_callback(req, do_listing_cb, &state);
1995 if (!py_tevent_req_wait_exc(self, req)) {
1996 return NT_STATUS_INTERNAL_ERROR;
2000 status = state.status;
2001 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_MORE_FILES)) {
2002 status = NT_STATUS_OK;
2010 static PyObject *py_cli_list(struct py_cli_state *self,
2015 char *user_mask = NULL;
2016 unsigned int attribute = LIST_ATTRIBUTE_MASK;
2018 PyObject *result = NULL;
2019 const char *kwlist[] = { "directory", "mask", "attribs", NULL };
2021 if (!ParseTupleAndKeywords(args, kwds, "z|sI:list", kwlist,
2022 &base_dir, &user_mask, &attribute)) {
2026 result = Py_BuildValue("[]");
2027 if (result == NULL) {
2031 status = do_listing(self, base_dir, user_mask, attribute,
2032 list_helper, result);
2034 if (!NT_STATUS_IS_OK(status)) {
2036 PyErr_SetNTSTATUS(status);
2043 static PyObject *py_smb_unlink(struct py_cli_state *self, PyObject *args)
2046 const char *filename = NULL;
2047 struct tevent_req *req = NULL;
2048 const uint32_t attrs = (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
2050 if (!PyArg_ParseTuple(args, "s:unlink", &filename)) {
2054 req = cli_unlink_send(NULL, self->ev, self->cli, filename, attrs);
2055 if (!py_tevent_req_wait_exc(self, req)) {
2058 status = cli_unlink_recv(req);
2060 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2065 static PyObject *py_smb_rmdir(struct py_cli_state *self, PyObject *args)
2068 struct tevent_req *req = NULL;
2069 const char *dirname = NULL;
2071 if (!PyArg_ParseTuple(args, "s:rmdir", &dirname)) {
2075 req = cli_rmdir_send(NULL, self->ev, self->cli, dirname);
2076 if (!py_tevent_req_wait_exc(self, req)) {
2079 status = cli_rmdir_recv(req);
2081 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2087 * Create a directory
2089 static PyObject *py_smb_mkdir(struct py_cli_state *self, PyObject *args)
2092 const char *dirname = NULL;
2093 struct tevent_req *req = NULL;
2095 if (!PyArg_ParseTuple(args, "s:mkdir", &dirname)) {
2099 req = cli_mkdir_send(NULL, self->ev, self->cli, dirname);
2100 if (!py_tevent_req_wait_exc(self, req)) {
2103 status = cli_mkdir_recv(req);
2105 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2111 * Does a whoami call
2113 static PyObject *py_smb_posix_whoami(struct py_cli_state *self,
2114 PyObject *Py_UNUSED(ignored))
2116 TALLOC_CTX *frame = talloc_stackframe();
2118 struct tevent_req *req = NULL;
2122 uint64_t *gids = NULL;
2124 struct dom_sid *sids = NULL;
2126 PyObject *py_gids = NULL;
2127 PyObject *py_sids = NULL;
2128 PyObject *py_guest = NULL;
2129 PyObject *py_ret = NULL;
2132 req = cli_posix_whoami_send(frame, self->ev, self->cli);
2133 if (!py_tevent_req_wait_exc(self, req)) {
2136 status = cli_posix_whoami_recv(req,
2145 if (!NT_STATUS_IS_OK(status)) {
2146 PyErr_SetNTSTATUS(status);
2149 if (num_gids > PY_SSIZE_T_MAX) {
2150 PyErr_SetString(PyExc_OverflowError, "posix_whoami: Too many GIDs");
2153 if (num_sids > PY_SSIZE_T_MAX) {
2154 PyErr_SetString(PyExc_OverflowError, "posix_whoami: Too many SIDs");
2158 py_gids = PyList_New(num_gids);
2162 for (i = 0; i < num_gids; ++i) {
2164 PyObject *py_item = PyLong_FromUnsignedLongLong(gids[i]);
2169 ret = PyList_SetItem(py_gids, i, py_item);
2174 py_sids = PyList_New(num_sids);
2178 for (i = 0; i < num_sids; ++i) {
2180 struct dom_sid *sid;
2183 sid = dom_sid_dup(frame, &sids[i]);
2189 py_item = pytalloc_steal(dom_sid_Type, sid);
2195 ret = PyList_SetItem(py_sids, i, py_item);
2201 py_guest = guest ? Py_True : Py_False;
2203 py_ret = Py_BuildValue("KKNNO",
2228 * Checks existence of a directory
2230 static bool check_dir_path(struct py_cli_state *self, const char *path)
2233 struct tevent_req *req = NULL;
2235 req = cli_chkpath_send(NULL, self->ev, self->cli, path);
2236 if (!py_tevent_req_wait_exc(self, req)) {
2239 status = cli_chkpath_recv(req);
2242 return NT_STATUS_IS_OK(status);
2245 static PyObject *py_smb_chkpath(struct py_cli_state *self, PyObject *args)
2247 const char *path = NULL;
2250 if (!PyArg_ParseTuple(args, "s:chkpath", &path)) {
2254 dir_exists = check_dir_path(self, path);
2255 return PyBool_FromLong(dir_exists);
2258 static PyObject *py_smb_have_posix(struct py_cli_state *self,
2259 PyObject *Py_UNUSED(ignored))
2261 bool posix = smbXcli_conn_have_posix(self->cli->conn);
2269 static PyObject *py_smb_get_sd(struct py_cli_state *self, PyObject *args)
2273 struct tevent_req *req = NULL;
2274 struct security_descriptor *sd = NULL;
2277 if (!PyArg_ParseTuple(args, "iI:get_acl", &fnum, &sinfo)) {
2281 req = cli_query_security_descriptor_send(
2282 NULL, self->ev, self->cli, fnum, sinfo);
2283 if (!py_tevent_req_wait_exc(self, req)) {
2286 status = cli_query_security_descriptor_recv(req, NULL, &sd);
2287 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2289 return py_return_ndr_struct(
2290 "samba.dcerpc.security", "descriptor", sd, sd);
2293 static PyObject *py_smb_set_sd(struct py_cli_state *self, PyObject *args)
2295 PyObject *py_sd = NULL;
2296 struct tevent_req *req = NULL;
2297 struct security_descriptor *sd = NULL;
2302 if (!PyArg_ParseTuple(args, "iOI:set_sd", &fnum, &py_sd, &sinfo)) {
2306 sd = pytalloc_get_type(py_sd, struct security_descriptor);
2308 PyErr_Format(PyExc_TypeError,
2309 "Expected dcerpc.security.descriptor as argument, got %s",
2310 pytalloc_get_name(py_sd));
2314 req = cli_set_security_descriptor_send(
2315 NULL, self->ev, self->cli, fnum, sinfo, sd);
2316 if (!py_tevent_req_wait_exc(self, req)) {
2320 status = cli_set_security_descriptor_recv(req);
2321 PyErr_NTSTATUS_NOT_OK_RAISE(status);
2326 static PyObject *py_smb_smb1_posix(
2327 struct py_cli_state *self, PyObject *Py_UNUSED(ignored))
2330 struct tevent_req *req = NULL;
2331 uint16_t major, minor;
2332 uint32_t caplow, caphigh;
2333 PyObject *result = NULL;
2335 req = cli_unix_extensions_version_send(NULL, self->ev, self->cli);
2336 if (!py_tevent_req_wait_exc(self, req)) {
2339 status = cli_unix_extensions_version_recv(
2340 req, &major, &minor, &caplow, &caphigh);
2342 if (!NT_STATUS_IS_OK(status)) {
2343 PyErr_SetNTSTATUS(status);
2347 req = cli_set_unix_extensions_capabilities_send(
2348 NULL, self->ev, self->cli, major, minor, caplow, caphigh);
2349 if (!py_tevent_req_wait_exc(self, req)) {
2352 status = cli_set_unix_extensions_capabilities_recv(req);
2354 if (!NT_STATUS_IS_OK(status)) {
2355 PyErr_SetNTSTATUS(status);
2359 result = Py_BuildValue(
2368 static PyObject *py_smb_smb1_readlink(
2369 struct py_cli_state *self, PyObject *args)
2372 const char *filename = NULL;
2373 struct tevent_req *req = NULL;
2374 char *target = NULL;
2375 PyObject *result = NULL;
2377 if (!PyArg_ParseTuple(args, "s:smb1_readlink", &filename)) {
2381 req = cli_posix_readlink_send(NULL, self->ev, self->cli, filename);
2382 if (!py_tevent_req_wait_exc(self, req)) {
2385 status = cli_posix_readlink_recv(req, NULL, &target);
2387 if (!NT_STATUS_IS_OK(status)) {
2388 PyErr_SetNTSTATUS(status);
2392 result = PyBytes_FromString(target);
2393 TALLOC_FREE(target);
2397 static PyObject *py_smb_smb1_symlink(
2398 struct py_cli_state *self, PyObject *args)
2401 const char *target = NULL, *newname = NULL;
2402 struct tevent_req *req = NULL;
2404 if (!PyArg_ParseTuple(args, "ss:smb1_symlink", &target, &newname)) {
2408 req = cli_posix_symlink_send(
2409 NULL, self->ev, self->cli, target, newname);
2410 if (!py_tevent_req_wait_exc(self, req)) {
2413 status = cli_posix_symlink_recv(req);
2415 if (!NT_STATUS_IS_OK(status)) {
2416 PyErr_SetNTSTATUS(status);
2423 static PyMethodDef py_cli_state_methods[] = {
2424 { "settimeout", (PyCFunction)py_cli_settimeout, METH_VARARGS,
2425 "settimeout(new_timeout_msecs) => return old_timeout_msecs" },
2426 { "echo", (PyCFunction)py_cli_echo, METH_NOARGS,
2427 "Ping the server connection" },
2428 { "create", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_create),
2429 METH_VARARGS|METH_KEYWORDS,
2432 PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_create_ex),
2433 METH_VARARGS|METH_KEYWORDS,
2434 "Open a file, SMB2 version returning create contexts" },
2435 { "close", (PyCFunction)py_cli_close, METH_VARARGS,
2436 "Close a file handle" },
2437 { "write", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_write),
2438 METH_VARARGS|METH_KEYWORDS,
2439 "Write to a file handle" },
2440 { "read", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_read),
2441 METH_VARARGS|METH_KEYWORDS,
2442 "Read from a file handle" },
2443 { "truncate", PY_DISCARD_FUNC_SIG(PyCFunction,
2445 METH_VARARGS|METH_KEYWORDS,
2446 "Truncate a file" },
2447 { "delete_on_close", PY_DISCARD_FUNC_SIG(PyCFunction,
2448 py_cli_delete_on_close),
2449 METH_VARARGS|METH_KEYWORDS,
2450 "Set/Reset the delete on close flag" },
2451 { "notify", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_notify),
2452 METH_VARARGS|METH_KEYWORDS,
2453 "Wait for change notifications: \n"
2454 "notify(fnum, buffer_size, completion_filter...) -> "
2455 "libsmb_samba_internal.Notify request handle\n" },
2456 { "list", PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_list),
2457 METH_VARARGS|METH_KEYWORDS,
2458 "list(directory, mask='*', attribs=DEFAULT_ATTRS) -> "
2459 "directory contents as a dictionary\n"
2460 "\t\tDEFAULT_ATTRS: FILE_ATTRIBUTE_SYSTEM | "
2461 "FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_ARCHIVE\n\n"
2462 "\t\tList contents of a directory. The keys are, \n"
2463 "\t\t\tname: Long name of the directory item\n"
2464 "\t\t\tshort_name: Short name of the directory item\n"
2465 "\t\t\tsize: File size in bytes\n"
2466 "\t\t\tattrib: Attributes\n"
2467 "\t\t\tmtime: Modification time\n" },
2468 { "get_oplock_break", (PyCFunction)py_cli_get_oplock_break,
2469 METH_VARARGS, "Wait for an oplock break" },
2470 { "unlink", (PyCFunction)py_smb_unlink,
2472 "unlink(path) -> None\n\n \t\tDelete a file." },
2473 { "mkdir", (PyCFunction)py_smb_mkdir, METH_VARARGS,
2474 "mkdir(path) -> None\n\n \t\tCreate a directory." },
2475 { "posix_whoami", (PyCFunction)py_smb_posix_whoami, METH_NOARGS,
2476 "posix_whoami() -> (uid, gid, gids, sids, guest)" },
2477 { "rmdir", (PyCFunction)py_smb_rmdir, METH_VARARGS,
2478 "rmdir(path) -> None\n\n \t\tDelete a directory." },
2480 PY_DISCARD_FUNC_SIG(PyCFunction, py_cli_rename),
2481 METH_VARARGS|METH_KEYWORDS,
2482 "rename(src,dst) -> None\n\n \t\tRename a file." },
2483 { "chkpath", (PyCFunction)py_smb_chkpath, METH_VARARGS,
2484 "chkpath(dir_path) -> True or False\n\n"
2485 "\t\tReturn true if directory exists, false otherwise." },
2486 { "savefile", (PyCFunction)py_smb_savefile, METH_VARARGS,
2487 "savefile(path, bytes) -> None\n\n"
2488 "\t\tWrite bytes to file." },
2489 { "loadfile", (PyCFunction)py_smb_loadfile, METH_VARARGS,
2490 "loadfile(path) -> file contents as a bytes object"
2491 "\n\n\t\tRead contents of a file." },
2492 { "get_sd", (PyCFunction)py_smb_get_sd, METH_VARARGS,
2493 "get_sd(fnum[, security_info=0]) -> security_descriptor object\n\n"
2494 "\t\tGet security descriptor for opened file." },
2495 { "set_sd", (PyCFunction)py_smb_set_sd, METH_VARARGS,
2496 "set_sd(fnum, security_descriptor[, security_info=0]) -> None\n\n"
2497 "\t\tSet security descriptor for opened file." },
2499 (PyCFunction)py_smb_have_posix,
2501 "have_posix() -> True/False\n\n"
2502 "\t\tReturn if the server has posix extensions"
2505 (PyCFunction)py_smb_smb1_posix,
2507 "Negotiate SMB1 posix extensions",
2510 (PyCFunction)py_smb_smb1_readlink,
2512 "smb1_readlink(path) -> link target",
2515 (PyCFunction)py_smb_smb1_symlink,
2517 "smb1_symlink(target, newname) -> None",
2519 { NULL, NULL, 0, NULL }
2522 static PyTypeObject py_cli_state_type = {
2523 PyVarObject_HEAD_INIT(NULL, 0)
2524 .tp_name = "libsmb_samba_cwrapper.LibsmbCConn",
2525 .tp_basicsize = sizeof(struct py_cli_state),
2526 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
2527 .tp_doc = "libsmb cwrapper connection",
2528 .tp_new = py_cli_state_new,
2529 .tp_init = (initproc)py_cli_state_init,
2530 .tp_dealloc = (destructor)py_cli_state_dealloc,
2531 .tp_methods = py_cli_state_methods,
2534 static PyMethodDef py_libsmb_methods[] = {
2538 void initlibsmb_samba_cwrapper(void);
2540 static struct PyModuleDef moduledef = {
2541 PyModuleDef_HEAD_INIT,
2542 .m_name = "libsmb_samba_cwrapper",
2543 .m_doc = "libsmb wrapper",
2545 .m_methods = py_libsmb_methods,
2548 MODULE_INIT_FUNC(libsmb_samba_cwrapper)
2551 PyObject *mod = NULL;
2553 talloc_stackframe();
2555 if (PyType_Ready(&py_cli_state_type) < 0) {
2558 if (PyType_Ready(&py_cli_notify_state_type) < 0) {
2562 m = PyModule_Create(&moduledef);
2567 /* Import dom_sid type from dcerpc.security */
2568 mod = PyImport_ImportModule("samba.dcerpc.security");
2573 dom_sid_Type = (PyTypeObject *)PyObject_GetAttrString(mod, "dom_sid");
2574 if (dom_sid_Type == NULL) {
2579 Py_INCREF(&py_cli_state_type);
2580 PyModule_AddObject(m, "LibsmbCConn", (PyObject *)&py_cli_state_type);
2582 #define ADD_FLAGS(val) PyModule_AddObject(m, #val, PyLong_FromLong(val))
2584 ADD_FLAGS(FILE_ATTRIBUTE_READONLY);
2585 ADD_FLAGS(FILE_ATTRIBUTE_HIDDEN);
2586 ADD_FLAGS(FILE_ATTRIBUTE_SYSTEM);
2587 ADD_FLAGS(FILE_ATTRIBUTE_VOLUME);
2588 ADD_FLAGS(FILE_ATTRIBUTE_DIRECTORY);
2589 ADD_FLAGS(FILE_ATTRIBUTE_ARCHIVE);
2590 ADD_FLAGS(FILE_ATTRIBUTE_DEVICE);
2591 ADD_FLAGS(FILE_ATTRIBUTE_NORMAL);
2592 ADD_FLAGS(FILE_ATTRIBUTE_TEMPORARY);
2593 ADD_FLAGS(FILE_ATTRIBUTE_SPARSE);
2594 ADD_FLAGS(FILE_ATTRIBUTE_REPARSE_POINT);
2595 ADD_FLAGS(FILE_ATTRIBUTE_COMPRESSED);
2596 ADD_FLAGS(FILE_ATTRIBUTE_OFFLINE);
2597 ADD_FLAGS(FILE_ATTRIBUTE_NONINDEXED);
2598 ADD_FLAGS(FILE_ATTRIBUTE_ENCRYPTED);
2599 ADD_FLAGS(FILE_ATTRIBUTE_ALL_MASK);
2601 ADD_FLAGS(FILE_SHARE_READ);
2602 ADD_FLAGS(FILE_SHARE_WRITE);
2603 ADD_FLAGS(FILE_SHARE_DELETE);
2605 /* change notify completion filter flags */
2606 ADD_FLAGS(FILE_NOTIFY_CHANGE_FILE_NAME);
2607 ADD_FLAGS(FILE_NOTIFY_CHANGE_DIR_NAME);
2608 ADD_FLAGS(FILE_NOTIFY_CHANGE_ATTRIBUTES);
2609 ADD_FLAGS(FILE_NOTIFY_CHANGE_SIZE);
2610 ADD_FLAGS(FILE_NOTIFY_CHANGE_LAST_WRITE);
2611 ADD_FLAGS(FILE_NOTIFY_CHANGE_LAST_ACCESS);
2612 ADD_FLAGS(FILE_NOTIFY_CHANGE_CREATION);
2613 ADD_FLAGS(FILE_NOTIFY_CHANGE_EA);
2614 ADD_FLAGS(FILE_NOTIFY_CHANGE_SECURITY);
2615 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_NAME);
2616 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_SIZE);
2617 ADD_FLAGS(FILE_NOTIFY_CHANGE_STREAM_WRITE);
2618 ADD_FLAGS(FILE_NOTIFY_CHANGE_NAME);
2619 ADD_FLAGS(FILE_NOTIFY_CHANGE_ALL);
2621 /* change notify action results */
2622 ADD_FLAGS(NOTIFY_ACTION_ADDED);
2623 ADD_FLAGS(NOTIFY_ACTION_REMOVED);
2624 ADD_FLAGS(NOTIFY_ACTION_MODIFIED);
2625 ADD_FLAGS(NOTIFY_ACTION_OLD_NAME);
2626 ADD_FLAGS(NOTIFY_ACTION_NEW_NAME);
2627 ADD_FLAGS(NOTIFY_ACTION_ADDED_STREAM);
2628 ADD_FLAGS(NOTIFY_ACTION_REMOVED_STREAM);
2629 ADD_FLAGS(NOTIFY_ACTION_MODIFIED_STREAM);
2631 #define ADD_STRING(val) PyModule_AddObject(m, #val, PyBytes_FromString(val))
2633 ADD_STRING(SMB2_CREATE_TAG_EXTA);
2634 ADD_STRING(SMB2_CREATE_TAG_MXAC);
2635 ADD_STRING(SMB2_CREATE_TAG_SECD);
2636 ADD_STRING(SMB2_CREATE_TAG_DHNQ);
2637 ADD_STRING(SMB2_CREATE_TAG_DHNC);
2638 ADD_STRING(SMB2_CREATE_TAG_ALSI);
2639 ADD_STRING(SMB2_CREATE_TAG_TWRP);
2640 ADD_STRING(SMB2_CREATE_TAG_QFID);
2641 ADD_STRING(SMB2_CREATE_TAG_RQLS);
2642 ADD_STRING(SMB2_CREATE_TAG_DH2Q);
2643 ADD_STRING(SMB2_CREATE_TAG_DH2C);
2644 ADD_STRING(SMB2_CREATE_TAG_AAPL);
2645 ADD_STRING(SMB2_CREATE_TAG_APP_INSTANCE_ID);
2646 ADD_STRING(SVHDX_OPEN_DEVICE_CONTEXT);
2647 ADD_STRING(SMB2_CREATE_TAG_POSIX);