tftp.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /**
  2. * nmrpflash - Netgear Unbrick Utility
  3. * Copyright (C) 2016 Joseph Lehner <joseph.c.lehner@gmail.com>
  4. *
  5. * nmrpflash is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * nmrpflash is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with nmrpflash. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. #include <string.h>
  20. #include <unistd.h>
  21. #include <stdlib.h>
  22. #include <stdio.h>
  23. #include <errno.h>
  24. #include <fcntl.h>
  25. #include <ctype.h>
  26. #include "nmrpd.h"
  27. #ifndef O_BINARY
  28. #define O_BINARY 0
  29. #endif
  30. #define TFTP_BLKSIZE 1456
  31. static const char *opcode_names[] = {
  32. "RRQ", "WRQ", "DATA", "ACK", "ERR", "OACK"
  33. };
  34. enum tftp_opcode {
  35. RRQ = 1,
  36. WRQ = 2,
  37. DATA = 3,
  38. ACK = 4,
  39. ERR = 5,
  40. OACK = 6
  41. };
  42. static bool is_netascii(const char *str)
  43. {
  44. uint8_t *p = (uint8_t*)str;
  45. for (; *p; ++p) {
  46. if (*p < 0x20 || *p > 0x7f) {
  47. return false;
  48. }
  49. }
  50. return true;
  51. }
  52. static inline char *pkt_mknum(char *pkt, uint16_t n)
  53. {
  54. *(uint16_t*)pkt = htons(n);
  55. return pkt + 2;
  56. }
  57. static inline uint16_t pkt_num(char *pkt)
  58. {
  59. return ntohs(*(uint16_t*)pkt);
  60. }
  61. static char *pkt_mkopt(char *pkt, const char *opt, const char* val)
  62. {
  63. strcpy(pkt, opt);
  64. pkt += strlen(opt) + 1;
  65. strcpy(pkt, val);
  66. pkt += strlen(val) + 1;
  67. return pkt;
  68. }
  69. static bool pkt_nextstr(char **pkt, char **str, size_t *rem)
  70. {
  71. size_t len;
  72. if (!isprint(**pkt) || !(len = strnlen(*pkt, *rem))) {
  73. return false;
  74. } else if (str) {
  75. *str = *pkt;
  76. }
  77. *pkt += len + 1;
  78. if (*rem > 1) {
  79. *rem -= len + 1;
  80. } else {
  81. *rem = 0;
  82. }
  83. return true;
  84. }
  85. static bool pkt_nextopt(char **pkt, char **opt, char **val, size_t *rem)
  86. {
  87. return pkt_nextstr(pkt, opt, rem) && pkt_nextstr(pkt, val, rem);
  88. }
  89. static char *pkt_optval(char* pkt, const char* name)
  90. {
  91. size_t rem = 512;
  92. char *opt, *val;
  93. pkt += 2;
  94. while (pkt_nextopt(&pkt, &opt, &val, &rem)) {
  95. if (!strcasecmp(name, opt)) {
  96. return val;
  97. }
  98. }
  99. return NULL;
  100. }
  101. static size_t pkt_xrqlen(char *pkt)
  102. {
  103. size_t rem = 512;
  104. pkt += 2;
  105. while (pkt_nextopt(&pkt, NULL, NULL, &rem)) {
  106. ;
  107. }
  108. return 514 - rem;
  109. }
  110. static void pkt_mkwrq(char *pkt, const char *filename, unsigned blksize)
  111. {
  112. filename = leafname(filename);
  113. if (!tftp_is_valid_filename(filename)) {
  114. fprintf(stderr, "Overlong/illegal filename; using 'firmware'.\n");
  115. filename = "firmware";
  116. } else if (!strcmp(filename, "-")) {
  117. filename = "firmware";
  118. }
  119. pkt = pkt_mknum(pkt, WRQ);
  120. pkt = pkt_mkopt(pkt, filename, "octet");
  121. if (blksize && blksize != 512) {
  122. pkt = pkt_mkopt(pkt, "blksize", lltostr(blksize, 10));
  123. }
  124. }
  125. static inline void pkt_print(char *pkt, FILE *fp)
  126. {
  127. uint16_t opcode = pkt_num(pkt);
  128. size_t rem;
  129. char *opt, *val;
  130. if (!opcode || opcode > OACK) {
  131. fprintf(fp, "(%d)", opcode);
  132. } else {
  133. fprintf(fp, "%s", opcode_names[opcode - 1]);
  134. if (opcode == ACK || opcode == DATA) {
  135. fprintf(fp, "(%d)", pkt_num(pkt + 2));
  136. } else if (opcode == WRQ || opcode == RRQ) {
  137. fprintf(fp, "(%s, %s)", pkt + 2, pkt + 2 + strlen(pkt + 2) + 1);
  138. } else if (opcode == OACK) {
  139. fprintf(fp, "(");
  140. rem = 512;
  141. pkt += 2;
  142. while (pkt_nextopt(&pkt, &opt, &val, &rem)) {
  143. fprintf(fp, " %s=%s ", opt, val);
  144. }
  145. fprintf(fp, ")");
  146. }
  147. }
  148. }
  149. static ssize_t tftp_recvfrom(int sock, char *pkt, uint16_t* port,
  150. unsigned timeout, size_t pktlen)
  151. {
  152. ssize_t len;
  153. struct sockaddr_in src;
  154. #ifndef NMRPFLASH_WINDOWS
  155. socklen_t alen;
  156. #else
  157. int alen;
  158. #endif
  159. len = select_fd(sock, timeout);
  160. if (len < 0) {
  161. return -1;
  162. } else if (!len) {
  163. return 0;
  164. }
  165. #ifndef NMRPFLASH_FUZZ
  166. alen = sizeof(src);
  167. len = recvfrom(sock, pkt, pktlen, 0, (struct sockaddr*)&src, &alen);
  168. if (len < 0) {
  169. sock_perror("recvfrom");
  170. return -1;
  171. }
  172. #else
  173. len = read(sock, pkt, pktlen);
  174. if (len < 0) {
  175. perror("read");
  176. return -1;
  177. }
  178. #endif
  179. *port = ntohs(src.sin_port);
  180. uint16_t opcode = pkt_num(pkt);
  181. if (opcode == ERR) {
  182. fprintf(stderr, "Error (%d): %.511s\n", pkt_num(pkt + 2), pkt + 4);
  183. return -1;
  184. } else if (isprint(pkt[0])) {
  185. /* In case of a firmware checksum error, the EX2700 I've tested this
  186. * on sends a raw UDP packet containing just an error message starting
  187. * at offset 0. The limit of 32 chars is arbitrary.
  188. */
  189. fprintf(stderr, "Error: %.32s\n", pkt);
  190. return -2;
  191. } else if (!opcode || opcode > OACK) {
  192. fprintf(stderr, "Received invalid packet: ");
  193. pkt_print(pkt, stderr);
  194. fprintf(stderr, ".\n");
  195. return -1;
  196. }
  197. if (verbosity > 2) {
  198. printf(">> ");
  199. pkt_print(pkt, stdout);
  200. printf("\n");
  201. }
  202. return len;
  203. }
  204. static ssize_t tftp_sendto(int sock, char *pkt, size_t len,
  205. struct sockaddr_in *dst)
  206. {
  207. ssize_t sent;
  208. switch (pkt_num(pkt)) {
  209. case RRQ:
  210. case WRQ:
  211. case OACK:
  212. len = pkt_xrqlen(pkt);
  213. break;
  214. case DATA:
  215. len += 4;
  216. break;
  217. case ACK:
  218. len = 4;
  219. break;
  220. case ERR:
  221. len = 4 + strlen(pkt + 4);
  222. break;
  223. default:
  224. fprintf(stderr, "Attempted to send invalid packet ");
  225. pkt_print(pkt, stderr);
  226. fprintf(stderr, "; this is a bug!\n");
  227. return -1;
  228. }
  229. if (verbosity > 2) {
  230. printf("<< ");
  231. pkt_print(pkt, stdout);
  232. printf("\n");
  233. }
  234. #ifndef NMRPFLASH_FUZZ
  235. sent = sendto(sock, pkt, len, 0, (struct sockaddr*)dst, sizeof(*dst));
  236. if (sent < 0) {
  237. sock_perror("sendto");
  238. }
  239. #else
  240. sent = len;
  241. #endif
  242. return sent;
  243. }
  244. const char *leafname(const char *path)
  245. {
  246. if (!path) {
  247. return NULL;
  248. }
  249. const char *slash, *bslash;
  250. slash = strrchr(path, '/');
  251. bslash = strrchr(path, '\\');
  252. if (slash && bslash) {
  253. path = 1 + (slash > bslash ? slash : bslash);
  254. } else if (slash) {
  255. path = 1 + slash;
  256. } else if (bslash) {
  257. path = 1 + bslash;
  258. }
  259. return path;
  260. }
  261. #ifdef NMRPFLASH_WINDOWS
  262. void sock_perror(const char *msg)
  263. {
  264. win_perror2(msg, WSAGetLastError());
  265. }
  266. #endif
  267. inline bool tftp_is_valid_filename(const char *filename)
  268. {
  269. return strlen(filename) <= 255 && is_netascii(filename);
  270. }
  271. static const char *spinner = "\\|/-";
  272. ssize_t tftp_put(struct nmrpd_args *args)
  273. {
  274. struct sockaddr_in addr;
  275. uint16_t block, port, op, blksize;
  276. ssize_t len, last_len, bytes;
  277. int fd, sock, ret, timeouts, errors, ackblock;
  278. char rx[2048], tx[2048];
  279. const char *file_remote = args->file_remote;
  280. char *val, *end;
  281. bool rollover;
  282. const unsigned rx_timeout = MAX(args->rx_timeout / 50, 200);
  283. const unsigned max_timeouts = args->blind ? 3 : 5;
  284. #ifndef NMRPFLASH_WINDOWS
  285. int enabled = 1;
  286. #else
  287. char enabled = TRUE;
  288. #endif
  289. sock = -1;
  290. ret = -1;
  291. fd = -1;
  292. if (g_interrupted) {
  293. goto cleanup;
  294. }
  295. if (!strcmp(args->file_local, "-")) {
  296. fd = STDIN_FILENO;
  297. if (!file_remote) {
  298. file_remote = "firmware";
  299. }
  300. } else {
  301. fd = open(args->file_local, O_RDONLY | O_BINARY);
  302. if (fd < 0) {
  303. xperror("open");
  304. goto cleanup;
  305. } else if (!file_remote) {
  306. file_remote = args->file_local;
  307. }
  308. if (lseek(fd, args->offset, SEEK_SET) == (off_t)-1) {
  309. xperror("lseek");
  310. goto cleanup;
  311. }
  312. }
  313. #ifndef NMRPFLASH_FUZZ_TFTP
  314. sock = socket(AF_INET, SOCK_DGRAM, 0);
  315. if (sock < 0) {
  316. sock_perror("socket");
  317. goto cleanup;
  318. }
  319. if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &enabled, sizeof(enabled)) != 0) {
  320. sock_perror("setsockopt");
  321. goto cleanup;
  322. }
  323. #else
  324. sock = STDIN_FILENO;
  325. #endif
  326. memset(&addr, 0, sizeof(addr));
  327. addr.sin_family = AF_INET;
  328. // check if we have an interface address, and bind to it if we do
  329. if (args->ipaddr_intf) {
  330. addr.sin_addr.s_addr = inet_addr(args->ipaddr_intf);
  331. if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr_intf)) == INADDR_NONE) {
  332. xperror("inet_addr");
  333. goto cleanup;
  334. }
  335. if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0) {
  336. sock_perror("bind");
  337. goto cleanup;
  338. }
  339. }
  340. if ((addr.sin_addr.s_addr = inet_addr(args->ipaddr)) == INADDR_NONE) {
  341. xperror("inet_addr");
  342. goto cleanup;
  343. }
  344. addr.sin_port = htons(args->port);
  345. blksize = 512;
  346. block = 0;
  347. last_len = -1;
  348. len = 0;
  349. bytes = 0;
  350. errors = 0;
  351. rollover = false;
  352. /* Not really, but this way the loop sends our WRQ before receiving */
  353. timeouts = 1;
  354. pkt_mkwrq(tx, file_remote, TFTP_BLKSIZE);
  355. while (!g_interrupted) {
  356. ackblock = -1;
  357. op = pkt_num(rx);
  358. if (!timeouts) {
  359. if (op == ACK) {
  360. ackblock = pkt_num(rx + 2);
  361. } else if (op == OACK) {
  362. ackblock = 0;
  363. if ((val = pkt_optval(rx, "blksize"))) {
  364. blksize = strtol(val, &end, 10);
  365. if (*end != '\0' || blksize < 8 || blksize > TFTP_BLKSIZE) {
  366. fprintf(stderr, "Error: invalid blksize in OACK: %s\n", val);
  367. ret = -1;
  368. goto cleanup;
  369. }
  370. if (verbosity) {
  371. printf("Remote accepted blksize option: %d b\n", blksize);
  372. }
  373. }
  374. }
  375. }
  376. if (timeouts || ackblock == block) {
  377. if (!timeouts) {
  378. if (++block == 0) {
  379. if (!rollover) {
  380. printf("Warning: TFTP block rollover. Upload might fail!\n");
  381. rollover = true;
  382. }
  383. }
  384. printf("%c ", spinner[block & 3]);
  385. fflush(stdout);
  386. printf("\b\b");
  387. pkt_mknum(tx, DATA);
  388. pkt_mknum(tx + 2, block);
  389. len = read(fd, tx + 4, blksize);
  390. if (len < 0) {
  391. xperror("read");
  392. ret = len;
  393. goto cleanup;
  394. } else if (!len) {
  395. if (last_len != blksize && last_len != -1) {
  396. break;
  397. }
  398. }
  399. last_len = len;
  400. bytes += len;
  401. }
  402. ret = tftp_sendto(sock, tx, len, &addr);
  403. if (ret < 0) {
  404. goto cleanup;
  405. }
  406. } else if ((op != OACK && op != ACK) || ackblock > block) {
  407. if (verbosity) {
  408. fprintf(stderr, "Expected ACK(%d), got ", block);
  409. pkt_print(rx, stderr);
  410. fprintf(stderr, ".\n");
  411. }
  412. if (ackblock != -1 && ++errors > 5) {
  413. fprintf(stderr, "Protocol error; bailing out.\n");
  414. ret = -1;
  415. goto cleanup;
  416. }
  417. }
  418. ret = tftp_recvfrom(sock, rx, &port, rx_timeout, blksize + 4);
  419. nmrp_discard(args->sock);
  420. if (ret < 0) {
  421. goto cleanup;
  422. } else if (!ret) {
  423. if (++timeouts < max_timeouts || (!block && timeouts < (max_timeouts * 4))) {
  424. continue;
  425. } else if (args->blind) {
  426. timeouts = 0;
  427. // fake an ACK packet
  428. pkt_mknum(rx, ACK);
  429. pkt_mknum(rx + 2, block);
  430. continue;
  431. } else if (block) {
  432. fprintf(stderr, "Timeout while waiting for ACK(%d).\n", block);
  433. } else {
  434. fprintf(stderr, "Timeout while waiting for ACK(0)/OACK.\n");
  435. }
  436. ret = -1;
  437. goto cleanup;
  438. } else {
  439. timeouts = 0;
  440. ret = 0;
  441. if (!block && port != args->port) {
  442. if (verbosity > 1) {
  443. printf("Switching to port %d\n", port);
  444. }
  445. addr.sin_port = htons(port);
  446. }
  447. }
  448. }
  449. ret = !g_interrupted ? 0 : -1;
  450. cleanup:
  451. if (fd >= 0) {
  452. close(fd);
  453. }
  454. if (sock >= 0) {
  455. #ifndef NMRPFLASH_WINDOWS
  456. shutdown(sock, SHUT_RDWR);
  457. close(sock);
  458. #else
  459. shutdown(sock, SD_BOTH);
  460. closesocket(sock);
  461. #endif
  462. }
  463. return (ret == 0) ? bytes : ret;
  464. }