tftp.c 23 KB

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