2 smbget: a wget-like utility with support for recursive downloading of
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 "system/filesys.h"
21 #include "popt_common_cmdline.h"
22 #include "libsmbclient.h"
23 #include "cmdline_contexts.h"
25 static int columns
= 0;
27 static time_t total_start_time
= 0;
28 static off_t total_bytes
= 0;
30 #define SMB_MAXPATHLEN MAXPATHLEN
33 * Number of bytes to read when checking whether local and remote file
34 * are really the same file
36 #define RESUME_CHECK_SIZE 512
37 #define RESUME_DOWNLOAD_OFFSET 1024
38 #define RESUME_CHECK_OFFSET (RESUME_DOWNLOAD_OFFSET+RESUME_CHECK_SIZE)
39 /* Number of bytes to read at once */
40 #define SMB_DEFAULT_BLOCKSIZE 64000
44 bool username_specified
;
46 bool password_specified
;
60 static struct opt opt
= { .blocksize
= SMB_DEFAULT_BLOCKSIZE
};
62 static bool smb_download_file(const char *base
, const char *name
,
63 bool recursive
, bool resume
, bool toplevel
,
66 static int get_num_cols(void)
70 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) < 0) {
75 #warning No support for TIOCGWINSZ
76 char *cols
= getenv("COLUMNS");
84 static void change_columns(int sig
)
86 columns
= get_num_cols();
89 static void human_readable(off_t s
, char *buffer
, int l
)
91 if (s
> 1024 * 1024 * 1024) {
92 snprintf(buffer
, l
, "%.2fGB", 1.0 * s
/ (1024 * 1024 * 1024));
93 } else if (s
> 1024 * 1024) {
94 snprintf(buffer
, l
, "%.2fMB", 1.0 * s
/ (1024 * 1024));
95 } else if (s
> 1024) {
96 snprintf(buffer
, l
, "%.2fkB", 1.0 * s
/ 1024);
98 snprintf(buffer
, l
, "%jdb", (intmax_t)s
);
102 static void get_auth_data(const char *srv
, const char *shr
, char *wg
, int wglen
,
103 char *un
, int unlen
, char *pw
, int pwlen
)
105 static bool hasasked
= false;
106 static char *savedwg
;
107 static char *savedun
;
108 static char *savedpw
;
111 strncpy(wg
, savedwg
, wglen
- 1);
112 strncpy(un
, savedun
, unlen
- 1);
113 strncpy(pw
, savedpw
, pwlen
- 1);
119 * If no user has been specified un is initialized with the current
120 * username of the user who started smbget.
122 if (opt
.username_specified
) {
123 strncpy(un
, opt
.username
, unlen
- 1);
126 if (!opt
.nonprompt
&& !opt
.password_specified
&& pw
[0] == '\0') {
130 rc
= asprintf(&prompt
,
131 "Password for [%s] connecting to //%s/%s: ",
136 (void)samba_getpass(prompt
, pw
, pwlen
, false, false);
138 } else if (opt
.password
!= NULL
) {
139 strncpy(pw
, opt
.password
, pwlen
-1);
142 if (opt
.workgroup
!= NULL
) {
143 strncpy(wg
, opt
.workgroup
, wglen
-1);
146 /* save the values found for later */
147 savedwg
= SMB_STRDUP(wg
);
148 savedun
= SMB_STRDUP(un
);
149 savedpw
= SMB_STRDUP(pw
);
152 char *wgtmp
, *usertmp
;
153 wgtmp
= SMB_STRNDUP(wg
, wglen
);
154 usertmp
= SMB_STRNDUP(un
, unlen
);
155 printf("Using workgroup %s, %s%s\n",
157 *usertmp
? "user " : "guest user",
164 static bool smb_download_dir(const char *base
, const char *name
, int resume
)
166 char path
[SMB_MAXPATHLEN
];
168 struct smbc_dirent
*dirent
;
169 const char *relname
= name
;
173 snprintf(path
, SMB_MAXPATHLEN
-1, "%s%s%s", base
,
174 (base
[0] && name
[0] && name
[0] != '/' &&
175 base
[strlen(base
)-1] != '/') ? "/" : "",
178 /* List files in directory and call smb_download_file on them */
179 dirhandle
= smbc_opendir(path
);
181 if (errno
== ENOTDIR
) {
182 return smb_download_file(base
, name
, true, resume
,
185 fprintf(stderr
, "Can't open directory %s: %s\n", path
,
190 while (*relname
== '/') {
193 mkdir(relname
, 0755);
195 tmpname
= SMB_STRDUP(name
);
197 while ((dirent
= smbc_readdir(dirhandle
))) {
199 if (!strcmp(dirent
->name
, ".") || !strcmp(dirent
->name
, "..")) {
202 if (asprintf(&newname
, "%s/%s", tmpname
, dirent
->name
) == -1) {
206 switch (dirent
->smbc_type
) {
208 ok
= smb_download_dir(base
, newname
, resume
);
212 ok
= smb_download_dir("smb://", dirent
->name
, resume
);
216 ok
= smb_download_dir("smb://", dirent
->name
, resume
);
220 ok
= smb_download_file(base
, newname
, true, resume
,
224 case SMBC_FILE_SHARE
:
225 ok
= smb_download_dir(base
, newname
, resume
);
228 case SMBC_PRINTER_SHARE
:
230 printf("Ignoring printer share %s\n",
235 case SMBC_COMMS_SHARE
:
237 printf("Ignoring comms share %s\n",
244 printf("Ignoring ipc$ share %s\n",
250 fprintf(stderr
, "Ignoring file '%s' of type '%d'\n",
251 newname
, dirent
->smbc_type
);
256 fprintf(stderr
, "Failed to download %s: %s\n",
257 newname
, strerror(errno
));
265 smbc_closedir(dirhandle
);
269 static char *print_time(long t
)
271 static char buffer
[100];
272 int secs
, mins
, hours
;
274 strncpy(buffer
, "Unknown", sizeof(buffer
));
279 mins
= (int)t
/ 60 % 60;
280 hours
= (int)t
/ (60 * 60);
281 snprintf(buffer
, sizeof(buffer
) - 1, "%02d:%02d:%02d", hours
, mins
,
286 static void print_progress(const char *name
, time_t start
, time_t now
,
287 off_t start_pos
, off_t pos
, off_t total
)
292 char hpos
[22], htotal
[22], havg
[22];
293 char *status
, *filename
;
296 avg
= 1.0 * (pos
- start_pos
) / (now
- start
);
298 eta
= (total
- pos
) / avg
;
300 prcnt
= 100.0 * pos
/ total
;
303 human_readable(pos
, hpos
, sizeof(hpos
));
304 human_readable(total
, htotal
, sizeof(htotal
));
305 human_readable(avg
, havg
, sizeof(havg
));
307 len
= asprintf(&status
, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos
,
308 htotal
, prcnt
, havg
, print_time(eta
));
314 int required
= strlen(name
),
315 available
= columns
- len
- strlen("[] ");
316 if (required
> available
) {
317 if (asprintf(&filename
, "...%s",
318 name
+ required
- available
+ 3) == -1) {
322 filename
= SMB_STRNDUP(name
, available
);
325 filename
= SMB_STRDUP(name
);
328 fprintf(stderr
, "\r[%s] %s", filename
, status
);
334 /* Return false on error, true on success. */
336 static bool smb_download_file(const char *base
, const char *name
,
337 bool recursive
, bool resume
, bool toplevel
,
340 int remotehandle
, localhandle
;
341 time_t start_time
= time_mono(NULL
);
343 char path
[SMB_MAXPATHLEN
];
344 char checkbuf
[2][RESUME_CHECK_SIZE
];
345 char *readbuf
= NULL
;
346 off_t offset_download
= 0, offset_check
= 0, curpos
= 0,
348 struct stat localstat
, remotestat
;
350 snprintf(path
, SMB_MAXPATHLEN
-1, "%s%s%s", base
,
351 (*base
&& *name
&& name
[0] != '/' &&
352 base
[strlen(base
)-1] != '/') ? "/" : "",
355 remotehandle
= smbc_open(path
, O_RDONLY
, 0755);
357 if (remotehandle
< 0) {
362 "%s is a directory. Specify -R "
363 "to download recursively\n",
367 return smb_download_dir(base
, name
, resume
);
371 "%s can't be found on the remote server\n",
376 fprintf(stderr
, "Not enough memory\n");
381 "The share name used in %s does not exist\n",
386 fprintf(stderr
, "You don't have enough permissions "
397 if (smbc_fstat(remotehandle
, &remotestat
) < 0) {
398 fprintf(stderr
, "Can't stat %s: %s\n", path
, strerror(errno
));
404 } else if (!name
[0]) {
405 newpath
= strrchr(base
, '/');
415 if (!toplevel
&& (newpath
[0] == '/')) {
419 /* Open local file according to the mode */
421 /* if it is up-to-date, skip */
422 if (stat(newpath
, &localstat
) == 0 &&
423 localstat
.st_mtime
>= remotestat
.st_mtime
) {
425 printf("%s is up-to-date, skipping\n", newpath
);
427 smbc_close(remotehandle
);
430 /* else open it for writing and truncate if it exists */
432 newpath
, O_CREAT
| O_NONBLOCK
| O_RDWR
| O_TRUNC
, 0775);
433 if (localhandle
< 0) {
434 fprintf(stderr
, "Can't open %s : %s\n", newpath
,
436 smbc_close(remotehandle
);
440 } else if (!opt
.send_stdout
) {
441 localhandle
= open(newpath
, O_CREAT
| O_NONBLOCK
| O_RDWR
|
442 (!resume
? O_EXCL
: 0),
444 if (localhandle
< 0) {
445 fprintf(stderr
, "Can't open %s: %s\n", newpath
,
447 smbc_close(remotehandle
);
451 if (fstat(localhandle
, &localstat
) != 0) {
452 fprintf(stderr
, "Can't fstat %s: %s\n", newpath
,
454 smbc_close(remotehandle
);
459 start_offset
= localstat
.st_size
;
461 if (localstat
.st_size
&&
462 localstat
.st_size
== remotestat
.st_size
) {
464 fprintf(stderr
, "%s is already downloaded "
467 } else if (!opt
.quiet
) {
468 fprintf(stderr
, "%s\n", path
);
470 smbc_close(remotehandle
);
475 if (localstat
.st_size
> RESUME_CHECK_OFFSET
&&
476 remotestat
.st_size
> RESUME_CHECK_OFFSET
) {
478 localstat
.st_size
- RESUME_DOWNLOAD_OFFSET
;
479 offset_check
= localstat
.st_size
- RESUME_CHECK_OFFSET
;
481 printf("Trying to start resume of %s at %jd\n"
482 "At the moment %jd of %jd bytes have "
484 newpath
, (intmax_t)offset_check
,
485 (intmax_t)localstat
.st_size
,
486 (intmax_t)remotestat
.st_size
);
492 /* First, check all bytes from offset_check to
494 off1
= lseek(localhandle
, offset_check
, SEEK_SET
);
497 "Can't seek to %jd in local file %s\n",
498 (intmax_t)offset_check
, newpath
);
499 smbc_close(remotehandle
);
504 off2
= smbc_lseek(remotehandle
, offset_check
, SEEK_SET
);
507 "Can't seek to %jd in remote file %s\n",
508 (intmax_t)offset_check
, newpath
);
509 smbc_close(remotehandle
);
515 fprintf(stderr
, "Offset in local and remote "
516 "files are different "
517 "(local: %jd, remote: %jd)\n",
518 (intmax_t)off1
, (intmax_t)off2
);
519 smbc_close(remotehandle
);
524 if (smbc_read(remotehandle
, checkbuf
[0],
525 RESUME_CHECK_SIZE
) != RESUME_CHECK_SIZE
) {
526 fprintf(stderr
, "Can't read %d bytes from "
528 RESUME_CHECK_SIZE
, path
);
529 smbc_close(remotehandle
);
534 if (read(localhandle
, checkbuf
[1], RESUME_CHECK_SIZE
) !=
536 fprintf(stderr
, "Can't read %d bytes from "
538 RESUME_CHECK_SIZE
, name
);
539 smbc_close(remotehandle
);
544 if (memcmp(checkbuf
[0], checkbuf
[1],
545 RESUME_CHECK_SIZE
) == 0) {
547 printf("Current local and remote file "
548 "appear to be the same. "
549 "Starting download from "
551 (intmax_t)offset_download
);
554 fprintf(stderr
, "Local and remote file appear "
555 "to be different, not "
556 "doing resume for %s\n",
558 smbc_close(remotehandle
);
564 localhandle
= STDOUT_FILENO
;
570 readbuf
= (char *)SMB_MALLOC(opt
.blocksize
);
572 fprintf(stderr
, "Failed to allocate %zu bytes for read "
573 "buffer (%s)", opt
.blocksize
, strerror(errno
));
574 if (localhandle
!= STDOUT_FILENO
) {
580 /* Now, download all bytes from offset_download to the end */
581 for (curpos
= offset_download
; curpos
< remotestat
.st_size
;
582 curpos
+= opt
.blocksize
) {
584 ssize_t byteswritten
;
586 bytesread
= smbc_read(remotehandle
, readbuf
, opt
.blocksize
);
589 "Can't read %zu bytes at offset %jd, file %s\n",
590 opt
.blocksize
, (intmax_t)curpos
, path
);
591 smbc_close(remotehandle
);
592 if (localhandle
!= STDOUT_FILENO
) {
599 total_bytes
+= bytesread
;
601 byteswritten
= write(localhandle
, readbuf
, bytesread
);
602 if (byteswritten
!= bytesread
) {
604 "Can't write %zd bytes to local file %s at "
605 "offset %jd\n", bytesread
, path
,
608 smbc_close(remotehandle
);
609 if (localhandle
!= STDOUT_FILENO
) {
617 } else if (!opt
.quiet
) {
618 print_progress(newpath
, start_time
, time_mono(NULL
),
619 start_offset
, curpos
,
628 printf("%s downloaded\n", path
);
629 } else if (!opt
.quiet
) {
631 fprintf(stderr
, "\r%s", path
);
633 for (i
= strlen(path
); i
< columns
; i
++) {
640 smbc_close(remotehandle
);
641 if (localhandle
!= STDOUT_FILENO
) {
647 static void clean_exit(void)
650 human_readable(total_bytes
, bs
, sizeof(bs
));
652 fprintf(stderr
, "Downloaded %s in %lu seconds\n", bs
,
653 (unsigned long)(time_mono(NULL
) - total_start_time
));
658 static void signal_quit(int v
)
663 static int readrcfile(const char *name
, const struct poptOption long_options
[])
665 FILE *fd
= fopen(name
, "r");
667 char var
[101], val
[101];
672 fprintf(stderr
, "Can't open RC file %s\n", name
);
678 if (fscanf(fd
, "%100s %100s\n", var
, val
) < 2) {
680 "Can't parse line %d of %s, ignoring.\n",
687 for (i
= 0; long_options
[i
].argInfo
; i
++) {
688 if (!long_options
[i
].longName
) {
691 if (strcmp(long_options
[i
].longName
, var
)) {
694 if (!long_options
[i
].arg
) {
698 switch (long_options
[i
].argInfo
) {
700 intdata
= (int *)long_options
[i
].arg
;
701 if (!strcmp(val
, "on")) {
703 } else if (!strcmp(val
, "off")) {
706 fprintf(stderr
, "Illegal value %s for "
707 "%s at line %d in %s\n",
708 val
, var
, lineno
, name
);
712 intdata
= (int *)long_options
[i
].arg
;
713 *intdata
= atoi(val
);
715 case POPT_ARG_STRING
:
716 stringdata
= (char **)long_options
[i
].arg
;
717 *stringdata
= SMB_STRDUP(val
);
718 if (long_options
[i
].shortName
== 'U') {
720 opt
.username_specified
= true;
721 p
= strchr(*stringdata
, '%');
724 opt
.password
= p
+ 1;
725 opt
.password_specified
= true;
730 fprintf(stderr
, "Invalid variable %s at "
740 "Invalid variable %s at line %d in %s\n", var
,
749 int main(int argc
, char **argv
)
752 const char *file
= NULL
;
754 bool smb_encrypt
= false;
755 int resume
= 0, recursive
= 0;
756 TALLOC_CTX
*frame
= talloc_stackframe();
759 const char **argv_const
= discard_const_p(const char *, argv
);
760 struct poptOption long_options
[] = {
763 {"workgroup", 'w', POPT_ARG_STRING
, &opt
.workgroup
, 'w', "Workgroup to use (optional)" },
764 {"user", 'U', POPT_ARG_STRING
, &opt
.username
, 'U', "Username to use" },
765 {"guest", 'a', POPT_ARG_NONE
, NULL
, 'a', "Work as user guest" },
767 {"nonprompt", 'n', POPT_ARG_NONE
, NULL
, 'n', "Don't ask anything (non-interactive)" },
768 {"debuglevel", 'd', POPT_ARG_INT
, &opt
.debuglevel
, 'd', "Debuglevel to use" },
770 {"encrypt", 'e', POPT_ARG_NONE
, NULL
, 'e', "Encrypt SMB transport" },
771 {"resume", 'r', POPT_ARG_NONE
, NULL
, 'r', "Automatically resume aborted files" },
772 {"update", 'u', POPT_ARG_NONE
, NULL
, 'u', "Download only when remote file is newer than local file or local file is missing"},
773 {"recursive", 'R', POPT_ARG_NONE
, NULL
, 'R', "Recursively download files" },
774 {"blocksize", 'b', POPT_ARG_INT
, &opt
.blocksize
, 'b', "Change number of bytes in a block"},
776 {"outputfile", 'o', POPT_ARG_STRING
, &opt
.outputfile
, 'o', "Write downloaded data to specified file" },
777 {"stdout", 'O', POPT_ARG_NONE
, NULL
, 'O', "Write data to stdout" },
778 {"dots", 'D', POPT_ARG_NONE
, NULL
, 'D', "Show dots as progress indication" },
779 {"quiet", 'q', POPT_ARG_NONE
, NULL
, 'q', "Be quiet" },
780 {"verbose", 'v', POPT_ARG_NONE
, NULL
, 'v', "Be verbose" },
781 {"rcfile", 'f', POPT_ARG_STRING
, NULL
, 'f', "Use specified rc file"},
789 /* only read rcfile if it exists */
790 if (asprintf(&rcfile
, "%s/.smbgetrc", getenv("HOME")) == -1) {
793 if (access(rcfile
, F_OK
) == 0) {
794 readrcfile(rcfile
, long_options
);
799 signal(SIGWINCH
, change_columns
);
801 signal(SIGINT
, signal_quit
);
802 signal(SIGTERM
, signal_quit
);
804 pc
= poptGetContext(argv
[0], argc
, argv_const
, long_options
, 0);
806 while ((c
= poptGetNextOpt(pc
)) > 0) {
809 readrcfile(poptGetOptArg(pc
), long_options
);
812 opt
.username_specified
= true;
813 opt
.username
= talloc_strdup(frame
, "");
814 opt
.password_specified
= true;
815 opt
.password
= talloc_strdup(frame
, "");
821 opt
.username_specified
= true;
822 opt
.username
= talloc_strdup(frame
, opt
.username
);
823 p
= strchr(opt
.username
,'%');
826 opt
.password
= p
+ 1;
827 opt
.password_specified
= true;
831 opt
.nonprompt
= true;
843 opt
.send_stdout
= true;
858 fprintf(stderr
, "%s: %s\n",
859 poptBadOption(pc
, POPT_BADOPTION_NOALIAS
),
864 if ((opt
.send_stdout
|| resume
|| opt
.outputfile
) && opt
.update
) {
865 fprintf(stderr
, "The -o, -R or -O and -U options can not be "
869 if ((opt
.send_stdout
|| opt
.outputfile
) && recursive
) {
870 fprintf(stderr
, "The -o or -O and -R options can not be "
875 if (opt
.outputfile
&& opt
.send_stdout
) {
876 fprintf(stderr
, "The -o and -O options can not be "
881 popt_burn_cmdline_password(argc
, argv
);
883 cmdline_messaging_context(get_dyn_CONFIGFILE());
885 if (smbc_init(get_auth_data
, opt
.debuglevel
) < 0) {
886 fprintf(stderr
, "Unable to initialize libsmbclient\n");
891 SMBCCTX
*smb_ctx
= smbc_set_context(NULL
);
892 smbc_option_set(smb_ctx
,
893 discard_const_p(char, "smb_encrypt_level"),
897 columns
= get_num_cols();
899 total_start_time
= time_mono(NULL
);
901 while ((file
= poptGetArg(pc
))) {
903 ret
= smb_download_file(file
, "", recursive
, resume
,
904 true, opt
.outputfile
);
906 ret
= smb_download_dir(file
, "", resume
);