pysmbc-1.0.23/0000755000175000017500000000000013745433040013625 5ustar hamanohamano00000000000000pysmbc-1.0.23/Makefile0000644000175000017500000000111113661003263015254 0ustar hamanohamano00000000000000PYTHON=python NAME=pysmbc VERSION:=$(shell $(PYTHON) setup.py --version) _smbc.so: force $(PYTHON) setup.py build mv build/lib*/_smbc*.so . doc: _smbc.so rm -rf html epydoc -o html --html $< doczip: doc cd html && zip ../smbc-html.zip * clean: -rm -rf build smbc.so *.pyc tests/*.pyc *~ tests/*~ _smbc*.so dist: $(PYTHON) setup.py sdist $(SDIST_ARGS) upload: $(PYTHON) setup.py sdist $(SDIST_ARGS) upload -s install: ROOT= ; \ if [ -n "$$DESTDIR" ]; then ROOT="--root $$DESTDIR"; fi; \ $(PYTHON) setup.py install $$ROOT .PHONY: doc doczip clean dist install force pysmbc-1.0.23/setup.cfg0000644000175000017500000000004613745433040015446 0ustar hamanohamano00000000000000[egg_info] tag_build = tag_date = 0 pysmbc-1.0.23/smbc/0000755000175000017500000000000013745433040014551 5ustar hamanohamano00000000000000pysmbc-1.0.23/smbc/xattr.py0000644000175000017500000000262113543345042016266 0ustar hamanohamano00000000000000#!/usr/bin/python SMB_POSIX_ACL_USER_OBJ=0x01 SMB_POSIX_ACL_USER=0x02 SMB_POSIX_ACL_GROUP_OBJ=0x04 SMB_POSIX_ACL_GROUP=0x08 SMB_POSIX_ACL_MASK=0x10 SMB_POSIX_ACL_OTHER=0x20 SMB_POSIX_ACL_READ=0x04 SMB_POSIX_ACL_WRITE=0x02 SMB_POSIX_ACL_EXECUTE=0x01 SMB_POSIX_ACL_HEADER_SIZE=6 SMB_POSIX_ACL_ENTRY_SIZE=10 rwx=0x001e01ff x=0x001200a0 w=0x00120116 r=0x00120089 class SmbAcl(): revision = None owner = None group = None acl = [] def __init__(self, xattr_s=None): """ parse an acl into a SmbAcl object """ if xattr_s: xattr_l = [ s[s.index(":")+1:] for s in xattr_s.split(",")] (self.revision, self.owner, self.group) = xattr_l[0:3] self.acl = xattr_l[3:] def __str__(self): ret = "REVISION:%s,OWNER:%s,GROUP:%s" % (self.revision,self.owner,self.group) for a in self.acl: ret = ret + ",ACL:%s" % a return ret @staticmethod def get_target(acl_s): return acl_s[0:acl_s.index(":")] @staticmethod def get_perm(acl_s): return acl_s[acl_s.index(":")+1:] # #import smbc # #c = smbc.Context(debug=1) #cb = lambda se, sh, w, u, p: ("WORKGROUP","babel","b3nedetto") #c.functionAuthData = cb # #print c.opendir("smb://localhost/share/Neffa").getdents() #print c.getxattr("smb://localhost/share/Neffa", "system.nt_sec_desc.*") #print c.getxattr("smb://localhost/share/Neffa", "s") # pysmbc-1.0.23/smbc/file.h0000644000175000017500000000233413543345042015643 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008, 2010 Red Hat, Inc * Copyright (C) 2010 Open Source Solution Technology Corporation * Authors: * Tim Waugh * Tsukasa Hamano * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef HAVE_FILE_H #define HAVE_FILE_H typedef struct { PyObject_HEAD Context *context; SMBCFILE *file; } File; extern PyMethodDef File_methods[]; extern PyTypeObject smbc_FileType; #endif /* HAVE_FILE_H */ pysmbc-1.0.23/smbc/context.c0000644000175000017500000011601213744321370016403 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008, 2010, 2011, 2012, 2013 Red Hat, Inc * Copyright (C) 2010 Open Source Solution Technology Corporation * Copyright (C) 2010 Patrick Geltinger * Authors: * Tim Waugh * Tsukasa Hamano * Patrick Geltinger * Roberto Polli * Fabio Isgro' * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "smbcmodule.h" #include "context.h" #include "dir.h" #include "file.h" static void auth_fn (SMBCCTX *ctx, const char *server, const char *share, char *workgroup, int wgmaxlen, char *username, int unmaxlen, char *password, int pwmaxlen) { PyObject *args; PyObject *kwds; PyObject *result; Context *self; const char *use_workgroup, *use_username, *use_password; debugprintf ("-> auth_fn (server=%s, share=%s)\n", server ? server : "", share ? share : ""); self = smbc_getOptionUserData (ctx); if (self->auth_fn == NULL) { debugprintf ("<- auth_fn (), no callback\n"); return; } if (!server || !*server) { debugprintf ("<- auth_fn(), no server\n"); return; } args = Py_BuildValue ("(sssss)", server, share, workgroup, username, password); kwds = PyDict_New (); result = PyObject_Call (self->auth_fn, args, kwds); Py_DECREF (args); Py_DECREF (kwds); if (result == NULL) { debugprintf ("<- auth_fn(), failed callback\n"); return; } if (!PyArg_ParseTuple (result, "sss", &use_workgroup, &use_username, &use_password)) { Py_DECREF (result); debugprintf ("<- auth_fn(), incorrect callback result\n"); return; } strncpy (workgroup, use_workgroup, wgmaxlen - 1); workgroup[wgmaxlen - 1] = '\0'; strncpy (username, use_username, unmaxlen - 1); username[unmaxlen - 1] = '\0'; strncpy (password, use_password, pwmaxlen - 1); password[pwmaxlen - 1] = '\0'; Py_DECREF (result); debugprintf ("<- auth_fn(), got callback result\n"); } ///////////// // Context // ///////////// static PyObject * Context_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Context *self; self = (Context *) type->tp_alloc (type, 0); if (self != NULL) self->context = NULL; return (PyObject *) self; } static int Context_init (Context *self, PyObject *args, PyObject *kwds) { PyObject *auth = NULL; int debug = 0; SMBCCTX *ctx; char *proto = NULL; static char *kwlist[] = { "auth_fn", "debug", "proto", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "|Ois", kwlist, &auth, &debug, &proto)) { return -1; } if (auth) { if (!PyCallable_Check (auth)) { PyErr_SetString (PyExc_TypeError, "auth_fn must be callable"); return -1; } Py_INCREF (auth); self->auth_fn = auth; } debugprintf ("-> Context_init ()\n"); errno = 0; ctx = smbc_new_context (); if (ctx == NULL) { PyErr_SetFromErrno (PyExc_RuntimeError); debugprintf ("<- Context_init() EXCEPTION\n"); return -1; } smbc_setDebug (ctx, debug); self->context = ctx; smbc_setOptionUserData (ctx, self); if (auth) smbc_setFunctionAuthDataWithContext (ctx, auth_fn); if(proto) { #if SMBCLIENT_VERSION >= 500 /* 0.5.0 or newer */ debugprintf("-> Setting client min/max protocol to %s by smbc_setOptionProtocols\n", proto); smbc_setOptionProtocols(ctx, proto, proto); #else debugprintf("-> Setting client min/max protocol to %s by smbc_option_set\n", proto); smbc_option_set(ctx, "client max protocol", proto); smbc_option_set(ctx, "client min protocol", proto); #endif } if (smbc_init_context (ctx) == NULL) { PyErr_SetFromErrno (PyExc_RuntimeError); smbc_free_context (ctx, 0); debugprintf ("<- Context_init() EXCEPTION\n"); return -1; } debugprintf ("%p <- Context_init() = 0\n", self->context); return 0; } static void Context_dealloc (Context *self) { if (self->context) { debugprintf ("%p smbc_free_context()\n", self->context); smbc_free_context (self->context, 1); } Py_XDECREF (self->auth_fn); Py_TYPE(self)->tp_free ((PyObject *) self); } static PyObject * Context_set_credentials_with_fallback (Context *self, PyObject *args) { char *workgroup = NULL; char *user = NULL; char *password = NULL; debugprintf ("%p -> Context_set_credentials_with_fallback()\n", self->context); if (!PyArg_ParseTuple (args, "sss", &workgroup, &user, &password)) { debugprintf ("%p <- Context_open() EXCEPTION\n", self->context); return NULL; } smbc_set_credentials_with_fallback (self->context, workgroup, user, password); debugprintf ("%p <- Context_set_credentials_with_fallback()\n", self->context); Py_RETURN_NONE; } static PyObject * Context_open (Context *self, PyObject *args) { PyObject *result = NULL; PyObject *largs = NULL; PyObject *lkwlist = NULL; char *uri; File *file = NULL; int flags = 0; int mode = 0; smbc_open_fn fn_open; debugprintf ("%p -> Context_open()\n", self->context); do /*once*/ { if (!PyArg_ParseTuple (args, "s|ii", &uri, &flags, &mode)) { debugprintf ("%p <- Context_open() EXCEPTION\n", self->context); break; } /*if*/ largs = Py_BuildValue("()"); if (PyErr_Occurred()) break; lkwlist = PyDict_New(); if (PyErr_Occurred()) break; PyDict_SetItemString(lkwlist, "context", (PyObject *)self); if (PyErr_Occurred()) break; file = (File *)smbc_FileType.tp_new(&smbc_FileType, largs, lkwlist); if (file == NULL) { PyErr_NoMemory(); break; } /*if*/ if (smbc_FileType.tp_init((PyObject *)file, largs, lkwlist) < 0) { debugprintf ("%p <- Context_open() EXCEPTION\n", self->context); // already set error break; } /*if*/ fn_open = smbc_getFunctionOpen(self->context); errno = 0; file->file = fn_open(self->context, uri, (int)flags, (mode_t)mode); if (file->file == NULL) { pysmbc_SetFromErrno(); break; } /*if*/ debugprintf ("%p <- Context_open() = File\n", self->context); /* all done */ result = (PyObject *)file; file = NULL; /* so I don't dispose of it yet */ } while (false); if (file != NULL) { smbc_FileType.tp_dealloc((PyObject *)file); } /*if*/ Py_XDECREF(largs); Py_XDECREF(lkwlist); return result; } /*Context_open*/ static PyObject * Context_creat (Context *self, PyObject *args) { PyObject *result = NULL; PyObject *largs = NULL; PyObject *lkwlist = NULL; char *uri; int mode = 0; File *file = NULL; smbc_creat_fn fn_creat; do /*once*/ { if (!PyArg_ParseTuple (args, "s|i", &uri, &mode)) break; largs = Py_BuildValue("()"); if (PyErr_Occurred()) break; lkwlist = PyDict_New(); if (PyErr_Occurred()) break; PyDict_SetItemString(lkwlist, "context", (PyObject *)self); if (PyErr_Occurred()) break; file = (File *)smbc_FileType.tp_new(&smbc_FileType, largs, lkwlist); if (file == NULL) { PyErr_NoMemory(); break; } /*if*/ if (smbc_FileType.tp_init((PyObject *)file, largs, lkwlist) < 0) break; fn_creat = smbc_getFunctionCreat (self->context); errno = 0; file->file = fn_creat(self->context, uri, mode); if (file->file == NULL) { pysmbc_SetFromErrno(); break; } /*if*/ /* all done */ result = (PyObject *)file; file = NULL; /* so I don't dispose of it yet */ } while (false); if (file != NULL) { smbc_FileType.tp_dealloc((PyObject *)file); } /*if*/ Py_XDECREF(largs); Py_XDECREF(lkwlist); return result; } /*Context_creat*/ static PyObject * Context_unlink (Context *self, PyObject *args) { int ret; char *uri = NULL; smbc_unlink_fn fn; if(!PyArg_ParseTuple (args, "s", &uri)) { return NULL; } fn = smbc_getFunctionUnlink (self->context); errno = 0; ret = (*fn) (self->context, uri); if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return PyLong_FromLong (ret); } static PyObject * Context_rename (Context *self, PyObject *args) { int ret; char *ouri = NULL; char *nuri = NULL; Context *nctx = NULL; smbc_rename_fn fn; if (!PyArg_ParseTuple (args, "ss|O", &ouri, &nuri, &nctx)) { return NULL; } fn = smbc_getFunctionRename(self->context); errno = 0; if (nctx && nctx->context) { ret = (*fn) (self->context, ouri, nctx->context, nuri); } else { ret = (*fn) (self->context, ouri, self->context, nuri); } if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return PyLong_FromLong (ret); } static PyObject * Context_opendir (Context *self, PyObject *args) { PyObject *result = NULL; PyObject *largs = NULL; PyObject *lkwlist = NULL; PyObject *uri; PyObject *dir = NULL; debugprintf ("%p -> Context_opendir()\n", self->context); do /*once*/ { if (!PyArg_ParseTuple(args, "O", &uri)) { debugprintf ("%p <- Context_opendir() EXCEPTION\n", self->context); break; } /*if*/ largs = Py_BuildValue("()"); if (PyErr_Occurred()) break; lkwlist = PyDict_New(); if (PyErr_Occurred()) break; PyDict_SetItemString(lkwlist, "context", (PyObject *) self); if (PyErr_Occurred()) break; PyDict_SetItemString(lkwlist, "uri", uri); if (PyErr_Occurred()) break; dir = smbc_DirType.tp_new(&smbc_DirType, largs, lkwlist); if (dir == NULL) { PyErr_NoMemory(); break; } /*if*/ if (smbc_DirType.tp_init(dir, largs, lkwlist) < 0) { debugprintf ("%p <- Context_opendir() EXCEPTION\n", self->context); break; } /*if*/ debugprintf ("%p <- Context_opendir() = Dir\n", self->context); /* all done */ result = (PyObject *)dir; dir = NULL; /* so I don't dispose of it yet */ } while (false); if (dir != NULL) { smbc_DirType.tp_dealloc(dir); } /*if*/ Py_XDECREF(largs); Py_XDECREF(lkwlist); return result; } /*Context_opendir*/ static PyObject * Context_mkdir (Context *self, PyObject *args) { int ret; char *uri = NULL; unsigned int mode = 0; smbc_mkdir_fn fn; if (!PyArg_ParseTuple (args, "s|I", &uri, &mode)) { return NULL; } fn = smbc_getFunctionMkdir (self->context); errno = 0; ret = (*fn) (self->context, uri, mode); if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return PyLong_FromLong (ret); } static PyObject * Context_rmdir (Context *self, PyObject *args) { int ret; char *uri = NULL; smbc_rmdir_fn fn; if (!PyArg_ParseTuple (args, "s", &uri)) { return NULL; } fn = smbc_getFunctionRmdir (self->context); errno = 0; ret = (*fn) (self->context, uri); if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return PyLong_FromLong (ret); } static PyObject * Context_stat (Context *self, PyObject *args) { int ret; char *uri = NULL; smbc_stat_fn fn; struct stat st; if (!PyArg_ParseTuple (args, "s", &uri)) { return NULL; } fn = smbc_getFunctionStat (self->context); errno = 0; ret = (*fn) (self->context, uri, &st); if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return Py_BuildValue ("(IKKKIIKIII)", st.st_mode, (unsigned long long)st.st_ino, (unsigned long long)st.st_dev, (unsigned long long)st.st_nlink, st.st_uid, st.st_gid, st.st_size, st.st_atime, st.st_mtime, st.st_ctime); } static PyObject * Context_chmod (Context *self, PyObject *args) { int ret; char *uri = NULL; mode_t mode = 0; smbc_chmod_fn fn; if (!PyArg_ParseTuple (args, "si", &uri, &mode)) { return NULL; } errno = 0; fn = smbc_getFunctionChmod (self->context); ret = (*fn) (self->context, uri, mode); if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return PyLong_FromLong (ret); } /** * Wrapper for the smbc_getxattr() smbclient function. From libsmbclient.h * @author fisgro@babel.it, rpolli@babel.it * * @param uri The smb url of the file or directory to get extended * attributes for. * * @param name The name of an attribute to be retrieved. Names are of * one of the following forms: * * system.nt_sec_desc. * system.nt_sec_desc.* * system.nt_sec_desc.*+ */ static PyObject * Context_getxattr (Context *self, PyObject *args) { PyObject * result = NULL; char *uri = NULL; char *name = NULL; char *buffer = NULL; int ret; do /*once*/ { if (!PyArg_ParseTuple(args, "ss", &uri, &name)) break; const smbc_getxattr_fn fn = smbc_getFunctionGetxattr(self->context); errno = 0; ret = fn(self->context, uri, name, NULL, 0); if (ret < 0) { pysmbc_SetFromErrno(); break; } const int bufsize = ret + 1; buffer = (char *)malloc(bufsize); if (buffer == NULL) { PyErr_NoMemory(); break; } /*if*/ ret = fn(self->context, uri, name, buffer, bufsize); if (ret < 0) { pysmbc_SetFromErrno(); break; } /*if*/ result = PyUnicode_FromString(buffer); } while (false); free(buffer); return result; } /*Context_getxattr*/ /** * Wrapper for the smbc_setxattr() smbclient function. From libsmbclient.h * @author fisgro@babel.it, rpolli@babel.it * * @param uri The smb url of the file or directory to set extended * attributes for. * * @param name The name of an attribute to be retrieved. Names are of * one of the following forms: * * system.nt_sec_desc. * system.nt_sec_desc.+ * system.nt_sec_desc.revision DANGEROUS!!! * system.nt_sec_desc.owner * system.nt_sec_desc.owner+ * system.nt_sec_desc.group * system.nt_sec_desc.group+ * system.nt_sec_desc.* * system.nt_sec_desc.*+ * system.nt_sec_desc.ACL:// * * @param value The value to be assigned to the specified attribute name. * This buffer should contain only the attribute value if the * name was of the "system.nt_sec_desc." * form. If the name was of the "system.nt_sec_desc.*" form * then a complete security descriptor, with name:value pairs * separated by tabs, commas, or newlines (not spaces!), * should be provided in this value buffer. A complete * security descriptor will contain one or more entries * selected from the following: * * REVISION: * OWNER: * GROUP: * ACL::// * * The revision of the ACL specifies the internal Windows NT * ACL revision for the security descriptor. If not specified * it defaults to 1. Using values other than 1 may cause * strange behaviour. * * The owner and group specify the owner and group sids for * the object. If the attribute name (either '*+' with a * complete security descriptor, or individual 'owner+' or * 'group+' attribute names) ended with a plus sign, the * specified name is resolved to a SID value, using the * server on which the file or directory resides. Otherwise, * the value should be provided in SID-printable format as * S-1-x-y-z, and is used directly. The * associated with the ACL: attribute should be provided * similarly. * @return 0 on success, < 0 on error with errno set: * - EINVAL The client library is not properly initialized * or one of the parameters is not of a correct * form * - ENOMEM No memory was available for internal needs * - EEXIST If the attribute already exists and the flag * SMBC_XATTR_FLAG_CREAT was specified * - ENOATTR If the attribute does not exist and the flag * SMBC_XATTR_FLAG_REPLACE was specified * - EPERM Permission was denied. * - ENOTSUP The referenced file system does not support * extended attributes * */ static PyObject* Context_setxattr (Context *self, PyObject *args) { int ret; char *uri = NULL; char *name = NULL; char *value = NULL; unsigned int flags; static smbc_setxattr_fn fn; if (!PyArg_ParseTuple (args, "sssi", &uri, &name, &value, &flags)) { return NULL; } if (!value) { return NULL; } errno = 0; fn = smbc_getFunctionSetxattr (self->context); ret = (*fn)(self->context, uri, name, value, strlen (value), flags); if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return PyLong_FromLong (ret); } static PyObject * Context_getDebug (Context *self, void *closure) { int d = smbc_getDebug (self->context); return PyLong_FromLong (d); } static int Context_setDebug (Context *self, PyObject *value, void *closure) { int d; #if PY_MAJOR_VERSION < 3 if (PyInt_Check (value)) value = PyLong_FromLong (PyInt_AsLong (value)); #endif if (!PyLong_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be int"); return -1; } d = PyLong_AsLong (value); smbc_setDebug (self->context, d); return 0; } static PyObject * Context_getNetbiosName (Context *self, void *closure) { const char *netbios_name = smbc_getNetbiosName (self->context); return PyUnicode_FromString (netbios_name); } static int Context_setNetbiosName (Context *self, PyObject *value, void *closure) { wchar_t *w_name; size_t chars; char *name; size_t bytes; ssize_t written; #if PY_MAJOR_VERSION < 3 if (PyString_Check (value)) value = PyUnicode_FromString (PyString_AsString (value)); #endif if (!PyUnicode_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be string"); return -1; } #if PY_MAJOR_VERSION > 3 chars = PyUnicode_GET_LENGTH(value); #else chars = PyUnicode_GET_SIZE(value); /* not including NUL */ #endif w_name = malloc ((chars + 1) * sizeof (wchar_t)); if (!w_name) { PyErr_NoMemory (); return -1; } #if PY_MAJOR_VERSION < 3 if (PyUnicode_AsWideChar ((PyUnicodeObject *) value, w_name, chars) == -1) #else if (PyUnicode_AsWideChar (value, w_name, chars) == -1) #endif { free (w_name); return -1; } w_name[chars] = L'\0'; bytes = MB_CUR_MAX * chars + 1; /* extra byte for NUL */ name = malloc (bytes); if (!name) { free (w_name); PyErr_NoMemory (); return -1; } written = wcstombs (name, w_name, bytes); free (w_name); if (written == -1) name[0] = '\0'; else /* NUL-terminate it (this is why we allocated an extra byte) */ name[written] = '\0'; smbc_setNetbiosName (self->context, name); // Don't free name: the API function just takes a reference(!) return 0; } static PyObject * Context_getWorkgroup (Context *self, void *closure) { const char *workgroup = smbc_getWorkgroup (self->context); return PyUnicode_FromString (workgroup); } static int Context_setWorkgroup (Context *self, PyObject *value, void *closure) { wchar_t *w_workgroup; size_t chars; char *workgroup; size_t bytes; ssize_t written; #if PY_MAJOR_VERSION < 3 if (PyString_Check (value)) value = PyUnicode_FromString (PyString_AsString (value)); #endif if (!PyUnicode_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be string"); return -1; } #if PY_MAJOR_VERSION > 3 chars = PyUnicode_GET_LENGTH(value); #else chars = PyUnicode_GET_SIZE(value); /* not including NUL */ #endif w_workgroup = malloc ((chars + 1) * sizeof (wchar_t)); if (!w_workgroup) { PyErr_NoMemory (); return -1; } #if PY_MAJOR_VERSION < 3 if (PyUnicode_AsWideChar ((PyUnicodeObject *) value, w_workgroup, chars) == -1) #else if (PyUnicode_AsWideChar (value, w_workgroup, chars) == -1) #endif { free (w_workgroup); return -1; } w_workgroup[chars] = L'\0'; bytes = MB_CUR_MAX * chars + 1; /* extra byte for NUL */ workgroup = malloc (bytes); if (!workgroup) { free (w_workgroup); PyErr_NoMemory (); return -1; } written = wcstombs (workgroup, w_workgroup, bytes); free (w_workgroup); if (written == -1) workgroup[0] = '\0'; else /* NUL-terminate it (this is why we allocated the extra byte) */ workgroup[written] = '\0'; smbc_setWorkgroup (self->context, workgroup); // Don't free workgroup: the API function just takes a reference(!) return 0; } static PyObject * Context_getTimeout (Context *self, void *closure) { int timeout = smbc_getTimeout (self->context); return PyLong_FromLong (timeout); } static int Context_setTimeout (Context *self, PyObject *value, void *closure) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check (value)) #else if (!PyLong_Check (value)) #endif { PyErr_SetString (PyExc_TypeError, "must be long"); return -1; } #if PY_MAJOR_VERSION < 3 smbc_setTimeout (self->context, PyInt_AsLong (value)); #else smbc_setTimeout (self->context, PyLong_AsLong (value)); #endif return 0; } static PyObject * Context_getPort (Context *self, void *closure) { int port = smbc_getPort (self->context); return PyLong_FromLong (port); } static int Context_setPort (Context *self, PyObject *value, void *closure) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check (value)) #else if (!PyLong_Check (value)) #endif { PyErr_SetString (PyExc_TypeError, "must be long"); return -1; } #if PY_MAJOR_VERSION < 3 smbc_setPort (self->context, PyInt_AsLong (value)); #else smbc_setPort (self->context, PyLong_AsLong (value)); #endif return 0; } static int Context_setFunctionAuthData (Context *self, PyObject *value, void *closure) { if (!PyCallable_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be callable object"); return -1; } Py_XDECREF (self->auth_fn); Py_INCREF (value); self->auth_fn = value; smbc_setFunctionAuthDataWithContext (self->context, auth_fn); return 0; } static PyObject * Context_getOptionDebugToStderr (Context *self, void *closure) { smbc_bool b; b = smbc_getOptionDebugToStderr (self->context); return PyBool_FromLong ((long) b); } static int Context_setOptionDebugToStderr (Context *self, PyObject *value, void *closure) { if (!PyBool_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be Boolean"); return -1; } smbc_setOptionDebugToStderr (self->context, value == Py_True); return 0; } static PyObject * Context_getOptionFullTimeNames (Context *self, void *closure) { smbc_bool b; b = smbc_getOptionFullTimeNames (self->context); return PyBool_FromLong ((long) b); } static int Context_setOptionFullTimeNames (Context *self, PyObject *value, void *closure) { if (!PyBool_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be Boolean"); return -1; } smbc_setOptionFullTimeNames (self->context, value == Py_True); return 0; } static PyObject * Context_getOptionNoAutoAnonymousLogin (Context *self, void *closure) { smbc_bool b; b = smbc_getOptionNoAutoAnonymousLogin (self->context); return PyBool_FromLong ((long) b); } static int Context_setOptionNoAutoAnonymousLogin (Context *self, PyObject *value, void *closure) { if (!PyBool_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be Boolean"); return -1; } smbc_setOptionNoAutoAnonymousLogin (self->context, value == Py_True); return 0; } static PyObject * Context_getOptionUseKerberos (Context *self, void *closure) { smbc_bool b; b = smbc_getOptionUseKerberos (self->context); return PyBool_FromLong ((long) b); } static int Context_setOptionUseKerberos (Context *self, PyObject *value, void *closure) { if (!PyBool_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be Boolean"); return -1; } smbc_setOptionUseKerberos (self->context, value == Py_True); return 0; } static PyObject * Context_getOptionFallbackAfterKerberos (Context *self, void *closure) { smbc_bool b; b = smbc_getOptionFallbackAfterKerberos (self->context); return PyBool_FromLong ((long) b); } static int Context_setOptionFallbackAfterKerberos (Context *self, PyObject *value, void *closure) { if (!PyBool_Check (value)) { PyErr_SetString (PyExc_TypeError, "must be Boolean"); return -1; } smbc_setOptionFallbackAfterKerberos (self->context, value == Py_True); return 0; } PyGetSetDef Context_getseters[] = { { "debug", (getter) Context_getDebug, (setter) Context_setDebug, "Debug level.", NULL }, { "netbiosName", (getter) Context_getNetbiosName, (setter) Context_setNetbiosName, "Netbios name used for making connections.", NULL }, { "workgroup", (getter) Context_getWorkgroup, (setter) Context_setWorkgroup, "Workgroup used for making connections.", NULL }, { "timeout", (getter) Context_getTimeout, (setter) Context_setTimeout, "Get the timeout used for waiting on connections and response data(in milliseconds)", NULL }, { "port", (getter) Context_getPort, (setter) Context_setPort, "Set the TCP port used to connect (0 means default).", NULL }, { "functionAuthData", (getter) NULL, (setter) Context_setFunctionAuthData, "Function for obtaining authentication data.", NULL }, { "optionDebugToStderr", (getter) Context_getOptionDebugToStderr, (setter) Context_setOptionDebugToStderr, "Whether to log to standard error instead of standard output.", NULL }, { "optionFullTimeNames", (getter) Context_getOptionFullTimeNames, (setter) Context_setOptionFullTimeNames, "Use full time names (Create Time)", NULL }, { "optionNoAutoAnonymousLogin", (getter) Context_getOptionNoAutoAnonymousLogin, (setter) Context_setOptionNoAutoAnonymousLogin, "Whether to automatically select anonymous login.", NULL }, { "optionUseKerberos", (getter) Context_getOptionUseKerberos, (setter) Context_setOptionUseKerberos, "Whether to enable use of Kerberos.", NULL }, { "optionFallbackAfterKerberos", (getter) Context_getOptionFallbackAfterKerberos, (setter) Context_setOptionFallbackAfterKerberos, "Whether to fallback after Kerberos.", NULL }, { NULL } }; PyMethodDef Context_methods[] = { { "set_credentials_with_fallback", (PyCFunction) Context_set_credentials_with_fallback, METH_VARARGS, "set_credentials_with_fallback(workgroup, user, password)\n\n" "@type workgroup: string\n" "@param workgroup: Workgroup of user\n" "@type user: string\n" "@param user: Username of user\n" "@type password: string\n" "@param password: Password of user\n" }, { "opendir", (PyCFunction) Context_opendir, METH_VARARGS, "opendir(uri) -> Dir\n\n" "@type uri: string\n" "@param uri: URI to opendir\n" "@return: a L{smbc.Dir} object for the URI" }, { "open", (PyCFunction) Context_open, METH_VARARGS, "open(uri) -> File\n\n" "@type uri: string\n" "@param uri: URI to open\n" "@return: a L{smbc.File} object for the URI" }, { "creat", (PyCFunction) Context_creat, METH_VARARGS, "creat(uri) -> File\n\n" "@type uri: string\n" "@param uri: URI to creat\n" "@return: a L{smbc.File} object for the URI" }, { "unlink", (PyCFunction) Context_unlink, METH_VARARGS, "unlink(uri) -> int\n\n" "@type uri: string\n" "@param uri: URI to unlink\n" "@return: 0 on success, < 0 on error" }, { "rename", (PyCFunction) Context_rename, METH_VARARGS, "rename(ouri, nuri) -> int\n\n" "@type ouri: string\n" "@param ouri: The original smb uri\n" "@type nuri: string\n" "@param nuri: The new smb uri\n" "@return: 0 on success, < 0 on error" }, { "mkdir", (PyCFunction) Context_mkdir, METH_VARARGS, "mkdir(uri, mode) -> int\n\n" "@type uri: string\n" "@param uri: URI to mkdir\n" "@param mode: Specifies the permissions to use.\n" "@return: 0 on success, < 0 on error" }, { "rmdir", (PyCFunction) Context_rmdir, METH_VARARGS, "rmdir(uri) -> int\n\n" "@type uri: string\n" "@param uri: URI to rmdir\n" "@return: 0 on success, < 0 on error" }, { "stat", (PyCFunction) Context_stat, METH_VARARGS, "stat(uri) -> tuple\n\n" "@type uri: string\n" "@param uri: URI to get stat information\n" "@return: stat information" }, { "chmod", (PyCFunction) Context_chmod, METH_VARARGS, "chmod(uri, mode) -> int\n\n" "@type uri: string\n" "@param uri: URI to chmod\n" "@type mode: int\n" "@param mode: permissions to set\n" "@return: 0 on success, < 0 on error" }, { "getxattr", (PyCFunction) Context_getxattr, METH_VARARGS, "getxattr(uri, the_acl) -> int\n\n" "@type uri: string\n" "@param uri: URI to scan\n" "@type name: string\n" "@param name: the acl to get with the following syntax\n" "\n" " system.nt_sec_desc.\n" " system.nt_sec_desc.*\n" " system.nt_sec_desc.*+\n" " \n" " where is one of:\n" " \n" " revision\n" " owner\n" " owner+\n" " group\n" " group+\n" " acl:\n" " acl+:\n" " \n" " In the forms \"system.nt_sec_desc.*\" and\n" " \"system.nt_sec_desc.*+\", the asterisk and plus signs are\n" " literal, i.e. the string is provided exactly as shown, and\n" " the value parameter will return a complete security\n" " descriptor with name:value pairs separated by tabs,\n" " commas, or newlines (not spaces!).\n" "\n" " The plus sign ('+') indicates that SIDs should be mapped\n" " to names. Without the plus sign, SIDs are not mapped;\n" " rather they are simply converted to a string format.\n" "@return: a string representing the actual extended attributes of the uri" }, { "setxattr", (PyCFunction) Context_setxattr, METH_VARARGS, "setxattr(uri, the_acl) -> int\n\n" "@type uri: string\n" "@param uri: URI to modify\n" "@type name: string\n" "@param name: the acl to set with the following syntax\n" "\n" " system.nt_sec_desc.\n" " system.nt_sec_desc.*\n" " system.nt_sec_desc.*+\n" " \n" " where is one of:\n" " \n" " revision\n" " owner\n" " owner+\n" " group\n" " group+\n" " acl:\n" " acl+:\n" " \n" " In the forms \"system.nt_sec_desc.*\" and\n" " \"system.nt_sec_desc.*+\", the asterisk and plus signs are\n" " literal, i.e. the string is provided exactly as shown, and\n" " the value parameter will return a complete security\n" " descriptor with name:value pairs separated by tabs,\n" " commas, or newlines (not spaces!).\n" "\n" " The plus sign ('+') indicates that SIDs should be mapped\n" " to names. Without the plus sign, SIDs are not mapped;\n" " rather they are simply converted to a string format.\n" "@type string\n" "@param value - a string representing the acl\n" "@type int\n" "@param flags - XATTR_FLAG_CREATE or XATTR_FLAG_REPLACE\n" "@return: 0 on success" }, { NULL } /* Sentinel */ }; #if PY_MAJOR_VERSION >= 3 PyTypeObject smbc_ContextType = { PyVarObject_HEAD_INIT(NULL, 0) "smbc.Context", /*tp_name*/ sizeof(Context), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Context_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "SMBC context\n" "============\n\n" " A context for libsmbclient calls.\n\n" "Optional parameters are:\n\n" "auth_fn: a function for collecting authentication details from\n" "the user. This is called whenever authentication details are needed.\n" "The parameters it will be given are all strings: server, share,\n" "workgroup, username, and password (these last two can be ignored).\n" "The function should return a tuple of strings: workgroup, username,\n" "and password.\n\n" "debug: an integer representing the debug level to use.\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Context_methods, /* tp_methods */ 0, /* tp_members */ Context_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Context_init, /* tp_init */ 0, /* tp_alloc */ Context_new, /* tp_new */ }; #else PyTypeObject smbc_ContextType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "smbc.Context", /*tp_name*/ sizeof(Context), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Context_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "SMBC context\n" "============\n\n" " A context for libsmbclient calls.\n\n" "Optional parameters are:\n\n" "auth_fn: a function for collecting authentication details from\n" "the user. This is called whenever authentication details are needed.\n" "The parameters it will be given are all strings: server, share,\n" "workgroup, username, and password (these last two can be ignored).\n" "The function should return a tuple of strings: workgroup, username,\n" "and password.\n\n" "debug: an integer representing the debug level to use.\n" "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Context_methods, /* tp_methods */ 0, /* tp_members */ Context_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Context_init, /* tp_init */ 0, /* tp_alloc */ Context_new, /* tp_new */ }; #endif pysmbc-1.0.23/smbc/dir.c0000644000175000017500000002473513744321174015511 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008, 2011 Tim Waugh * Copyright (C) 2010 Patrick Geltinger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "smbcmodule.h" #include "context.h" #include "dir.h" #include "smbcdirent.h" typedef struct { PyObject_HEAD Context *context; SMBCFILE *dir; } Dir; ///////// // Dir // ///////// static PyObject * Dir_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Dir *self; self = (Dir *) type->tp_alloc (type, 0); if (self != NULL) self->dir = NULL; return (PyObject *) self; } static int Dir_init (Dir *self, PyObject *args, PyObject *kwds) { PyObject *ctxobj; Context *ctx; const char *uri; smbc_opendir_fn fn; SMBCFILE *dir; static char *kwlist[] = { "context", "uri", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "Os", kwlist, &ctxobj, &uri)) return -1; debugprintf ("-> Dir_init (%p, \"%s\")\n", ctxobj, uri); if (!PyObject_TypeCheck (ctxobj, &smbc_ContextType)) { PyErr_SetString (PyExc_TypeError, "Expected smbc.Context"); debugprintf ("<- Dir_init() EXCEPTION\n"); return -1; } Py_INCREF (ctxobj); ctx = (Context *) ctxobj; self->context = ctx; fn = smbc_getFunctionOpendir (ctx->context); errno = 0; dir = (*fn) (ctx->context, uri); if (dir == NULL) { pysmbc_SetFromErrno(); return -1; } self->dir = dir; debugprintf ("%p <- Dir_init() = 0\n", self->dir); return 0; } static void Dir_dealloc (Dir *self) { Context *ctx = self->context; smbc_closedir_fn fn; if (self->dir) { debugprintf ("%p closedir()\n", self->dir); fn = smbc_getFunctionClosedir (ctx->context); (*fn) (ctx->context, self->dir); } if (self->context) { Py_DECREF ((PyObject *) self->context); } Py_TYPE(self)->tp_free ((PyObject *) self); } static PyObject * Dir_getdents (Dir *self) { PyObject *result = NULL; PyObject *listobj = NULL; SMBCCTX *ctx; debugprintf ("-> Dir_getdents()\n"); ctx = self->context->context; do /*once*/ { listobj = PyList_New(0); if (PyErr_Occurred()) break; const smbc_getdents_fn fn_getdents = smbc_getFunctionGetdents(ctx); errno = 0; for (;;) { char dirbuf[1024]; int dirlen = fn_getdents(ctx, self->dir, (struct smbc_dirent *)dirbuf, sizeof dirbuf); struct smbc_dirent *dirp; if (dirlen <= 0) { if (dirlen < 0) { pysmbc_SetFromErrno(); debugprintf ("<- Dir_getdents() EXCEPTION\n"); } /*if*/ break; } /*if*/ debugprintf ("dirlen = %d\n", dirlen); dirp = (struct smbc_dirent *)dirbuf; for (;;) { PyObject *dent = NULL; PyObject *largs = NULL; PyObject *lkwlist = NULL; PyObject *name = NULL; PyObject *comment = NULL; PyObject *type = NULL; do /*once*/ { largs = Py_BuildValue("()"); if (PyErr_Occurred()) break; name = PyBytes_FromString(dirp->name); if (PyErr_Occurred()) break; comment = PyBytes_FromString(dirp->comment); if (PyErr_Occurred()) break; type = PyLong_FromLong(dirp->smbc_type); if (PyErr_Occurred()) break; lkwlist = PyDict_New(); if (PyErr_Occurred()) break; PyDict_SetItemString(lkwlist, "name", name); if (PyErr_Occurred()) break; PyDict_SetItemString(lkwlist, "comment", comment); if (PyErr_Occurred()) break; PyDict_SetItemString(lkwlist, "smbc_type", type); if (PyErr_Occurred()) break; dent = smbc_DirentType.tp_new(&smbc_DirentType, largs, lkwlist); if (PyErr_Occurred()) break; if (smbc_DirentType.tp_init(dent, largs, lkwlist) < 0) { PyErr_SetString(PyExc_RuntimeError, "Cannot initialize smbc_DirentType"); break; } /*if*/ PyList_Append(listobj, dent); if (PyErr_Occurred()) break; } while (false); Py_XDECREF(dent); Py_XDECREF(largs); Py_XDECREF(lkwlist); Py_XDECREF(name); Py_XDECREF(comment); Py_XDECREF(type); if (PyErr_Occurred()) break; const int len = dirp->dirlen; dirp = (struct smbc_dirent *)(((char *)dirp) + len); dirlen -= len; if (dirlen == 0) break; } /*for*/ if (PyErr_Occurred()) break; } /*for*/ if (PyErr_Occurred()) break; /* all done */ result = listobj; listobj = NULL; /* so I don't dispose of it yet */ debugprintf ("<- Dir_getdents() = list\n"); } while (false); Py_XDECREF(listobj); return result; } /*Dir_getdents*/ PyMethodDef Dir_methods[] = { { "getdents", (PyCFunction) Dir_getdents, METH_NOARGS, "getdents() -> list\n\n" "@return: a list of L{smbc.Dirent} objects" }, { NULL } /* Sentinel */ }; #if PY_MAJOR_VERSION >= 3 PyTypeObject smbc_DirType = { PyVarObject_HEAD_INIT(NULL, 0) "smbc.Dir", /*tp_name*/ sizeof(Dir), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Dir_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "SMBC Dir\n" "========\n\n" " A directory object." "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Dir_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Dir_init, /* tp_init */ 0, /* tp_alloc */ Dir_new, /* tp_new */ }; #else PyTypeObject smbc_DirType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "smbc.Dir", /*tp_name*/ sizeof(Dir), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Dir_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "SMBC Dir\n" "========\n\n" " A directory object." "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Dir_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Dir_init, /* tp_init */ 0, /* tp_alloc */ Dir_new, /* tp_new */ }; #endif pysmbc-1.0.23/smbc/context.h0000644000175000017500000000242313543345042016407 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008, 2010 Red Hat, Inc * Copyright (C) 2010 Open Source Solution Technology Corporation * Authors: * Tim Waugh * Tsukasa Hamano * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef HAVE_CONTEXT_H #define HAVE_CONTEXT_H extern PyMethodDef Context_methods[]; extern PyTypeObject smbc_ContextType; typedef struct { PyObject_HEAD SMBCCTX *context; PyObject *auth_fn; } Context; extern Context *current_context; #endif /* HAVE_CONTEXT_H */ pysmbc-1.0.23/smbc/smbcdirent.c0000644000175000017500000001744313744321744017066 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008, 2011, 2012 Tim Waugh * Copyright (C) 2010 Patrick Geltinger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "smbcmodule.h" #include "smbcdirent.h" typedef struct { PyObject_HEAD unsigned int smbc_type; char *comment; char *name; } Dirent; ///////// // Dir // ///////// static PyObject * Dirent_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { Dirent *self; debugprintf ("-> Dirent_new ()\n"); self = (Dirent *) type->tp_alloc (type, 0); if (self != NULL) { self->smbc_type = -1; self->comment = NULL; self->name = NULL; } debugprintf ("<- Dirent_new ()\n"); return (PyObject *) self; } static int Dirent_init (Dirent *self, PyObject *args, PyObject *kwds) { const char *name; Py_ssize_t name_len; const char *comment; Py_ssize_t comment_len; unsigned int smbc_type; static char *kwlist[] = { "name", "comment", "smbc_type", NULL }; debugprintf ("%p -> Dirent_init ()\n", self); if (!PyArg_ParseTupleAndKeywords (args, kwds, "s#s#i", kwlist, &name, &name_len, &comment, &comment_len, &smbc_type)) { debugprintf ("<- Dirent_init() EXCEPTION\n"); return -1; } self->name = strndup (name, name_len); self->comment = strndup (comment, comment_len); self->smbc_type = smbc_type; debugprintf ("%p <- Dirent_init()\n", self); return 0; } static void Dirent_dealloc (Dirent *self) { free (self->comment); free (self->name); Py_TYPE(self)->tp_free ((PyObject *) self); } static PyObject * Dirent_repr (PyObject *self) { static const char *types[] = { "?", "Workgroup", "Server", "File share", "Printer share", "Comms share", "IPC share", "Dir", "File", "Link", }; Dirent *dent = (Dirent *) self; #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat( "", dent->name, dent->smbc_type < (sizeof (types) / sizeof *(types)) ? types[dent->smbc_type] : "?", dent); #else char s[1024]; snprintf (s, sizeof (s), "", dent->name, dent->smbc_type < (sizeof (types) / sizeof *(types)) ? types[dent->smbc_type] : "?", dent); return PyBytes_FromStringAndSize (s, strlen (s)); #endif } static PyObject * Dirent_getName (Dirent *self, void *closure) { return PyUnicode_FromFormat("%s", self->name); } static PyObject * Dirent_getComment (Dirent *self, void *closure) { return PyUnicode_FromFormat("%s", self->comment); } static PyObject * Dirent_getSmbcType (Dirent *self, void *closure) { return PyLong_FromLong (self->smbc_type); } PyGetSetDef Dirent_getseters[] = { { "name", (getter) Dirent_getName, (setter) NULL, "name", NULL }, { "comment", (getter) Dirent_getComment, (setter) NULL, "comment", NULL }, { "smbc_type", (getter) Dirent_getSmbcType, (setter) NULL, "smbc_type", NULL }, { NULL } }; #if PY_MAJOR_VERSION >= 3 PyTypeObject smbc_DirentType = { PyVarObject_HEAD_INIT(NULL, 0) "smbc.Dirent", /*tp_name*/ sizeof(Dirent), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Dirent_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ Dirent_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "SMBC Dirent\n" "===========\n\n" " A directory entry object." "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ Dirent_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Dirent_init, /* tp_init */ 0, /* tp_alloc */ Dirent_new, /* tp_new */ }; #else PyTypeObject smbc_DirentType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "smbc.Dirent", /*tp_name*/ sizeof(Dirent), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)Dirent_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ Dirent_repr, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "SMBC Dirent\n" "===========\n\n" " A directory entry object." "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ Dirent_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)Dirent_init, /* tp_init */ 0, /* tp_alloc */ Dirent_new, /* tp_new */ }; #endif pysmbc-1.0.23/smbc/file.c0000644000175000017500000003154413744321212015637 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008, 2010, 2011, 2012 Red Hat, Inc * Copyright (C) 2010 Open Source Solution Technology Corporation * Copyright (C) 2010 Patrick Geltinger * Authors: * Tim Waugh * Tsukasa Hamano * Patrick Geltinger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "smbcmodule.h" #include "context.h" #include "file.h" ////////// // File // ////////// /* The size of off_t is potentionally unknown, so try to use the biggest integer type possible when coverting between ptyhon values and off_t. In order to communicate offset values between python objects and C types use off_t_long as the C type and OFF_T_FORMAT as the format character for Py_BuildValue, PyArg_Parse, and similar functions. */ #ifdef HAVE_LONG_LONG typedef PY_LONG_LONG off_t_long; #define OFF_T_FORMAT "L" #else typedef PY_LONG off_t_long; #define OFF_T_FORMAT "l" #endif static PyObject * File_new (PyTypeObject *type, PyObject *args, PyObject *kwds) { File *self; self = (File *) type->tp_alloc (type, 0); if (self != NULL) self->file = NULL; return (PyObject *) self; } static int File_init (File *self, PyObject *args, PyObject *kwds) { PyObject *ctxobj; Context *ctx; char *uri = NULL; int flags = 0; int mode = 0; smbc_open_fn fn; SMBCFILE *file; static char *kwlist[] = { "context", "uri", "flags", "mode", NULL }; if (!PyArg_ParseTupleAndKeywords (args, kwds, "O|sii", kwlist, &ctxobj, &uri, &flags, &mode)) return -1; debugprintf ("-> File_init (%p, \"%s\")\n", ctxobj, uri); if (!PyObject_TypeCheck (ctxobj, &smbc_ContextType)) { PyErr_SetString (PyExc_TypeError, "Expected smbc.Context"); debugprintf ("<- File_init() EXCEPTION\n"); return -1; } Py_INCREF (ctxobj); ctx = (Context *) ctxobj; self->context = ctx; if (uri) { fn = smbc_getFunctionOpen (ctx->context); file = (*fn) (ctx->context, uri, (int) flags, (mode_t) mode); if (file == NULL) { pysmbc_SetFromErrno(); Py_DECREF (ctxobj); return -1; } self->file = file; } debugprintf ("%p open()\n", self->file); debugprintf ("%p <- File_init() = 0\n", self->file); return 0; } static void File_dealloc (File *self) { Context *ctx = self->context; smbc_close_fn fn; if (self->file) { debugprintf ("%p close()\n", self->file); fn = smbc_getFunctionClose (ctx->context); (*fn) (ctx->context, self->file); } if (self->context) Py_DECREF ((PyObject *) self->context); Py_TYPE (self)->tp_free ((PyObject *) self); } static PyObject * File_read (File *self, PyObject *args) { Context *ctx = self->context; size_t size = 0; smbc_read_fn fn; char *buf; ssize_t len; PyObject *ret; smbc_fstat_fn fn_fstat; struct stat st; smbc_lseek_fn fn_lseek; int current = 0; if (!PyArg_ParseTuple (args, "|k", &size)) return NULL; fn = smbc_getFunctionRead (ctx->context); if (size == 0) { fn_fstat = smbc_getFunctionFstat (ctx->context); (*fn_fstat) (ctx->context, self->file, &st); fn_lseek = smbc_getFunctionLseek (ctx->context); current = (*fn_lseek) (ctx->context, self->file, 0, 1); size = st.st_size-current; } buf = (char *)malloc (size); if (!buf) return PyErr_NoMemory (); len = (*fn) (ctx->context, self->file, buf, size); if (len < 0) { pysmbc_SetFromErrno (); free (buf); return NULL; } ret = PyBytes_FromStringAndSize (buf, len); free (buf); return ret; } static PyObject * File_readinto (File *self, PyObject *args) { Context *ctx = self->context; smbc_read_fn fn; Py_buffer buf; ssize_t len; if (!PyArg_ParseTuple (args, "|s*", &buf)) return NULL; fn = smbc_getFunctionRead (ctx->context); len = (*fn) (ctx->context, self->file, buf.buf, buf.len); PyBuffer_Release(&buf); if (len < 0) { pysmbc_SetFromErrno (); return NULL; } return PyLong_FromLong (len); } static PyObject * File_write (File *self, PyObject *args) { Context *ctx = self->context; smbc_write_fn fn; Py_buffer buf; ssize_t len; if (!PyArg_ParseTuple (args, "s*", &buf)) return NULL; fn = smbc_getFunctionWrite (ctx->context); len = (*fn) (ctx->context, self->file, buf.buf, buf.len); PyBuffer_Release(&buf); if (len < 0) { pysmbc_SetFromErrno (); return NULL; } return PyLong_FromLong (len); } static PyObject * File_fstat (File *self, PyObject *args) { Context *ctx = self->context; smbc_fstat_fn fn; struct stat st; int ret; fn = smbc_getFunctionFstat (ctx->context); errno = 0; ret = (*fn) (ctx->context, self->file, &st); if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return Py_BuildValue ("(IKKKIIKIII)", st.st_mode, (unsigned long long)st.st_ino, (unsigned long long)st.st_dev, (unsigned long long)st.st_nlink, st.st_uid, st.st_gid, st.st_size, st.st_atime, st.st_mtime, st.st_ctime); } static PyObject * File_close (File *self, PyObject *args) { Context *ctx = self->context; smbc_close_fn fn; int ret = 0; fn = smbc_getFunctionClose (ctx->context); if (self->file) { ret = (*fn) (ctx->context, self->file); self->file = NULL; } return PyLong_FromLong (ret); } static PyObject * File_iter (PyObject *self) { Py_INCREF (self); return self; } static PyObject * File_iternext (PyObject *self) { File *file = (File *) self; Context *ctx = file->context; smbc_read_fn fn; char buf[2048]; ssize_t len; fn = smbc_getFunctionRead (ctx->context); len = (*fn) (ctx->context, file->file, buf, 2048); if (len > 0) return PyBytes_FromStringAndSize (buf, len); else if (len == 0) PyErr_SetNone (PyExc_StopIteration); else pysmbc_SetFromErrno (); return NULL; } static PyObject * File_lseek (File *self, PyObject *args) { Context *ctx = self->context; smbc_lseek_fn fn; off_t_long py_offset; off_t offset; int whence=0; off_t ret; if (!PyArg_ParseTuple (args, (OFF_T_FORMAT "|i"), &py_offset, &whence)) return NULL; offset = py_offset; /* check for data loss from cast */ if ((off_t_long)offset != py_offset) PyErr_SetString (PyExc_OverflowError, "Data loss in casting off_t"); fn = smbc_getFunctionLseek (ctx->context); ret = (*fn) (ctx->context, self->file, offset, whence); if (ret < 0) { pysmbc_SetFromErrno (); return NULL; } return Py_BuildValue (OFF_T_FORMAT, ret); } static PyObject * File_flush (PyObject *self) { return NULL; } static PyObject * File_tell (File *self) { PyObject *args = Py_BuildValue (OFF_T_FORMAT "i", 0, 1); return File_lseek (self, args); } static PyObject * File_seekable (File *self) { return Py_BuildValue("b", 1); } PyMethodDef File_methods[] = { {"read", (PyCFunction)File_read, METH_VARARGS, "read(size) -> string\n\n" "@type size: int\n" "@param size: size of reading\n" "@return: read data" }, {"readinto", (PyCFunction)File_readinto, METH_VARARGS, "readinto(b) -> int\n\n" "@type b: writable bytes-like object\n" "@param b: buffer to fill\n" "@return: number of bytes read" }, {"write", (PyCFunction)File_write, METH_VARARGS, "write(buf) -> int\n\n" "@type buf: string\n" "@param buf: write data\n" "@return: size of written" }, {"fstat", (PyCFunction)File_fstat, METH_NOARGS, "fstat() -> tuple\n\n" "@return: fstat information" }, {"close", (PyCFunction)File_close, METH_NOARGS, "close() -> int\n\n" "@return: on success, < 0 on error" }, {"lseek", (PyCFunction)File_lseek, METH_VARARGS, "lseek(offset, whence=0)\n\n" "@return: on success, current offset location, othwerwise -1" }, {"seek", (PyCFunction)File_lseek, METH_VARARGS, "seek(offset, whence=0)\n\n" "@return: on success, current offset location, othwerwise -1" }, {"flush", (PyCFunction)File_flush, METH_NOARGS, "flush()\n\n" "@return: NOP function" }, {"tell", (PyCFunction)File_tell, METH_NOARGS, "tell() -> int\n\n" "@return: on success, current location, othwerwise -1" }, {"seekable", (PyCFunction)File_seekable, METH_NOARGS, "seekable() -> bool\n\n" "@return: determine if seekable" }, { NULL } /* Sentinel */ }; #if PY_MAJOR_VERSION >= 3 PyTypeObject smbc_FileType = { PyVarObject_HEAD_INIT(NULL, 0) "smbc.File", /*tp_name*/ sizeof(File), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)File_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_reserved*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "SMBC File\n" "=========\n\n" " A file object." "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ File_iter, /* tp_iter */ File_iternext, /* tp_iternext */ File_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)File_init, /* tp_init */ 0, /* tp_alloc */ File_new, /* tp_new */ }; #else PyTypeObject smbc_FileType = { PyObject_HEAD_INIT(NULL) 0, /*ob_size*/ "smbc.File", /*tp_name*/ sizeof(File), /*tp_basicsize*/ 0, /*tp_itemsize*/ (destructor)File_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash */ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT, /*tp_flags*/ "SMBC File\n" "=========\n\n" " A file object." "", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ File_iter, /* tp_iter */ File_iternext, /* tp_iternext */ File_methods, /* tp_methods */ 0, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)File_init, /* tp_init */ 0, /* tp_alloc */ File_new, /* tp_new */ }; #endif pysmbc-1.0.23/smbc/smbcmodule.h0000644000175000017500000000420313744321462017056 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008, 2010 Red Hat, Inc * Copyright (C) 2010 Open Source Solution Technology Corporation * Authors: * Tim Waugh * Tsukasa Hamano * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef HAVE_SMBCMODULE_H #define HAVE_SMBCMODULE_H #define PY_SSIZE_T_CLEAN #include #include #include /* GCC attributes */ #if !defined(__GNUC__) || __GNUC__ < 2 || \ (__GNUC__ == 2 && __GNUC_MINOR__ < 5) || __STRICT_ANSI__ # define FORMAT(x) #else /* GNU C: */ # define FORMAT(x) __attribute__ ((__format__ x)) #endif extern void debugprintf (const char *fmt, ...) FORMAT ((__printf__, 1, 2)); extern void pysmbc_SetFromErrno(void); extern PyObject *NoEntryError; extern PyObject *PermissionError; extern PyObject *ExistsError; extern PyObject *NotEmptyError; extern PyObject *TimedOutError; #define SMBC_XATTR "system.nt_sec_desc." #define SMBC_XATTR_ALL SMBC_XATTR "*" #define SMBC_XATTR_ALL_SID SMBC_XATTR_ALL "+" #define SMBC_XATTR_REVISION SMBC_XATTR "revision" #define SMBC_XATTR_OWNER SMBC_XATTR "owner" #define SMBC_XATTR_OWNER_SID SMBC_XATTR_OWNER "+" #define SMBC_XATTR_GROUP SMBC_XATTR "group" #define SMBC_XATTR_GROUP_SID SMBC_XATTR_GROUP "+" #define SMBC_XATTR_ACL SMBC_XATTR "acl" #define SMBC_XATTR_ACL_SID SMBC_XATTR_ACL "+" #endif /* HAVE_SMBCMODULE_H */ pysmbc-1.0.23/smbc/dir.h0000644000175000017500000000176713543345042015513 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008 Tim Waugh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef HAVE_DIR_H #define HAVE_DIR_H extern PyMethodDef Dir_methods[]; extern PyTypeObject smbc_DirType; #endif /* HAVE_DIR_H */ pysmbc-1.0.23/smbc/smbcmodule.c0000644000175000017500000001562513744321125017057 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008, 2010 Red Hat, Inc * Copyright (C) 2010 Open Source Solution Technology Corporation * Copyright (C) 2010 Patrick Geltinger * Authors: * Tim Waugh * Tsukasa Hamano * Patrick Geltinger * Fabio Isgrò * Roberto Polli * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include #include "smbcmodule.h" #include "context.h" #include "dir.h" #include "file.h" #include "smbcdirent.h" static PyMethodDef SmbcMethods[] = { { NULL, NULL, 0, NULL } }; PyObject *NoEntryError; PyObject *PermissionError; PyObject *ExistsError; PyObject *NotEmptyError; PyObject *TimedOutError; PyObject *NoSpaceError; PyObject *NotDirectoryError; PyObject *ConnectionRefusedError; #if PY_MAJOR_VERSION >= 3 #define PYSMBC_INIT_ERROR NULL static struct PyModuleDef smbc_module = { PyModuleDef_HEAD_INIT, "_smbc", NULL, -1, SmbcMethods }; #define PYSMBC_PROTOTYPE_HEADER PyObject * PyInit__smbc (void) #define PYSMBC_MODULE_CREATOR PyModule_Create (&smbc_module) #else #define PYSMBC_INIT_ERROR #define PYSMBC_PROTOTYPE_HEADER void init_smbc (void) #define PYSMBC_MODULE_CREATOR Py_InitModule ("_smbc", SmbcMethods) #endif PYSMBC_PROTOTYPE_HEADER { PyObject *m = PYSMBC_MODULE_CREATOR; PyObject *d = PyModule_GetDict (m); // Context type if (PyType_Ready (&smbc_ContextType) < 0) return PYSMBC_INIT_ERROR; PyModule_AddObject (m, "Context", (PyObject *) &smbc_ContextType); // Dir type if (PyType_Ready (&smbc_DirType) < 0) return PYSMBC_INIT_ERROR; PyModule_AddObject (m, "Dir", (PyObject *) &smbc_DirType); // File type if (PyType_Ready (&smbc_FileType) < 0) return PYSMBC_INIT_ERROR; PyModule_AddObject (m, "File", (PyObject *) &smbc_FileType); // Dirent type if (PyType_Ready (&smbc_DirentType) < 0) return PYSMBC_INIT_ERROR; PyModule_AddObject (m, "Dirent", (PyObject *) &smbc_DirentType); // ACL string constants PyModule_AddStringConstant(m, "XATTR_ALL", SMBC_XATTR_ALL); PyModule_AddStringConstant(m, "XATTR_ALL_SID", SMBC_XATTR_ALL_SID); PyModule_AddStringConstant(m, "XATTR_GROUP", SMBC_XATTR_GROUP); PyModule_AddStringConstant(m, "XATTR_GROUP_SID", SMBC_XATTR_GROUP_SID); PyModule_AddStringConstant(m, "XATTR_OWNER", SMBC_XATTR_OWNER); PyModule_AddStringConstant(m, "XATTR_OWNER_SID", SMBC_XATTR_OWNER_SID); PyModule_AddStringConstant(m, "XATTR_ACL", SMBC_XATTR_ACL); PyModule_AddStringConstant(m, "XATTR_ACL_SID", SMBC_XATTR_ACL_SID); PyModule_AddStringConstant(m, "XATTR_REVISION", SMBC_XATTR_REVISION); #define INT_CONSTANT(prefix, name) \ do \ { \ PyObject *val = PyLong_FromLong (prefix##name); \ PyDict_SetItemString (d, #name, val); \ Py_DECREF (val); \ } while (0); INT_CONSTANT (SMBC_, WORKGROUP); INT_CONSTANT (SMBC_, SERVER); INT_CONSTANT (SMBC_, FILE_SHARE); INT_CONSTANT (SMBC_, PRINTER_SHARE); INT_CONSTANT (SMBC_, COMMS_SHARE); INT_CONSTANT (SMBC_, IPC_SHARE); INT_CONSTANT (SMBC_, DIR); INT_CONSTANT (SMBC_, FILE); INT_CONSTANT (SMBC_, LINK); INT_CONSTANT (SMB_CTX_, FLAG_USE_KERBEROS); INT_CONSTANT (SMB_CTX_, FLAG_FALLBACK_AFTER_KERBEROS); INT_CONSTANT (SMBCCTX_, FLAG_NO_AUTO_ANONYMOUS_LOGON); // define constants for ACL INT_CONSTANT (SMBC_, XATTR_FLAG_CREATE); INT_CONSTANT (SMBC_, XATTR_FLAG_REPLACE); // define exception objects PyObject *SmbError = PyErr_NewException("smbc.SmbError", PyExc_IOError, NULL); Py_INCREF(SmbError); PyModule_AddObject(m, "SmbError", SmbError); NoEntryError = PyErr_NewException("smbc.NoEntryError", SmbError, NULL); Py_INCREF(NoEntryError); PyModule_AddObject(m, "NoEntryError", NoEntryError); PermissionError = PyErr_NewException("smbc.PermissionError", SmbError, NULL); Py_INCREF(PermissionError); PyModule_AddObject(m, "PermissionError", PermissionError); ExistsError = PyErr_NewException("smbc.ExistsError", SmbError, NULL); Py_INCREF(ExistsError); PyModule_AddObject(m, "ExistsError", ExistsError); NotEmptyError = PyErr_NewException("smbc.NotEmptyError", SmbError, NULL); Py_INCREF(NotEmptyError); PyModule_AddObject(m, "NotEmptyError", NotEmptyError); TimedOutError = PyErr_NewException("smbc.TimedOutError", SmbError, NULL); Py_INCREF(TimedOutError); PyModule_AddObject(m, "TimedOutError", TimedOutError); NoSpaceError = PyErr_NewException("smbc.NoSpaceError", SmbError, NULL); Py_INCREF(NoSpaceError); PyModule_AddObject(m, "NoSpaceError", NoSpaceError); NotDirectoryError = PyErr_NewException("smbc.NotDirectoryError", SmbError, NULL); Py_INCREF(NotDirectoryError); PyModule_AddObject(m, "NotDirectoryError", NotDirectoryError); ConnectionRefusedError = PyErr_NewException("smbc.ConnectionRefusedError", SmbError, NULL); Py_INCREF(ConnectionRefusedError); PyModule_AddObject(m, "ConnectionRefusedError", ConnectionRefusedError); #if PY_MAJOR_VERSION >= 3 return m; #endif } void pysmbc_SetFromErrno() { switch(errno){ case EPERM: PyErr_SetFromErrno(PermissionError); break; case EEXIST: PyErr_SetFromErrno(ExistsError); break; case ENOTEMPTY: PyErr_SetFromErrno(NotEmptyError); break; case EACCES: PyErr_SetFromErrno(PermissionError); break; case ENOENT: PyErr_SetFromErrno(NoEntryError); break; case ETIMEDOUT: PyErr_SetFromErrno(TimedOutError); break; case ENOMEM: PyErr_SetFromErrno(PyExc_MemoryError); break; case ENOSPC: PyErr_SetFromErrno(NoSpaceError); break; case EINVAL: PyErr_SetFromErrno(PyExc_ValueError); break; case ENOTDIR: PyErr_SetFromErrno(NotDirectoryError); break; case ECONNREFUSED: PyErr_SetFromErrno(ConnectionRefusedError); break; default: PyErr_SetFromErrno(PyExc_RuntimeError); } return; } /////////////// // Debugging // /////////////// #define ENVAR "PYSMBC_DEBUG" static int debugging_enabled = -1; void debugprintf (const char *fmt, ...) { if (!debugging_enabled) return; if (debugging_enabled == -1) { if (!getenv (ENVAR)) { debugging_enabled = 0; return; } debugging_enabled = 1; } { va_list ap; va_start (ap, fmt); vfprintf (stderr, fmt, ap); va_end (ap); } } pysmbc-1.0.23/smbc/__init__.py0000644000175000017500000000005413543345042016661 0ustar hamanohamano00000000000000from smbc import xattr from _smbc import * pysmbc-1.0.23/smbc/smbcdirent.h0000644000175000017500000000202213543345042017050 0ustar hamanohamano00000000000000/* -*- Mode: C; c-file-style: "gnu" -*- * pysmbc - Python bindings for libsmbclient * Copyright (C) 2002, 2005, 2006, 2007, 2008 Tim Waugh * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef HAVE_SMBCDIRENT_H #define HAVE_SMBCDIRENT_H extern PyMethodDef Dirent_methods[]; extern PyTypeObject smbc_DirentType; #endif /* HAVE_SMBCDIRENT_H */ pysmbc-1.0.23/setup.py0000755000175000017500000001004713745432733015354 0ustar hamanohamano00000000000000#!/usr/bin/env python ## Copyright (C) 2002, 2005, 2006, 2007, 2008, 2010, 2011, 2012 Red Hat, Inc ## Copyright (C) 2010 Open Source Solution Technology Corporation ## Authors: ## Tim Waugh ## Tsukasa Hamano ## Laurent Coustet ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any later version. ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## You should have received a copy of the GNU General Public License ## along with this program; if not, write to the Free Software ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. """This is a set of Python bindings for the libsmbclient library from the samba project. >>> # Directory listing example: >>> import smbc >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> entries = ctx.opendir ("smb://SERVER").getdents () >>> for entry in entries: ... print entry >>> d = ctx.open ("smb://SERVER/music") >>> # Write file example: >>> import smbc >>> import os >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> file = ctx.open ("smb://SERVER/music/file.txt", os.O_CREAT | os.O_WRONLY) >>> file.write ("hello") >>> # Read file example: >>> import smbc >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> file = ctx.open ("smb://SERVER/music/file.txt") >>> print file.read() hello """ import subprocess from setuptools import setup, Extension def pkgconfig_I(pkg): dirs = [] c = subprocess.Popen(["pkg-config", "--cflags", pkg], stdout=subprocess.PIPE) (stdout, stderr) = c.communicate () for p in stdout.decode('ascii').split(): if p.startswith("-I"): dirs.append(p[2:]) return dirs def pkgconfig_L(pkg): dirs = [] c = subprocess.Popen(["pkg-config", "--libs", pkg], stdout=subprocess.PIPE) (stdout, stderr) = c.communicate () for p in stdout.decode('ascii').split(): if p.startswith("-L"): dirs.append(p[2:]) return dirs def pkgconfig_Dversion(pkg, prefix=None): if prefix is None: prefix = pkg.upper() + '_' c = subprocess.Popen(["pkg-config", "--modversion", pkg], stdout=subprocess.PIPE) (stdout, stderr) = c.communicate() vers = stdout.decode('ascii').rstrip().split('.') if len(vers) == 3: ver = str(int(vers[0]) * 10000 + int(vers[1]) * 100 + int(vers[2])) else: ver = str(int(vers[0])) return [(prefix + 'VERSION', ver)] setup( name="pysmbc", version="1.0.23", description="Python bindings for libsmbclient", long_description=__doc__, author=[ "Tim Waugh ", "Tsukasa Hamano ", "Roberto Polli ", ], url="https://github.com/hamano/pysmbc", license="GPLv2+", packages=["smbc"], classifiers=[ "Intended Audience :: Developers", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: GNU General Public License (GPL)", "Development Status :: 5 - Production/Stable", "Operating System :: Unix", "Programming Language :: C", ], ext_modules=[ Extension("_smbc", [ "smbc/smbcmodule.c", "smbc/context.c", "smbc/dir.c", "smbc/file.c", "smbc/smbcdirent.c" ], libraries=["smbclient"], library_dirs=pkgconfig_L("smbclient"), include_dirs=pkgconfig_I("smbclient"), define_macros=pkgconfig_Dversion("smbclient"), ) ], ) pysmbc-1.0.23/pysmbc.egg-info/0000755000175000017500000000000013745433040016614 5ustar hamanohamano00000000000000pysmbc-1.0.23/pysmbc.egg-info/dependency_links.txt0000644000175000017500000000000113745433040022662 0ustar hamanohamano00000000000000 pysmbc-1.0.23/pysmbc.egg-info/top_level.txt0000644000175000017500000000001313745433040021340 0ustar hamanohamano00000000000000_smbc smbc pysmbc-1.0.23/pysmbc.egg-info/PKG-INFO0000644000175000017500000000335313745433040017715 0ustar hamanohamano00000000000000Metadata-Version: 1.1 Name: pysmbc Version: 1.0.23 Summary: Python bindings for libsmbclient Home-page: https://github.com/hamano/pysmbc Author: ['Tim Waugh ', 'Tsukasa Hamano ', 'Roberto Polli '] Author-email: UNKNOWN License: GPLv2+ Description: This is a set of Python bindings for the libsmbclient library from the samba project. >>> # Directory listing example: >>> import smbc >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> entries = ctx.opendir ("smb://SERVER").getdents () >>> for entry in entries: ... print entry >>> d = ctx.open ("smb://SERVER/music") >>> # Write file example: >>> import smbc >>> import os >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> file = ctx.open ("smb://SERVER/music/file.txt", os.O_CREAT | os.O_WRONLY) >>> file.write ("hello") >>> # Read file example: >>> import smbc >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> file = ctx.open ("smb://SERVER/music/file.txt") >>> print file.read() hello Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: Unix Classifier: Programming Language :: C pysmbc-1.0.23/pysmbc.egg-info/SOURCES.txt0000644000175000017500000000063613745433040020505 0ustar hamanohamano00000000000000COPYING MANIFEST.in Makefile NEWS README.md setup.py test.py pysmbc.egg-info/PKG-INFO pysmbc.egg-info/SOURCES.txt pysmbc.egg-info/dependency_links.txt pysmbc.egg-info/top_level.txt smbc/__init__.py smbc/context.c smbc/context.h smbc/dir.c smbc/dir.h smbc/file.c smbc/file.h smbc/smbcdirent.c smbc/smbcdirent.h smbc/smbcmodule.c smbc/smbcmodule.h smbc/xattr.py tests/__init__.py tests/conftest.py tests/test_auth.pypysmbc-1.0.23/test.py0000644000175000017500000000040013741620551015151 0ustar hamanohamano00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import smbc def main(): ctx = smbc.Context() uri = 'smb://localhost' entries = ctx.opendir(uri).getdents() for d in entries: print(d) if __name__ == '__main__': main() pysmbc-1.0.23/PKG-INFO0000644000175000017500000000335313745433040014726 0ustar hamanohamano00000000000000Metadata-Version: 1.1 Name: pysmbc Version: 1.0.23 Summary: Python bindings for libsmbclient Home-page: https://github.com/hamano/pysmbc Author: ['Tim Waugh ', 'Tsukasa Hamano ', 'Roberto Polli '] Author-email: UNKNOWN License: GPLv2+ Description: This is a set of Python bindings for the libsmbclient library from the samba project. >>> # Directory listing example: >>> import smbc >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> entries = ctx.opendir ("smb://SERVER").getdents () >>> for entry in entries: ... print entry >>> d = ctx.open ("smb://SERVER/music") >>> # Write file example: >>> import smbc >>> import os >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> file = ctx.open ("smb://SERVER/music/file.txt", os.O_CREAT | os.O_WRONLY) >>> file.write ("hello") >>> # Read file example: >>> import smbc >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> file = ctx.open ("smb://SERVER/music/file.txt") >>> print file.read() hello Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: Unix Classifier: Programming Language :: C pysmbc-1.0.23/README.md0000644000175000017500000000452213660742036015113 0ustar hamanohamano00000000000000SMB bindings for Python ----------------------- [![PyPI](https://img.shields.io/pypi/v/pysmbc.svg)](https://pypi.python.org/pypi/pysmbc/) [![Build Status](https://travis-ci.org/hamano/pysmbc.svg?branch=master)](https://travis-ci.org/hamano/pysmbc) [![GitHub license](https://img.shields.io/github/license/hamano/pysmbc.svg)]() These Python bindings are intended to wrap the libsmbclient API. Prerequisites ------ Currently libsmbclient 3.2.x or later is required. Ubuntu Example: ~~~ # sudo apt install build-essential pkg-config smbclient libsmbclient libsmbclient-dev python-dev ~~~ Or `python3-dev` instead of `python-dev` depending on your needs. Build ------ ~~~ # make ~~~ Test ------ To run Python tests in tests/ you need python-nose See nose documentation http://readthedocs.org/docs/nose To run all the tests execute ~~~ # nosetests ~~~ To run just one test, use ~~~ # nosetests file.py ~~~ To selectively run test methods, printing output to console ~~~ # nosetests -vs test_context.py:test_Workgroup ~~~ NOTE: to run your tests, you need * a running samba server * one shared folder with * rw permissions * guest ok = no Examples ------ Directory listing ~~~ >>> import smbc >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> entries = ctx.opendir ("smb://SERVER").getdents () >>> for entry in entries: ... print entry >>> d = ctx.open ("smb://SERVER/music") ~~~ Shared Printer Listing ~~~ >>> import smbc >>> ctx = smbc.Context() >>> ctx.optionNoAutoAnonymousLogin = True >>> ctx.functionAuthData = lambda se, sh, w, u, p: (domain_name, domain_username, domain_password) >>> uri = 'smb://' + smb_server >>> shared_printers = [] >>> entries = ctx.opendir(uri).getdents() >>> for entry in entries: >>> if entry.smbc_type == 4: >>> shared_printers.append(entry.name) ~~~ Write file ~~~ >>> import smbc >>> import os >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> file = ctx.open ("smb://SERVER/music/file.txt", os.O_CREAT | os.O_WRONLY) >>> file.write ("hello") ~~~ Read file ~~~ >>> import smbc >>> ctx = smbc.Context (auth_fn=my_auth_callback_fn) >>> file = ctx.open ("smb://SERVER/music/file.txt") >>> print file.read() hello ~~~ pysmbc-1.0.23/NEWS0000644000175000017500000000432013660742172014330 0ustar hamanohamano00000000000000NEWS ---- New in 1.0.22: * Add File_seekable #52 * Rework some routines to fix holes in error checking and potential mem… #50 * Fix File_read when the current location is not zero #49 * Add File_flush #48 * Add File_tell #47 New in 1.0.21: * Fix protocol support #45 New in 1.0.19: * Added SAMBA protocol version optional variable #41 New in 1.0.18: * Support Fix memleak for auth_fn #32 * Support readinto #31 New in 1.0.17: * Support buffer protocol #30 * exceptions: use a shared superclass #28 * setup: autodetect required library dirs #27 New in 1.0.15.5: * fix NUL-termination bug New in 1.0.15.4: * added some constants New in 1.0.15.3: * added smbc.ConnectionRefusedError New in 1.0.15.1: * Return direntry with unicode string New in 1.0.15: * Working with Python3 New in 1.0.14.2: * added smbc.NotDirectoryError New in 1.0.14.1: * Fix for Python 2.6 New in 1.0.14: * Context.set_credentials_with_fallback() * Context.getxattr, Context.setxattr * smbc.XATTR, smbc.XATTR_ACL, smbc.XATTR_ACL_SID, smbc.XATTR_ALL, smbc.XATTR_ALL_SID, smbc.XATTR_FLAG_CREATE, smbc.XATTR_FLAG_REPLACE, smbc.XATTR_GROUP, smbc.XATTR_GROUP_SID, smbc.XATTR_OWNER, smbc.XATTR_OWNER_SID, smbc.XATTR_REVISION New in 1.0.12: * Context.optionUseKerberos * Context.optionFallbackAfterKerberos New in 1.0.11: * read/iternext now use Bytes type New in 1.0.10: * smbc.NoSpaceError * Now compiles against Python 3 New in 1.0.9: * iteration file read * rewrite tests for python nose * fixed stat portability issue * smbc.NoEntryError * smbc.ExistsError * smbc.NotEmptyError * smbc.TimedOutError * File.seek() and File.lseek() New in 1.0.8: * Context.chmod() * Context.rename() * Context.unlink() * Context.creat() New in 1.0.7: * Context.open: omissible flags and mode * File: omissible flags and mode * File.read() * smbc.PermissionError * Context.mkdir() * Context.stat() * File.fstat() * File.write() * File.close() New in 1.0.4: * Context.workgroup * Context.netbiosName New in 1.0.2: * Context.Debug -> Context.debug * Context.FunctionAuthData -> Context.functionAuthData * Context.OptionDebugToStderr -> Context.optionDebugToStderr * Context.OptionNoAutoAnonymousLogin -> Context.optionNoAutoAnonymousLogin New in 1.0.1: * Context.open() pysmbc-1.0.23/tests/0000755000175000017500000000000013745433040014767 5ustar hamanohamano00000000000000pysmbc-1.0.23/tests/conftest.py0000644000175000017500000000141313742175300017164 0ustar hamanohamano00000000000000import pytest def pytest_addoption(parser): parser.addoption('--server', action='store', default='localhost') parser.addoption('--share', action='store', default='share') parser.addoption('--username', action='store', default='user1') parser.addoption('--password', action='store', default='password1') @pytest.fixture(autouse=True, scope='session') def config(pytestconfig): server = pytestconfig.getoption('server') share = pytestconfig.getoption('share') username = pytestconfig.getoption('username') password = pytestconfig.getoption('password') uri = 'smb://{}/{}/'.format(server, share) yield { 'server': server, 'share': share, 'username': username, 'password': password, 'uri': uri, } pysmbc-1.0.23/tests/test_auth.py0000644000175000017500000000220213745305303017335 0ustar hamanohamano00000000000000import smbc def test_auth_succes(config): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True cb = lambda se, sh, w, u, p: (w, config['username'], config['password']) ctx.functionAuthData = cb d = ctx.opendir(config['uri']) assert d != None def test_auth_failed_noauth(config): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True try: ctx.opendir(config['uri']) except smbc.PermissionError: assert True else: assert False def test_auth_failed_nopass(config): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True cb = lambda se, sh, w, u, p: (w, config['username'], "") ctx.functionAuthData = cb try: ctx.opendir(config['uri']) except smbc.PermissionError: assert True else: assert False def test_auth_failed_nouser(config): ctx = smbc.Context() ctx.optionNoAutoAnonymousLogin = True cb = lambda se, sh, w, u, p: (w, "", config['password']) ctx.functionAuthData = cb try: ctx.opendir(config['uri']) except smbc.PermissionError: assert True else: assert False pysmbc-1.0.23/tests/__init__.py0000644000175000017500000000000013742173150017066 0ustar hamanohamano00000000000000pysmbc-1.0.23/MANIFEST.in0000644000175000017500000000036313543345042015365 0ustar hamanohamano00000000000000include MANIFEST.in include Makefile include COPYING include NEWS include README include TODO include tests/*.py include smbc/context.h include smbc/dir.h include smbc/file.h include smbc/smbcdirent.h include smbc/smbcmodule.h include test.py pysmbc-1.0.23/COPYING0000644000175000017500000004312713543345042014667 0ustar hamanohamano00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.