tftp.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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 USE_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 USE_GETPUT(...)
  65. #define CMD_GET(cmd) 0
  66. #define CMD_PUT(cmd) 1
  67. #else
  68. #define USE_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_DEBUG_TFTP
  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. USE_TFTP(, const char *remote_file)
  144. USE_FEATURE_TFTP_BLOCKSIZE(USE_TFTPD(, void *tsize))
  145. USE_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. USE_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 = getpwnam(user_opt);
  199. if (!pw)
  200. bb_error_msg_and_die("unknown user %s", user_opt);
  201. change_identity(pw); /* initgroups, setgid, setuid */
  202. }
  203. }
  204. /* Open local file (must be after changing user) */
  205. if (CMD_PUT(option_mask32)) {
  206. open_mode = O_RDONLY;
  207. } else {
  208. open_mode = O_WRONLY | O_TRUNC | O_CREAT;
  209. #if ENABLE_TFTPD
  210. if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
  211. /* tftpd without -c */
  212. open_mode = O_WRONLY | O_TRUNC;
  213. }
  214. #endif
  215. }
  216. if (!(option_mask32 & TFTPD_OPT)) {
  217. local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
  218. if (NOT_LONE_DASH(local_file))
  219. local_fd = xopen(local_file, open_mode);
  220. } else {
  221. local_fd = open(local_file, open_mode);
  222. if (local_fd < 0) {
  223. error_pkt_reason = ERR_NOFILE;
  224. strcpy((char*)error_pkt_str, "can't open file");
  225. goto send_err_pkt;
  226. }
  227. }
  228. if (!ENABLE_TFTP || our_lsa) {
  229. /* gcc 4.3.1 would NOT optimize it out as it should! */
  230. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  231. if (blksize != TFTP_BLKSIZE_DEFAULT || tsize) {
  232. /* Create and send OACK packet. */
  233. /* For the download case, block_nr is still 1 -
  234. * we expect 1st ACK from peer to be for (block_nr-1),
  235. * that is, for "block 0" which is our OACK pkt */
  236. opcode = TFTP_OACK;
  237. goto add_blksize_opt;
  238. }
  239. #endif
  240. } else {
  241. /* Removing it, or using if() statement instead of #if may lead to
  242. * "warning: null argument where non-null required": */
  243. #if ENABLE_TFTP
  244. /* tftp */
  245. /* We can't (and don't really need to) bind the socket:
  246. * we don't know from which local IP datagrams will be sent,
  247. * but kernel will pick the same IP every time (unless routing
  248. * table is changed), thus peer will see dgrams consistently
  249. * coming from the same IP.
  250. * We would like to connect the socket, but since peer's
  251. * UDP code can be less perfect than ours, _peer's_ IP:port
  252. * in replies may differ from IP:port we used to send
  253. * our first packet. We can connect() only when we get
  254. * first reply. */
  255. /* build opcode */
  256. opcode = TFTP_WRQ;
  257. if (CMD_GET(option_mask32)) {
  258. opcode = TFTP_RRQ;
  259. }
  260. /* add filename and mode */
  261. /* fill in packet if the filename fits into xbuf */
  262. len = strlen(remote_file) + 1;
  263. if (2 + len + sizeof("octet") >= io_bufsize) {
  264. bb_error_msg("remote filename is too long");
  265. goto ret;
  266. }
  267. strcpy(cp, remote_file);
  268. cp += len;
  269. /* add "mode" part of the package */
  270. strcpy(cp, "octet");
  271. cp += sizeof("octet");
  272. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  273. if (blksize == TFTP_BLKSIZE_DEFAULT)
  274. goto send_pkt;
  275. /* Non-standard blocksize: add option to pkt */
  276. if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN")) {
  277. bb_error_msg("remote filename is too long");
  278. goto ret;
  279. }
  280. want_option_ack = 1;
  281. #endif
  282. #endif /* ENABLE_TFTP */
  283. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  284. add_blksize_opt:
  285. #if ENABLE_TFTPD
  286. if (tsize) {
  287. struct stat st;
  288. /* add "tsize", <nul>, size, <nul> */
  289. strcpy(cp, "tsize");
  290. cp += sizeof("tsize");
  291. fstat(local_fd, &st);
  292. cp += snprintf(cp, 10, "%u", (int) st.st_size) + 1;
  293. }
  294. #endif
  295. if (blksize != TFTP_BLKSIZE_DEFAULT) {
  296. /* add "blksize", <nul>, blksize, <nul> */
  297. strcpy(cp, "blksize");
  298. cp += sizeof("blksize");
  299. cp += snprintf(cp, 6, "%d", blksize) + 1;
  300. }
  301. #endif
  302. /* First packet is built, so skip packet generation */
  303. goto send_pkt;
  304. }
  305. /* Using mostly goto's - continue/break will be less clear
  306. * in where we actually jump to */
  307. while (1) {
  308. /* Build ACK or DATA */
  309. cp = xbuf + 2;
  310. *((uint16_t*)cp) = htons(block_nr);
  311. cp += 2;
  312. block_nr++;
  313. opcode = TFTP_ACK;
  314. if (CMD_PUT(option_mask32)) {
  315. opcode = TFTP_DATA;
  316. len = full_read(local_fd, cp, blksize);
  317. if (len < 0) {
  318. goto send_read_err_pkt;
  319. }
  320. if (len != blksize) {
  321. finished = 1;
  322. }
  323. cp += len;
  324. }
  325. send_pkt:
  326. /* Send packet */
  327. *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
  328. send_len = cp - xbuf;
  329. /* NB: send_len value is preserved in code below
  330. * for potential resend */
  331. retries = TFTP_NUM_RETRIES; /* re-initialize */
  332. waittime_ms = TFTP_TIMEOUT_MS;
  333. send_again:
  334. #if ENABLE_DEBUG_TFTP
  335. fprintf(stderr, "sending %u bytes\n", send_len);
  336. for (cp = xbuf; cp < &xbuf[send_len]; cp++)
  337. fprintf(stderr, "%02x ", (unsigned char) *cp);
  338. fprintf(stderr, "\n");
  339. #endif
  340. xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
  341. /* Was it final ACK? then exit */
  342. if (finished && (opcode == TFTP_ACK))
  343. goto ret;
  344. recv_again:
  345. /* Receive packet */
  346. /*pfd[0].fd = socket_fd;*/
  347. pfd[0].events = POLLIN;
  348. switch (safe_poll(pfd, 1, waittime_ms)) {
  349. default:
  350. /*bb_perror_msg("poll"); - done in safe_poll */
  351. goto ret;
  352. case 0:
  353. retries--;
  354. if (retries == 0) {
  355. bb_error_msg("timeout");
  356. goto ret; /* no err packet sent */
  357. }
  358. /* exponential backoff with limit */
  359. waittime_ms += waittime_ms/2;
  360. if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
  361. waittime_ms = TFTP_MAXTIMEOUT_MS;
  362. }
  363. goto send_again; /* resend last sent pkt */
  364. case 1:
  365. if (!our_lsa) {
  366. /* tftp (not tftpd!) receiving 1st packet */
  367. our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
  368. len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
  369. &peer_lsa->u.sa, &peer_lsa->len);
  370. /* Our first dgram went to port 69
  371. * but reply may come from different one.
  372. * Remember and use this new port (and IP) */
  373. if (len >= 0)
  374. xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
  375. } else {
  376. /* tftpd, or not the very first packet:
  377. * socket is connect()ed, can just read from it. */
  378. /* Don't full_read()!
  379. * This is not TCP, one read == one pkt! */
  380. len = safe_read(socket_fd, rbuf, io_bufsize);
  381. }
  382. if (len < 0) {
  383. goto send_read_err_pkt;
  384. }
  385. if (len < 4) { /* too small? */
  386. goto recv_again;
  387. }
  388. }
  389. /* Process recv'ed packet */
  390. opcode = ntohs( ((uint16_t*)rbuf)[0] );
  391. recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
  392. #if ENABLE_DEBUG_TFTP
  393. fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
  394. #endif
  395. if (opcode == TFTP_ERROR) {
  396. static const char errcode_str[] ALIGN1 =
  397. "\0"
  398. "file not found\0"
  399. "access violation\0"
  400. "disk full\0"
  401. "bad operation\0"
  402. "unknown transfer id\0"
  403. "file already exists\0"
  404. "no such user\0"
  405. "bad option";
  406. const char *msg = "";
  407. if (len > 4 && rbuf[4] != '\0') {
  408. msg = &rbuf[4];
  409. rbuf[io_bufsize - 1] = '\0'; /* paranoia */
  410. } else if (recv_blk <= 8) {
  411. msg = nth_string(errcode_str, recv_blk);
  412. }
  413. bb_error_msg("server error: (%u) %s", recv_blk, msg);
  414. goto ret;
  415. }
  416. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  417. if (want_option_ack) {
  418. want_option_ack = 0;
  419. if (opcode == TFTP_OACK) {
  420. /* server seems to support options */
  421. char *res;
  422. res = tftp_get_option("blksize", &rbuf[2], len - 2);
  423. if (res) {
  424. blksize = tftp_blksize_check(res, blksize);
  425. if (blksize < 0) {
  426. error_pkt_reason = ERR_BAD_OPT;
  427. goto send_err_pkt;
  428. }
  429. io_bufsize = blksize + 4;
  430. /* Send ACK for OACK ("block" no: 0) */
  431. block_nr = 0;
  432. continue;
  433. }
  434. /* rfc2347:
  435. * "An option not acknowledged by the server
  436. * must be ignored by the client and server
  437. * as if it were never requested." */
  438. }
  439. bb_error_msg("server only supports blocksize of 512");
  440. blksize = TFTP_BLKSIZE_DEFAULT;
  441. io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
  442. }
  443. #endif
  444. /* block_nr is already advanced to next block# we expect
  445. * to get / block# we are about to send next time */
  446. if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
  447. if (recv_blk == block_nr) {
  448. int sz = full_write(local_fd, &rbuf[4], len - 4);
  449. if (sz != len - 4) {
  450. strcpy((char*)error_pkt_str, bb_msg_write_error);
  451. error_pkt_reason = ERR_WRITE;
  452. goto send_err_pkt;
  453. }
  454. if (sz != blksize) {
  455. finished = 1;
  456. }
  457. continue; /* send ACK */
  458. }
  459. if (recv_blk == (block_nr - 1)) {
  460. /* Server lost our TFTP_ACK. Resend it */
  461. block_nr = recv_blk;
  462. continue;
  463. }
  464. }
  465. if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
  466. /* did peer ACK our last DATA pkt? */
  467. if (recv_blk == (uint16_t) (block_nr - 1)) {
  468. if (finished)
  469. goto ret;
  470. continue; /* send next block */
  471. }
  472. }
  473. /* Awww... recv'd packet is not recognized! */
  474. goto recv_again;
  475. /* why recv_again? - rfc1123 says:
  476. * "The sender (i.e., the side originating the DATA packets)
  477. * must never resend the current DATA packet on receipt
  478. * of a duplicate ACK".
  479. * DATA pkts are resent ONLY on timeout.
  480. * Thus "goto send_again" will ba a bad mistake above.
  481. * See:
  482. * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
  483. */
  484. } /* end of "while (1)" */
  485. ret:
  486. if (ENABLE_FEATURE_CLEAN_UP) {
  487. close(local_fd);
  488. close(socket_fd);
  489. free(xbuf);
  490. free(rbuf);
  491. }
  492. return finished == 0; /* returns 1 on failure */
  493. send_read_err_pkt:
  494. strcpy((char*)error_pkt_str, bb_msg_read_error);
  495. send_err_pkt:
  496. if (error_pkt_str[0])
  497. bb_error_msg((char*)error_pkt_str);
  498. error_pkt[1] = TFTP_ERROR;
  499. xsendto(socket_fd, error_pkt, 4 + 1 + strlen((char*)error_pkt_str),
  500. &peer_lsa->u.sa, peer_lsa->len);
  501. return EXIT_FAILURE;
  502. #undef remote_file
  503. #undef tsize
  504. }
  505. #if ENABLE_TFTP
  506. int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  507. int tftp_main(int argc UNUSED_PARAM, char **argv)
  508. {
  509. len_and_sockaddr *peer_lsa;
  510. const char *local_file = NULL;
  511. const char *remote_file = NULL;
  512. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  513. const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
  514. int blksize;
  515. #endif
  516. int result;
  517. int port;
  518. USE_GETPUT(int opt;)
  519. INIT_G();
  520. /* -p or -g is mandatory, and they are mutually exclusive */
  521. opt_complementary = "" USE_FEATURE_TFTP_GET("g:") USE_FEATURE_TFTP_PUT("p:")
  522. USE_GETPUT("g--p:p--g:");
  523. USE_GETPUT(opt =) getopt32(argv,
  524. USE_FEATURE_TFTP_GET("g") USE_FEATURE_TFTP_PUT("p")
  525. "l:r:" USE_FEATURE_TFTP_BLOCKSIZE("b:"),
  526. &local_file, &remote_file
  527. USE_FEATURE_TFTP_BLOCKSIZE(, &blksize_str));
  528. argv += optind;
  529. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  530. /* Check if the blksize is valid:
  531. * RFC2348 says between 8 and 65464 */
  532. blksize = tftp_blksize_check(blksize_str, 65564);
  533. if (blksize < 0) {
  534. //bb_error_msg("bad block size");
  535. return EXIT_FAILURE;
  536. }
  537. #endif
  538. if (!local_file)
  539. local_file = remote_file;
  540. if (!remote_file)
  541. remote_file = local_file;
  542. /* Error if filename or host is not known */
  543. if (!remote_file || !argv[0])
  544. bb_show_usage();
  545. port = bb_lookup_port(argv[1], "udp", 69);
  546. peer_lsa = xhost2sockaddr(argv[0], port);
  547. #if ENABLE_DEBUG_TFTP
  548. fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
  549. xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
  550. remote_file, local_file);
  551. #endif
  552. result = tftp_protocol(
  553. NULL /*our_lsa*/, peer_lsa,
  554. local_file, remote_file
  555. USE_FEATURE_TFTP_BLOCKSIZE(USE_TFTPD(, NULL /*tsize*/))
  556. USE_FEATURE_TFTP_BLOCKSIZE(, blksize)
  557. );
  558. if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
  559. unlink(local_file);
  560. }
  561. return result;
  562. }
  563. #endif /* ENABLE_TFTP */
  564. #if ENABLE_TFTPD
  565. /* TODO: libbb candidate? */
  566. static len_and_sockaddr *get_sock_lsa(int s)
  567. {
  568. len_and_sockaddr *lsa;
  569. socklen_t len = 0;
  570. if (getsockname(s, NULL, &len) != 0)
  571. return NULL;
  572. lsa = xzalloc(LSA_LEN_SIZE + len);
  573. lsa->len = len;
  574. getsockname(s, &lsa->u.sa, &lsa->len);
  575. return lsa;
  576. }
  577. int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  578. int tftpd_main(int argc UNUSED_PARAM, char **argv)
  579. {
  580. len_and_sockaddr *our_lsa;
  581. len_and_sockaddr *peer_lsa;
  582. char *local_file, *mode;
  583. const char *error_msg;
  584. int opt, result, opcode;
  585. USE_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
  586. USE_FEATURE_TFTP_BLOCKSIZE(char *tsize = NULL;)
  587. INIT_G();
  588. our_lsa = get_sock_lsa(STDIN_FILENO);
  589. if (!our_lsa)
  590. bb_perror_msg_and_die("stdin is not a socket");
  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. || (USE_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
  606. USE_GETPUT(&&)
  607. USE_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. USE_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
  649. } else {
  650. USE_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 USE_TFTP(, NULL /*remote_file*/)
  660. USE_FEATURE_TFTP_BLOCKSIZE(, tsize)
  661. USE_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 */