3
0

tftp.c 19 KB

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