package.xml 0000664 0001750 0001750 00000007214 12665077535 013377 0 ustar eduardok eduardok
smbclientpecl.php.netA PHP wrapper for libsmbclientsmbclient is a PHP extension that uses Samba's libsmbclient library to provide
Samba related functions and 'smb' streams to PHP programs.Eduardo Bacchi Kienetzeduardoeduardo@kienetz.comyesRemi Colletremiremi@php.netyes2016-02-290.8.00.8.0stablestableBSD 2-clause
- Promoting to stable after almost 3 months with no commits needed.
5.3.01.9.5smbclient
smbclient-0.8.0/tests/ClosedirTest.php 0000664 0001750 0001750 00000002306 12665077535 020157 0 ustar eduardok eduardok assertTrue(smbclient_closedir($state, $dir));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testClosedirEmpty ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$this->assertFalse(smbclient_closedir($state));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testClosedirNull ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$this->assertTrue(smbclient_closedir($state, null));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testClosedirDouble ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$dir = smbclient_opendir($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE);
$this->assertTrue(smbclient_closedir($state, $dir));
$this->assertFalse(smbclient_closedir($state, $dir));
}
}
smbclient-0.8.0/tests/CreateTest.php 0000664 0001750 0001750 00000001537 12665077535 017623 0 ustar eduardok eduardok assertTrue(is_resource($file));
$this->assertFileExists($realfile);
unlink($realfile);
}
public function
testCreateUrlencodedSuccess ()
{
$testuri = 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/ex%25%25%25ample.txt';
$realfile = SMB_LOCAL . '/ex%%%ample.txt';
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$file = smbclient_creat($state, $testuri);
$this->assertTrue(is_resource($file));
$this->assertFileExists($realfile);
#unlink($realfile);
}
}
smbclient-0.8.0/tests/GetxattrTest.php 0000664 0001750 0001750 00000003132 12665077535 020213 0 ustar eduardok eduardok assertTrue(is_string($attr));
}
public function
testGetxattrDirSuccess ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$attr = smbclient_getxattr($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/testdir', 'system.*');
$this->assertTrue(is_string($attr));
}
public function
testGetxattrShareSuccess ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$attr = smbclient_getxattr($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE, 'system.*');
$this->assertTrue(is_string($attr));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testGetxattrServer ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$attr = smbclient_getxattr($state, 'smb://'.SMB_HOST, 'system.*');
$this->assertFalse($attr);
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testGetxattrFileNotFound ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$attr = smbclient_getxattr($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/testdir/does-not-exist', 'system.dos_attr.mode');
$this->assertFalse($attr);
$this->assertEquals(smbclient_state_errno($state), 2); // ENOENT
}
}
smbclient-0.8.0/tests/LseekTest.php 0000664 0001750 0001750 00000003372 12665077535 017462 0 ustar eduardok eduardok testuri = 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/lseektest.txt';
$this->realfile = SMB_LOCAL.'/lseektest.txt';
}
public function
testLseekSet ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$file = smbclient_creat($state, $this->testuri);
$ret = smbclient_write($state, $file, 'abcdefgh');
$this->assertTrue(is_integer($ret));
$ret = smbclient_lseek($state, $file, 3, SEEK_SET);
$this->assertEquals(3, $ret);
smbclient_write($state, $file, 'foo');
smbclient_close($state, $file);
$this->assertStringEqualsFile($this->realfile, 'abcfoogh');
}
public function
testLseekSetPastEnd ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$file = smbclient_creat($state, $this->testuri);
$ret = smbclient_lseek($state, $file, 3, SEEK_SET);
$this->assertEquals(3, $ret);
smbclient_write($state, $file, 'foo');
smbclient_close($state, $file);
$this->assertStringEqualsFile($this->realfile, sprintf('%c%c%c%s', 0, 0, 0, 'foo'));
}
public function
testLseekCurPositive ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$file = smbclient_creat($state, $this->testuri);
smbclient_write($state, $file, 'abcdefgh');
$ret = smbclient_lseek($state, $file, 3, SEEK_CUR);
$this->assertEquals(11, $ret);
smbclient_write($state, $file, 'foo', 3);
smbclient_close($state, $file);
$this->assertStringEqualsFile($this->realfile, sprintf('%s%c%c%c%s', 'abcdefgh', 0, 0, 0, 'foo'));
}
}
smbclient-0.8.0/tests/OpendirTest.php 0000664 0001750 0001750 00000003344 12665077535 020016 0 ustar eduardok eduardok assertTrue(is_resource($dir));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testOpendirInvalidState ()
{
$dir = smbclient_opendir(null, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/testdir');
$this->assertFalse($dir);
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testOpendirNotFound ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$dir = smbclient_opendir($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/does-not-exist');
$this->assertFalse($dir);
$errno = smbclient_state_errno($state);
$this->assertEquals(2, $errno); // ENOENT
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testOpendirPermissionDenied ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$dir = smbclient_opendir($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/noaccess');
$this->assertFalse($dir);
$errno = smbclient_state_errno($state);
$this->assertEquals(13, $errno); // EACCES
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testOpendirNotDir ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$dir = smbclient_opendir($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/testfile.txt');
$this->assertFalse($dir);
$errno = smbclient_state_errno($state);
$this->assertEquals(20, $errno); // ENOTDIR
}
}
smbclient-0.8.0/tests/OptionsTest.php 0000664 0001750 0001750 00000010352 12665077535 020046 0 ustar eduardok eduardok assertTrue(is_long(SMBCLIENT_OPT_OPEN_SHAREMODE));
$this->assertTrue(is_long(SMBCLIENT_OPT_ENCRYPT_LEVEL));
$this->assertTrue(is_long(SMBCLIENT_OPT_CASE_SENSITIVE));
$this->assertTrue(is_long(SMBCLIENT_OPT_BROWSE_MAX_LMB_COUNT));
$this->assertTrue(is_long(SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES));
$this->assertTrue(is_long(SMBCLIENT_OPT_USE_KERBEROS));
$this->assertTrue(is_long(SMBCLIENT_OPT_FALLBACK_AFTER_KERBEROS));
$this->assertTrue(is_long(SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN));
$this->assertTrue(is_long(SMBCLIENT_OPT_USE_CCACHE));
$this->assertTrue(is_long(SMBCLIENT_OPT_USE_NT_HASH));
$this->assertTrue(is_long(SMBCLIENT_OPT_NETBIOS_NAME));
$this->assertTrue(is_long(SMBCLIENT_OPT_WORKGROUP));
$this->assertTrue(is_long(SMBCLIENT_OPT_USER));
$this->assertTrue(is_long(SMBCLIENT_OPT_PORT));
$this->assertTrue(is_long(SMBCLIENT_OPT_TIMEOUT));
}
public function
testOptionNotExists ()
{
$state = smbclient_state_new();
$this->assertNull(smbclient_option_get($state, 9999));
smbclient_state_free($state);
}
public function
testOptionSetGetCaseSensitive ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$this->assertTrue(smbclient_option_set($state, SMBCLIENT_OPT_CASE_SENSITIVE, true));
$this->assertTrue(smbclient_option_get($state, SMBCLIENT_OPT_CASE_SENSITIVE));
$this->assertTrue(smbclient_option_set($state, SMBCLIENT_OPT_CASE_SENSITIVE, false));
$this->assertFalse(smbclient_option_get($state, SMBCLIENT_OPT_CASE_SENSITIVE));
smbclient_state_free($state);
}
public function
testOptionSetGetUser ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$this->assertTrue(smbclient_option_set($state, SMBCLIENT_OPT_USER, SMB_USER));
$this->assertEquals(SMB_USER, smbclient_option_get($state, SMBCLIENT_OPT_USER));
smbclient_state_free($state);
}
public function
testOptionSetGetUserWithOpen ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$this->assertTrue(smbclient_option_set($state, SMBCLIENT_OPT_USER, SMB_USER));
$this->assertEquals(SMB_USER, smbclient_option_get($state, SMBCLIENT_OPT_USER));
$dir = smbclient_opendir($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE);
while (($out = smbclient_readdir($state, $dir)) !== false);
smbclient_closedir($state, $dir);
smbclient_state_free($state);
}
public function
testOptionUrlencodeReaddir ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
// Create a file via the regular filesystem:
touch(SMB_LOCAL.'/readdir%option.txt');
// Technically options can only be set between new and init...
smbclient_option_set($state, SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES, false);
$dir = smbclient_opendir($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE);
$found = false;
while (($out = smbclient_readdir($state, $dir)) !== false) {
if ($out['name'] === 'readdir%option.txt') {
$found = true;
break;
}
}
smbclient_closedir($state, $dir);
$this->assertTrue($found);
smbclient_option_set($state, SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES, true);
$dir = smbclient_opendir($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE);
$found = false;
while (($out = smbclient_readdir($state, $dir)) !== false) {
if ($out['name'] === 'readdir%25option.txt') {
$found = true;
break;
}
}
smbclient_closedir($state, $dir);
smbclient_state_free($state);
$this->assertTrue($found);
unlink(SMB_LOCAL.'/readdir%option.txt');
}
public function
testOptionNTHash ()
{
$state = smbclient_state_new();
if (smbclient_option_get($state, SMBCLIENT_OPT_USE_NT_HASH) === null) {
smbclient_state_free($state);
return;
}
smbclient_option_set($state, SMBCLIENT_OPT_USE_NT_HASH, true);
// NTLM hash of 'password' generated at http://www.tobtu.com/lmntlm.php
smbclient_state_init($state, null, SMB_USER, SMB_HASH);
$dir = smbclient_opendir($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE);
while (($out = smbclient_readdir($state, $dir)) !== false);
$this->assertTrue(is_resource($dir));
smbclient_closedir($state, $dir);
smbclient_state_free($state);
}
}
smbclient-0.8.0/tests/ReaddirTest.php 0000664 0001750 0001750 00000001112 12665077535 017757 0 ustar eduardok eduardok assertEquals($smb, $local);
}
}
smbclient-0.8.0/tests/RenameTest.php 0000664 0001750 0001750 00000003273 12665077535 017626 0 ustar eduardok eduardok assertTrue(smbclient_rename($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/foo', $state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/bar'));
$moved = is_file(SMB_LOCAL.'/bar');
$this->assertTrue($moved);
$gone = is_file(SMB_LOCAL.'/foo');
$this->assertFalse($gone);
if ($moved) {
$this->assertEquals('this is a test', file_get_contents(SMB_LOCAL.'/bar'));
}
@unlink(SMB_LOCAL.'/foo');
@unlink(SMB_LOCAL.'/bar');
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testRenameFileNotExists ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$this->assertFalse(smbclient_rename($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/does-not-exist', $state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/somewhere-else'));
$this->assertEquals(2, smbclient_state_errno($state)); // ENOENT
}
public function
testRenameDirSuccess ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
// Create mock dir "foo" via regular filesystem:
mkdir(SMB_LOCAL.'/foo');
$this->assertTrue(smbclient_rename($state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/foo', $state, 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/bar'));
$moved = is_dir(SMB_LOCAL.'/bar');
$this->assertTrue($moved);
$gone = is_dir(SMB_LOCAL.'/foo');
$this->assertFalse($gone);
@rmdir(SMB_LOCAL.'/foo');
@rmdir(SMB_LOCAL.'/bar');
}
}
smbclient-0.8.0/tests/setup-share.sh 0000664 0001750 0001750 00000000613 12665077535 017635 0 ustar eduardok eduardok set -e
rm -rf /home/testuser/testshare
mkdir /home/testuser/testshare
mkdir /home/testuser/testshare/testdir
echo "this is a test file" > /home/testuser/testshare/testdir/testfile.txt
chown -R testuser /home/testuser
mkdir /home/testuser/testshare/noaccess
chmod 0700 /home/testuser/testshare/noaccess
# Our test user can write to /home/testuser/testshare:
chmod 0777 /home/testuser/testshare
smbclient-0.8.0/tests/StateFreeTest.php 0000664 0001750 0001750 00000001376 12665077535 020303 0 ustar eduardok eduardok assertTrue(smbclient_state_free($state));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testStateFreeEmpty ()
{
$this->assertFalse(smbclient_state_free());
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testStateFreeNull ()
{
$this->assertFalse(smbclient_state_free(null));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testStateFreeDouble ()
{
$state = smbclient_state_new();
$this->assertTrue(smbclient_state_free($state));
$this->assertFalse(smbclient_state_free($state));
}
}
smbclient-0.8.0/tests/StateInitTest.php 0000664 0001750 0001750 00000000610 12665077535 020313 0 ustar eduardok eduardok assertTrue(smbclient_state_init($state, null, SMB_USER, SMB_PASS));
}
/**
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function
testStateInitInvalidState ()
{
$this->assertFalse(smbclient_state_init(null));
}
}
smbclient-0.8.0/tests/StateNewTest.php 0000664 0001750 0001750 00000000265 12665077535 020147 0 ustar eduardok eduardok assertTrue(is_resource($state));
}
}
smbclient-0.8.0/tests/StreamsTest.php 0000664 0001750 0001750 00000012667 12665077535 020044 0 ustar eduardok eduardok readuri = 'smb://'.SMB_USER.':'.SMB_PASS.'@'.SMB_HOST.'/'.SMB_SHARE.'/testdir/testfile.txt';
$this->realread = SMB_LOCAL . '/testdir/testfile.txt';
$this->writeuri = 'smb://'.SMB_USER.':'.SMB_PASS.'@'.SMB_HOST.'/'.SMB_SHARE.'/streamfile.txt';
$this->writealt = 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/streamfile.txt';
$this->realfile = SMB_LOCAL . '/streamfile.txt';
$this->diruri = 'smb://'.SMB_USER.':'.SMB_PASS.'@'.SMB_HOST.'/'.SMB_SHARE.'/streamdir';
$this->realdir = SMB_LOCAL . '/streamdir';
}
public function
tearDown()
{
@unlink($this->realfile);
@rmdir($this->realdir);
}
public function
testRegistered ()
{
$this->assertContains('smb', stream_get_wrappers());
}
public function
testReadWrite ()
{
$fic = fopen($this->writeuri, "w+");
$this->assertTrue(is_resource($fic), "Get a resource");
$len = fwrite($fic, $this->testdata);
$this->assertEquals(strlen($this->testdata), $len);
$this->assertEquals($len, ftell($fic));
$this->assertEquals(3, fwrite($fic, "foo"));
$this->assertEquals($len, fwrite($fic, $this->testdata));
$this->assertEquals(2*$len+3, ftell($fic));
$this->assertEquals(0, fseek($fic, $len, SEEK_SET));
$this->assertEquals($len, ftell($fic));
$this->assertEquals('foo', fread($fic, 3));
$stat = fstat($fic);
$this->assertCount(26, $stat);
$this->assertArrayHasKey('atime', $stat);
$this->assertArrayHasKey('mtime', $stat);
$this->assertArrayHasKey('ctime', $stat);
$this->assertArrayHasKey('size', $stat);
$this->assertEquals(2*$len+3, $stat['size']);
$this->assertTrue(fclose($fic));
}
public function
testPutContents ()
{
$len = file_put_contents($this->writeuri, $this->testdata);
$this->assertEquals(strlen($this->testdata), $len);
$this->assertFileExists($this->realfile);
}
public function
testPutContentsContext ()
{
$context = stream_context_create(array('smb' => array(
'username' => SMB_USER,
'password' => SMB_PASS
)));
$len = file_put_contents($this->writealt, $this->testdata, 0, $context);
$this->assertEquals(strlen($this->testdata), $len);
$this->assertFileExists($this->realfile);
}
public function
testGetContents ()
{
$data = file_get_contents($this->readuri);
$this->assertTrue(strlen($data) > 0);
}
public function
testUnlink ()
{
$this->assertTrue(copy($this->readuri, $this->writeuri));
$this->assertFileExists($this->realfile);
$this->assertTrue(unlink($this->writeuri));
$this->assertFileNotExists($this->realfile);
}
public function
testMkdirRmdir ()
{
$this->assertTrue(mkdir($this->diruri));
$this->assertTrue(is_dir($this->realdir), "Directory exists");
$this->assertTrue(rmdir($this->diruri));
clearstatcache();
$this->assertFalse(is_dir($this->realdir), "Directory not exists");
}
public function
testRenameFile ()
{
$this->assertTrue(copy($this->readuri, $this->writeuri));
$this->assertTrue(rename($this->writeuri, $this->writeuri.'2'));
$this->assertFileExists($this->realfile.'2');
$this->assertTrue(unlink($this->writeuri.'2'));
}
public function
testRenameDir ()
{
$this->assertTrue(mkdir($this->diruri));
$this->assertTrue(is_dir($this->realdir), "Directory exists");
$this->assertTrue(rename($this->diruri, $this->diruri.'2'));
$this->assertTrue(is_dir($this->realdir.'2'), "Directory exists");
$this->assertTrue(rmdir($this->diruri.'2'));
}
public function
testReaddir ()
{
$local = scandir(dirname($this->realdir));
$smb = scandir(dirname($this->diruri));
$this->assertEquals($local, $smb);
}
public function
testStat ()
{
$stat = stat($this->readuri);
$this->assertCount(26, $stat);
$this->assertArrayHasKey('atime', $stat);
$this->assertArrayHasKey('mtime', $stat);
$this->assertArrayHasKey('ctime', $stat);
$this->assertArrayHasKey('size', $stat);
$local = stat($this->realread);
$this->assertEquals($local['size'], $stat['size']);
/* can't compare other values as local/remote are different */
}
public function
testChmod ()
{
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$this->markTestSkipped("PHP > 5.4 needed");
}
$this->assertTrue(copy($this->readuri, $this->writeuri));
$old = fileperms($this->writeuri) & 0777;
/* noop only test */
$this->assertTrue(chmod($this->writeuri, $old));
$new = fileperms($this->writeuri) & 0777;
$this->assertEquals($old, $new);
}
public function
testTouch ()
{
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$this->markTestSkipped("PHP > 5.4 needed");
}
$mt = mktime(0,0,0,9,5,2015);
$at = mktime(0,0,0,9,6,2015);
$this->assertTrue(touch($this->writeuri, $mt, $at));
$this->assertFileExists($this->realfile);
$stat = stat($this->writeuri);
$this->assertEquals($mt, $stat['mtime'], "mtime");
$this->assertEquals($at, $stat['atime'], "atime");
}
public function
testFileinfo ()
{
if (!extension_loaded('fileinfo')) {
$this->markTestSkipped('Fileinfo extension needed');
}
$fi = new finfo(FILEINFO_MIME_TYPE);
$this->assertEquals('text/plain', $fi->file($this->readuri));
}
public function
testListShares ()
{
$smb = scandir('smb://'.SMB_USER.':'.SMB_PASS.'@'.SMB_HOST.'/');
$this->assertContains(SMB_SHARE, $smb, print_r($smb, true));
}
}
smbclient-0.8.0/tests/VersionTest.php 0000664 0001750 0001750 00000000410 12665077535 020032 0 ustar eduardok eduardok assertTrue(is_string(smbclient_version()));
}
public function
testLibraryVersion ()
{
$this->assertTrue(is_string(smbclient_library_version()));
}
}
smbclient-0.8.0/tests/VfsTest.php 0000664 0001750 0001750 00000002540 12665077535 017151 0 ustar eduardok eduardok testuri = 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/testdir/testfile.txt';
}
public function
testHaveConstants ()
{
$this->assertTrue(defined('SMBCLIENT_VFS_RDONLY'));
$this->assertTrue(defined('SMBCLIENT_VFS_DFS'));
$this->assertTrue(defined('SMBCLIENT_VFS_CASE_INSENSITIVE'));
$this->assertTrue(defined('SMBCLIENT_VFS_NO_UNIXCIFS'));
}
private function
hasParts ($vfs)
{
$parts = array('bsize','frsize','blocks','bfree','bavail','files','ffree','favail','fsid','flag','namemax');
foreach ($parts as $part) {
$this->assertTrue(isset($vfs[$part]));
$this->assertTrue(is_int($vfs[$part]));
}
}
public function
testStatVFS ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$vfs = smbclient_statvfs($state, $this->testuri);
smbclient_state_free($state);
$this->assertTrue(is_array($vfs));
$this->hasParts($vfs);
}
public function
testFstatVFS ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$file = smbclient_open($state, $this->testuri, 'r');
$vfs = smbclient_fstatvfs($state, $file);
smbclient_close($state, $file);
smbclient_state_free($state);
$this->assertTrue(is_array($vfs));
$this->hasParts($vfs);
}
}
smbclient-0.8.0/tests/WriteTest.php 0000664 0001750 0001750 00000006201 12665077535 017503 0 ustar eduardok eduardok testuri = 'smb://'.SMB_HOST.'/'.SMB_SHARE.'/writetest.txt';
$this->realfile = SMB_LOCAL.'/writetest.txt';
$this->testuri2 = 'smb://'.SMB_USER.':'.SMB_PASS.'@'.SMB_HOST.'/'.SMB_SHARE.'/writetest.txt';
}
public function
tearDown()
{
@unlink($this->realfile);
}
public function
testWriteSuccess ()
{
/* credentials sent during init */
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$file = smbclient_creat($state, $this->testuri);
$this->assertTrue(is_resource($file));
$ret = smbclient_write($state, $file, $this->testdata);
$this->assertTrue(is_integer($ret));
$this->assertEquals(strlen($this->testdata), $ret);
// Use the regular filesystem to check the file that was created:
$this->assertFileExists($this->realfile);
$this->assertEquals(filesize($this->realfile), $ret);
$this->assertStringEqualsFile($this->realfile, $this->testdata);
}
public function
testWriteSuccess2 ()
{
/* credentials in URI */
$state = smbclient_state_new();
smbclient_state_init($state);
$file = smbclient_creat($state, $this->testuri2);
$this->assertTrue(is_resource($file));
$ret = smbclient_write($state, $file, $this->testdata);
$this->assertTrue(is_integer($ret));
$this->assertEquals(strlen($this->testdata), $ret);
// Use the regular filesystem to check the file that was created:
$this->assertFileExists($this->realfile);
$this->assertEquals(filesize($this->realfile), $ret);
$this->assertStringEqualsFile($this->realfile, $this->testdata);
}
public function
testWritePartial ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$file = smbclient_creat($state, $this->testuri);
$this->assertTrue(is_resource($file));
// Write just 30 bytes:
$ret = smbclient_write($state, $file, $this->testdata, 30);
$this->assertEquals(30, $ret);
// Use the regular filesystem to check the file that was created:
$this->assertFileExists($this->realfile);
$this->assertEquals(filesize($this->realfile), $ret);
$this->assertStringEqualsFile($this->realfile, substr($this->testdata, 0, 30));
}
public function
testWriteOversized ()
{
$state = smbclient_state_new();
smbclient_state_init($state, null, SMB_USER, SMB_PASS);
$file = smbclient_creat($state, $this->testuri);
$this->assertTrue(is_resource($file));
// Write way more bytes than data:
$ret = smbclient_write($state, $file, $this->testdata, 1000);
$this->assertTrue(is_integer($ret));
$this->assertEquals(strlen($this->testdata), $ret);
// Use the regular filesystem to check the file that was created:
$this->assertFileExists($this->realfile);
$this->assertEquals(filesize($this->realfile), $ret);
$this->assertStringEqualsFile($this->realfile, $this->testdata);
}
}
smbclient-0.8.0/config.m4 0000664 0001750 0001750 00000004750 12665077535 015414 0 ustar eduardok eduardok dnl If your extension references something external, use with:
PHP_ARG_ENABLE(libsmbclient, whether to enable smbclient support,
[ --enable-smbclient Enable libsmbclient support])
PHP_ARG_WITH(libsmbclient, for libsmbclient support,
[ --with-libsmbclient=DIR Installation prefix of libsmbclient.
If DIR is not specified, use the system library.])
if test "$PHP_SMBCLIENT" != "no"; then
dnl If a path was given, expect to find the library in $PHP_LIBDIR
dnl and the include file in include/
if test "$PHP_LIBSMBCLIENT" != "yes"; then
LIBSMBCLIENT_DIR=$PHP_LIBSMBCLIENT/$PHP_LIBDIR
LIBSMBCLIENT_INCDIR=$PHP_LIBSMBCLIENT/include
AC_DEFINE(HAVE_LIBSMBCLIENT, 1, [ ])
PHP_ADD_INCLUDE($LIBSMBCLIENT_INCDIR)
PHP_ADD_LIBRARY_WITH_PATH(smbclient, $LIBSMBCLIENT_DIR, SMBCLIENT_SHARED_LIBADD)
dnl Otherwise find the header and shared library by the normal means:
else
dnl Find the header file:
AC_MSG_CHECKING([for libsmbclient.h in default paths])
for i in /usr/local/include /usr/local/include/samba-* /usr/include /usr/include/samba-* ; do
if test -r $i/libsmbclient.h; then
LIBSMBCLIENT_INCDIR="$i";
AC_MSG_RESULT([found in $i])
break;
fi
done
if test -z "$LIBSMBCLIENT_INCDIR"; then
AC_MSG_RESULT([not found])
AC_MSG_ERROR([Could not find libsmbclient.h])
fi
dnl Find the shared library:
PHP_CHECK_LIBRARY(smbclient, smbc_getOptionUserData,
[
AC_DEFINE(HAVE_LIBSMBCLIENT, 1, [ ])
PHP_ADD_INCLUDE($LIBSMBCLIENT_INCDIR)
PHP_ADD_LIBRARY(smbclient, 1, SMBCLIENT_SHARED_LIBADD)
],[
AC_MSG_ERROR([Could not find libsmbclient.so or symbol smbc_getOptionUserData. Check version and config.log for more information.])
],[
-lsmbclient
])
fi
dnl Check for smbc_setOptionUseNTHash;
dnl a relatively recent addition that is not available in our Travis test environment:
PHP_CHECK_LIBRARY(smbclient, smbc_setOptionUseNTHash,
[
AC_DEFINE(HAVE_SMBC_SETOPTIONUSENTHASH, 1, [Whether smbc_setOptionUseNTHash is available])
], [
], [
-lsmbclient
])
dnl Check for smbc_setPort;
dnl a relatively recent addition that is not available in our Travis test environment:
PHP_CHECK_LIBRARY(smbclient, smbc_setPort,
[
AC_DEFINE(HAVE_SMBC_SETPORT, 1, [Whether smbc_setPort is available])
], [
], [
-lsmbclient
])
PHP_SUBST(SMBCLIENT_SHARED_LIBADD)
PHP_NEW_EXTENSION(smbclient, smbclient.c smb_streams.c, $ext_shared)
fi
smbclient-0.8.0/php_smbclient.h 0000664 0001750 0001750 00000010433 12665077535 016700 0 ustar eduardok eduardok /* ------------------------------------------------------------------
* This file is part of libsmbclient-php: Samba bindings for PHP.
* Libsmbclient-php is licensed under the BSD 2-clause license:
* ------------------------------------------------------------------
*
* Copyright (c) 2003, Matthew Sachs
* 2009 - 2014, Eduardo Bacchi Kienetz
* 2013 - 2015, Alfred Klomp
* 2015, Remi Collet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* ------------------------------------------------------------------
*/
#ifndef PHP_SMBCLIENT_H
#define PHP_SMBCLIENT_H
#include
#define PHP_SMBCLIENT_VERSION "0.8.0"
extern zend_module_entry smbclient_module_entry;
#define phpext_smbclient_ptr &smbclient_module_entry
typedef struct {
} php_smbclient_globals;
typedef struct _php_smbclient_state
{
SMBCCTX *ctx;
char *wrkg;
char *user;
char *pass;
int wrkglen;
int userlen;
int passlen;
int err;
}
php_smbclient_state;
PHP_MINIT_FUNCTION(smbclient);
PHP_MSHUTDOWN_FUNCTION(smbclient);
PHP_RINIT_FUNCTION(smbclient);
PHP_MINFO_FUNCTION(smbclient);
PHP_FUNCTION(smbclient_version);
PHP_FUNCTION(smbclient_library_version);
PHP_FUNCTION(smbclient_state_new);
PHP_FUNCTION(smbclient_state_init);
PHP_FUNCTION(smbclient_state_errno);
PHP_FUNCTION(smbclient_state_free);
PHP_FUNCTION(smbclient_option_get);
PHP_FUNCTION(smbclient_option_set);
PHP_FUNCTION(smbclient_opendir);
PHP_FUNCTION(smbclient_readdir);
PHP_FUNCTION(smbclient_closedir);
PHP_FUNCTION(smbclient_rename);
PHP_FUNCTION(smbclient_unlink);
PHP_FUNCTION(smbclient_mkdir);
PHP_FUNCTION(smbclient_rmdir);
PHP_FUNCTION(smbclient_stat);
PHP_FUNCTION(smbclient_fstat);
PHP_FUNCTION(smbclient_open);
PHP_FUNCTION(smbclient_creat);
PHP_FUNCTION(smbclient_read);
PHP_FUNCTION(smbclient_write);
PHP_FUNCTION(smbclient_lseek);
PHP_FUNCTION(smbclient_ftruncate);
PHP_FUNCTION(smbclient_close);
PHP_FUNCTION(smbclient_chmod);
PHP_FUNCTION(smbclient_utimes);
PHP_FUNCTION(smbclient_listxattr);
PHP_FUNCTION(smbclient_getxattr);
PHP_FUNCTION(smbclient_setxattr);
PHP_FUNCTION(smbclient_removexattr);
PHP_FUNCTION(smbclient_statvfs);
PHP_FUNCTION(smbclient_fstatvfs);
/* If Zend Thread Safety (ZTS) is defined, each thread gets its own private
* php_smbclient_globals structure, the elements of which it can access
* through the SMBCLIENT() macro. Without ZTS, there is just one master
* structure in which we access the members directly: */
#ifdef ZTS
#define SMBCLIENT_G(v) TSRMG(smbclient_globals_id, php_smbclient_globals *, v)
#else
#define SMBCLIENT_G(v) (smbclient_globals.v)
#endif
php_stream_wrapper php_stream_smb_wrapper;
php_smbclient_state * php_smbclient_state_new (php_stream_context *context, int init TSRMLS_DC);
void php_smbclient_state_free (php_smbclient_state *state TSRMLS_DC);
int php_smbclient_state_init (php_smbclient_state *state TSRMLS_DC);
int flagstring_to_smbflags (const char *flags, int flags_len, int *retval TSRMLS_DC);
#endif /* PHP_SMBCLIENT_H */
smbclient-0.8.0/smbclient.c 0000664 0001750 0001750 00000201521 12665077535 016024 0 ustar eduardok eduardok /* ------------------------------------------------------------------
* This file is part of libsmbclient-php: Samba bindings for PHP.
* Libsmbclient-php is licensed under the BSD 2-clause license:
* ------------------------------------------------------------------
*
* Copyright (c) 2003, Matthew Sachs
* 2009 - 2014, Eduardo Bacchi Kienetz
* 2013 - 2015, Alfred Klomp
* 2015, Remi Collet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* ------------------------------------------------------------------
*/
#define IS_EXT_MODULE
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "ext/standard/info.h"
#include "php_smbclient.h"
/* If Zend Thread Safety (ZTS) is defined, each thread gets its own copy of
* the php_smbclient_globals structure. Else we use a single global copy: */
#ifdef ZTS
static int smbclient_globals_id;
#else
static php_smbclient_globals smbclient_globals;
#endif
static void php_smbclient_init_globals(php_smbclient_globals *smbclient_globals_p TSRMLS_DC)
{
/* This function initializes the thread-local storage.
* We currently don't use this. */
}
#define PHP_SMBCLIENT_STATE_NAME "smbclient state"
#define PHP_SMBCLIENT_FILE_NAME "smbclient file"
static int le_smbclient_state;
static int le_smbclient_file;
#if PHP_MAJOR_VERSION >= 7
typedef size_t strsize_t;
#else
typedef int strsize_t;
typedef long zend_long;
#endif
enum {
SMBCLIENT_OPT_OPEN_SHAREMODE = 1,
SMBCLIENT_OPT_ENCRYPT_LEVEL = 2,
SMBCLIENT_OPT_CASE_SENSITIVE = 3,
SMBCLIENT_OPT_BROWSE_MAX_LMB_COUNT = 4,
SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES = 5,
/* Ignore OneSharePerServer, not relevant to us. */
SMBCLIENT_OPT_USE_KERBEROS = 6,
SMBCLIENT_OPT_FALLBACK_AFTER_KERBEROS = 7,
/* Reverse the sense of this option, the original
* is the confusing "NoAutoAnonymousLogin": */
SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN = 8,
SMBCLIENT_OPT_USE_CCACHE = 9,
SMBCLIENT_OPT_USE_NT_HASH = 10,
SMBCLIENT_OPT_NETBIOS_NAME = 11,
SMBCLIENT_OPT_WORKGROUP = 12,
SMBCLIENT_OPT_USER = 13,
SMBCLIENT_OPT_PORT = 14,
SMBCLIENT_OPT_TIMEOUT = 15,
}
php_smbclient_options;
static char *
find_char (char *start, char *last, char q)
{
char *c;
for (c = start; c <= last; c++) {
if (*c == q) {
return c;
}
}
return NULL;
}
static char *
find_second_char (char *start, char *last, char q)
{
char *c;
if ((c = find_char(start, last, q)) == NULL) {
return NULL;
}
return find_char(c + 1, last, q);
}
static void
astfill (char *start, char *last)
{
char *c;
for (c = start; c <= last; c++) {
*c = '*';
}
}
static void
hide_password (char *url, int len)
{
/* URL should have the form:
* smb://[[[domain;]user[:password@]]server[/share[/path[/file]]]]
* Replace everything after the second colon and before the next @
* with asterisks. */
char *last = (url + len) - 1;
char *second_colon;
char *slash;
char *at_sign;
if (len <= 0) {
return;
}
if ((second_colon = find_second_char(url, last, ':')) == NULL) {
return;
}
if ((slash = find_char(second_colon + 1, last, '/')) == NULL) {
slash = last + 1;
}
if ((at_sign = find_char(second_colon + 1, last, '@')) == NULL) {
astfill(second_colon + 1, slash - 1);
return;
}
if (at_sign > slash) {
at_sign = slash;
}
astfill(second_colon + 1, at_sign - 1);
}
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_void, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_smbclient_state_init, 0, 0, 1)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, workgroup)
ZEND_ARG_INFO(0, user)
ZEND_ARG_INFO(0, password)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_state, 0)
ZEND_ARG_INFO(0, state)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_option_get, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, option)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_option_set, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, option)
ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_path, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, path)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_rename, 0)
ZEND_ARG_INFO(0, oldstate)
ZEND_ARG_INFO(0, oldpath)
ZEND_ARG_INFO(0, oldstate)
ZEND_ARG_INFO(0, oldpath)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_dir, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, dir)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_file, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, file)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_smbclient_open, 0, 0, 3)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, flags)
ZEND_ARG_INFO(0, mode)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_smbclient_creat, 0, 0, 2)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, mode)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_smbclient_write, 0, 0, 3)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, file)
ZEND_ARG_INFO(0, buffer)
ZEND_ARG_INFO(0, count)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_lseek, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, file)
ZEND_ARG_INFO(0, offset)
ZEND_ARG_INFO(0, whence)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_ftruncate, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, file)
ZEND_ARG_INFO(0, offset)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_utimes, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, mtime)
ZEND_ARG_INFO(0, atime)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO(arginfo_smbclient_getxattr, 0)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, name)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_smbclient_setxattr, 0, 0, 4)
ZEND_ARG_INFO(0, state)
ZEND_ARG_INFO(0, path)
ZEND_ARG_INFO(0, name)
ZEND_ARG_INFO(0, value)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()
/* }}} */
static zend_function_entry smbclient_functions[] =
{
PHP_FE(smbclient_version, arginfo_smbclient_void)
PHP_FE(smbclient_library_version, arginfo_smbclient_void)
PHP_FE(smbclient_state_new, arginfo_smbclient_void)
PHP_FE(smbclient_state_init, arginfo_smbclient_state_init)
PHP_FE(smbclient_state_errno, arginfo_smbclient_state)
PHP_FE(smbclient_state_free, arginfo_smbclient_state)
PHP_FE(smbclient_option_get, arginfo_smbclient_option_get)
PHP_FE(smbclient_option_set, arginfo_smbclient_option_set)
PHP_FE(smbclient_opendir, arginfo_smbclient_path)
PHP_FE(smbclient_readdir, arginfo_smbclient_dir)
PHP_FE(smbclient_closedir, arginfo_smbclient_dir)
PHP_FE(smbclient_stat, arginfo_smbclient_path)
PHP_FE(smbclient_fstat, arginfo_smbclient_file)
PHP_FE(smbclient_open, arginfo_smbclient_open)
PHP_FE(smbclient_creat, arginfo_smbclient_creat)
PHP_FE(smbclient_read, arginfo_smbclient_file)
PHP_FE(smbclient_close, arginfo_smbclient_file)
PHP_FE(smbclient_mkdir, arginfo_smbclient_creat)
PHP_FE(smbclient_rmdir, arginfo_smbclient_path)
PHP_FE(smbclient_rename, arginfo_smbclient_rename)
PHP_FE(smbclient_write, arginfo_smbclient_write)
PHP_FE(smbclient_unlink, arginfo_smbclient_path)
PHP_FE(smbclient_lseek, arginfo_smbclient_lseek)
PHP_FE(smbclient_ftruncate, arginfo_smbclient_ftruncate)
PHP_FE(smbclient_chmod, arginfo_smbclient_creat)
PHP_FE(smbclient_utimes, arginfo_smbclient_utimes)
PHP_FE(smbclient_listxattr, arginfo_smbclient_path)
PHP_FE(smbclient_getxattr, arginfo_smbclient_getxattr)
PHP_FE(smbclient_setxattr, arginfo_smbclient_setxattr)
PHP_FE(smbclient_removexattr, arginfo_smbclient_getxattr)
PHP_FE(smbclient_statvfs, arginfo_smbclient_path)
PHP_FE(smbclient_fstatvfs, arginfo_smbclient_file)
#ifdef PHP_FE_END
PHP_FE_END
#else
{NULL, NULL, NULL}
#endif
};
zend_module_entry smbclient_module_entry =
{ STANDARD_MODULE_HEADER
, "smbclient" /* name */
, smbclient_functions /* functions */
, PHP_MINIT(smbclient) /* module_startup_func */
, PHP_MSHUTDOWN(smbclient) /* module_shutdown_func */
, PHP_RINIT(smbclient) /* request_startup_func */
, NULL /* request_shutdown_func */
, PHP_MINFO(smbclient) /* info_func */
, PHP_SMBCLIENT_VERSION /* version */
, STANDARD_MODULE_PROPERTIES
} ;
zend_module_entry old_module_entry = {
STANDARD_MODULE_HEADER,
"libsmbclient",
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
PHP_SMBCLIENT_VERSION,
STANDARD_MODULE_PROPERTIES,
};
#ifdef COMPILE_DL_SMBCLIENT
ZEND_GET_MODULE(smbclient)
#endif
static void
auth_copy (char *dst, char *src, size_t srclen, size_t maxlen)
{
if (dst == NULL || maxlen == 0) {
return;
}
if (src == NULL || srclen == 0) {
*dst = '\0';
return;
}
if (srclen < maxlen) {
memcpy(dst, src, srclen);
dst[srclen] = '\0';
return;
}
memcpy(dst, src, maxlen - 1);
dst[maxlen - 1] = '\0';
}
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)
{
/* Given context, server and share, return workgroup, username and password.
* String lengths are the max allowable lengths. */
php_smbclient_state *state;
if (ctx == NULL || (state = smbc_getOptionUserData(ctx)) == NULL) {
return;
}
auth_copy(wrkg, state->wrkg, (size_t)state->wrkglen, (size_t)wrkglen);
auth_copy(user, state->user, (size_t)state->userlen, (size_t)userlen);
auth_copy(pass, state->pass, (size_t)state->passlen, (size_t)passlen);
}
void
php_smbclient_state_free (php_smbclient_state *state TSRMLS_DC)
{
/* TODO: if smbc_free_context() returns 0, PHP will leak the handle: */
if (state->ctx != NULL && smbc_free_context(state->ctx, 1) != 0) {
switch (errno) {
case EBUSY: php_error(E_WARNING, "Couldn't destroy SMB context: connection in use"); break;
case EBADF: php_error(E_WARNING, "Couldn't destroy SMB context: invalid handle"); break;
default: php_error(E_WARNING, "Couldn't destroy SMB context: unknown error (%d)", errno); break;
}
}
if (state->wrkg != NULL) {
memset(state->wrkg, 0, state->wrkglen);
efree(state->wrkg);
}
if (state->user != NULL) {
memset(state->user, 0, state->userlen);
efree(state->user);
}
if (state->pass != NULL) {
memset(state->pass, 0, state->passlen);
efree(state->pass);
}
efree(state);
}
static inline void
smbclient_state_dtor (
#if PHP_MAJOR_VERSION >= 7
zend_resource *rsrc
#else
zend_rsrc_list_entry *rsrc
#endif
TSRMLS_DC)
{
php_smbclient_state_free((php_smbclient_state *)rsrc->ptr TSRMLS_CC);
}
static void
smbclient_file_dtor (
#if PHP_VERSION_ID >= 70000
zend_resource *rsrc
#else
zend_rsrc_list_entry *rsrc
#endif
TSRMLS_DC)
{
/* Because libsmbclient's file/dir close functions require a pointer to
* a context which we don't have, we cannot reliably destroy a file
* resource. One way of obtaining the context pointer could be to save
* it in a structure along with the file context, but the pointer could
* grow stale or otherwise spark a race condition. So it seems that the
* best we can do is nothing. The PHP programmer can either manually
* free the file resources, or wait for them to be cleaned up when the
* associated context is destroyed. */
}
PHP_MINIT_FUNCTION(smbclient)
{
/* If ZTS is defined, allocate and init a copy of the global
* datastructure for each thread: */
#ifdef ZTS
ts_allocate_id(&smbclient_globals_id, sizeof(php_smbclient_globals), (ts_allocate_ctor) php_smbclient_init_globals, NULL);
#else
php_smbclient_init_globals(&smbclient_globals);
#endif
/* Constants for smbclient_setxattr: */
REGISTER_LONG_CONSTANT("SMBCLIENT_XATTR_CREATE", SMBC_XATTR_FLAG_CREATE, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_XATTR_REPLACE", SMBC_XATTR_FLAG_REPLACE, CONST_PERSISTENT | CONST_CS);
/* Constants for getting/setting options: */
#define SMBCLIENT_CONST(x) REGISTER_LONG_CONSTANT(#x, x, CONST_PERSISTENT | CONST_CS);
SMBCLIENT_CONST(SMBCLIENT_OPT_OPEN_SHAREMODE);
SMBCLIENT_CONST(SMBCLIENT_OPT_ENCRYPT_LEVEL);
SMBCLIENT_CONST(SMBCLIENT_OPT_CASE_SENSITIVE);
SMBCLIENT_CONST(SMBCLIENT_OPT_BROWSE_MAX_LMB_COUNT);
SMBCLIENT_CONST(SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES);
SMBCLIENT_CONST(SMBCLIENT_OPT_USE_KERBEROS);
SMBCLIENT_CONST(SMBCLIENT_OPT_FALLBACK_AFTER_KERBEROS);
SMBCLIENT_CONST(SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN);
SMBCLIENT_CONST(SMBCLIENT_OPT_USE_CCACHE);
SMBCLIENT_CONST(SMBCLIENT_OPT_USE_NT_HASH);
SMBCLIENT_CONST(SMBCLIENT_OPT_NETBIOS_NAME);
SMBCLIENT_CONST(SMBCLIENT_OPT_WORKGROUP);
SMBCLIENT_CONST(SMBCLIENT_OPT_USER);
SMBCLIENT_CONST(SMBCLIENT_OPT_PORT);
SMBCLIENT_CONST(SMBCLIENT_OPT_TIMEOUT);
#undef SMBCLIENT_CONST
/* Constants for use with SMBCLIENT_OPT_OPENSHAREMODE: */
REGISTER_LONG_CONSTANT("SMBCLIENT_SHAREMODE_DENY_DOS", SMBC_SHAREMODE_DENY_DOS, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_SHAREMODE_DENY_ALL", SMBC_SHAREMODE_DENY_ALL, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_SHAREMODE_DENY_WRITE", SMBC_SHAREMODE_DENY_WRITE, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_SHAREMODE_DENY_READ", SMBC_SHAREMODE_DENY_READ, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_SHAREMODE_DENY_NONE", SMBC_SHAREMODE_DENY_NONE, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_SHAREMODE_DENY_FCB", SMBC_SHAREMODE_DENY_FCB, CONST_PERSISTENT | CONST_CS);
/* Constants for use with SMBCLIENT_OPT_ENCRYPTLEVEL: */
REGISTER_LONG_CONSTANT("SMBCLIENT_ENCRYPTLEVEL_NONE", SMBC_ENCRYPTLEVEL_NONE, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_ENCRYPTLEVEL_REQUEST", SMBC_ENCRYPTLEVEL_REQUEST, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_ENCRYPTLEVEL_REQUIRE", SMBC_ENCRYPTLEVEL_REQUIRE, CONST_PERSISTENT | CONST_CS);
/* Constants for the VFS functions: */
REGISTER_LONG_CONSTANT("SMBCLIENT_VFS_RDONLY", SMBC_VFS_FEATURE_RDONLY, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_VFS_DFS", SMBC_VFS_FEATURE_DFS, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_VFS_CASE_INSENSITIVE", SMBC_VFS_FEATURE_CASE_INSENSITIVE, CONST_PERSISTENT | CONST_CS);
REGISTER_LONG_CONSTANT("SMBCLIENT_VFS_NO_UNIXCIFS", SMBC_VFS_FEATURE_NO_UNIXCIFS, CONST_PERSISTENT | CONST_CS);
le_smbclient_state = zend_register_list_destructors_ex(smbclient_state_dtor, NULL, PHP_SMBCLIENT_STATE_NAME, module_number);
le_smbclient_file = zend_register_list_destructors_ex(smbclient_file_dtor, NULL, PHP_SMBCLIENT_FILE_NAME, module_number);
php_register_url_stream_wrapper("smb", &php_stream_smb_wrapper TSRMLS_CC);
/* register with old name for code using extension_loaded(libsmbclient) */
zend_register_internal_module(&old_module_entry TSRMLS_CC);
return SUCCESS;
}
PHP_RINIT_FUNCTION(smbclient)
{
return SUCCESS;
}
PHP_MSHUTDOWN_FUNCTION(smbclient)
{
return SUCCESS;
}
PHP_MINFO_FUNCTION(smbclient)
{
php_info_print_table_start();
php_info_print_table_row(2, "smbclient Support", "enabled");
php_info_print_table_row(2, "smbclient extension Version", PHP_SMBCLIENT_VERSION);
php_info_print_table_row(2, "libsmbclient library Version", smbc_version());
php_info_print_table_end();
}
static int
ctx_init_getauth (zval *z, char **dest, int *destlen, char *varname)
{
if (*dest != NULL) {
efree(*dest);
*dest = NULL;
}
*destlen = 0;
if (z == NULL) {
return 1;
}
switch (Z_TYPE_P(z))
{
case IS_NULL:
return 1;
#if PHP_MAJOR_VERSION >= 7
case IS_TRUE:
php_error(E_WARNING, "invalid value for %s", varname);
return 0;
case IS_FALSE:
return 1;
#else
case IS_BOOL:
if (Z_LVAL_P(z) == 1) {
php_error(E_WARNING, "invalid value for %s", varname);
return 0;
}
return 1;
#endif
case IS_STRING:
*destlen = Z_STRLEN_P(z);
*dest = estrndup(Z_STRVAL_P(z), *destlen);
return 1;
default:
php_error(E_WARNING, "invalid datatype for %s", varname);
return 0;
}
}
php_smbclient_state *
php_smbclient_state_new (php_stream_context *context, int init TSRMLS_DC)
{
php_smbclient_state *state;
SMBCCTX *ctx;
if ((ctx = smbc_new_context()) == NULL) {
switch (errno) {
case ENOMEM: php_error(E_WARNING, "Couldn't create smbclient state: insufficient memory"); break;
default: php_error(E_WARNING, "Couldn't create smbclient state: unknown error (%d)", errno); break;
};
return NULL;
}
state = emalloc(sizeof(php_smbclient_state));
state->ctx = ctx;
state->wrkg = NULL;
state->user = NULL;
state->pass = NULL;
state->wrkglen = 0;
state->userlen = 0;
state->passlen = 0;
state->err = 0;
smbc_setFunctionAuthDataWithContext(state->ctx, smbclient_auth_func);
/* Must also save a pointer to the state object inside the context, to
* find the state from the context in the auth function: */
smbc_setOptionUserData(ctx, (void *)state);
/* Force full, modern timenames when getting xattrs: */
smbc_setOptionFullTimeNames(state->ctx, 1);
if (context) {
#if PHP_MAJOR_VERSION >= 7
zval *tmpzval;
if (NULL != (tmpzval = php_stream_context_get_option(context, "smb", "workgroup"))) {
if (ctx_init_getauth(tmpzval, &state->wrkg, &state->wrkglen, "workgroup") == 0) {
php_smbclient_state_free(state);
return NULL;
}
}
if (NULL != (tmpzval = php_stream_context_get_option(context, "smb", "username"))) {
if (ctx_init_getauth(tmpzval, &state->user, &state->userlen, "username") == 0) {
php_smbclient_state_free(state);
return NULL;
}
}
if (NULL != (tmpzval = php_stream_context_get_option(context, "smb", "password"))) {
if (ctx_init_getauth(tmpzval, &state->pass, &state->passlen, "password") == 0) {
php_smbclient_state_free(state);
return NULL;
}
}
#else
zval **tmpzval;
if (php_stream_context_get_option(context, "smb", "workgroup", &tmpzval) == SUCCESS) {
if (ctx_init_getauth(*tmpzval, &state->wrkg, &state->wrkglen, "workgroup") == 0) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
}
if (php_stream_context_get_option(context, "smb", "username", &tmpzval) == SUCCESS) {
if (ctx_init_getauth(*tmpzval, &state->user, &state->userlen, "username") == 0) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
}
if (php_stream_context_get_option(context, "smb", "password", &tmpzval) == SUCCESS) {
if (ctx_init_getauth(*tmpzval, &state->pass, &state->passlen, "password") == 0) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
}
#endif
}
if (init) {
if (php_smbclient_state_init(state TSRMLS_CC)) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
}
return state;
}
PHP_FUNCTION(smbclient_state_new)
{
php_smbclient_state *state;
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
if ((state = php_smbclient_state_new(NULL, 0 TSRMLS_CC)) == NULL) {
RETURN_FALSE;
}
#if PHP_MAJOR_VERSION >= 7
ZVAL_RES(return_value, zend_register_resource(state, le_smbclient_state));
#else
ZEND_REGISTER_RESOURCE(return_value, state, le_smbclient_state);
#endif
}
PHP_FUNCTION(smbclient_version)
{
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
#if PHP_MAJOR_VERSION >= 7
RETURN_STRING(PHP_SMBCLIENT_VERSION);
#else
RETURN_STRING(PHP_SMBCLIENT_VERSION, 1);
#endif
}
PHP_FUNCTION(smbclient_library_version)
{
if (zend_parse_parameters_none() == FAILURE) {
RETURN_FALSE;
}
#if PHP_MAJOR_VERSION >= 7
RETURN_STRING(smbc_version());
#else
RETURN_STRING(smbc_version(), 1);
#endif
}
int
php_smbclient_state_init (php_smbclient_state *state TSRMLS_DC)
{
SMBCCTX *ctx;
if ((ctx = smbc_init_context(state->ctx)) != NULL) {
state->ctx = ctx;
return 0;
}
switch (state->err = errno) {
case EBADF: php_error(E_WARNING, "Couldn't init SMB context: null context given"); break;
case ENOMEM: php_error(E_WARNING, "Couldn't init SMB context: insufficient memory"); break;
case ENOENT: php_error(E_WARNING, "Couldn't init SMB context: cannot load smb.conf"); break;
default: php_error(E_WARNING, "Couldn't init SMB context: unknown error (%d)", errno); break;
}
return 1;
}
#if PHP_MAJOR_VERSION >= 7
#define SMB_FETCH_RESOURCE(_state, _type, _zval, _name, _le) \
if ((_state = (_type)zend_fetch_resource(Z_RES_P(*_zval), _name, _le)) == NULL) { \
RETURN_FALSE; \
}
#else
#define SMB_FETCH_RESOURCE(_state, _type, _zval, _name, _le) \
ZEND_FETCH_RESOURCE(_state, _type, _zval, -1, _name, _le);
#endif
#define STATE_FROM_ZSTATE \
SMB_FETCH_RESOURCE(state, php_smbclient_state *, &zstate, PHP_SMBCLIENT_STATE_NAME, le_smbclient_state); \
if (state == NULL || state->ctx == NULL) { \
php_error(E_WARNING, PHP_SMBCLIENT_STATE_NAME " not found"); \
RETURN_FALSE; \
}
#define FILE_FROM_ZFILE \
SMB_FETCH_RESOURCE(file, SMBCFILE *, &zfile, PHP_SMBCLIENT_FILE_NAME, le_smbclient_file); \
if (file == NULL) { \
php_error(E_WARNING, PHP_SMBCLIENT_FILE_NAME " not found"); \
RETURN_FALSE; \
}
PHP_FUNCTION(smbclient_state_init)
{
zval *zstate;
zval *zwrkg = NULL;
zval *zuser = NULL;
zval *zpass = NULL;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|zzz", &zstate, &zwrkg, &zuser, &zpass) != SUCCESS) {
RETURN_FALSE;
}
SMB_FETCH_RESOURCE(state, php_smbclient_state *, &zstate, PHP_SMBCLIENT_STATE_NAME, le_smbclient_state);
if (state->ctx == NULL) {
php_error(E_WARNING, "Couldn't init SMB context: context is null");
RETURN_FALSE;
}
if (ctx_init_getauth(zwrkg, &state->wrkg, &state->wrkglen, "workgroup") == 0) {
RETURN_FALSE;
}
if (ctx_init_getauth(zuser, &state->user, &state->userlen, "username") == 0) {
RETURN_FALSE;
}
if (ctx_init_getauth(zpass, &state->pass, &state->passlen, "password") == 0) {
RETURN_FALSE;
}
if (php_smbclient_state_init(state TSRMLS_CC)) {
RETURN_FALSE;
}
RETURN_TRUE;
}
PHP_FUNCTION(smbclient_state_errno)
{
zval *zstate;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstate) != SUCCESS) {
RETURN_LONG(0);
}
SMB_FETCH_RESOURCE(state, php_smbclient_state *, &zstate, PHP_SMBCLIENT_STATE_NAME, le_smbclient_state);
RETURN_LONG(state->err);
}
PHP_FUNCTION(smbclient_state_free)
{
zval *zstate;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zstate) != SUCCESS) {
RETURN_FALSE;
}
SMB_FETCH_RESOURCE(state, php_smbclient_state *, &zstate, PHP_SMBCLIENT_STATE_NAME, le_smbclient_state);
if (state->ctx == NULL) {
#if PHP_MAJOR_VERSION >= 7
zend_list_close(Z_RES_P(zstate));
#else
zend_list_delete(Z_LVAL_P(zstate));
#endif
RETURN_TRUE;
}
if (smbc_free_context(state->ctx, 1) == 0) {
state->ctx = NULL;
#if PHP_MAJOR_VERSION >= 7
zend_list_close(Z_RES_P(zstate));
#else
zend_list_delete(Z_LVAL_P(zstate));
#endif
RETURN_TRUE;
}
switch (state->err = errno) {
case EBUSY: php_error(E_WARNING, "Couldn't destroy smbclient state: connection in use"); break;
case EBADF: php_error(E_WARNING, "Couldn't destroy smbclient state: invalid handle"); break;
default: php_error(E_WARNING, "Couldn't destroy smbclient state: unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_opendir)
{
char *path;
strsize_t path_len;
zval *zstate;
SMBCFILE *dir;
smbc_opendir_fn smbc_opendir;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &zstate, &path, &path_len) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_opendir = smbc_getFunctionOpendir(state->ctx)) == NULL) {
RETURN_FALSE;
}
if ((dir = smbc_opendir(state->ctx, path)) != NULL) {
#if PHP_MAJOR_VERSION >= 7
ZVAL_RES(return_value, zend_register_resource(dir, le_smbclient_file));
#else
ZEND_REGISTER_RESOURCE(return_value, dir, le_smbclient_file);
#endif
return;
}
hide_password(path, path_len);
switch (state->err = errno) {
case EACCES: php_error(E_WARNING, "Couldn't open SMB directory %s: Permission denied", path); break;
case EINVAL: php_error(E_WARNING, "Couldn't open SMB directory %s: Invalid URL", path); break;
case ENOENT: php_error(E_WARNING, "Couldn't open SMB directory %s: Path does not exist", path); break;
case ENOMEM: php_error(E_WARNING, "Couldn't open SMB directory %s: Insufficient memory", path); break;
case ENOTDIR: php_error(E_WARNING, "Couldn't open SMB directory %s: Not a directory", path); break;
case EPERM: php_error(E_WARNING, "Couldn't open SMB directory %s: Workgroup not found", path); break;
case ENODEV: php_error(E_WARNING, "Couldn't open SMB directory %s: Workgroup or server not found", path); break;
default: php_error(E_WARNING, "Couldn't open SMB directory %s: unknown error (%d)", path, errno); break;
}
RETURN_FALSE;
}
static char *
type_to_string (unsigned int type)
{
switch (type) {
case SMBC_WORKGROUP : return "workgroup";
case SMBC_SERVER : return "server";
case SMBC_FILE_SHARE : return "file share";
case SMBC_PRINTER_SHARE : return "printer share";
case SMBC_COMMS_SHARE : return "communication share";
case SMBC_IPC_SHARE : return "IPC share";
case SMBC_DIR : return "directory";
case SMBC_FILE : return "file";
case SMBC_LINK : return "link";
}
return "unknown";
}
PHP_FUNCTION(smbclient_readdir)
{
struct smbc_dirent *dirent;
zval *zstate;
zval *zfile;
SMBCFILE *file;
smbc_readdir_fn smbc_readdir;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &zstate, &zfile) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_readdir = smbc_getFunctionReaddir(state->ctx)) == NULL) {
RETURN_FALSE;
}
errno = 0;
if ((dirent = smbc_readdir(state->ctx, file)) == NULL) {
switch (state->err = errno) {
case 0: RETURN_FALSE;
case EBADF: php_error(E_WARNING, "Couldn't read " PHP_SMBCLIENT_FILE_NAME ": Not a directory resource"); break;
case EINVAL: php_error(E_WARNING, "Couldn't read " PHP_SMBCLIENT_FILE_NAME ": State resource not initialized"); break;
default: php_error(E_WARNING, "Couldn't read " PHP_SMBCLIENT_FILE_NAME ": unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
if (array_init(return_value) != SUCCESS) {
php_error(E_WARNING, "Couldn't initialize array");
RETURN_FALSE;
}
#if PHP_MAJOR_VERSION >= 7
add_assoc_string(return_value, "type", type_to_string(dirent->smbc_type));
add_assoc_stringl(return_value, "comment", dirent->comment, dirent->commentlen);
add_assoc_stringl(return_value, "name", dirent->name, dirent->namelen);
#else
add_assoc_string(return_value, "type", type_to_string(dirent->smbc_type), 1);
add_assoc_stringl(return_value, "comment", dirent->comment, dirent->commentlen, 1);
add_assoc_stringl(return_value, "name", dirent->name, dirent->namelen, 1);
#endif
}
PHP_FUNCTION(smbclient_closedir)
{
zval *zstate;
zval *zfile;
SMBCFILE *file;
smbc_closedir_fn smbc_closedir;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &zstate, &zfile) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_closedir = smbc_getFunctionClosedir(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_closedir(state->ctx, file) == 0) {
#if PHP_MAJOR_VERSION >= 7
zend_list_close(Z_RES_P(zfile));
#else
zend_list_delete(Z_LVAL_P(zfile));
#endif
RETURN_TRUE;
}
switch (state->err = errno) {
case EBADF: php_error(E_WARNING, "Couldn't close " PHP_SMBCLIENT_FILE_NAME ": Not a directory resource"); break;
default: php_error(E_WARNING, "Couldn't close " PHP_SMBCLIENT_FILE_NAME ": unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_rename)
{
char *ourl, *nurl;
strsize_t ourl_len, nurl_len;
zval *zstate_old;
zval *zstate_new;
smbc_rename_fn smbc_rename;
php_smbclient_state *state_old;
php_smbclient_state *state_new;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsrs", &zstate_old, &ourl, &ourl_len, &zstate_new, &nurl, &nurl_len) == FAILURE) {
return;
}
SMB_FETCH_RESOURCE(state_old, php_smbclient_state *, &zstate_old, PHP_SMBCLIENT_STATE_NAME, le_smbclient_state);
SMB_FETCH_RESOURCE(state_new, php_smbclient_state *, &zstate_new, PHP_SMBCLIENT_STATE_NAME, le_smbclient_state);
if (state_old == NULL || state_old->ctx == NULL) {
php_error(E_WARNING, "old " PHP_SMBCLIENT_STATE_NAME " is null");
RETURN_FALSE;
}
if (state_new == NULL || state_new->ctx == NULL) {
php_error(E_WARNING, "new " PHP_SMBCLIENT_STATE_NAME " is null");
RETURN_FALSE;
}
if ((smbc_rename = smbc_getFunctionRename(state_old->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_rename(state_old->ctx, ourl, state_new->ctx, nurl) == 0) {
RETURN_TRUE;
}
hide_password(ourl, ourl_len);
switch (state_old->err = errno) {
case EISDIR: php_error(E_WARNING, "Couldn't rename SMB directory %s: existing url is not a directory", ourl); break;
case EACCES: php_error(E_WARNING, "Couldn't open SMB directory %s: Permission denied", ourl); break;
case EINVAL: php_error(E_WARNING, "Couldn't open SMB directory %s: Invalid URL", ourl); break;
case ENOENT: php_error(E_WARNING, "Couldn't open SMB directory %s: Path does not exist", ourl); break;
case ENOMEM: php_error(E_WARNING, "Couldn't open SMB directory %s: Insufficient memory", ourl); break;
case ENOTDIR: php_error(E_WARNING, "Couldn't open SMB directory %s: Not a directory", ourl); break;
case EPERM: php_error(E_WARNING, "Couldn't open SMB directory %s: Workgroup not found", ourl); break;
case EXDEV: php_error(E_WARNING, "Couldn't open SMB directory %s: Workgroup or server not found", ourl); break;
case EEXIST: php_error(E_WARNING, "Couldn't rename SMB directory %s: new name already exists", ourl); break;
default: php_error(E_WARNING, "Couldn't open SMB directory %s: unknown error (%d)", ourl, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_unlink)
{
char *url;
strsize_t url_len;
zval *zstate;
smbc_unlink_fn smbc_unlink;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &zstate, &url, &url_len) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_unlink = smbc_getFunctionUnlink(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_unlink(state->ctx, url) == 0) {
RETURN_TRUE;
}
hide_password(url, url_len);
switch (state->err = errno) {
case EACCES: php_error(E_WARNING, "Couldn't delete %s: Permission denied", url); break;
case EINVAL: php_error(E_WARNING, "Couldn't delete %s: Invalid URL", url); break;
case ENOENT: php_error(E_WARNING, "Couldn't delete %s: Path does not exist", url); break;
case ENOMEM: php_error(E_WARNING, "Couldn't delete %s: Insufficient memory", url); break;
case EPERM: php_error(E_WARNING, "Couldn't delete %s: Workgroup not found", url); break;
case EISDIR: php_error(E_WARNING, "Couldn't delete %s: It is a Directory (use rmdir instead)", url); break;
case EBUSY: php_error(E_WARNING, "Couldn't delete %s: Device or resource busy", url); break;
default: php_error(E_WARNING, "Couldn't delete %s: unknown error (%d)", url, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_mkdir)
{
char *path = NULL;
strsize_t path_len;
zend_long mode = 0777; /* Same as PHP's native mkdir() */
zval *zstate;
smbc_mkdir_fn smbc_mkdir;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|l", &zstate, &path, &path_len, &mode) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_mkdir = smbc_getFunctionMkdir(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_mkdir(state->ctx, path, (mode_t)mode) == 0) {
RETURN_TRUE;
}
hide_password(path, path_len);
switch (state->err = errno) {
case EACCES: php_error(E_WARNING, "Couldn't create SMB directory %s: Permission denied", path); break;
case EINVAL: php_error(E_WARNING, "Couldn't create SMB directory %s: Invalid URL", path); break;
case ENOENT: php_error(E_WARNING, "Couldn't create SMB directory %s: Path does not exist", path); break;
case ENOMEM: php_error(E_WARNING, "Couldn't create SMB directory %s: Insufficient memory", path); break;
case EEXIST: php_error(E_WARNING, "Couldn't create SMB directory %s: Directory already exists", path); break;
default: php_error(E_WARNING, "Couldn't create SMB directory %s: unknown error (%d)", path, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_rmdir)
{
char *url;
strsize_t url_len;
zval *zstate;
smbc_rmdir_fn smbc_rmdir;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &zstate, &url, &url_len) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_rmdir = smbc_getFunctionRmdir(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_rmdir(state->ctx, url) == 0) {
RETURN_TRUE;
}
hide_password(url, url_len);
switch (state->err = errno) {
case EACCES: php_error(E_WARNING, "Couldn't delete %s: Permission denied", url); break;
case EINVAL: php_error(E_WARNING, "Couldn't delete %s: Invalid URL", url); break;
case ENOENT: php_error(E_WARNING, "Couldn't delete %s: Path does not exist", url); break;
case ENOMEM: php_error(E_WARNING, "Couldn't delete %s: Insufficient memory", url); break;
case EPERM: php_error(E_WARNING, "Couldn't delete %s: Workgroup not found", url); break;
case ENOTEMPTY: php_error(E_WARNING, "Couldn't delete %s: It is not empty", url); break;
default: php_error(E_WARNING, "Couldn't delete %s: unknown error (%d)", url, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_stat)
{
char *file;
struct stat statbuf;
strsize_t file_len;
zval *zstate;
smbc_stat_fn smbc_stat;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &zstate, &file, &file_len) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_stat = smbc_getFunctionStat(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_stat(state->ctx, file, &statbuf) < 0) {
hide_password(file, file_len);
switch (state->err = errno) {
case ENOENT: php_error(E_WARNING, "Couldn't stat %s: Does not exist", file); break;
case EINVAL: php_error(E_WARNING, "Couldn't stat: null URL or smbc_init failed"); break;
case EACCES: php_error(E_WARNING, "Couldn't stat %s: Permission denied", file); break;
case ENOMEM: php_error(E_WARNING, "Couldn't stat %s: Out of memory", file); break;
case ENOTDIR: php_error(E_WARNING, "Couldn't stat %s: Not a directory", file); break;
default: php_error(E_WARNING, "Couldn't stat %s: unknown error (%d)", file, errno); break;
}
RETURN_FALSE;
}
if (array_init(return_value) != SUCCESS) {
php_error(E_WARNING, "Couldn't initialize array");
RETURN_FALSE;
}
add_index_long(return_value, 0, statbuf.st_dev);
add_index_long(return_value, 1, statbuf.st_ino);
add_index_long(return_value, 2, statbuf.st_mode);
add_index_long(return_value, 3, statbuf.st_nlink);
add_index_long(return_value, 4, statbuf.st_uid);
add_index_long(return_value, 5, statbuf.st_gid);
add_index_long(return_value, 6, statbuf.st_rdev);
add_index_long(return_value, 7, statbuf.st_size);
add_index_long(return_value, 8, statbuf.st_atime);
add_index_long(return_value, 9, statbuf.st_mtime);
add_index_long(return_value, 10, statbuf.st_ctime);
add_index_long(return_value, 11, statbuf.st_blksize);
add_index_long(return_value, 12, statbuf.st_blocks);
add_assoc_long(return_value, "dev", statbuf.st_dev);
add_assoc_long(return_value, "ino", statbuf.st_ino);
add_assoc_long(return_value, "mode", statbuf.st_mode);
add_assoc_long(return_value, "nlink", statbuf.st_nlink);
add_assoc_long(return_value, "uid", statbuf.st_uid);
add_assoc_long(return_value, "gid", statbuf.st_gid);
add_assoc_long(return_value, "rdev", statbuf.st_rdev);
add_assoc_long(return_value, "size", statbuf.st_size);
add_assoc_long(return_value, "atime", statbuf.st_atime);
add_assoc_long(return_value, "mtime", statbuf.st_mtime);
add_assoc_long(return_value, "ctime", statbuf.st_ctime);
add_assoc_long(return_value, "blksize", statbuf.st_blksize);
add_assoc_long(return_value, "blocks", statbuf.st_blocks);
}
PHP_FUNCTION(smbclient_fstat)
{
struct stat statbuf;
zval *zstate;
zval *zfile;
SMBCFILE *file;
smbc_fstat_fn smbc_fstat;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &zstate, &zfile) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_fstat = smbc_getFunctionFstat(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_fstat(state->ctx, file, &statbuf) < 0) {
switch (state->err = errno) {
case ENOENT: php_error(E_WARNING, "Couldn't fstat " PHP_SMBCLIENT_FILE_NAME ": Does not exist"); break;
case EINVAL: php_error(E_WARNING, "Couldn't fstat: null resource or smbc_init failed"); break;
case EACCES: php_error(E_WARNING, "Couldn't fstat " PHP_SMBCLIENT_FILE_NAME ": Permission denied"); break;
case ENOMEM: php_error(E_WARNING, "Couldn't fstat " PHP_SMBCLIENT_FILE_NAME ": Out of memory"); break;
case ENOTDIR: php_error(E_WARNING, "Couldn't fstat " PHP_SMBCLIENT_FILE_NAME ": Not a directory"); break;
default: php_error(E_WARNING, "Couldn't fstat " PHP_SMBCLIENT_FILE_NAME ": unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
if (array_init(return_value) != SUCCESS) {
php_error(E_WARNING, "Couldn't initialize array");
RETURN_FALSE;
}
add_index_long(return_value, 0, statbuf.st_dev);
add_index_long(return_value, 1, statbuf.st_ino);
add_index_long(return_value, 2, statbuf.st_mode);
add_index_long(return_value, 3, statbuf.st_nlink);
add_index_long(return_value, 4, statbuf.st_uid);
add_index_long(return_value, 5, statbuf.st_gid);
add_index_long(return_value, 6, statbuf.st_rdev);
add_index_long(return_value, 7, statbuf.st_size);
add_index_long(return_value, 8, statbuf.st_atime);
add_index_long(return_value, 9, statbuf.st_mtime);
add_index_long(return_value, 10, statbuf.st_ctime);
add_index_long(return_value, 11, statbuf.st_blksize);
add_index_long(return_value, 12, statbuf.st_blocks);
add_assoc_long(return_value, "dev", statbuf.st_dev);
add_assoc_long(return_value, "ino", statbuf.st_ino);
add_assoc_long(return_value, "mode", statbuf.st_mode);
add_assoc_long(return_value, "nlink", statbuf.st_nlink);
add_assoc_long(return_value, "uid", statbuf.st_uid);
add_assoc_long(return_value, "gid", statbuf.st_gid);
add_assoc_long(return_value, "rdev", statbuf.st_rdev);
add_assoc_long(return_value, "size", statbuf.st_size);
add_assoc_long(return_value, "atime", statbuf.st_atime);
add_assoc_long(return_value, "mtime", statbuf.st_mtime);
add_assoc_long(return_value, "ctime", statbuf.st_ctime);
add_assoc_long(return_value, "blksize", statbuf.st_blksize);
add_assoc_long(return_value, "blocks", statbuf.st_blocks);
}
int
flagstring_to_smbflags (const char *flags, int flags_len, int *retval TSRMLS_DC)
{
/* Returns 0 on failure, or 1 on success with *retval filled. */
if (flags_len != 1 && flags_len != 2) {
goto err;
}
if (flags_len == 2 && flags[1] != '+') {
goto err;
}
/* For both lengths, add the "core business" flags.
* See php_stream_parse_fopen_modes() in PHP's /main/streams/plain_wrapper.c
* for how PHP's native fopen() translates these flags: */
switch (flags[0]) {
case 'r': *retval = 0; break;
case 'w': *retval = O_CREAT | O_TRUNC; break;
case 'a': *retval = O_CREAT | O_APPEND; break;
case 'x': *retval = O_CREAT | O_EXCL; break;
case 'c': *retval = O_CREAT; break;
default: goto err;
}
/* If length is 1, enforce read-only or write-only: */
if (flags_len == 1) {
*retval |= (*retval == 0) ? O_RDONLY : O_WRONLY;
return 1;
}
/* Length is 2 and this is a '+' mode, so read/write everywhere: */
*retval |= O_RDWR;
return 1;
err:
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid flag string '%s'", flags);
return 0;
}
PHP_FUNCTION(smbclient_open)
{
char *file, *flags;
strsize_t file_len, flags_len;
int smbflags;
zend_long mode = 0666;
zval *zstate;
SMBCFILE *handle;
smbc_open_fn smbc_open;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss|l", &zstate, &file, &file_len, &flags, &flags_len, &mode) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
/* The flagstring is in the same format as the native fopen() uses, so
* one of the characters r, w, a, x, c, optionally followed by a plus.
* Need to translate this to an integer value for smbc_open: */
if (flagstring_to_smbflags(flags, flags_len, &smbflags TSRMLS_CC) == 0) {
RETURN_FALSE;
}
if ((smbc_open = smbc_getFunctionOpen(state->ctx)) == NULL) {
RETURN_FALSE;
}
if ((handle = smbc_open(state->ctx, file, smbflags, mode)) != NULL) {
#if PHP_MAJOR_VERSION >= 7
ZVAL_RES(return_value, zend_register_resource(handle, le_smbclient_file));
#else
ZEND_REGISTER_RESOURCE(return_value, handle, le_smbclient_file);
#endif
return;
}
hide_password(file, file_len);
switch (state->err = errno) {
case ENOMEM: php_error(E_WARNING, "Couldn't open %s: Out of memory", file); break;
case EINVAL: php_error(E_WARNING, "Couldn't open %s: No file?", file); break;
case EEXIST: php_error(E_WARNING, "Couldn't open %s: Pathname already exists and O_CREAT and O_EXECL were specified", file); break;
case EISDIR: php_error(E_WARNING, "Couldn't open %s: Can't write to a directory", file); break;
case EACCES: php_error(E_WARNING, "Couldn't open %s: Access denied", file); break;
case ENODEV: php_error(E_WARNING, "Couldn't open %s: Requested share does not exist", file); break;
case ENOTDIR: php_error(E_WARNING, "Couldn't open %s: Path component isn't a directory", file); break;
case ENOENT: php_error(E_WARNING, "Couldn't open %s: Directory in path doesn't exist", file); break;
default: php_error(E_WARNING, "Couldn't open %s: unknown error (%d)", file, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_creat)
{
char *file;
strsize_t file_len;
zend_long mode = 0666;
zval *zstate;
SMBCFILE *handle;
smbc_creat_fn smbc_creat;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|l", &zstate, &file, &file_len, &mode) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_creat = smbc_getFunctionCreat(state->ctx)) == NULL) {
RETURN_FALSE;
}
if ((handle = smbc_creat(state->ctx, file, (mode_t)mode)) != NULL) {
#if PHP_MAJOR_VERSION >= 7
ZVAL_RES(return_value, zend_register_resource(handle, le_smbclient_file));
#else
ZEND_REGISTER_RESOURCE(return_value, handle, le_smbclient_file);
#endif
return;
}
hide_password(file, file_len);
switch (state->err = errno) {
case ENOMEM: php_error(E_WARNING, "Couldn't create %s: Out of memory", file); break;
case EINVAL: php_error(E_WARNING, "Couldn't create %s: No file?", file); break;
case EEXIST: php_error(E_WARNING, "Couldn't create %s: Pathname already exists and O_CREAT and O_EXECL were specified", file); break;
case EISDIR: php_error(E_WARNING, "Couldn't create %s: Can't write to a directory", file); break;
case EACCES: php_error(E_WARNING, "Couldn't create %s: Access denied", file); break;
case ENODEV: php_error(E_WARNING, "Couldn't create %s: Requested share does not exist", file); break;
case ENOENT: php_error(E_WARNING, "Couldn't create %s: Directory in path doesn't exist", file); break;
default: php_error(E_WARNING, "Couldn't create %s: unknown error (%d)", file, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_read)
{
zend_long count;
zval *zstate;
zval *zfile;
SMBCFILE *file;
smbc_read_fn smbc_read;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrl", &zstate, &zfile, &count) == FAILURE) {
return;
}
if (count < 0) {
php_error(E_WARNING, "Negative byte count: %ld", count);
RETURN_FALSE;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_read = smbc_getFunctionRead(state->ctx)) == NULL) {
RETURN_FALSE;
}
#if PHP_MAJOR_VERSION >= 7
zend_string *buf = zend_string_alloc(count, 0);
if ((ZSTR_LEN(buf) = smbc_read(state->ctx, file, ZSTR_VAL(buf), count)) >= 0) {
RETURN_STR(buf);
#else
void *buf = emalloc(count);
ssize_t nbytes;
if ((nbytes = smbc_read(state->ctx, file, buf, count)) >= 0) {
RETURN_STRINGL(buf, nbytes, 0);
#endif
}
efree(buf);
switch (state->err = errno) {
case EISDIR: php_error(E_WARNING, "Read error: Is a directory"); break;
case EBADF: php_error(E_WARNING, "Read error: Not a valid file resource or not open for reading"); break;
case EINVAL: php_error(E_WARNING, "Read error: Object not suitable for reading or bad buffer"); break;
default: php_error(E_WARNING, "Read error: unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_write)
{
zend_long count = 0;
strsize_t str_len;
char * str;
size_t nwrite;
ssize_t nbytes;
zval *zstate;
zval *zfile;
SMBCFILE *file;
smbc_write_fn smbc_write;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrs|l", &zstate, &zfile, &str, &str_len, &count) == FAILURE) {
return;
}
if (count < 0) {
php_error(E_WARNING, "Negative byte count: %ld", count);
RETURN_FALSE;
}
if (count == 0 || count > str_len) {
nwrite = str_len;
}
else {
nwrite = count;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_write = smbc_getFunctionWrite(state->ctx)) == NULL) {
RETURN_FALSE;
}
if ((nbytes = smbc_write(state->ctx, file, str, nwrite)) >= 0) {
RETURN_LONG(nbytes);
}
switch (state->err = errno) {
case EISDIR: php_error(E_WARNING, "Write error: Is a directory"); break;
case EBADF: php_error(E_WARNING, "Write error: Not a valid file resource or not open for reading"); break;
case EINVAL: php_error(E_WARNING, "Write error: Object not suitable for reading or bad buffer"); break;
case EACCES: php_error(E_WARNING, "Write error: Permission denied"); break;
default: php_error(E_WARNING, "Write error: unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_lseek)
{
zend_long offset, whence, ret;
zval *zstate;
zval *zfile;
SMBCFILE *file;
smbc_lseek_fn smbc_lseek;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrll", &zstate, &zfile, &offset, &whence) == FAILURE) {
return;
}
if ((int)whence != SEEK_SET && (int)whence != SEEK_CUR && (int)whence != SEEK_END) {
php_error(E_WARNING, "Invalid argument for whence");
RETURN_FALSE;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_lseek = smbc_getFunctionLseek(state->ctx)) == NULL) {
RETURN_FALSE;
}
if ((ret = smbc_lseek(state->ctx, file, (off_t)offset, (int)whence)) > -1) {
RETURN_LONG(ret);
}
switch (state->err = errno) {
case EBADF: php_error(E_WARNING, "Couldn't lseek: resource is invalid"); break;
case EINVAL: php_error(E_WARNING, "Couldn't lseek: invalid parameters or not initialized"); break;
default: php_error(E_WARNING, "Couldn't lseek: unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_ftruncate)
{
zend_long offset;
zval *zstate;
zval *zfile;
SMBCFILE *file;
smbc_ftruncate_fn smbc_ftruncate;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rrl", &zstate, &zfile, &offset) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_ftruncate = smbc_getFunctionFtruncate(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_ftruncate(state->ctx, file, offset) == 0) {
RETURN_TRUE;
}
switch (state->err = errno) {
case EBADF: php_error(E_WARNING, "Couldn't ftruncate: resource is invalid"); break;
case EACCES: php_error(E_WARNING, "Couldn't ftruncate: permission denied"); break;
case EINVAL: php_error(E_WARNING, "Couldn't ftruncate: invalid parameters or not initialized"); break;
case ENOMEM: php_error(E_WARNING, "Couldn't ftruncate: out of memory"); break;
default: php_error(E_WARNING, "Couldn't ftruncate: unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_close)
{
zval *zstate;
zval *zfile;
SMBCFILE *file;
smbc_close_fn smbc_close;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &zstate, &zfile) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_close = smbc_getFunctionClose(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_close(state->ctx, file) == 0) {
#if PHP_MAJOR_VERSION >= 7
zend_list_close(Z_RES_P(zfile));
#else
zend_list_delete(Z_LVAL_P(zfile));
#endif
RETURN_TRUE;
}
switch (state->err = errno) {
case EBADF: php_error(E_WARNING, "Close error: Not a valid file resource or not open for reading"); break;
case EINVAL: php_error(E_WARNING, "Close error: State resource not initialized"); break;
default: php_error(E_WARNING, "Close error: unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_chmod)
{
char *file;
strsize_t file_len;
zend_long mode;
zval *zstate;
smbc_chmod_fn smbc_chmod;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsl", &zstate, &file, &file_len, &mode) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_chmod = smbc_getFunctionChmod(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_chmod(state->ctx, file, (mode_t)mode) == 0) {
RETURN_TRUE;
}
hide_password(file, file_len);
switch (state->err = errno) {
case EPERM: php_error(E_WARNING, "Couldn't chmod %s: the effective UID does not match the owner of the file, and is not zero", file); break;
case ENOENT: php_error(E_WARNING, "Couldn't chmod %s: file or directory does not exist", file); break;
case ENOMEM: php_error(E_WARNING, "Couldn't chmod %s: insufficient memory", file); break;
default: php_error(E_WARNING, "Couldn't chmod %s: unknown error (%d)", file, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_utimes)
{
char *file;
strsize_t file_len;
zend_long mtime = -1, atime = -1;
zval *zstate;
struct timeval times[2];
smbc_utimes_fn smbc_utimes;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|ll", &zstate, &file, &file_len, &mtime, &atime) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
times[0].tv_usec = 0; /* times[0] = access time (atime) */
times[1].tv_usec = 0; /* times[1] = write time (mtime) */
/* TODO: we are a bit lazy here about the optional arguments and assume
* that if they are negative, they were omitted. This makes it
* impossible to use legitimate negative timestamps - a rare use-case. */
times[1].tv_sec = (mtime < 0) ? time(NULL) : mtime;
/* If not given, atime defaults to value of mtime: */
times[0].tv_sec = (atime < 0) ? times[1].tv_sec : atime;
if ((smbc_utimes = smbc_getFunctionUtimes(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_utimes(state->ctx, file, times) == 0) {
RETURN_TRUE;
}
hide_password(file, file_len);
switch (state->err = errno) {
case EINVAL: php_error(E_WARNING, "Couldn't set times on %s: the client library is not properly initialized", file); break;
case EPERM: php_error(E_WARNING, "Couldn't set times on %s: permission was denied", file); break;
default: php_error(E_WARNING, "Couldn't set times on %s: unknown error (%d)", file, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_listxattr)
{
char *url, *s, *c;
strsize_t url_len;
char values[1000];
zval *zstate;
smbc_listxattr_fn smbc_listxattr;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &zstate, &url, &url_len) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_listxattr = smbc_getFunctionListxattr(state->ctx)) == NULL) {
RETURN_FALSE;
}
/* This is a bit of a bogus function. Looking in the Samba source, it
* always returns all possible attribute names, regardless of what the
* file system supports or which attributes the file actually has.
* Because this list is static, we can get away with using a fixed
* buffer size.*/
if (smbc_listxattr(state->ctx, url, values, sizeof(values)) >= 0) {
if (array_init(return_value) != SUCCESS) {
php_error(E_WARNING, "Couldn't initialize array");
RETURN_FALSE;
}
/* Each attribute is null-separated, the list itself terminates
* with an empty element (i.e. two null bytes in a row). */
for (s = c = values; c < values + sizeof(values); c++) {
if (*c != '\0') {
continue;
}
/* c and s identical: last element */
if (s == c) {
break;
}
#if PHP_MAJOR_VERSION >= 7
add_next_index_stringl(return_value, s, c - s);
#else
add_next_index_stringl(return_value, s, c - s, 1);
#endif
s = c + 1;
}
return;
}
switch (state->err = errno) {
case EINVAL: php_error(E_WARNING, "Couldn't get xattrs: library not initialized"); break;
case ENOMEM: php_error(E_WARNING, "Couldn't get xattrs: out of memory"); break;
case EPERM: php_error(E_WARNING, "Couldn't get xattrs: permission denied"); break;
case ENOTSUP: php_error(E_WARNING, "Couldn't get xattrs: file system does not support extended attributes"); break;
default: php_error(E_WARNING, "Couldn't get xattrs: unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_getxattr)
{
char *url, *name;
strsize_t url_len, name_len;
int retsize;
char values[1000];
zval *zstate;
smbc_getxattr_fn smbc_getxattr;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &zstate, &url, &url_len, &name, &name_len) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_getxattr = smbc_getFunctionGetxattr(state->ctx)) == NULL) {
RETURN_FALSE;
}
/* TODO: 1000 chars should be enough for everyone...?
* However, doing an initial blank call to determine the response size
* seems wasteful, and vulnerable to a time-of-check, time-of-use
* error. */
if ((retsize = smbc_getxattr(state->ctx, url, name, values, sizeof(values))) >= 0) {
if (retsize > sizeof(values)) {
retsize = sizeof(values);
}
#if PHP_MAJOR_VERSION >= 7
RETURN_STRINGL(values, retsize);
#else
RETURN_STRINGL(values, retsize, 1);
#endif
}
hide_password(url, url_len);
switch (state->err = errno) {
case EINVAL: php_error(E_WARNING, "Couldn't get xattr for %s: library not initialized or incorrect parameter", url); break;
case ENOMEM: php_error(E_WARNING, "Couldn't get xattr for %s: out of memory", url); break;
case EPERM: php_error(E_WARNING, "Couldn't get xattr for %s: permission denied", url); break;
case ENOTSUP: php_error(E_WARNING, "Couldn't get xattr for %s: file system does not support extended attributes", url); break;
default: php_error(E_WARNING, "Couldn't get xattr for %s: unknown error (%d)", url, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_setxattr)
{
char *url, *name, *val;
strsize_t url_len, name_len, val_len;
zend_long flags = 0;
zval *zstate;
smbc_setxattr_fn smbc_setxattr;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsss|l", &zstate, &url, &url_len, &name, &name_len, &val, &val_len, &flags) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_setxattr = smbc_getFunctionSetxattr(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_setxattr(state->ctx, url, name, val, val_len, flags) == 0) {
RETURN_TRUE;
}
hide_password(url, url_len);
switch (state->err = errno) {
case EINVAL: php_error(E_WARNING, "Couldn't set attribute on %s: client library not properly initialized", url); break;
case ENOMEM: php_error(E_WARNING, "Couldn't set attribute on %s: out of memory", url); break;
case EEXIST: php_error(E_WARNING, "Couldn't set attribute on %s: attribute already exists", url); break;
case ENOATTR: php_error(E_WARNING, "Couldn't set attribute on %s: attribute does not exist", url); break;
case ENOTSUP: php_error(E_WARNING, "Couldn't set attribute on %s: not supported by filesystem", url); break;
case EPERM: php_error(E_WARNING, "Couldn't set attribute on %s: permission denied", url); break;
default: php_error(E_WARNING, "Couldn't set attribute on %s: unknown error (%d)", url, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_removexattr)
{
char *url, *name;
strsize_t url_len, name_len;
zval *zstate;
smbc_removexattr_fn smbc_removexattr;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &zstate, &url, &url_len, &name, &name_len) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_removexattr = smbc_getFunctionRemovexattr(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_removexattr(state->ctx, url, name) == 0) {
RETURN_TRUE;
}
hide_password(url, url_len);
switch (state->err = errno) {
case EINVAL: php_error(E_WARNING, "Couldn't remove attribute on %s: client library not properly initialized", url); break;
case ENOMEM: php_error(E_WARNING, "Couldn't remove attribute on %s: out of memory", url); break;
case ENOTSUP: php_error(E_WARNING, "Couldn't remove attribute on %s: not supported by filesystem", url); break;
case EPERM: php_error(E_WARNING, "Couldn't remove attribute on %s: permission denied", url); break;
default: php_error(E_WARNING, "Couldn't remove attribute on %s: unknown error (%d)", url, errno); break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_option_get)
{
zend_long option;
char *ret;
zval *zstate;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zstate, &option) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
switch (option)
{
case SMBCLIENT_OPT_OPEN_SHAREMODE:
RETURN_LONG(smbc_getOptionOpenShareMode(state->ctx));
case SMBCLIENT_OPT_ENCRYPT_LEVEL:
RETURN_LONG(smbc_getOptionSmbEncryptionLevel(state->ctx));
case SMBCLIENT_OPT_CASE_SENSITIVE:
RETURN_BOOL(smbc_getOptionCaseSensitive(state->ctx));
case SMBCLIENT_OPT_BROWSE_MAX_LMB_COUNT:
RETURN_LONG(smbc_getOptionBrowseMaxLmbCount(state->ctx));
case SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES:
RETURN_BOOL(smbc_getOptionUrlEncodeReaddirEntries(state->ctx));
case SMBCLIENT_OPT_USE_KERBEROS:
RETURN_BOOL(smbc_getOptionUseKerberos(state->ctx));
case SMBCLIENT_OPT_FALLBACK_AFTER_KERBEROS:
RETURN_BOOL(smbc_getOptionFallbackAfterKerberos(state->ctx));
/* Reverse the sense of this option, the original is confusing: */
case SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN:
RETURN_BOOL(!(smbc_getOptionNoAutoAnonymousLogin(state->ctx)));
case SMBCLIENT_OPT_USE_CCACHE:
RETURN_BOOL(smbc_getOptionUseCCache(state->ctx));
#ifdef HAVE_SMBC_SETOPTIONUSENTHASH
case SMBCLIENT_OPT_USE_NT_HASH:
RETURN_BOOL(smbc_getOptionUseNTHash(state->ctx));
#endif
#ifdef HAVE_SMBC_SETPORT
case SMBCLIENT_OPT_PORT:
RETURN_LONG(smbc_getPort(state->ctx));
#endif
case SMBCLIENT_OPT_TIMEOUT:
RETURN_LONG(smbc_getTimeout(state->ctx));
case SMBCLIENT_OPT_NETBIOS_NAME:
if ((ret = smbc_getNetbiosName(state->ctx)) == NULL) {
RETURN_EMPTY_STRING();
}
if (strlen(ret) == 0) {
RETURN_EMPTY_STRING();
}
#if PHP_MAJOR_VERSION >= 7
RETURN_STRING(ret);
#else
RETURN_STRING(ret, 1);
#endif
case SMBCLIENT_OPT_WORKGROUP:
if ((ret = smbc_getWorkgroup(state->ctx)) == NULL) {
RETURN_EMPTY_STRING();
}
if (strlen(ret) == 0) {
RETURN_EMPTY_STRING();
}
#if PHP_MAJOR_VERSION >= 7
RETURN_STRING(ret);
#else
RETURN_STRING(ret, 1);
#endif
case SMBCLIENT_OPT_USER:
if ((ret = smbc_getUser(state->ctx)) == NULL) {
RETURN_EMPTY_STRING();
}
if (strlen(ret) == 0) {
RETURN_EMPTY_STRING();
}
#if PHP_MAJOR_VERSION >= 7
RETURN_STRING(ret);
#else
RETURN_STRING(ret, 1);
#endif
}
RETURN_NULL();
}
PHP_FUNCTION(smbclient_option_set)
{
zend_long option, vbool = 0;
zval *zstate;
zval *zvalue;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rlz", &zstate, &option, &zvalue) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
switch (Z_TYPE_P(zvalue))
{
#if PHP_MAJOR_VERSION >= 7
case IS_TRUE:
vbool = 1;
/* no break, fallthrough */
case IS_FALSE:
#else
case IS_BOOL:
vbool = Z_BVAL_P(zvalue);
#endif
switch (option)
{
case SMBCLIENT_OPT_CASE_SENSITIVE:
smbc_setOptionCaseSensitive(state->ctx, vbool);
RETURN_TRUE;
case SMBCLIENT_OPT_URLENCODE_READDIR_ENTRIES:
smbc_setOptionUrlEncodeReaddirEntries(state->ctx, vbool);
RETURN_TRUE;
case SMBCLIENT_OPT_USE_KERBEROS:
smbc_setOptionUseKerberos(state->ctx, vbool);
RETURN_TRUE;
case SMBCLIENT_OPT_FALLBACK_AFTER_KERBEROS:
smbc_setOptionFallbackAfterKerberos(state->ctx, vbool);
RETURN_TRUE;
/* Reverse the sense of this option: */
case SMBCLIENT_OPT_AUTO_ANONYMOUS_LOGIN:
smbc_setOptionNoAutoAnonymousLogin(state->ctx, !(vbool));
RETURN_TRUE;
case SMBCLIENT_OPT_USE_CCACHE:
smbc_setOptionUseCCache(state->ctx, vbool);
RETURN_TRUE;
#ifdef HAVE_SMBC_SETOPTIONUSENTHASH
case SMBCLIENT_OPT_USE_NT_HASH:
smbc_setOptionUseNTHash(state->ctx, vbool);
RETURN_TRUE;
#endif
}
break;
case IS_LONG:
switch (option)
{
case SMBCLIENT_OPT_OPEN_SHAREMODE:
smbc_setOptionOpenShareMode(state->ctx, Z_LVAL_P(zvalue));
RETURN_TRUE;
case SMBCLIENT_OPT_ENCRYPT_LEVEL:
smbc_setOptionSmbEncryptionLevel(state->ctx, Z_LVAL_P(zvalue));
RETURN_TRUE;
case SMBCLIENT_OPT_BROWSE_MAX_LMB_COUNT:
smbc_setOptionBrowseMaxLmbCount(state->ctx, Z_LVAL_P(zvalue));
RETURN_TRUE;
#ifdef HAVE_SMBC_SETPORT
case SMBCLIENT_OPT_PORT:
smbc_setPort(state->ctx, Z_LVAL_P(zvalue));
RETURN_TRUE;
#endif
case SMBCLIENT_OPT_TIMEOUT:
smbc_setTimeout(state->ctx, Z_LVAL_P(zvalue));
RETURN_TRUE;
}
break;
case IS_STRING:
switch (option)
{
case SMBCLIENT_OPT_NETBIOS_NAME:
smbc_setNetbiosName(state->ctx, Z_STRVAL_P(zvalue));
RETURN_TRUE;
/* For the next two options, update our state object as well: */
case SMBCLIENT_OPT_WORKGROUP:
if (ctx_init_getauth(zvalue, &state->wrkg, &state->wrkglen, "workgroup") == 0) {
RETURN_FALSE;
}
smbc_setWorkgroup(state->ctx, Z_STRVAL_P(zvalue));
RETURN_TRUE;
case SMBCLIENT_OPT_USER:
if (ctx_init_getauth(zvalue, &state->user, &state->userlen, "username") == 0) {
RETURN_FALSE;
}
smbc_setUser(state->ctx, Z_STRVAL_P(zvalue));
RETURN_TRUE;
}
break;
}
RETURN_FALSE;
}
PHP_FUNCTION(smbclient_statvfs)
{
char *url;
strsize_t url_len;
zval *zstate;
struct statvfs st;
smbc_statvfs_fn smbc_statvfs;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &zstate, &url, &url_len) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
if ((smbc_statvfs = smbc_getFunctionStatVFS(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_statvfs(state->ctx, url, &st) != 0) {
hide_password(url, url_len);
switch (state->err = errno) {
case EBADF: php_error(E_WARNING, "Couldn't statvfs %s: bad file descriptor", url); break;
case EACCES: php_error(E_WARNING, "Couldn't statvfs %s: permission denied", url); break;
case EINVAL: php_error(E_WARNING, "Couldn't statvfs %s: library not initalized or otherwise invalid", url); break;
case ENOMEM: php_error(E_WARNING, "Couldn't statvfs %s: out of memory", url); break;
default: php_error(E_WARNING, "Couldn't statvfs %s: unknown error (%d)", url, errno); break;
}
RETURN_FALSE;
}
if (array_init(return_value) != SUCCESS) {
php_error(E_WARNING, "Couldn't initialize array");
RETURN_FALSE;
}
add_assoc_long(return_value, "bsize", st.f_bsize);
add_assoc_long(return_value, "frsize", st.f_frsize);
add_assoc_long(return_value, "blocks", st.f_blocks);
add_assoc_long(return_value, "bfree", st.f_bfree);
add_assoc_long(return_value, "bavail", st.f_bavail);
add_assoc_long(return_value, "files", st.f_files);
add_assoc_long(return_value, "ffree", st.f_ffree);
add_assoc_long(return_value, "favail", st.f_favail);
add_assoc_long(return_value, "fsid", st.f_fsid);
add_assoc_long(return_value, "flag", st.f_flag);
add_assoc_long(return_value, "namemax", st.f_namemax);
}
PHP_FUNCTION(smbclient_fstatvfs)
{
zval *zstate;
zval *zfile;
SMBCFILE *file;
struct statvfs st;
smbc_fstatvfs_fn smbc_fstatvfs;
php_smbclient_state *state;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rr", &zstate, &zfile) == FAILURE) {
return;
}
STATE_FROM_ZSTATE;
FILE_FROM_ZFILE;
if ((smbc_fstatvfs = smbc_getFunctionFstatVFS(state->ctx)) == NULL) {
RETURN_FALSE;
}
if (smbc_fstatvfs(state->ctx, file, &st) != 0) {
switch (state->err = errno) {
case EBADF: php_error(E_WARNING, "Couldn't fstatvfs: bad file descriptor"); break;
case EACCES: php_error(E_WARNING, "Couldn't fstatvfs: permission denied"); break;
case EINVAL: php_error(E_WARNING, "Couldn't fstatvfs: library not initalized or otherwise invalid"); break;
case ENOMEM: php_error(E_WARNING, "Couldn't fstatvfs: out of memory"); break;
default: php_error(E_WARNING, "Couldn't fstatvfs: unknown error (%d)", errno); break;
}
RETURN_FALSE;
}
if (array_init(return_value) != SUCCESS) {
php_error(E_WARNING, "Couldn't initialize array");
RETURN_FALSE;
}
add_assoc_long(return_value, "bsize", st.f_bsize);
add_assoc_long(return_value, "frsize", st.f_frsize);
add_assoc_long(return_value, "blocks", st.f_blocks);
add_assoc_long(return_value, "bfree", st.f_bfree);
add_assoc_long(return_value, "bavail", st.f_bavail);
add_assoc_long(return_value, "files", st.f_files);
add_assoc_long(return_value, "ffree", st.f_ffree);
add_assoc_long(return_value, "favail", st.f_favail);
add_assoc_long(return_value, "fsid", st.f_fsid);
add_assoc_long(return_value, "flag", st.f_flag);
add_assoc_long(return_value, "namemax", st.f_namemax);
}
smbclient-0.8.0/smb_streams.c 0000664 0001750 0001750 00000036356 12665077535 016377 0 ustar eduardok eduardok /* ------------------------------------------------------------------
* This file is part of libsmbclient-php: Samba bindings for PHP.
* Libsmbclient-php is licensed under the BSD 2-clause license:
* ------------------------------------------------------------------
*
* Copyright (c) 2003, Matthew Sachs
* 2009 - 2014, Eduardo Bacchi Kienetz
* 2013 - 2015, Alfred Klomp
* 2015, Remi Collet
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* ------------------------------------------------------------------
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "ext/standard/url.h"
#include "ext/standard/info.h"
#include "ext/standard/php_filestat.h"
#include "php_smbclient.h"
#include
#define STREAM_DATA_FROM_STREAM() \
php_smb_stream_data *self = (php_smb_stream_data *) stream->abstract;
typedef struct _php_smb_stream_data {
php_smbclient_state *state;
SMBCFILE *handle;
/* pointers cache for multiple call */
smbc_read_fn smbc_read;
smbc_readdir_fn smbc_readdir;
smbc_write_fn smbc_write;
smbc_lseek_fn smbc_lseek;
} php_smb_stream_data;
static int php_smb_ops_close(php_stream *stream, int close_handle TSRMLS_DC)
{
smbc_close_fn smbc_close;
STREAM_DATA_FROM_STREAM();
if (!self) {
return EOF;
}
if (close_handle) {
if (self->handle) {
smbc_close = smbc_getFunctionClose(self->state->ctx);
if (smbc_close) {
smbc_close(self->state->ctx, self->handle);
}
self->handle = NULL;
}
}
php_smbclient_state_free(self->state TSRMLS_CC);
efree(self);
stream->abstract = NULL;
return EOF;
}
static int php_smb_ops_flush(php_stream *stream TSRMLS_DC)
{
return 0;
}
static size_t php_smb_ops_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
{
ssize_t n = 0;
STREAM_DATA_FROM_STREAM();
if (!self || !self->handle) {
return 0;
}
if (!self->smbc_read) {
self->smbc_read = smbc_getFunctionRead(self->state->ctx);
}
if (self->smbc_read) {
n = self->smbc_read(self->state->ctx, self->handle, buf, count);
}
/* cast count to signed value to avoid possibly negative n being cast to unsigned value */
if (n == 0 || n < (ssize_t)count) {
stream->eof = 1;
}
return (n < 1 ? 0 : (size_t)n);
}
static size_t php_smb_ops_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC)
{
size_t len = 0;
STREAM_DATA_FROM_STREAM();
if (!self || !self->handle) {
return 0;
}
if (!self->smbc_write) {
self->smbc_write = smbc_getFunctionWrite(self->state->ctx);
}
if (self->smbc_write) {
len = self->smbc_write(self->state->ctx, self->handle, buf, count);
}
return len;
}
static int php_smb_ops_stat(php_stream *stream, php_stream_statbuf *ssb TSRMLS_DC) /* {{{ */
{
smbc_fstat_fn smbc_fstat;
STREAM_DATA_FROM_STREAM();
if (!self || !self->handle) {
return -1;
}
if ((smbc_fstat = smbc_getFunctionFstat(self->state->ctx)) == NULL) {
return -1;
}
if (smbc_fstat(self->state->ctx, self->handle, &ssb->sb) < 0) {
return -1;
}
return 0;
}
static int php_smb_ops_seek(php_stream *stream, off_t offset, int whence, off_t *newoffset TSRMLS_DC)
{
STREAM_DATA_FROM_STREAM();
if (!self || !self->handle) {
return -1;
}
if (!self->smbc_lseek) {
self->smbc_lseek = smbc_getFunctionLseek(self->state->ctx);
}
if (self->smbc_lseek) {
*newoffset = self->smbc_lseek(self->state->ctx, self->handle, offset, whence);
return 0;
}
return -1;
}
static php_stream_ops php_stream_smbio_ops = {
php_smb_ops_write,
php_smb_ops_read,
php_smb_ops_close,
php_smb_ops_flush,
"smb",
php_smb_ops_seek,
NULL, /* cast */
php_smb_ops_stat,
NULL /* set_option */
};
static php_stream *
php_stream_smb_opener(
php_stream_wrapper *wrapper,
#if PHP_VERSION_ID < 50600
char *path,
char *mode,
#else
const char *path,
const char *mode,
#endif
int options,
#if PHP_MAJOR_VERSION < 7
char **opened_path,
#else
zend_string **opened_path,
#endif
php_stream_context *context
STREAMS_DC TSRMLS_DC)
{
php_smbclient_state *state;
int smbflags;
long smbmode = 0666;
smbc_open_fn smbc_open;
SMBCFILE *handle;
php_smb_stream_data *self;
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return NULL;
}
/* File */
if (!strcmp(mode, "wb")) {
mode = "w";
} else if (!strcmp(mode, "rb")) {
mode = "r";
}
if (flagstring_to_smbflags(mode, strlen(mode), &smbflags TSRMLS_CC) == 0) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
if ((smbc_open = smbc_getFunctionOpen(state->ctx)) == NULL) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
if ((handle = smbc_open(state->ctx, path, smbflags, smbmode)) == NULL) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
self = ecalloc(sizeof(*self), 1);
self->state = state;
self->handle = handle;
return php_stream_alloc(&php_stream_smbio_ops, self, NULL, mode);
}
static int
php_stream_smb_unlink(
php_stream_wrapper *wrapper,
#if PHP_VERSION_ID < 50600
char *url,
#else
const char *url,
#endif
int options,
php_stream_context *context
TSRMLS_DC)
{
php_smbclient_state *state;
smbc_unlink_fn smbc_unlink;
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return 0;
}
/* Unlink */
if ((smbc_unlink = smbc_getFunctionUnlink(state->ctx)) == NULL) {
if (options & REPORT_ERRORS) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unlink not supported");
}
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
if (smbc_unlink(state->ctx, url) == 0) {
php_smbclient_state_free(state TSRMLS_CC);
return 1;
}
if (options & REPORT_ERRORS) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unlink fails: %s", strerror(errno));
}
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
static int
php_stream_smb_mkdir(
php_stream_wrapper *wrapper,
#if PHP_VERSION_ID < 50600
char *url,
#else
const char *url,
#endif
int mode,
int options,
php_stream_context *context
TSRMLS_DC)
{
php_smbclient_state *state;
smbc_mkdir_fn smbc_mkdir;
if (options & PHP_STREAM_MKDIR_RECURSIVE) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Recursive mkdir not supported");
return 0;
}
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return 0;
}
/* Mkdir */
if ((smbc_mkdir = smbc_getFunctionMkdir(state->ctx)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Mkdir not supported");
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
if (smbc_mkdir(state->ctx, url, (mode_t)mode) == 0) {
php_smbclient_state_free(state TSRMLS_CC);
return 1;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Mkdir fails: %s", strerror(errno));
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
static int
php_stream_smb_rmdir(
php_stream_wrapper *wrapper,
#if PHP_VERSION_ID < 50600
char *url,
#else
const char *url,
#endif
int options,
php_stream_context *context
TSRMLS_DC)
{
php_smbclient_state *state;
smbc_rmdir_fn smbc_rmdir;
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return 0;
}
/* Rmdir */
if ((smbc_rmdir = smbc_getFunctionRmdir(state->ctx)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Rmdir not supported");
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
if (smbc_rmdir(state->ctx, url) == 0) {
php_smbclient_state_free(state TSRMLS_CC);
return 1;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Rmdir fails: %s", strerror(errno));
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
static int
php_stream_smb_rename(
php_stream_wrapper *wrapper,
#if PHP_VERSION_ID < 50600
char *url_from,
char *url_to,
#else
const char *url_from,
const char *url_to,
#endif
int options,
php_stream_context *context
TSRMLS_DC)
{
php_smbclient_state *state;
smbc_rename_fn smbc_rename;
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return 0;
}
if ((smbc_rename = smbc_getFunctionRename(state->ctx)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Rename not supported");
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
if (smbc_rename(state->ctx, url_from, state->ctx, url_to) == 0) {
php_smbclient_state_free(state TSRMLS_CC);
return 1;
}
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Rename fails: %s", strerror(errno));
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
static int php_smbdir_ops_close(php_stream *stream, int close_handle TSRMLS_DC)
{
smbc_closedir_fn smbc_closedir;
STREAM_DATA_FROM_STREAM();
if (close_handle) {
if (self->handle) {
smbc_closedir = smbc_getFunctionClosedir(self->state->ctx);
if (smbc_closedir) {
smbc_closedir(self->state->ctx, self->handle);
}
self->handle = NULL;
}
}
php_smbclient_state_free(self->state TSRMLS_CC);
efree(self);
stream->abstract = NULL;
return EOF;
}
static size_t php_smbdir_ops_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
{
struct smbc_dirent *dirent;
php_stream_dirent *ent = (php_stream_dirent*)buf;
STREAM_DATA_FROM_STREAM();
if (!self || !self->handle) {
return 0;
}
/* avoid problems if someone mis-uses the stream */
if (count != sizeof(php_stream_dirent)) {
return 0;
}
if (!self->smbc_readdir) {
self->smbc_readdir = smbc_getFunctionReaddir(self->state->ctx);
}
if (self->smbc_readdir) {
if ((dirent = self->smbc_readdir(self->state->ctx, self->handle)) != NULL) {
PHP_STRLCPY(ent->d_name, dirent->name, sizeof(ent->d_name), dirent->namelen);
return sizeof(php_stream_dirent);
}
}
stream->eof = 1;
return 0;
}
static php_stream_ops php_stream_smbdir_ops = {
NULL,
php_smbdir_ops_read,
php_smbdir_ops_close,
NULL,
"smbdir",
NULL, /* rewind */
NULL, /* cast */
NULL, /* stat */
NULL /* set_option */
};
static php_stream *
php_stream_smbdir_opener(
php_stream_wrapper *wrapper,
#if PHP_VERSION_ID < 50600
char *path,
char *mode,
#else
const char *path,
const char *mode,
#endif
int options,
#if PHP_MAJOR_VERSION < 7
char **opened_path,
#else
zend_string **opened_path,
#endif
php_stream_context *context
STREAMS_DC TSRMLS_DC)
{
php_smbclient_state *state;
smbc_opendir_fn smbc_opendir;
SMBCFILE *handle;
php_smb_stream_data *self;
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return NULL;
}
/* Directory */
if ((smbc_opendir = smbc_getFunctionOpendir(state->ctx)) == NULL) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
if ((handle = smbc_opendir(state->ctx, path)) == NULL) {
php_smbclient_state_free(state TSRMLS_CC);
return NULL;
}
self = ecalloc(sizeof(*self), 1);
self->state = state;
self->handle = handle;
return php_stream_alloc(&php_stream_smbdir_ops, self, NULL, mode);
}
static int
php_stream_smb_stat(
php_stream_wrapper *wrapper,
#if PHP_VERSION_ID < 50600
char *url,
#else
const char *url,
#endif
int flags,
php_stream_statbuf *ssb,
php_stream_context *context
TSRMLS_DC)
{
php_smbclient_state *state;
smbc_stat_fn smbc_stat;
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return 0;
}
/* Stat */
if ((smbc_stat = smbc_getFunctionStat(state->ctx)) == NULL) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "Stat not supported");
php_smbclient_state_free(state TSRMLS_CC);
return -1;
}
if (smbc_stat(state->ctx, url, &ssb->sb) >= 0) {
php_smbclient_state_free(state TSRMLS_CC);
return 0;
}
/* dont display error as PHP use this method internally to check if file exists */
php_smbclient_state_free(state TSRMLS_CC);
return -1;
}
#if PHP_VERSION_ID >= 50400
static int
php_stream_smb_metadata(
php_stream_wrapper *wrapper,
#if PHP_VERSION_ID < 50600
char *url,
#else
const char *url,
#endif
int option,
void *value,
php_stream_context *context
TSRMLS_DC)
{
php_smbclient_state *state;
smbc_chmod_fn smbc_chmod;
smbc_open_fn smbc_open;
smbc_utimes_fn smbc_utimes;
smbc_close_fn smbc_close;
mode_t mode;
struct utimbuf *newtime;
struct timeval times[2];
SMBCFILE *handle;
int ret = 0;
switch(option) {
case PHP_STREAM_META_TOUCH:
newtime = (struct utimbuf *)value;
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return 0;
}
/* Create + Utimes */
if ((smbc_open = smbc_getFunctionOpen(state->ctx)) == NULL
|| (smbc_close = smbc_getFunctionClose(state->ctx)) == NULL
|| (smbc_utimes = smbc_getFunctionUtimes(state->ctx)) == NULL) {
ret = -1;
break;
}
/* Create can fail if file exists, ignore result */
handle = smbc_open(state->ctx, url, O_EXCL|O_CREAT, 0666);
if (handle) {
smbc_close(state->ctx, handle);
}
if (newtime) {
times[0].tv_usec = 0;
times[0].tv_sec = newtime->actime;
times[1].tv_usec = 0;
times[1].tv_sec = newtime->modtime;
ret = smbc_utimes(state->ctx, url, times);
}
break;
case PHP_STREAM_META_ACCESS:
mode = (mode_t)*(long *)value;
/* Context */
state = php_smbclient_state_new(context, 1 TSRMLS_CC);
if (!state) {
return 0;
}
/* Chmod */
if ((smbc_chmod = smbc_getFunctionChmod(state->ctx)) == NULL) {
ret = -1;
break;
}
ret = smbc_chmod(state->ctx, url, (mode_t)mode);
break;
default:
php_error_docref1(NULL TSRMLS_CC, url, E_WARNING, "Unknown option %d for stream_metadata", option);
return 0;
}
php_smbclient_state_free(state TSRMLS_CC);
if (ret == -1) {
php_error_docref1(NULL TSRMLS_CC, url, E_WARNING, "Operation failed: %s", strerror(errno));
return 0;
}
php_clear_stat_cache(0, NULL, 0 TSRMLS_CC);
return 1;
}
#endif
static php_stream_wrapper_ops smb_stream_wops = {
php_stream_smb_opener,
NULL, /* close */
NULL, /* fstat */
php_stream_smb_stat,
php_stream_smbdir_opener,
"smb",
php_stream_smb_unlink,
php_stream_smb_rename,
php_stream_smb_mkdir,
php_stream_smb_rmdir
#if PHP_VERSION_ID >= 50400
, php_stream_smb_metadata
#endif
};
php_stream_wrapper php_stream_smb_wrapper = {
&smb_stream_wops,
NULL,
1 /* is_url */
};
smbclient-0.8.0/LICENSE 0000664 0001750 0001750 00000002640 12665077535 014706 0 ustar eduardok eduardok Copyright (c) 2003, Matthew Sachs
2009 - 2014, Eduardo Bacchi Kienetz
2013 - 2015, Alfred Klomp
2015, Remi Collet
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
smbclient-0.8.0/README.md 0000664 0001750 0001750 00000062141 12665077535 015162 0 ustar eduardok eduardok 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.
[](https://travis-ci.org/eduardok/libsmbclient-php)
Getting started
---------------
### Installation from PECL
```sh
pecl install smbclient
```
### Binary package installation
Some distribution provide binary package:
* RPM for Fedora / RHEL / CentOS: [php-smbclient](https://apps.fedoraproject.org/packages/php-smbclient)
### Installation from sources
- Download a [release tarball](https://github.com/eduardok/libsmbclient-php/releases) or check out the source code using git:
```sh
git clone git://github.com/eduardok/libsmbclient-php.git
```
- phpize it:
```sh
cd libsmbclient-php ; phpize
```
- Build the module
```sh
./configure
make
```
- As root install the module into the extensions directory:
```sh
sudo make install
```
- Or for packaging purposes, install to a specific root directory:
```sh
make install INSTALL_ROOT=/tmp/smbc
```
- Activate libsmbclient-php in php.ini:
```sh
extension="smbclient.so"
```
Contributions and bug reports
-----------------------------
If you encounter a bug or want to contribute, please file an [issue](https://github.com/eduardok/libsmbclient-php/issues) at GitHub.
Sending pull requests on GitHub is the preferred method of contributing code, because Travis CI will automatically build and test your pull request.
There is also a defunct [mailing list](http://groups.google.com/group/libsmbclient-php).
## License
Since version 0.7.0, libsmbclient-php is licensed under the [BSD 2-clause](http://opensource.org/licenses/BSD-2-Clause) license.
See [Issue #15](https://github.com/eduardok/libsmbclient-php/issues/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](http://www.php.net/license/2_02.txt).
## 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`](http://php.net/manual/en/function.rawurlencode.php) 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
```php
string smbclient_version ( )
```
Returns libsmbclient-php's own version string.
### smbclient_library_version
```php
string smbclient_library_version ( )
```
Returns libsmbclient's version string, which is the same as the Samba version string.
### smbclient_state_new
```php
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_option_set
```php
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
```php
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
```php
bool smbclient_state_init ( resource $state [, string $workgroup = null [, string $username = null [, string $password = null ] ] ] )
```
Initialize the smbclient state resource.
Returns `true` on success, `false` 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
```php
bool smbclient_state_free ( resource $state )
```
Release the state resource passed to it.
Returns `true` on success, `false` on failure.
### smbclient_state_errno
```php
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
```php
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
```php
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:
```php
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
```php
bool smbclient_closedir ( resource $state, resource $dir )
```
Closes a directory resource obtained with `smbclient_opendir`.
Returns `true` on success, `false` on failure.
### smbclient_rename
```php
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
```php
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
```php
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](http://php.net/manual/en/function.umask.php)).
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
```php
bool smbclient_rmdir ( resource $state, string $uri )
```
Deletes the given directory if empty.
Returns `true` on success, `false` on failure.
### smbclient_stat
```php
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`](http://php.net/manual/en/function.stat.php).
See that manual for a complete description.
### smbclient_fstat
```php
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`](http://php.net/manual/en/function.stat.php).
See that manual for a complete description.
### smbclient_open
```php
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](http://php.net/manual/en/function.umask.php)) 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`](http://php.net/manual/en/function.fopen.php).
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
```php
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
```php
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
```php
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 contents 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
```php
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`](http://php.net/manual/en/function.fseek.php):
* `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
```php
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
```php
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
```php
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
```php
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
```php
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
```php
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](http://msdn.microsoft.com/en-us/library/cc246322.aspx), query the `system.dos_attr.mode` key.
### smbclient_setxattr
```php
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
```php
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
```php
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
```php
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.
```php
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
tests