r11833: fix build issues in smbget with the Sun compiler. Reported by Richard Bollinger
[samba.git] / source3 / utils / smbget.c
1 /*
2    smbget: a wget-like utility with support for recursive downloading and 
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 2 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, write to the Free Software
18    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20 #include "includes.h"
21 #include "libsmbclient.h"
22
23 #if _FILE_OFFSET_BITS==64
24 #define OFF_T_FORMAT "%lld"
25 #else
26 #define OFF_T_FORMAT "%ld"
27 #endif
28
29 int columns = 0;
30
31 static int _resume, _recursive, debuglevel;
32 static char *outputfile;
33
34
35 time_t total_start_time = 0;
36 off_t total_bytes = 0;
37
38 #define SMB_MAXPATHLEN MAXPATHLEN
39
40 /* Number of bytes to read when checking whether local and remote file are really the same file */
41 #define RESUME_CHECK_SIZE                               512
42 #define RESUME_DOWNLOAD_OFFSET                  1024
43 #define RESUME_CHECK_OFFSET                             RESUME_DOWNLOAD_OFFSET+RESUME_CHECK_SIZE
44 /* Number of bytes to read at once */
45 #define SMB_DEFAULT_BLOCKSIZE                                   64000
46
47 const char *username = NULL, *password = NULL, *workgroup = NULL;
48 int nonprompt = 0, quiet = 0, dots = 0, keep_permissions = 0, verbose = 0, send_stdout = 0;
49 int blocksize = SMB_DEFAULT_BLOCKSIZE;
50
51 int smb_download_file(const char *base, const char *name, int recursive, int resume, char *outfile);
52
53 int get_num_cols(void)
54 {
55 #ifdef TIOCGWINSZ
56         struct winsize ws;
57         if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) < 0) {
58                 return 0;
59         }
60         return ws.ws_col;
61 #else
62 #warning No support for TIOCGWINSZ
63         char *cols = getenv("COLUMNS");
64         if(!cols) return 0;
65         return atoi(cols);
66 #endif
67 }
68
69 void change_columns(int sig)
70 {
71         columns = get_num_cols();
72 }
73
74 void human_readable(off_t s, char *buffer, int l)
75 {
76         if(s > 1024 * 1024 * 1024) snprintf(buffer, l, "%.2fGb", 1.0 * s / (1024 * 1024 * 1024));
77         else if(s > 1024 * 1024) snprintf(buffer, l, "%.2fMb", 1.0 * s / (1024 * 1024));
78         else if(s > 1024) snprintf(buffer, l, "%.2fkb", 1.0 * s / 1024);
79         else snprintf(buffer, l, OFF_T_FORMAT"b", s);
80 }
81
82 void get_auth_data(const char *srv, const char *shr, char *wg, int wglen, char *un, int unlen, char *pw, int pwlen)
83 {
84         static char hasasked = 0;
85         char *wgtmp, *usertmp;
86         char tmp[128];
87
88         if(hasasked) return;
89         hasasked = 1;
90
91         if(!nonprompt && !username) {
92                 printf("Username for %s at %s [guest] ", shr, srv);
93                 fgets(tmp, sizeof(tmp), stdin);
94                 if(tmp[strlen(tmp)-1] == '\n')tmp[strlen(tmp)-1] = '\0';
95                 strncpy(un, tmp, unlen-1);
96         } else if(username) strncpy(un, username, unlen-1);
97
98         if(!nonprompt && !password) {
99                 char *prompt, *pass;
100                 asprintf(&prompt, "Password for %s at %s: ", shr, srv);
101                 pass = getpass(prompt);
102                 free(prompt);
103                 strncpy(pw, pass, pwlen-1);
104         } else if(password) strncpy(pw, password, pwlen-1);
105
106         if(workgroup)strncpy(wg, workgroup, wglen-1);
107
108         wgtmp = SMB_STRNDUP(wg, wglen); 
109         usertmp = SMB_STRNDUP(un, unlen);
110         if(!quiet)printf("Using workgroup %s, %s%s\n", wgtmp, *usertmp?"user ":"guest user", usertmp);
111         free(wgtmp); free(usertmp);
112 }
113
114 int smb_download_dir(const char *base, const char *name, int resume)
115 {
116         char path[SMB_MAXPATHLEN];
117         int dirhandle;
118         struct smbc_dirent *dirent;
119         const char *relname = name;
120         char *tmpname;
121         struct stat remotestat;
122         snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (base[0] && name[0] && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name);
123
124         /* List files in directory and call smb_download_file on them */
125         dirhandle = smbc_opendir(path);
126         if(dirhandle < 1) {
127                 if(errno == ENOTDIR) return smb_download_file(base, name, 1, resume, NULL);
128                 fprintf(stderr, "Can't open directory %s: %s\n", path, strerror(errno));
129                 return 0;
130         }
131
132         while(*relname == '/')relname++;
133         mkdir(relname, 0755);
134         
135         tmpname = SMB_STRDUP(name);
136
137         while((dirent = smbc_readdir(dirhandle))) {
138                 char *newname;
139                 if(!strcmp(dirent->name, ".") || !strcmp(dirent->name, ".."))continue;
140                 asprintf(&newname, "%s/%s", tmpname, dirent->name);
141                 switch(dirent->smbc_type) {
142                 case SMBC_DIR:
143                         smb_download_dir(base, newname, resume);
144                         break;
145
146                 case SMBC_WORKGROUP:
147                         smb_download_dir("smb://", dirent->name, resume);
148                         break;
149
150                 case SMBC_SERVER:
151                         smb_download_dir("smb://", dirent->name, resume);
152                         break;
153
154                 case SMBC_FILE:
155                         smb_download_file(base, newname, 1, resume, NULL);
156                         break;
157
158                 case SMBC_FILE_SHARE:
159                         smb_download_dir(base, newname, resume);
160                         break;
161
162                 case SMBC_PRINTER_SHARE:
163                         if(!quiet)printf("Ignoring printer share %s\n", dirent->name);
164                         break;
165
166                 case SMBC_COMMS_SHARE:
167                         if(!quiet)printf("Ignoring comms share %s\n", dirent->name);
168                         break;
169                         
170                 case SMBC_IPC_SHARE:
171                         if(!quiet)printf("Ignoring ipc$ share %s\n", dirent->name);
172                         break;
173
174                 default:
175                         fprintf(stderr, "Ignoring file '%s' of type '%d'\n", newname, dirent->smbc_type);
176                         break;
177                 }
178                 free(newname);
179         }
180         free(tmpname);
181
182         if(keep_permissions) {
183                 if(smbc_fstat(dirhandle, &remotestat) < 0) {
184                         fprintf(stderr, "Unable to get stats on %s on remote server\n", path);
185                         smbc_closedir(dirhandle);
186                         return 0;
187                 }
188                 
189                 if(chmod(relname, remotestat.st_mode) < 0) {
190                         fprintf(stderr, "Unable to change mode of local dir %s to %o\n", relname, remotestat.st_mode);
191                         smbc_closedir(dirhandle);
192                         return 0;
193                 }
194         }
195
196         smbc_closedir(dirhandle);
197         return 1;
198 }
199
200 char *print_time(long t)
201 {
202         static char buffer[100];
203         int secs, mins, hours;
204         if(t < -1) {
205                 strncpy(buffer, "Unknown", sizeof(buffer));
206                 return buffer;
207         }
208
209         secs = (int)t % 60;
210         mins = (int)t / 60 % 60;
211         hours = (int)t / (60 * 60);
212         snprintf(buffer, sizeof(buffer)-1, "%02d:%02d:%02d", hours, mins, secs);
213         return buffer;
214 }
215
216 void print_progress(const char *name, time_t start, time_t now, off_t start_pos, off_t pos, off_t total)
217 {
218         double avg = 0.0;
219         long  eta = -1; 
220         double prcnt = 0.0;
221         char hpos[20], htotal[20], havg[20];
222         char *status, *filename;
223         int len;
224         if(now - start)avg = 1.0 * (pos - start_pos) / (now - start);
225         eta = (total - pos) / avg;
226         if(total)prcnt = 100.0 * pos / total;
227
228         human_readable(pos, hpos, sizeof(hpos));
229         human_readable(total, htotal, sizeof(htotal));
230         human_readable(avg, havg, sizeof(havg));
231
232         len = asprintf(&status, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos, htotal, prcnt, havg, print_time(eta));
233         
234         if(columns) {
235                 int required = strlen(name), available = columns - len - strlen("[] ");
236                 if(required > available) asprintf(&filename, "...%s", name + required - available + 3);
237                 else filename = SMB_STRNDUP(name, available);
238         } else filename = SMB_STRDUP(name);
239
240         fprintf(stderr, "\r[%s] %s", filename, status);
241
242         free(filename); free(status);
243 }
244
245 int smb_download_file(const char *base, const char *name, int recursive, int resume, char *outfile) {
246         int remotehandle, localhandle;
247         time_t start_time = time(NULL);
248         const char *newpath;
249         char path[SMB_MAXPATHLEN];
250         char checkbuf[2][RESUME_CHECK_SIZE];
251         char *readbuf = NULL;
252         off_t offset_download = 0, offset_check = 0, curpos = 0, start_offset = 0;
253         struct stat localstat, remotestat;
254
255         snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (*base && *name && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name);
256         
257         remotehandle = smbc_open(path, O_RDONLY, 0755);
258
259         if(remotehandle < 0) {
260                 switch(errno) {
261                 case EISDIR: 
262                         if(!recursive) {
263                                 fprintf(stderr, "%s is a directory. Specify -R to download recursively\n", path);
264                                 return 0;
265                         }
266                         smb_download_dir(base, name, resume);
267                         return 0;
268
269                 case ENOENT:
270                         fprintf(stderr, "%s can't be found on the remote server\n", path);
271                         return 0;
272
273                 case ENOMEM:
274                         fprintf(stderr, "Not enough memory\n");
275                         exit(1);
276                         return 0;
277
278                 case ENODEV:
279                         fprintf(stderr, "The share name used in %s does not exist\n", path);
280                         return 0;
281
282                 case EACCES:
283                         fprintf(stderr, "You don't have enough permissions to access %s\n", path);
284                         return 0;
285
286                 default:
287                         perror("smbc_open");
288                         return 0;
289                 }
290         } 
291
292         if(smbc_fstat(remotehandle, &remotestat) < 0) {
293                 fprintf(stderr, "Can't stat %s: %s\n", path, strerror(errno));
294                 return 0;
295         }
296
297         if(outfile) newpath = outfile;
298         else if(!name[0]) {
299                 newpath = strrchr(base, '/');
300                 if(newpath)newpath++; else newpath = base;
301         } else newpath = name;
302
303         if(newpath[0] == '/')newpath++;
304         
305         /* Open local file and, if necessary, resume */
306         if(!send_stdout) {
307                 localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR | (!resume?O_EXCL:0), 0755);
308                 if(localhandle < 0) {
309                         fprintf(stderr, "Can't open %s: %s\n", newpath, strerror(errno));
310                         smbc_close(remotehandle);
311                         return 0;
312                 }
313         
314                 fstat(localhandle, &localstat);
315
316                 start_offset = localstat.st_size;
317
318                 if(localstat.st_size && localstat.st_size == remotestat.st_size) {
319                         if(verbose)fprintf(stderr, "%s is already downloaded completely.\n", path);
320                         else if(!quiet)fprintf(stderr, "%s\n", path);
321                         smbc_close(remotehandle);
322                         close(localhandle);
323                         return 1;
324                 }
325
326                 if(localstat.st_size > RESUME_CHECK_OFFSET && remotestat.st_size > RESUME_CHECK_OFFSET) {
327                         offset_download = localstat.st_size - RESUME_DOWNLOAD_OFFSET;
328                         offset_check = localstat.st_size - RESUME_CHECK_OFFSET;
329                         if(verbose)printf("Trying to start resume of %s at "OFF_T_FORMAT"\n"
330                                    "At the moment "OFF_T_FORMAT" of "OFF_T_FORMAT" bytes have been retrieved\n", newpath, offset_check, 
331                                    localstat.st_size, remotestat.st_size);
332                 }
333
334                 if(offset_check) { 
335                         off_t off1, off2;
336                         /* First, check all bytes from offset_check to offset_download */
337                         off1 = lseek(localhandle, offset_check, SEEK_SET);
338                         if(off1 < 0) {
339                                 fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in local file %s\n", offset_check, newpath);
340                                 smbc_close(remotehandle); close(localhandle);
341                                 return 0;
342                         }
343
344                         off2 = smbc_lseek(remotehandle, offset_check, SEEK_SET); 
345                         if(off2 < 0) {
346                                 fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in remote file %s\n", offset_check, newpath);
347                                 smbc_close(remotehandle); close(localhandle);
348                                 return 0;
349                         }
350
351                         if(off1 != off2) {
352                                 fprintf(stderr, "Offset in local and remote files is different (local: "OFF_T_FORMAT", remote: "OFF_T_FORMAT")\n", off1, off2);
353                                 return 0;
354                         }
355
356                         if(smbc_read(remotehandle, checkbuf[0], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
357                                 fprintf(stderr, "Can't read %d bytes from remote file %s\n", RESUME_CHECK_SIZE, path);
358                                 smbc_close(remotehandle); close(localhandle);
359                                 return 0;
360                         }
361
362                         if(read(localhandle, checkbuf[1], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) {
363                                 fprintf(stderr, "Can't read %d bytes from local file %s\n", RESUME_CHECK_SIZE, name);
364                                 smbc_close(remotehandle); close(localhandle);
365                                 return 0;
366                         }
367
368                         if(memcmp(checkbuf[0], checkbuf[1], RESUME_CHECK_SIZE) == 0) {
369                                 if(verbose)printf("Current local and remote file appear to be the same. Starting download from offset "OFF_T_FORMAT"\n", offset_download);
370                         } else {
371                                 fprintf(stderr, "Local and remote file appear to be different, not doing resume for %s\n", path);
372                                 smbc_close(remotehandle); close(localhandle);
373                                 return 0;
374                         }
375                 }
376         } else {
377                 localhandle = STDOUT_FILENO;
378                 start_offset = 0;
379                 offset_download = 0;
380                 offset_check = 0;
381         }
382
383         readbuf = SMB_MALLOC(blocksize);
384
385         /* Now, download all bytes from offset_download to the end */
386         for(curpos = offset_download; curpos < remotestat.st_size; curpos+=blocksize) {
387                 ssize_t bytesread = smbc_read(remotehandle, readbuf, blocksize);
388                 if(bytesread < 0) {
389                         fprintf(stderr, "Can't read %d bytes at offset "OFF_T_FORMAT", file %s\n", blocksize, curpos, path);
390                         smbc_close(remotehandle);
391                         if (localhandle != STDOUT_FILENO) close(localhandle);
392                         free(readbuf);
393                         return 0;
394                 }
395
396                 total_bytes += bytesread;
397
398                 if(write(localhandle, readbuf, bytesread) < 0) {
399                         fprintf(stderr, "Can't write %d bytes to local file %s at offset "OFF_T_FORMAT"\n", bytesread, path, curpos);
400                         free(readbuf);
401                         smbc_close(remotehandle);
402                         if (localhandle != STDOUT_FILENO) close(localhandle);
403                         return 0;
404                 }
405
406                 if(dots)fputc('.', stderr);
407                 else if(!quiet) {
408                         print_progress(newpath, start_time, time(NULL), start_offset, curpos, remotestat.st_size);
409                 }
410         }
411
412         free(readbuf);
413
414         if(dots){
415                 fputc('\n', stderr);
416                 printf("%s downloaded\n", path);
417         } else if(!quiet) {
418                 int i;
419                 fprintf(stderr, "\r%s", path);
420                 if(columns) {
421                         for(i = strlen(path); i < columns; i++) {
422                                 fputc(' ', stderr);
423                         }
424                 }
425                 fputc('\n', stderr);
426         }
427
428         if(keep_permissions && !send_stdout) {
429                 if(fchmod(localhandle, remotestat.st_mode) < 0) {
430                         fprintf(stderr, "Unable to change mode of local file %s to %o\n", path, remotestat.st_mode);
431                         smbc_close(remotehandle);
432                         close(localhandle);
433                         return 0;
434                 }
435         }
436
437         smbc_close(remotehandle);
438         if (localhandle != STDOUT_FILENO) close(localhandle);
439         return 1;
440 }
441
442 void clean_exit(void)
443 {
444         char bs[100];
445         human_readable(total_bytes, bs, sizeof(bs));
446         if(!quiet)fprintf(stderr, "Downloaded %s in %lu seconds\n", bs, time(NULL) - total_start_time);
447         exit(0);
448 }
449
450 void signal_quit(int v)
451 {
452         clean_exit();
453 }
454
455 int readrcfile(const char *name, const struct poptOption long_options[])
456 {
457         FILE *fd = fopen(name, "r");
458         int lineno = 0, i;
459         char var[101], val[101];
460         char found;
461         int *intdata; char **stringdata;
462         if(!fd) {
463                 fprintf(stderr, "Can't open RC file %s\n", name);
464                 return 1;
465         }
466
467         while(!feof(fd)) {
468                 lineno++;
469                 if(fscanf(fd, "%100s %100s\n", var, val) < 2) {
470                         fprintf(stderr, "Can't parse line %d of %s, ignoring.\n", lineno, name);
471                         continue;
472                 }
473
474                 found = 0;
475
476                 for(i = 0; long_options[i].shortName; i++) {
477                         if(!long_options[i].longName)continue;
478                         if(strcmp(long_options[i].longName, var)) continue;
479                         if(!long_options[i].arg)continue;
480
481                         switch(long_options[i].argInfo) {
482                         case POPT_ARG_NONE:
483                                 intdata = (int *)long_options[i].arg;
484                                 if(!strcmp(val, "on")) *intdata = 1;
485                                 else if(!strcmp(val, "off")) *intdata = 0;
486                                 else fprintf(stderr, "Illegal value %s for %s at line %d in %s\n", val, var, lineno, name);
487                                 break;
488                         case POPT_ARG_INT:
489                                 intdata = (int *)long_options[i].arg;
490                                 *intdata = atoi(val);
491                                 break;
492                         case POPT_ARG_STRING:
493                                 stringdata = (char **)long_options[i].arg;
494                                 *stringdata = SMB_STRDUP(val);
495                                 break;
496                         default:
497                                 fprintf(stderr, "Invalid variable %s at line %d in %s\n", var, lineno, name);
498                                 break;
499                         }
500
501                         found = 1;
502                 }
503                 if(!found) {
504                         fprintf(stderr, "Invalid variable %s at line %d in %s\n", var, lineno, name);
505                 }
506         }
507
508         fclose(fd);
509         return 0;
510 }
511
512 int main(int argc, const char **argv)
513 {
514         int c = 0;
515         const char *file = NULL;
516         char *rcfile = NULL;
517         struct poptOption long_options[] = {
518                 {"guest", 'a', POPT_ARG_NONE, NULL, 'a', "Work as user guest" },        
519                 {"resume", 'r', POPT_ARG_NONE, &_resume, 0, "Automatically resume aborted files" },
520                 {"recursive", 'R',  POPT_ARG_NONE, &_recursive, 0, "Recursively download files" },
521                 {"username", 'u', POPT_ARG_STRING, &username, 'u', "Username to use" },
522                 {"password", 'p', POPT_ARG_STRING, &password, 'p', "Password to use" },
523                 {"workgroup", 'w', POPT_ARG_STRING, &workgroup, 'w', "Workgroup to use (optional)" },
524                 {"nonprompt", 'n', POPT_ARG_NONE, &nonprompt, 'n', "Don't ask anything (non-interactive)" },
525                 {"debuglevel", 'd', POPT_ARG_INT, &debuglevel, 'd', "Debuglevel to use" },
526                 {"outputfile", 'o', POPT_ARG_STRING, &outputfile, 'o', "Write downloaded data to specified file" },
527                 {"stdout", 'O', POPT_ARG_NONE, &send_stdout, 'O', "Write data to stdout" },
528                 {"dots", 'D', POPT_ARG_NONE, &dots, 'D', "Show dots as progress indication" },
529                 {"quiet", 'q', POPT_ARG_NONE, &quiet, 'q', "Be quiet" },
530                 {"verbose", 'v', POPT_ARG_NONE, &verbose, 'v', "Be verbose" },
531                 {"keep-permissions", 'P', POPT_ARG_NONE, &keep_permissions, 'P', "Keep permissions" },
532                 {"blocksize", 'b', POPT_ARG_INT, &blocksize, 'b', "Change number of bytes in a block"},
533                 {"rcfile", 'f', POPT_ARG_STRING, NULL, 0, "Use specified rc file"},
534                 POPT_AUTOHELP
535                 POPT_TABLEEND
536         };
537         poptContext pc;
538
539         /* only read rcfile if it exists */
540         asprintf(&rcfile, "%s/.smbgetrc", getenv("HOME"));
541         if(access(rcfile, F_OK) == 0) 
542                 readrcfile(rcfile, long_options);
543         free(rcfile);
544
545 #ifdef SIGWINCH
546         signal(SIGWINCH, change_columns);
547 #endif
548         signal(SIGINT, signal_quit);
549         signal(SIGTERM, signal_quit);
550
551         pc = poptGetContext(argv[0], argc, argv, long_options, 0);
552
553         while((c = poptGetNextOpt(pc)) >= 0) {
554                 switch(c) {
555                 case 'f':
556                         readrcfile(poptGetOptArg(pc), long_options);
557                         break;
558                 case 'a':
559                         username = ""; password = "";
560                         break;
561                 }
562         }
563
564         if((send_stdout || outputfile) && _recursive) {
565                 fprintf(stderr, "The -o or -O and -R options can not be used together.\n");
566                 return 1;
567         }
568
569         if(outputfile && send_stdout) {
570                 fprintf(stderr, "The -o and -O options cannot be used together.\n");
571                 return 1;
572         }
573
574         if(smbc_init(get_auth_data, debuglevel) < 0) {
575                 fprintf(stderr, "Unable to initialize libsmbclient\n");
576                 return 1;
577         }
578
579         columns = get_num_cols();
580
581         total_start_time = time(NULL);
582
583         while ( (file = poptGetArg(pc)) ) {
584                 if (!_recursive) 
585                         return smb_download_file(file, "", _recursive, _resume, outputfile);
586                 else 
587                         return smb_download_dir(file, "", _resume);
588         }
589
590         clean_exit();
591
592         return 0;
593 }