tftp.c 29 KB

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