GithubHelp home page GithubHelp logo

libsmbclient-php's Introduction

libsmbclient-php: a PHP wrapper for libsmbclient

libsmbclient-php is a PHP extension that uses Samba's libsmbclient library to provide Samba related functions to PHP programs.

Getting started

Installation from PECL

pecl install smbclient

Binary package installation

Some distributions provide binary packages:

Installation from sources

  • Install the required libsmbclient header files, via package libsmbclient-dev (Debian/Ubuntu) or libsmbclient-devel (CentOS/Fedora/Red Hat).

  • Download a release tarball or check out the source code using git:

git clone git://github.com/eduardok/libsmbclient-php.git
  • phpize it:
cd libsmbclient-php ; phpize
  • Build the module
./configure
make
  • As root, install the module into the extensions directory:
sudo make install
  • Or for packaging purposes, install to a specific root directory:
make install INSTALL_ROOT=/tmp/smbc
  • Activate libsmbclient-php in php.ini:
extension="smbclient.so"

Contributions and bug reports

If you encounter a bug or want to contribute, please file an issue on GitHub. Sending pull requests on GitHub is the preferred method of contributing code.

License

Since version 0.7.0, libsmbclient-php is licensed under the BSD 2-clause license. See Issue #15 for background. The full license text can be found in the LICENSE file. Before that, libsmbclient-php was licensed under the PHP license, version 2.02.

PHP interface

URI's

URI's have the format smb://[[[workgroup;]user[:password@]]server[/share[/path[/file]]]]. They should be urlencoded to escape special characters. Use PHP's rawurlencode function to encode an URI. If you need to specify a workgroup, username or password, you can either include them in the URI, or specify them when you create a state resource. Examples of valid URI's:

smb://server
smb://server/share
smb://user:password@server/share/path/to/file.txt
smb://server/share/Moscow%20is%20written%20%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0.txt

Error handling

As a low-level extension, libsmbclient-php does not throw exceptions. Success or failure is communicated the old-fashioned way, by the function's return value. You should always check if a function returns false for failure. If you really want exceptions, you can build your own high-level layer by translating return values and error codes to appropriate exceptions.

For errors that occur in the Samba layer, the smbclient_ functions will generally print a human-readable PHP warning with an interpretation of what went wrong. The interpretations come from Samba's libsmbclient.h header file. You can suppress the warnings by prefixing the function call with an @. Please don't attempt to parse the warning messages, their wording is not very consistent and likely to change in future versions.

For some unlikely errors encountered by the extension itself, no warning is printed and the function just returns false.

When an error occurs, you can get the error number with smbclient_state_errno. For errors outside of Samba (such as wrong arguments to the function), its value will be 0, but for errors originating within Samba, it will be a Unix errno value straight from the underlying library. For example, smbclient_open may set the error code to 13, which corresponds with EACCES, which means that permission was denied. Please refer to Samba's libsmbclient.h for documentation on which error codes you can expect to see; each function has its own list of things that can go wrong.

For convenience, here's a non-exhaustive list of popular error codes:

name value description
EPERM 1 Operation not permitted
ENOENT 2 No such file or directory
EBADF 9 Bad file or directory resource
ENOMEM 12 Out of memory
EACCES 13 Permission denied
EBUSY 16 Device or resource busy
EEXIST 17 Resource exists
ENOTDIR 20 Not a directory
EISDIR 21 Is a directory
EINVAL 22 Invalid argument
ENOSPC 28 No space left on device
ENOTEMPTY 39 Directory not empty
ECONNREFUSED 111 Connection refused (Samba not running?)

smbclient_version

string smbclient_version ( )

Returns libsmbclient-php's own version string.

smbclient_library_version

string smbclient_library_version ( )

Returns libsmbclient's version string, which is the same as the Samba version string.

smbclient_state_new

resource smbclient_state_new ( )

Acquire a new smbclient state. Returns a state resource on success, or false on failure. The state resource holds persistent data about the current server connection, so that the backend can reuse the existing channel instead of reconnecting for every operation. The state resource must be passed on to most of the other functions in this extension. Before using the state resource in other functions, it must be initialized by calling smbclient_state_init. Between creating and initializing the resource, you can set certain options for the connection with smbclient_option_set. The state resource should be released when you're done with it by passing it to smbclient_state_free (although PHP will auto-destroy it when it goes out of scope).

smbclient_client_protocols

bool smbclient_client_protocols ( resource $state, string $min_protocol = null, string $max_protocol = null )

Sets the minimum and maximum protocols (client min protocol and client max protocol) for negotiation. Either can be set to null. Returns true on success, false on failure.

smbclient_option_set

bool smbclient_option_set ( resource $state, int option, mixed value )

