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