ftpd: handle restarts past 2147483647 bytes. closes 10741
[oweals/busybox.git] / networking / ftpgetput.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * ftpget
4  *
5  * Mini implementation of FTP to retrieve a remote file.
6  *
7  * Copyright (C) 2002 Jeff Angielski, The PTR Group <jeff@theptrgroup.com>
8  * Copyright (C) 2002 Glenn McGrath
9  *
10  * Based on wget.c by Chip Rosenthal Covad Communications
11  * <chip@laserlink.net>
12  *
13  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
14  */
15 //config:config FTPGET
16 //config:       bool "ftpget (8 kb)"
17 //config:       default y
18 //config:       help
19 //config:       Retrieve a remote file via FTP.
20 //config:
21 //config:config FTPPUT
22 //config:       bool "ftpput (7.7 kb)"
23 //config:       default y
24 //config:       help
25 //config:       Store a remote file via FTP.
26 //config:
27 //config:config FEATURE_FTPGETPUT_LONG_OPTIONS
28 //config:       bool "Enable long options in ftpget/ftpput"
29 //config:       default y
30 //config:       depends on LONG_OPTS && (FTPGET || FTPPUT)
31
32 //applet:IF_FTPGET(APPLET_ODDNAME(ftpget, ftpgetput, BB_DIR_USR_BIN, BB_SUID_DROP, ftpget))
33 //applet:IF_FTPPUT(APPLET_ODDNAME(ftpput, ftpgetput, BB_DIR_USR_BIN, BB_SUID_DROP, ftpput))
34
35 //kbuild:lib-$(CONFIG_FTPGET) += ftpgetput.o
36 //kbuild:lib-$(CONFIG_FTPPUT) += ftpgetput.o
37
38 //usage:#define ftpget_trivial_usage
39 //usage:       "[OPTIONS] HOST [LOCAL_FILE] REMOTE_FILE"
40 //usage:#define ftpget_full_usage "\n\n"
41 //usage:       "Download a file via FTP\n"
42 //usage:     "\n        -c      Continue previous transfer"
43 //usage:     "\n        -v      Verbose"
44 //usage:     "\n        -u USER Username"
45 //usage:     "\n        -p PASS Password"
46 //usage:     "\n        -P NUM  Port"
47 //usage:
48 //usage:#define ftpput_trivial_usage
49 //usage:       "[OPTIONS] HOST [REMOTE_FILE] LOCAL_FILE"
50 //usage:#define ftpput_full_usage "\n\n"
51 //usage:       "Upload a file to a FTP server\n"
52 //usage:     "\n        -v      Verbose"
53 //usage:     "\n        -u USER Username"
54 //usage:     "\n        -p PASS Password"
55 //usage:     "\n        -P NUM  Port number"
56
57 #include "libbb.h"
58 #include "common_bufsiz.h"
59
60 struct globals {
61         const char *user;
62         const char *password;
63         struct len_and_sockaddr *lsa;
64         FILE *control_stream;
65         int verbose_flag;
66         int do_continue;
67         char buf[4]; /* actually [BUFSZ] */
68 } FIX_ALIASING;
69 #define G (*(struct globals*)bb_common_bufsiz1)
70 enum { BUFSZ = COMMON_BUFSIZE - offsetof(struct globals, buf) };
71 #define user           (G.user          )
72 #define password       (G.password      )
73 #define lsa            (G.lsa           )
74 #define control_stream (G.control_stream)
75 #define verbose_flag   (G.verbose_flag  )
76 #define do_continue    (G.do_continue   )
77 #define buf            (G.buf           )
78 #define INIT_G() do { \
79         setup_common_bufsiz(); \
80         BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
81 } while (0)
82
83
84 static void ftp_die(const char *msg) NORETURN;
85 static void ftp_die(const char *msg)
86 {
87         char *cp = buf; /* buf holds peer's response */
88
89         /* Guard against garbage from remote server */
90         while (*cp >= ' ' && *cp < '\x7f')
91                 cp++;
92         *cp = '\0';
93         bb_error_msg_and_die("unexpected server response%s%s: %s",
94                         (msg ? " to " : ""), (msg ? msg : ""), buf);
95 }
96
97 static int ftpcmd(const char *s1, const char *s2)
98 {
99         unsigned n;
100
101         if (verbose_flag) {
102                 bb_error_msg("cmd %s %s", s1, s2);
103         }
104
105         if (s1) {
106                 fprintf(control_stream, (s2 ? "%s %s\r\n" : "%s %s\r\n"+3),
107                                                 s1, s2);
108                 fflush(control_stream);
109         }
110
111         do {
112                 strcpy(buf, "EOF"); /* for ftp_die */
113                 if (fgets(buf, BUFSZ - 2, control_stream) == NULL) {
114                         ftp_die(NULL);
115                 }
116         } while (!isdigit(buf[0]) || buf[3] != ' ');
117
118         buf[3] = '\0';
119         n = xatou(buf);
120         buf[3] = ' ';
121         return n;
122 }
123
124 static void ftp_login(void)
125 {
126         /* Connect to the command socket */
127         control_stream = fdopen(xconnect_stream(lsa), "r+");
128         if (control_stream == NULL) {
129                 /* fdopen failed - extremely unlikely */
130                 bb_perror_nomsg_and_die();
131         }
132
133         if (ftpcmd(NULL, NULL) != 220) {
134                 ftp_die(NULL);
135         }
136
137         /*  Login to the server */
138         switch (ftpcmd("USER", user)) {
139         case 230:
140                 break;
141         case 331:
142                 if (ftpcmd("PASS", password) != 230) {
143                         ftp_die("PASS");
144                 }
145                 break;
146         default:
147                 ftp_die("USER");
148         }
149
150         ftpcmd("TYPE I", NULL);
151 }
152
153 static int xconnect_ftpdata(void)
154 {
155         char *buf_ptr;
156         unsigned port_num;
157
158 /*
159 PASV command will not work for IPv6. RFC2428 describes
160 IPv6-capable "extended PASV" - EPSV.
161
162 "EPSV [protocol]" asks server to bind to and listen on a data port
163 in specified protocol. Protocol is 1 for IPv4, 2 for IPv6.
164 If not specified, defaults to "same as used for control connection".
165 If server understood you, it should answer "229 <some text>(|||port|)"
166 where "|" are literal pipe chars and "port" is ASCII decimal port#.
167
168 There is also an IPv6-capable replacement for PORT (EPRT),
169 but we don't need that.
170
171 NB: PASV may still work for some servers even over IPv6.
172 For example, vsftp happily answers
173 "227 Entering Passive Mode (0,0,0,0,n,n)" and proceeds as usual.
174 */
175         if (!ENABLE_FEATURE_IPV6
176          || ftpcmd("EPSV", NULL) != 229
177         ) {
178 /* maybe also go straight to PAST if lsa->u.sa.sa_family == AF_INET? */
179                 if (ftpcmd("PASV", NULL) != 227) {
180                         ftp_die("PASV");
181                 }
182
183                 /* Response is "NNN garbageN1,N2,N3,N4,P1,P2[)garbage]"
184                  * Server's IP is N1.N2.N3.N4 (we ignore it)
185                  * Server's port for data connection is P1*256+P2 */
186                 buf_ptr = strrchr(buf, ')');
187                 if (buf_ptr) *buf_ptr = '\0';
188
189                 buf_ptr = strrchr(buf, ',');
190                 *buf_ptr = '\0';
191                 port_num = xatoul_range(buf_ptr + 1, 0, 255);
192
193                 buf_ptr = strrchr(buf, ',');
194                 *buf_ptr = '\0';
195                 port_num += xatoul_range(buf_ptr + 1, 0, 255) * 256;
196         } else {
197                 /* Response is "NNN garbage(|||P1|)"
198                  * Server's port for data connection is P1 */
199                 buf_ptr = strrchr(buf, '|');
200                 if (buf_ptr) *buf_ptr = '\0';
201
202                 buf_ptr = strrchr(buf, '|');
203                 *buf_ptr = '\0';
204                 port_num = xatoul_range(buf_ptr + 1, 0, 65535);
205         }
206
207         set_nport(&lsa->u.sa, htons(port_num));
208         return xconnect_stream(lsa);
209 }
210
211 static int pump_data_and_QUIT(int from, int to)
212 {
213         /* copy the file */
214         if (bb_copyfd_eof(from, to) == -1) {
215                 /* error msg is already printed by bb_copyfd_eof */
216                 return EXIT_FAILURE;
217         }
218
219         /* close data connection */
220         close(from); /* don't know which one is that, so we close both */
221         close(to);
222
223         /* does server confirm that transfer is finished? */
224         if (ftpcmd(NULL, NULL) != 226) {
225                 ftp_die(NULL);
226         }
227         ftpcmd("QUIT", NULL);
228
229         return EXIT_SUCCESS;
230 }
231
232 #if !ENABLE_FTPGET
233 int ftp_receive(const char *local_path, char *server_path);
234 #else
235 static
236 int ftp_receive(const char *local_path, char *server_path)
237 {
238         int fd_data;
239         int fd_local = -1;
240         off_t beg_range = 0;
241
242         /* connect to the data socket */
243         fd_data = xconnect_ftpdata();
244
245         if (ftpcmd("SIZE", server_path) != 213) {
246                 do_continue = 0;
247         }
248
249         if (LONE_DASH(local_path)) {
250                 fd_local = STDOUT_FILENO;
251                 do_continue = 0;
252         }
253
254         if (do_continue) {
255                 struct stat sbuf;
256                 /* lstat would be wrong here! */
257                 if (stat(local_path, &sbuf) < 0) {
258                         bb_perror_msg_and_die("stat");
259                 }
260                 if (sbuf.st_size > 0) {
261                         beg_range = sbuf.st_size;
262                 } else {
263                         do_continue = 0;
264                 }
265         }
266
267         if (do_continue) {
268                 sprintf(buf, "REST %"OFF_FMT"u", beg_range);
269                 if (ftpcmd(buf, NULL) != 350) {
270                         do_continue = 0;
271                 }
272         }
273
274         if (ftpcmd("RETR", server_path) > 150) {
275                 ftp_die("RETR");
276         }
277
278         /* create local file _after_ we know that remote file exists */
279         if (fd_local == -1) {
280                 fd_local = xopen(local_path,
281                         do_continue ? (O_APPEND | O_WRONLY)
282                                     : (O_CREAT | O_TRUNC | O_WRONLY)
283                 );
284         }
285
286         return pump_data_and_QUIT(fd_data, fd_local);
287 }
288 #endif
289
290 #if !ENABLE_FTPPUT
291 int ftp_send(const char *server_path, char *local_path);
292 #else
293 static
294 int ftp_send(const char *server_path, char *local_path)
295 {
296         int fd_data;
297         int fd_local;
298         int response;
299
300         /* connect to the data socket */
301         fd_data = xconnect_ftpdata();
302
303         /* get the local file */
304         fd_local = STDIN_FILENO;
305         if (NOT_LONE_DASH(local_path))
306                 fd_local = xopen(local_path, O_RDONLY);
307
308         response = ftpcmd("STOR", server_path);
309         switch (response) {
310         case 125:
311         case 150:
312                 break;
313         default:
314                 ftp_die("STOR");
315         }
316
317         return pump_data_and_QUIT(fd_local, fd_data);
318 }
319 #endif
320
321 #if ENABLE_FEATURE_FTPGETPUT_LONG_OPTIONS
322 static const char ftpgetput_longopts[] ALIGN1 =
323         "continue\0" Required_argument "c"
324         "verbose\0"  No_argument       "v"
325         "username\0" Required_argument "u"
326         "password\0" Required_argument "p"
327         "port\0"     Required_argument "P"
328         ;
329 #endif
330
331 int ftpgetput_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
332 int ftpgetput_main(int argc UNUSED_PARAM, char **argv)
333 {
334         const char *port = "ftp";
335         /* socket to ftp server */
336
337 #if ENABLE_FTPPUT && !ENABLE_FTPGET
338 # define ftp_action ftp_send
339 #elif ENABLE_FTPGET && !ENABLE_FTPPUT
340 # define ftp_action ftp_receive
341 #else
342         int (*ftp_action)(const char *, char *) = ftp_send;
343
344         /* Check to see if the command is ftpget or ftput */
345         if (applet_name[3] == 'g') {
346                 ftp_action = ftp_receive;
347         }
348 #endif
349
350         INIT_G();
351         /* Set default values */
352         user = "anonymous";
353         password = "busybox@";
354
355         /*
356          * Decipher the command line
357          */
358         /* must have 2 to 3 params; -v and -c count */
359 #define OPTSTRING "^cvu:p:P:" "\0" "-2:?3:vv:cc"
360 #if ENABLE_FEATURE_FTPGETPUT_LONG_OPTIONS
361         getopt32long(argv, OPTSTRING, ftpgetput_longopts,
362 #else
363         getopt32(argv, OPTSTRING,
364 #endif
365                         &user, &password, &port, &verbose_flag, &do_continue
366         );
367         argv += optind;
368
369         /* We want to do exactly _one_ DNS lookup, since some
370          * sites (i.e. ftp.us.debian.org) use round-robin DNS
371          * and we want to connect to only one IP... */
372         lsa = xhost2sockaddr(argv[0], bb_lookup_port(port, "tcp", 21));
373         if (verbose_flag) {
374                 printf("Connecting to %s (%s)\n", argv[0],
375                         xmalloc_sockaddr2dotted(&lsa->u.sa));
376         }
377
378         ftp_login();
379         return ftp_action(argv[1], argv[2] ? argv[2] : argv[1]);
380 }