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
));
263 smbc_closedir(dirhandle
);
267 static char *print_time(long t
)
269 static char buffer
[100];
270 int secs
, mins
, hours
;
272 strncpy(buffer
, "Unknown", sizeof(buffer
));
277 mins
= (int)t
/ 60 % 60;
278 hours
= (int)t
/ (60 * 60);
279 snprintf(buffer
, sizeof(buffer
) - 1, "%02d:%02d:%02d", hours
, mins
,
284 static void print_progress(const char *name
, time_t start
, time_t now
,
285 off_t start_pos
, off_t pos
, off_t total
)
290 char hpos
[20], htotal
[20], havg
[20];
291 char *status
, *filename
;
294 avg
= 1.0 * (pos
- start_pos
) / (now
- start
);
296 eta
= (total
- pos
) / avg
;
298 prcnt
= 100.0 * pos
/ total
;
301 human_readable(pos
, hpos
, sizeof(hpos
));
302 human_readable(total
, htotal
, sizeof(htotal
));
303 human_readable(avg
, havg
, sizeof(havg
));
305 len
= asprintf(&status
, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos
,
306 htotal
, prcnt
, havg
, print_time(eta
));
312 int required
= strlen(name
),
313 available
= columns
- len
- strlen("[] ");
314 if (required
> available
) {
315 if (asprintf(&filename
, "...%s",
316 name
+ required
- available
+ 3) == -1) {
320 filename
= SMB_STRNDUP(name
, available
);
323 filename
= SMB_STRDUP(name
);
326 fprintf(stderr
, "\r[%s] %s", filename
, status
);
332 /* Return false on error, true on success. */
334 static bool smb_download_file(const char *base
, const char *name
,
335 bool recursive
, bool resume
, bool toplevel
,
338 int remotehandle
, localhandle
;
339 time_t start_time
= time_mono(NULL
);
341 char path
[SMB_MAXPATHLEN
];
342 char checkbuf
[2][RESUME_CHECK_SIZE
];
343 char *readbuf
= NULL
;
344 off_t offset_download
= 0, offset_check
= 0, curpos
= 0,
346 struct stat localstat
, remotestat
;
348 snprintf(path
, SMB_MAXPATHLEN
-1, "%s%s%s", base
,
349 (*base
&& *name
&& name
[0] != '/' &&
350 base
[strlen(base
)-1] != '/') ? "/" : "",
353 remotehandle
= smbc_open(path
, O_RDONLY
, 0755);
355 if (remotehandle
< 0) {
360 "%s is a directory. Specify -R "
361 "to download recursively\n",
365 return smb_download_dir(base
, name
, resume
);
369 "%s can't be found on the remote server\n",
374 fprintf(stderr
, "Not enough memory\n");
379 "The share name used in %s does not exist\n",
384 fprintf(stderr
, "You don't have enough permissions "
395 if (smbc_fstat(remotehandle
, &remotestat
) < 0) {
396 fprintf(stderr
, "Can't stat %s: %s\n", path
, strerror(errno
));
402 } else if (!name
[0]) {
403 newpath
= strrchr(base
, '/');
413 if (!toplevel
&& (newpath
[0] == '/')) {
417 /* Open local file according to the mode */
419 /* if it is up-to-date, skip */
420 if (stat(newpath
, &localstat
) == 0 &&
421 localstat
.st_mtime
>= remotestat
.st_mtime
) {
423 printf("%s is up-to-date, skipping\n", newpath
);
425 smbc_close(remotehandle
);
428 /* else open it for writing and truncate if it exists */
430 newpath
, O_CREAT
| O_NONBLOCK
| O_RDWR
| O_TRUNC
, 0775);
431 if (localhandle
< 0) {
432 fprintf(stderr
, "Can't open %s : %s\n", newpath
,
434 smbc_close(remotehandle
);
438 } else if (!opt
.send_stdout
) {
439 localhandle
= open(newpath
, O_CREAT
| O_NONBLOCK
| O_RDWR
|
440 (!resume
? O_EXCL
: 0),
442 if (localhandle
< 0) {
443 fprintf(stderr
, "Can't open %s: %s\n", newpath
,
445 smbc_close(remotehandle
);
449 if (fstat(localhandle
, &localstat
) != 0) {
450 fprintf(stderr
, "Can't fstat %s: %s\n", newpath
,
452 smbc_close(remotehandle
);
457 start_offset
= localstat
.st_size
;
459 if (localstat
.st_size
&&
460 localstat
.st_size
== remotestat
.st_size
) {
462 fprintf(stderr
, "%s is already downloaded "
465 } else if (!opt
.quiet
) {
466 fprintf(stderr
, "%s\n", path
);
468 smbc_close(remotehandle
);
473 if (localstat
.st_size
> RESUME_CHECK_OFFSET
&&
474 remotestat
.st_size
> RESUME_CHECK_OFFSET
) {
476 localstat
.st_size
- RESUME_DOWNLOAD_OFFSET
;
477 offset_check
= localstat
.st_size
- RESUME_CHECK_OFFSET
;
479 printf("Trying to start resume of %s at %jd\n"
480 "At the moment %jd of %jd bytes have "
482 newpath
, (intmax_t)offset_check
,
483 (intmax_t)localstat
.st_size
,
484 (intmax_t)remotestat
.st_size
);
490 /* First, check all bytes from offset_check to
492 off1
= lseek(localhandle
, offset_check
, SEEK_SET
);
495 "Can't seek to %jd in local file %s\n",
496 (intmax_t)offset_check
, newpath
);
497 smbc_close(remotehandle
);
502 off2
= smbc_lseek(remotehandle
, offset_check
, SEEK_SET
);
505 "Can't seek to %jd in remote file %s\n",
506 (intmax_t)offset_check
, newpath
);
507 smbc_close(remotehandle
);
513 fprintf(stderr
, "Offset in local and remote "
514 "files are different "
515 "(local: %jd, remote: %jd)\n",
516 (intmax_t)off1
, (intmax_t)off2
);
517 smbc_close(remotehandle
);
522 if (smbc_read(remotehandle
, checkbuf
[0],
523 RESUME_CHECK_SIZE
) != RESUME_CHECK_SIZE
) {
524 fprintf(stderr
, "Can't read %d bytes from "
526 RESUME_CHECK_SIZE
, path
);
527 smbc_close(remotehandle
);
532 if (read(localhandle
, checkbuf
[1], RESUME_CHECK_SIZE
) !=
534 fprintf(stderr
, "Can't read %d bytes from "
536 RESUME_CHECK_SIZE
, name
);
537 smbc_close(remotehandle
);
542 if (memcmp(checkbuf
[0], checkbuf
[1],
543 RESUME_CHECK_SIZE
) == 0) {
545 printf("Current local and remote file "
546 "appear to be the same. "
547 "Starting download from "
549 (intmax_t)offset_download
);
552 fprintf(stderr
, "Local and remote file appear "
553 "to be different, not "
554 "doing resume for %s\n",
556 smbc_close(remotehandle
);
562 localhandle
= STDOUT_FILENO
;
568 readbuf
= (char *)SMB_MALLOC(opt
.blocksize
);
570 fprintf(stderr
, "Failed to allocate %zu bytes for read "
571 "buffer (%s)", opt
.blocksize
, strerror(errno
));
572 if (localhandle
!= STDOUT_FILENO
) {
578 /* Now, download all bytes from offset_download to the end */
579 for (curpos
= offset_download
; curpos
< remotestat
.st_size
;
580 curpos
+= opt
.blocksize
) {
582 ssize_t byteswritten
;
584 bytesread
= smbc_read(remotehandle
, readbuf
, opt
.blocksize
);
587 "Can't read %zu bytes at offset %jd, file %s\n",
588 opt
.blocksize
, (intmax_t)curpos
, path
);
589 smbc_close(remotehandle
);
590 if (localhandle
!= STDOUT_FILENO
) {
597 total_bytes
+= bytesread
;
599 byteswritten
= write(localhandle
, readbuf
, bytesread
);
600 if (byteswritten
!= bytesread
) {
602 "Can't write %zd bytes to local file %s at "
603 "offset %jd\n", bytesread
, path
,
606 smbc_close(remotehandle
);
607 if (localhandle
!= STDOUT_FILENO
) {
615 } else if (!opt
.quiet
) {
616 print_progress(newpath
, start_time
, time_mono(NULL
),
617 start_offset
, curpos
,
626 printf("%s downloaded\n", path
);
627 } else if (!opt
.quiet
) {
629 fprintf(stderr
, "\r%s", path
);
631 for (i
= strlen(path
); i
< columns
; i
++) {
638 smbc_close(remotehandle
);
639 if (localhandle
!= STDOUT_FILENO
) {
645 static void clean_exit(void)
648 human_readable(total_bytes
, bs
, sizeof(bs
));
650 fprintf(stderr
, "Downloaded %s in %lu seconds\n", bs
,
651 (unsigned long)(time_mono(NULL
) - total_start_time
));
656 static void signal_quit(int v
)
661 static int readrcfile(const char *name
, const struct poptOption long_options
[])
663 FILE *fd
= fopen(name
, "r");
665 char var
[101], val
[101];
670 fprintf(stderr
, "Can't open RC file %s\n", name
);
676 if (fscanf(fd
, "%100s %100s\n", var
, val
) < 2) {
678 "Can't parse line %d of %s, ignoring.\n",
685 for (i
= 0; long_options
[i
].argInfo
; i
++) {
686 if (!long_options
[i
].longName
) {
689 if (strcmp(long_options
[i
].longName
, var
)) {
692 if (!long_options
[i
].arg
) {
696 switch (long_options
[i
].argInfo
) {
698 intdata
= (int *)long_options
[i
].arg
;
699 if (!strcmp(val
, "on")) {
701 } else if (!strcmp(val
, "off")) {
704 fprintf(stderr
, "Illegal value %s for "
705 "%s at line %d in %s\n",
706 val
, var
, lineno
, name
);
710 intdata
= (int *)long_options
[i
].arg
;
711 *intdata
= atoi(val
);
713 case POPT_ARG_STRING
:
714 stringdata
= (char **)long_options
[i
].arg
;
715 *stringdata
= SMB_STRDUP(val
);
716 if (long_options
[i
].shortName
== 'U') {
718 opt
.username_specified
= true;
719 p
= strchr(*stringdata
, '%');
722 opt
.password
= p
+ 1;
723 opt
.password_specified
= true;
728 fprintf(stderr
, "Invalid variable %s at "
738 "Invalid variable %s at line %d in %s\n", var
,
747 int main(int argc
, char **argv
)
750 const char *file
= NULL
;
752 bool smb_encrypt
= false;
753 int resume
= 0, recursive
= 0;
754 TALLOC_CTX
*frame
= talloc_stackframe();
757 const char **argv_const
= discard_const_p(const char *, argv
);
758 struct poptOption long_options
[] = {
761 {"workgroup", 'w', POPT_ARG_STRING
, &opt
.workgroup
, 'w', "Workgroup to use (optional)" },
762 {"user", 'U', POPT_ARG_STRING
, &opt
.username
, 'U', "Username to use" },
763 {"guest", 'a', POPT_ARG_NONE
, NULL
, 'a', "Work as user guest" },
765 {"nonprompt", 'n', POPT_ARG_NONE
, NULL
, 'n', "Don't ask anything (non-interactive)" },
766 {"debuglevel", 'd', POPT_ARG_INT
, &opt
.debuglevel
, 'd', "Debuglevel to use" },
768 {"encrypt", 'e', POPT_ARG_NONE
, NULL
, 'e', "Encrypt SMB transport" },
769 {"resume", 'r', POPT_ARG_NONE
, NULL
, 'r', "Automatically resume aborted files" },
770 {"update", 'u', POPT_ARG_NONE
, NULL
, 'u', "Download only when remote file is newer than local file or local file is missing"},
771 {"recursive", 'R', POPT_ARG_NONE
, NULL
, 'R', "Recursively download files" },
772 {"blocksize", 'b', POPT_ARG_INT
, &opt
.blocksize
, 'b', "Change number of bytes in a block"},
774 {"outputfile", 'o', POPT_ARG_STRING
, &opt
.outputfile
, 'o', "Write downloaded data to specified file" },
775 {"stdout", 'O', POPT_ARG_NONE
, NULL
, 'O', "Write data to stdout" },
776 {"dots", 'D', POPT_ARG_NONE
, NULL
, 'D', "Show dots as progress indication" },
777 {"quiet", 'q', POPT_ARG_NONE
, NULL
, 'q', "Be quiet" },
778 {"verbose", 'v', POPT_ARG_NONE
, NULL
, 'v', "Be verbose" },
779 {"rcfile", 'f', POPT_ARG_STRING
, NULL
, 'f', "Use specified rc file"},
787 /* only read rcfile if it exists */
788 if (asprintf(&rcfile
, "%s/.smbgetrc", getenv("HOME")) == -1) {
791 if (access(rcfile
, F_OK
) == 0) {
792 readrcfile(rcfile
, long_options
);
797 signal(SIGWINCH
, change_columns
);
799 signal(SIGINT
, signal_quit
);
800 signal(SIGTERM
, signal_quit
);
802 pc
= poptGetContext(argv
[0], argc
, argv_const
, long_options
, 0);
804 while ((c
= poptGetNextOpt(pc
)) > 0) {
807 readrcfile(poptGetOptArg(pc
), long_options
);
810 opt
.username_specified
= true;
811 opt
.username
= talloc_strdup(frame
, "");
812 opt
.password_specified
= true;
813 opt
.password
= talloc_strdup(frame
, "");
819 opt
.username_specified
= true;
820 opt
.username
= talloc_strdup(frame
, opt
.username
);
821 p
= strchr(opt
.username
,'%');
824 opt
.password
= p
+ 1;
825 opt
.password_specified
= true;
829 opt
.nonprompt
= true;
841 opt
.send_stdout
= true;
856 fprintf(stderr
, "%s: %s\n",
857 poptBadOption(pc
, POPT_BADOPTION_NOALIAS
),
862 if ((opt
.send_stdout
|| resume
|| opt
.outputfile
) && opt
.update
) {
863 fprintf(stderr
, "The -o, -R or -O and -U options can not be "
867 if ((opt
.send_stdout
|| opt
.outputfile
) && recursive
) {
868 fprintf(stderr
, "The -o or -O and -R options can not be "
873 if (opt
.outputfile
&& opt
.send_stdout
) {
874 fprintf(stderr
, "The -o and -O options can not be "
879 popt_burn_cmdline_password(argc
, argv
);
881 if (smbc_init(get_auth_data
, opt
.debuglevel
) < 0) {
882 fprintf(stderr
, "Unable to initialize libsmbclient\n");
887 SMBCCTX
*smb_ctx
= smbc_set_context(NULL
);
888 smbc_option_set(smb_ctx
,
889 discard_const_p(char, "smb_encrypt_level"),
893 columns
= get_num_cols();
895 total_start_time
= time_mono(NULL
);
897 while ((file
= poptGetArg(pc
))) {
899 ret
= smb_download_file(file
, "", recursive
, resume
,
900 true, opt
.outputfile
);
902 ret
= smb_download_dir(file
, "", resume
);