Sets the value of an option to libsmbclient. Returns true if setting the option succeeded, false on failure. This function should be called before calling smbclient_state_init on your context. The second argument should be one of the constants below:

  • SMBCLIENT_OPT_OPEN_SHAREMODE

    The share mode to use when opening files. The value can be one of these constants:

    • SMBCLIENT_SHAREMODE_DENY_DOS
    • SMBCLIENT_SHAREMODE_DENY_ALL
    • SMBCLIENT_SHAREMODE_DENY_WRITE
    • SMBCLIENT_SHAREMODE_DENY_READ
    • SMBCLIENT_SHAREMODE_DENY_NONE
    • SMBCLIENT_SHAREMODE_DENY_FCB

    The default is SMBCLIENT_SHAREMODE_DENY_NONE.

  • SMBCLIENT_OPT_ENCRYPT_LEVEL

    The encryption level to adopt for the connection. The value can be one of these constants:

    • SMBCLIENT_ENCRYPTLEVEL_NONE
    • SMBCLIENT_ENCRYPTLEVEL_REQUEST
    • SMBCLIENT_ENCRYPTLEVEL_REQUIRE
  • SMBCLIENT_OPT_CASE_SENSITIVE

    Boolean. What to do when we can't determine from the file system attributes whether the file system is case sensitive. Assume that the filesystem is case sensitive (true), or that it isn't (false). Defaults to false, because only really old file systems aren't autodetected, and most of those are case insensitive.

  • SMBCLIENT_OPT_BROWSE_MAX_LMB_COUNT

    From how many servers to retrieve the list of workgroups, if you're doing that. See Samba's libsmbclient.h for details.

  • SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES

    Boolean. Whether the entries returned by smbclient_readdir are urlencoded. Defaults to false, the entries are returned "raw".

  • SMBCLIENT_OPT_USE_KERBEROS

    Boolean. Whether to use Kerberos authentication.

  • SMBCLIENT_OPT_FALLBACK_AFTER_KERBEROS

    Boolean. Whether to fall back on regular authentication if Kerberos didn't work out. The regular username and password given in smbclient_state_init will be queried.

  • SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN

    Boolean. Whether to automatically select anonymous login.

  • SMBCLIENT_OPT_USE_CCACHE

    Boolean. Whether to use the Winbind cache.

  • SMBCLIENT_OPT_USE_NT_HASH

    Boolean. Whether the password supplied in smbclient_state_init is actually an NT hash. If you set this to true and work with NT hashes, you can avoid passing around plaintext passwords.

    The smbc_getOptionUseNTHash function is relatively new to libsmbclient (June 2012), so the configure script tests whether your libsmbclient has that symbol, and conditionally activates this option. If the option is not available, trying to set it will return false.

  • SMBCLIENT_OPT_NETBIOS_NAME

    String. The NetBIOS (host) name used for making connections.

  • SMBCLIENT_OPT_WORKGROUP

    String. The workgroup used for making connections.

  • SMBCLIENT_OPT_USER

    String. The username used to make connections. This appears to be something different from the username given in smbclient_state_init, and appears to correspond to the system user running PHP.

  • SMBCLIENT_OPT_PORT

    Int. The TCP port to connect to. 0 means "use the default".

    The smbc_setPort function is relatively new to libsmbclient (April 2013), so the configure script tests whether your libsmbclient has that symbol, and conditionally activates this option. If the option is not available, trying to set it will return false.

  • SMBCLIENT_OPT_TIMEOUT

    Int. The timeout value for connections and responses in milliseconds.

smbclient_option_get

mixed smbclient_option_get ( resource $state, int option )

This is a mirror function of smbclient_option_set. Everything settable is also gettable. See that function for the description of the available options and their return types/values. If a given option is not available, this function will return null and not false, to distinguish it from an option's legitimate false value.

smbclient_state_init

int smbclient_state_init ( resource $state [, string $workgroup = null [, string $username = null [, string $password = null ] ] ] )

Initialize the smbclient state resource. Returns 0 on success, 1 on failure. Before using the state resource in other functions, it must be initialized. Workgroup, username and password are optional parameters. You can specify any of them as null or false to indicate that the credential is not available. Such might be the case for anonymous or guest access.

smbclient_state_free

bool smbclient_state_free ( resource $state )

Release the state resource passed to it. Returns true on success, false on failure.

smbclient_state_errno

int smbclient_state_errno ( resource $state )

Returns the error number of the last error encountered by libsmbclient. Returns 0 on failure (invalid resource) or if no error has yet occurred for this resource. The numbers returned are the standard Posix constants as returned by libsmbclient itself, so check your system's errno.h or man errno for documentation.

smbclient_opendir

resource smbclient_opendir ( resource $state, string $uri )

Opens the given directory for reading with smbclient_readdir.

Returns either a directory resource, or false on failure. The directory resource should be closed after use with smbclient_closedir.

smbclient_readdir

array smbclient_readdir ( resource $state, resource $dir )

Reads the next entry from the given directory resource obtained with smbclient_opendir. Call this in a while loop to read all entries in the directory.

Returns an array with details for the directory entry on success, or false on failure or end-of-file. The returned array has the following structure:

array(
  'type'    => 'type string',
  'comment' => 'comment string',
  'name'    => 'name string'
)

Comment and name are passed through from libsmbclient. By default, the name is not returned in urlencoded format, it's been decoded for convenience. You can toggle that by setting the SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES option to true. type is one of the following strings:

  • 'workgroup'
  • 'server'
  • 'file share'
  • 'printer share'
  • 'communication share'
  • 'IPC share'
  • 'directory'
  • 'file'
  • 'link'
  • 'unknown'

smbclient_closedir

bool smbclient_closedir ( resource $state, resource $dir )

Closes a directory resource obtained with smbclient_opendir. Returns true on success, false on failure.

smbclient_rename

bool smbclient_rename ( resource $state_old, string $uri_old, resource $state_new, string $uri_new )

Renames the old file/directory to the new file/directory. $state_old and $state_new refer to the states belonging to the old and new URI's. Due to a limitation of the underlying library, old and new locations must be on the same share. Due to the same limitation, $state_old and $state_new should point to the same resource. Returns true on success, false on failure.

smbclient_unlink

bool smbclient_unlink ( resource $state, string $uri )

Unlinks (deletes) the file. Does not work on directories; to delete those, use smbclient_rmdir. Returns true on success, false on failure.

smbclient_mkdir

