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