Debian Codegraph @

plugins/wfx/samba/src/smbfunc.pas

raw
1 {
2 Double commander
3 -------------------------------------------------------------------------
4 WFX plugin for working with Common Internet File System (CIFS)
5
6 Copyright (C) 2011-2015 Alexander Koblov ([email protected])
7
8 This library is free software; you can redistribute it and/or
9 modify it under the terms of the GNU Lesser General Public
10 License as published by the Free Software Foundation; either
11 version 2.1 of the License, or (at your option) any later version.
12
13 This library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public
19 License along with this library; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 }
22
23 unit SmbFunc;
24
25 {$mode objfpc}{$H+}
26
27 interface
28
29 uses
30 InitC, Classes, SysUtils, WfxPlugin, Extension;
31
32 function FsInit(PluginNr: Integer; pProgressProc: TProgressProc; pLogProc: TLogProc; pRequestProc: TRequestProc): Integer; cdecl;
33
34 function FsFindFirst(Path: PAnsiChar; var FindData: TWin32FindData): THandle; cdecl;
35 function FsFindNext(Hdl: THandle; var FindData: TWin32FindData): BOOL; cdecl;
36 function FsFindClose(Hdl: THandle): Integer; cdecl;
37
38 function FsRenMovFile(OldName, NewName: PAnsiChar; Move, OverWrite: BOOL;
39 RemoteInfo: pRemoteInfo): Integer; cdecl;
40 function FsGetFile(RemoteName, LocalName: PAnsiChar; CopyFlags: Integer;
41 RemoteInfo: pRemoteInfo): Integer; cdecl;
42 function FsPutFile(LocalName, RemoteName: PAnsiChar; CopyFlags: Integer): Integer; cdecl;
43 function FsDeleteFile(RemoteName: PAnsiChar): BOOL; cdecl;
44
45 function FsMkDir(RemoteDir: PAnsiChar): BOOL; cdecl;
46 function FsRemoveDir(RemoteName: PAnsiChar): BOOL; cdecl;
47
48 function FsSetAttr(RemoteName: PAnsiChar; NewAttr: Integer): BOOL; cdecl;
49 function FsSetTime(RemoteName: PAnsiChar; CreationTime, LastAccessTime, LastWriteTime: PFileTime): BOOL; cdecl;
50
51 procedure FsGetDefRootName(DefRootName: PAnsiChar; MaxLen: Integer); cdecl;
52
53 { Extension API }
54 procedure ExtensionInitialize(StartupInfo: PExtensionStartupInfo); cdecl;
55
56 var
57 Message: AnsiString;
58 WorkGroup: array[0..MAX_PATH-1] of AnsiChar;
59 UserName: array[0..MAX_PATH-1] of AnsiChar;
60 Password: array[0..MAX_PATH-1] of AnsiChar;
61 ExtensionStartupInfo: TExtensionStartupInfo;
62
63 implementation
64
65 uses
66 Math, Unix, BaseUnix, UnixType, StrUtils, URIParser, SmbAuthDlg, libsmbclient;
67
68 const
69 SMB_BUFFER_SIZE = 524288;
70
71 type
72 PSambaHandle = ^TSambaHandle;
73 TSambaHandle = record
74 Path: String;
75 Handle: LongInt;
76 end;
77
78 var
79 ProgressProc: TProgressProc;
80 LogProc: TLogProc;
81 RequestProc: TRequestProc;
82 PluginNumber: Integer;
83 Auth: Boolean = False;
84 Abort: Boolean = False;
85 NeedAuth: Boolean = False;
86
87 function FileTimeToUnixTime(ft: TFileTime): time_t;
88 var
89 UnixTime: Int64;
90 begin
91 UnixTime:= ft.dwHighDateTime;
92 UnixTime:= (UnixTime shl 32) or ft.dwLowDateTime;
93 UnixTime:= (UnixTime - 116444736000000000) div 10000000;
94 Result:= time_t(UnixTime);
95 end;
96
97 function UnixTimeToFileTime(mtime: time_t): TFileTime;
98 var
99 FileTime: Int64;
100 begin
101 FileTime:= Int64(mtime) * 10000000 + 116444736000000000;
102 Result.dwLowDateTime:= (FileTime and $FFFF);
103 Result.dwHighDateTime:= (FileTime shr $20);
104 end;
105
106 function URIEncode(Path: String): String;
107 begin
108 Result:= FileNameToURI(Path);
109 Result:= 'smb:/' + Copy(Result, 8, MaxInt);
110 end;
111
112 procedure WriteError(const FuncName: String);
113 begin
114 WriteLn(FuncName + ': ', SysErrorMessage(fpgetCerrno));
115 end;
116
117 procedure smbc_get_auth_data(server, share: PAnsiChar;
118 wg: PAnsiChar; wglen: LongInt;
119 un: PAnsiChar; unlen: LongInt;
120 pw: PAnsiChar; pwlen: LongInt); cdecl;
121 begin
122 Auth:= True;
123
124 if NeedAuth then
125 begin
126 Abort:= True;
127
128 // Set query resource
129 if (server = nil) then
130 Message:= StrPas(share)
131 else
132 Message:= StrPas(server) + PathDelim + StrPas(share);
133
134 // Set authentication data
135 StrLCopy(WorkGroup, wg, wglen);
136 StrLCopy(UserName, un, unlen);
137 StrLCopy(Password, pw, pwlen);
138
139 // Query authentication data
140 if ShowSmbAuthDlg then
141 begin
142 Abort:= False;
143 // Get authentication data
144 StrLCopy(wg, WorkGroup, wglen);
145 StrLCopy(un, UserName, unlen);
146 StrLCopy(pw, Password, pwlen);
147 end;
148 end
149 else
150 begin
151 // If has saved workgroup then use it
152 if StrLen(WorkGroup) <> 0 then
153 StrLCopy(wg, WorkGroup, wglen);
154 // If has saved user name then use it
155 if StrLen(UserName) <> 0 then
156 StrLCopy(un, UserName, unlen);
157 // If has saved password then use it
158 if StrLen(Password) <> 0 then
159 StrLCopy(pw, Password, pwlen);
160 end;
161 end;
162
163 function BuildNetworkPath(const Path: String): String;
164 var
165 I, C: Integer;
166 begin
167 C:= 0;
168 if Path = PathDelim then Exit('smb://');
169 Result := Path;
170 // Don't check last symbol
171 for I := 1 to Length(Result) - 1 do
172 begin
173 if (Result[I] = PathDelim) then
174 Inc(C);
175 end;
176 if (C < 2) then
177 Result:= URIEncode(Result)
178 else
179 begin
180 I:= PosEx(PathDelim, Result, 2);
181 Result:= URIEncode(Copy(Result, I, MaxInt));
182 end;
183 end;
184
185 function ForceAuth(Path: PAnsiChar): String;
186 var
187 un: array[0..MAX_PATH-1] of AnsiChar;
188 pw: array[0..MAX_PATH-1] of AnsiChar;
189 begin
190 Result:= BuildNetworkPath(Path);
191 // Use by default saved user name and password
192 StrLCopy(un, UserName, MAX_PATH);
193 StrLCopy(pw, Password, MAX_PATH);
194 // Query auth data
195 smbc_get_auth_data(nil, PAnsiChar(Result), WorkGroup, MAX_PATH, un, MAX_PATH, pw, MAX_PATH);
196 if (Abort = False) and (un <> '') then
197 begin
198 if StrLen(WorkGroup) = 0 then
199 Result:= 'smb://' + un + ':' + pw + '@' + Copy(Result, 7, MAX_PATH)
200 else
201 Result:= 'smb://' + WorkGroup + ';' + un + ':' + pw + '@' + Copy(Result, 7, MAX_PATH);
202 end;
203 end;
204
205 function FsInit(PluginNr: Integer; pProgressProc: tProgressProc; pLogProc: tLogProc; pRequestProc: tRequestProc): Integer; cdecl;
206 begin
207 if not LoadSambaLibrary then
208 begin
209 pRequestProc(PluginNr, RT_MsgOK, nil, 'Can not load "libsmbclient" library!', nil, 0);
210 Exit(-1);
211 end;
212 ProgressProc := pProgressProc;
213 LogProc := pLogProc;
214 RequestProc := pRequestProc;
215 PluginNumber := PluginNr;
216 FillChar(WorkGroup, SizeOf(WorkGroup), #0);
217 FillChar(UserName, SizeOf(UserName), #0);
218 FillChar(Password, SizeOf(Password), #0);
219
220 Result := smbc_init(@smbc_get_auth_data, 0);
221 if Result < 0 then WriteError('smbc_init');
222 end;
223
224 function FsFindFirst(Path: PAnsiChar; var FindData: TWin32FindData): THandle; cdecl;
225 var
226 NetworkPath: String;
227 SambaHandle: PSambaHandle;
228 Handle: LongInt;
229 begin
230 Abort:= False;
231 NetworkPath:= BuildNetworkPath(Path);
232 repeat
233 Auth:= False;
234 Handle:= smbc_opendir(PChar(NetworkPath));
235 NeedAuth:= (Handle = -1);
236 // Sometimes smbc_get_auth_data don't called automatically
237 // so we call it manually
238 if NeedAuth and (Auth = False) then
239 begin
240 NetworkPath:= ForceAuth(Path);
241 end;
242 until not NeedAuth or Abort;
243 if Handle < 0 then
244 begin
245 WriteError('smbc_opendir');
246 Result:= wfxInvalidHandle;
247 end
248 else
249 begin
250 New(SambaHandle);
251 SambaHandle^.Path:= IncludeTrailingPathDelimiter(NetworkPath);
252 SambaHandle^.Handle:= Handle;
253 Result:= THandle(SambaHandle);
254 FsFindNext(Result, FindData);
255 end;
256 end;
257
258 function FsFindNext(Hdl: THandle; var FindData: TWin32FindData): BOOL; cdecl;
259 var
260 dirent: psmbc_dirent;
261 FileInfo: BaseUnix.Stat;
262 Mode: array[0..10] of AnsiChar;
263 SambaHandle: PSambaHandle absolute Hdl;
264 begin
265 Result:= True;
266 dirent := smbc_readdir(SambaHandle^.Handle);
267 if (dirent = nil) then Exit(False);
268 FillByte(FindData, SizeOf(TWin32FindData), 0);
269 StrLCopy(FindData.cFileName, dirent^.name, dirent^.namelen);
270 if dirent^.smbc_type in [SMBC_WORKGROUP, SMBC_SERVER, SMBC_FILE_SHARE] then
271 FindData.dwFileAttributes:= FILE_ATTRIBUTE_DIRECTORY;
272 if dirent^.smbc_type in [SMBC_DIR, SMBC_FILE, SMBC_LINK] then
273 begin
274 if smbc_stat(PChar(SambaHandle^.Path + FindData.cFileName), @FileInfo) = 0 then
275 begin
276 FindData.nFileSizeLow := (FileInfo.st_size and MAXDWORD);
277 FindData.nFileSizeHigh := (FileInfo.st_size shr $20);
278 FindData.ftLastAccessTime:= UnixTimeToFileTime(FileInfo.st_atime);
279 FindData.ftCreationTime:= UnixTimeToFileTime(FileInfo.st_ctime);
280 FindData.ftLastWriteTime:= UnixTimeToFileTime(FileInfo.st_mtime);
281 FindData.dwFileAttributes:= IfThen(fpS_ISDIR(FileInfo.st_mode), FILE_ATTRIBUTE_DIRECTORY, 0);
282 end;
283 if smbc_getxattr(PChar(SambaHandle^.Path + FindData.cFileName), 'system.dos_attr.mode', @Mode, SizeOf(Mode)) >= 0 then
284 begin
285 // smbc_getxattr returns attributes as hex string (like 0x00000000)
286 FindData.dwFileAttributes:= StrToIntDef(Mode, FindData.dwFileAttributes);
287 end;
288 end;
289 end;
290
291 function FsFindClose(Hdl: THandle): Integer; cdecl;
292 var
293 SambaHandle: PSambaHandle absolute Hdl;
294 begin
295 Result:= smbc_closedir(SambaHandle^.Handle);
296 if Result < 0 then WriteError('smbc_closedir');
297 Dispose(SambaHandle);
298 end;
299
300 function FsRenMovFile(OldName, NewName: PAnsiChar; Move, OverWrite: BOOL;
301 RemoteInfo: pRemoteInfo): Integer; cdecl;
302 var
303 OldFileName,
304 NewFileName: String;
305 Buffer: Pointer = nil;
306 BufferSize: LongWord;
307 fdOldFile: LongInt;
308 fdNewFile: LongInt;
309 dwRead: ssize_t;
310 Written: Int64;
311 FileSize: Int64;
312 Percent: LongInt;
313 Flags: cint = O_CREAT or O_RDWR or O_TRUNC;
314 begin
315 OldFileName:= BuildNetworkPath(OldName);
316 NewFileName:= BuildNetworkPath(NewName);
317 if Move then
318 begin
319 if smbc_rename(PChar(OldFileName), PChar(NewFileName)) < 0 then
320 Exit(-1);
321 end
322 else
323 begin
324 if OverWrite = False then
325 begin
326 Flags:= Flags or O_EXCL;
327 end;
328 BufferSize:= SMB_BUFFER_SIZE;
329 Buffer:= GetMem(BufferSize);
330 try
331 // Open source file
332 fdOldFile:= smbc_open(PChar(OldFileName), O_RDONLY, 0);
333 if (fdOldFile < 0) then Exit(FS_FILE_READERROR);
334 // Open target file
335 fdNewFile:= smbc_open(PChar(NewFileName), Flags, RemoteInfo^.Attr);
336 if (fdNewFile < 0) then
337 begin
338 if cerrno = ESysEEXIST then
339 Exit(FS_FILE_EXISTS)
340 else
341 Exit(FS_FILE_WRITEERROR);
342 end;
343 // Get source file size
344 FileSize:= smbc_lseek(fdOldFile, 0, SEEK_END);
345 smbc_lseek(fdOldFile, 0, SEEK_SET);
346 Written:= 0;
347 // Copy data
348 repeat
349 dwRead:= smbc_read(fdOldFile, Buffer, BufferSize);
350 if (dwRead < 0) then Exit(FS_FILE_READERROR);
351 if (dwRead > 0) then
352 begin
353 if smbc_write(fdNewFile, Buffer, dwRead) <> dwRead then
354 Exit(FS_FILE_WRITEERROR);
355 Written:= Written + dwRead;
356 // Calculate percent
357 Percent:= (Written * 100) div FileSize;
358 // Update statistics
359 if ProgressProc(PluginNumber, PChar(OldFileName), PChar(NewFileName), Percent) = 1 then
360 Exit(FS_FILE_USERABORT);
361 end;
362 until (dwRead = 0);
363 finally
364 if Assigned(Buffer) then
365 FreeMem(Buffer);
366 if not (fdOldFile < 0) then
367 smbc_close(fdOldFile);
368 if not (fdNewFile < 0) then
369 smbc_close(fdNewFile);
370 end;
371 end;
372 Result:= FS_FILE_OK;
373 end;
374
375 function FsGetFile(RemoteName, LocalName: PAnsiChar; CopyFlags: Integer;
376 RemoteInfo: pRemoteInfo): Integer; cdecl;
377 var
378 OldFileName: String;
379 Buffer: Pointer = nil;
380 BufferSize: LongWord;
381 fdOldFile: LongInt;
382 fdNewFile: LongInt;
383 dwRead: ssize_t;
384 Written: Int64;
385 FileSize: Int64;
386 Percent: LongInt;
387 Flags: cint = O_CREAT or O_RDWR or O_TRUNC;
388 begin
389 OldFileName:= BuildNetworkPath(RemoteName);
390 if (CopyFlags and FS_COPYFLAGS_OVERWRITE) = 0 then
391 begin
392 Flags:= Flags or O_EXCL;
393 end;
394 BufferSize:= SMB_BUFFER_SIZE;
395 Buffer:= GetMem(BufferSize);
396 try
397 // Open source file
398 fdOldFile:= smbc_open(PChar(OldFileName), O_RDONLY, 0);
399 if (fdOldFile < 0) then Exit(FS_FILE_READERROR);
400 // Open target file
401 fdNewFile:= fpOpen(PChar(LocalName), Flags, $1A4); // $1A4 = &644
402 if (fdNewFile < 0) then
403 begin
404 if errno = ESysEEXIST then
405 Exit(FS_FILE_EXISTS)
406 else
407 Exit(FS_FILE_WRITEERROR);
408 end;
409 // Get source file size
410 FileSize:= smbc_lseek(fdOldFile, 0, SEEK_END);
411 smbc_lseek(fdOldFile, 0, SEEK_SET);
412 Written:= 0;
413 // Copy data
414 repeat
415 dwRead:= smbc_read(fdOldFile, Buffer, BufferSize);
416 if (dwRead < 0) then Exit(FS_FILE_READERROR);
417 if (dwRead > 0) then
418 begin
419 if fpWrite(fdNewFile, Buffer^, dwRead) <> dwRead then
420 Exit(FS_FILE_WRITEERROR);
421 Written:= Written + dwRead;
422 // Calculate percent
423 Percent:= (Written * 100) div FileSize;
424 // Update statistics
425 if ProgressProc(PluginNumber, PChar(OldFileName), LocalName, Percent) = 1 then
426 Exit(FS_FILE_USERABORT);
427 end;
428 until (dwRead = 0);
429 finally
430 if Assigned(Buffer) then
431 FreeMem(Buffer);
432 if not (fdOldFile < 0) then
433 smbc_close(fdOldFile);
434 if not (fdNewFile < 0) then
435 fpClose(fdNewFile);
436 end;
437 Result:= FS_FILE_OK;
438 end;
439
440 function FsPutFile(LocalName, RemoteName: PAnsiChar; CopyFlags: Integer): Integer; cdecl;
441 var
442 NewFileName: String;
443 Buffer: Pointer = nil;
444 BufferSize: LongWord;
445 fdOldFile: LongInt;
446 fdNewFile: LongInt;
447 dwRead: TSsize;
448 Written: Int64;
449 FileSize: Int64;
450 Percent: LongInt;
451 Flags: cint = O_CREAT or O_RDWR or O_TRUNC;
452 begin
453 NewFileName:= BuildNetworkPath(RemoteName);
454 if (CopyFlags and FS_COPYFLAGS_OVERWRITE) = 0 then
455 begin
456 Flags:= Flags or O_EXCL;
457 end;
458 BufferSize:= SMB_BUFFER_SIZE;
459 Buffer:= GetMem(BufferSize);
460 try
461 // Open source file
462 fdOldFile:= fpOpen(LocalName, O_RDONLY, 0);
463 if (fdOldFile < 0) then Exit(FS_FILE_READERROR);
464 // Open target file
465 fdNewFile:= smbc_open(PChar(NewFileName), Flags, 0);
466 if (fdNewFile < 0) then
467 begin
468 if cerrno = ESysEEXIST then
469 Exit(FS_FILE_EXISTS)
470 else
471 Exit(FS_FILE_WRITEERROR);
472 end;
473 // Get source file size
474 FileSize:= fpLseek(fdOldFile, 0, SEEK_END);
475 fpLseek(fdOldFile, 0, SEEK_SET);
476 Written:= 0;
477 // Copy data
478 repeat
479 dwRead:= fpRead(fdOldFile, Buffer^, BufferSize);
480 if (dwRead < 0) then Exit(FS_FILE_READERROR);
481 if (dwRead > 0) then
482 begin
483 if smbc_write(fdNewFile, Buffer, dwRead) <> dwRead then
484 Exit(FS_FILE_WRITEERROR);
485 Written:= Written + dwRead;
486 // Calculate percent
487 Percent:= (Written * 100) div FileSize;
488 // Update statistics
489 if ProgressProc(PluginNumber, LocalName, PChar(NewFileName), Percent) = 1 then
490 Exit(FS_FILE_USERABORT);
491 end;
492 until (dwRead = 0);
493 finally
494 if Assigned(Buffer) then
495 FreeMem(Buffer);
496 if not (fdOldFile < 0) then
497 fpClose(fdOldFile);
498 if not (fdNewFile < 0) then
499 smbc_close(fdNewFile);
500 end;
501 Result:= FS_FILE_OK;
502 end;
503
504 function FsDeleteFile(RemoteName: PAnsiChar): BOOL; cdecl;
505 var
506 FileName: String;
507 begin
508 FileName:= BuildNetworkPath(RemoteName);
509 Result:= smbc_unlink(PChar(FileName)) = 0;
510 end;
511
512 function FsMkDir(RemoteDir: PAnsiChar): BOOL; cdecl;
513 var
514 NewDir: String;
515 begin
516 NewDir:= BuildNetworkPath(RemoteDir);
517 Result:= smbc_mkdir(PChar(NewDir), $1FF) = 0; // $1FF = &0777
518 end;
519
520 function FsRemoveDir(RemoteName: PAnsiChar): BOOL; cdecl;
521 var
522 RemDir: String;
523 begin
524 RemDir:= BuildNetworkPath(RemoteName);
525 Result:= smbc_rmdir(PChar(RemDir)) = 0;
526 end;
527
528 function FsSetAttr(RemoteName: PAnsiChar; NewAttr: Integer): BOOL; cdecl;
529 var
530 FileName: String;
531 Mode: array[0..10] of AnsiChar;
532 begin
533 Mode:= '0x' + HexStr(NewAttr, 8) + #0;
534 FileName:= BuildNetworkPath(RemoteName);
535 // smbc_setxattr takes attributes as hex string (like 0x00000000)
536 Result:= (smbc_setxattr(PChar(FileName), 'system.dos_attr.mode', @Mode, SizeOf(Mode), 0) >= 0);
537 end;
538
539 function FsSetTime(RemoteName: PAnsiChar; CreationTime, LastAccessTime, LastWriteTime: PFileTime): BOOL; cdecl;
540 var
541 FileName: String;
542 tbuf: array[0..1] of timeval;
543 FileInfo: BaseUnix.Stat;
544 begin
545 FileName:= BuildNetworkPath(RemoteName);
546 if (LastAccessTime = nil) or (LastWriteTime = nil) then
547 begin
548 if smbc_stat(PChar(FileName), @FileInfo) < 0 then
549 Exit(False);
550
551 if (LastAccessTime = nil) then
552 tbuf[0].tv_sec:= FileInfo.st_atime
553 else
554 tbuf[0].tv_sec:= FileTimeToUnixTime(LastAccessTime^);
555
556 if (LastWriteTime = nil) then
557 tbuf[1].tv_sec:= FileInfo.st_mtime
558 else
559 tbuf[1].tv_sec:= FileTimeToUnixTime(LastWriteTime^);
560 end
561 else
562 begin
563 tbuf[0].tv_sec:= FileTimeToUnixTime(LastAccessTime^);
564 tbuf[1].tv_sec:= FileTimeToUnixTime(LastWriteTime^);
565 end;
566 Result:= (smbc_utimes(PChar(FileName), @tbuf) = 0);
567 end;
568
569 procedure FsGetDefRootName(DefRootName: PAnsiChar; MaxLen: Integer); cdecl;
570 begin
571 StrPLCopy(DefRootName, 'Windows Network', MaxLen);
572 end;
573
574 procedure ExtensionInitialize(StartupInfo: PExtensionStartupInfo); cdecl;
575 begin
576 ExtensionStartupInfo:= StartupInfo^;
577 end;
578
579 end.
580