bool smbclient_mkdir ( resource $state, string $uri [, int $mask = 0777 ] )

Creates the given directory. If $mask is given, use that as the creation mask (after subtracting the umask). Support for $mask may be absent; libsmbclient notes in its header file that umasks are not supported by SMB servers. Returns true on success, false on failure.

smbclient_rmdir

bool smbclient_rmdir ( resource $state, string $uri )

Deletes the given directory if empty. Returns true on success, false on failure.

smbclient_stat

array smbclient_stat ( resource $state, string $uri )

Returns information about the given file or directory. Returns an array with information on success, false on failure. The structure of the return array is the same as PHP's native stat. See that manual for a complete description.

smbclient_fstat

array smbclient_fstat ( resource $state, resource $file )

Returns information about the given file or directory. Returns an array with information on success, false on failure. The structure of the return array is the same as PHP's native stat. See that manual for a complete description.

smbclient_open

resource smbclient_open ( resource $state, string $uri, string $mode [, int $mask = 0666 ] )

Opens a file for reading or writing according to the $mode specified. Applies the creation mask in $mask (after subtracting the umask) if the file had to be created. Support for $mask may be absent; libsmbclient notes in its header file that umasks are not supported by SMB servers.

$mode is in the same format as the $mode argument in PHP's native fopen. See that manual for more information. Summary:

value description
'r' open read-only, place file pointer at start of file.
'r+' open read-write, place file pointer at start of file.
'w' open write-only, place file pointer at start of file; create file if not exists.
'w+' as above, but open read-write.
'a' open write-only, place file pointer at end of file; create file if not exists.
'a+' as above, but open read-write.
'x' exclusive open for write only; create file only if it doesn't already exist, else return error.
'x+' as above, but open read-write.
'c' open write-only, create if not exists; if it already exists, don't return error. Do not truncate, but place file pointer at start of file.
'c+' as above, but open read-write.

Returns a file resource on success, or false on failure.

smbclient_creat

resource smbclient_creat ( resource $state, string $uri [, int $mask = 0666 ] )

Almost the same as calling smbclient_open with mode 'c', but will truncate the file to 0 bytes if it already exists. Opens the file write-only and creates it if it doesn't already exist.

Returns a file resource on success, or false on failure.

smbclient_read

string smbclient_read ( resource $state, resource $file, int $bytes )

Reads data from a file resource obtained through smbclient_open or smbclient_creat. Tries to read the amount of bytes given in $bytes, but may return less. Returns a string longer than 0 bytes on success, a string of 0 bytes on end-of-file, or false on failure.

Checking the string length to figure out EOF is primitive, but libsmbclient does not expose an feof equivalent. strlen in PHP is relatively efficient because PHP tracks string lengths internally.

smbclient_write

int smbclient_write ( resource $state, resource $file, string $data [, int $length ] )

Writes data to a file resource obtained through smbclient_open or smbclient_creat. If $length is not specified, write the whole contents of $data. If $length is specified, write either the whole content of $data or $length bytes, whichever is less. $length, if specified, must be larger than 0. If you want to write zero bytes for some reason, write the empty string and omit $length.

Returns the number of bytes written on success, or false on failure.

smbclient_lseek

int smbclient_lseek ( resource $state, resource $file, int offset, int whence )

Places the internal file pointer at the given byte offset. The whence parameter indicates from where to count. It can take three possible constants, which are the same as for PHP's native fseek:

  • SEEK_SET: set position equal to offset bytes;
  • SEEK_CUR: set position to current location plus offset;
  • SEEK_END: set position to end of file plus offset.

Returns the new file offset as measured from the start of the file on success, false on failure.

smbclient_ftruncate

bool smbclient_ftruncate ( resource $state, resource $file, int size )

Truncates the given file to the given file size. Returns true on success, false on failure.

smbclient_close

bool smbclient_close ( resource $state, resource $file )

Close a file resource obtained with smbclient_open or smbclient_creat. Returns true on success, false on failure.

smbclient_chmod

bool smbclient_chmod ( resource $state, string $uri, int mode )

Set the DOS attributes for a file. According to the libsmbclient header file, this function is not implemented. However, the Samba sources do seem to implement it, and use the following mapping:

Permission description
Not u+w, g+w or o+w File is read-only
u+x File is archived
g+x File is system
o+x File is hidden

So to set a file to readable and hidden, you would use o+wx, or mode 003. This function is a Posix compatibility shim; if you want better control over file attributes, use the more powerful xattr functions.

smbclient_utimes

bool smbclient_utimes ( resource $state, string $uri [, int $mtime = time() [, int $atime = $mtime ] ] )

Set the write time and access time for the given file or directory. These correspond to Unix mtime and atime. Timestamps are in Unix timestamp format. Returns true on success, false on failure.

