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