3
0

tftp.c 27 KB

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