smb.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. ###################################################################
  3. # smb.php
  4. # This class implements a SMB stream wrapper based on 'smbclient'
  5. #
  6. # Date: lun oct 22 10:35:35 CEST 2007
  7. #
  8. # Homepage: http://www.phpclasses.org/smb4php
  9. #
  10. # Copyright (c) 2007 Victor M. Varela <vmvarela@gmail.com>
  11. #
  12. # This program is free software; you can redistribute it and/or
  13. # modify it under the terms of the GNU General Public License
  14. # as published by the Free Software Foundation; either version 2
  15. # of the License, or (at your option) any later version.
  16. #
  17. # This program is distributed in the hope that it will be useful,
  18. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. # GNU General Public License for more details.
  21. #
  22. ###################################################################
  23. define ('SMB4PHP_VERSION', '0.8');
  24. ###################################################################
  25. # CONFIGURATION SECTION - Change for your needs
  26. ###################################################################
  27. define ('SMB4PHP_SMBCLIENT', 'smbclient');
  28. define ('SMB4PHP_SMBOPTIONS', 'TCP_NODELAY IPTOS_LOWDELAY SO_KEEPALIVE SO_RCVBUF=8192 SO_SNDBUF=8192');
  29. define ('SMB4PHP_AUTHMODE', 'arg'); # set to 'env' to use USER enviroment variable
  30. ###################################################################
  31. # SMB - commands that does not need an instance
  32. ###################################################################
  33. $GLOBALS['__smb_cache'] = array ('stat' => array (), 'dir' => array ());
  34. class smb {
  35. function parse_url ($url) {
  36. $pu = parse_url (trim($url));
  37. foreach (array ('domain', 'user', 'pass', 'host', 'port', 'path') as $i)
  38. if (! isset($pu[$i])) $pu[$i] = '';
  39. if (count ($userdomain = explode (';', urldecode ($pu['user']))) > 1)
  40. @list ($pu['domain'], $pu['user']) = $userdomain;
  41. $path = preg_replace (array ('/^\//', '/\/$/'), '', urldecode ($pu['path']));
  42. list ($pu['share'], $pu['path']) = (preg_match ('/^([^\/]+)\/(.*)/', $path, $regs))
  43. ? array ($regs[1], preg_replace ('/\//', '\\', $regs[2]))
  44. : array ($path, '');
  45. $pu['type'] = $pu['path'] ? 'path' : ($pu['share'] ? 'share' : ($pu['host'] ? 'host' : '**error**'));
  46. if (! ($pu['port'] = intval(@$pu['port']))) $pu['port'] = 139;
  47. return $pu;
  48. }
  49. function look ($purl) {
  50. return smb::client ('-L ' . escapeshellarg ($purl['host']), $purl);
  51. }
  52. function execute ($command, $purl) {
  53. return smb::client ('-d 0 '
  54. . escapeshellarg ('//' . $purl['host'] . '/' . $purl['share'])
  55. . ' -c ' . escapeshellarg ($command), $purl
  56. );
  57. }
  58. function client ($params, $purl) {
  59. static $regexp = array (
  60. '^added interface ip=(.*) bcast=(.*) nmask=(.*)$' => 'skip',
  61. 'Anonymous login successful' => 'skip',
  62. '^Domain=\[(.*)\] OS=\[(.*)\] Server=\[(.*)\]$' => 'skip',
  63. '^\tSharename[ ]+Type[ ]+Comment$' => 'shares',
  64. '^\t---------[ ]+----[ ]+-------$' => 'skip',
  65. '^\tServer [ ]+Comment$' => 'servers',
  66. '^\t---------[ ]+-------$' => 'skip',
  67. '^\tWorkgroup[ ]+Master$' => 'workg',
  68. '^\t(.*)[ ]+(Disk|IPC)[ ]+IPC.*$' => 'skip',
  69. '^\tIPC\\\$(.*)[ ]+IPC' => 'skip',
  70. '^\t(.*)[ ]+(Disk)[ ]+(.*)$' => 'share',
  71. '^\t(.*)[ ]+(Printer)[ ]+(.*)$' => 'skip',
  72. '([0-9]+) blocks of size ([0-9]+)\. ([0-9]+) blocks available' => 'skip',
  73. 'Got a positive name query response from ' => 'skip',
  74. '^(session setup failed): (.*)$' => 'error',
  75. '^(.*): ERRSRV - ERRbadpw' => 'error',
  76. '^Error returning browse list: (.*)$' => 'error',
  77. '^tree connect failed: (.*)$' => 'error',
  78. '^(Connection to .* failed)$' => 'error',
  79. '^NT_STATUS_(.*) ' => 'error',
  80. '^NT_STATUS_(.*)\$' => 'error',
  81. 'ERRDOS - ERRbadpath \((.*).\)' => 'error',
  82. 'cd (.*): (.*)$' => 'error',
  83. '^cd (.*): NT_STATUS_(.*)' => 'error',
  84. '^\t(.*)$' => 'srvorwg',
  85. '^([0-9]+)[ ]+([0-9]+)[ ]+(.*)$' => 'skip',
  86. '^Job ([0-9]+) cancelled' => 'skip',
  87. '^[ ]+(.*)[ ]+([0-9]+)[ ]+(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[ ](Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[ ]+([0-9]+)[ ]+([0-9]{2}:[0-9]{2}:[0-9]{2})[ ]([0-9]{4})$' => 'files',
  88. '^message start: ERRSRV - (ERRmsgoff)' => 'error'
  89. );
  90. if (SMB4PHP_AUTHMODE == 'env') {
  91. putenv("USER={$purl['user']}%{$purl['pass']}");
  92. $auth = '';
  93. } else {
  94. $auth = ($purl['user'] <> '' ? (' -U ' . escapeshellarg ($purl['user'] . '%' . $purl['pass'])) : '');
  95. }
  96. if ($purl['domain'] <> '') {
  97. $auth .= ' -W ' . escapeshellarg ($purl['domain']);
  98. }
  99. $port = ($purl['port'] <> 139 ? ' -p ' . escapeshellarg ($purl['port']) : '');
  100. $options = '-O ' . escapeshellarg(SMB4PHP_SMBOPTIONS);
  101. $output = popen (SMB4PHP_SMBCLIENT." -N {$auth} {$options} {$port} {$options} {$params} 2>/dev/null", 'r');
  102. $info = array ();
  103. $info['info']= array ();
  104. while ($line = fgets ($output, 4096)) {
  105. list ($tag, $regs, $i) = array ('skip', array (), array ());
  106. reset ($regexp);
  107. foreach ($regexp as $r => $t) if (preg_match ('/'.$r.'/', $line, $regs)) {
  108. $tag = $t;
  109. break;
  110. }
  111. switch ($tag) {
  112. case 'skip': continue;
  113. case 'shares': $mode = 'shares'; break;
  114. case 'servers': $mode = 'servers'; break;
  115. case 'workg': $mode = 'workgroups'; break;
  116. case 'share':
  117. list($name, $type) = array (
  118. trim(substr($line, 1, 15)),
  119. trim(strtolower(substr($line, 17, 10)))
  120. );
  121. $i = ($type <> 'disk' && preg_match('/^(.*) Disk/', $line, $regs))
  122. ? array(trim($regs[1]), 'disk')
  123. : array($name, 'disk');
  124. break;
  125. case 'srvorwg':
  126. list ($name, $master) = array (
  127. strtolower(trim(substr($line,1,21))),
  128. strtolower(trim(substr($line, 22)))
  129. );
  130. $i = ($mode == 'servers') ? array ($name, "server") : array ($name, "workgroup", $master);
  131. break;
  132. case 'files':
  133. list ($attr, $name) = preg_match ("/^(.*)[ ]+([D|A|H|S|R]+)$/", trim ($regs[1]), $regs2)
  134. ? array (trim ($regs2[2]), trim ($regs2[1]))
  135. : array ('', trim ($regs[1]));
  136. list ($his, $im) = array (
  137. explode(':', $regs[6]), 1 + strpos("JanFebMarAprMayJunJulAugSepOctNovDec", $regs[4]) / 3);
  138. $i = ($name <> '.' && $name <> '..')
  139. ? array (
  140. $name,
  141. (strpos($attr,'D') === FALSE) ? 'file' : 'folder',
  142. 'attr' => $attr,
  143. 'size' => intval($regs[2]),
  144. 'time' => mktime ($his[0], $his[1], $his[2], $im, $regs[5], $regs[7])
  145. )
  146. : array();
  147. break;
  148. case 'error':
  149. if(substr($regs[0],0,22)=='NT_STATUS_NO_SUCH_FILE'){
  150. return false;
  151. }elseif(substr($regs[0],0,31)=='NT_STATUS_OBJECT_NAME_COLLISION'){
  152. return false;
  153. }elseif(substr($regs[0],0,31)=='NT_STATUS_OBJECT_PATH_NOT_FOUND'){
  154. return false;
  155. }
  156. trigger_error($regs[0].' params('.$params.')', E_USER_ERROR);
  157. }
  158. if ($i) switch ($i[1]) {
  159. case 'file':
  160. case 'folder': $info['info'][$i[0]] = $i;
  161. case 'disk':
  162. case 'server':
  163. case 'workgroup': $info[$i[1]][] = $i[0];
  164. }
  165. }
  166. pclose($output);
  167. return $info;
  168. }
  169. # stats
  170. function url_stat ($url, $flags = STREAM_URL_STAT_LINK) {
  171. if ($s = smb::getstatcache($url)) { return $s; }
  172. list ($stat, $pu) = array (array (), smb::parse_url ($url));
  173. switch ($pu['type']) {
  174. case 'host':
  175. if ($o = smb::look ($pu))
  176. $stat = stat ("/tmp");
  177. else
  178. trigger_error ("url_stat(): list failed for host '{$host}'", E_USER_WARNING);
  179. break;
  180. case 'share':
  181. if ($o = smb::look ($pu)) {
  182. $found = FALSE;
  183. $lshare = strtolower ($pu['share']); # fix by Eric Leung
  184. foreach ($o['disk'] as $s) if ($lshare == strtolower($s)) {
  185. $found = TRUE;
  186. $stat = stat ("/tmp");
  187. break;
  188. }
  189. if (! $found)
  190. trigger_error ("url_stat(): disk resource '{$share}' not found in '{$host}'", E_USER_WARNING);
  191. }
  192. break;
  193. case 'path':
  194. if ($o = smb::execute ('dir "'.$pu['path'].'"', $pu)) {
  195. $p = explode('\\', $pu['path']);
  196. $name = $p[count($p)-1];
  197. if (isset ($o['info'][$name])) {
  198. $stat = smb::addstatcache ($url, $o['info'][$name]);
  199. } else {
  200. trigger_error ("url_stat(): path '{$pu['path']}' not found", E_USER_WARNING);
  201. }
  202. } else {
  203. return false;
  204. // trigger_error ("url_stat(): dir failed for path '{$pu['path']}'", E_USER_WARNING);
  205. }
  206. break;
  207. default: trigger_error ('error in URL', E_USER_ERROR);
  208. }
  209. return $stat;
  210. }
  211. function addstatcache ($url, $info) {
  212. global $__smb_cache;
  213. $is_file = (strpos ($info['attr'],'D') === FALSE);
  214. $s = ($is_file) ? stat ('/etc/passwd') : stat ('/tmp');
  215. $s[7] = $s['size'] = $info['size'];
  216. $s[8] = $s[9] = $s[10] = $s['atime'] = $s['mtime'] = $s['ctime'] = $info['time'];
  217. return $__smb_cache['stat'][$url] = $s;
  218. }
  219. function getstatcache ($url) {
  220. global $__smb_cache;
  221. return isset ($__smb_cache['stat'][$url]) ? $__smb_cache['stat'][$url] : FALSE;
  222. }
  223. function clearstatcache ($url='') {
  224. global $__smb_cache;
  225. if ($url == '') $__smb_cache['stat'] = array (); else unset ($__smb_cache['stat'][$url]);
  226. }
  227. # commands
  228. function unlink ($url) {
  229. $pu = smb::parse_url($url);
  230. if ($pu['type'] <> 'path') trigger_error('unlink(): error in URL', E_USER_ERROR);
  231. smb::clearstatcache ($url);
  232. smb_stream_wrapper::cleardircache (dirname($url));
  233. return smb::execute ('del "'.$pu['path'].'"', $pu);
  234. }
  235. function rename ($url_from, $url_to) {
  236. list ($from, $to) = array (smb::parse_url($url_from), smb::parse_url($url_to));
  237. if ($from['host'] <> $to['host'] ||
  238. $from['share'] <> $to['share'] ||
  239. $from['user'] <> $to['user'] ||
  240. $from['pass'] <> $to['pass'] ||
  241. $from['domain'] <> $to['domain']) {
  242. trigger_error('rename(): FROM & TO must be in same server-share-user-pass-domain', E_USER_ERROR);
  243. }
  244. if ($from['type'] <> 'path' || $to['type'] <> 'path') {
  245. trigger_error('rename(): error in URL', E_USER_ERROR);
  246. }
  247. smb::clearstatcache ($url_from);
  248. return smb::execute ('rename "'.$from['path'].'" "'.$to['path'].'"', $to);
  249. }
  250. function mkdir ($url, $mode, $options) {
  251. $pu = smb::parse_url($url);
  252. if ($pu['type'] <> 'path') trigger_error('mkdir(): error in URL', E_USER_ERROR);
  253. return smb::execute ('mkdir "'.$pu['path'].'"', $pu)!==false;
  254. }
  255. function rmdir ($url) {
  256. $pu = smb::parse_url($url);
  257. if ($pu['type'] <> 'path') trigger_error('rmdir(): error in URL', E_USER_ERROR);
  258. smb::clearstatcache ($url);
  259. smb_stream_wrapper::cleardircache (dirname($url));
  260. return smb::execute ('rmdir "'.$pu['path'].'"', $pu)!==false;
  261. }
  262. }
  263. ###################################################################
  264. # SMB_STREAM_WRAPPER - class to be registered for smb:// URLs
  265. ###################################################################
  266. class smb_stream_wrapper extends smb {
  267. # variables
  268. private $stream, $url, $parsed_url = array (), $mode, $tmpfile;
  269. private $need_flush = FALSE;
  270. private $dir = array (), $dir_index = -1;
  271. # directories
  272. function dir_opendir ($url, $options) {
  273. if ($d = $this->getdircache ($url)) {
  274. $this->dir = $d;
  275. $this->dir_index = 0;
  276. return TRUE;
  277. }
  278. $pu = smb::parse_url ($url);
  279. switch ($pu['type']) {
  280. case 'host':
  281. if ($o = smb::look ($pu)) {
  282. $this->dir = $o['disk'];
  283. $this->dir_index = 0;
  284. } else {
  285. trigger_error ("dir_opendir(): list failed for host '{$pu['host']}'", E_USER_WARNING);
  286. return false;
  287. }
  288. break;
  289. case 'share':
  290. case 'path':
  291. if (is_array($o = smb::execute ('dir "'.$pu['path'].'\*"', $pu))) {
  292. $this->dir = array_keys($o['info']);
  293. $this->dir_index = 0;
  294. $this->adddircache ($url, $this->dir);
  295. foreach ($o['info'] as $name => $info) {
  296. smb::addstatcache($url . '/' . urlencode($name), $info);
  297. }
  298. } else {
  299. trigger_error ("dir_opendir(): dir failed for path '".$pu['path']."'", E_USER_WARNING);
  300. return false;
  301. }
  302. break;
  303. default:
  304. trigger_error ('dir_opendir(): error in URL', E_USER_ERROR);
  305. return false;
  306. }
  307. return TRUE;
  308. }
  309. function dir_readdir () {
  310. return ($this->dir_index < count($this->dir)) ? $this->dir[$this->dir_index++] : FALSE;
  311. }
  312. function dir_rewinddir () { $this->dir_index = 0; }
  313. function dir_closedir () { $this->dir = array(); $this->dir_index = -1; return TRUE; }
  314. # cache
  315. function adddircache ($url, $content) {
  316. global $__smb_cache;
  317. return $__smb_cache['dir'][$url] = $content;
  318. }
  319. function getdircache ($url) {
  320. global $__smb_cache;
  321. return isset ($__smb_cache['dir'][$url]) ? $__smb_cache['dir'][$url] : FALSE;
  322. }
  323. function cleardircache ($url='') {
  324. global $__smb_cache;
  325. if ($url == ''){
  326. $__smb_cache['dir'] = array ();
  327. }else{
  328. unset ($__smb_cache['dir'][$url]);
  329. }
  330. }
  331. # streams
  332. function stream_open ($url, $mode, $options, $opened_path) {
  333. $this->url = $url;
  334. $this->mode = $mode;
  335. $this->parsed_url = $pu = smb::parse_url($url);
  336. if ($pu['type'] <> 'path') trigger_error('stream_open(): error in URL', E_USER_ERROR);
  337. switch ($mode) {
  338. case 'r':
  339. case 'r+':
  340. case 'rb':
  341. case 'a':
  342. case 'a+': $this->tmpfile = tempnam('/tmp', 'smb.down.');
  343. smb::execute ('get "'.$pu['path'].'" "'.$this->tmpfile.'"', $pu);
  344. break;
  345. case 'w':
  346. case 'w+':
  347. case 'wb':
  348. case 'x':
  349. case 'x+': $this->cleardircache();
  350. $this->tmpfile = tempnam('/tmp', 'smb.up.');
  351. $this->need_flush=true;
  352. }
  353. $this->stream = fopen ($this->tmpfile, $mode);
  354. return TRUE;
  355. }
  356. function stream_close () { return fclose($this->stream); }
  357. function stream_read ($count) { return fread($this->stream, $count); }
  358. function stream_write ($data) { $this->need_flush = TRUE; return fwrite($this->stream, $data); }
  359. function stream_eof () { return feof($this->stream); }
  360. function stream_tell () { return ftell($this->stream); }
  361. function stream_seek ($offset, $whence=null) { return fseek($this->stream, $offset, $whence); }
  362. function stream_flush () {
  363. if ($this->mode <> 'r' && $this->need_flush) {
  364. smb::clearstatcache ($this->url);
  365. smb::execute ('put "'.$this->tmpfile.'" "'.$this->parsed_url['path'].'"', $this->parsed_url);
  366. $this->need_flush = FALSE;
  367. }
  368. }
  369. function stream_stat () { return smb::url_stat ($this->url); }
  370. function __destruct () {
  371. if ($this->tmpfile <> '') {
  372. if ($this->need_flush) $this->stream_flush ();
  373. unlink ($this->tmpfile);
  374. }
  375. }
  376. }
  377. ###################################################################
  378. # Register 'smb' protocol !
  379. ###################################################################
  380. stream_wrapper_register('smb', 'smb_stream_wrapper')
  381. or die ('Failed to register protocol');