s4/torture: add more lock cancellation tests
[Samba/fernandojvsilva.git] / source3 / utils / smbget.c
blob15fe1fd70a424ba3c18c3a42822ebcd55a355dcf
1 /*
2 smbget: a wget-like utility with support for recursive downloading and
3 smb:// urls
4 Copyright (C) 2003-2004 Jelmer Vernooij <jelmer@samba.org>
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "includes.h"
20 #include "libsmbclient.h"
22 #if _FILE_OFFSET_BITS==64
23 #define OFF_T_FORMAT "%lld"
24 #define OFF_T_FORMAT_CAST long long
25 #else
26 #define OFF_T_FORMAT "%ld"
27 #define OFF_T_FORMAT_CAST long
28 #endif
30 static int columns = 0;
32 static int debuglevel, update;
33 static char *outputfile;
36 static time_t total_start_time = 0;
37 static off_t total_bytes = 0;
39 #define SMB_MAXPATHLEN MAXPATHLEN
41 /* Number of bytes to read when checking whether local and remote file are really the same file */
42 #define RESUME_CHECK_SIZE 512
43 #define RESUME_DOWNLOAD_OFFSET 1024
44 #define RESUME_CHECK_OFFSET RESUME_DOWNLOAD_OFFSET+RESUME_CHECK_SIZE
45 /* Number of bytes to read at once */
46 #define SMB_DEFAULT_BLOCKSIZE 64000
48 static const char *username = NULL, *password = NULL, *workgroup = NULL;
49 static int nonprompt = 0, quiet = 0, dots = 0, keep_permissions = 0, verbose = 0, send_stdout = 0;
50 static int blocksize = SMB_DEFAULT_BLOCKSIZE;
52 static int smb_download_file(const char *base, const char *name, int recursive, int resume, char *outfile);
54 static int get_num_cols(void)
56 #ifdef TIOCGWINSZ
57 struct winsize ws;
58 if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
59 return 0;
61 return ws.ws_col;
62 #else
63 #warning No support for TIOCGWINSZ
64 char *cols = getenv("COLUMNS");
65 if(!cols) return 0;
66 return atoi(cols);
67 #endif
70 static void change_columns(int sig)
72 columns = get_num_cols();
75 static void human_readable(off_t s, char *buffer, int l)
77 if(s > 1024 * 1024 * 1024) snprintf(buffer, l, "%.2fGb", 1.0 * s / (1024 * 1024 * 1024));
78 else if(s > 1024 * 1024) snprintf(buffer, l, "%.2fMb", 1.0 * s / (1024 * 1024));
79 else if(s > 1024) snprintf(buffer, l, "%.2fkb", 1.0 * s / 1024);
80 else snprintf(buffer, l, OFF_T_FORMAT"b", (OFF_T_FORMAT_CAST)s);
83 static void get_auth_data(const char *srv, const char *shr, char *wg, int wglen, char *un, int unlen, char *pw, int pwlen)
85 static char hasasked = 0;
86 char *wgtmp, *usertmp;
87 char tmp[128];
89 if(hasasked) return;
90 hasasked = 1;
92 if(!nonprompt && !username) {
93 printf("Username for %s at %s [guest] ", shr, srv);
94 if (fgets(tmp, sizeof(tmp), stdin) == NULL) {
95 return;
97 if ((strlen(tmp) > 0) && (tmp[strlen(tmp)-1] == '\n')) {
98 tmp[strlen(tmp)-1] = '\0';
100 strncpy(un, tmp, unlen-1);
101 } else if(username) strncpy(un, username, unlen-1);
103 if(!nonprompt && !password) {
104 char *prompt, *pass;
105 if (asprintf(&prompt, "Password for %s at %s: ", shr, srv) == -1) {
106 return;
108 pass = getpass(prompt);
109 free(prompt);
110 strncpy(pw, pass, pwlen-1);
111 } else if(password) strncpy(pw, password, pwlen-1);
113 if(workgroup)strncpy(wg, workgroup, wglen-1);
115 wgtmp = SMB_STRNDUP(wg, wglen);
116 usertmp = SMB_STRNDUP(un, unlen);
117 if(!quiet)printf("Using workgroup %s, %s%s\n", wgtmp, *usertmp?"user ":"guest user", usertmp);
118 free(wgtmp); free(usertmp);
121 static int smb_download_dir(const char *base, const char *name, int resume)
123 char path[SMB_MAXPATHLEN];
124 int dirhandle;
125 struct smbc_dirent *dirent;
126 const char *relname = name;
127 char *tmpname;
128 struct stat remotestat;
129 snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (base[0] && name[0] && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name);
131 /* List files in directory and call smb_download_file on them */
132 dirhandle = smbc_opendir(path);
133 if(dirhandle < 1) {
134 if(errno == ENOTDIR) return smb_download_file(base, name, 1, resume, NULL);
135 fprintf(stderr, "Can't open directory %s: %s\n", path, strerror(errno));
136 return 0;
139 while(*relname == '/')relname++;
140 mkdir(relname, 0755);
142 tmpname = SMB_STRDUP(name);
144 while((dirent = smbc_readdir(dirhandle))) {
145 char *newname;
146 if(!strcmp(dirent->name, ".") || !strcmp(dirent->name, ".."))continue;
147 if (asprintf(&newname, "%s/%s", tmpname, dirent->name) == -1) {
148 return 0;
150 switch(dirent->smbc_type) {
151 case SMBC_DIR:
152 smb_download_dir(base, newname, resume);
153 break;
155 case SMBC_WORKGROUP:
156 smb_download_dir("smb://", dirent->name, resume);
157 break;
159 case SMBC_SERVER:
160 smb_download_dir("smb://", dirent->name, resume);
161 break;
163 case SMBC_FILE:
164 smb_download_file(base, newname, 1, resume, NULL);
165 break;
167 case SMBC_FILE_SHARE:
168 smb_download_dir(base, newname, resume);
169 break;
171 case SMBC_PRINTER_SHARE:
172 if(!quiet)printf("Ignoring printer share %s\n", dirent->name);
173 break;
175 case SMBC_COMMS_SHARE:
176 if(!quiet)printf("Ignoring comms share %s\n", dirent->name);
177 break;
179 case SMBC_IPC_SHARE:
180 if(!quiet)printf("Ignoring ipc$ share %s\n", dirent->name);
181 break;
183 default:
184 fprintf(stderr, "Ignoring file '%s' of type '%d'\n", newname, dirent->smbc_type);
185 break;
187 free(newname);
189 free(tmpname);
191 if(keep_permissions) {
192 if(smbc_fstat(dirhandle, &remotestat) < 0) {
193 fprintf(stderr, "Unable to get stats on %s on remote server\n", path);
194 smbc_closedir(dirhandle);
195 return 0;
198 if(chmod(relname, remotestat.st_mode) < 0) {
199 fprintf(stderr, "Unable to change mode of local dir %s to %o\n", relname,
200 (unsigned int)remotestat.st_mode);
201 smbc_closedir(dirhandle);
202 return 0;
206 smbc_closedir(dirhandle);
207 return 1;
210 static char *print_time(long t)
212 static char buffer[100];
213 int secs, mins, hours;
214 if(t < -1) {
215 strncpy(buffer, "Unknown", sizeof(buffer));
216 return buffer;
219 secs = (int)t % 60;
220 mins = (int)t / 60 % 60;
221 hours = (int)t / (60 * 60);
222 snprintf(buffer, sizeof(buffer)-1, "%02d:%02d:%02d", hours, mins, secs);
223 return buffer;
226 static void print_progress(const char *name, time_t start, time_t now, off_t start_pos, off_t pos, off_t total)
228 double avg = 0.0;
229 long eta = -1;
230 double prcnt = 0.0;
231 char hpos[20], htotal[20], havg[20];
232 char *status, *filename;
233 int len;
234 if(now - start)avg = 1.0 * (pos - start_pos) / (now - start);
235 eta = (total - pos) / avg;
236 if(total)prcnt = 100.0 * pos / total;
238 human_readable(pos, hpos, sizeof(hpos));
239 human_readable(total, htotal, sizeof(htotal));
240 human_readable(avg, havg, sizeof(havg));
242 len = asprintf(&status, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos, htotal, prcnt, havg, print_time(eta));
243 if (len == -1) {
244 return;
247 if(columns) {
248 int required = strlen(name), available = columns - len - strlen("[] ");
249 if(required > available) {
250 if (asprintf(&filename, "...%s", name + required - available + 3) == -1) {
251 return;
253 } else {
254 filename = SMB_STRNDUP(name, available);
256 } else filename = SMB_STRDUP(name);
258 fprintf(stderr, "\r[%s] %s", filename, status);
260 free(filename); free(status);
263 static int smb_download_file(const char *base, const char *name, int recursive, int resume, char *outfile) {
264 int remotehandle, localhandle;
265 time_t start_time = time(NULL);
266 const char *newpath;
267 char path[SMB_MAXPATHLEN];
268 char checkbuf[2][RESUME_CHECK_SIZE];
269 char *readbuf = NULL;
270 off_t offset_download = 0, offset_check = 0, curpos = 0, start_offset = 0;
271 struct stat localstat, remotestat;
273 snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (*base && *name && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name);
275 remotehandle = smbc_open(path, O_RDONLY, 0755);
277 if(remotehandle < 0) {
278 switch(errno) {
279 case EISDIR:
280 if(!recursive) {
281 fprintf(stderr, "%s is a directory. Specify -R to download recursively\n", path);
282 return 0;
284 smb_download_dir(base, name, resume);
285 return 0;
287 case ENOENT:
288 fprintf(stderr, "%s can't be found on the remote server\n", path);
289 return 0;
291 case ENOMEM:
292 fprintf(stderr, "Not enough memory\n");
293 exit(1);
294 return 0;
296 case ENODEV:
297 fprintf(stderr, "The share name used in %s does not exist\n", path);
298 return 0;
300 case EACCES:
301 fprintf(stderr, "You don't have enough permissions to access %s\n", path);
302 return 0;
304 default:
305 perror("smbc_open");
306 return 0;
310 if(smbc_fstat(remotehandle, &remotestat) < 0) {
311 fprintf(stderr, "Can't stat %s: %s\n", path, strerror(errno));
312 return 0;
315 if(outfile) newpath = outfile;
316 else if(!name[0]) {
317 newpath = strrchr(base, '/');
318 if(newpath)newpath++; else newpath = base;
319 } else newpath = name;
321 if(newpath[0] == '/')newpath++;
323 /* Open local file according to the mode */
324 if(update) {
325 /* if it is up-to-date, skip */
326 if(stat(newpath, &localstat) == 0 &&
327 localstat.st_mtime >= remotestat.st_mtime) {
328 if(verbose)
329 printf("%s is up-to-date, skipping\n", newpath);
330 smbc_close(remotehandle);
331 return 0;
333 /* else open it for writing and truncate if it exists */
334 localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR | O_TRUNC, 0775);
335 if(localhandle < 0) {
336 fprintf(stderr, "Can't open %s : %s\n", newpath,
337 strerror(errno));
338 smbc_close(remotehandle);
339 return 0;
341 /* no offset */
342 } else if(!send_stdout) {
343 localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR | (!resume?O_EXCL:0), 0755);
344 if(localhandle < 0) {
345 fprintf(stderr, "Can't open %s: %s\n", newpath, strerror(errno));
346 smbc_close(remotehandle);
347 return 0;
350 if (fstat(localhandle, &localstat) != 0) {
351 fprintf(stderr, "Can't fstat %s: %s\n", newpath, strerror(errno));
352 smbc_close(remotehandle);
353 close(localhandle);
354 return 0;
357 start_offset = localstat.st_size;
359 if(localstat.st_size && localstat.st_size == remotestat.st_size) {
360 if(verbose)fprintf(stderr, "%s is already downloaded completely.\n", path);
361 else if(!quiet)fprintf(stderr, "%s\n", path);
362 smbc_close(remotehandle);
363 close(localhandle);
364 return 1;
367 if(localstat.st_size > RESUME_CHECK_OFFSET && remotestat.st_size > RESUME_CHECK_OFFSET) {
368 offset_download = localstat.st_size - RESUME_DOWNLOAD_OFFSET;
369 offset_check = localstat.st_size - RESUME_CHECK_OFFSET;
370 if(verbose)printf("Trying to start resume of %s at "OFF_T_FORMAT"\n"
371 "At the moment "OFF_T_FORMAT" of "OFF_T_FORMAT" bytes have been retrieved\n",
372 newpath, (OFF_T_FORMAT_CAST)offset_check,
373 (OFF_T_FORMAT_CAST)localstat.st_size,
374 (OFF_T_FORMAT_CAST)remotestat.st_size);
377 if(offset_check) {
378 off_t off1, off2;
379 /* First, check all bytes from offset_check to offset_download */
380 off1 = lseek(localhandle, offset_check, SEEK_SET);
381 if(off1 < 0) {
382 fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in local file %s\n",
383 (OFF_T_FORMAT_CAST)offset_check, newpath);
384 smbc_close(remotehandle); close(localhandle);
385 return 0;
388 off2 = smbc_lseek(remotehandle, offset_check, SEEK_SET);
389 if(off2 < 0) {
390 fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in remote file %s\n",
391 (OFF_T_FORMAT_CAST)offset_check, newpath);
392 smbc_close(remotehandle); close(localhandle);
393 return 0;
396 if(off1 != off2) {
397 fprintf(stderr, "Offset in local and remote files is different (local: "OFF_T_FORMAT", remote: "OFF_T_FORMAT")\n",
398 (OFF_T_FORMAT_CAST)off1,
399 (OFF_T_FORMAT_CAST)off2);
400 return 0;
403 if(smbc_read(remotehandle, checkbuf[0], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
404 fprintf(stderr, "Can't read %d bytes from remote file %s\n", RESUME_CHECK_SIZE, path);
405 smbc_close(remotehandle); close(localhandle);
406 return 0;
409 if(read(localhandle, checkbuf[1], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
410 fprintf(stderr, "Can't read %d bytes from local file %s\n", RESUME_CHECK_SIZE, name);
411 smbc_close(remotehandle); close(localhandle);
412 return 0;
415 if(memcmp(checkbuf[0], checkbuf[1], RESUME_CHECK_SIZE) == 0) {
416 if(verbose)printf("Current local and remote file appear to be the same. Starting download from offset "OFF_T_FORMAT"\n", (OFF_T_FORMAT_CAST)offset_download);
417 } else {
418 fprintf(stderr, "Local and remote file appear to be different, not doing resume for %s\n", path);
419 smbc_close(remotehandle); close(localhandle);
420 return 0;
423 } else {
424 localhandle = STDOUT_FILENO;
425 start_offset = 0;
426 offset_download = 0;
427 offset_check = 0;
430 readbuf = (char *)SMB_MALLOC(blocksize);
432 /* Now, download all bytes from offset_download to the end */
433 for(curpos = offset_download; curpos < remotestat.st_size; curpos+=blocksize) {
434 ssize_t bytesread = smbc_read(remotehandle, readbuf, blocksize);
435 if(bytesread < 0) {
436 fprintf(stderr, "Can't read %u bytes at offset "OFF_T_FORMAT", file %s\n", (unsigned int)blocksize, (OFF_T_FORMAT_CAST)curpos, path);
437 smbc_close(remotehandle);
438 if (localhandle != STDOUT_FILENO) close(localhandle);
439 free(readbuf);
440 return 0;
443 total_bytes += bytesread;
445 if(write(localhandle, readbuf, bytesread) < 0) {
446 fprintf(stderr, "Can't write %u bytes to local file %s at offset "OFF_T_FORMAT"\n", (unsigned int)bytesread, path, (OFF_T_FORMAT_CAST)curpos);
447 free(readbuf);
448 smbc_close(remotehandle);
449 if (localhandle != STDOUT_FILENO) close(localhandle);
450 return 0;
453 if(dots)fputc('.', stderr);
454 else if(!quiet) {
455 print_progress(newpath, start_time, time(NULL), start_offset, curpos, remotestat.st_size);
459 free(readbuf);
461 if(dots){
462 fputc('\n', stderr);
463 printf("%s downloaded\n", path);
464 } else if(!quiet) {
465 int i;
466 fprintf(stderr, "\r%s", path);
467 if(columns) {
468 for(i = strlen(path); i < columns; i++) {
469 fputc(' ', stderr);
472 fputc('\n', stderr);
475 if(keep_permissions && !send_stdout) {
476 if(fchmod(localhandle, remotestat.st_mode) < 0) {
477 fprintf(stderr, "Unable to change mode of local file %s to %o\n", path,
478 (unsigned int)remotestat.st_mode);
479 smbc_close(remotehandle);
480 close(localhandle);
481 return 0;
485 smbc_close(remotehandle);
486 if (localhandle != STDOUT_FILENO) close(localhandle);
487 return 1;
490 static void clean_exit(void)
492 char bs[100];
493 human_readable(total_bytes, bs, sizeof(bs));
494 if(!quiet)fprintf(stderr, "Downloaded %s in %lu seconds\n", bs,
495 (unsigned long)(time(NULL) - total_start_time));
496 exit(0);
499 static void signal_quit(int v)
501 clean_exit();
504 static int readrcfile(const char *name, const struct poptOption long_options[])
506 FILE *fd = fopen(name, "r");
507 int lineno = 0, i;
508 char var[101], val[101];
509 char found;
510 int *intdata; char **stringdata;
511 if(!fd) {
512 fprintf(stderr, "Can't open RC file %s\n", name);
513 return 1;
516 while(!feof(fd)) {
517 lineno++;
518 if(fscanf(fd, "%100s %100s\n", var, val) < 2) {
519 fprintf(stderr, "Can't parse line %d of %s, ignoring.\n", lineno, name);
520 continue;
523 found = 0;
525 for(i = 0; long_options[i].shortName; i++) {
526 if(!long_options[i].longName)continue;
527 if(strcmp(long_options[i].longName, var)) continue;
528 if(!long_options[i].arg)continue;
530 switch(long_options[i].argInfo) {
531 case POPT_ARG_NONE:
532 intdata = (int *)long_options[i].arg;
533 if(!strcmp(val, "on")) *intdata = 1;
534 else if(!strcmp(val, "off")) *intdata = 0;
535 else fprintf(stderr, "Illegal value %s for %s at line %d in %s\n", val, var, lineno, name);
536 break;
537 case POPT_ARG_INT:
538 intdata = (int *)long_options[i].arg;
539 *intdata = atoi(val);
540 break;
541 case POPT_ARG_STRING:
542 stringdata = (char **)long_options[i].arg;
543 *stringdata = SMB_STRDUP(val);
544 break;
545 default:
546 fprintf(stderr, "Invalid variable %s at line %d in %s\n", var, lineno, name);
547 break;
550 found = 1;
552 if(!found) {
553 fprintf(stderr, "Invalid variable %s at line %d in %s\n", var, lineno, name);
557 fclose(fd);
558 return 0;
561 int main(int argc, const char **argv)
563 int c = 0;
564 const char *file = NULL;
565 char *rcfile = NULL;
566 bool smb_encrypt = false;
567 int resume = 0, recursive = 0;
568 TALLOC_CTX *frame = talloc_stackframe();
569 struct poptOption long_options[] = {
570 {"guest", 'a', POPT_ARG_NONE, NULL, 'a', "Work as user guest" },
571 {"encrypt", 'e', POPT_ARG_NONE, NULL, 'e', "Encrypt SMB transport (UNIX extended servers only)" },
572 {"resume", 'r', POPT_ARG_NONE, &resume, 0, "Automatically resume aborted files" },
573 {"update", 'U', POPT_ARG_NONE, &update, 0, "Download only when remote file is newer than local file or local file is missing"},
574 {"recursive", 'R', POPT_ARG_NONE, &recursive, 0, "Recursively download files" },
575 {"username", 'u', POPT_ARG_STRING, &username, 'u', "Username to use" },
576 {"password", 'p', POPT_ARG_STRING, &password, 'p', "Password to use" },
577 {"workgroup", 'w', POPT_ARG_STRING, &workgroup, 'w', "Workgroup to use (optional)" },
578 {"nonprompt", 'n', POPT_ARG_NONE, &nonprompt, 'n', "Don't ask anything (non-interactive)" },
579 {"debuglevel", 'd', POPT_ARG_INT, &debuglevel, 'd', "Debuglevel to use" },
580 {"outputfile", 'o', POPT_ARG_STRING, &outputfile, 'o', "Write downloaded data to specified file" },
581 {"stdout", 'O', POPT_ARG_NONE, &send_stdout, 'O', "Write data to stdout" },
582 {"dots", 'D', POPT_ARG_NONE, &dots, 'D', "Show dots as progress indication" },
583 {"quiet", 'q', POPT_ARG_NONE, &quiet, 'q', "Be quiet" },
584 {"verbose", 'v', POPT_ARG_NONE, &verbose, 'v', "Be verbose" },
585 {"keep-permissions", 'P', POPT_ARG_NONE, &keep_permissions, 'P', "Keep permissions" },
586 {"blocksize", 'b', POPT_ARG_INT, &blocksize, 'b', "Change number of bytes in a block"},
587 {"rcfile", 'f', POPT_ARG_STRING, NULL, 'f', "Use specified rc file"},
588 POPT_AUTOHELP
589 POPT_TABLEEND
591 poptContext pc;
593 load_case_tables();
595 /* only read rcfile if it exists */
596 if (asprintf(&rcfile, "%s/.smbgetrc", getenv("HOME")) == -1) {
597 return 1;
599 if(access(rcfile, F_OK) == 0)
600 readrcfile(rcfile, long_options);
601 free(rcfile);
603 #ifdef SIGWINCH
604 signal(SIGWINCH, change_columns);
605 #endif
606 signal(SIGINT, signal_quit);
607 signal(SIGTERM, signal_quit);
609 pc = poptGetContext(argv[0], argc, argv, long_options, 0);
611 while((c = poptGetNextOpt(pc)) >= 0) {
612 switch(c) {
613 case 'f':
614 readrcfile(poptGetOptArg(pc), long_options);
615 break;
616 case 'a':
617 username = ""; password = "";
618 break;
619 case 'e':
620 smb_encrypt = true;
621 break;
625 if((send_stdout || resume || outputfile) && update) {
626 fprintf(stderr, "The -o, -R or -O and -U options can not be used together.\n");
627 return 1;
629 if((send_stdout || outputfile) && recursive) {
630 fprintf(stderr, "The -o or -O and -R options can not be used together.\n");
631 return 1;
634 if(outputfile && send_stdout) {
635 fprintf(stderr, "The -o and -O options cannot be used together.\n");
636 return 1;
639 if(smbc_init(get_auth_data, debuglevel) < 0) {
640 fprintf(stderr, "Unable to initialize libsmbclient\n");
641 return 1;
644 if (smb_encrypt) {
645 SMBCCTX *smb_ctx = smbc_set_context(NULL);
646 smbc_option_set(smb_ctx,
647 CONST_DISCARD(char *, "smb_encrypt_level"),
648 "require");
651 columns = get_num_cols();
653 total_start_time = time(NULL);
655 while ( (file = poptGetArg(pc)) ) {
656 if (!recursive)
657 return smb_download_file(file, "", recursive, resume, outputfile);
658 else
659 return smb_download_dir(file, "", resume);
662 clean_exit();
663 TALLOC_FREE(frame);
664 return 0;