tftp.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * A simple tftp client/server for busybox.
  4. * Tries to follow RFC1350.
  5. * Only "octet" mode supported.
  6. * Optional blocksize negotiation (RFC2347 + RFC2348)
  7. *
  8. * Copyright (C) 2001 Magnus Damm <damm@opensource.se>
  9. *
  10. * Parts of the code based on:
  11. *
  12. * atftp: Copyright (C) 2000 Jean-Pierre Lefebvre <helix@step.polymtl.ca>
  13. * and Remi Lefebvre <remi@debian.org>
  14. *
  15. * utftp: Copyright (C) 1999 Uwe Ohse <uwe@ohse.de>
  16. *
  17. * tftpd added by Denys Vlasenko & Vladimir Dronnikov
  18. *
  19. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  20. */
  21. //usage:#define tftp_trivial_usage
  22. //usage: "[OPTIONS] HOST [PORT]"
  23. //usage:#define tftp_full_usage "\n\n"
  24. //usage: "Transfer a file from/to tftp server\n"
  25. //usage: "\n -l FILE Local FILE"
  26. //usage: "\n -r FILE Remote FILE"
  27. //usage: IF_FEATURE_TFTP_GET(
  28. //usage: "\n -g Get file"
  29. //usage: )
  30. //usage: IF_FEATURE_TFTP_PUT(
  31. //usage: "\n -p Put file"
  32. //usage: )
  33. //usage: IF_FEATURE_TFTP_BLOCKSIZE(
  34. //usage: "\n -b SIZE Transfer blocks of SIZE octets"
  35. //usage: )
  36. //usage:
  37. //usage:#define tftpd_trivial_usage
  38. //usage: "[-cr] [-u USER] [DIR]"
  39. //usage:#define tftpd_full_usage "\n\n"
  40. //usage: "Transfer a file on tftp client's request\n"
  41. //usage: "\n"
  42. //usage: "tftpd should be used as an inetd service.\n"
  43. //usage: "tftpd's line for inetd.conf:\n"
  44. //usage: " 69 dgram udp nowait root tftpd tftpd -l /files/to/serve\n"
  45. //usage: "It also can be ran from udpsvd:\n"
  46. //usage: " udpsvd -vE 0.0.0.0 69 tftpd /files/to/serve\n"
  47. //usage: "\n -r Prohibit upload"
  48. //usage: "\n -c Allow file creation via upload"
  49. //usage: "\n -u Access files as USER"
  50. //usage: "\n -l Log to syslog (inetd mode requires this)"
  51. #include "libbb.h"
  52. #include <syslog.h>
  53. #if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
  54. #define TFTP_BLKSIZE_DEFAULT 512 /* according to RFC 1350, don't change */
  55. #define TFTP_BLKSIZE_DEFAULT_STR "512"
  56. /* Was 50 ms but users asked to bump it up a bit */
  57. #define TFTP_TIMEOUT_MS 100
  58. #define TFTP_MAXTIMEOUT_MS 2000
  59. #define TFTP_NUM_RETRIES 12 /* number of backed-off retries */
  60. /* opcodes we support */
  61. #define TFTP_RRQ 1
  62. #define TFTP_WRQ 2
  63. #define TFTP_DATA 3
  64. #define TFTP_ACK 4
  65. #define TFTP_ERROR 5
  66. #define TFTP_OACK 6
  67. /* error codes sent over network (we use only 0, 1, 3 and 8) */
  68. /* generic (error message is included in the packet) */
  69. #define ERR_UNSPEC 0
  70. #define ERR_NOFILE 1
  71. #define ERR_ACCESS 2
  72. /* disk full or allocation exceeded */
  73. #define ERR_WRITE 3
  74. #define ERR_OP 4
  75. #define ERR_BAD_ID 5
  76. #define ERR_EXIST 6
  77. #define ERR_BAD_USER 7
  78. #define ERR_BAD_OPT 8
  79. /* masks coming from getopt32 */
  80. enum {
  81. TFTP_OPT_GET = (1 << 0),
  82. TFTP_OPT_PUT = (1 << 1),
  83. /* pseudo option: if set, it's tftpd */
  84. TFTPD_OPT = (1 << 7) * ENABLE_TFTPD,
  85. TFTPD_OPT_r = (1 << 8) * ENABLE_TFTPD,
  86. TFTPD_OPT_c = (1 << 9) * ENABLE_TFTPD,
  87. TFTPD_OPT_u = (1 << 10) * ENABLE_TFTPD,
  88. TFTPD_OPT_l = (1 << 11) * ENABLE_TFTPD,
  89. };
  90. #if ENABLE_FEATURE_TFTP_GET && !ENABLE_FEATURE_TFTP_PUT
  91. #define IF_GETPUT(...)
  92. #define CMD_GET(cmd) 1
  93. #define CMD_PUT(cmd) 0
  94. #elif !ENABLE_FEATURE_TFTP_GET && ENABLE_FEATURE_TFTP_PUT
  95. #define IF_GETPUT(...)
  96. #define CMD_GET(cmd) 0
  97. #define CMD_PUT(cmd) 1
  98. #else
  99. #define IF_GETPUT(...) __VA_ARGS__
  100. #define CMD_GET(cmd) ((cmd) & TFTP_OPT_GET)
  101. #define CMD_PUT(cmd) ((cmd) & TFTP_OPT_PUT)
  102. #endif
  103. /* NB: in the code below
  104. * CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
  105. */
  106. struct globals {
  107. /* u16 TFTP_ERROR; u16 reason; both network-endian, then error text: */
  108. uint8_t error_pkt[4 + 32];
  109. struct passwd *pw;
  110. /* Used in tftpd_main() for initial packet */
  111. /* Some HP PA-RISC firmware always sends fixed 516-byte requests */
  112. char block_buf[516];
  113. char block_buf_tail[1];
  114. #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  115. off_t pos;
  116. off_t size;
  117. const char *file;
  118. bb_progress_t pmt;
  119. #endif
  120. } FIX_ALIASING;
  121. #define G (*(struct globals*)&bb_common_bufsiz1)
  122. struct BUG_G_too_big {
  123. char BUG_G_too_big[sizeof(G) <= COMMON_BUFSIZE ? 1 : -1];
  124. };
  125. #define INIT_G() do { } while (0)
  126. #define G_error_pkt_reason (G.error_pkt[3])
  127. #define G_error_pkt_str ((char*)(G.error_pkt + 4))
  128. #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  129. static void tftp_progress_update(void)
  130. {
  131. bb_progress_update(&G.pmt, 0, G.pos, G.size);
  132. }
  133. static void tftp_progress_init(void)
  134. {
  135. bb_progress_init(&G.pmt, G.file);
  136. tftp_progress_update();
  137. }
  138. static void tftp_progress_done(void)
  139. {
  140. if (is_bb_progress_inited(&G.pmt)) {
  141. tftp_progress_update();
  142. bb_putchar_stderr('\n');
  143. bb_progress_free(&G.pmt);
  144. }
  145. }
  146. #else
  147. # define tftp_progress_init() ((void)0)
  148. # define tftp_progress_done() ((void)0)
  149. #endif
  150. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  151. static int tftp_blksize_check(const char *blksize_str, int maxsize)
  152. {
  153. /* Check if the blksize is valid:
  154. * RFC2348 says between 8 and 65464,
  155. * but our implementation makes it impossible
  156. * to use blksizes smaller than 22 octets. */
  157. unsigned blksize = bb_strtou(blksize_str, NULL, 10);
  158. if (errno
  159. || (blksize < 24) || (blksize > maxsize)
  160. ) {
  161. bb_error_msg("bad blocksize '%s'", blksize_str);
  162. return -1;
  163. }
  164. # if ENABLE_TFTP_DEBUG
  165. bb_error_msg("using blksize %u", blksize);
  166. # endif
  167. return blksize;
  168. }
  169. static char *tftp_get_option(const char *option, char *buf, int len)
  170. {
  171. int opt_val = 0;
  172. int opt_found = 0;
  173. int k;
  174. /* buf points to:
  175. * "opt_name<NUL>opt_val<NUL>opt_name2<NUL>opt_val2<NUL>..." */
  176. while (len > 0) {
  177. /* Make sure options are terminated correctly */
  178. for (k = 0; k < len; k++) {
  179. if (buf[k] == '\0') {
  180. goto nul_found;
  181. }
  182. }
  183. return NULL;
  184. nul_found:
  185. if (opt_val == 0) { /* it's "name" part */
  186. if (strcasecmp(buf, option) == 0) {
  187. opt_found = 1;
  188. }
  189. } else if (opt_found) {
  190. return buf;
  191. }
  192. k++;
  193. buf += k;
  194. len -= k;
  195. opt_val ^= 1;
  196. }
  197. return NULL;
  198. }
  199. #endif
  200. static int tftp_protocol(
  201. /* NULL if tftp, !NULL if tftpd: */
  202. len_and_sockaddr *our_lsa,
  203. len_and_sockaddr *peer_lsa,
  204. const char *local_file
  205. IF_TFTP(, const char *remote_file)
  206. #if !ENABLE_TFTP
  207. # define remote_file NULL
  208. #endif
  209. /* 1 for tftp; 1/0 for tftpd depending whether client asked about it: */
  210. IF_FEATURE_TFTP_BLOCKSIZE(, int want_transfer_size)
  211. IF_FEATURE_TFTP_BLOCKSIZE(, int blksize))
  212. {
  213. #if !ENABLE_FEATURE_TFTP_BLOCKSIZE
  214. enum { blksize = TFTP_BLKSIZE_DEFAULT };
  215. #endif
  216. struct pollfd pfd[1];
  217. #define socket_fd (pfd[0].fd)
  218. int len;
  219. int send_len;
  220. IF_FEATURE_TFTP_BLOCKSIZE(smallint expect_OACK = 0;)
  221. smallint finished = 0;
  222. uint16_t opcode;
  223. uint16_t block_nr;
  224. uint16_t recv_blk;
  225. int open_mode, local_fd;
  226. int retries, waittime_ms;
  227. int io_bufsize = blksize + 4;
  228. char *cp;
  229. /* Can't use RESERVE_CONFIG_BUFFER here since the allocation
  230. * size varies meaning BUFFERS_GO_ON_STACK would fail.
  231. *
  232. * We must keep the transmit and receive buffers separate
  233. * in case we rcv a garbage pkt - we need to rexmit the last pkt.
  234. */
  235. char *xbuf = xmalloc(io_bufsize);
  236. char *rbuf = xmalloc(io_bufsize);
  237. socket_fd = xsocket(peer_lsa->u.sa.sa_family, SOCK_DGRAM, 0);
  238. setsockopt_reuseaddr(socket_fd);
  239. if (!ENABLE_TFTP || our_lsa) { /* tftpd */
  240. /* Create a socket which is:
  241. * 1. bound to IP:port peer sent 1st datagram to,
  242. * 2. connected to peer's IP:port
  243. * This way we will answer from the IP:port peer
  244. * expects, will not get any other packets on
  245. * the socket, and also plain read/write will work. */
  246. xbind(socket_fd, &our_lsa->u.sa, our_lsa->len);
  247. xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
  248. /* Is there an error already? Send pkt and bail out */
  249. if (G_error_pkt_reason || G_error_pkt_str[0])
  250. goto send_err_pkt;
  251. if (G.pw) {
  252. change_identity(G.pw); /* initgroups, setgid, setuid */
  253. }
  254. }
  255. /* Prepare open mode */
  256. if (CMD_PUT(option_mask32)) {
  257. open_mode = O_RDONLY;
  258. } else {
  259. open_mode = O_WRONLY | O_TRUNC | O_CREAT;
  260. #if ENABLE_TFTPD
  261. if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
  262. /* tftpd without -c */
  263. open_mode = O_WRONLY | O_TRUNC;
  264. }
  265. #endif
  266. }
  267. /* Examples of network traffic.
  268. * Note two cases when ACKs with block# of 0 are sent.
  269. *
  270. * Download without options:
  271. * tftp -> "\0\1FILENAME\0octet\0"
  272. * "\0\3\0\1FILEDATA..." <- tftpd
  273. * tftp -> "\0\4\0\1"
  274. * ...
  275. * Download with option of blksize 16384:
  276. * tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
  277. * "\0\6blksize\00016384\0" <- tftpd
  278. * tftp -> "\0\4\0\0"
  279. * "\0\3\0\1FILEDATA..." <- tftpd
  280. * tftp -> "\0\4\0\1"
  281. * ...
  282. * Upload without options:
  283. * tftp -> "\0\2FILENAME\0octet\0"
  284. * "\0\4\0\0" <- tftpd
  285. * tftp -> "\0\3\0\1FILEDATA..."
  286. * "\0\4\0\1" <- tftpd
  287. * ...
  288. * Upload with option of blksize 16384:
  289. * tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
  290. * "\0\6blksize\00016384\0" <- tftpd
  291. * tftp -> "\0\3\0\1FILEDATA..."
  292. * "\0\4\0\1" <- tftpd
  293. * ...
  294. */
  295. block_nr = 1;
  296. cp = xbuf + 2;
  297. if (!ENABLE_TFTP || our_lsa) { /* tftpd */
  298. /* Open file (must be after changing user) */
  299. local_fd = open(local_file, open_mode, 0666);
  300. if (local_fd < 0) {
  301. G_error_pkt_reason = ERR_NOFILE;
  302. strcpy(G_error_pkt_str, "can't open file");
  303. goto send_err_pkt;
  304. }
  305. /* gcc 4.3.1 would NOT optimize it out as it should! */
  306. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  307. if (blksize != TFTP_BLKSIZE_DEFAULT || want_transfer_size) {
  308. /* Create and send OACK packet. */
  309. /* For the download case, block_nr is still 1 -
  310. * we expect 1st ACK from peer to be for (block_nr-1),
  311. * that is, for "block 0" which is our OACK pkt */
  312. opcode = TFTP_OACK;
  313. goto add_blksize_opt;
  314. }
  315. #endif
  316. if (CMD_GET(option_mask32)) {
  317. /* It's upload and we don't send OACK.
  318. * We must ACK 1st packet (with filename)
  319. * as if it is "block 0" */
  320. block_nr = 0;
  321. }
  322. } else { /* tftp */
  323. /* Open file (must be after changing user) */
  324. local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
  325. if (NOT_LONE_DASH(local_file))
  326. local_fd = xopen(local_file, open_mode);
  327. /* Removing #if, or using if() statement instead of #if may lead to
  328. * "warning: null argument where non-null required": */
  329. #if ENABLE_TFTP
  330. /* tftp */
  331. /* We can't (and don't really need to) bind the socket:
  332. * we don't know from which local IP datagrams will be sent,
  333. * but kernel will pick the same IP every time (unless routing
  334. * table is changed), thus peer will see dgrams consistently
  335. * coming from the same IP.
  336. * We would like to connect the socket, but since peer's
  337. * UDP code can be less perfect than ours, _peer's_ IP:port
  338. * in replies may differ from IP:port we used to send
  339. * our first packet. We can connect() only when we get
  340. * first reply. */
  341. /* build opcode */
  342. opcode = TFTP_WRQ;
  343. if (CMD_GET(option_mask32)) {
  344. opcode = TFTP_RRQ;
  345. }
  346. /* add filename and mode */
  347. /* fill in packet if the filename fits into xbuf */
  348. len = strlen(remote_file) + 1;
  349. if (2 + len + sizeof("octet") >= io_bufsize) {
  350. bb_error_msg("remote filename is too long");
  351. goto ret;
  352. }
  353. strcpy(cp, remote_file);
  354. cp += len;
  355. /* add "mode" part of the packet */
  356. strcpy(cp, "octet");
  357. cp += sizeof("octet");
  358. # if ENABLE_FEATURE_TFTP_BLOCKSIZE
  359. if (blksize == TFTP_BLKSIZE_DEFAULT && !want_transfer_size)
  360. goto send_pkt;
  361. /* Need to add option to pkt */
  362. if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN tsize ") + sizeof(off_t)*3) {
  363. bb_error_msg("remote filename is too long");
  364. goto ret;
  365. }
  366. expect_OACK = 1;
  367. # endif
  368. #endif /* ENABLE_TFTP */
  369. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  370. add_blksize_opt:
  371. if (blksize != TFTP_BLKSIZE_DEFAULT) {
  372. /* add "blksize", <nul>, blksize, <nul> */
  373. strcpy(cp, "blksize");
  374. cp += sizeof("blksize");
  375. cp += snprintf(cp, 6, "%d", blksize) + 1;
  376. }
  377. if (want_transfer_size) {
  378. /* add "tsize", <nul>, size, <nul> (see RFC2349) */
  379. /* if tftp and downloading, we send "0" (since we opened local_fd with O_TRUNC)
  380. * and this makes server to send "tsize" option with the size */
  381. /* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
  382. /* if tftpd and downloading, we are answering to client's request */
  383. /* if tftpd and uploading: !want_transfer_size, this code is not executed */
  384. struct stat st;
  385. strcpy(cp, "tsize");
  386. cp += sizeof("tsize");
  387. st.st_size = 0;
  388. fstat(local_fd, &st);
  389. cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
  390. # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  391. /* Save for progress bar. If 0 (tftp downloading),
  392. * we look at server's reply later */
  393. G.size = st.st_size;
  394. if (remote_file && st.st_size)
  395. tftp_progress_init();
  396. # endif
  397. }
  398. #endif
  399. /* First packet is built, so skip packet generation */
  400. goto send_pkt;
  401. }
  402. /* Using mostly goto's - continue/break will be less clear
  403. * in where we actually jump to */
  404. while (1) {
  405. /* Build ACK or DATA */
  406. cp = xbuf + 2;
  407. *((uint16_t*)cp) = htons(block_nr);
  408. cp += 2;
  409. block_nr++;
  410. opcode = TFTP_ACK;
  411. if (CMD_PUT(option_mask32)) {
  412. opcode = TFTP_DATA;
  413. len = full_read(local_fd, cp, blksize);
  414. if (len < 0) {
  415. goto send_read_err_pkt;
  416. }
  417. if (len != blksize) {
  418. finished = 1;
  419. }
  420. cp += len;
  421. IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
  422. }
  423. send_pkt:
  424. /* Send packet */
  425. *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
  426. send_len = cp - xbuf;
  427. /* NB: send_len value is preserved in code below
  428. * for potential resend */
  429. retries = TFTP_NUM_RETRIES; /* re-initialize */
  430. waittime_ms = TFTP_TIMEOUT_MS;
  431. send_again:
  432. #if ENABLE_TFTP_DEBUG
  433. fprintf(stderr, "sending %u bytes\n", send_len);
  434. for (cp = xbuf; cp < &xbuf[send_len]; cp++)
  435. fprintf(stderr, "%02x ", (unsigned char) *cp);
  436. fprintf(stderr, "\n");
  437. #endif
  438. xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
  439. #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  440. if (is_bb_progress_inited(&G.pmt))
  441. tftp_progress_update();
  442. #endif
  443. /* Was it final ACK? then exit */
  444. if (finished && (opcode == TFTP_ACK))
  445. goto ret;
  446. recv_again:
  447. /* Receive packet */
  448. /*pfd[0].fd = socket_fd;*/
  449. pfd[0].events = POLLIN;
  450. switch (safe_poll(pfd, 1, waittime_ms)) {
  451. default:
  452. /*bb_perror_msg("poll"); - done in safe_poll */
  453. goto ret;
  454. case 0:
  455. retries--;
  456. if (retries == 0) {
  457. tftp_progress_done();
  458. bb_error_msg("timeout");
  459. goto ret; /* no err packet sent */
  460. }
  461. /* exponential backoff with limit */
  462. waittime_ms += waittime_ms/2;
  463. if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
  464. waittime_ms = TFTP_MAXTIMEOUT_MS;
  465. }
  466. goto send_again; /* resend last sent pkt */
  467. case 1:
  468. if (!our_lsa) {
  469. /* tftp (not tftpd!) receiving 1st packet */
  470. our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
  471. len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
  472. &peer_lsa->u.sa, &peer_lsa->len);
  473. /* Our first dgram went to port 69
  474. * but reply may come from different one.
  475. * Remember and use this new port (and IP) */
  476. if (len >= 0)
  477. xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
  478. } else {
  479. /* tftpd, or not the very first packet:
  480. * socket is connect()ed, can just read from it. */
  481. /* Don't full_read()!
  482. * This is not TCP, one read == one pkt! */
  483. len = safe_read(socket_fd, rbuf, io_bufsize);
  484. }
  485. if (len < 0) {
  486. goto send_read_err_pkt;
  487. }
  488. if (len < 4) { /* too small? */
  489. goto recv_again;
  490. }
  491. }
  492. /* Process recv'ed packet */
  493. opcode = ntohs( ((uint16_t*)rbuf)[0] );
  494. recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
  495. #if ENABLE_TFTP_DEBUG
  496. fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
  497. #endif
  498. if (opcode == TFTP_ERROR) {
  499. static const char errcode_str[] ALIGN1 =
  500. "\0"
  501. "file not found\0"
  502. "access violation\0"
  503. "disk full\0"
  504. "bad operation\0"
  505. "unknown transfer id\0"
  506. "file already exists\0"
  507. "no such user\0"
  508. "bad option";
  509. const char *msg = "";
  510. if (len > 4 && rbuf[4] != '\0') {
  511. msg = &rbuf[4];
  512. rbuf[io_bufsize - 1] = '\0'; /* paranoia */
  513. } else if (recv_blk <= 8) {
  514. msg = nth_string(errcode_str, recv_blk);
  515. }
  516. bb_error_msg("server error: (%u) %s", recv_blk, msg);
  517. goto ret;
  518. }
  519. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  520. if (expect_OACK) {
  521. expect_OACK = 0;
  522. if (opcode == TFTP_OACK) {
  523. /* server seems to support options */
  524. char *res;
  525. res = tftp_get_option("blksize", &rbuf[2], len - 2);
  526. if (res) {
  527. blksize = tftp_blksize_check(res, blksize);
  528. if (blksize < 0) {
  529. G_error_pkt_reason = ERR_BAD_OPT;
  530. goto send_err_pkt;
  531. }
  532. io_bufsize = blksize + 4;
  533. }
  534. # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  535. if (remote_file && G.size == 0) { /* if we don't know it yet */
  536. res = tftp_get_option("tsize", &rbuf[2], len - 2);
  537. if (res) {
  538. G.size = bb_strtoull(res, NULL, 10);
  539. if (G.size)
  540. tftp_progress_init();
  541. }
  542. }
  543. # endif
  544. if (CMD_GET(option_mask32)) {
  545. /* We'll send ACK for OACK,
  546. * such ACK has "block no" of 0 */
  547. block_nr = 0;
  548. }
  549. continue;
  550. }
  551. /* rfc2347:
  552. * "An option not acknowledged by the server
  553. * must be ignored by the client and server
  554. * as if it were never requested." */
  555. if (blksize != TFTP_BLKSIZE_DEFAULT)
  556. bb_error_msg("falling back to blocksize "TFTP_BLKSIZE_DEFAULT_STR);
  557. blksize = TFTP_BLKSIZE_DEFAULT;
  558. io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
  559. }
  560. #endif
  561. /* block_nr is already advanced to next block# we expect
  562. * to get / block# we are about to send next time */
  563. if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
  564. if (recv_blk == block_nr) {
  565. int sz = full_write(local_fd, &rbuf[4], len - 4);
  566. if (sz != len - 4) {
  567. strcpy(G_error_pkt_str, bb_msg_write_error);
  568. G_error_pkt_reason = ERR_WRITE;
  569. goto send_err_pkt;
  570. }
  571. if (sz != blksize) {
  572. finished = 1;
  573. }
  574. IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += sz;)
  575. continue; /* send ACK */
  576. }
  577. /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
  578. #if 0
  579. if (recv_blk == (block_nr - 1)) {
  580. /* Server lost our TFTP_ACK. Resend it */
  581. block_nr = recv_blk;
  582. continue;
  583. }
  584. #endif
  585. }
  586. if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
  587. /* did peer ACK our last DATA pkt? */
  588. if (recv_blk == (uint16_t) (block_nr - 1)) {
  589. if (finished)
  590. goto ret;
  591. continue; /* send next block */
  592. }
  593. }
  594. /* Awww... recv'd packet is not recognized! */
  595. goto recv_again;
  596. /* why recv_again? - rfc1123 says:
  597. * "The sender (i.e., the side originating the DATA packets)
  598. * must never resend the current DATA packet on receipt
  599. * of a duplicate ACK".
  600. * DATA pkts are resent ONLY on timeout.
  601. * Thus "goto send_again" will ba a bad mistake above.
  602. * See:
  603. * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
  604. */
  605. } /* end of "while (1)" */
  606. ret:
  607. if (ENABLE_FEATURE_CLEAN_UP) {
  608. close(local_fd);
  609. close(socket_fd);
  610. free(xbuf);
  611. free(rbuf);
  612. }
  613. return finished == 0; /* returns 1 on failure */
  614. send_read_err_pkt:
  615. strcpy(G_error_pkt_str, bb_msg_read_error);
  616. send_err_pkt:
  617. if (G_error_pkt_str[0])
  618. bb_error_msg("%s", G_error_pkt_str);
  619. G.error_pkt[1] = TFTP_ERROR;
  620. xsendto(socket_fd, G.error_pkt, 4 + 1 + strlen(G_error_pkt_str),
  621. &peer_lsa->u.sa, peer_lsa->len);
  622. return EXIT_FAILURE;
  623. #undef remote_file
  624. }
  625. #if ENABLE_TFTP
  626. int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  627. int tftp_main(int argc UNUSED_PARAM, char **argv)
  628. {
  629. len_and_sockaddr *peer_lsa;
  630. const char *local_file = NULL;
  631. const char *remote_file = NULL;
  632. # if ENABLE_FEATURE_TFTP_BLOCKSIZE
  633. const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
  634. int blksize;
  635. # endif
  636. int result;
  637. int port;
  638. IF_GETPUT(int opt;)
  639. INIT_G();
  640. /* -p or -g is mandatory, and they are mutually exclusive */
  641. opt_complementary = "" IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
  642. IF_GETPUT("g--p:p--g:");
  643. IF_GETPUT(opt =) getopt32(argv,
  644. IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
  645. "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:"),
  646. &local_file, &remote_file
  647. IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str));
  648. argv += optind;
  649. # if ENABLE_FEATURE_TFTP_BLOCKSIZE
  650. /* Check if the blksize is valid:
  651. * RFC2348 says between 8 and 65464 */
  652. blksize = tftp_blksize_check(blksize_str, 65564);
  653. if (blksize < 0) {
  654. //bb_error_msg("bad block size");
  655. return EXIT_FAILURE;
  656. }
  657. # endif
  658. if (remote_file) {
  659. if (!local_file) {
  660. const char *slash = strrchr(remote_file, '/');
  661. local_file = slash ? slash + 1 : remote_file;
  662. }
  663. } else {
  664. remote_file = local_file;
  665. }
  666. /* Error if filename or host is not known */
  667. if (!remote_file || !argv[0])
  668. bb_show_usage();
  669. port = bb_lookup_port(argv[1], "udp", 69);
  670. peer_lsa = xhost2sockaddr(argv[0], port);
  671. # if ENABLE_TFTP_DEBUG
  672. fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
  673. xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
  674. remote_file, local_file);
  675. # endif
  676. # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  677. G.file = remote_file;
  678. # endif
  679. result = tftp_protocol(
  680. NULL /*our_lsa*/, peer_lsa,
  681. local_file, remote_file
  682. IF_FEATURE_TFTP_BLOCKSIZE(, 1 /* want_transfer_size */)
  683. IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
  684. );
  685. tftp_progress_done();
  686. if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
  687. unlink(local_file);
  688. }
  689. return result;
  690. }
  691. #endif /* ENABLE_TFTP */
  692. #if ENABLE_TFTPD
  693. int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  694. int tftpd_main(int argc UNUSED_PARAM, char **argv)
  695. {
  696. len_and_sockaddr *our_lsa;
  697. len_and_sockaddr *peer_lsa;
  698. char *local_file, *mode, *user_opt;
  699. const char *error_msg;
  700. int opt, result, opcode;
  701. IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
  702. IF_FEATURE_TFTP_BLOCKSIZE(int want_transfer_size = 0;)
  703. INIT_G();
  704. our_lsa = get_sock_lsa(STDIN_FILENO);
  705. if (!our_lsa) {
  706. /* This is confusing:
  707. *bb_error_msg_and_die("stdin is not a socket");
  708. * Better: */
  709. bb_show_usage();
  710. /* Help text says that tftpd must be used as inetd service,
  711. * which is by far the most usual cause of get_sock_lsa
  712. * failure */
  713. }
  714. peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
  715. peer_lsa->len = our_lsa->len;
  716. /* Shifting to not collide with TFTP_OPTs */
  717. opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:l", &user_opt) << 8);
  718. argv += optind;
  719. if (opt & TFTPD_OPT_l) {
  720. openlog(applet_name, LOG_PID, LOG_DAEMON);
  721. logmode = LOGMODE_SYSLOG;
  722. }
  723. if (opt & TFTPD_OPT_u) {
  724. /* Must be before xchroot */
  725. G.pw = xgetpwnam(user_opt);
  726. }
  727. if (argv[0]) {
  728. xchroot(argv[0]);
  729. }
  730. result = recv_from_to(STDIN_FILENO,
  731. G.block_buf, sizeof(G.block_buf) + 1,
  732. /* ^^^ sizeof+1 to reliably detect oversized input */
  733. 0 /* flags */,
  734. &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
  735. error_msg = "malformed packet";
  736. opcode = ntohs(*(uint16_t*)G.block_buf);
  737. if (result < 4 || result > sizeof(G.block_buf)
  738. /*|| G.block_buf[result-1] != '\0' - bug compatibility, see below */
  739. || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
  740. IF_GETPUT(&&)
  741. IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
  742. )
  743. ) {
  744. goto err;
  745. }
  746. /* Some HP PA-RISC firmware always sends fixed 516-byte requests,
  747. * with trailing garbage.
  748. * Support that by not requiring NUL to be the last byte (see above).
  749. * To make strXYZ() ops safe, force NUL termination:
  750. */
  751. G.block_buf_tail[0] = '\0';
  752. local_file = G.block_buf + 2;
  753. if (local_file[0] == '.' || strstr(local_file, "/.")) {
  754. error_msg = "dot in file name";
  755. goto err;
  756. }
  757. mode = local_file + strlen(local_file) + 1;
  758. /* RFC 1350 says mode string is case independent */
  759. if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
  760. goto err;
  761. }
  762. # if ENABLE_FEATURE_TFTP_BLOCKSIZE
  763. {
  764. char *res;
  765. char *opt_str = mode + sizeof("octet");
  766. int opt_len = G.block_buf + result - opt_str;
  767. if (opt_len > 0) {
  768. res = tftp_get_option("blksize", opt_str, opt_len);
  769. if (res) {
  770. blksize = tftp_blksize_check(res, 65564);
  771. if (blksize < 0) {
  772. G_error_pkt_reason = ERR_BAD_OPT;
  773. /* will just send error pkt */
  774. goto do_proto;
  775. }
  776. }
  777. if (opcode != TFTP_WRQ /* download? */
  778. /* did client ask us about file size? */
  779. && tftp_get_option("tsize", opt_str, opt_len)
  780. ) {
  781. want_transfer_size = 1;
  782. }
  783. }
  784. }
  785. # endif
  786. if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
  787. if (opt & TFTPD_OPT_r) {
  788. /* This would mean "disk full" - not true */
  789. /*G_error_pkt_reason = ERR_WRITE;*/
  790. error_msg = bb_msg_write_error;
  791. goto err;
  792. }
  793. IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
  794. } else {
  795. IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
  796. }
  797. /* NB: if G_error_pkt_str or G_error_pkt_reason is set up,
  798. * tftp_protocol() just sends one error pkt and returns */
  799. do_proto:
  800. close(STDIN_FILENO); /* close old, possibly wildcard socket */
  801. /* tftp_protocol() will create new one, bound to particular local IP */
  802. result = tftp_protocol(
  803. our_lsa, peer_lsa,
  804. local_file IF_TFTP(, NULL /*remote_file*/)
  805. IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
  806. IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
  807. );
  808. return result;
  809. err:
  810. strcpy(G_error_pkt_str, error_msg);
  811. goto do_proto;
  812. }
  813. #endif /* ENABLE_TFTPD */
  814. #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */