tftp.c 20 KB

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