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.h"
22 #include "libsmbclient.h"
24 static int columns
= 0;
26 static time_t total_start_time
= 0;
27 static off_t total_bytes
= 0;
29 #define SMB_MAXPATHLEN MAXPATHLEN
32 * Number of bytes to read when checking whether local and remote file
33 * are really the same file
35 #define RESUME_CHECK_SIZE 512
36 #define RESUME_DOWNLOAD_OFFSET 1024
37 #define RESUME_CHECK_OFFSET (RESUME_DOWNLOAD_OFFSET+RESUME_CHECK_SIZE)
38 /* Number of bytes to read at once */
39 #define SMB_DEFAULT_BLOCKSIZE 64000
43 bool username_specified
;
45 bool password_specified
;
59 static struct opt opt
= { .blocksize
= SMB_DEFAULT_BLOCKSIZE
};
61 static bool smb_download_file(const char *base
, const char *name
,
62 bool recursive
, bool resume
, bool toplevel
,
65 static int get_num_cols(void)
69 if (ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &ws
) < 0) {
74 #warning No support for TIOCGWINSZ
75 char *cols
= getenv("COLUMNS");
83 static void change_columns(int sig
)
85 columns
= get_num_cols();
88 static void human_readable(off_t s
, char *buffer
, int l
)
90 if (s
> 1024 * 1024 * 1024) {
91 snprintf(buffer
, l
, "%.2fGB", 1.0 * s
/ (1024 * 1024 * 1024));
92 } else if (s
> 1024 * 1024) {
93 snprintf(buffer
, l
, "%.2fMB", 1.0 * s
/ (1024 * 1024));
94 } else if (s
> 1024) {
95 snprintf(buffer
, l
, "%.2fkB", 1.0 * s
/ 1024);
97 snprintf(buffer
, l
, "%jdb", (intmax_t)s
);
101 static void get_auth_data(const char *srv
, const char *shr
, char *wg
, int wglen
,
102 char *un
, int unlen
, char *pw
, int pwlen
)
104 static bool hasasked
= false;
105 static char *savedwg
;
106 static char *savedun
;
107 static char *savedpw
;
110 strncpy(wg
, savedwg
, wglen
- 1);
111 strncpy(un
, savedun
, unlen
- 1);
112 strncpy(pw
, savedpw
, pwlen
- 1);
118 * If no user has been specified un is initialized with the current
119 * username of the user who started smbget.
121 if (opt
.username_specified
) {
122 strncpy(un
, opt
.username
, unlen
- 1);
125 if (!opt
.nonprompt
&& !opt
.password_specified
&& pw
[0] == '\0') {
129 rc
= asprintf(&prompt
,
130 "Password for [%s] connecting to //%s/%s: ",
135 (void)samba_getpass(prompt
, pw
, pwlen
, false, false);
137 } else if (opt
.password
!= NULL
) {
138 strncpy(pw
, opt
.password
, pwlen
-1);
141 if (opt
.workgroup
!= NULL
) {
142 strncpy(wg
, opt
.workgroup
, wglen
-1);
145 /* save the values found for later */
146 savedwg
= SMB_STRDUP(wg
);
147 savedun
= SMB_STRDUP(un
);
148 savedpw
= SMB_STRDUP(pw
);
151 char *wgtmp
, *usertmp
;
152 wgtmp
= SMB_STRNDUP(wg
, wglen
);
153 usertmp
= SMB_STRNDUP(un
, unlen
);
154 printf("Using workgroup %s, %s%s\n",
156 *usertmp
? "user " : "guest user",
163 static bool smb_download_dir(const char *base
, const char *name
, int resume
)
165 char path
[SMB_MAXPATHLEN
];
167 struct smbc_dirent
*dirent
;
168 const char *relname
= name
;
172 snprintf(path
, SMB_MAXPATHLEN
-1, "%s%s%s", base
,
173 (base
[0] && name
[0] && name
[0] != '/' &&
174 base
[strlen(base
)-1] != '/') ? "/" : "",
177 /* List files in directory and call smb_download_file on them */
178 dirhandle
= smbc_opendir(path
);
180 if (errno
== ENOTDIR
) {
181 return smb_download_file(base
, name
, true, resume
,
184 fprintf(stderr
, "Can't open directory %s: %s\n", path
,
189 while (*relname
== '/') {
192 mkdir(relname
, 0755);
194 tmpname
= SMB_STRDUP(name
);
196 while ((dirent
= smbc_readdir(dirhandle
))) {
198 if (!strcmp(dirent
->name
, ".") || !strcmp(dirent
->name
, "..")) {
201 if (asprintf(&newname
, "%s/%s", tmpname
, dirent
->name
) == -1) {
205 switch (dirent
->smbc_type
) {
207 ok
= smb_download_dir(base
, newname
, resume
);
211 ok
= smb_download_dir("smb://", dirent
->name
, resume
);
215 ok
= smb_download_dir("smb://", dirent
->name
, resume
);
219 ok
= smb_download_file(base
, newname
, true, resume
,
223 case SMBC_FILE_SHARE
:
224 ok
= smb_download_dir(base
, newname
, resume
);
227 case SMBC_PRINTER_SHARE
:
229 printf("Ignoring printer share %s\n",
234 case SMBC_COMMS_SHARE
:
236 printf("Ignoring comms share %s\n",
243 printf("Ignoring ipc$ share %s\n",
249 fprintf(stderr
, "Ignoring file '%s' of type '%d'\n",
250 newname
, dirent
->smbc_type
);
255 fprintf(stderr
, "Failed to download %s: %s\n",
256 newname
, strerror(errno
));
264 smbc_closedir(dirhandle
);
268 static char *print_time(long t
)
270 static char buffer
[100];
271 int secs
, mins
, hours
;
273 strncpy(buffer
, "Unknown", sizeof(buffer
));
278 mins
= (int)t
/ 60 % 60;
279 hours
= (int)t
/ (60 * 60);
280 snprintf(buffer
, sizeof(buffer
) - 1, "%02d:%02d:%02d", hours
, mins
,
285 static void print_progress(const char *name
, time_t start
, time_t now
,
286 off_t start_pos
, off_t pos
, off_t total
)
291 char hpos
[20], htotal
[20], havg
[20];
292 char *status
, *filename
;
295 avg
= 1.0 * (pos
- start_pos
) / (now
- start
);
297 eta
= (total
- pos
) / avg
;
299 prcnt
= 100.0 * pos
/ total
;
302 human_readable(pos
, hpos
, sizeof(hpos
));
303 human_readable(total
, htotal
, sizeof(htotal
));
304 human_readable(avg
, havg
, sizeof(havg
));
306 len
= asprintf(&status
, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos
,
307 htotal
, prcnt
, havg
, print_time(eta
));
313 int required
= strlen(name
),
314 available
= columns
- len
- strlen("[] ");
315 if (required
> available
) {
316 if (asprintf(&filename
, "...%s",
317 name
+ required
- available
+ 3) == -1) {
321 filename
= SMB_STRNDUP(name
, available
);
324 filename
= SMB_STRDUP(name
);
327 fprintf(stderr
, "\r[%s] %s", filename
, status
);
333 /* Return false on error, true on success. */
335 static bool smb_download_file(const char *base
, const char *name
,
336 bool recursive
, bool resume
, bool toplevel
,
339 int remotehandle
, localhandle
;
340 time_t start_time
= time_mono(NULL
);
342 char path
[SMB_MAXPATHLEN
];
343 char checkbuf
[2][RESUME_CHECK_SIZE
];
344 char *readbuf
= NULL
;
345 off_t offset_download
= 0, offset_check
= 0, curpos
= 0,
347 struct stat localstat
, remotestat
;
349 snprintf(path
, SMB_MAXPATHLEN
-1, "%s%s%s", base
,
350 (*base
&& *name
&& name
[0] != '/' &&
351 base
[strlen(base
)-1] != '/') ? "/" : "",
354 remotehandle
= smbc_open(path
, O_RDONLY
, 0755);
356 if (remotehandle
< 0) {
361 "%s is a directory. Specify -R "
362 "to download recursively\n",
366 return smb_download_dir(base
, name
, resume
);
370 "%s can't be found on the remote server\n",
375 fprintf(stderr
, "Not enough memory\n");
380 "The share name used in %s does not exist\n",
385 fprintf(stderr
, "You don't have enough permissions "
396 if (smbc_fstat(remotehandle
, &remotestat
) < 0) {
397 fprintf(stderr
, "Can't stat %s: %s\n", path
, strerror(errno
));
403 } else if (!name
[0]) {
404 newpath
= strrchr(base
, '/');
414 if (!toplevel
&& (newpath
[0] == '/')) {
418 /* Open local file according to the mode */
420 /* if it is up-to-date, skip */
421 if (stat(newpath
, &localstat
) == 0 &&
422 localstat
.st_mtime
>= remotestat
.st_mtime
) {
424 printf("%s is up-to-date, skipping\n", newpath
);
426 smbc_close(remotehandle
);
429 /* else open it for writing and truncate if it exists */
431 newpath
, O_CREAT
| O_NONBLOCK
| O_RDWR
| O_TRUNC
, 0775);
432 if (localhandle
< 0) {
433 fprintf(stderr
, "Can't open %s : %s\n", newpath
,
435 smbc_close(remotehandle
);
439 } else if (!opt
.send_stdout
) {
440 localhandle
= open(newpath
, O_CREAT
| O_NONBLOCK
| O_RDWR
|
441 (!resume
? O_EXCL
: 0),
443 if (localhandle
< 0) {
444 fprintf(stderr
, "Can't open %s: %s\n", newpath
,
446 smbc_close(remotehandle
);
450 if (fstat(localhandle
, &localstat
) != 0) {
451 fprintf(stderr
, "Can't fstat %s: %s\n", newpath
,
453 smbc_close(remotehandle
);
458 start_offset
= localstat
.st_size
;
460 if (localstat
.st_size
&&
461 localstat
.st_size
== remotestat
.st_size
) {
463 fprintf(stderr
, "%s is already downloaded "
466 } else if (!opt
.quiet
) {
467 fprintf(stderr
, "%s\n", path
);
469 smbc_close(remotehandle
);
474 if (localstat
.st_size
> RESUME_CHECK_OFFSET
&&
475 remotestat
.st_size
> RESUME_CHECK_OFFSET
) {
477 localstat
.st_size
- RESUME_DOWNLOAD_OFFSET
;
478 offset_check
= localstat
.st_size
- RESUME_CHECK_OFFSET
;
480 printf("Trying to start resume of %s at %jd\n"
481 "At the moment %jd of %jd bytes have "
483 newpath
, (intmax_t)offset_check
,
484 (intmax_t)localstat
.st_size
,
485 (intmax_t)remotestat
.st_size
);
491 /* First, check all bytes from offset_check to
493 off1
= lseek(localhandle
, offset_check
, SEEK_SET
);
496 "Can't seek to %jd in local file %s\n",
497 (intmax_t)offset_check
, newpath
);
498 smbc_close(remotehandle
);
503 off2
= smbc_lseek(remotehandle
, offset_check
, SEEK_SET
);
506 "Can't seek to %jd in remote file %s\n",
507 (intmax_t)offset_check
, newpath
);
508 smbc_close(remotehandle
);
514 fprintf(stderr
, "Offset in local and remote "
515 "files are different "
516 "(local: %jd, remote: %jd)\n",
517 (intmax_t)off1
, (intmax_t)off2
);
518 smbc_close(remotehandle
);
523 if (smbc_read(remotehandle
, checkbuf
[0],
524 RESUME_CHECK_SIZE
) != RESUME_CHECK_SIZE
) {
525 fprintf(stderr
, "Can't read %d bytes from "
527 RESUME_CHECK_SIZE
, path
);
528 smbc_close(remotehandle
);
533 if (read(localhandle
, checkbuf
[1], RESUME_CHECK_SIZE
) !=
535 fprintf(stderr
, "Can't read %d bytes from "
537 RESUME_CHECK_SIZE
, name
);
538 smbc_close(remotehandle
);
543 if (memcmp(checkbuf
[0], checkbuf
[1],
544 RESUME_CHECK_SIZE
) == 0) {
546 printf("Current local and remote file "
547 "appear to be the same. "
548 "Starting download from "
550 (intmax_t)offset_download
);
553 fprintf(stderr
, "Local and remote file appear "
554 "to be different, not "
555 "doing resume for %s\n",
557 smbc_close(remotehandle
);
563 localhandle
= STDOUT_FILENO
;
569 readbuf
= (char *)SMB_MALLOC(opt
.blocksize
);
571 fprintf(stderr
, "Failed to allocate %zu bytes for read "
572 "buffer (%s)", opt
.blocksize
, strerror(errno
));
573 if (localhandle
!= STDOUT_FILENO
) {
579 /* Now, download all bytes from offset_download to the end */
580 for (curpos
= offset_download
; curpos
< remotestat
.st_size
;
581 curpos
+= opt
.blocksize
) {
583 ssize_t byteswritten
;
585 bytesread
= smbc_read(remotehandle
, readbuf
, opt
.blocksize
);
588 "Can't read %zu bytes at offset %jd, file %s\n",
589 opt
.blocksize
, (intmax_t)curpos
, path
);
590 smbc_close(remotehandle
);
591 if (localhandle
!= STDOUT_FILENO
) {
598 total_bytes
+= bytesread
;
600 byteswritten
= write(localhandle
, readbuf
, bytesread
);
601 if (byteswritten
!= bytesread
) {
603 "Can't write %zd bytes to local file %s at "
604 "offset %jd\n", bytesread
, path
,
607 smbc_close(remotehandle
);
608 if (localhandle
!= STDOUT_FILENO
) {
616 } else if (!opt
.quiet
) {
617 print_progress(newpath
, start_time
, time_mono(NULL
),
618 start_offset
, curpos
,
627 printf("%s downloaded\n", path
);
628 } else if (!opt
.quiet
) {
630 fprintf(stderr
, "\r%s", path
);
632 for (i
= strlen(path
); i
< columns
; i
++) {
639 smbc_close(remotehandle
);
640 if (localhandle
!= STDOUT_FILENO
) {
646 static void clean_exit(void)
649 human_readable(total_bytes
, bs
, sizeof(bs
));
651 fprintf(stderr
, "Downloaded %s in %lu seconds\n", bs
,
652 (unsigned long)(time_mono(NULL
) - total_start_time
));
657 static void signal_quit(int v
)
662 static int readrcfile(const char *name
, const struct poptOption long_options
[])
664 FILE *fd
= fopen(name
, "r");
666 char var
[101], val
[101];
671 fprintf(stderr
, "Can't open RC file %s\n", name
);
677 if (fscanf(fd
, "%100s %100s\n", var
, val
) < 2) {
679 "Can't parse line %d of %s, ignoring.\n",
686 for (i
= 0; long_options
[i
].argInfo
; i
++) {
687 if (!long_options
[i
].longName
) {
690 if (strcmp(long_options
[i
].longName
, var
)) {
693 if (!long_options
[i
].arg
) {
697 switch (long_options
[i
].argInfo
) {
699 intdata
= (int *)long_options
[i
].arg
;
700 if (!strcmp(val
, "on")) {
702 } else if (!strcmp(val
, "off")) {
705 fprintf(stderr
, "Illegal value %s for "
706 "%s at line %d in %s\n",
707 val
, var
, lineno
, name
);
711 intdata
= (int *)long_options
[i
].arg
;
712 *intdata
= atoi(val
);
714 case POPT_ARG_STRING
:
715 stringdata
= (char **)long_options
[i
].arg
;
716 *stringdata
= SMB_STRDUP(val
);
717 if (long_options
[i
].shortName
== 'U') {
719 opt
.username_specified
= true;
720 p
= strchr(*stringdata
, '%');
723 opt
.password
= p
+ 1;
724 opt
.password_specified
= true;
729 fprintf(stderr
, "Invalid variable %s at "
739 "Invalid variable %s at line %d in %s\n", var
,
748 int main(int argc
, char **argv
)
751 const char *file
= NULL
;
753 bool smb_encrypt
= false;
754 int resume
= 0, recursive
= 0;
755 TALLOC_CTX
*frame
= talloc_stackframe();
758 const char **argv_const
= discard_const_p(const char *, argv
);
759 struct poptOption long_options
[] = {
762 {"workgroup", 'w', POPT_ARG_STRING
, &opt
.workgroup
, 'w', "Workgroup to use (optional)" },
763 {"user", 'U', POPT_ARG_STRING
, &opt
.username
, 'U', "Username to use" },
764 {"guest", 'a', POPT_ARG_NONE
, NULL
, 'a', "Work as user guest" },
766 {"nonprompt", 'n', POPT_ARG_NONE
, NULL
, 'n', "Don't ask anything (non-interactive)" },
767 {"debuglevel", 'd', POPT_ARG_INT
, &opt
.debuglevel
, 'd', "Debuglevel to use" },
769 {"encrypt", 'e', POPT_ARG_NONE
, NULL
, 'e', "Encrypt SMB transport" },
770 {"resume", 'r', POPT_ARG_NONE
, NULL
, 'r', "Automatically resume aborted files" },
771 {"update", 'u', POPT_ARG_NONE
, NULL
, 'u', "Download only when remote file is newer than local file or local file is missing"},
772 {"recursive", 'R', POPT_ARG_NONE
, NULL
, 'R', "Recursively download files" },
773 {"blocksize", 'b', POPT_ARG_INT
, &opt
.blocksize
, 'b', "Change number of bytes in a block"},
775 {"outputfile", 'o', POPT_ARG_STRING
, &opt
.outputfile
, 'o', "Write downloaded data to specified file" },
776 {"stdout", 'O', POPT_ARG_NONE
, NULL
, 'O', "Write data to stdout" },
777 {"dots", 'D', POPT_ARG_NONE
, NULL
, 'D', "Show dots as progress indication" },
778 {"quiet", 'q', POPT_ARG_NONE
, NULL
, 'q', "Be quiet" },
779 {"verbose", 'v', POPT_ARG_NONE
, NULL
, 'v', "Be verbose" },
780 {"rcfile", 'f', POPT_ARG_STRING
, NULL
, 'f', "Use specified rc file"},
788 /* only read rcfile if it exists */
789 if (asprintf(&rcfile
, "%s/.smbgetrc", getenv("HOME")) == -1) {
792 if (access(rcfile
, F_OK
) == 0) {
793 readrcfile(rcfile
, long_options
);
798 signal(SIGWINCH
, change_columns
);
800 signal(SIGINT
, signal_quit
);
801 signal(SIGTERM
, signal_quit
);
803 pc
= poptGetContext(argv
[0], argc
, argv_const
, long_options
, 0);
805 while ((c
= poptGetNextOpt(pc
)) > 0) {
808 readrcfile(poptGetOptArg(pc
), long_options
);
811 opt
.username_specified
= true;
812 opt
.username
= talloc_strdup(frame
, "");
813 opt
.password_specified
= true;
814 opt
.password
= talloc_strdup(frame
, "");
820 opt
.username_specified
= true;
821 opt
.username
= talloc_strdup(frame
, opt
.username
);
822 p
= strchr(opt
.username
,'%');
825 opt
.password
= p
+ 1;
826 opt
.password_specified
= true;
830 opt
.nonprompt
= true;
842 opt
.send_stdout
= true;
857 fprintf(stderr
, "%s: %s\n",
858 poptBadOption(pc
, POPT_BADOPTION_NOALIAS
),
863 if ((opt
.send_stdout
|| resume
|| opt
.outputfile
) && opt
.update
) {
864 fprintf(stderr
, "The -o, -R or -O and -U options can not be "
868 if ((opt
.send_stdout
|| opt
.outputfile
) && recursive
) {
869 fprintf(stderr
, "The -o or -O and -R options can not be "
874 if (opt
.outputfile
&& opt
.send_stdout
) {
875 fprintf(stderr
, "The -o and -O options can not be "
880 popt_burn_cmdline_password(argc
, argv
);
882 if (smbc_init(get_auth_data
, opt
.debuglevel
) < 0) {
883 fprintf(stderr
, "Unable to initialize libsmbclient\n");
888 SMBCCTX
*smb_ctx
= smbc_set_context(NULL
);
889 smbc_option_set(smb_ctx
,
890 discard_const_p(char, "smb_encrypt_level"),
894 columns
= get_num_cols();
896 total_start_time
= time_mono(NULL
);
898 while ((file
= poptGetArg(pc
))) {
900 ret
= smb_download_file(file
, "", recursive
, resume
,
901 true, opt
.outputfile
);
903 ret
= smb_download_dir(file
, "", resume
);