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