3
0

tftp.c 29 KB

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