tftp.c 27 KB

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