tftp.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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 open_mode, local_fd;
  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. /* Prepare open mode */
  329. if (CMD_PUT(option_mask32)) {
  330. open_mode = O_RDONLY;
  331. } else {
  332. open_mode = O_WRONLY | O_TRUNC | O_CREAT;
  333. #if ENABLE_TFTPD
  334. if ((option_mask32 & (TFTPD_OPT+TFTPD_OPT_c)) == TFTPD_OPT) {
  335. /* tftpd without -c */
  336. open_mode = O_WRONLY | O_TRUNC;
  337. }
  338. #endif
  339. }
  340. /* Examples of network traffic.
  341. * Note two cases when ACKs with block# of 0 are sent.
  342. *
  343. * Download without options:
  344. * tftp -> "\0\1FILENAME\0octet\0"
  345. * "\0\3\0\1FILEDATA..." <- tftpd
  346. * tftp -> "\0\4\0\1"
  347. * ...
  348. * Download with option of blksize 16384:
  349. * tftp -> "\0\1FILENAME\0octet\0blksize\00016384\0"
  350. * "\0\6blksize\00016384\0" <- tftpd
  351. * tftp -> "\0\4\0\0"
  352. * "\0\3\0\1FILEDATA..." <- tftpd
  353. * tftp -> "\0\4\0\1"
  354. * ...
  355. * Upload without options:
  356. * tftp -> "\0\2FILENAME\0octet\0"
  357. * "\0\4\0\0" <- tftpd
  358. * tftp -> "\0\3\0\1FILEDATA..."
  359. * "\0\4\0\1" <- tftpd
  360. * ...
  361. * Upload with option of blksize 16384:
  362. * tftp -> "\0\2FILENAME\0octet\0blksize\00016384\0"
  363. * "\0\6blksize\00016384\0" <- tftpd
  364. * tftp -> "\0\3\0\1FILEDATA..."
  365. * "\0\4\0\1" <- tftpd
  366. * ...
  367. */
  368. block_nr = 1;
  369. cp = xbuf + 2;
  370. if (!ENABLE_TFTP || our_lsa) { /* tftpd */
  371. /* Open file (must be after changing user) */
  372. local_fd = open(local_file, open_mode, 0666);
  373. if (local_fd < 0) {
  374. G_error_pkt_reason = ERR_NOFILE;
  375. strcpy(G_error_pkt_str, "can't open file");
  376. goto send_err_pkt;
  377. }
  378. /* gcc 4.3.1 would NOT optimize it out as it should! */
  379. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  380. if (blksize != TFTP_BLKSIZE_DEFAULT || want_transfer_size) {
  381. /* Create and send OACK packet. */
  382. /* For the download case, block_nr is still 1 -
  383. * we expect 1st ACK from peer to be for (block_nr-1),
  384. * that is, for "block 0" which is our OACK pkt */
  385. opcode = TFTP_OACK;
  386. goto add_blksize_opt;
  387. }
  388. #endif
  389. if (CMD_GET(option_mask32)) {
  390. /* It's upload and we don't send OACK.
  391. * We must ACK 1st packet (with filename)
  392. * as if it is "block 0" */
  393. block_nr = 0;
  394. }
  395. } else { /* tftp */
  396. /* Open file (must be after changing user) */
  397. local_fd = CMD_GET(option_mask32) ? STDOUT_FILENO : STDIN_FILENO;
  398. if (NOT_LONE_DASH(local_file))
  399. local_fd = xopen(local_file, open_mode);
  400. /* Removing #if, or using if() statement instead of #if may lead to
  401. * "warning: null argument where non-null required": */
  402. #if ENABLE_TFTP
  403. /* tftp */
  404. /* We can't (and don't really need to) bind the socket:
  405. * we don't know from which local IP datagrams will be sent,
  406. * but kernel will pick the same IP every time (unless routing
  407. * table is changed), thus peer will see dgrams consistently
  408. * coming from the same IP.
  409. * We would like to connect the socket, but since peer's
  410. * UDP code can be less perfect than ours, _peer's_ IP:port
  411. * in replies may differ from IP:port we used to send
  412. * our first packet. We can connect() only when we get
  413. * first reply. */
  414. /* build opcode */
  415. opcode = TFTP_WRQ;
  416. if (CMD_GET(option_mask32)) {
  417. opcode = TFTP_RRQ;
  418. }
  419. /* add filename and mode */
  420. /* fill in packet if the filename fits into xbuf */
  421. len = strlen(remote_file) + 1;
  422. if (2 + len + sizeof("octet") >= io_bufsize) {
  423. bb_error_msg("remote filename is too long");
  424. goto ret;
  425. }
  426. strcpy(cp, remote_file);
  427. cp += len;
  428. /* add "mode" part of the packet */
  429. strcpy(cp, "octet");
  430. cp += sizeof("octet");
  431. # if ENABLE_FEATURE_TFTP_BLOCKSIZE
  432. if (blksize == TFTP_BLKSIZE_DEFAULT && !want_transfer_size)
  433. goto send_pkt;
  434. /* Need to add option to pkt */
  435. if ((&xbuf[io_bufsize - 1] - cp) < sizeof("blksize NNNNN tsize ") + sizeof(off_t)*3) {
  436. bb_error_msg("remote filename is too long");
  437. goto ret;
  438. }
  439. expect_OACK = 1;
  440. # endif
  441. #endif /* ENABLE_TFTP */
  442. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  443. add_blksize_opt:
  444. if (blksize != TFTP_BLKSIZE_DEFAULT) {
  445. /* add "blksize", <nul>, blksize, <nul> */
  446. strcpy(cp, "blksize");
  447. cp += sizeof("blksize");
  448. cp += snprintf(cp, 6, "%d", blksize) + 1;
  449. }
  450. if (want_transfer_size) {
  451. /* add "tsize", <nul>, size, <nul> (see RFC2349) */
  452. /* if tftp and downloading, we send "0" (since we opened local_fd with O_TRUNC)
  453. * and this makes server to send "tsize" option with the size */
  454. /* if tftp and uploading, we send file size (maybe dont, to not confuse old servers???) */
  455. /* if tftpd and downloading, we are answering to client's request */
  456. /* if tftpd and uploading: !want_transfer_size, this code is not executed */
  457. struct stat st;
  458. strcpy(cp, "tsize");
  459. cp += sizeof("tsize");
  460. st.st_size = 0;
  461. fstat(local_fd, &st);
  462. cp += sprintf(cp, "%"OFF_FMT"u", (off_t)st.st_size) + 1;
  463. # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  464. /* Save for progress bar. If 0 (tftp downloading),
  465. * we look at server's reply later */
  466. G.size = st.st_size;
  467. if (remote_file && st.st_size)
  468. tftp_progress_init();
  469. # endif
  470. }
  471. #endif
  472. /* First packet is built, so skip packet generation */
  473. goto send_pkt;
  474. }
  475. /* Using mostly goto's - continue/break will be less clear
  476. * in where we actually jump to */
  477. while (1) {
  478. /* Build ACK or DATA */
  479. cp = xbuf + 2;
  480. *((uint16_t*)cp) = htons(block_nr);
  481. cp += 2;
  482. block_nr++;
  483. opcode = TFTP_ACK;
  484. if (CMD_PUT(option_mask32)) {
  485. opcode = TFTP_DATA;
  486. len = full_read(local_fd, cp, blksize);
  487. if (len < 0) {
  488. goto send_read_err_pkt;
  489. }
  490. if (len != blksize) {
  491. finished = 1;
  492. }
  493. cp += len;
  494. IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += len;)
  495. }
  496. send_pkt:
  497. /* Send packet */
  498. *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
  499. send_len = cp - xbuf;
  500. /* NB: send_len value is preserved in code below
  501. * for potential resend */
  502. retries = TFTP_NUM_RETRIES; /* re-initialize */
  503. waittime_ms = TFTP_TIMEOUT_MS;
  504. send_again:
  505. #if ENABLE_TFTP_DEBUG
  506. fprintf(stderr, "sending %u bytes\n", send_len);
  507. for (cp = xbuf; cp < &xbuf[send_len]; cp++)
  508. fprintf(stderr, "%02x ", (unsigned char) *cp);
  509. fprintf(stderr, "\n");
  510. #endif
  511. xsendto(socket_fd, xbuf, send_len, &peer_lsa->u.sa, peer_lsa->len);
  512. #if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  513. if (is_bb_progress_inited(&G.pmt))
  514. tftp_progress_update();
  515. #endif
  516. /* Was it final ACK? then exit */
  517. if (finished && (opcode == TFTP_ACK))
  518. goto ret;
  519. recv_again:
  520. /* Receive packet */
  521. /*pfd[0].fd = socket_fd;*/
  522. pfd[0].events = POLLIN;
  523. switch (safe_poll(pfd, 1, waittime_ms)) {
  524. default:
  525. /*bb_perror_msg("poll"); - done in safe_poll */
  526. goto ret;
  527. case 0:
  528. retries--;
  529. if (retries == 0) {
  530. tftp_progress_done();
  531. bb_error_msg("timeout");
  532. goto ret; /* no err packet sent */
  533. }
  534. /* exponential backoff with limit */
  535. waittime_ms += waittime_ms/2;
  536. if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
  537. waittime_ms = TFTP_MAXTIMEOUT_MS;
  538. }
  539. goto send_again; /* resend last sent pkt */
  540. case 1:
  541. if (!our_lsa) {
  542. /* tftp (not tftpd!) receiving 1st packet */
  543. our_lsa = ((void*)(ptrdiff_t)-1); /* not NULL */
  544. len = recvfrom(socket_fd, rbuf, io_bufsize, 0,
  545. &peer_lsa->u.sa, &peer_lsa->len);
  546. /* Our first dgram went to port 69
  547. * but reply may come from different one.
  548. * Remember and use this new port (and IP) */
  549. if (len >= 0)
  550. xconnect(socket_fd, &peer_lsa->u.sa, peer_lsa->len);
  551. } else {
  552. /* tftpd, or not the very first packet:
  553. * socket is connect()ed, can just read from it. */
  554. /* Don't full_read()!
  555. * This is not TCP, one read == one pkt! */
  556. len = safe_read(socket_fd, rbuf, io_bufsize);
  557. }
  558. if (len < 0) {
  559. goto send_read_err_pkt;
  560. }
  561. if (len < 4) { /* too small? */
  562. goto recv_again;
  563. }
  564. }
  565. /* Process recv'ed packet */
  566. opcode = ntohs( ((uint16_t*)rbuf)[0] );
  567. recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
  568. #if ENABLE_TFTP_DEBUG
  569. fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
  570. #endif
  571. if (opcode == TFTP_ERROR) {
  572. static const char errcode_str[] ALIGN1 =
  573. "\0"
  574. "file not found\0"
  575. "access violation\0"
  576. "disk full\0"
  577. "bad operation\0"
  578. "unknown transfer id\0"
  579. "file already exists\0"
  580. "no such user\0"
  581. "bad option";
  582. const char *msg = "";
  583. if (len > 4 && rbuf[4] != '\0') {
  584. msg = &rbuf[4];
  585. rbuf[io_bufsize - 1] = '\0'; /* paranoia */
  586. } else if (recv_blk <= 8) {
  587. msg = nth_string(errcode_str, recv_blk);
  588. }
  589. bb_error_msg("server error: (%u) %s", recv_blk, msg);
  590. goto ret;
  591. }
  592. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  593. if (expect_OACK) {
  594. expect_OACK = 0;
  595. if (opcode == TFTP_OACK) {
  596. /* server seems to support options */
  597. char *res;
  598. res = tftp_get_option("blksize", &rbuf[2], len - 2);
  599. if (res) {
  600. blksize = tftp_blksize_check(res, blksize);
  601. if (blksize < 0) {
  602. G_error_pkt_reason = ERR_BAD_OPT;
  603. goto send_err_pkt;
  604. }
  605. io_bufsize = blksize + 4;
  606. }
  607. # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  608. if (remote_file && G.size == 0) { /* if we don't know it yet */
  609. res = tftp_get_option("tsize", &rbuf[2], len - 2);
  610. if (res) {
  611. G.size = bb_strtoull(res, NULL, 10);
  612. if (G.size)
  613. tftp_progress_init();
  614. }
  615. }
  616. # endif
  617. if (CMD_GET(option_mask32)) {
  618. /* We'll send ACK for OACK,
  619. * such ACK has "block no" of 0 */
  620. block_nr = 0;
  621. }
  622. continue;
  623. }
  624. /* rfc2347:
  625. * "An option not acknowledged by the server
  626. * must be ignored by the client and server
  627. * as if it were never requested." */
  628. if (blksize != TFTP_BLKSIZE_DEFAULT)
  629. bb_error_msg("falling back to blocksize "TFTP_BLKSIZE_DEFAULT_STR);
  630. blksize = TFTP_BLKSIZE_DEFAULT;
  631. io_bufsize = TFTP_BLKSIZE_DEFAULT + 4;
  632. }
  633. #endif
  634. /* block_nr is already advanced to next block# we expect
  635. * to get / block# we are about to send next time */
  636. if (CMD_GET(option_mask32) && (opcode == TFTP_DATA)) {
  637. if (recv_blk == block_nr) {
  638. int sz = full_write(local_fd, &rbuf[4], len - 4);
  639. if (sz != len - 4) {
  640. strcpy(G_error_pkt_str, bb_msg_write_error);
  641. G_error_pkt_reason = ERR_WRITE;
  642. goto send_err_pkt;
  643. }
  644. if (sz != blksize) {
  645. finished = 1;
  646. }
  647. IF_FEATURE_TFTP_PROGRESS_BAR(G.pos += sz;)
  648. continue; /* send ACK */
  649. }
  650. /* Disabled to cope with servers with Sorcerer's Apprentice Syndrome */
  651. #if 0
  652. if (recv_blk == (block_nr - 1)) {
  653. /* Server lost our TFTP_ACK. Resend it */
  654. block_nr = recv_blk;
  655. continue;
  656. }
  657. #endif
  658. }
  659. if (CMD_PUT(option_mask32) && (opcode == TFTP_ACK)) {
  660. /* did peer ACK our last DATA pkt? */
  661. if (recv_blk == (uint16_t) (block_nr - 1)) {
  662. if (finished)
  663. goto ret;
  664. continue; /* send next block */
  665. }
  666. }
  667. /* Awww... recv'd packet is not recognized! */
  668. goto recv_again;
  669. /* why recv_again? - rfc1123 says:
  670. * "The sender (i.e., the side originating the DATA packets)
  671. * must never resend the current DATA packet on receipt
  672. * of a duplicate ACK".
  673. * DATA pkts are resent ONLY on timeout.
  674. * Thus "goto send_again" will ba a bad mistake above.
  675. * See:
  676. * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
  677. */
  678. } /* end of "while (1)" */
  679. ret:
  680. if (ENABLE_FEATURE_CLEAN_UP) {
  681. close(local_fd);
  682. close(socket_fd);
  683. free(xbuf);
  684. free(rbuf);
  685. }
  686. return finished == 0; /* returns 1 on failure */
  687. send_read_err_pkt:
  688. strcpy(G_error_pkt_str, bb_msg_read_error);
  689. send_err_pkt:
  690. if (G_error_pkt_str[0])
  691. bb_error_msg("%s", G_error_pkt_str);
  692. G.error_pkt[1] = TFTP_ERROR;
  693. xsendto(socket_fd, G.error_pkt, 4 + 1 + strlen(G_error_pkt_str),
  694. &peer_lsa->u.sa, peer_lsa->len);
  695. return EXIT_FAILURE;
  696. #undef remote_file
  697. }
  698. #if ENABLE_TFTP
  699. int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  700. int tftp_main(int argc UNUSED_PARAM, char **argv)
  701. {
  702. len_and_sockaddr *peer_lsa;
  703. const char *local_file = NULL;
  704. const char *remote_file = NULL;
  705. # if ENABLE_FEATURE_TFTP_BLOCKSIZE
  706. const char *blksize_str = TFTP_BLKSIZE_DEFAULT_STR;
  707. int blksize;
  708. # endif
  709. int result;
  710. int port;
  711. IF_GETPUT(int opt;)
  712. INIT_G();
  713. if (ENABLE_FEATURE_TFTP_HPA_COMPAT) {
  714. /* As of 2019, common tftp client in Linux distros
  715. * is one maintained by H. Peter Anvin:
  716. * I've seen "tftp-hpa 5.2" version.
  717. * Make the following command work:
  718. * "tftp HOST [PORT] -m binary -c get/put FILE"
  719. * by mangling it into "....... -g/-p -r FILE"
  720. * and accepting and ignoring -m STR option.
  721. */
  722. unsigned i = 1;
  723. while (argv[i]) {
  724. /* Accept not only -c, but also
  725. * -lc, -cl, -llcclcllcc etc:
  726. * "-l Literal mode (do not recognize HOST:FILE)"
  727. * since we do not recognize that syntax anyway,
  728. * might as well allow the option.
  729. */
  730. if (argv[i][0] == '-' && strchr(argv[i], 'c')
  731. /*&& argv[i][1+strspn(argv[i]+1, "lc")] == '\0'*/
  732. ) {
  733. if (!argv[++i])
  734. break;
  735. if (strcmp(argv[i], "get") == 0) {
  736. argv[i-1] = (char*)"-g";
  737. argv[i] = (char*)"-r";
  738. break;
  739. }
  740. if (strcmp(argv[i], "put") == 0) {
  741. argv[i-1] = (char*)"-p";
  742. argv[i] = (char*)"-r";
  743. break;
  744. }
  745. }
  746. i++;
  747. }
  748. }
  749. IF_GETPUT(opt =) getopt32(argv, "^"
  750. IF_FEATURE_TFTP_GET("g") IF_FEATURE_TFTP_PUT("p")
  751. "l:r:" IF_FEATURE_TFTP_BLOCKSIZE("b:")
  752. IF_FEATURE_TFTP_HPA_COMPAT("m:")
  753. "\0"
  754. /* -p or -g is mandatory, and they are mutually exclusive */
  755. IF_FEATURE_TFTP_GET("g:") IF_FEATURE_TFTP_PUT("p:")
  756. IF_GETPUT("g--p:p--g:"),
  757. &local_file, &remote_file
  758. IF_FEATURE_TFTP_BLOCKSIZE(, &blksize_str)
  759. IF_FEATURE_TFTP_HPA_COMPAT(, NULL)
  760. );
  761. argv += optind;
  762. # if ENABLE_FEATURE_TFTP_BLOCKSIZE
  763. /* Check if the blksize is valid:
  764. * RFC2348 says between 8 and 65464 */
  765. blksize = tftp_blksize_check(blksize_str, 65564);
  766. if (blksize < 0) {
  767. //bb_error_msg("bad block size");
  768. return EXIT_FAILURE;
  769. }
  770. # endif
  771. if (remote_file) {
  772. if (!local_file) {
  773. const char *slash = strrchr(remote_file, '/');
  774. local_file = slash ? slash + 1 : remote_file;
  775. }
  776. } else {
  777. remote_file = local_file;
  778. }
  779. /* Error if filename or host is not known */
  780. if (!remote_file || !argv[0])
  781. bb_show_usage();
  782. port = bb_lookup_port(argv[1], "udp", 69);
  783. peer_lsa = xhost2sockaddr(argv[0], port);
  784. # if ENABLE_TFTP_DEBUG
  785. fprintf(stderr, "using server '%s', remote_file '%s', local_file '%s'\n",
  786. xmalloc_sockaddr2dotted(&peer_lsa->u.sa),
  787. remote_file, local_file);
  788. # endif
  789. # if ENABLE_FEATURE_TFTP_PROGRESS_BAR
  790. G.file = remote_file;
  791. # endif
  792. result = tftp_protocol(
  793. NULL /*our_lsa*/, peer_lsa,
  794. local_file, remote_file
  795. IF_FEATURE_TFTP_BLOCKSIZE(, 1 /* want_transfer_size */)
  796. IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
  797. );
  798. tftp_progress_done();
  799. if (result != EXIT_SUCCESS && NOT_LONE_DASH(local_file) && CMD_GET(opt)) {
  800. unlink(local_file);
  801. }
  802. return result;
  803. }
  804. #endif /* ENABLE_TFTP */
  805. #if ENABLE_TFTPD
  806. int tftpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  807. int tftpd_main(int argc UNUSED_PARAM, char **argv)
  808. {
  809. len_and_sockaddr *our_lsa;
  810. len_and_sockaddr *peer_lsa;
  811. char *mode, *user_opt;
  812. char *local_file = local_file;
  813. const char *error_msg;
  814. int opt, result, opcode;
  815. IF_FEATURE_TFTP_BLOCKSIZE(int blksize = TFTP_BLKSIZE_DEFAULT;)
  816. IF_FEATURE_TFTP_BLOCKSIZE(int want_transfer_size = 0;)
  817. INIT_G();
  818. our_lsa = get_sock_lsa(STDIN_FILENO);
  819. if (!our_lsa) {
  820. /* This is confusing:
  821. *bb_error_msg_and_die("stdin is not a socket");
  822. * Better: */
  823. bb_show_usage();
  824. /* Help text says that tftpd must be used as inetd service,
  825. * which is by far the most usual cause of get_sock_lsa
  826. * failure */
  827. }
  828. peer_lsa = xzalloc(LSA_LEN_SIZE + our_lsa->len);
  829. peer_lsa->len = our_lsa->len;
  830. /* Shifting to not collide with TFTP_OPTs */
  831. opt = option_mask32 = TFTPD_OPT | (getopt32(argv, "rcu:l", &user_opt) << 8);
  832. argv += optind;
  833. if (opt & TFTPD_OPT_l) {
  834. openlog(applet_name, LOG_PID, LOG_DAEMON);
  835. logmode = LOGMODE_SYSLOG;
  836. }
  837. if (opt & TFTPD_OPT_u) {
  838. /* Must be before xchroot */
  839. G.pw = xgetpwnam(user_opt);
  840. }
  841. if (argv[0]) {
  842. xchroot(argv[0]);
  843. }
  844. result = recv_from_to(STDIN_FILENO,
  845. G.block_buf, sizeof(G.block_buf) + 1,
  846. /* ^^^ sizeof+1 to reliably detect oversized input */
  847. 0 /* flags */,
  848. &peer_lsa->u.sa, &our_lsa->u.sa, our_lsa->len);
  849. error_msg = "malformed packet";
  850. opcode = ntohs(*(uint16_t*)G.block_buf);
  851. if (result < 4 || result > sizeof(G.block_buf)
  852. /*|| G.block_buf[result-1] != '\0' - bug compatibility, see below */
  853. || (IF_FEATURE_TFTP_PUT(opcode != TFTP_RRQ) /* not download */
  854. IF_GETPUT(&&)
  855. IF_FEATURE_TFTP_GET(opcode != TFTP_WRQ) /* not upload */
  856. )
  857. ) {
  858. goto err;
  859. }
  860. /* Some HP PA-RISC firmware always sends fixed 516-byte requests,
  861. * with trailing garbage.
  862. * Support that by not requiring NUL to be the last byte (see above).
  863. * To make strXYZ() ops safe, force NUL termination:
  864. */
  865. G.block_buf_tail[0] = '\0';
  866. local_file = G.block_buf + 2;
  867. if (local_file[0] == '.' || strstr(local_file, "/.")) {
  868. error_msg = "dot in file name";
  869. goto err;
  870. }
  871. mode = local_file + strlen(local_file) + 1;
  872. /* RFC 1350 says mode string is case independent */
  873. if (mode >= G.block_buf + result || strcasecmp(mode, "octet") != 0) {
  874. error_msg = "mode is not 'octet'";
  875. goto err;
  876. }
  877. # if ENABLE_FEATURE_TFTP_BLOCKSIZE
  878. {
  879. char *res;
  880. char *opt_str = mode + sizeof("octet");
  881. int opt_len = G.block_buf + result - opt_str;
  882. if (opt_len > 0) {
  883. res = tftp_get_option("blksize", opt_str, opt_len);
  884. if (res) {
  885. blksize = tftp_blksize_check(res, 65564);
  886. if (blksize < 0) {
  887. G_error_pkt_reason = ERR_BAD_OPT;
  888. /* will just send error pkt */
  889. goto do_proto;
  890. }
  891. }
  892. if (opcode != TFTP_WRQ /* download? */
  893. /* did client ask us about file size? */
  894. && tftp_get_option("tsize", opt_str, opt_len)
  895. ) {
  896. want_transfer_size = 1;
  897. }
  898. }
  899. }
  900. # endif
  901. if (!ENABLE_FEATURE_TFTP_PUT || opcode == TFTP_WRQ) {
  902. if (opt & TFTPD_OPT_r) {
  903. /* This would mean "disk full" - not true */
  904. /*G_error_pkt_reason = ERR_WRITE;*/
  905. error_msg = bb_msg_write_error;
  906. goto err;
  907. }
  908. IF_GETPUT(option_mask32 |= TFTP_OPT_GET;) /* will receive file's data */
  909. } else {
  910. IF_GETPUT(option_mask32 |= TFTP_OPT_PUT;) /* will send file's data */
  911. }
  912. /* NB: if G_error_pkt_str or G_error_pkt_reason is set up,
  913. * tftp_protocol() just sends one error pkt and returns */
  914. do_proto:
  915. close(STDIN_FILENO); /* close old, possibly wildcard socket */
  916. /* tftp_protocol() will create new one, bound to particular local IP */
  917. result = tftp_protocol(
  918. our_lsa, peer_lsa,
  919. local_file
  920. IF_TFTP(, NULL /*remote_file*/)
  921. IF_FEATURE_TFTP_BLOCKSIZE(, want_transfer_size)
  922. IF_FEATURE_TFTP_BLOCKSIZE(, blksize)
  923. );
  924. return result;
  925. err:
  926. strcpy(G_error_pkt_str, error_msg);
  927. goto do_proto;
  928. }
  929. #endif /* ENABLE_TFTPD */
  930. #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */