tftp.c 27 KB

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