s3:libsmb: Revert SMB Py bindings name back to libsmb_samba_internal
[samba.git] / source3 / libsmb / pylibsmb.c
1 /*
2  * Unix SMB/CIFS implementation.
3  *
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.
7  *
8  * Copyright (C) Volker Lendecke 2012
9  *
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.
14  *
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.
19  *
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/>.
22 */
23
24 #include <Python.h>
25 #include "includes.h"
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"
33 #include "trans2.h"
34 #include "libsmb/clirap.h"
35
36 #define LIST_ATTRIBUTE_MASK \
37         (FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN)
38
39 static PyTypeObject *get_pytype(const char *module, const char *type)
40 {
41         PyObject *mod;
42         PyTypeObject *result;
43
44         mod = PyImport_ImportModule(module);
45         if (mod == NULL) {
46                 PyErr_Format(PyExc_RuntimeError,
47                              "Unable to import %s to check type %s",
48                              module, type);
49                 return NULL;
50         }
51         result = (PyTypeObject *)PyObject_GetAttrString(mod, type);
52         Py_DECREF(mod);
53         if (result == NULL) {
54                 PyErr_Format(PyExc_RuntimeError,
55                              "Unable to find type %s in module %s",
56                              module, type);
57                 return NULL;
58         }
59         return result;
60 }
61
62 /*
63  * We're using "const char * const *" for keywords,
64  * PyArg_ParseTupleAndKeywords expects a "char **". Confine the
65  * inevitable warnings to just one place.
66  */
67 static int ParseTupleAndKeywords(PyObject *args, PyObject *kw,
68                                  const char *format, const char * const *keywords,
69                                  ...)
70 {
71         char **_keywords = discard_const_p(char *, keywords);
72         va_list a;
73         int ret;
74         va_start(a, keywords);
75         ret = PyArg_VaParseTupleAndKeywords(args, kw, format,
76                                             _keywords, a);
77         va_end(a);
78         return ret;
79 }
80
81 struct py_cli_thread;
82
83 struct py_cli_oplock_break {
84         uint16_t fnum;
85         uint8_t level;
86 };
87
88 struct py_cli_state {
89         PyObject_HEAD
90         struct cli_state *cli;
91         bool is_smb1;
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;
96
97         struct tevent_req *oplock_waiter;
98         struct py_cli_oplock_break *oplock_breaks;
99         struct py_tevent_cond *oplock_cond;
100 };
101
102 #ifdef HAVE_PTHREAD
103
104 #include <pthread.h>
105
106 struct py_cli_thread {
107
108         /*
109          * Pipe to make the poll thread wake up in our destructor, so
110          * that we can exit and join the thread.
111          */
112         int shutdown_pipe[2];
113         struct tevent_fd *shutdown_fde;
114         bool do_shutdown;
115         pthread_t id;
116
117         /*
118          * Thread state to release the GIL during the poll(2) syscall
119          */
120         PyThreadState *py_threadstate;
121 };
122
123 static void *py_cli_state_poll_thread(void *private_data)
124 {
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;
128
129         gstate = PyGILState_Ensure();
130
131         while (!t->do_shutdown) {
132                 int ret;
133                 ret = tevent_loop_once(self->ev);
134                 assert(ret == 0);
135         }
136         PyGILState_Release(gstate);
137         return NULL;
138 }
139
140 static void py_cli_state_trace_callback(enum tevent_trace_point point,
141                                         void *private_data)
142 {
143         struct py_cli_state *self = (struct py_cli_state *)private_data;
144         struct py_cli_thread *t = self->thread_state;
145
146         switch(point) {
147         case TEVENT_TRACE_BEFORE_WAIT:
148                 assert(t->py_threadstate == NULL);
149                 t->py_threadstate = PyEval_SaveThread();
150                 break;
151         case TEVENT_TRACE_AFTER_WAIT:
152                 assert(t->py_threadstate != NULL);
153                 PyEval_RestoreThread(t->py_threadstate);
154                 t->py_threadstate = NULL;
155                 break;
156         default:
157                 break;
158         }
159 }
160
161 static void py_cli_state_shutdown_handler(struct tevent_context *ev,
162                                           struct tevent_fd *fde,
163                                           uint16_t flags,
164                                           void *private_data)
165 {
166         struct py_cli_state *self = (struct py_cli_state *)private_data;
167         struct py_cli_thread *t = self->thread_state;
168
169         if ((flags & TEVENT_FD_READ) == 0) {
170                 return;
171         }
172         TALLOC_FREE(t->shutdown_fde);
173         t->do_shutdown = true;
174 }
175
176 static int py_cli_thread_destructor(struct py_cli_thread *t)
177 {
178         char c = 0;
179         ssize_t written;
180         int ret;
181
182         do {
183                 /*
184                  * This will wake the poll thread from the poll(2)
185                  */
186                 written = write(t->shutdown_pipe[1], &c, 1);
187         } while ((written == -1) && (errno == EINTR));
188
189         /*
190          * Allow the poll thread to do its own cleanup under the GIL
191          */
192         Py_BEGIN_ALLOW_THREADS
193         ret = pthread_join(t->id, NULL);
194         Py_END_ALLOW_THREADS
195         assert(ret == 0);
196
197         if (t->shutdown_pipe[0] != -1) {
198                 close(t->shutdown_pipe[0]);
199                 t->shutdown_pipe[0] = -1;
200         }
201         if (t->shutdown_pipe[1] != -1) {
202                 close(t->shutdown_pipe[1]);
203                 t->shutdown_pipe[1] = -1;
204         }
205         return 0;
206 }
207
208 static int py_tevent_cond_req_wait(struct tevent_context *ev,
209                                    struct tevent_req *req);
210
211 static bool py_cli_state_setup_mt_ev(struct py_cli_state *self)
212 {
213         struct py_cli_thread *t = NULL;
214         int ret;
215
216         self->ev = tevent_context_init_byname(NULL, "poll_mt");
217         if (self->ev == NULL) {
218                 goto fail;
219         }
220         samba_tevent_set_debug(self->ev, "pylibsmb_tevent_mt");
221         tevent_set_trace_callback(self->ev, py_cli_state_trace_callback, self);
222
223         self->req_wait_fn = py_tevent_cond_req_wait;
224
225         self->thread_state = talloc_zero(NULL, struct py_cli_thread);
226         if (self->thread_state == NULL) {
227                 goto fail;
228         }
229         t = self->thread_state;
230
231         ret = pipe(t->shutdown_pipe);
232         if (ret == -1) {
233                 goto fail;
234         }
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) {
239                 goto fail;
240         }
241
242         PyEval_InitThreads();
243
244         ret = pthread_create(&t->id, NULL, py_cli_state_poll_thread, self);
245         if (ret != 0) {
246                 goto fail;
247         }
248         talloc_set_destructor(self->thread_state, py_cli_thread_destructor);
249         return true;
250
251 fail:
252         if (t != NULL) {
253                 TALLOC_FREE(t->shutdown_fde);
254
255                 if (t->shutdown_pipe[0] != -1) {
256                         close(t->shutdown_pipe[0]);
257                         t->shutdown_pipe[0] = -1;
258                 }
259                 if (t->shutdown_pipe[1] != -1) {
260                         close(t->shutdown_pipe[1]);
261                         t->shutdown_pipe[1] = -1;
262                 }
263         }
264
265         TALLOC_FREE(self->thread_state);
266         TALLOC_FREE(self->ev);
267         return false;
268 }
269
270 struct py_tevent_cond {
271         pthread_mutex_t mutex;
272         pthread_cond_t cond;
273         bool is_done;
274 };
275
276 static void py_tevent_signalme(struct tevent_req *req);
277
278 static int py_tevent_cond_wait(struct py_tevent_cond *cond)
279 {
280         int ret, result;
281
282         result = pthread_mutex_init(&cond->mutex, NULL);
283         if (result != 0) {
284                 goto fail;
285         }
286         result = pthread_cond_init(&cond->cond, NULL);
287         if (result != 0) {
288                 goto fail_mutex;
289         }
290
291         result = pthread_mutex_lock(&cond->mutex);
292         if (result != 0) {
293                 goto fail_cond;
294         }
295
296         cond->is_done = false;
297
298         while (!cond->is_done) {
299
300                 Py_BEGIN_ALLOW_THREADS
301                 result = pthread_cond_wait(&cond->cond, &cond->mutex);
302                 Py_END_ALLOW_THREADS
303
304                 if (result != 0) {
305                         goto fail_unlock;
306                 }
307         }
308
309 fail_unlock:
310         ret = pthread_mutex_unlock(&cond->mutex);
311         assert(ret == 0);
312 fail_cond:
313         ret = pthread_cond_destroy(&cond->cond);
314         assert(ret == 0);
315 fail_mutex:
316         ret = pthread_mutex_destroy(&cond->mutex);
317         assert(ret == 0);
318 fail:
319         return result;
320 }
321
322 static int py_tevent_cond_req_wait(struct tevent_context *ev,
323                                    struct tevent_req *req)
324 {
325         struct py_tevent_cond cond;
326         tevent_req_set_callback(req, py_tevent_signalme, &cond);
327         return py_tevent_cond_wait(&cond);
328 }
329
330 static void py_tevent_cond_signal(struct py_tevent_cond *cond)
331 {
332         int ret;
333
334         ret = pthread_mutex_lock(&cond->mutex);
335         assert(ret == 0);
336
337         cond->is_done = true;
338
339         ret = pthread_cond_signal(&cond->cond);
340         assert(ret == 0);
341         ret = pthread_mutex_unlock(&cond->mutex);
342         assert(ret == 0);
343 }
344
345 static void py_tevent_signalme(struct tevent_req *req)
346 {
347         struct py_tevent_cond *cond = (struct py_tevent_cond *)
348                 tevent_req_callback_data_void(req);
349
350         py_tevent_cond_signal(cond);
351 }
352
353 #endif
354
355 static int py_tevent_req_wait(struct tevent_context *ev,
356                               struct tevent_req *req);
357
358 static bool py_cli_state_setup_ev(struct py_cli_state *self)
359 {
360         self->ev = tevent_context_init(NULL);
361         if (self->ev == NULL) {
362                 return false;
363         }
364
365         samba_tevent_set_debug(self->ev, "pylibsmb_tevent");
366
367         self->req_wait_fn = py_tevent_req_wait;
368
369         return true;
370 }
371
372 static int py_tevent_req_wait(struct tevent_context *ev,
373                               struct tevent_req *req)
374 {
375         while (tevent_req_is_in_progress(req)) {
376                 int ret;
377
378                 ret = tevent_loop_once(ev);
379                 if (ret != 0) {
380                         return ret;
381                 }
382         }
383         return 0;
384 }
385
386 static bool py_tevent_req_wait_exc(struct py_cli_state *self,
387                                    struct tevent_req *req)
388 {
389         int ret;
390
391         if (req == NULL) {
392                 PyErr_NoMemory();
393                 return false;
394         }
395         ret = self->req_wait_fn(self->ev, req);
396         if (ret != 0) {
397                 TALLOC_FREE(req);
398                 errno = ret;
399                 PyErr_SetFromErrno(PyExc_RuntimeError);
400                 return false;
401         }
402         return true;
403 }
404
405 static PyObject *py_cli_state_new(PyTypeObject *type, PyObject *args,
406                                   PyObject *kwds)
407 {
408         struct py_cli_state *self;
409
410         self = (struct py_cli_state *)type->tp_alloc(type, 0);
411         if (self == NULL) {
412                 return NULL;
413         }
414         self->cli = NULL;
415         self->is_smb1 = false;
416         self->ev = NULL;
417         self->thread_state = NULL;
418         self->oplock_waiter = NULL;
419         self->oplock_cond = NULL;
420         self->oplock_breaks = NULL;
421         return (PyObject *)self;
422 }
423
424 static void py_cli_got_oplock_break(struct tevent_req *req);
425
426 static int py_cli_state_init(struct py_cli_state *self, PyObject *args,
427                              PyObject *kwds)
428 {
429         NTSTATUS status;
430         char *host, *share;
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;
437         bool sign = 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;
442         bool ret;
443         int flags = 0;
444
445         static const char *kwlist[] = {
446                 "host", "share", "lp", "creds",
447                 "multi_threaded", "sign", "force_smb1",
448                 NULL
449         };
450
451         PyTypeObject *py_type_Credentials = get_pytype(
452                 "samba.credentials", "Credentials");
453         if (py_type_Credentials == NULL) {
454                 return -1;
455         }
456
457         ret = ParseTupleAndKeywords(
458                 args, kwds, "ssO|O!OOO", kwlist,
459                 &host, &share, &py_lp,
460                 py_type_Credentials, &creds,
461                 &py_multi_threaded,
462                 &py_sign,
463                 &py_force_smb1);
464
465         Py_DECREF(py_type_Credentials);
466
467         if (!ret) {
468                 return -1;
469         }
470
471         multi_threaded = PyObject_IsTrue(py_multi_threaded);
472         sign = PyObject_IsTrue(py_sign);
473         force_smb1 = PyObject_IsTrue(py_force_smb1);
474
475         if (sign) {
476                 signing_state = SMB_SIGNING_REQUIRED;
477         }
478
479         if (force_smb1) {
480                 /*
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.
485                  */
486                 flags = CLI_FULL_CONNECTION_FORCE_SMB1;
487         }
488
489         if (multi_threaded) {
490 #ifdef HAVE_PTHREAD
491                 ret = py_cli_state_setup_mt_ev(self);
492                 if (!ret) {
493                         return -1;
494                 }
495 #else
496                 PyErr_SetString(PyExc_RuntimeError,
497                                 "No PTHREAD support available");
498                 return -1;
499 #endif
500                 if (!force_smb1) {
501                         PyErr_SetString(PyExc_RuntimeError,
502                                         "multi_threaded is only possible on "
503                                         "SMB1 connections");
504                         return -1;
505                 }
506         } else {
507                 ret = py_cli_state_setup_ev(self);
508                 if (!ret) {
509                         return -1;
510                 }
511         }
512
513         if (creds == NULL) {
514                 cli_creds = cli_credentials_init_anon(NULL);
515         } else {
516                 cli_creds = PyCredentials_AsCliCredentials(creds);
517         }
518
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)) {
523                 return -1;
524         }
525         status = cli_full_connection_creds_recv(req, &self->cli);
526         TALLOC_FREE(req);
527
528         if (!NT_STATUS_IS_OK(status)) {
529                 PyErr_SetNTSTATUS(status);
530                 return -1;
531         }
532
533         if (smbXcli_conn_protocol(self->cli->conn) < PROTOCOL_SMB2_02) {
534                 self->is_smb1 = true;
535         }
536
537         /*
538          * Oplocks require a multi threaded connection
539          */
540         if (self->thread_state == NULL) {
541                 return 0;
542         }
543
544         self->oplock_waiter = cli_smb_oplock_break_waiter_send(
545                 self->ev, self->ev, self->cli);
546         if (self->oplock_waiter == NULL) {
547                 PyErr_NoMemory();
548                 return -1;
549         }
550         tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
551                                 self);
552         return 0;
553 }
554
555 static void py_cli_got_oplock_break(struct tevent_req *req)
556 {
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;
561         size_t num_breaks;
562         NTSTATUS status;
563
564         status = cli_smb_oplock_break_waiter_recv(req, &b.fnum, &b.level);
565         TALLOC_FREE(req);
566         self->oplock_waiter = NULL;
567
568         if (!NT_STATUS_IS_OK(status)) {
569                 return;
570         }
571
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);
575         if (tmp == NULL) {
576                 return;
577         }
578         self->oplock_breaks = tmp;
579         self->oplock_breaks[num_breaks] = b;
580
581         if (self->oplock_cond != NULL) {
582                 py_tevent_cond_signal(self->oplock_cond);
583         }
584
585         self->oplock_waiter = cli_smb_oplock_break_waiter_send(
586                 self->ev, self->ev, self->cli);
587         if (self->oplock_waiter == NULL) {
588                 return;
589         }
590         tevent_req_set_callback(self->oplock_waiter, py_cli_got_oplock_break,
591                                 self);
592 }
593
594 static PyObject *py_cli_get_oplock_break(struct py_cli_state *self,
595                                          PyObject *args)
596 {
597         size_t num_oplock_breaks;
598
599         if (!PyArg_ParseTuple(args, "")) {
600                 return NULL;
601         }
602
603         if (self->thread_state == NULL) {
604                 PyErr_SetString(PyExc_RuntimeError,
605                                 "get_oplock_break() only possible on "
606                                 "a multi_threaded connection");
607                 return NULL;
608         }
609
610         if (self->oplock_cond != NULL) {
611                 errno = EBUSY;
612                 PyErr_SetFromErrno(PyExc_RuntimeError);
613                 return NULL;
614         }
615
616         num_oplock_breaks = talloc_array_length(self->oplock_breaks);
617
618         if (num_oplock_breaks == 0) {
619                 struct py_tevent_cond cond;
620                 int ret;
621
622                 self->oplock_cond = &cond;
623                 ret = py_tevent_cond_wait(&cond);
624                 self->oplock_cond = NULL;
625
626                 if (ret != 0) {
627                         errno = ret;
628                         PyErr_SetFromErrno(PyExc_RuntimeError);
629                         return NULL;
630                 }
631         }
632
633         num_oplock_breaks = talloc_array_length(self->oplock_breaks);
634         if (num_oplock_breaks > 0) {
635                 PyObject *result;
636
637                 result = Py_BuildValue(
638                         "{s:i,s:i}",
639                         "fnum", self->oplock_breaks[0].fnum,
640                         "level", self->oplock_breaks[0].level);
641
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);
648
649                 return result;
650         }
651         Py_RETURN_NONE;
652 }
653
654 static void py_cli_state_dealloc(struct py_cli_state *self)
655 {
656         TALLOC_FREE(self->thread_state);
657         TALLOC_FREE(self->oplock_waiter);
658         TALLOC_FREE(self->ev);
659
660         if (self->cli != NULL) {
661                 cli_shutdown(self->cli);
662                 self->cli = NULL;
663         }
664         Py_TYPE(self)->tp_free((PyObject *)self);
665 }
666
667 static PyObject *py_cli_settimeout(struct py_cli_state *self, PyObject *args)
668 {
669         unsigned int nmsecs = 0;
670         unsigned int omsecs = 0;
671
672         if (!PyArg_ParseTuple(args, "I", &nmsecs)) {
673                 return NULL;
674         }
675
676         omsecs = cli_set_timeout(self->cli, nmsecs);
677
678         return PyInt_FromLong(omsecs);
679 }
680
681 static PyObject *py_cli_create(struct py_cli_state *self, PyObject *args,
682                                PyObject *kwds)
683 {
684         char *fname;
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;
693         uint16_t fnum;
694         struct tevent_req *req;
695         NTSTATUS status;
696
697         static const char *kwlist[] = {
698                 "Name", "CreateFlags", "DesiredAccess", "FileAttributes",
699                 "ShareAccess", "CreateDisposition", "CreateOptions",
700                 "ImpersonationLevel", "SecurityFlags", NULL };
701
702         if (!ParseTupleAndKeywords(
703                     args, kwds, "s|IIIIIIII", kwlist,
704                     &fname, &CreateFlags, &DesiredAccess, &FileAttributes,
705                     &ShareAccess, &CreateDisposition, &CreateOptions,
706                     &ImpersonationLevel, &SecurityFlags)) {
707                 return NULL;
708         }
709
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)) {
715                 return NULL;
716         }
717         status = cli_ntcreate_recv(req, &fnum, NULL);
718         TALLOC_FREE(req);
719
720         if (!NT_STATUS_IS_OK(status)) {
721                 PyErr_SetNTSTATUS(status);
722                 return NULL;
723         }
724         return Py_BuildValue("I", (unsigned)fnum);
725 }
726
727 static PyObject *py_cli_close(struct py_cli_state *self, PyObject *args)
728 {
729         struct tevent_req *req;
730         int fnum;
731         NTSTATUS status;
732
733         if (!PyArg_ParseTuple(args, "i", &fnum)) {
734                 return NULL;
735         }
736
737         req = cli_close_send(NULL, self->ev, self->cli, fnum);
738         if (!py_tevent_req_wait_exc(self, req)) {
739                 return NULL;
740         }
741         status = cli_close_recv(req);
742         TALLOC_FREE(req);
743
744         if (!NT_STATUS_IS_OK(status)) {
745                 PyErr_SetNTSTATUS(status);
746                 return NULL;
747         }
748         Py_RETURN_NONE;
749 }
750
751 struct push_state {
752         char *data;
753         off_t nread;
754         off_t total_data;
755 };
756
757 /*
758  * cli_push() helper to write a chunk of data to a remote file
759  */
760 static size_t push_data(uint8_t *buf, size_t n, void *priv)
761 {
762         struct push_state *state = (struct push_state *)priv;
763         char *curr_ptr = NULL;
764         off_t remaining;
765         size_t copied_bytes;
766
767         if (state->nread >= state->total_data) {
768                 return 0;
769         }
770
771         curr_ptr = state->data + state->nread;
772         remaining = state->total_data - state->nread;
773         copied_bytes = MIN(remaining, n);
774
775         memcpy(buf, curr_ptr, copied_bytes);
776         state->nread += copied_bytes;
777         return copied_bytes;
778 }
779
780 /*
781  * Writes a file with the contents specified
782  */
783 static PyObject *py_smb_savefile(struct py_cli_state *self, PyObject *args,
784                                  PyObject *kwargs)
785 {
786         uint16_t fnum;
787         const char *filename = NULL;
788         char *data = NULL;
789         Py_ssize_t size = 0;
790         NTSTATUS status;
791         struct tevent_req *req = NULL;
792         struct push_state state;
793
794         if (!PyArg_ParseTuple(args, "s"PYARG_BYTES_LEN":savefile", &filename,
795                               &data, &size)) {
796                 return NULL;
797         }
798
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)) {
806                 return NULL;
807         }
808         status = cli_ntcreate_recv(req, &fnum, NULL);
809         TALLOC_FREE(req);
810         PyErr_NTSTATUS_IS_ERR_RAISE(status);
811
812         /* write the new file contents */
813         state.data = data;
814         state.nread = 0;
815         state.total_data = size;
816
817         req = cli_push_send(NULL, self->ev, self->cli, fnum, 0, 0, 0,
818                             push_data, &state);
819         if (!py_tevent_req_wait_exc(self, req)) {
820                 return NULL;
821         }
822         status = cli_push_recv(req);
823         TALLOC_FREE(req);
824         PyErr_NTSTATUS_IS_ERR_RAISE(status);
825
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)) {
829                 return NULL;
830         }
831         status = cli_close_recv(req);
832         PyErr_NTSTATUS_IS_ERR_RAISE(status);
833
834         Py_RETURN_NONE;
835 }
836
837 static PyObject *py_cli_write(struct py_cli_state *self, PyObject *args,
838                               PyObject *kwds)
839 {
840         int fnum;
841         unsigned mode = 0;
842         char *buf;
843         Py_ssize_t buflen;
844         unsigned long long offset;
845         struct tevent_req *req;
846         NTSTATUS status;
847         size_t written;
848
849         static const char *kwlist[] = {
850                 "fnum", "buffer", "offset", "mode", NULL };
851
852         if (!ParseTupleAndKeywords(
853                     args, kwds, "I" PYARG_BYTES_LEN "K|I", kwlist,
854                     &fnum, &buf, &buflen, &offset, &mode)) {
855                 return NULL;
856         }
857
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)) {
861                 return NULL;
862         }
863         status = cli_write_recv(req, &written);
864         TALLOC_FREE(req);
865
866         if (!NT_STATUS_IS_OK(status)) {
867                 PyErr_SetNTSTATUS(status);
868                 return NULL;
869         }
870         return Py_BuildValue("K", (unsigned long long)written);
871 }
872
873 /*
874  * Returns the size of the given file
875  */
876 static NTSTATUS py_smb_filesize(struct py_cli_state *self, uint16_t fnum,
877                                 off_t *size)
878 {
879         NTSTATUS status;
880
881         if (self->is_smb1) {
882                 uint8_t *rdata = NULL;
883                 struct tevent_req *req = NULL;
884
885                 req = cli_qfileinfo_send(NULL, self->ev, self->cli, fnum,
886                                          SMB_QUERY_FILE_ALL_INFO, 68,
887                                          CLI_BUFFER_SIZE);
888                 if (!py_tevent_req_wait_exc(self, req)) {
889                         return NT_STATUS_INTERNAL_ERROR;
890                 }
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);
894                 }
895                 TALLOC_FREE(req);
896                 TALLOC_FREE(rdata);
897         } else {
898                 status = cli_qfileinfo_basic(self->cli, fnum, NULL, size,
899                                              NULL, NULL, NULL, NULL, NULL);
900         }
901         return status;
902 }
903
904 /*
905  * Loads the specified file's contents and returns it
906  */
907 static PyObject *py_smb_loadfile(struct py_cli_state *self, PyObject *args,
908                                  PyObject *kwargs)
909 {
910         NTSTATUS status;
911         const char *filename = NULL;
912         struct tevent_req *req = NULL;
913         uint16_t fnum;
914         off_t size;
915         char *buf = NULL;
916         off_t nread = 0;
917         PyObject *result = NULL;
918
919         if (!PyArg_ParseTuple(args, "s:loadfile", &filename)) {
920                 return NULL;
921         }
922
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)) {
929                 return NULL;
930         }
931         status = cli_ntcreate_recv(req, &fnum, NULL);
932         TALLOC_FREE(req);
933         PyErr_NTSTATUS_IS_ERR_RAISE(status);
934
935         /* get a buffer to hold the file contents */
936         status = py_smb_filesize(self, fnum, &size);
937         PyErr_NTSTATUS_IS_ERR_RAISE(status);
938
939         result = PyBytes_FromStringAndSize(NULL, size);
940         if (result == NULL) {
941                 return NULL;
942         }
943
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)) {
949                 Py_XDECREF(result);
950                 return NULL;
951         }
952         status = cli_pull_recv(req, &nread);
953         TALLOC_FREE(req);
954         if (!NT_STATUS_IS_OK(status)) {
955                 Py_XDECREF(result);
956                 PyErr_SetNTSTATUS(status);
957                 return NULL;
958         }
959
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)) {
963                 Py_XDECREF(result);
964                 return NULL;
965         }
966         status = cli_close_recv(req);
967         TALLOC_FREE(req);
968         if (!NT_STATUS_IS_OK(status)) {
969                 Py_XDECREF(result);
970                 PyErr_SetNTSTATUS(status);
971                 return NULL;
972         }
973
974         /* sanity-check we read the expected number of bytes */
975         if (nread > size) {
976                 Py_XDECREF(result);
977                 PyErr_Format(PyExc_IOError,
978                              "read invalid - got %zu requested %zu",
979                              nread, size);
980                 return NULL;
981         }
982
983         if (nread < size) {
984                 if (_PyBytes_Resize(&result, nread) < 0) {
985                         return NULL;
986                 }
987         }
988
989         return result;
990 }
991
992 static PyObject *py_cli_read(struct py_cli_state *self, PyObject *args,
993                              PyObject *kwds)
994 {
995         int fnum;
996         unsigned long long offset;
997         unsigned size;
998         struct tevent_req *req;
999         NTSTATUS status;
1000         char *buf;
1001         size_t received;
1002         PyObject *result;
1003
1004         static const char *kwlist[] = {
1005                 "fnum", "offset", "size", NULL };
1006
1007         if (!ParseTupleAndKeywords(
1008                     args, kwds, "IKI", kwlist, &fnum, &offset,
1009                     &size)) {
1010                 return NULL;
1011         }
1012
1013         result = PyBytes_FromStringAndSize(NULL, size);
1014         if (result == NULL) {
1015                 return NULL;
1016         }
1017         buf = PyBytes_AS_STRING(result);
1018
1019         req = cli_read_send(NULL, self->ev, self->cli, fnum,
1020                             buf, offset, size);
1021         if (!py_tevent_req_wait_exc(self, req)) {
1022                 Py_XDECREF(result);
1023                 return NULL;
1024         }
1025         status = cli_read_recv(req, &received);
1026         TALLOC_FREE(req);
1027
1028         if (!NT_STATUS_IS_OK(status)) {
1029                 Py_XDECREF(result);
1030                 PyErr_SetNTSTATUS(status);
1031                 return NULL;
1032         }
1033
1034         if (received > size) {
1035                 Py_XDECREF(result);
1036                 PyErr_Format(PyExc_IOError,
1037                              "read invalid - got %zu requested %u",
1038                              received, size);
1039                 return NULL;
1040         }
1041
1042         if (received < size) {
1043                 if (_PyBytes_Resize(&result, received) < 0) {
1044                         return NULL;
1045                 }
1046         }
1047
1048         return result;
1049 }
1050
1051 static PyObject *py_cli_ftruncate(struct py_cli_state *self, PyObject *args,
1052                                   PyObject *kwds)
1053 {
1054         int fnum;
1055         unsigned long long size;
1056         struct tevent_req *req;
1057         NTSTATUS status;
1058
1059         static const char *kwlist[] = {
1060                 "fnum", "size", NULL };
1061
1062         if (!ParseTupleAndKeywords(
1063                     args, kwds, "IK", kwlist, &fnum, &size)) {
1064                 return NULL;
1065         }
1066
1067         req = cli_ftruncate_send(NULL, self->ev, self->cli, fnum, size);
1068         if (!py_tevent_req_wait_exc(self, req)) {
1069                 return NULL;
1070         }
1071         status = cli_ftruncate_recv(req);
1072         TALLOC_FREE(req);
1073
1074         if (!NT_STATUS_IS_OK(status)) {
1075                 PyErr_SetNTSTATUS(status);
1076                 return NULL;
1077         }
1078         Py_RETURN_NONE;
1079 }
1080
1081 static PyObject *py_cli_delete_on_close(struct py_cli_state *self,
1082                                         PyObject *args,
1083                                         PyObject *kwds)
1084 {
1085         unsigned fnum, flag;
1086         struct tevent_req *req;
1087         NTSTATUS status;
1088
1089         static const char *kwlist[] = {
1090                 "fnum", "flag", NULL };
1091
1092         if (!ParseTupleAndKeywords(
1093                     args, kwds, "II", kwlist, &fnum, &flag)) {
1094                 return NULL;
1095         }
1096
1097         req = cli_nt_delete_on_close_send(NULL, self->ev, self->cli, fnum,
1098                                           flag);
1099         if (!py_tevent_req_wait_exc(self, req)) {
1100                 return NULL;
1101         }
1102         status = cli_nt_delete_on_close_recv(req);
1103         TALLOC_FREE(req);
1104
1105         if (!NT_STATUS_IS_OK(status)) {
1106                 PyErr_SetNTSTATUS(status);
1107                 return NULL;
1108         }
1109         Py_RETURN_NONE;
1110 }
1111
1112 /*
1113  * Helper to add directory listing entries to an overall Python list
1114  */
1115 static NTSTATUS list_helper(const char *mntpoint, struct file_info *finfo,
1116                             const char *mask, void *state)
1117 {
1118         PyObject *result = (PyObject *)state;
1119         PyObject *file = NULL;
1120         int ret;
1121
1122         /* suppress '.' and '..' in the results we return */
1123         if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
1124                 return NT_STATUS_OK;
1125         }
1126
1127         /*
1128          * Build a dictionary representing the file info.
1129          * Note: Windows does not always return short_name (so it may be None)
1130          */
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),
1136                              "mtime",
1137                              convert_timespec_to_time_t(finfo->mtime_ts));
1138
1139         if (file == NULL) {
1140                 return NT_STATUS_NO_MEMORY;
1141         }
1142
1143         ret = PyList_Append(result, file);
1144         if (ret == -1) {
1145                 return NT_STATUS_INTERNAL_ERROR;
1146         }
1147
1148         return NT_STATUS_OK;
1149 }
1150
1151 static NTSTATUS do_listing(struct py_cli_state *self,
1152                            const char *base_dir, const char *user_mask,
1153                            uint16_t attribute,
1154                            NTSTATUS (*callback_fn)(const char *,
1155                                                    struct file_info *,
1156                                                    const char *, void *),
1157                            void *priv)
1158 {
1159         char *mask = NULL;
1160         unsigned int info_level = SMB_FIND_FILE_BOTH_DIRECTORY_INFO;
1161         struct file_info *finfos = NULL;
1162         size_t i;
1163         size_t num_finfos = 0;
1164         NTSTATUS status;
1165
1166         if (user_mask == NULL) {
1167                 mask = talloc_asprintf(NULL, "%s\\*", base_dir);
1168         } else {
1169                 mask = talloc_asprintf(NULL, "%s\\%s", base_dir, user_mask);
1170         }
1171
1172         if (mask == NULL) {
1173                 return NT_STATUS_NO_MEMORY;
1174         }
1175         dos_format(mask);
1176
1177         if (self->is_smb1) {
1178                 struct tevent_req *req = NULL;
1179
1180                 req = cli_list_send(NULL, self->ev, self->cli, mask, attribute,
1181                                     info_level);
1182                 if (!py_tevent_req_wait_exc(self, req)) {
1183                         return NT_STATUS_INTERNAL_ERROR;
1184                 }
1185                 status = cli_list_recv(req, NULL, &finfos, &num_finfos);
1186                 TALLOC_FREE(req);
1187         } else {
1188                 status = cli_list(self->cli, mask, attribute, callback_fn,
1189                                   priv);
1190         }
1191         TALLOC_FREE(mask);
1192
1193         if (!NT_STATUS_IS_OK(status)) {
1194                 return status;
1195         }
1196
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,
1200                                      priv);
1201                 if (!NT_STATUS_IS_OK(status)) {
1202                         TALLOC_FREE(finfos);
1203                         return status;
1204                 }
1205         }
1206
1207         TALLOC_FREE(finfos);
1208         return status;
1209 }
1210
1211 static PyObject *py_cli_list(struct py_cli_state *self,
1212                              PyObject *args,
1213                              PyObject *kwds)
1214 {
1215         char *base_dir;
1216         char *user_mask = NULL;
1217         unsigned int attribute = LIST_ATTRIBUTE_MASK;
1218         NTSTATUS status;
1219         PyObject *result;
1220         const char *kwlist[] = { "directory", "mask", "attribs", NULL };
1221
1222         if (!ParseTupleAndKeywords(args, kwds, "z|sH:list", kwlist,
1223                                    &base_dir, &user_mask, &attribute)) {
1224                 return NULL;
1225         }
1226
1227         result = Py_BuildValue("[]");
1228         if (result == NULL) {
1229                 return NULL;
1230         }
1231
1232         status = do_listing(self, base_dir, user_mask, attribute,
1233                             list_helper, result);
1234
1235         if (!NT_STATUS_IS_OK(status)) {
1236                 Py_XDECREF(result);
1237                 PyErr_SetNTSTATUS(status);
1238                 return NULL;
1239         }
1240
1241         return result;
1242 }
1243
1244 /*
1245  * Deletes a file
1246  */
1247 static NTSTATUS unlink_file(struct py_cli_state *self, const char *filename)
1248 {
1249         NTSTATUS status;
1250         uint16_t attrs = (FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
1251
1252         if (self->is_smb1) {
1253                 struct tevent_req *req = NULL;
1254
1255                 req = cli_unlink_send(NULL, self->ev, self->cli, filename,
1256                                       attrs);
1257                 if (!py_tevent_req_wait_exc(self, req)) {
1258                         return NT_STATUS_INTERNAL_ERROR;
1259                 }
1260                 status = cli_unlink_recv(req);
1261                 TALLOC_FREE(req);
1262         } else {
1263                 status = cli_unlink(self->cli, filename, attrs);
1264         }
1265
1266         return status;
1267 }
1268
1269 static PyObject *py_smb_unlink(struct py_cli_state *self, PyObject *args)
1270 {
1271         NTSTATUS status;
1272         const char *filename = NULL;
1273
1274         if (!PyArg_ParseTuple(args, "s:unlink", &filename)) {
1275                 return NULL;
1276         }
1277
1278         status = unlink_file(self, filename);
1279         PyErr_NTSTATUS_NOT_OK_RAISE(status);
1280
1281         Py_RETURN_NONE;
1282 }
1283
1284 /*
1285  * Delete an empty directory
1286  */
1287 static NTSTATUS remove_dir(struct py_cli_state *self, const char *dirname)
1288 {
1289         NTSTATUS status;
1290
1291         if (self->is_smb1) {
1292                 struct tevent_req *req = NULL;
1293
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;
1297                 }
1298                 status = cli_rmdir_recv(req);
1299                 TALLOC_FREE(req);
1300         } else {
1301                 status = cli_rmdir(self->cli, dirname);
1302         }
1303         return status;
1304 }
1305
1306 static PyObject *py_smb_rmdir(struct py_cli_state *self, PyObject *args)
1307 {
1308         NTSTATUS status;
1309         const char *dirname;
1310
1311         if (!PyArg_ParseTuple(args, "s:rmdir", &dirname)) {
1312                 return NULL;
1313         }
1314
1315         status = remove_dir(self, dirname);
1316         PyErr_NTSTATUS_IS_ERR_RAISE(status);
1317
1318         Py_RETURN_NONE;
1319 }
1320
1321 /*
1322  * Create a directory
1323  */
1324 static PyObject *py_smb_mkdir(struct py_cli_state *self, PyObject *args)
1325 {
1326         NTSTATUS status;
1327         const char *dirname;
1328
1329         if (!PyArg_ParseTuple(args, "s:mkdir", &dirname)) {
1330                 return NULL;
1331         }
1332
1333         if (self->is_smb1) {
1334                 struct tevent_req *req = NULL;
1335
1336                 req = cli_mkdir_send(NULL, self->ev, self->cli, dirname);
1337                 if (!py_tevent_req_wait_exc(self, req)) {
1338                         return NULL;
1339                 }
1340                 status = cli_mkdir_recv(req);
1341                 TALLOC_FREE(req);
1342         } else {
1343                 status = cli_mkdir(self->cli, dirname);
1344         }
1345         PyErr_NTSTATUS_IS_ERR_RAISE(status);
1346
1347         Py_RETURN_NONE;
1348 }
1349
1350 /*
1351  * Checks existence of a directory
1352  */
1353 static bool check_dir_path(struct py_cli_state *self, const char *path)
1354 {
1355         NTSTATUS status;
1356
1357         if (self->is_smb1) {
1358                 struct tevent_req *req = NULL;
1359
1360                 req = cli_chkpath_send(NULL, self->ev, self->cli, path);
1361                 if (!py_tevent_req_wait_exc(self, req)) {
1362                         return false;
1363                 }
1364                 status = cli_chkpath_recv(req);
1365                 TALLOC_FREE(req);
1366         } else {
1367                 status = cli_chkpath(self->cli, path);
1368         }
1369
1370         return NT_STATUS_IS_OK(status);
1371 }
1372
1373 static PyObject *py_smb_chkpath(struct py_cli_state *self, PyObject *args)
1374 {
1375         const char *path;
1376         bool dir_exists;
1377
1378         if (!PyArg_ParseTuple(args, "s:chkpath", &path)) {
1379                 return NULL;
1380         }
1381
1382         dir_exists = check_dir_path(self, path);
1383         return PyBool_FromLong(dir_exists);
1384 }
1385
1386 struct deltree_state {
1387         struct py_cli_state *self;
1388         const char *full_dirpath;
1389 };
1390
1391 static NTSTATUS delete_dir_tree(struct py_cli_state *self,
1392                                 const char *dirpath);
1393
1394 /*
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.
1398  */
1399 static NTSTATUS delete_tree_callback(const char *mntpoint,
1400                                      struct file_info *finfo,
1401                                      const char *mask, void *priv)
1402 {
1403         char *filepath = NULL;
1404         struct deltree_state *state = priv;
1405         NTSTATUS status;
1406
1407         /* skip '.' or '..' directory listings */
1408         if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
1409                 return NT_STATUS_OK;
1410         }
1411
1412         /* get the absolute filepath */
1413         filepath = talloc_asprintf(NULL, "%s\\%s", state->full_dirpath,
1414                                    finfo->name);
1415         if (filepath == NULL) {
1416                 return NT_STATUS_NO_MEMORY;
1417         }
1418
1419         if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
1420
1421                 /* recursively delete the sub-directory and its contents */
1422                 status = delete_dir_tree(state->self, filepath);
1423         } else {
1424                 status = unlink_file(state->self, filepath);
1425         }
1426
1427         TALLOC_FREE(filepath);
1428         return status;
1429 }
1430
1431 /*
1432  * Removes a directory and all its contents
1433  */
1434 static NTSTATUS delete_dir_tree(struct py_cli_state *self,
1435                                 const char *filepath)
1436 {
1437         NTSTATUS status;
1438         const char *mask = "*";
1439         struct deltree_state state = { 0 };
1440
1441         /* go through the directory's contents, deleting each item */
1442         state.self = self;
1443         state.full_dirpath = filepath;
1444         status = do_listing(self, filepath, mask, LIST_ATTRIBUTE_MASK,
1445                             delete_tree_callback, &state);
1446
1447         /* remove the directory itself */
1448         if (NT_STATUS_IS_OK(status)) {
1449                 status = remove_dir(self, filepath);
1450         }
1451         return status;
1452 }
1453
1454 static PyObject *py_smb_deltree(struct py_cli_state *self, PyObject *args)
1455 {
1456         NTSTATUS status;
1457         const char *filepath = NULL;
1458         bool dir_exists;
1459
1460         if (!PyArg_ParseTuple(args, "s:deltree", &filepath)) {
1461                 return NULL;
1462         }
1463
1464         /* check whether we're removing a directory or a file */
1465         dir_exists = check_dir_path(self, filepath);
1466
1467         if (dir_exists) {
1468                 status = delete_dir_tree(self, filepath);
1469         } else {
1470                 status = unlink_file(self, filepath);
1471         }
1472
1473         PyErr_NTSTATUS_IS_ERR_RAISE(status);
1474
1475         Py_RETURN_NONE;
1476 }
1477
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,
1482           "Open a file" },
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,
1509           METH_VARARGS,
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 }
1528 };
1529
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,
1540 };
1541
1542 static PyMethodDef py_libsmb_methods[] = {
1543         { NULL },
1544 };
1545
1546 void initlibsmb_samba_internal(void);
1547
1548 static struct PyModuleDef moduledef = {
1549     PyModuleDef_HEAD_INIT,
1550     .m_name = "libsmb_samba_internal",
1551     .m_doc = "libsmb wrapper",
1552     .m_size = -1,
1553     .m_methods = py_libsmb_methods,
1554 };
1555
1556 MODULE_INIT_FUNC(libsmb_samba_internal)
1557 {
1558         PyObject *m = NULL;
1559
1560         talloc_stackframe();
1561
1562         m = PyModule_Create(&moduledef);
1563         if (m == NULL) {
1564                 return m;
1565         }
1566         if (PyType_Ready(&py_cli_state_type) < 0) {
1567                 return NULL;
1568         }
1569         Py_INCREF(&py_cli_state_type);
1570         PyModule_AddObject(m, "Conn", (PyObject *)&py_cli_state_type);
1571
1572 #define ADD_FLAGS(val)  PyModule_AddObject(m, #val, PyInt_FromLong(val))
1573
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);
1590
1591         return m;
1592 }