Beware of inconsistencies in how Samba stores and retrieves timestamps. When you change the mtime and atime for a file, then stat the file with smbclient_stat, the stat output will indicate that you changed ctime and mtime, in that order, instead. (This is likely a bug somewhere, but it's hard to pinpoint the cause.) When you use mount.cifs to mount the share and check the results of this function with the stat commandline tool, the mtime argument will set both the mtime and ctime, and the atime argument will set the atime. This is a Posix compatibility shim. Use the more powerful xattr functions if you need more control, such as setting the ctime.

smbclient_listxattr

array smbclient_listxattr ( resource $state, string $uri )

This function should, according to Samba documentation, return a list of all names of extended attributes applicable to the given file or directory. Instead, the function returns an array of the names of all extended attributes known to Samba, regardless of what the filesystem actually supports or which attributes are actually available on the resource. Since the underlying function always returns a static string without looking, don't take the output as gospel. It does provide you with a list of attribute names that you can use to fetch individually. Returns false on failure.

smbclient_getxattr

string smbclient_getxattr ( resource $state, string $uri, string $key )

Returns the value of the given extended attribute with name $key, or false on failure. The value returned is always a string.

For example, to get a file's extended attributes, query the system.dos_attr.mode key.

smbclient_setxattr

bool smbclient_setxattr ( resource $state, string $uri, string $key, string $value [, int flags = 0 ] )

Sets the extended attribute with name $key to value $value. For now, see libsmbclient.h, the section on smbc_setxattr, for details on how to specify keys and values. flags defaults to zero, meaning that the attribute will be created if it does not exist, and replaced if it already exists. You can also set flags to one of these values:

Constant description
SMBCLIENT_XATTR_CREATE Only create the attribute: fail with EEXIST if it already exists
SMBCLIENT_XATTR_REPLACE Only replace the attribute: fail with ENOATTR if it does not exist

Returns true on success, false on failure.

smbclient_removexattr

bool smbclient_removexattr ( resource $state, string $uri, string $key )

Removes the extended attribute with name $key from the file or directory pointed to by the URI. Returns true on success, false on failure.

smbclient_statvfs

array smbclient_statvfs ( resource $state, string $uri )

Returns an array with file system statistics for the given URI, or false on failure. The array contains the keys listed below, each with an integer value. See the manpage for the Unix statvfs function for more information on how to interpret the values.

  • bsize: file system block size;
  • frsize: fragment size;
  • blocks: size of filesystem in frsize units;
  • bfree: number of free blocks;
  • bavail: number of free blocks for unprivileged users;
  • files: number of inodes;
  • ffree: number of free inodes;
  • favail: number of free inodes for unprivileged users;
  • fsid: file system ID;
  • flag: mount flags;
  • namemax: maximum filename length.

The flag value can contain a boolean OR of the following constants:

  • SMBCLIENT_VFS_RDONLY;
  • SMBCLIENT_VFS_DFS;
  • SMBCLIENT_VFS_CASE_INSENSITIVE;
  • SMBCLIENT_VFS_NO_UNIXCIFS;

smbclient_fstatvfs

array smbclient_fstatvfs ( resource $state, resource $file_or_dir )

Returns an array with file system statistics for the given file or directory resource, or false on failure. See smbclient_statvfs for a description of the returned array.

streams support

Starting with version 0.8.0, streams support is enabled. Most of standard functions work transparently with 'smb' URIs.

  readfile('smb://user:password@smbserver/share/file.txt');
  scandir('smb://user:password@smbserver/share/somedir/');

Which include: copy, file_get_contents, file_put_contents, fileperms, fopen, mkdir, opendir, rmdir, rename, stat, unlink... Notice: touch and chmod functions require PHP >= 5.4

Examples

Some bare-bones examples of how to use libsmbclient-php. These have deliberately been kept simple. In production, you should at least check whether the extension has been loaded. Also, you should urlencode your URI's, check the return value of each function, and handle errors appropriately.

List the contents of a directory:

<?php

// Create new state:
$state = smbclient_state_new();

// Initialize the state with workgroup, username and password:
smbclient_state_init($state, null, 'testuser', 'password');

// Open a directory:
$dir = smbclient_opendir($state, 'smb://localhost/testshare');

// Loop over the directory contents, print each node:
while (($entry = smbclient_readdir($state, $dir)) !== false) {
	echo "{$entry['name']} : {$entry['type']}\n";
}
// Close the directory handle:
smbclient_closedir($state, $dir);

// Free the state:
smbclient_state_free($state);

Dump a file to standard output:

<?php

// Create new state:
$state = smbclient_state_new();

// Initialize the state with workgroup, username and password:
smbclient_state_init($state, null, 'testuser', 'password');

// Open a file for reading:
$file = smbclient_open($state, 'smb://localhost/testshare/testdir/testfile.txt', 'r');

// Read the file incrementally, dump contents to output:
while (true) {
	$data = smbclient_read($state, $file, 100000);
	if ($data === false || strlen($data) === 0) {
		break;
	}
	echo $data;
}
// Close the file handle:
smbclient_close($state, $file);

// Free the state:
smbclient_state_free($state);

libsmbclient-php's People

Contributors

aklomp avatar crrodriguez avatar eduardok avatar eduardokvb avatar mario-kr avatar matthewg avatar peterg98 avatar remicollet avatar sunpoet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

libsmbclient-php's Issues

DFS connections remain open leading to eventual system crash

When connecting to a standard Windows/SAMBA file server, calling smbclient_state_free ensures that the connection is closed. Since smbc_free_context is called in the module's destructor we can even get away with not calling it. However, when the connection is to a DFS target said connection remains open even after the script completes.

After connecting to a DFS target, running lsof | grep microsoft on the server yields four open microsoft-ds connections per request. This can cause serious issues because eventually the system will reach it's open files limit and crash.

The only way to close the connections is to restart Apache and this issue can be worked around by setting MaxRequestsPerChild in httpd.conf to something very low (say fifteen) but from a performance standpoint this is less than ideal.

It seems that the connections live as long as PHP does so this issue does not occur when running a script from the command line.

I think that in the case of DFS we need to be doing something more than calling smbc_free_context. Looking through http://fossies.org/linux/misc/samba-4.0.25.tar.gz/samba-4.0.25/source3/libsmb/clientgen.c there is a cli_shutdown function which talks about connections remaining active even when smbc_free_context is called but I'm not sure if this is relevant here.

smbclient-php IRC channel

If you guys use IRC, please join me on freenode's #smbclient-php
I suppose we can pick another channel name if you guys prefer.

configure: error: Could not find libsmbclient.h

When trying to install i got:
configure: error: Could not find libsmbclient.h

some day's earlier, it worked fine, something changed?

wanted to reinstall because php had trouble loding it:
PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20131226/smbclient.so' - /usr/lib/php5/20131226/smbclient.so: undefined symbol: zend_list_close in Unknown on line 0

it seems the libsmbclient-php is dependend on php7 stuff
i found a debian package: https://packages.debian.org/stretch/php-smbclient

but it only installs it in the php7 folders
when i copy it to the php5 folders it won't load it.
how can i get php5 to also load the version 7 externtions?

Add libsmbclient's print-related functions

Libsmbclient has various functions for printing to print shares, getting print queues and so on. We should add them, because it's easy to do so within the framework that we have and because it's the last large bit of upstream functionality we don't expose.

Issue with -ldl on a FreeBSD system

I just had to install libsmbclient-php on a FreeBSD system (to be correct, on a Jail on a FreeNAS system).
The problem is, on FreeBSD, there is no such library. So the test for smbc_open will fail due to this.
Error message : configure: error: Could not find libsmbclient.so or symbol smbc_open. Check config.log for more information.

The solution to this problem is pretty simple, just remove -ldl in this part of the configure file (generated after the "phpize" command) :

save_old_LDFLAGS=$LDFLAGS
ac_stuff="
-lsmbclient -lm -ldl
"

And now, the ./configure should be ok

Is there a way to force php smbclient to use SMv2.0

Our organization has disabled SMB 1.0 due to vulnarebilities. However, for some reason owncloud wont connect to the shares if SMBv1 is disabled.
Is there a way to force php smbclient to use SMv2.0?

I have already changed the smb.conf file to look like:

    max open files = 32808
    server string = %h univention corporate server
    ntlm auth       = yes
    machine password timeout        = 0
    acl allow execute always = True
    min protocol = SMB2
    max protocol = SMB3
    client ipc min protocol = SMB2
    client ipc max protocol = SMB3

Please help as I cannot keep the SMBv1 enabled for long.

make DESTDIR ignored

Current when trying to do:

make DESTDIR=/home/pmjdebruijn/test install

The process fails trying install to my rootfs, where the it has no permissions as non-root.

Would it be possible to honour DESTDIR as this is beneficial to unpriviledged package builds.

Inconsistent workgroup behavior between stream wrapper and smb_state_init

The smb:// builtin stream wrapper and smb_state_init seem to behave differently when setting an empty workgroup.

var_dump(scandir('smb://test:test@localhost/test'));

$state = smbclient_state_new();
smbclient_option_set($state, SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN, false);
var_dump(smbclient_state_init($state, null, 'test', 'test'));

$dir = smbclient_opendir($state, 'smb://localhost/test');
var_dump($dir);
var_dump(smbclient_state_errno($state));

The top line prints the expected folder content, while the bottom part fails with 'Workgroup no found' (same error when passing false or '' as workgroup, setting a non empty string makes things work as expected)

Since no workgroup is passed to the stream wrapper I would expect it to fail in the same way as the smb_state_ functions

Strange behavior with smbclient_getxattr

We have one Ubuntu Server 16.04 with php 7.3, smbclient 4.3.11 and php-smbclient 1.0.0 and an other server with Ubuntu Server 18.04 with php 7.4., smbclient v4.10.15 and php-smbclient v1.0.0.

There is also an debian 10.3 with Samba 4.9.5, php-smbclient 0.9.0 where the mode returns 0x10.

On the 16.04 system smbclient_getxattr returns for a directory the mode 0x10 on the 18.04 system it returns for a directory the mode 0x41ed.

The mode is read with this code:
smbclient_getxattr($state, $uri, 'system.dos_attr.*');

My code to read the mode is:

<?php
$workgroup ='your workgroup or domain';
$user           ='your user';
$pwd           = 'your secret password';
$uri             = 'smb://your.server.local/share';
// Create new state:
$state = smbclient_state_new();
// Initialize the state with workgroup, username and password:
smbclient_state_init($state, $workgroup, $user, $pwd);

$attr = @smbclient_getxattr($state, $uri, 'system.dos_attr.*');
var_dump($attr);

I don't understand where the 0x41ed comes from.
I've also checked your source and the source from samba but didn't find anything.
I think this problem is related to an smb configuration, but don't know which it can be?
Maybe you can point me to the right direction or solve my problem?

OS X 10.12 Build

Can't see what I'm doing wrong. Tried to follow the advice given in #36 but to no avail.

cc ${wl}-flat_namespace ${wl}-undefined ${wl}suppress -o .libs/smbclient.so -bundle .libs/smbclient.o .libs/smb_streams.o -L/usr/local/Cellar/samba/3.6.25//lib -lsmbclient -Wl,-rpath -Wl,/usr/local/Cellar/samba/3.6.25//lib duplicate symbol _php_stream_smb_wrapper in: .libs/smbclient.o .libs/smb_streams.o ld: 1 duplicate symbol for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) make: *** [smbclient.la] Error 1

I've tried 0.8 and 0.9, same issue. Any ideas? Thanks!

Broken build with samba 4.7

checking whether to enable smbclient support... yes, shared
checking for libsmbclient support... yes, shared
checking for libsmbclient.h in default paths... found in /usr/include/samba-4.0
checking for smbc_getOptionUserData in -lsmbclient... no
configure: error: Could not find libsmbclient.so or symbol smbc_getOptionUserData. Check version and config.log for more information.

Will try to investigate for a fix ASAP

Create release 0.6.0

Many functions have been added since the release of 0.5.0, along with unit tests which all pass. My work queue is empty and I consider this project to be at a stable point, so how about a new release?

Support for PHP 7.4?

Just installed this with PHP 7.4 and it seems to work, but is it actually supported?

Thanks!

Add support for smbclient_notify

The smbclient notify command allows clients to get notified whenever a file or folder is changed on the server.

From what I can tell this functionality is exposed as smbc_setFunctionNotify in libsmbclient in newer versions of smbclient

How to get file owner (SID)

Is it possible to get the file owner - either as a SID or string.

If so, how ?

If not, is this something that can be added ?

If I do var_dump(fileowner('smb://fileserver/share/file1.txt'));
then I just get "int(0)" as output - presume that is to tell me that "root" user owns the file, but this is not correct... I need the Windows/AD user...

Thanks in advance !

Current PHP License not suitable for anything else but PHP

Hi,

The old (pre 3.x) version of PHP License this source code is using, is not really usable for anything else than PHP itself. Basically this license talks only about PHP, the PHP Group, and includes Zend Engine, so its not applicable to anything else.

Ref: https://ftp-master.debian.org/REJECT-FAQ.html

It would be nice to change the license to something like LGPL or BSD that would properly achieve the freeness of the code as you see fit.

Installing on virtualbox ubuntu

Hi Guys,

I've just installed a virtualbox ubuntu vm to test the libsmbclient.. I followed the installation instructions, but on the ./configure command, i receive the following error:

checking for libsmbclient.h in default paths... not found
configure: error: Could not find libsmbclient.h

Does anyone know how to fix this?

Thanks!

File creation date

HI,

Is it also possible to display file or folder creation date? Using stat of fstat is not returning that information..

Thanks!

lseek with SEEK_CUR unexpectedly generates huge sparse files

Found this while writing testcases. This innocent-looking script will generate a 4.1GB sparse file on my machine:

<?php

// Open a file, write something:
$state = smbclient_state_new();
smbclient_state_init($state, null, 'testuser', 'password');
$file = smbclient_creat($state, 'smb://localhost/testshare/lseektest.txt');
smbclient_write($state, $file, 'abcdefgh');

// Seek 3 characters onwards:
smbclient_lseek($state, $file, 3, SEEK_CUR);

// Write some more, close the file:
smbclient_write($state, $file, 'foo', 3);
smbclient_close($state, $file);
smbclient_state_free($state);

Expected outcome: a file of 14 bytes in size: the characters 'abcdefgh', three zero bytes, and 'foo'.

I tried unsuccessfully to reproduce this behaviour with an equivalent c program, which leads me to conclude that this is a bug in libsmbclient-php somewhere.

#include <string.h>
#include <libsmbclient.h>

static void
smbclient_auth_func (SMBCCTX *ctx, const char *server, const char *share, char *wrkg, int wrkglen, char *user, int userlen, char *pass, int passlen)
{
    strcpy(wrkg, "");
    strcpy(user, "testuser");
    strcpy(pass, "password");
}

int main ()
{
    char *uri = "smb://localhost/testshare/lseektest.txt";
    SMBCCTX *ctx = smbc_new_context();
    smbc_setFunctionAuthDataWithContext(ctx, smbclient_auth_func);
    smbc_init_context(ctx);

    SMBCFILE *file = smbc_getFunctionCreat(ctx)(ctx, uri, 0666);
    smbc_getFunctionWrite(ctx)(ctx, file, "abcdefgh", 8);

    smbc_getFunctionLseek(ctx)(ctx, file, 3, SEEK_CUR);

    smbc_getFunctionWrite(ctx)(ctx, file, "foo", 3);
    smbc_getFunctionClose(ctx)(ctx, file);
    smbc_free_context(ctx, 1);
}

Makefile:

test: test.c
    $(CC) -lsmbclient -I/usr/include/samba-4.0 -o $@ $^

The c program outputs a file 11 bytes in size, containing the string 'abcdefghfoo'. Better, but also not what I expected.

More weirdness: in the PHP version, the lseek call returns '3'. In the c version, the lseek call returns '8'. Neither is correct from the documentation's point of view, since the return value should be the current absolute offset into the file (that is, '11').

No releases tagged or downloadable

libsmbclient-php has been released as versions 0.1, 0.2 and 0.3, but none of the releases have been tagged as such, or turned into downloadable release tarballs. For the benefit of end users, it would be preferable to tag each version and create a release tarball.

The advantage is that the install process can be made much easier by saying "download the latest tarball from github" instead of "git clone the code locally, git checkout commit 76ab345b43, run git archive..."

Cannot dump all content of file to localfile

Hello,

I'm trying to copy files from a SMB share to a Linux host.
It is working so far verry good.

Code:
# Open file on server
$file = smbclient_open($state, 'smb://'.$remotePath."/".$smb[$i+2], 'r');
while (true) {
$data = smbclient_read($state, $file, 100000);
if ($data === false || strlen($data) === 0) {
break;
}
#write content to local file
file_put_contents($folder.$vendor."/".$invoicenrpath."/".$smb[$i+2], $data);
}

My problem is when the file is big ( I think more than the 100000 bytes) the file is not fully streamed to the local file.

is there an other way to copy a file from SMB share to local linux host?

Best regards
Tobias

Workgroup required for SMB2 connections

Checked with unreleased samba 4.8.0 (compiled from samba-team/samba@20fe434) and libsmbclient-php 0.9.0 (also compiled against the above)

The test script matches the one shown in the example of this repository, adjusted to connect to the target server.

PHP Warning:  Couldn't open SMB directory smb://10.0.2.8/opt: Permission denied in /opt/test.php on line 11

Filling the workgroup with any random value solves the problem, as long as the server supports it

@eduardok @aklomp (sorry if I pinged the wrong people)

Apache segfault DFSR share

I've been having an issue with some of the files on a smb dfsr share. Can't quite narrow it down but it doesn't seem to be a permission issue, I can access the file fine in windows

I used the Dump a file to standard output to test this:

[Fri Apr 05 08:25:24.096494 2019] [core:notice] [pid 28400] AH00051: child pid 28976 exit signal Segmentation fault (11), possible coredump in /etc/apache2

I don't really know how to get more info on why it's happening.
Thanks

php-smbclient:
Installed: 0.8.0rc1-2build1
Candidate: 0.8.0
rc1-2build1
Version table:
*** 0.8.0rc1-2build1 500
500 http://au.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages
100 /var/lib/dpkg/status
0.8.0
rc1-2 500
500 http://au.archive.ubuntu.com/ubuntu xenial/universe amd64 Packages

configure ignores --with-libdir

I am compiling on FreeBSD 10.2-RELEASE. I've installed the samba-libsmbclient port, (which is based on samba 3.6, but whatever).

I am running:
./configure --prefix=/usr/local --with-libdir=/usr/local/lib
or
./configure --prefix=/usr/local

In both cases, configure dies with this error:
configure:4427: cc -o conftest -g -O2 -lsmbclient conftest.c -lsmbclient >&5 /usr/bin/ld: cannot find -lsmbclient

I set the environment variable LDFLAGS=-L/usr/local/lib and then I see
configure:6283: cc -o conftest -g -O2 -L/usr/local/lib conftest.c conftstm.o >&5

and configure works correctly. Seems like the configure script isn't really processing many of the args it says it does.

smbclient_state_free leads to segfault

I'd been working on context support but noticed that it's been added anyway which is great. However freeing the context seems to occasionally cause a segfault the next time that smbclient_opendir is called.

Example script:-

$state = smbclient_state_new();
smbclient_state_init($state, 'WORKGROUP', 'username', 'password');
$dir = smbclient_opendir($state, $url);
smbclient_closedir($state, $dir);
smbclient_state_free($state);

The first three or four requests are fine, after that it begins seemingly randomly segfaulting. Removing any mention of smbc_free_context from libsmbclient.c prevents the issue from happening but obviously isn't ideal because connections are then left open.

I'm testing this with PHP 5.5 on Apache Prefork.

Let me know if you need any more information.

Download file

Hi,

How can i download a file? I am able to list the contents of a folder etc. but just want to download a simple file.

i can't manage to do this with smbclient_open or read..

Am i missing something?

Thanks!

Set the SMB protocol

Our organization has shutdown the use of SMB protocol (version) 1.0. Is there a way to force php smbclient to use a different protocol such as 2.0, 2.1, or 3.0?

DFS issues with SMBCLIENT_OPT_USE_NT_HASH

Not sure if this is an issue with libsmbclient or libsmbclient-php.

When setting SMBCLIENT_OPT_USE_NT_HASH to true you can access (and list etc.) the root of a DFS share but none of it's subfolders. This works fine when using plain credentials.

PECL release

What about having this extension in PECL repository to get more visibility ?

libsmbclient expects URI's to be urlencoded, how to handle this?

Just read libsmbclient.h and found that libsmbclient expects all URI's to be urlencoded. This means for instance that reading or writing a file called ex%2Fample.txt (a strange but valid filename) will not work as expected, since the library decodes the %2F to a slash.

This is unexpected behaviour. Especially since smbclient_readdir does not return urlencoded names "for backwards compatibility". I think we can handle this in two ways:

  • leave things as they are and make it really clear in the documentation that people need to urlencode their URI's;
  • accept "raw" strings everywhere and transparently urlencode them with the smbc_urlencode library function, so that the end user does not notice anything.

Because the second option breaks backwards compatibility, I propose to leave the current behaviour at least in the 0.5 branch, and improve the documentation to make the issue clear.

Extension name

For discussion:
Extension name is libsmbclient, but libsmbclient.so is not a good name, and create confusion with the library.

Even "autotool" don't like it.

$ touch libsmbclient.c
$ make
*** Warning: Linking the shared library libsmbclient.la against the loadable module
*** libsmbclient.so is not portable!

*** Warning: Linking the shared library libsmbclient.la against the loadable module
*** libsmbclient.so is not portable!
libtool: link: rm -fr  .libs/libsmbclient.la .libs/libsmbclient.lai .libs/libsmbclient.so
libtool: link: cc -shared  -fPIC -DPIC  .libs/libsmbclient.o .libs/smb_streams.o   -Wl,-rpath -Wl,/work/GIT/libsmbclient-php/.libs -Wl,-rpath -Wl,/work/GIT/libsmbclient-php/modules /work/GIT/libsmbclient-php/.libs/libsmbclient.so  -O2 -m64 -mtune=generic -Wl,-z -Wl,relro   -Wl,-soname -Wl,libsmbclient.so -o .libs/libsmbclient.so
cc: error: /work/GIT/libsmbclient-php/.libs/libsmbclient.so: No such file or directory
Makefile:188: recipe for target 'libsmbclient.la' failed
make: *** [libsmbclient.la] Error 1

Ok, this can be workaround (make clean && make, and auto-provides filtering for downstream packaging)

Possible names:

  • smb
  • smbc
  • smbclient (functions prefix)
  • samba

Invalid smbclient_chmod in readme

Currently the description of smbclient_chmod states

According to the libsmbclient header file, this function is not implemented. However, the Samba sources do seem to implement it

However, samba only seems to partly implement chmod, according to my own research libsmbclient/smbd seems to ignore the group and other bits and always set those to read only, meaning that it's impossible to set the hidden or system bits (i.e. chmod 0677 and chmod 0644 result in the same behaviour).

Note that is also doesn't seem possible to set those bits using setmode test.txt +h with smbclient

Additionally, when setting the file mode directly on the file system, (lib)smbclient does read those bits correctly from the unix file permissions

PHP Startup: Unable to load dynamic library /usr/lib/php5/20121212/smbclient.so

Hello,

I recently installed ownCloud 9.1.1 on a 14.04.5 installation. I followed the libsmbclient-php instructions here: https://github.com/eduardok/libsmbclient-php/ to get SMB shares to work. I also had to install libsmbclient-dev to get past a missing file error. As it stands, I have the following issues...

  1. The instructions didn't cite which php.ini to add extension="smbclient.so", so I assumed /etc/php5/cli/php.ini was the correct one. Is this correct? I have the 5 different ones: /etc/php5/apache2/php.ini, /etc/php5/cli/php.ini, /usr/share/php5/php.ini-dev, /usr/share/php5/php.ini-production and /usr/share/php5/php.ini-production.cli

  2. After adding extension="smbclient.so" to /etc/php5/cli/php.ini, I get the following PHP error: PHP Startup: Unable to load dynamic library '/usr/lib/php5/20121212/smbclient.so' - /usr/lib/php5/20121212/smbclient.so: cannot open shared object file: No such file or directory in Unknown on line 0.

  3. An obvious side effect of the above two issues is that I cannot access SMB shares via ownCloud. I get the following error when trying to access any shares via the web: "Storage not available" and the folder is empty.

Thoughts? Thanks all.

Error 13 (Permission Denied) with PECL krb5 since version 1.1.1

After obtaining a valid Kerberos ticket with PECL krb5, a call to smbclient_stat('smb://host/share/') returns error code 13 for access.

Using the same ticket cache file on command line, access to the network share works:

KRB5CCNAME=/tmp/(...)/krb5cc smbclient -k //host/share/
OS=[Windows Server 2008 R2 Standard 7601 Service Pack 1] Server=[Windows Server 2008 R2 Standard 6.1]
smb: \> ls
  .                                   D        0  Sun Oct 23 16:32:19 2016
  ..                                  D        0  Sun Oct 23 16:32:19 2016
(...)

-> I can browse the share; the kerberos cache file is the same one created using PECL krb5 1.1.1, so the bug is not necessarily in this library!

After downgrading PECL krb5 to 1.1.0, libsmbclient-php has access to the share.
I do not know if the bug is in the KRB5 library or in libsmbclient-php

Please add LICENSE file

Whatever the license is (PHP or BSD), please add a LICENSE file which is mandatory, per license term, for redistribution.

* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

Error While Running ./configure

Hello,

When i execute the command ./configure it will show an error as

==================================

checking for libsmbclient support... yes, shared
checking for libsmbclient.h in default paths... not found
configure: error: Could not find libsmbclient.h

=================================

Please help to let me know does it also need some other client as well to install. or Which PHP version.
Currently i have php 5.6

Unable to install on El Capitan...

Hi have downloaded your 0.7 and 0.8 version and I'm unable to install it.
After ./configure i have error:

Server-1:smbclient-0.8.0RC1 psadmin$ ./configure --enable-shared
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ISO C89... none needed
checking how to run the C preprocessor... cc -E
checking for icc... no
checking for suncc... no
checking whether cc understands -c and -o together... yes
checking for system library directory... lib
checking if compiler supports -R... no
checking if compiler supports -Wl,-rpath,... yes
checking build system type... x86_64-apple-darwin15.2.0
checking host system type... x86_64-apple-darwin15.2.0
checking target system type... x86_64-apple-darwin15.2.0
checking for PHP prefix... /usr/local/Cellar/php55/5.5.31
checking for PHP includes... -I/usr/local/Cellar/php55/5.5.31/include/php -I/usr/local/Cellar/php55/5.5.31/include/php/main -I/usr/local/Cellar/php55/5.5.31/include/php/TSRM -I/usr/local/Cellar/php55/5.5.31/include/php/Zend -I/usr/local/Cellar/php55/5.5.31/include/php/ext -I/usr/local/Cellar/php55/5.5.31/include/php/ext/date/lib
checking for PHP extension directory... /usr/local/Cellar/php55/5.5.31/lib/php/extensions/no-debug-non-zts-20121212
checking for PHP installed headers prefix... /usr/local/Cellar/php55/5.5.31/include/php
checking if debug is enabled... no
checking if zts is enabled... no
checking for re2c... no
configure: WARNING: You will need re2c 0.13.4 or later if you want to regenerate PHP parsers.
checking for gawk... no
checking for nawk... no
checking for awk... awk
checking if awk is broken... no
checking whether to enable smbclient support... yes, shared
checking for libsmbclient support... yes, shared
checking for libsmbclient.h in default paths... not found
configure: error: Could not find libsmbclient.h

Please can you help me?

Use smbclient_state_init with the stream wrapper

It would be fantastic if one could initialize the state using "smbclient_state_init" then continue to use the stream wrapper, so that regular file management functions can be used, while authenticated, but not including the username and password in the used paths/URLs.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.