tftp.c 24 KB

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