2 smbget: a wget-like utility with support for recursive downloading and
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/>. */
20 #include "popt_common.h"
21 #include "libsmbclient.h"
23 #if _FILE_OFFSET_BITS==64
24 #define OFF_T_FORMAT "%lld"
25 #define OFF_T_FORMAT_CAST long long
27 #define OFF_T_FORMAT "%ld"
28 #define OFF_T_FORMAT_CAST long
31 static int columns = 0;
33 static int debuglevel, update;
34 static char *outputfile;
37 static time_t total_start_time = 0;
38 static off_t total_bytes = 0;
40 #define SMB_MAXPATHLEN MAXPATHLEN
42 /* Number of bytes to read when checking whether local and remote file are really the same file */
43 #define RESUME_CHECK_SIZE 512
44 #define RESUME_DOWNLOAD_OFFSET 1024
45 #define RESUME_CHECK_OFFSET RESUME_DOWNLOAD_OFFSET+RESUME_CHECK_SIZE
46 /* Number of bytes to read at once */
47 #define SMB_DEFAULT_BLOCKSIZE 64000
49 static const char *username = NULL, *password = NULL, *workgroup = NULL;
50 static int nonprompt = 0, quiet = 0, dots = 0, keep_permissions = 0, verbose = 0, send_stdout = 0;
51 static int blocksize = SMB_DEFAULT_BLOCKSIZE;
53 static int smb_download_file(const char *base, const char *name, int recursive,
54 int resume, int toplevel, char *outfile);
56 static int get_num_cols(void)
60 if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
65 #warning No support for TIOCGWINSZ
66 char *cols = getenv("COLUMNS");
72 static void change_columns(int sig)
74 columns = get_num_cols();
77 static void human_readable(off_t s, char *buffer, int l)
79 if(s > 1024 * 1024 * 1024) snprintf(buffer, l, "%.2fGb", 1.0 * s / (1024 * 1024 * 1024));
80 else if(s > 1024 * 1024) snprintf(buffer, l, "%.2fMb", 1.0 * s / (1024 * 1024));
81 else if(s > 1024) snprintf(buffer, l, "%.2fkb", 1.0 * s / 1024);
82 else snprintf(buffer, l, OFF_T_FORMAT"b", (OFF_T_FORMAT_CAST)s);
85 static void get_auth_data(const char *srv, const char *shr, char *wg, int wglen, char *un, int unlen, char *pw, int pwlen)
87 static char hasasked = 0;
88 char *wgtmp, *usertmp;
94 if(!nonprompt && !username) {
95 printf("Username for %s at %s [guest] ", shr, srv);
96 if (fgets(tmp, sizeof(tmp), stdin) == NULL) {
99 if ((strlen(tmp) > 0) && (tmp[strlen(tmp)-1] == '\n')) {
100 tmp[strlen(tmp)-1] = '\0';
102 strncpy(un, tmp, unlen-1);
103 } else if(username) strncpy(un, username, unlen-1);
105 if(!nonprompt && !password) {
107 if (asprintf(&prompt, "Password for %s at %s: ", shr, srv) == -1) {
110 pass = getpass(prompt);
112 strncpy(pw, pass, pwlen-1);
113 } else if(password) strncpy(pw, password, pwlen-1);
115 if(workgroup)strncpy(wg, workgroup, wglen-1);
117 wgtmp = SMB_STRNDUP(wg, wglen);
118 usertmp = SMB_STRNDUP(un, unlen);
119 if(!quiet)printf("Using workgroup %s, %s%s\n", wgtmp, *usertmp?"user ":"guest user", usertmp);
120 free(wgtmp); free(usertmp);
123 /* Return 1 on error, 0 on success. */
125 static int smb_download_dir(const char *base, const char *name, int resume)
127 char path[SMB_MAXPATHLEN];
129 struct smbc_dirent *dirent;
130 const char *relname = name;
132 struct stat remotestat;
135 snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (base[0] && name[0] && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name);
137 /* List files in directory and call smb_download_file on them */
138 dirhandle = smbc_opendir(path);
140 if (errno == ENOTDIR) {
141 return smb_download_file(base, name, 1, resume,
144 fprintf(stderr, "Can't open directory %s: %s\n", path, strerror(errno));
148 while(*relname == '/')relname++;
149 mkdir(relname, 0755);
151 tmpname = SMB_STRDUP(name);
153 while((dirent = smbc_readdir(dirhandle))) {
155 if(!strcmp(dirent->name, ".") || !strcmp(dirent->name, ".."))continue;
156 if (asprintf(&newname, "%s/%s", tmpname, dirent->name) == -1) {
159 switch(dirent->smbc_type) {
161 ret = smb_download_dir(base, newname, resume);
165 ret = smb_download_dir("smb://", dirent->name, resume);
169 ret = smb_download_dir("smb://", dirent->name, resume);
173 ret = smb_download_file(base, newname, 1, resume, 0,
177 case SMBC_FILE_SHARE:
178 ret = smb_download_dir(base, newname, resume);
181 case SMBC_PRINTER_SHARE:
182 if(!quiet)printf("Ignoring printer share %s\n", dirent->name);
185 case SMBC_COMMS_SHARE:
186 if(!quiet)printf("Ignoring comms share %s\n", dirent->name);
190 if(!quiet)printf("Ignoring ipc$ share %s\n", dirent->name);
194 fprintf(stderr, "Ignoring file '%s' of type '%d'\n", newname, dirent->smbc_type);
201 if(keep_permissions) {
202 if(smbc_fstat(dirhandle, &remotestat) < 0) {
203 fprintf(stderr, "Unable to get stats on %s on remote server\n", path);
204 smbc_closedir(dirhandle);
208 if(chmod(relname, remotestat.st_mode) < 0) {
209 fprintf(stderr, "Unable to change mode of local dir %s to %o\n", relname,
210 (unsigned int)remotestat.st_mode);
211 smbc_closedir(dirhandle);
216 smbc_closedir(dirhandle);
220 static char *print_time(long t)
222 static char buffer[100];
223 int secs, mins, hours;
225 strncpy(buffer, "Unknown", sizeof(buffer));
230 mins = (int)t / 60 % 60;
231 hours = (int)t / (60 * 60);
232 snprintf(buffer, sizeof(buffer)-1, "%02d:%02d:%02d", hours, mins, secs);
236 static void print_progress(const char *name, time_t start, time_t now, off_t start_pos, off_t pos, off_t total)
241 char hpos[20], htotal[20], havg[20];
242 char *status, *filename;
244 if(now - start)avg = 1.0 * (pos - start_pos) / (now - start);
245 eta = (total - pos) / avg;
246 if(total)prcnt = 100.0 * pos / total;
248 human_readable(pos, hpos, sizeof(hpos));
249 human_readable(total, htotal, sizeof(htotal));
250 human_readable(avg, havg, sizeof(havg));
252 len = asprintf(&status, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos, htotal, prcnt, havg, print_time(eta));
258 int required = strlen(name), available = columns - len - strlen("[] ");
259 if(required > available) {
260 if (asprintf(&filename, "...%s", name + required - available + 3) == -1) {
264 filename = SMB_STRNDUP(name, available);
266 } else filename = SMB_STRDUP(name);
268 fprintf(stderr, "\r[%s] %s", filename, status);
270 free(filename); free(status);
273 /* Return 1 on error, 0 on success. */
275 static int smb_download_file(const char *base, const char *name, int recursive,
276 int resume, int toplevel, char *outfile)
278 int remotehandle, localhandle;
279 time_t start_time = time_mono(NULL);
282 char path[SMB_MAXPATHLEN];
283 char checkbuf[2][RESUME_CHECK_SIZE];
284 char *readbuf = NULL;
285 off_t offset_download = 0, offset_check = 0, curpos = 0, start_offset = 0;
286 struct stat localstat, remotestat;
288 snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (*base && *name && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name);
290 remotehandle = smbc_open(path, O_RDONLY, 0755);
292 if(remotehandle < 0) {
296 fprintf(stderr, "%s is a directory. Specify -R to download recursively\n", path);
299 return smb_download_dir(base, name, resume);
302 fprintf(stderr, "%s can't be found on the remote server\n", path);
306 fprintf(stderr, "Not enough memory\n");
310 fprintf(stderr, "The share name used in %s does not exist\n", path);
314 fprintf(stderr, "You don't have enough permissions to access %s\n", path);
323 if(smbc_fstat(remotehandle, &remotestat) < 0) {
324 fprintf(stderr, "Can't stat %s: %s\n", path, strerror(errno));
328 if(outfile) newpath = outfile;
330 newpath = strrchr(base, '/');
331 if(newpath)newpath++; else newpath = base;
332 } else newpath = name;
334 if (!toplevel && (newpath[0] == '/')) {
338 /* Open local file according to the mode */
340 /* if it is up-to-date, skip */
341 if(stat(newpath, &localstat) == 0 &&
342 localstat.st_mtime >= remotestat.st_mtime) {
344 printf("%s is up-to-date, skipping\n", newpath);
345 smbc_close(remotehandle);
348 /* else open it for writing and truncate if it exists */
349 localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR | O_TRUNC, 0775);
350 if(localhandle < 0) {
351 fprintf(stderr, "Can't open %s : %s\n", newpath,
353 smbc_close(remotehandle);
357 } else if(!send_stdout) {
358 localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR | (!resume?O_EXCL:0), 0755);
359 if(localhandle < 0) {
360 fprintf(stderr, "Can't open %s: %s\n", newpath, strerror(errno));
361 smbc_close(remotehandle);
365 if (fstat(localhandle, &localstat) != 0) {
366 fprintf(stderr, "Can't fstat %s: %s\n", newpath, strerror(errno));
367 smbc_close(remotehandle);
372 start_offset = localstat.st_size;
374 if(localstat.st_size && localstat.st_size == remotestat.st_size) {
375 if(verbose)fprintf(stderr, "%s is already downloaded completely.\n", path);
376 else if(!quiet)fprintf(stderr, "%s\n", path);
377 smbc_close(remotehandle);
382 if(localstat.st_size > RESUME_CHECK_OFFSET && remotestat.st_size > RESUME_CHECK_OFFSET) {
383 offset_download = localstat.st_size - RESUME_DOWNLOAD_OFFSET;
384 offset_check = localstat.st_size - RESUME_CHECK_OFFSET;
385 if(verbose)printf("Trying to start resume of %s at "OFF_T_FORMAT"\n"
386 "At the moment "OFF_T_FORMAT" of "OFF_T_FORMAT" bytes have been retrieved\n",
387 newpath, (OFF_T_FORMAT_CAST)offset_check,
388 (OFF_T_FORMAT_CAST)localstat.st_size,
389 (OFF_T_FORMAT_CAST)remotestat.st_size);
394 /* First, check all bytes from offset_check to offset_download */
395 off1 = lseek(localhandle, offset_check, SEEK_SET);
397 fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in local file %s\n",
398 (OFF_T_FORMAT_CAST)offset_check, newpath);
399 smbc_close(remotehandle); close(localhandle);
403 off2 = smbc_lseek(remotehandle, offset_check, SEEK_SET);
405 fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in remote file %s\n",
406 (OFF_T_FORMAT_CAST)offset_check, newpath);
407 smbc_close(remotehandle); close(localhandle);
412 fprintf(stderr, "Offset in local and remote files is different (local: "OFF_T_FORMAT", remote: "OFF_T_FORMAT")\n",
413 (OFF_T_FORMAT_CAST)off1,
414 (OFF_T_FORMAT_CAST)off2);
418 if(smbc_read(remotehandle, checkbuf[0], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
419 fprintf(stderr, "Can't read %d bytes from remote file %s\n", RESUME_CHECK_SIZE, path);
420 smbc_close(remotehandle); close(localhandle);
424 if(read(localhandle, checkbuf[1], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
425 fprintf(stderr, "Can't read %d bytes from local file %s\n", RESUME_CHECK_SIZE, name);
426 smbc_close(remotehandle); close(localhandle);
430 if(memcmp(checkbuf[0], checkbuf[1], RESUME_CHECK_SIZE) == 0) {
431 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);
433 fprintf(stderr, "Local and remote file appear to be different, not doing resume for %s\n", path);
434 smbc_close(remotehandle); close(localhandle);
439 localhandle = STDOUT_FILENO;
445 readbuf = (char *)SMB_MALLOC(blocksize);
447 /* Now, download all bytes from offset_download to the end */
448 for(curpos = offset_download; curpos < remotestat.st_size; curpos+=blocksize) {
449 ssize_t bytesread = smbc_read(remotehandle, readbuf, blocksize);
451 fprintf(stderr, "Can't read %u bytes at offset "OFF_T_FORMAT", file %s\n", (unsigned int)blocksize, (OFF_T_FORMAT_CAST)curpos, path);
452 smbc_close(remotehandle);
453 if (localhandle != STDOUT_FILENO) close(localhandle);
458 total_bytes += bytesread;
460 if(write(localhandle, readbuf, bytesread) < 0) {
461 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);
463 smbc_close(remotehandle);
464 if (localhandle != STDOUT_FILENO) close(localhandle);
468 if(dots)fputc('.', stderr);
470 print_progress(newpath, start_time, time_mono(NULL),
471 start_offset, curpos, remotestat.st_size);
479 printf("%s downloaded\n", path);
482 fprintf(stderr, "\r%s", path);
484 for(i = strlen(path); i < columns; i++) {
491 if(keep_permissions && !send_stdout) {
492 if(fchmod(localhandle, remotestat.st_mode) < 0) {
493 fprintf(stderr, "Unable to change mode of local file %s to %o\n", path,
494 (unsigned int)remotestat.st_mode);
495 smbc_close(remotehandle);
501 smbc_close(remotehandle);
502 if (localhandle != STDOUT_FILENO) close(localhandle);
506 static void clean_exit(void)
509 human_readable(total_bytes, bs, sizeof(bs));
510 if(!quiet)fprintf(stderr, "Downloaded %s in %lu seconds\n", bs,
511 (unsigned long)(time_mono(NULL) - total_start_time));
515 static void signal_quit(int v)
520 static int readrcfile(const char *name, const struct poptOption long_options[])
522 FILE *fd = fopen(name, "r");
524 char var[101], val[101];
526 int *intdata; char **stringdata;
528 fprintf(stderr, "Can't open RC file %s\n", name);
534 if(fscanf(fd, "%100s %100s\n", var, val) < 2) {
535 fprintf(stderr, "Can't parse line %d of %s, ignoring.\n", lineno, name);
541 for(i = 0; long_options[i].shortName; i++) {
542 if(!long_options[i].longName)continue;
543 if(strcmp(long_options[i].longName, var)) continue;
544 if(!long_options[i].arg)continue;
546 switch(long_options[i].argInfo) {
548 intdata = (int *)long_options[i].arg;
549 if(!strcmp(val, "on")) *intdata = 1;
550 else if(!strcmp(val, "off")) *intdata = 0;
551 else fprintf(stderr, "Illegal value %s for %s at line %d in %s\n", val, var, lineno, name);
554 intdata = (int *)long_options[i].arg;
555 *intdata = atoi(val);
557 case POPT_ARG_STRING:
558 stringdata = (char **)long_options[i].arg;
559 *stringdata = SMB_STRDUP(val);
562 fprintf(stderr, "Invalid variable %s at line %d in %s\n", var, lineno, name);
569 fprintf(stderr, "Invalid variable %s at line %d in %s\n", var, lineno, name);
577 int main(int argc, const char **argv)
580 const char *file = NULL;
582 bool smb_encrypt = false;
583 int resume = 0, recursive = 0;
584 TALLOC_CTX *frame = talloc_stackframe();
586 struct poptOption long_options[] = {
587 {"guest", 'a', POPT_ARG_NONE, NULL, 'a', "Work as user guest" },
588 {"encrypt", 'e', POPT_ARG_NONE, NULL, 'e', "Encrypt SMB transport (UNIX extended servers only)" },
589 {"resume", 'r', POPT_ARG_NONE, &resume, 0, "Automatically resume aborted files" },
590 {"update", 'U', POPT_ARG_NONE, &update, 0, "Download only when remote file is newer than local file or local file is missing"},
591 {"recursive", 'R', POPT_ARG_NONE, &recursive, 0, "Recursively download files" },
592 {"username", 'u', POPT_ARG_STRING, &username, 'u', "Username to use" },
593 {"password", 'p', POPT_ARG_STRING, &password, 'p', "Password to use" },
594 {"workgroup", 'w', POPT_ARG_STRING, &workgroup, 'w', "Workgroup to use (optional)" },
595 {"nonprompt", 'n', POPT_ARG_NONE, &nonprompt, 'n', "Don't ask anything (non-interactive)" },
596 {"debuglevel", 'd', POPT_ARG_INT, &debuglevel, 'd', "Debuglevel to use" },
597 {"outputfile", 'o', POPT_ARG_STRING, &outputfile, 'o', "Write downloaded data to specified file" },
598 {"stdout", 'O', POPT_ARG_NONE, &send_stdout, 'O', "Write data to stdout" },
599 {"dots", 'D', POPT_ARG_NONE, &dots, 'D', "Show dots as progress indication" },
600 {"quiet", 'q', POPT_ARG_NONE, &quiet, 'q', "Be quiet" },
601 {"verbose", 'v', POPT_ARG_NONE, &verbose, 'v', "Be verbose" },
602 {"keep-permissions", 'P', POPT_ARG_NONE, &keep_permissions, 'P', "Keep permissions" },
603 {"blocksize", 'b', POPT_ARG_INT, &blocksize, 'b', "Change number of bytes in a block"},
604 {"rcfile", 'f', POPT_ARG_STRING, NULL, 'f', "Use specified rc file"},
612 /* only read rcfile if it exists */
613 if (asprintf(&rcfile, "%s/.smbgetrc", getenv("HOME")) == -1) {
616 if(access(rcfile, F_OK) == 0)
617 readrcfile(rcfile, long_options);
621 signal(SIGWINCH, change_columns);
623 signal(SIGINT, signal_quit);
624 signal(SIGTERM, signal_quit);
626 pc = poptGetContext(argv[0], argc, argv, long_options, 0);
628 while((c = poptGetNextOpt(pc)) >= 0) {
631 readrcfile(poptGetOptArg(pc), long_options);
634 username = ""; password = "";
642 if((send_stdout || resume || outputfile) && update) {
643 fprintf(stderr, "The -o, -R or -O and -U options can not be used together.\n");
646 if((send_stdout || outputfile) && recursive) {
647 fprintf(stderr, "The -o or -O and -R options can not be used together.\n");
651 if(outputfile && send_stdout) {
652 fprintf(stderr, "The -o and -O options cannot be used together.\n");
656 if(smbc_init(get_auth_data, debuglevel) < 0) {
657 fprintf(stderr, "Unable to initialize libsmbclient\n");
662 SMBCCTX *smb_ctx = smbc_set_context(NULL);
663 smbc_option_set(smb_ctx,
664 CONST_DISCARD(char *, "smb_encrypt_level"),
668 columns = get_num_cols();
670 total_start_time = time_mono(NULL);
672 while ( (file = poptGetArg(pc)) ) {
674 ret = smb_download_file(file, "", recursive, resume,
677 ret = smb_download_dir(file, "", resume);