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