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
;
54 bool keep_permissions
;
60 static struct opt opt
;
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
;
112 strncpy(wg
, savedwg
, wglen
- 1);
113 strncpy(un
, savedun
, unlen
- 1);
114 strncpy(pw
, savedpw
, pwlen
- 1);
119 if (!opt
.nonprompt
&& !opt
.username_specified
) {
120 printf("Username for %s at %s [guest] ", shr
, srv
);
121 if (fgets(tmp
, sizeof(tmp
), stdin
) == NULL
) {
124 if ((strlen(tmp
) > 0) && (tmp
[strlen(tmp
) - 1] == '\n')) {
125 tmp
[strlen(tmp
) - 1] = '\0';
127 strncpy(un
, tmp
, unlen
- 1);
128 } else if (opt
.username
!= NULL
) {
129 strncpy(un
, opt
.username
, unlen
- 1);
132 if (!opt
.nonprompt
&& !opt
.password_specified
) {
134 if (asprintf(&prompt
, "Password for %s at %s: ", shr
, srv
) ==
138 (void)samba_getpass(prompt
, pw
, pwlen
, false, false);
140 } else if (opt
.password
!= NULL
) {
141 strncpy(pw
, opt
.password
, pwlen
-1);
144 if (opt
.workgroup
!= NULL
) {
145 strncpy(wg
, opt
.workgroup
, wglen
-1);
148 /* save the values found for later */
149 savedwg
= SMB_STRDUP(wg
);
150 savedun
= SMB_STRDUP(un
);
151 savedpw
= SMB_STRDUP(pw
);
154 char *wgtmp
, *usertmp
;
155 wgtmp
= SMB_STRNDUP(wg
, wglen
);
156 usertmp
= SMB_STRNDUP(un
, unlen
);
157 printf("Using workgroup %s, %s%s\n",
159 *usertmp
? "user " : "guest user",
166 /* Return 1 on error, 0 on success. */
168 static int smb_download_dir(const char *base
, const char *name
, int resume
)
170 char path
[SMB_MAXPATHLEN
];
172 struct smbc_dirent
*dirent
;
173 const char *relname
= name
;
175 struct stat remotestat
;
178 snprintf(path
, SMB_MAXPATHLEN
-1, "%s%s%s", base
,
179 (base
[0] && name
[0] && name
[0] != '/' &&
180 base
[strlen(base
)-1] != '/') ? "/" : "",
183 /* List files in directory and call smb_download_file on them */
184 dirhandle
= smbc_opendir(path
);
186 if (errno
== ENOTDIR
) {
187 return smb_download_file(base
, name
, true, resume
,
190 fprintf(stderr
, "Can't open directory %s: %s\n", path
,
195 while (*relname
== '/') {
198 mkdir(relname
, 0755);
200 tmpname
= SMB_STRDUP(name
);
202 while ((dirent
= smbc_readdir(dirhandle
))) {
204 if (!strcmp(dirent
->name
, ".") || !strcmp(dirent
->name
, "..")) {
207 if (asprintf(&newname
, "%s/%s", tmpname
, dirent
->name
) == -1) {
211 switch (dirent
->smbc_type
) {
213 ret
= smb_download_dir(base
, newname
, resume
);
217 ret
= smb_download_dir("smb://", dirent
->name
, resume
);
221 ret
= smb_download_dir("smb://", dirent
->name
, resume
);
225 ret
= smb_download_file(base
, newname
, true, resume
,
229 case SMBC_FILE_SHARE
:
230 ret
= smb_download_dir(base
, newname
, resume
);
233 case SMBC_PRINTER_SHARE
:
235 printf("Ignoring printer share %s\n",
240 case SMBC_COMMS_SHARE
:
242 printf("Ignoring comms share %s\n",
249 printf("Ignoring ipc$ share %s\n",
255 fprintf(stderr
, "Ignoring file '%s' of type '%d'\n",
256 newname
, dirent
->smbc_type
);
263 if (opt
.keep_permissions
) {
264 if (smbc_fstat(dirhandle
, &remotestat
) < 0) {
266 "Unable to get stats on %s on remote server\n",
268 smbc_closedir(dirhandle
);
272 if (chmod(relname
, remotestat
.st_mode
) < 0) {
274 "Unable to change mode of local dir %s to %o\n",
275 relname
, (unsigned int)remotestat
.st_mode
);
276 smbc_closedir(dirhandle
);
281 smbc_closedir(dirhandle
);
285 static char *print_time(long t
)
287 static char buffer
[100];
288 int secs
, mins
, hours
;
290 strncpy(buffer
, "Unknown", sizeof(buffer
));
295 mins
= (int)t
/ 60 % 60;
296 hours
= (int)t
/ (60 * 60);
297 snprintf(buffer
, sizeof(buffer
) - 1, "%02d:%02d:%02d", hours
, mins
,
302 static void print_progress(const char *name
, time_t start
, time_t now
,
303 off_t start_pos
, off_t pos
, off_t total
)
308 char hpos
[20], htotal
[20], havg
[20];
309 char *status
, *filename
;
312 avg
= 1.0 * (pos
- start_pos
) / (now
- start
);
314 eta
= (total
- pos
) / avg
;
316 prcnt
= 100.0 * pos
/ total
;
319 human_readable(pos
, hpos
, sizeof(hpos
));
320 human_readable(total
, htotal
, sizeof(htotal
));
321 human_readable(avg
, havg
, sizeof(havg
));
323 len
= asprintf(&status
, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos
,
324 htotal
, prcnt
, havg
, print_time(eta
));
330 int required
= strlen(name
),
331 available
= columns
- len
- strlen("[] ");
332 if (required
> available
) {
333 if (asprintf(&filename
, "...%s",
334 name
+ required
- available
+ 3) == -1) {
338 filename
= SMB_STRNDUP(name
, available
);
341 filename
= SMB_STRDUP(name
);
344 fprintf(stderr
, "\r[%s] %s", filename
, status
);
350 /* Return false on error, true on success. */
352 static bool smb_download_file(const char *base
, const char *name
,
353 bool recursive
, bool resume
, bool toplevel
,
356 int remotehandle
, localhandle
;
357 time_t start_time
= time_mono(NULL
);
359 char path
[SMB_MAXPATHLEN
];
360 char checkbuf
[2][RESUME_CHECK_SIZE
];
361 char *readbuf
= NULL
;
362 off_t offset_download
= 0, offset_check
= 0, curpos
= 0,
364 struct stat localstat
, remotestat
;
366 snprintf(path
, SMB_MAXPATHLEN
-1, "%s%s%s", base
,
367 (*base
&& *name
&& name
[0] != '/' &&
368 base
[strlen(base
)-1] != '/') ? "/" : "",
371 remotehandle
= smbc_open(path
, O_RDONLY
, 0755);
373 if (remotehandle
< 0) {
378 "%s is a directory. Specify -R "
379 "to download recursively\n",
383 return smb_download_dir(base
, name
, resume
);
387 "%s can't be found on the remote server\n",
392 fprintf(stderr
, "Not enough memory\n");
397 "The share name used in %s does not exist\n",
402 fprintf(stderr
, "You don't have enough permissions "
413 if (smbc_fstat(remotehandle
, &remotestat
) < 0) {
414 fprintf(stderr
, "Can't stat %s: %s\n", path
, strerror(errno
));
420 } else if (!name
[0]) {
421 newpath
= strrchr(base
, '/');
431 if (!toplevel
&& (newpath
[0] == '/')) {
435 /* Open local file according to the mode */
437 /* if it is up-to-date, skip */
438 if (stat(newpath
, &localstat
) == 0 &&
439 localstat
.st_mtime
>= remotestat
.st_mtime
) {
441 printf("%s is up-to-date, skipping\n", newpath
);
443 smbc_close(remotehandle
);
446 /* else open it for writing and truncate if it exists */
448 newpath
, O_CREAT
| O_NONBLOCK
| O_RDWR
| O_TRUNC
, 0775);
449 if (localhandle
< 0) {
450 fprintf(stderr
, "Can't open %s : %s\n", newpath
,
452 smbc_close(remotehandle
);
456 } else if (!opt
.send_stdout
) {
457 localhandle
= open(newpath
, O_CREAT
| O_NONBLOCK
| O_RDWR
|
458 (!resume
? O_EXCL
: 0),
460 if (localhandle
< 0) {
461 fprintf(stderr
, "Can't open %s: %s\n", newpath
,
463 smbc_close(remotehandle
);
467 if (fstat(localhandle
, &localstat
) != 0) {
468 fprintf(stderr
, "Can't fstat %s: %s\n", newpath
,
470 smbc_close(remotehandle
);
475 start_offset
= localstat
.st_size
;
477 if (localstat
.st_size
&&
478 localstat
.st_size
== remotestat
.st_size
) {
480 fprintf(stderr
, "%s is already downloaded "
483 } else if (!opt
.quiet
) {
484 fprintf(stderr
, "%s\n", path
);
486 smbc_close(remotehandle
);
491 if (localstat
.st_size
> RESUME_CHECK_OFFSET
&&
492 remotestat
.st_size
> RESUME_CHECK_OFFSET
) {
494 localstat
.st_size
- RESUME_DOWNLOAD_OFFSET
;
495 offset_check
= localstat
.st_size
- RESUME_CHECK_OFFSET
;
497 printf("Trying to start resume of %s at %jd\n"
498 "At the moment %jd of %jd bytes have "
500 newpath
, (intmax_t)offset_check
,
501 (intmax_t)localstat
.st_size
,
502 (intmax_t)remotestat
.st_size
);
508 /* First, check all bytes from offset_check to
510 off1
= lseek(localhandle
, offset_check
, SEEK_SET
);
513 "Can't seek to %jd in local file %s\n",
514 (intmax_t)offset_check
, newpath
);
515 smbc_close(remotehandle
);
520 off2
= smbc_lseek(remotehandle
, offset_check
, SEEK_SET
);
523 "Can't seek to %jd in remote file %s\n",
524 (intmax_t)offset_check
, newpath
);
525 smbc_close(remotehandle
);
531 fprintf(stderr
, "Offset in local and remote "
532 "files are different "
533 "(local: %jd, remote: %jd)\n",
534 (intmax_t)off1
, (intmax_t)off2
);
535 smbc_close(remotehandle
);
540 if (smbc_read(remotehandle
, checkbuf
[0],
541 RESUME_CHECK_SIZE
) != RESUME_CHECK_SIZE
) {
542 fprintf(stderr
, "Can't read %d bytes from "
544 RESUME_CHECK_SIZE
, path
);
545 smbc_close(remotehandle
);
550 if (read(localhandle
, checkbuf
[1], RESUME_CHECK_SIZE
) !=
552 fprintf(stderr
, "Can't read %d bytes from "
554 RESUME_CHECK_SIZE
, name
);
555 smbc_close(remotehandle
);
560 if (memcmp(checkbuf
[0], checkbuf
[1],
561 RESUME_CHECK_SIZE
) == 0) {
563 printf("Current local and remote file "
564 "appear to be the same. "
565 "Starting download from "
567 (intmax_t)offset_download
);
570 fprintf(stderr
, "Local and remote file appear "
571 "to be different, not "
572 "doing resume for %s\n",
574 smbc_close(remotehandle
);
580 localhandle
= STDOUT_FILENO
;
586 readbuf
= (char *)SMB_MALLOC(opt
.blocksize
);
588 if (localhandle
!= STDOUT_FILENO
) {
594 /* Now, download all bytes from offset_download to the end */
595 for (curpos
= offset_download
; curpos
< remotestat
.st_size
;
596 curpos
+= opt
.blocksize
) {
597 ssize_t bytesread
= smbc_read(remotehandle
,
602 "Can't read %zu bytes at offset %jd, file %s\n",
603 opt
.blocksize
, (intmax_t)curpos
, path
);
604 smbc_close(remotehandle
);
605 if (localhandle
!= STDOUT_FILENO
) {
612 total_bytes
+= bytesread
;
614 if(write(localhandle
, readbuf
, bytesread
) < 0) {
616 "Can't write %zd bytes to local file %s at "
617 "offset %jd\n", bytesread
, path
,
620 smbc_close(remotehandle
);
621 if (localhandle
!= STDOUT_FILENO
) {
629 } else if (!opt
.quiet
) {
630 print_progress(newpath
, start_time
, time_mono(NULL
),
631 start_offset
, curpos
,
640 printf("%s downloaded\n", path
);
641 } else if (!opt
.quiet
) {
643 fprintf(stderr
, "\r%s", path
);
645 for (i
= strlen(path
); i
< columns
; i
++) {
652 if (opt
.keep_permissions
&& !opt
.send_stdout
) {
653 if (fchmod(localhandle
, remotestat
.st_mode
) < 0) {
654 fprintf(stderr
, "Unable to change mode of local "
656 path
, (unsigned int)remotestat
.st_mode
);
657 smbc_close(remotehandle
);
663 smbc_close(remotehandle
);
664 if (localhandle
!= STDOUT_FILENO
) {
670 static void clean_exit(void)
673 human_readable(total_bytes
, bs
, sizeof(bs
));
675 fprintf(stderr
, "Downloaded %s in %lu seconds\n", bs
,
676 (unsigned long)(time_mono(NULL
) - total_start_time
));
681 static void signal_quit(int v
)
686 static int readrcfile(const char *name
, const struct poptOption long_options
[])
688 FILE *fd
= fopen(name
, "r");
690 char var
[101], val
[101];
695 fprintf(stderr
, "Can't open RC file %s\n", name
);
701 if (fscanf(fd
, "%100s %100s\n", var
, val
) < 2) {
703 "Can't parse line %d of %s, ignoring.\n",
710 for (i
= 0; long_options
[i
].argInfo
; i
++) {
711 if (!long_options
[i
].longName
) {
714 if (strcmp(long_options
[i
].longName
, var
)) {
717 if (!long_options
[i
].arg
) {
721 switch (long_options
[i
].argInfo
) {
723 intdata
= (int *)long_options
[i
].arg
;
724 if (!strcmp(val
, "on")) {
726 } else if (!strcmp(val
, "off")) {
729 fprintf(stderr
, "Illegal value %s for "
730 "%s at line %d in %s\n",
731 val
, var
, lineno
, name
);
735 intdata
= (int *)long_options
[i
].arg
;
736 *intdata
= atoi(val
);
738 case POPT_ARG_STRING
:
739 stringdata
= (char **)long_options
[i
].arg
;
740 *stringdata
= SMB_STRDUP(val
);
743 fprintf(stderr
, "Invalid variable %s at "
753 "Invalid variable %s at line %d in %s\n", var
,
762 int main(int argc
, char **argv
)
765 const char *file
= NULL
;
767 bool smb_encrypt
= false;
768 int resume
= 0, recursive
= 0;
769 TALLOC_CTX
*frame
= talloc_stackframe();
772 const char **argv_const
= discard_const_p(const char *, argv
);
773 struct poptOption long_options
[] = {
776 {"workgroup", 'w', POPT_ARG_STRING
, &opt
.workgroup
, 'w', "Workgroup to use (optional)" },
777 {"user", 'U', POPT_ARG_STRING
, &opt
.username
, 'U', "Username to use" },
778 {"guest", 'a', POPT_ARG_NONE
, NULL
, 'a', "Work as user guest" },
780 {"nonprompt", 'n', POPT_ARG_NONE
, &opt
.nonprompt
, 'n', "Don't ask anything (non-interactive)" },
781 {"debuglevel", 'd', POPT_ARG_INT
, &opt
.debuglevel
, 'd', "Debuglevel to use" },
783 {"encrypt", 'e', POPT_ARG_NONE
, NULL
, 'e', "Encrypt SMB transport" },
784 {"resume", 'r', POPT_ARG_NONE
, &resume
, 0, "Automatically resume aborted files" },
785 {"update", 'u', POPT_ARG_NONE
, &opt
.update
, 0, "Download only when remote file is newer than local file or local file is missing"},
786 {"recursive", 'R', POPT_ARG_NONE
, &recursive
, 0, "Recursively download files" },
787 {"keep-permissions", 'P', POPT_ARG_NONE
, &opt
.keep_permissions
, 'P', "Keep permissions" },
788 {"blocksize", 'b', POPT_ARG_INT
, &opt
.blocksize
, 'b', "Change number of bytes in a block"},
790 {"outputfile", 'o', POPT_ARG_STRING
, &opt
.outputfile
, 'o', "Write downloaded data to specified file" },
791 {"stdout", 'O', POPT_ARG_NONE
, &opt
.send_stdout
, 'O', "Write data to stdout" },
792 {"dots", 'D', POPT_ARG_NONE
, &opt
.dots
, 'D', "Show dots as progress indication" },
793 {"quiet", 'q', POPT_ARG_NONE
, &opt
.quiet
, 'q', "Be quiet" },
794 {"verbose", 'v', POPT_ARG_NONE
, &opt
.verbose
, 'v', "Be verbose" },
795 {"rcfile", 'f', POPT_ARG_STRING
, NULL
, 'f', "Use specified rc file"},
803 /* only read rcfile if it exists */
804 if (asprintf(&rcfile
, "%s/.smbgetrc", getenv("HOME")) == -1) {
807 if (access(rcfile
, F_OK
) == 0) {
808 readrcfile(rcfile
, long_options
);
813 signal(SIGWINCH
, change_columns
);
815 signal(SIGINT
, signal_quit
);
816 signal(SIGTERM
, signal_quit
);
818 pc
= poptGetContext(argv
[0], argc
, argv_const
, long_options
, 0);
820 while ((c
= poptGetNextOpt(pc
)) >= 0) {
823 readrcfile(poptGetOptArg(pc
), long_options
);
826 opt
.username_specified
= true;
827 opt
.username
= talloc_strdup(frame
, "");
828 opt
.password_specified
= true;
829 opt
.password
= talloc_strdup(frame
, "");
835 opt
.username_specified
= true;
836 opt
.username
= talloc_strdup(frame
, opt
.username
);
837 p
= strchr(opt
.username
,'%');
840 opt
.password
= p
+ 1;
841 opt
.password_specified
= true;
847 if ((opt
.send_stdout
|| resume
|| opt
.outputfile
) && opt
.update
) {
848 fprintf(stderr
, "The -o, -R or -O and -U options can not be "
852 if ((opt
.send_stdout
|| opt
.outputfile
) && recursive
) {
853 fprintf(stderr
, "The -o or -O and -R options can not be "
858 if (opt
.outputfile
&& opt
.send_stdout
) {
859 fprintf(stderr
, "The -o and -O options can not be "
864 popt_burn_cmdline_password(argc
, argv
);
866 if (smbc_init(get_auth_data
, opt
.debuglevel
) < 0) {
867 fprintf(stderr
, "Unable to initialize libsmbclient\n");
872 SMBCCTX
*smb_ctx
= smbc_set_context(NULL
);
873 smbc_option_set(smb_ctx
,
874 discard_const_p(char, "smb_encrypt_level"),
878 columns
= get_num_cols();
880 total_start_time
= time_mono(NULL
);
882 while ((file
= poptGetArg(pc
))) {
884 ret
= smb_download_file(file
, "", recursive
, resume
,
885 true, opt
.outputfile
);
887 ret
= smb_download_dir(file
, "", resume
);