tftp.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /* vi: set sw=4 ts=4: */
  2. /* -------------------------------------------------------------------------
  3. * tftp.c
  4. *
  5. * A simple tftp client for busybox.
  6. * Tries to follow RFC1350.
  7. * Only "octet" mode supported.
  8. * Optional blocksize negotiation (RFC2347 + RFC2348)
  9. *
  10. * Copyright (C) 2001 Magnus Damm <damm@opensource.se>
  11. *
  12. * Parts of the code based on:
  13. *
  14. * atftp: Copyright (C) 2000 Jean-Pierre Lefebvre <helix@step.polymtl.ca>
  15. * and Remi Lefebvre <remi@debian.org>
  16. *
  17. * utftp: Copyright (C) 1999 Uwe Ohse <uwe@ohse.de>
  18. *
  19. * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
  20. * ------------------------------------------------------------------------- */
  21. #include "libbb.h"
  22. #if ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT
  23. #define TFTP_BLOCKSIZE_DEFAULT 512 /* according to RFC 1350, don't change */
  24. #define TFTP_TIMEOUT_MS 50
  25. #define TFTP_MAXTIMEOUT_MS 2000
  26. #define TFTP_NUM_RETRIES 12 /* number of backed-off retries */
  27. /* opcodes we support */
  28. #define TFTP_RRQ 1
  29. #define TFTP_WRQ 2
  30. #define TFTP_DATA 3
  31. #define TFTP_ACK 4
  32. #define TFTP_ERROR 5
  33. #define TFTP_OACK 6
  34. #if ENABLE_FEATURE_TFTP_GET && !ENABLE_FEATURE_TFTP_PUT
  35. #define USE_GETPUT(...)
  36. #define CMD_GET(cmd) 1
  37. #define CMD_PUT(cmd) 0
  38. #elif !ENABLE_FEATURE_TFTP_GET && ENABLE_FEATURE_TFTP_PUT
  39. #define USE_GETPUT(...)
  40. #define CMD_GET(cmd) 0
  41. #define CMD_PUT(cmd) 1
  42. #else
  43. #define USE_GETPUT(...) __VA_ARGS__
  44. /* masks coming from getpot32 */
  45. #define CMD_GET(cmd) ((cmd) & 1)
  46. #define CMD_PUT(cmd) ((cmd) & 2)
  47. #endif
  48. /* NB: in the code below
  49. * CMD_GET(cmd) and CMD_PUT(cmd) are mutually exclusive
  50. */
  51. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  52. static int tftp_blocksize_check(int blocksize, int bufsize)
  53. {
  54. /* Check if the blocksize is valid:
  55. * RFC2348 says between 8 and 65464,
  56. * but our implementation makes it impossible
  57. * to use blocksizes smaller than 22 octets.
  58. */
  59. if ((bufsize && (blocksize > bufsize))
  60. || (blocksize < 8) || (blocksize > 65564)
  61. ) {
  62. bb_error_msg("bad blocksize");
  63. return 0;
  64. }
  65. return blocksize;
  66. }
  67. static char *tftp_option_get(char *buf, int len, const char *option)
  68. {
  69. int opt_val = 0;
  70. int opt_found = 0;
  71. int k;
  72. while (len > 0) {
  73. /* Make sure the options are terminated correctly */
  74. for (k = 0; k < len; k++) {
  75. if (buf[k] == '\0') {
  76. goto nul_found;
  77. }
  78. }
  79. return NULL;
  80. nul_found:
  81. if (opt_val == 0) {
  82. if (strcasecmp(buf, option) == 0) {
  83. opt_found = 1;
  84. }
  85. } else if (opt_found) {
  86. return buf;
  87. }
  88. k++;
  89. buf += k;
  90. len -= k;
  91. opt_val ^= 1;
  92. }
  93. return NULL;
  94. }
  95. #endif
  96. static int tftp( USE_GETPUT(const int cmd,)
  97. len_and_sockaddr *peer_lsa,
  98. const char *remotefile, const int localfd,
  99. unsigned port, int tftp_bufsize)
  100. {
  101. struct pollfd pfd[1];
  102. #define socketfd (pfd[0].fd)
  103. int len;
  104. int send_len;
  105. USE_FEATURE_TFTP_BLOCKSIZE(smallint want_option_ack = 0;)
  106. smallint finished = 0;
  107. uint16_t opcode;
  108. uint16_t block_nr = 1;
  109. uint16_t recv_blk;
  110. int retries, waittime_ms;
  111. char *cp;
  112. unsigned org_port;
  113. len_and_sockaddr *const from = alloca(offsetof(len_and_sockaddr, sa) + peer_lsa->len);
  114. /* Can't use RESERVE_CONFIG_BUFFER here since the allocation
  115. * size varies meaning BUFFERS_GO_ON_STACK would fail */
  116. /* We must keep the transmit and receive buffers seperate */
  117. /* In case we rcv a garbage pkt and we need to rexmit the last pkt */
  118. char *xbuf = xmalloc(tftp_bufsize += 4);
  119. char *rbuf = xmalloc(tftp_bufsize);
  120. port = org_port = htons(port);
  121. socketfd = xsocket(peer_lsa->sa.sa_family, SOCK_DGRAM, 0);
  122. /* build opcode */
  123. opcode = TFTP_WRQ;
  124. if (CMD_GET(cmd)) {
  125. opcode = TFTP_RRQ;
  126. }
  127. cp = xbuf + 2;
  128. /* add filename and mode */
  129. /* fill in packet if the filename fits into xbuf */
  130. len = strlen(remotefile) + 1;
  131. if (2 + len + sizeof("octet") >= tftp_bufsize) {
  132. bb_error_msg("remote filename is too long");
  133. goto ret;
  134. }
  135. strcpy(cp, remotefile);
  136. cp += len;
  137. /* add "mode" part of the package */
  138. strcpy(cp, "octet");
  139. cp += sizeof("octet");
  140. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  141. len = tftp_bufsize - 4; /* data block size */
  142. if (len != TFTP_BLOCKSIZE_DEFAULT) {
  143. /* rfc2348 says that 65464 is a max allowed value */
  144. if ((&xbuf[tftp_bufsize - 1] - cp) < sizeof("blksize NNNNN")) {
  145. bb_error_msg("remote filename is too long");
  146. goto ret;
  147. }
  148. /* add "blksize", <nul>, blocksize */
  149. strcpy(cp, "blksize");
  150. cp += sizeof("blksize");
  151. cp += snprintf(cp, 6, "%d", len) + 1;
  152. want_option_ack = 1;
  153. }
  154. #endif
  155. /* First packet is built, so skip packet generation */
  156. goto send_pkt;
  157. /* Using mostly goto's - continue/break will be less clear
  158. * in where we actually jump to */
  159. while (1) {
  160. /* Build ACK or DATA */
  161. cp = xbuf + 2;
  162. *((uint16_t*)cp) = htons(block_nr);
  163. cp += 2;
  164. block_nr++;
  165. opcode = TFTP_ACK;
  166. if (CMD_PUT(cmd)) {
  167. opcode = TFTP_DATA;
  168. len = full_read(localfd, cp, tftp_bufsize - 4);
  169. if (len < 0) {
  170. bb_perror_msg(bb_msg_read_error);
  171. goto ret;
  172. }
  173. if (len != (tftp_bufsize - 4)) {
  174. finished = 1;
  175. }
  176. cp += len;
  177. }
  178. send_pkt:
  179. /* Send packet */
  180. *((uint16_t*)xbuf) = htons(opcode); /* fill in opcode part */
  181. send_len = cp - xbuf;
  182. /* NB: send_len value is preserved in code below
  183. * for potential resend */
  184. retries = TFTP_NUM_RETRIES; /* re-initialize */
  185. waittime_ms = TFTP_TIMEOUT_MS;
  186. send_again:
  187. #if ENABLE_DEBUG_TFTP
  188. fprintf(stderr, "sending %u bytes\n", send_len);
  189. for (cp = xbuf; cp < &xbuf[send_len]; cp++)
  190. fprintf(stderr, "%02x ", (unsigned char) *cp);
  191. fprintf(stderr, "\n");
  192. #endif
  193. xsendto(socketfd, xbuf, send_len, &peer_lsa->sa, peer_lsa->len);
  194. /* Was it final ACK? then exit */
  195. if (finished && (opcode == TFTP_ACK))
  196. goto ret;
  197. recv_again:
  198. /* Receive packet */
  199. /*pfd[0].fd = socketfd;*/
  200. pfd[0].events = POLLIN;
  201. switch (safe_poll(pfd, 1, waittime_ms)) {
  202. unsigned from_port;
  203. case 1:
  204. from->len = peer_lsa->len;
  205. memset(&from->sa, 0, peer_lsa->len);
  206. len = recvfrom(socketfd, rbuf, tftp_bufsize, 0,
  207. &from->sa, &from->len);
  208. if (len < 0) {
  209. bb_perror_msg("recvfrom");
  210. goto ret;
  211. }
  212. from_port = get_nport(&from->sa);
  213. if (port == org_port) {
  214. /* Our first query went to port 69
  215. * but reply will come from different one.
  216. * Remember and use this new port */
  217. port = from_port;
  218. set_nport(peer_lsa, from_port);
  219. }
  220. if (port != from_port)
  221. goto recv_again;
  222. goto process_pkt;
  223. case 0:
  224. retries--;
  225. if (retries == 0) {
  226. bb_error_msg("timeout");
  227. goto ret;
  228. }
  229. /* exponential backoff with limit */
  230. waittime_ms += waittime_ms/2;
  231. if (waittime_ms > TFTP_MAXTIMEOUT_MS) {
  232. waittime_ms = TFTP_MAXTIMEOUT_MS;
  233. }
  234. goto send_again; /* resend last sent pkt */
  235. default:
  236. /*bb_perror_msg("poll"); - done in safe_poll */
  237. goto ret;
  238. }
  239. process_pkt:
  240. /* Process recv'ed packet */
  241. opcode = ntohs( ((uint16_t*)rbuf)[0] );
  242. recv_blk = ntohs( ((uint16_t*)rbuf)[1] );
  243. #if ENABLE_DEBUG_TFTP
  244. fprintf(stderr, "received %d bytes: %04x %04x\n", len, opcode, recv_blk);
  245. #endif
  246. if (opcode == TFTP_ERROR) {
  247. static const char *const errcode_str[] = {
  248. "",
  249. "file not found",
  250. "access violation",
  251. "disk full",
  252. "illegal TFTP operation",
  253. "unknown transfer id",
  254. "file already exists",
  255. "no such user",
  256. "bad option"
  257. };
  258. const char *msg = "";
  259. if (rbuf[4] != '\0') {
  260. msg = &rbuf[4];
  261. rbuf[tftp_bufsize - 1] = '\0';
  262. } else if (recv_blk < ARRAY_SIZE(errcode_str)) {
  263. msg = errcode_str[recv_blk];
  264. }
  265. bb_error_msg("server error: (%u) %s", recv_blk, msg);
  266. goto ret;
  267. }
  268. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  269. if (want_option_ack) {
  270. want_option_ack = 0;
  271. if (opcode == TFTP_OACK) {
  272. /* server seems to support options */
  273. char *res;
  274. res = tftp_option_get(&rbuf[2], len - 2, "blksize");
  275. if (res) {
  276. int blksize = xatoi_u(res);
  277. if (!tftp_blocksize_check(blksize, tftp_bufsize - 4)) {
  278. /* send ERROR 8 to server... */
  279. /* htons can be impossible to use in const initializer: */
  280. /*static const uint16_t error_8[2] = { htons(TFTP_ERROR), htons(8) };*/
  281. /* thus we open-code big-endian layout */
  282. static const uint8_t error_8[4] = { 0,TFTP_ERROR, 0,8 };
  283. xsendto(socketfd, error_8, 4, &peer_lsa->sa, peer_lsa->len);
  284. bb_error_msg("server proposes bad blksize %d, exiting", blksize);
  285. goto ret;
  286. }
  287. #if ENABLE_DEBUG_TFTP
  288. fprintf(stderr, "using blksize %u\n",
  289. blksize);
  290. #endif
  291. tftp_bufsize = blksize + 4;
  292. /* Send ACK for OACK ("block" no: 0) */
  293. block_nr = 0;
  294. continue;
  295. }
  296. /* rfc2347:
  297. * "An option not acknowledged by the server
  298. * must be ignored by the client and server
  299. * as if it were never requested." */
  300. }
  301. bb_error_msg("blksize is not supported by server"
  302. " - reverting to 512");
  303. tftp_bufsize = TFTP_BLOCKSIZE_DEFAULT + 4;
  304. }
  305. #endif
  306. /* block_nr is already advanced to next block# we expect
  307. * to get / block# we are about to send next time */
  308. if (CMD_GET(cmd) && (opcode == TFTP_DATA)) {
  309. if (recv_blk == block_nr) {
  310. len = full_write(localfd, &rbuf[4], len - 4);
  311. if (len < 0) {
  312. bb_perror_msg(bb_msg_write_error);
  313. goto ret;
  314. }
  315. if (len != (tftp_bufsize - 4)) {
  316. finished = 1;
  317. }
  318. continue; /* send ACK */
  319. }
  320. if (recv_blk == (block_nr - 1)) {
  321. /* Server lost our TFTP_ACK. Resend it */
  322. block_nr = recv_blk;
  323. continue;
  324. }
  325. }
  326. if (CMD_PUT(cmd) && (opcode == TFTP_ACK)) {
  327. /* did server ACK our last DATA pkt? */
  328. if (recv_blk == (uint16_t) (block_nr - 1)) {
  329. if (finished)
  330. goto ret;
  331. continue; /* send next block */
  332. }
  333. }
  334. /* Awww... recv'd packet is not recognized! */
  335. goto recv_again;
  336. /* why recv_again? - rfc1123 says:
  337. * "The sender (i.e., the side originating the DATA packets)
  338. * must never resend the current DATA packet on receipt
  339. * of a duplicate ACK".
  340. * DATA pkts are resent ONLY on timeout.
  341. * Thus "goto send_again" will ba a bad mistake above.
  342. * See:
  343. * http://en.wikipedia.org/wiki/Sorcerer's_Apprentice_Syndrome
  344. */
  345. }
  346. ret:
  347. if (ENABLE_FEATURE_CLEAN_UP) {
  348. close(socketfd);
  349. free(xbuf);
  350. free(rbuf);
  351. }
  352. return finished == 0; /* returns 1 on failure */
  353. }
  354. int tftp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  355. int tftp_main(int argc, char **argv)
  356. {
  357. len_and_sockaddr *peer_lsa;
  358. const char *localfile = NULL;
  359. const char *remotefile = NULL;
  360. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  361. const char *sblocksize = NULL;
  362. #endif
  363. int port;
  364. USE_GETPUT(int cmd;)
  365. int fd = -1;
  366. int flags = 0;
  367. int result;
  368. int blocksize = TFTP_BLOCKSIZE_DEFAULT;
  369. /* -p or -g is mandatory, and they are mutually exclusive */
  370. opt_complementary = "" USE_FEATURE_TFTP_GET("g:") USE_FEATURE_TFTP_PUT("p:")
  371. USE_GETPUT("?g--p:p--g");
  372. USE_GETPUT(cmd =) getopt32(argv,
  373. USE_FEATURE_TFTP_GET("g") USE_FEATURE_TFTP_PUT("p")
  374. "l:r:" USE_FEATURE_TFTP_BLOCKSIZE("b:"),
  375. &localfile, &remotefile
  376. USE_FEATURE_TFTP_BLOCKSIZE(, &sblocksize));
  377. argv += optind;
  378. flags = O_RDONLY;
  379. if (CMD_GET(cmd))
  380. flags = O_WRONLY | O_CREAT | O_TRUNC;
  381. #if ENABLE_FEATURE_TFTP_BLOCKSIZE
  382. if (sblocksize) {
  383. blocksize = xatoi_u(sblocksize);
  384. if (!tftp_blocksize_check(blocksize, 0)) {
  385. return EXIT_FAILURE;
  386. }
  387. }
  388. #endif
  389. if (!localfile)
  390. localfile = remotefile;
  391. if (!remotefile)
  392. remotefile = localfile;
  393. /* Error if filename or host is not known */
  394. if (!remotefile || !argv[0])
  395. bb_show_usage();
  396. fd = CMD_GET(cmd) ? STDOUT_FILENO : STDIN_FILENO;
  397. if (!LONE_DASH(localfile)) {
  398. fd = xopen(localfile, flags);
  399. }
  400. port = bb_lookup_port(argv[1], "udp", 69);
  401. peer_lsa = xhost2sockaddr(argv[0], port);
  402. #if ENABLE_DEBUG_TFTP
  403. fprintf(stderr, "using server '%s', remotefile '%s', localfile '%s'\n",
  404. xmalloc_sockaddr2dotted(&peer_lsa->sa),
  405. remotefile, localfile);
  406. #endif
  407. result = tftp( USE_GETPUT(cmd,) peer_lsa, remotefile, fd, port, blocksize);
  408. if (ENABLE_FEATURE_CLEAN_UP)
  409. close(fd);
  410. if (result != EXIT_SUCCESS && !LONE_DASH(localfile) && CMD_GET(cmd)) {
  411. unlink(localfile);
  412. }
  413. return result;
  414. }
  415. #endif /* ENABLE_FEATURE_TFTP_GET || ENABLE_FEATURE_TFTP_PUT */