s3:utils: Handle the domain before username and password
[samba.git] / source3 / utils / smbget.c
1 /*
2    smbget: a wget-like utility with support for recursive downloading of
3         smb:// urls
4    Copyright (C) 2003-2004 Jelmer Vernooij <jelmer@samba.org>
5
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.
10
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.
15
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/>.  */
18
19 #include "includes.h"
20 #include "system/filesys.h"
21 #include "lib/cmdline/cmdline.h"
22 #include "lib/param/param.h"
23 #include "libsmbclient.h"
24 #include "cmdline_contexts.h"
25 #include "auth/credentials/credentials.h"
26 #include "auth/gensec/gensec.h"
27
28 static int columns = 0;
29
30 static time_t total_start_time = 0;
31 static off_t total_bytes = 0;
32
33 #define SMB_MAXPATHLEN MAXPATHLEN
34
35 /*
36  * Number of bytes to read when checking whether local and remote file
37  * are really the same file
38  */
39 #define RESUME_CHECK_SIZE       512
40 #define RESUME_DOWNLOAD_OFFSET  1024
41 #define RESUME_CHECK_OFFSET     (RESUME_DOWNLOAD_OFFSET+RESUME_CHECK_SIZE)
42 /* Number of bytes to read at once */
43 #define SMB_DEFAULT_BLOCKSIZE   64000
44
45 struct opt {
46         char *outputfile;
47         size_t blocksize;
48
49         int quiet;
50         int dots;
51         int verbose;
52         int send_stdout;
53         int update;
54         unsigned limit_rate;
55 };
56 static struct opt opt = { .blocksize = SMB_DEFAULT_BLOCKSIZE };
57
58 static bool smb_download_file(const char *base, const char *name,
59                               bool recursive, bool resume, bool toplevel,
60                               char *outfile);
61
62 static int get_num_cols(void)
63 {
64 #ifdef TIOCGWINSZ
65         struct winsize ws;
66         if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
67                 return 0;
68         }
69         return ws.ws_col;
70 #else
71 #warning No support for TIOCGWINSZ
72         char *cols = getenv("COLUMNS");
73         if (!cols) {
74                 return 0;
75         }
76         return atoi(cols);
77 #endif
78 }
79
80 static void change_columns(int sig)
81 {
82         columns = get_num_cols();
83 }
84
85 static void human_readable(off_t s, char *buffer, int l)
86 {
87         if (s > 1024 * 1024 * 1024) {
88                 snprintf(buffer, l, "%.2fGB", 1.0 * s / (1024 * 1024 * 1024));
89         } else if (s > 1024 * 1024) {
90                 snprintf(buffer, l, "%.2fMB", 1.0 * s / (1024 * 1024));
91         } else if (s > 1024) {
92                 snprintf(buffer, l, "%.2fkB", 1.0 * s / 1024);
93         } else {
94                 snprintf(buffer, l, "%jdb", (intmax_t)s);
95         }
96 }
97
98 /*
99  * Authentication callback for libsmbclient.
100  *
101  * The command line parser will take care asking for a password interactively!
102  */
103 static void get_auth_data_with_context_fn(SMBCCTX *ctx,
104                                           const char *srv,
105                                           const char *shr,
106                                           char *dom,
107                                           int dom_len,
108                                           char *usr,
109                                           int usr_len,
110                                           char *pwd,
111                                           int pwd_len)
112 {
113         struct cli_credentials *creds = samba_cmdline_get_creds();
114         const char *username = NULL;
115         const char *password = NULL;
116         const char *domain = NULL;
117         enum credentials_obtained obtained = CRED_UNINITIALISED;
118
119         domain = cli_credentials_get_domain_and_obtained(creds, &obtained);
120         if (domain != NULL) {
121                 bool overwrite = false;
122                 if (dom[0] == '\0') {
123                         overwrite = true;
124                 }
125                 if (obtained >= CRED_CALLBACK_RESULT) {
126                         overwrite = true;
127                 }
128                 if (overwrite) {
129                         strncpy(dom, domain, dom_len - 1);
130                 }
131         }
132
133         username = cli_credentials_get_username_and_obtained(creds, &obtained);
134         if (username != NULL) {
135                 bool overwrite = false;
136                 if (usr[0] == '\0') {
137                         overwrite = true;
138                 }
139                 if (obtained >= CRED_CALLBACK_RESULT) {
140                         overwrite = true;
141                 }
142                 if (overwrite) {
143                         strncpy(usr, username, usr_len - 1);
144                 }
145         }
146
147         password = cli_credentials_get_password_and_obtained(creds, &obtained);
148         if (password != NULL) {
149                 bool overwrite = false;
150                 if (pwd[0] == '\0') {
151                         overwrite = true;
152                 }
153                 if (obtained >= CRED_CALLBACK_RESULT) {
154                         overwrite = true;
155                 }
156                 if (overwrite) {
157                         strncpy(pwd, password, pwd_len - 1);
158                 }
159         }
160
161         smbc_set_credentials_with_fallback(ctx, domain, username, password);
162
163         if (!opt.quiet && username != NULL) {
164                 if (username[0] == '\0') {
165                         printf("Using guest user\n");
166                 } else {
167                         printf("Using domain: %s, user: %s\n",
168                                 domain,
169                                 username);
170                 }
171         }
172 }
173
174 static bool smb_download_dir(const char *base, const char *name, int resume)
175 {
176         char path[SMB_MAXPATHLEN];
177         int dirhandle;
178         struct smbc_dirent *dirent;
179         const char *relname = name;
180         char *tmpname;
181         bool ok = false;
182
183         snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base,
184                  (base[0] && name[0] && name[0] != '/' &&
185                   base[strlen(base)-1] != '/') ? "/" : "",
186                  name);
187
188         /* List files in directory and call smb_download_file on them */
189         dirhandle = smbc_opendir(path);
190         if (dirhandle < 1) {
191                 if (errno == ENOTDIR) {
192                         return smb_download_file(base, name, true, resume,
193                                                  false, NULL);
194                 }
195                 fprintf(stderr, "Can't open directory %s: %s\n", path,
196                         strerror(errno));
197                 return false;
198         }
199
200         while (*relname == '/') {
201                 relname++;
202         }
203
204         if (strlen(relname) > 0) {
205                 int rc = mkdir(relname, 0755);
206                 if (rc == -1 && errno != EEXIST) {
207                         fprintf(stderr, "Can't create directory %s: %s\n",
208                                 relname, strerror(errno));
209                         return false;
210                 }
211         }
212
213         tmpname = SMB_STRDUP(name);
214
215         while ((dirent = smbc_readdir(dirhandle))) {
216                 char *newname;
217                 if (!strcmp(dirent->name, ".") || !strcmp(dirent->name, "..")) {
218                         ok = true;
219                         continue;
220                 }
221                 if (asprintf(&newname, "%s/%s", tmpname, dirent->name) == -1) {
222                         free(tmpname);
223                         return false;
224                 }
225                 switch (dirent->smbc_type) {
226                 case SMBC_DIR:
227                         ok = smb_download_dir(base, newname, resume);
228                         break;
229
230                 case SMBC_WORKGROUP:
231                         ok = smb_download_dir("smb://", dirent->name, resume);
232                         break;
233
234                 case SMBC_SERVER:
235                         ok = smb_download_dir("smb://", dirent->name, resume);
236                         break;
237
238                 case SMBC_FILE:
239                         ok = smb_download_file(base, newname, true, resume,
240                                                 false, NULL);
241                         break;
242
243                 case SMBC_FILE_SHARE:
244                         ok = smb_download_dir(base, newname, resume);
245                         break;
246
247                 case SMBC_PRINTER_SHARE:
248                         if (!opt.quiet) {
249                                 printf("Ignoring printer share %s\n",
250                                        dirent->name);
251                         }
252                         break;
253
254                 case SMBC_COMMS_SHARE:
255                         if (!opt.quiet) {
256                                 printf("Ignoring comms share %s\n",
257                                        dirent->name);
258                         }
259                         break;
260
261                 case SMBC_IPC_SHARE:
262                         if (!opt.quiet) {
263                                 printf("Ignoring ipc$ share %s\n",
264                                        dirent->name);
265                         }
266                         break;
267
268                 default:
269                         fprintf(stderr, "Ignoring file '%s' of type '%d'\n",
270                                 newname, dirent->smbc_type);
271                         break;
272                 }
273
274                 if (!ok) {
275                         fprintf(stderr, "Failed to download %s: %s\n",
276                                 newname, strerror(errno));
277                         free(newname);
278                         free(tmpname);
279                         return false;
280                 }
281                 free(newname);
282         }
283         free(tmpname);
284
285         smbc_closedir(dirhandle);
286         return ok;
287 }
288
289 static char *print_time(long t)
290 {
291         static char buffer[100];
292         int secs, mins, hours;
293         if (t < -1) {
294                 strncpy(buffer, "Unknown", sizeof(buffer));
295                 return buffer;
296         }
297
298         secs = (int)t % 60;
299         mins = (int)t / 60 % 60;
300         hours = (int)t / (60 * 60);
301         snprintf(buffer, sizeof(buffer) - 1, "%02d:%02d:%02d", hours, mins,
302                  secs);
303         return buffer;
304 }
305
306 static void print_progress(const char *name, time_t start, time_t now,
307                            off_t start_pos, off_t pos, off_t total)
308 {
309         double avg = 0.0;
310         long eta = -1;
311         double prcnt = 0.0;
312         char hpos[22], htotal[22], havg[22];
313         char *status, *filename;
314         int len;
315         if (now - start) {
316                 avg = 1.0 * (pos - start_pos) / (now - start);
317         }
318         eta = (total - pos) / avg;
319         if (total) {
320                 prcnt = 100.0 * pos / total;
321         }
322
323         human_readable(pos, hpos, sizeof(hpos));
324         human_readable(total, htotal, sizeof(htotal));
325         human_readable(avg, havg, sizeof(havg));
326
327         len = asprintf(&status, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos,
328                        htotal, prcnt, havg, print_time(eta));
329         if (len == -1) {
330                 return;
331         }
332
333         if (columns) {
334                 int required = strlen(name),
335                     available = columns - len - strlen("[] ");
336                 if (required > available) {
337                         if (asprintf(&filename, "...%s",
338                                      name + required - available + 3) == -1) {
339                                 return;
340                         }
341                 } else {
342                         filename = SMB_STRNDUP(name, available);
343                 }
344         } else {
345                 filename = SMB_STRDUP(name);
346         }
347
348         fprintf(stderr, "\r[%s] %s", filename, status);
349
350         free(filename);
351         free(status);
352 }
353
354 /* Return false on error, true on success. */
355
356 static bool smb_download_file(const char *base, const char *name,
357                               bool recursive, bool resume, bool toplevel,
358                               char *outfile)
359 {
360         int remotehandle, localhandle;
361         time_t start_time = time_mono(NULL);
362         const char *newpath;
363         char path[SMB_MAXPATHLEN];
364         char checkbuf[2][RESUME_CHECK_SIZE];
365         char *readbuf = NULL;
366         off_t offset_download = 0, offset_check = 0, curpos = 0,
367               start_offset = 0;
368         struct stat localstat, remotestat;
369         clock_t start_of_bucket_ticks = 0;
370         size_t bytes_in_bucket = 0;
371         size_t bucket_size = 0;
372         clock_t ticks_to_fill_bucket = 0;
373
374         snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base,
375                  (*base && *name && name[0] != '/' &&
376                   base[strlen(base)-1] != '/') ? "/" : "",
377                  name);
378
379         remotehandle = smbc_open(path, O_RDONLY, 0755);
380
381         if (remotehandle < 0) {
382                 switch (errno) {
383                 case EISDIR:
384                         if (!recursive) {
385                                 fprintf(stderr,
386                                         "%s is a directory. Specify -R "
387                                         "to download recursively\n",
388                                         path);
389                                 return false;
390                         }
391                         return smb_download_dir(base, name, resume);
392
393                 case ENOENT:
394                         fprintf(stderr,
395                                 "%s can't be found on the remote server\n",
396                                 path);
397                         return false;
398
399                 case ENOMEM:
400                         fprintf(stderr, "Not enough memory\n");
401                         return false;
402
403                 case ENODEV:
404                         fprintf(stderr,
405                                 "The share name used in %s does not exist\n",
406                                 path);
407                         return false;
408
409                 case EACCES:
410                         fprintf(stderr, "You don't have enough permissions "
411                                 "to access %s\n",
412                                 path);
413                         return false;
414
415                 default:
416                         perror("smbc_open");
417                         return false;
418                 }
419         }
420
421         if (smbc_fstat(remotehandle, &remotestat) < 0) {
422                 fprintf(stderr, "Can't stat %s: %s\n", path, strerror(errno));
423                 return false;
424         }
425
426         if (outfile) {
427                 newpath = outfile;
428         } else if (!name[0]) {
429                 newpath = strrchr(base, '/');
430                 if (newpath) {
431                         newpath++;
432                 } else {
433                         newpath = base;
434                 }
435         } else {
436                 newpath = name;
437         }
438
439         if (!toplevel && (newpath[0] == '/')) {
440                 newpath++;
441         }
442
443         /* Open local file according to the mode */
444         if (opt.update) {
445                 /* if it is up-to-date, skip */
446                 if (stat(newpath, &localstat) == 0 &&
447                     localstat.st_mtime >= remotestat.st_mtime) {
448                         if (opt.verbose) {
449                                 printf("%s is up-to-date, skipping\n", newpath);
450                         }
451                         smbc_close(remotehandle);
452                         return true;
453                 }
454                 /* else open it for writing and truncate if it exists */
455                 localhandle = open(
456                     newpath, O_CREAT | O_NONBLOCK | O_RDWR | O_TRUNC, 0775);
457                 if (localhandle < 0) {
458                         fprintf(stderr, "Can't open %s : %s\n", newpath,
459                                 strerror(errno));
460                         smbc_close(remotehandle);
461                         return false;
462                 }
463                 /* no offset */
464         } else if (!opt.send_stdout) {
465                 localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR |
466                                                 (!resume ? O_EXCL : 0),
467                                    0755);
468                 if (localhandle < 0) {
469                         fprintf(stderr, "Can't open %s: %s\n", newpath,
470                                 strerror(errno));
471                         smbc_close(remotehandle);
472                         return false;
473                 }
474
475                 if (fstat(localhandle, &localstat) != 0) {
476                         fprintf(stderr, "Can't fstat %s: %s\n", newpath,
477                                 strerror(errno));
478                         smbc_close(remotehandle);
479                         close(localhandle);
480                         return false;
481                 }
482
483                 start_offset = localstat.st_size;
484
485                 if (localstat.st_size &&
486                     localstat.st_size == remotestat.st_size) {
487                         if (opt.verbose) {
488                                 fprintf(stderr, "%s is already downloaded "
489                                         "completely.\n",
490                                         path);
491                         } else if (!opt.quiet) {
492                                 fprintf(stderr, "%s\n", path);
493                         }
494                         smbc_close(remotehandle);
495                         close(localhandle);
496                         return true;
497                 }
498
499                 if (localstat.st_size > RESUME_CHECK_OFFSET &&
500                     remotestat.st_size > RESUME_CHECK_OFFSET) {
501                         offset_download =
502                             localstat.st_size - RESUME_DOWNLOAD_OFFSET;
503                         offset_check = localstat.st_size - RESUME_CHECK_OFFSET;
504                         if (opt.verbose) {
505                                 printf("Trying to start resume of %s at %jd\n"
506                                        "At the moment %jd of %jd bytes have "
507                                        "been retrieved\n",
508                                        newpath, (intmax_t)offset_check,
509                                        (intmax_t)localstat.st_size,
510                                        (intmax_t)remotestat.st_size);
511                         }
512                 }
513
514                 if (offset_check) {
515                         off_t off1, off2;
516                         /* First, check all bytes from offset_check to
517                          * offset_download */
518                         off1 = lseek(localhandle, offset_check, SEEK_SET);
519                         if (off1 < 0) {
520                                 fprintf(stderr,
521                                         "Can't seek to %jd in local file %s\n",
522                                         (intmax_t)offset_check, newpath);
523                                 smbc_close(remotehandle);
524                                 close(localhandle);
525                                 return false;
526                         }
527
528                         off2 = smbc_lseek(remotehandle, offset_check, SEEK_SET);
529                         if (off2 < 0) {
530                                 fprintf(stderr,
531                                         "Can't seek to %jd in remote file %s\n",
532                                         (intmax_t)offset_check, newpath);
533                                 smbc_close(remotehandle);
534                                 close(localhandle);
535                                 return false;
536                         }
537
538                         if (off1 != off2) {
539                                 fprintf(stderr, "Offset in local and remote "
540                                         "files are different "
541                                         "(local: %jd, remote: %jd)\n",
542                                         (intmax_t)off1, (intmax_t)off2);
543                                 smbc_close(remotehandle);
544                                 close(localhandle);
545                                 return false;
546                         }
547
548                         if (smbc_read(remotehandle, checkbuf[0],
549                                       RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
550                                 fprintf(stderr, "Can't read %d bytes from "
551                                         "remote file %s\n",
552                                         RESUME_CHECK_SIZE, path);
553                                 smbc_close(remotehandle);
554                                 close(localhandle);
555                                 return false;
556                         }
557
558                         if (read(localhandle, checkbuf[1], RESUME_CHECK_SIZE) !=
559                             RESUME_CHECK_SIZE) {
560                                 fprintf(stderr, "Can't read %d bytes from "
561                                         "local file %s\n",
562                                         RESUME_CHECK_SIZE, name);
563                                 smbc_close(remotehandle);
564                                 close(localhandle);
565                                 return false;
566                         }
567
568                         if (memcmp(checkbuf[0], checkbuf[1],
569                                    RESUME_CHECK_SIZE) == 0) {
570                                 if (opt.verbose) {
571                                         printf("Current local and remote file "
572                                                "appear to be the same. "
573                                                "Starting download from "
574                                                "offset %jd\n",
575                                                (intmax_t)offset_download);
576                                 }
577                         } else {
578                                 fprintf(stderr, "Local and remote file appear "
579                                         "to be different, not "
580                                         "doing resume for %s\n",
581                                         path);
582                                 smbc_close(remotehandle);
583                                 close(localhandle);
584                                 return false;
585                         }
586                 }
587         } else {
588                 localhandle = STDOUT_FILENO;
589                 start_offset = 0;
590                 offset_download = 0;
591                 offset_check = 0;
592         }
593
594         /* We implement rate limiting by filling up a bucket with bytes and
595          * checking, once the bucket is filled, if it was filled too fast.
596          * If so, we sleep for some time to get an average transfer rate that
597          * equals to the one set by the user.
598          *
599          * The bucket size directly affects the traffic characteristics.
600          * The smaller the bucket the more frequent the pause/resume cycle.
601          * A large bucket can result in burst of high speed traffic and large
602          * pauses. A cycle of 100ms looks like a good value. This value (in
603          * ticks) is held in `ticks_to_fill_bucket`. The `bucket_size` is
604          * calculated as:
605          * `limit_rate * 1024 * / (CLOCKS_PER_SEC / ticks_to_fill_bucket)`
606          *
607          * After selecting the bucket size we also need to check the blocksize
608          * of the transfer, since this is the minimum unit of traffic that we
609          * can observe. Achieving a ~10% precision requires a blocksize with a
610          * maximum size of `bucket_size / 10`.
611          */
612         if (opt.limit_rate > 0) {
613                 unsigned max_block_size;
614                 /* This is the time that the bucket should take to fill. */
615                 ticks_to_fill_bucket = 100 /*ms*/ * CLOCKS_PER_SEC / 1000;
616                 /* This is the size of the bucket in bytes.
617                  * If we fill the bucket too quickly we should pause */
618                 bucket_size = opt.limit_rate * 1024 / (CLOCKS_PER_SEC / ticks_to_fill_bucket);
619                 max_block_size = bucket_size / 10;
620                 max_block_size = max_block_size > 0 ? max_block_size : 1;
621                 if (opt.blocksize > max_block_size) {
622                         if (opt.blocksize != SMB_DEFAULT_BLOCKSIZE) {
623                                 fprintf(stderr,
624                                         "Warning: Overriding block size to %d "
625                                         "due to limit-rate", max_block_size);
626                         }
627                         opt.blocksize = max_block_size;
628                 }
629                 start_of_bucket_ticks = clock();
630         }
631
632         readbuf = (char *)SMB_MALLOC(opt.blocksize);
633         if (!readbuf) {
634                 fprintf(stderr, "Failed to allocate %zu bytes for read "
635                                 "buffer (%s)", opt.blocksize, strerror(errno));
636                 if (localhandle != STDOUT_FILENO) {
637                         close(localhandle);
638                 }
639                 return false;
640         }
641
642         /* Now, download all bytes from offset_download to the end */
643         for (curpos = offset_download; curpos < remotestat.st_size;
644              curpos += opt.blocksize) {
645                 ssize_t bytesread;
646                 ssize_t byteswritten;
647
648                 /* Rate limiting. This pauses the transfer to limit traffic. */
649                 if (opt.limit_rate > 0) {
650                         if (bytes_in_bucket > bucket_size) {
651                                 clock_t now_ticks = clock();
652                                 clock_t diff_ticks = now_ticks
653                                                      - start_of_bucket_ticks;
654                                 /* Check if the bucket filled up too fast. */
655                                 if (diff_ticks < ticks_to_fill_bucket) {
656                                         /* Pause until `ticks_to_fill_bucket` */
657                                         double sleep_us
658                                          = (ticks_to_fill_bucket - diff_ticks)
659                                           * 1000000.0 / CLOCKS_PER_SEC;
660                                         usleep(sleep_us);
661                                 }
662                                 /* Reset the byte counter and the ticks. */
663                                 bytes_in_bucket = 0;
664                                 start_of_bucket_ticks = clock();
665                         }
666                 }
667
668                 bytesread = smbc_read(remotehandle, readbuf, opt.blocksize);
669                 if (opt.limit_rate > 0) {
670                         bytes_in_bucket += bytesread;
671                 }
672                 if(bytesread < 0) {
673                         fprintf(stderr,
674                                 "Can't read %zu bytes at offset %jd, file %s\n",
675                                 opt.blocksize, (intmax_t)curpos, path);
676                         smbc_close(remotehandle);
677                         if (localhandle != STDOUT_FILENO) {
678                                 close(localhandle);
679                         }
680                         free(readbuf);
681                         return false;
682                 }
683
684                 total_bytes += bytesread;
685
686                 byteswritten = write(localhandle, readbuf, bytesread);
687                 if (byteswritten != bytesread) {
688                         fprintf(stderr,
689                                 "Can't write %zd bytes to local file %s at "
690                                 "offset %jd\n", bytesread, path,
691                                 (intmax_t)curpos);
692                         free(readbuf);
693                         smbc_close(remotehandle);
694                         if (localhandle != STDOUT_FILENO) {
695                                 close(localhandle);
696                         }
697                         return false;
698                 }
699
700                 if (opt.dots) {
701                         fputc('.', stderr);
702                 } else if (!opt.quiet) {
703                         print_progress(newpath, start_time, time_mono(NULL),
704                                        start_offset, curpos,
705                                        remotestat.st_size);
706                 }
707         }
708
709         free(readbuf);
710
711         if (opt.dots) {
712                 fputc('\n', stderr);
713                 printf("%s downloaded\n", path);
714         } else if (!opt.quiet) {
715                 int i;
716                 fprintf(stderr, "\r%s", path);
717                 if (columns) {
718                         for (i = strlen(path); i < columns; i++) {
719                                 fputc(' ', stderr);
720                         }
721                 }
722                 fputc('\n', stderr);
723         }
724
725         smbc_close(remotehandle);
726         if (localhandle != STDOUT_FILENO) {
727                 close(localhandle);
728         }
729         return true;
730 }
731
732 static void clean_exit(void)
733 {
734         char bs[100];
735         human_readable(total_bytes, bs, sizeof(bs));
736         if (!opt.quiet) {
737                 fprintf(stderr, "Downloaded %s in %lu seconds\n", bs,
738                         (unsigned long)(time_mono(NULL) - total_start_time));
739         }
740         exit(0);
741 }
742
743 static void signal_quit(int v)
744 {
745         clean_exit();
746 }
747
748 int main(int argc, char **argv)
749 {
750         int c = 0;
751         const char *file = NULL;
752         int smb_encrypt = false;
753         int resume = 0, recursive = 0;
754         TALLOC_CTX *frame = talloc_stackframe();
755         bool ok = false;
756         const char **argv_const = discard_const_p(const char *, argv);
757         struct poptOption long_options[] = {
758                 POPT_AUTOHELP
759
760                 {
761                         .longName   = "guest",
762                         .shortName  = 'a',
763                         .argInfo    = POPT_ARG_NONE,
764                         .arg        = NULL,
765                         .val        = 'a',
766                         .descrip    = "Work as user guest"
767                 },
768                 {
769                         .longName   = "encrypt",
770                         .shortName  = 'e',
771                         .argInfo    = POPT_ARG_NONE,
772                         .arg        = &smb_encrypt,
773                         .val        = 1,
774                         .descrip    = "Encrypt SMB transport"
775                 },
776                 {
777                         .longName   = "resume",
778                         .shortName  = 'r',
779                         .argInfo    = POPT_ARG_NONE,
780                         .arg        = &resume,
781                         .val        = 1,
782                         .descrip    = "Automatically resume aborted files"
783                 },
784                 {
785                         .longName   = "update",
786                         .shortName  = 'u',
787                         .argInfo    = POPT_ARG_NONE,
788                         .arg        = &opt.update,
789                         .val        = 1,
790                         .descrip    = "Download only when remote file is "
791                                       "newer than local file or local file "
792                                       "is missing"
793                 },
794                 {
795                         .longName   = "recursive",
796                         .shortName  = 0,
797                         .argInfo    = POPT_ARG_NONE,
798                         .arg        = &recursive,
799                         .val        = true,
800                         .descrip    = "Recursively download files"
801                 },
802                 {
803                         .longName   = "blocksize",
804                         .shortName  = 'b',
805                         .argInfo    = POPT_ARG_INT,
806                         .arg        = &opt.blocksize,
807                         .val        = 'b',
808                         .descrip    = "Change number of bytes in a block"
809                 },
810
811                 {
812                         .longName   = "outputfile",
813                         .shortName  = 'o',
814                         .argInfo    = POPT_ARG_STRING,
815                         .arg        = &opt.outputfile,
816                         .val        = 'o',
817                         .descrip    = "Write downloaded data to specified file"
818                 },
819                 {
820                         .longName   = "stdout",
821                         .shortName  = 0,
822                         .argInfo    = POPT_ARG_NONE,
823                         .arg        = &opt.send_stdout,
824                         .val        = true,
825                         .descrip    = "Write data to stdout"
826                 },
827                 {
828                         .longName   = "dots",
829                         .shortName  = 'D',
830                         .argInfo    = POPT_ARG_NONE,
831                         .arg        = &opt.dots,
832                         .val        = 1,
833                         .descrip    = "Show dots as progress indication"
834                 },
835                 {
836                         .longName   = "quiet",
837                         .shortName  = 'q',
838                         .argInfo    = POPT_ARG_NONE,
839                         .arg        = &opt.quiet,
840                         .val        = 1,
841                         .descrip    = "Be quiet"
842                 },
843                 {
844                         .longName   = "verbose",
845                         .shortName  = 'v',
846                         .argInfo    = POPT_ARG_NONE,
847                         .arg        = &opt.verbose,
848                         .val        = 1,
849                         .descrip    = "Be verbose"
850                 },
851                 {
852                         .longName   = "limit-rate",
853                         .shortName  = 0,
854                         .argInfo    = POPT_ARG_INT,
855                         .arg        = &opt.limit_rate,
856                         .val        = 'l',
857                         .descrip    = "Limit download speed to this many KB/s"
858                 },
859
860                 POPT_COMMON_SAMBA
861                 POPT_COMMON_CONNECTION
862                 POPT_COMMON_CREDENTIALS
863                 POPT_LEGACY_S3
864                 POPT_COMMON_VERSION
865                 POPT_TABLEEND
866         };
867         poptContext pc = NULL;
868         struct cli_credentials *creds = NULL;
869         enum smb_encryption_setting encryption_state = SMB_ENCRYPTION_DEFAULT;
870         enum credentials_use_kerberos use_kerberos = CRED_USE_KERBEROS_DESIRED;
871         smbc_smb_encrypt_level encrypt_level = SMBC_ENCRYPTLEVEL_DEFAULT;
872 #if 0
873         enum smb_signing_setting signing_state = SMB_SIGNING_DEFAULT;
874         const char *use_signing = "auto";
875 #endif
876         bool is_nt_hash = false;
877         uint32_t gensec_features;
878         bool use_wbccache = false;
879         SMBCCTX *smb_ctx = NULL;
880         int dbg_lvl = -1;
881         int rc;
882
883         smb_init_locale();
884
885         ok = samba_cmdline_init(frame,
886                                 SAMBA_CMDLINE_CONFIG_CLIENT,
887                                 false);
888         if (!ok) {
889                 goto done;
890         }
891
892 #ifdef SIGWINCH
893         signal(SIGWINCH, change_columns);
894 #endif
895         signal(SIGINT, signal_quit);
896         signal(SIGTERM, signal_quit);
897
898         pc = samba_popt_get_context(getprogname(),
899                                     argc,
900                                     argv_const,
901                                     long_options,
902                                     0);
903         if (pc == NULL) {
904                 ok = false;
905                 goto done;
906         }
907
908         creds = samba_cmdline_get_creds();
909
910         while ((c = poptGetNextOpt(pc)) != -1) {
911                 switch (c) {
912                 case 'a':
913                         cli_credentials_set_anonymous(creds);
914                         break;
915                 case POPT_ERROR_BADOPT:
916                         fprintf(stderr, "\nInvalid option %s: %s\n\n",
917                                 poptBadOption(pc, 0), poptStrerror(c));
918                         poptPrintUsage(pc, stderr, 0);
919                         ok = false;
920                         goto done;
921                 }
922
923                 if (c < -1) {
924                         fprintf(stderr, "%s: %s\n",
925                                 poptBadOption(pc, POPT_BADOPTION_NOALIAS),
926                                 poptStrerror(c));
927                         ok = false;
928                         goto done;
929                 }
930         }
931
932         if ((opt.send_stdout || resume || opt.outputfile) && opt.update) {
933                 fprintf(stderr, "The -o, -R or -O and -U options can not be "
934                         "used together.\n");
935                 ok = true;
936                 goto done;
937         }
938         if ((opt.send_stdout || opt.outputfile) && recursive) {
939                 fprintf(stderr, "The -o or -O and -R options can not be "
940                         "used together.\n");
941                 ok = true;
942                 goto done;
943         }
944
945         if (opt.outputfile && opt.send_stdout) {
946                 fprintf(stderr, "The -o and -O options can not be "
947                         "used together.\n");
948                 ok = true;
949                 goto done;
950         }
951
952         samba_cmdline_burn(argc, argv);
953
954         /* smbc_new_context() will set the log level to 0 */
955         dbg_lvl = debuglevel_get();
956
957         smb_ctx = smbc_new_context();
958         if (smb_ctx == NULL) {
959                 fprintf(stderr, "Unable to initialize libsmbclient\n");
960                 ok = false;
961                 goto done;
962         }
963         smbc_setDebug(smb_ctx, dbg_lvl);
964
965         rc = smbc_setConfiguration(smb_ctx, lp_default_path());
966         if (rc < 0) {
967                 ok = false;
968                 goto done;
969         }
970
971         smbc_setFunctionAuthDataWithContext(smb_ctx,
972                                             get_auth_data_with_context_fn);
973
974         ok = smbc_init_context(smb_ctx);
975         if (!ok) {
976                 goto done;
977         }
978         smbc_set_context(smb_ctx);
979
980         encryption_state = cli_credentials_get_smb_encryption(creds);
981         switch (encryption_state) {
982         case SMB_ENCRYPTION_REQUIRED:
983                 encrypt_level = SMBC_ENCRYPTLEVEL_REQUIRE;
984                 break;
985         case SMB_ENCRYPTION_DESIRED:
986         case SMB_ENCRYPTION_IF_REQUIRED:
987                 encrypt_level = SMBC_ENCRYPTLEVEL_REQUEST;
988                 break;
989         case SMB_ENCRYPTION_OFF:
990                 encrypt_level = SMBC_ENCRYPTLEVEL_NONE;
991                 break;
992         case SMB_ENCRYPTION_DEFAULT:
993                 encrypt_level = SMBC_ENCRYPTLEVEL_DEFAULT;
994                 break;
995         }
996         if (smb_encrypt) {
997                 encrypt_level = SMBC_ENCRYPTLEVEL_REQUIRE;
998         }
999         smbc_setOptionSmbEncryptionLevel(smb_ctx, encrypt_level);
1000
1001 #if 0
1002         signing_state = cli_credentials_get_smb_signing(creds);
1003         if (encryption_state >= SMB_ENCRYPTION_DESIRED) {
1004                 signing_state = SMB_SIGNING_REQUIRED;
1005         }
1006         switch (signing_state) {
1007         case SMB_SIGNING_REQUIRED:
1008                 use_signing = "required";
1009                 break;
1010         case SMB_SIGNING_DEFAULT:
1011         case SMB_SIGNING_DESIRED:
1012         case SMB_SIGNING_IF_REQUIRED:
1013                 use_signing = "yes";
1014                 break;
1015         case SMB_SIGNING_OFF:
1016                 use_signing = "off";
1017                 break;
1018         default:
1019                 use_signing = "auto";
1020                 break;
1021         }
1022         /* FIXME: There is no libsmbclient function to set signing state */
1023 #endif
1024
1025         use_kerberos = cli_credentials_get_kerberos_state(creds);
1026         switch (use_kerberos) {
1027         case CRED_USE_KERBEROS_REQUIRED:
1028                 smbc_setOptionUseKerberos(smb_ctx, true);
1029                 smbc_setOptionFallbackAfterKerberos(smb_ctx, false);
1030                 break;
1031         case CRED_USE_KERBEROS_DESIRED:
1032                 smbc_setOptionUseKerberos(smb_ctx, true);
1033                 smbc_setOptionFallbackAfterKerberos(smb_ctx, true);
1034                 break;
1035         case CRED_USE_KERBEROS_DISABLED:
1036                 smbc_setOptionUseKerberos(smb_ctx, false);
1037                 break;
1038         }
1039
1040         /* Check if the password supplied is an NT hash */
1041         is_nt_hash = cli_credentials_is_password_nt_hash(creds);
1042         smbc_setOptionUseNTHash(smb_ctx, is_nt_hash);
1043
1044         /* Check if we should use the winbind ccache */
1045         gensec_features = cli_credentials_get_gensec_features(creds);
1046         use_wbccache = (gensec_features & GENSEC_FEATURE_NTLM_CCACHE);
1047         smbc_setOptionUseCCache(smb_ctx, use_wbccache);
1048
1049         columns = get_num_cols();
1050
1051         total_start_time = time_mono(NULL);
1052
1053         while ((file = poptGetArg(pc))) {
1054                 if (!recursive) {
1055                         ok = smb_download_file(file, "", recursive, resume,
1056                                                 true, opt.outputfile);
1057                 } else {
1058                         ok = smb_download_dir(file, "", resume);
1059                 }
1060         }
1061
1062 done:
1063         gfree_all();
1064         poptFreeContext(pc);
1065         TALLOC_FREE(frame);
1066         if (ok) {
1067                 clean_exit();
1068         }
1069         return ok ? 0 : 1;
1070 }