tftp.c 23 KB

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