tftpd.c 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. *
  9. * Trivial file transfer protocol server.
  10. *
  11. * This code includes many modifications by Jim Guyton <guyton@rand-unix>
  12. *
  13. * This source file was started based on netkit-tftpd 0.17
  14. * Heavily modified for curl's test suite
  15. */
  16. /*
  17. * Copyright (C) 2005 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
  18. * Copyright (c) 1983, Regents of the University of California.
  19. * All rights reserved.
  20. *
  21. * Redistribution and use in source and binary forms, with or without
  22. * modification, are permitted provided that the following conditions
  23. * are met:
  24. * 1. Redistributions of source code must retain the above copyright
  25. * notice, this list of conditions and the following disclaimer.
  26. * 2. Redistributions in binary form must reproduce the above copyright
  27. * notice, this list of conditions and the following disclaimer in the
  28. * documentation and/or other materials provided with the distribution.
  29. * 3. All advertising materials mentioning features or use of this software
  30. * must display the following acknowledgement:
  31. * This product includes software developed by the University of
  32. * California, Berkeley and its contributors.
  33. * 4. Neither the name of the University nor the names of its contributors
  34. * may be used to endorse or promote products derived from this software
  35. * without specific prior written permission.
  36. *
  37. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  38. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  39. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  40. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  41. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  42. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  43. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  44. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  45. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  46. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  47. * SUCH DAMAGE.
  48. *
  49. * SPDX-License-Identifier: BSD-4-Clause-UC
  50. */
  51. #include "server_setup.h"
  52. #ifdef HAVE_SYS_IOCTL_H
  53. #include <sys/ioctl.h>
  54. #endif
  55. #ifdef HAVE_SIGNAL_H
  56. #include <signal.h>
  57. #endif
  58. #ifdef HAVE_FCNTL_H
  59. #include <fcntl.h>
  60. #endif
  61. #ifdef HAVE_NETINET_IN_H
  62. #include <netinet/in.h>
  63. #endif
  64. #ifdef HAVE_ARPA_INET_H
  65. #include <arpa/inet.h>
  66. #endif
  67. #ifdef HAVE_ARPA_TFTP_H
  68. #include <arpa/tftp.h>
  69. #else
  70. #include "tftp.h"
  71. #endif
  72. #ifdef HAVE_NETDB_H
  73. #include <netdb.h>
  74. #endif
  75. #ifdef HAVE_SYS_FILIO_H
  76. /* FIONREAD on Solaris 7 */
  77. #include <sys/filio.h>
  78. #endif
  79. #ifdef HAVE_SETJMP_H
  80. #include <setjmp.h>
  81. #endif
  82. #ifdef HAVE_PWD_H
  83. #include <pwd.h>
  84. #endif
  85. #include <ctype.h>
  86. #define ENABLE_CURLX_PRINTF
  87. /* make the curlx header define all printf() functions to use the curlx_*
  88. versions instead */
  89. #include "curlx.h" /* from the private lib dir */
  90. #include "getpart.h"
  91. #include "util.h"
  92. #include "server_sockaddr.h"
  93. /* include memdebug.h last */
  94. #include "memdebug.h"
  95. /*****************************************************************************
  96. * STRUCT DECLARATIONS AND DEFINES *
  97. *****************************************************************************/
  98. #ifndef PKTSIZE
  99. #define PKTSIZE (SEGSIZE + 4) /* SEGSIZE defined in arpa/tftp.h */
  100. #endif
  101. struct testcase {
  102. char *buffer; /* holds the file data to send to the client */
  103. size_t bufsize; /* size of the data in buffer */
  104. char *rptr; /* read pointer into the buffer */
  105. size_t rcount; /* amount of data left to read of the file */
  106. long testno; /* test case number */
  107. int ofile; /* file descriptor for output file when uploading to us */
  108. int writedelay; /* number of seconds between each packet */
  109. };
  110. struct formats {
  111. const char *f_mode;
  112. int f_convert;
  113. };
  114. struct errmsg {
  115. int e_code;
  116. const char *e_msg;
  117. };
  118. typedef union {
  119. struct tftphdr hdr;
  120. char storage[PKTSIZE];
  121. } tftphdr_storage_t;
  122. /*
  123. * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the
  124. * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE.
  125. */
  126. struct bf {
  127. int counter; /* size of data in buffer, or flag */
  128. tftphdr_storage_t buf; /* room for data packet */
  129. };
  130. #define BF_ALLOC -3 /* alloc'd but not yet filled */
  131. #define BF_FREE -2 /* free */
  132. #define opcode_RRQ 1
  133. #define opcode_WRQ 2
  134. #define opcode_DATA 3
  135. #define opcode_ACK 4
  136. #define opcode_ERROR 5
  137. #define TIMEOUT 5
  138. #undef MIN
  139. #define MIN(x,y) ((x)<(y)?(x):(y))
  140. #ifndef DEFAULT_LOGFILE
  141. #define DEFAULT_LOGFILE "log/tftpd.log"
  142. #endif
  143. #define REQUEST_DUMP "log/server.input"
  144. #define DEFAULT_PORT 8999 /* UDP */
  145. /*****************************************************************************
  146. * GLOBAL VARIABLES *
  147. *****************************************************************************/
  148. static struct errmsg errmsgs[] = {
  149. { EUNDEF, "Undefined error code" },
  150. { ENOTFOUND, "File not found" },
  151. { EACCESS, "Access violation" },
  152. { ENOSPACE, "Disk full or allocation exceeded" },
  153. { EBADOP, "Illegal TFTP operation" },
  154. { EBADID, "Unknown transfer ID" },
  155. { EEXISTS, "File already exists" },
  156. { ENOUSER, "No such user" },
  157. { -1, 0 }
  158. };
  159. static const struct formats formata[] = {
  160. { "netascii", 1 },
  161. { "octet", 0 },
  162. { NULL, 0 }
  163. };
  164. static struct bf bfs[2];
  165. static int nextone; /* index of next buffer to use */
  166. static int current; /* index of buffer in use */
  167. /* control flags for crlf conversions */
  168. static int newline = 0; /* fillbuf: in middle of newline expansion */
  169. static int prevchar = -1; /* putbuf: previous char (cr check) */
  170. static tftphdr_storage_t buf;
  171. static tftphdr_storage_t ackbuf;
  172. static srvr_sockaddr_union_t from;
  173. static curl_socklen_t fromlen;
  174. static curl_socket_t peer = CURL_SOCKET_BAD;
  175. static unsigned int timeout;
  176. static unsigned int maxtimeout = 5 * TIMEOUT;
  177. #ifdef ENABLE_IPV6
  178. static bool use_ipv6 = FALSE;
  179. #endif
  180. static const char *ipv_inuse = "IPv4";
  181. const char *serverlogfile = DEFAULT_LOGFILE;
  182. static const char *pidname = ".tftpd.pid";
  183. static const char *portname = NULL; /* none by default */
  184. static int serverlogslocked = 0;
  185. static int wrotepidfile = 0;
  186. static int wroteportfile = 0;
  187. #ifdef HAVE_SIGSETJMP
  188. static sigjmp_buf timeoutbuf;
  189. #endif
  190. #if defined(HAVE_ALARM) && defined(SIGALRM)
  191. static const unsigned int rexmtval = TIMEOUT;
  192. #endif
  193. /*****************************************************************************
  194. * FUNCTION PROTOTYPES *
  195. *****************************************************************************/
  196. static struct tftphdr *rw_init(int);
  197. static struct tftphdr *w_init(void);
  198. static struct tftphdr *r_init(void);
  199. static void read_ahead(struct testcase *test, int convert);
  200. static ssize_t write_behind(struct testcase *test, int convert);
  201. static int synchnet(curl_socket_t);
  202. static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
  203. static int validate_access(struct testcase *test, const char *fname, int mode);
  204. static void sendtftp(struct testcase *test, const struct formats *pf);
  205. static void recvtftp(struct testcase *test, const struct formats *pf);
  206. static void nak(int error);
  207. #if defined(HAVE_ALARM) && defined(SIGALRM)
  208. static void mysignal(int sig, void (*handler)(int));
  209. static void timer(int signum);
  210. static void justtimeout(int signum);
  211. #endif /* HAVE_ALARM && SIGALRM */
  212. /*****************************************************************************
  213. * FUNCTION IMPLEMENTATIONS *
  214. *****************************************************************************/
  215. #if defined(HAVE_ALARM) && defined(SIGALRM)
  216. /*
  217. * Like signal(), but with well-defined semantics.
  218. */
  219. static void mysignal(int sig, void (*handler)(int))
  220. {
  221. struct sigaction sa;
  222. memset(&sa, 0, sizeof(sa));
  223. sa.sa_handler = handler;
  224. sigaction(sig, &sa, NULL);
  225. }
  226. static void timer(int signum)
  227. {
  228. (void)signum;
  229. logmsg("alarm!");
  230. timeout += rexmtval;
  231. if(timeout >= maxtimeout) {
  232. if(wrotepidfile) {
  233. wrotepidfile = 0;
  234. unlink(pidname);
  235. }
  236. if(wroteportfile) {
  237. wroteportfile = 0;
  238. unlink(portname);
  239. }
  240. if(serverlogslocked) {
  241. serverlogslocked = 0;
  242. clear_advisor_read_lock(SERVERLOGS_LOCK);
  243. }
  244. exit(1);
  245. }
  246. #ifdef HAVE_SIGSETJMP
  247. siglongjmp(timeoutbuf, 1);
  248. #endif
  249. }
  250. static void justtimeout(int signum)
  251. {
  252. (void)signum;
  253. }
  254. #endif /* HAVE_ALARM && SIGALRM */
  255. /*
  256. * init for either read-ahead or write-behind.
  257. * zero for write-behind, one for read-head.
  258. */
  259. static struct tftphdr *rw_init(int x)
  260. {
  261. newline = 0; /* init crlf flag */
  262. prevchar = -1;
  263. bfs[0].counter = BF_ALLOC; /* pass out the first buffer */
  264. current = 0;
  265. bfs[1].counter = BF_FREE;
  266. nextone = x; /* ahead or behind? */
  267. return &bfs[0].buf.hdr;
  268. }
  269. static struct tftphdr *w_init(void)
  270. {
  271. return rw_init(0); /* write-behind */
  272. }
  273. static struct tftphdr *r_init(void)
  274. {
  275. return rw_init(1); /* read-ahead */
  276. }
  277. /* Have emptied current buffer by sending to net and getting ack.
  278. Free it and return next buffer filled with data.
  279. */
  280. static int readit(struct testcase *test, struct tftphdr **dpp,
  281. int convert /* if true, convert to ascii */)
  282. {
  283. struct bf *b;
  284. bfs[current].counter = BF_FREE; /* free old one */
  285. current = !current; /* "incr" current */
  286. b = &bfs[current]; /* look at new buffer */
  287. if(b->counter == BF_FREE) /* if it's empty */
  288. read_ahead(test, convert); /* fill it */
  289. *dpp = &b->buf.hdr; /* set caller's ptr */
  290. return b->counter;
  291. }
  292. /*
  293. * fill the input buffer, doing ascii conversions if requested
  294. * conversions are lf -> cr, lf and cr -> cr, nul
  295. */
  296. static void read_ahead(struct testcase *test,
  297. int convert /* if true, convert to ascii */)
  298. {
  299. int i;
  300. char *p;
  301. int c;
  302. struct bf *b;
  303. struct tftphdr *dp;
  304. b = &bfs[nextone]; /* look at "next" buffer */
  305. if(b->counter != BF_FREE) /* nop if not free */
  306. return;
  307. nextone = !nextone; /* "incr" next buffer ptr */
  308. dp = &b->buf.hdr;
  309. if(convert == 0) {
  310. /* The former file reading code did this:
  311. b->counter = read(fileno(file), dp->th_data, SEGSIZE); */
  312. size_t copy_n = MIN(SEGSIZE, test->rcount);
  313. memcpy(dp->th_data, test->rptr, copy_n);
  314. /* decrease amount, advance pointer */
  315. test->rcount -= copy_n;
  316. test->rptr += copy_n;
  317. b->counter = (int)copy_n;
  318. return;
  319. }
  320. p = dp->th_data;
  321. for(i = 0 ; i < SEGSIZE; i++) {
  322. if(newline) {
  323. if(prevchar == '\n')
  324. c = '\n'; /* lf to cr,lf */
  325. else
  326. c = '\0'; /* cr to cr,nul */
  327. newline = 0;
  328. }
  329. else {
  330. if(test->rcount) {
  331. c = test->rptr[0];
  332. test->rptr++;
  333. test->rcount--;
  334. }
  335. else
  336. break;
  337. if(c == '\n' || c == '\r') {
  338. prevchar = c;
  339. c = '\r';
  340. newline = 1;
  341. }
  342. }
  343. *p++ = (char)c;
  344. }
  345. b->counter = (int)(p - dp->th_data);
  346. }
  347. /* Update count associated with the buffer, get new buffer from the queue.
  348. Calls write_behind only if next buffer not available.
  349. */
  350. static int writeit(struct testcase *test, struct tftphdr * volatile *dpp,
  351. int ct, int convert)
  352. {
  353. bfs[current].counter = ct; /* set size of data to write */
  354. current = !current; /* switch to other buffer */
  355. if(bfs[current].counter != BF_FREE) /* if not free */
  356. write_behind(test, convert); /* flush it */
  357. bfs[current].counter = BF_ALLOC; /* mark as alloc'd */
  358. *dpp = &bfs[current].buf.hdr;
  359. return ct; /* this is a lie of course */
  360. }
  361. /*
  362. * Output a buffer to a file, converting from netascii if requested.
  363. * CR, NUL -> CR and CR, LF => LF.
  364. * Note spec is undefined if we get CR as last byte of file or a
  365. * CR followed by anything else. In this case we leave it alone.
  366. */
  367. static ssize_t write_behind(struct testcase *test, int convert)
  368. {
  369. char *writebuf;
  370. int count;
  371. int ct;
  372. char *p;
  373. int c; /* current character */
  374. struct bf *b;
  375. struct tftphdr *dp;
  376. b = &bfs[nextone];
  377. if(b->counter < -1) /* anything to flush? */
  378. return 0; /* just nop if nothing to do */
  379. if(!test->ofile) {
  380. char outfile[256];
  381. msnprintf(outfile, sizeof(outfile), "log/upload.%ld", test->testno);
  382. #ifdef WIN32
  383. test->ofile = open(outfile, O_CREAT|O_RDWR|O_BINARY, 0777);
  384. #else
  385. test->ofile = open(outfile, O_CREAT|O_RDWR, 0777);
  386. #endif
  387. if(test->ofile == -1) {
  388. logmsg("Couldn't create and/or open file %s for upload!", outfile);
  389. return -1; /* failure! */
  390. }
  391. }
  392. count = b->counter; /* remember byte count */
  393. b->counter = BF_FREE; /* reset flag */
  394. dp = &b->buf.hdr;
  395. nextone = !nextone; /* incr for next time */
  396. writebuf = dp->th_data;
  397. if(count <= 0)
  398. return -1; /* nak logic? */
  399. if(convert == 0)
  400. return write(test->ofile, writebuf, count);
  401. p = writebuf;
  402. ct = count;
  403. while(ct--) { /* loop over the buffer */
  404. c = *p++; /* pick up a character */
  405. if(prevchar == '\r') { /* if prev char was cr */
  406. if(c == '\n') /* if have cr,lf then just */
  407. lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
  408. else
  409. if(c == '\0') /* if have cr,nul then */
  410. goto skipit; /* just skip over the putc */
  411. /* else just fall through and allow it */
  412. }
  413. /* formerly
  414. putc(c, file); */
  415. if(1 != write(test->ofile, &c, 1))
  416. break;
  417. skipit:
  418. prevchar = c;
  419. }
  420. return count;
  421. }
  422. /* When an error has occurred, it is possible that the two sides are out of
  423. * synch. Ie: that what I think is the other side's response to packet N is
  424. * really their response to packet N-1.
  425. *
  426. * So, to try to prevent that, we flush all the input queued up for us on the
  427. * network connection on our host.
  428. *
  429. * We return the number of packets we flushed (mostly for reporting when trace
  430. * is active).
  431. */
  432. static int synchnet(curl_socket_t f /* socket to flush */)
  433. {
  434. #if defined(HAVE_IOCTLSOCKET)
  435. unsigned long i;
  436. #else
  437. int i;
  438. #endif
  439. int j = 0;
  440. char rbuf[PKTSIZE];
  441. srvr_sockaddr_union_t fromaddr;
  442. curl_socklen_t fromaddrlen;
  443. for(;;) {
  444. #if defined(HAVE_IOCTLSOCKET)
  445. (void) ioctlsocket(f, FIONREAD, &i);
  446. #else
  447. (void) ioctl(f, FIONREAD, &i);
  448. #endif
  449. if(i) {
  450. j++;
  451. #ifdef ENABLE_IPV6
  452. if(!use_ipv6)
  453. #endif
  454. fromaddrlen = sizeof(fromaddr.sa4);
  455. #ifdef ENABLE_IPV6
  456. else
  457. fromaddrlen = sizeof(fromaddr.sa6);
  458. #endif
  459. (void) recvfrom(f, rbuf, sizeof(rbuf), 0,
  460. &fromaddr.sa, &fromaddrlen);
  461. }
  462. else
  463. break;
  464. }
  465. return j;
  466. }
  467. int main(int argc, char **argv)
  468. {
  469. srvr_sockaddr_union_t me;
  470. struct tftphdr *tp;
  471. ssize_t n = 0;
  472. int arg = 1;
  473. unsigned short port = DEFAULT_PORT;
  474. curl_socket_t sock = CURL_SOCKET_BAD;
  475. int flag;
  476. int rc;
  477. int error;
  478. struct testcase test;
  479. int result = 0;
  480. memset(&test, 0, sizeof(test));
  481. while(argc>arg) {
  482. if(!strcmp("--version", argv[arg])) {
  483. printf("tftpd IPv4%s\n",
  484. #ifdef ENABLE_IPV6
  485. "/IPv6"
  486. #else
  487. ""
  488. #endif
  489. );
  490. return 0;
  491. }
  492. else if(!strcmp("--pidfile", argv[arg])) {
  493. arg++;
  494. if(argc>arg)
  495. pidname = argv[arg++];
  496. }
  497. else if(!strcmp("--portfile", argv[arg])) {
  498. arg++;
  499. if(argc>arg)
  500. portname = argv[arg++];
  501. }
  502. else if(!strcmp("--logfile", argv[arg])) {
  503. arg++;
  504. if(argc>arg)
  505. serverlogfile = argv[arg++];
  506. }
  507. else if(!strcmp("--ipv4", argv[arg])) {
  508. #ifdef ENABLE_IPV6
  509. ipv_inuse = "IPv4";
  510. use_ipv6 = FALSE;
  511. #endif
  512. arg++;
  513. }
  514. else if(!strcmp("--ipv6", argv[arg])) {
  515. #ifdef ENABLE_IPV6
  516. ipv_inuse = "IPv6";
  517. use_ipv6 = TRUE;
  518. #endif
  519. arg++;
  520. }
  521. else if(!strcmp("--port", argv[arg])) {
  522. arg++;
  523. if(argc>arg) {
  524. char *endptr;
  525. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  526. port = curlx_ultous(ulnum);
  527. arg++;
  528. }
  529. }
  530. else if(!strcmp("--srcdir", argv[arg])) {
  531. arg++;
  532. if(argc>arg) {
  533. path = argv[arg];
  534. arg++;
  535. }
  536. }
  537. else {
  538. puts("Usage: tftpd [option]\n"
  539. " --version\n"
  540. " --logfile [file]\n"
  541. " --pidfile [file]\n"
  542. " --portfile [file]\n"
  543. " --ipv4\n"
  544. " --ipv6\n"
  545. " --port [port]\n"
  546. " --srcdir [path]");
  547. return 0;
  548. }
  549. }
  550. #ifdef WIN32
  551. win32_init();
  552. atexit(win32_cleanup);
  553. #endif
  554. install_signal_handlers(true);
  555. #ifdef ENABLE_IPV6
  556. if(!use_ipv6)
  557. #endif
  558. sock = socket(AF_INET, SOCK_DGRAM, 0);
  559. #ifdef ENABLE_IPV6
  560. else
  561. sock = socket(AF_INET6, SOCK_DGRAM, 0);
  562. #endif
  563. if(CURL_SOCKET_BAD == sock) {
  564. error = SOCKERRNO;
  565. logmsg("Error creating socket: (%d) %s",
  566. error, strerror(error));
  567. result = 1;
  568. goto tftpd_cleanup;
  569. }
  570. flag = 1;
  571. if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  572. (void *)&flag, sizeof(flag))) {
  573. error = SOCKERRNO;
  574. logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
  575. error, strerror(error));
  576. result = 1;
  577. goto tftpd_cleanup;
  578. }
  579. #ifdef ENABLE_IPV6
  580. if(!use_ipv6) {
  581. #endif
  582. memset(&me.sa4, 0, sizeof(me.sa4));
  583. me.sa4.sin_family = AF_INET;
  584. me.sa4.sin_addr.s_addr = INADDR_ANY;
  585. me.sa4.sin_port = htons(port);
  586. rc = bind(sock, &me.sa, sizeof(me.sa4));
  587. #ifdef ENABLE_IPV6
  588. }
  589. else {
  590. memset(&me.sa6, 0, sizeof(me.sa6));
  591. me.sa6.sin6_family = AF_INET6;
  592. me.sa6.sin6_addr = in6addr_any;
  593. me.sa6.sin6_port = htons(port);
  594. rc = bind(sock, &me.sa, sizeof(me.sa6));
  595. }
  596. #endif /* ENABLE_IPV6 */
  597. if(0 != rc) {
  598. error = SOCKERRNO;
  599. logmsg("Error binding socket on port %hu: (%d) %s",
  600. port, error, strerror(error));
  601. result = 1;
  602. goto tftpd_cleanup;
  603. }
  604. if(!port) {
  605. /* The system was supposed to choose a port number, figure out which
  606. port we actually got and update the listener port value with it. */
  607. curl_socklen_t la_size;
  608. srvr_sockaddr_union_t localaddr;
  609. #ifdef ENABLE_IPV6
  610. if(!use_ipv6)
  611. #endif
  612. la_size = sizeof(localaddr.sa4);
  613. #ifdef ENABLE_IPV6
  614. else
  615. la_size = sizeof(localaddr.sa6);
  616. #endif
  617. memset(&localaddr.sa, 0, (size_t)la_size);
  618. if(getsockname(sock, &localaddr.sa, &la_size) < 0) {
  619. error = SOCKERRNO;
  620. logmsg("getsockname() failed with error: (%d) %s",
  621. error, strerror(error));
  622. sclose(sock);
  623. goto tftpd_cleanup;
  624. }
  625. switch(localaddr.sa.sa_family) {
  626. case AF_INET:
  627. port = ntohs(localaddr.sa4.sin_port);
  628. break;
  629. #ifdef ENABLE_IPV6
  630. case AF_INET6:
  631. port = ntohs(localaddr.sa6.sin6_port);
  632. break;
  633. #endif
  634. default:
  635. break;
  636. }
  637. if(!port) {
  638. /* Real failure, listener port shall not be zero beyond this point. */
  639. logmsg("Apparently getsockname() succeeded, with listener port zero.");
  640. logmsg("A valid reason for this failure is a binary built without");
  641. logmsg("proper network library linkage. This might not be the only");
  642. logmsg("reason, but double check it before anything else.");
  643. result = 2;
  644. goto tftpd_cleanup;
  645. }
  646. }
  647. wrotepidfile = write_pidfile(pidname);
  648. if(!wrotepidfile) {
  649. result = 1;
  650. goto tftpd_cleanup;
  651. }
  652. if(portname) {
  653. wroteportfile = write_portfile(portname, port);
  654. if(!wroteportfile) {
  655. result = 1;
  656. goto tftpd_cleanup;
  657. }
  658. }
  659. logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
  660. for(;;) {
  661. fromlen = sizeof(from);
  662. #ifdef ENABLE_IPV6
  663. if(!use_ipv6)
  664. #endif
  665. fromlen = sizeof(from.sa4);
  666. #ifdef ENABLE_IPV6
  667. else
  668. fromlen = sizeof(from.sa6);
  669. #endif
  670. n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0,
  671. &from.sa, &fromlen);
  672. if(got_exit_signal)
  673. break;
  674. if(n < 0) {
  675. logmsg("recvfrom");
  676. result = 3;
  677. break;
  678. }
  679. set_advisor_read_lock(SERVERLOGS_LOCK);
  680. serverlogslocked = 1;
  681. #ifdef ENABLE_IPV6
  682. if(!use_ipv6) {
  683. #endif
  684. from.sa4.sin_family = AF_INET;
  685. peer = socket(AF_INET, SOCK_DGRAM, 0);
  686. if(CURL_SOCKET_BAD == peer) {
  687. logmsg("socket");
  688. result = 2;
  689. break;
  690. }
  691. if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) {
  692. logmsg("connect: fail");
  693. result = 1;
  694. break;
  695. }
  696. #ifdef ENABLE_IPV6
  697. }
  698. else {
  699. from.sa6.sin6_family = AF_INET6;
  700. peer = socket(AF_INET6, SOCK_DGRAM, 0);
  701. if(CURL_SOCKET_BAD == peer) {
  702. logmsg("socket");
  703. result = 2;
  704. break;
  705. }
  706. if(connect(peer, &from.sa, sizeof(from.sa6)) < 0) {
  707. logmsg("connect: fail");
  708. result = 1;
  709. break;
  710. }
  711. }
  712. #endif
  713. maxtimeout = 5*TIMEOUT;
  714. tp = &buf.hdr;
  715. tp->th_opcode = ntohs(tp->th_opcode);
  716. if(tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
  717. memset(&test, 0, sizeof(test));
  718. if(do_tftp(&test, tp, n) < 0)
  719. break;
  720. free(test.buffer);
  721. }
  722. sclose(peer);
  723. peer = CURL_SOCKET_BAD;
  724. if(got_exit_signal)
  725. break;
  726. if(serverlogslocked) {
  727. serverlogslocked = 0;
  728. clear_advisor_read_lock(SERVERLOGS_LOCK);
  729. }
  730. logmsg("end of one transfer");
  731. }
  732. tftpd_cleanup:
  733. if(test.ofile > 0)
  734. close(test.ofile);
  735. if((peer != sock) && (peer != CURL_SOCKET_BAD))
  736. sclose(peer);
  737. if(sock != CURL_SOCKET_BAD)
  738. sclose(sock);
  739. if(got_exit_signal)
  740. logmsg("signalled to die");
  741. if(wrotepidfile)
  742. unlink(pidname);
  743. if(wroteportfile)
  744. unlink(portname);
  745. if(serverlogslocked) {
  746. serverlogslocked = 0;
  747. clear_advisor_read_lock(SERVERLOGS_LOCK);
  748. }
  749. restore_signal_handlers(true);
  750. if(got_exit_signal) {
  751. logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
  752. ipv_inuse, (int)port, (long)getpid(), exit_signal);
  753. /*
  754. * To properly set the return status of the process we
  755. * must raise the same signal SIGINT or SIGTERM that we
  756. * caught and let the old handler take care of it.
  757. */
  758. raise(exit_signal);
  759. }
  760. logmsg("========> tftpd quits");
  761. return result;
  762. }
  763. /*
  764. * Handle initial connection protocol.
  765. */
  766. static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
  767. {
  768. char *cp;
  769. int first = 1, ecode;
  770. const struct formats *pf;
  771. char *filename, *mode = NULL;
  772. #ifdef USE_WINSOCK
  773. DWORD recvtimeout, recvtimeoutbak;
  774. #endif
  775. const char *option = "mode"; /* mode is implicit */
  776. int toggle = 1;
  777. /* Open request dump file. */
  778. FILE *server = fopen(REQUEST_DUMP, "ab");
  779. if(!server) {
  780. int error = errno;
  781. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  782. logmsg("Error opening file: %s", REQUEST_DUMP);
  783. return -1;
  784. }
  785. /* store input protocol */
  786. fprintf(server, "opcode = %x\n", tp->th_opcode);
  787. cp = (char *)&tp->th_stuff;
  788. filename = cp;
  789. do {
  790. bool endofit = true;
  791. while(cp < &buf.storage[size]) {
  792. if(*cp == '\0') {
  793. endofit = false;
  794. break;
  795. }
  796. cp++;
  797. }
  798. if(endofit)
  799. /* no more options */
  800. break;
  801. /* before increasing pointer, make sure it is still within the legal
  802. space */
  803. if((cp + 1) < &buf.storage[size]) {
  804. ++cp;
  805. if(first) {
  806. /* store the mode since we need it later */
  807. mode = cp;
  808. first = 0;
  809. }
  810. if(toggle)
  811. /* name/value pair: */
  812. fprintf(server, "%s = %s\n", option, cp);
  813. else {
  814. /* store the name pointer */
  815. option = cp;
  816. }
  817. toggle ^= 1;
  818. }
  819. else
  820. /* No more options */
  821. break;
  822. } while(1);
  823. if(*cp) {
  824. nak(EBADOP);
  825. fclose(server);
  826. return 3;
  827. }
  828. /* store input protocol */
  829. fprintf(server, "filename = %s\n", filename);
  830. for(cp = mode; cp && *cp; cp++)
  831. if(ISUPPER(*cp))
  832. *cp = (char)tolower((int)*cp);
  833. /* store input protocol */
  834. fclose(server);
  835. for(pf = formata; pf->f_mode; pf++)
  836. if(strcmp(pf->f_mode, mode) == 0)
  837. break;
  838. if(!pf->f_mode) {
  839. nak(EBADOP);
  840. return 2;
  841. }
  842. ecode = validate_access(test, filename, tp->th_opcode);
  843. if(ecode) {
  844. nak(ecode);
  845. return 1;
  846. }
  847. #ifdef USE_WINSOCK
  848. recvtimeout = sizeof(recvtimeoutbak);
  849. getsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
  850. (char *)&recvtimeoutbak, (int *)&recvtimeout);
  851. recvtimeout = TIMEOUT*1000;
  852. setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
  853. (const char *)&recvtimeout, sizeof(recvtimeout));
  854. #endif
  855. if(tp->th_opcode == opcode_WRQ)
  856. recvtftp(test, pf);
  857. else
  858. sendtftp(test, pf);
  859. #ifdef USE_WINSOCK
  860. recvtimeout = recvtimeoutbak;
  861. setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
  862. (const char *)&recvtimeout, sizeof(recvtimeout));
  863. #endif
  864. return 0;
  865. }
  866. /* Based on the testno, parse the correct server commands. */
  867. static int parse_servercmd(struct testcase *req)
  868. {
  869. FILE *stream;
  870. int error;
  871. stream = test2fopen(req->testno);
  872. if(!stream) {
  873. error = errno;
  874. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  875. logmsg(" Couldn't open test file %ld", req->testno);
  876. return 1; /* done */
  877. }
  878. else {
  879. char *orgcmd = NULL;
  880. char *cmd = NULL;
  881. size_t cmdsize = 0;
  882. int num = 0;
  883. /* get the custom server control "commands" */
  884. error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream);
  885. fclose(stream);
  886. if(error) {
  887. logmsg("getpart() failed with error: %d", error);
  888. return 1; /* done */
  889. }
  890. cmd = orgcmd;
  891. while(cmd && cmdsize) {
  892. char *check;
  893. if(1 == sscanf(cmd, "writedelay: %d", &num)) {
  894. logmsg("instructed to delay %d secs between packets", num);
  895. req->writedelay = num;
  896. }
  897. else {
  898. logmsg("Unknown <servercmd> instruction found: %s", cmd);
  899. }
  900. /* try to deal with CRLF or just LF */
  901. check = strchr(cmd, '\r');
  902. if(!check)
  903. check = strchr(cmd, '\n');
  904. if(check) {
  905. /* get to the letter following the newline */
  906. while((*check == '\r') || (*check == '\n'))
  907. check++;
  908. if(!*check)
  909. /* if we reached a zero, get out */
  910. break;
  911. cmd = check;
  912. }
  913. else
  914. break;
  915. }
  916. free(orgcmd);
  917. }
  918. return 0; /* OK! */
  919. }
  920. /*
  921. * Validate file access.
  922. */
  923. static int validate_access(struct testcase *test,
  924. const char *filename, int mode)
  925. {
  926. char *ptr;
  927. logmsg("trying to get file: %s mode %x", filename, mode);
  928. if(!strncmp("verifiedserver", filename, 14)) {
  929. char weare[128];
  930. size_t count = msnprintf(weare, sizeof(weare), "WE ROOLZ: %"
  931. CURL_FORMAT_CURL_OFF_T "\r\n", our_getpid());
  932. logmsg("Are-we-friendly question received");
  933. test->buffer = strdup(weare);
  934. test->rptr = test->buffer; /* set read pointer */
  935. test->bufsize = count; /* set total count */
  936. test->rcount = count; /* set data left to read */
  937. return 0; /* fine */
  938. }
  939. /* find the last slash */
  940. ptr = strrchr(filename, '/');
  941. if(ptr) {
  942. char partbuf[80]="data";
  943. long partno;
  944. long testno;
  945. FILE *stream;
  946. ptr++; /* skip the slash */
  947. /* skip all non-numericals following the slash */
  948. while(*ptr && !ISDIGIT(*ptr))
  949. ptr++;
  950. /* get the number */
  951. testno = strtol(ptr, &ptr, 10);
  952. if(testno > 10000) {
  953. partno = testno % 10000;
  954. testno /= 10000;
  955. }
  956. else
  957. partno = 0;
  958. logmsg("requested test number %ld part %ld", testno, partno);
  959. test->testno = testno;
  960. (void)parse_servercmd(test);
  961. stream = test2fopen(testno);
  962. if(0 != partno)
  963. msnprintf(partbuf, sizeof(partbuf), "data%ld", partno);
  964. if(!stream) {
  965. int error = errno;
  966. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  967. logmsg("Couldn't open test file for test : %d", testno);
  968. return EACCESS;
  969. }
  970. else {
  971. size_t count;
  972. int error = getpart(&test->buffer, &count, "reply", partbuf, stream);
  973. fclose(stream);
  974. if(error) {
  975. logmsg("getpart() failed with error: %d", error);
  976. return EACCESS;
  977. }
  978. if(test->buffer) {
  979. test->rptr = test->buffer; /* set read pointer */
  980. test->bufsize = count; /* set total count */
  981. test->rcount = count; /* set data left to read */
  982. }
  983. else
  984. return EACCESS;
  985. }
  986. }
  987. else {
  988. logmsg("no slash found in path");
  989. return EACCESS; /* failure */
  990. }
  991. logmsg("file opened and all is good");
  992. return 0;
  993. }
  994. /*
  995. * Send the requested file.
  996. */
  997. static void sendtftp(struct testcase *test, const struct formats *pf)
  998. {
  999. int size;
  1000. ssize_t n;
  1001. /* These are volatile to live through a siglongjmp */
  1002. volatile unsigned short sendblock; /* block count */
  1003. struct tftphdr * volatile sdp = r_init(); /* data buffer */
  1004. struct tftphdr * const sap = &ackbuf.hdr; /* ack buffer */
  1005. sendblock = 1;
  1006. #if defined(HAVE_ALARM) && defined(SIGALRM)
  1007. mysignal(SIGALRM, timer);
  1008. #endif
  1009. do {
  1010. size = readit(test, (struct tftphdr **)&sdp, pf->f_convert);
  1011. if(size < 0) {
  1012. nak(errno + 100);
  1013. return;
  1014. }
  1015. sdp->th_opcode = htons((unsigned short)opcode_DATA);
  1016. sdp->th_block = htons(sendblock);
  1017. timeout = 0;
  1018. #ifdef HAVE_SIGSETJMP
  1019. (void) sigsetjmp(timeoutbuf, 1);
  1020. #endif
  1021. if(test->writedelay) {
  1022. logmsg("Pausing %d seconds before %d bytes", test->writedelay,
  1023. size);
  1024. wait_ms(1000*test->writedelay);
  1025. }
  1026. send_data:
  1027. logmsg("write");
  1028. if(swrite(peer, sdp, size + 4) != size + 4) {
  1029. logmsg("write: fail");
  1030. return;
  1031. }
  1032. read_ahead(test, pf->f_convert);
  1033. for(;;) {
  1034. #ifdef HAVE_ALARM
  1035. alarm(rexmtval); /* read the ack */
  1036. #endif
  1037. logmsg("read");
  1038. n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage));
  1039. logmsg("read: %zd", n);
  1040. #ifdef HAVE_ALARM
  1041. alarm(0);
  1042. #endif
  1043. if(got_exit_signal)
  1044. return;
  1045. if(n < 0) {
  1046. logmsg("read: fail");
  1047. return;
  1048. }
  1049. sap->th_opcode = ntohs((unsigned short)sap->th_opcode);
  1050. sap->th_block = ntohs(sap->th_block);
  1051. if(sap->th_opcode == opcode_ERROR) {
  1052. logmsg("got ERROR");
  1053. return;
  1054. }
  1055. if(sap->th_opcode == opcode_ACK) {
  1056. if(sap->th_block == sendblock) {
  1057. break;
  1058. }
  1059. /* Re-synchronize with the other side */
  1060. (void) synchnet(peer);
  1061. if(sap->th_block == (sendblock-1)) {
  1062. goto send_data;
  1063. }
  1064. }
  1065. }
  1066. sendblock++;
  1067. } while(size == SEGSIZE);
  1068. }
  1069. /*
  1070. * Receive a file.
  1071. */
  1072. static void recvtftp(struct testcase *test, const struct formats *pf)
  1073. {
  1074. ssize_t n, size;
  1075. /* These are volatile to live through a siglongjmp */
  1076. volatile unsigned short recvblock; /* block count */
  1077. struct tftphdr * volatile rdp; /* data buffer */
  1078. struct tftphdr *rap; /* ack buffer */
  1079. recvblock = 0;
  1080. rdp = w_init();
  1081. #if defined(HAVE_ALARM) && defined(SIGALRM)
  1082. mysignal(SIGALRM, timer);
  1083. #endif
  1084. rap = &ackbuf.hdr;
  1085. do {
  1086. timeout = 0;
  1087. rap->th_opcode = htons((unsigned short)opcode_ACK);
  1088. rap->th_block = htons(recvblock);
  1089. recvblock++;
  1090. #ifdef HAVE_SIGSETJMP
  1091. (void) sigsetjmp(timeoutbuf, 1);
  1092. #endif
  1093. send_ack:
  1094. logmsg("write");
  1095. if(swrite(peer, &ackbuf.storage[0], 4) != 4) {
  1096. logmsg("write: fail");
  1097. goto abort;
  1098. }
  1099. write_behind(test, pf->f_convert);
  1100. for(;;) {
  1101. #ifdef HAVE_ALARM
  1102. alarm(rexmtval);
  1103. #endif
  1104. logmsg("read");
  1105. n = sread(peer, rdp, PKTSIZE);
  1106. logmsg("read: %zd", n);
  1107. #ifdef HAVE_ALARM
  1108. alarm(0);
  1109. #endif
  1110. if(got_exit_signal)
  1111. goto abort;
  1112. if(n < 0) { /* really? */
  1113. logmsg("read: fail");
  1114. goto abort;
  1115. }
  1116. rdp->th_opcode = ntohs((unsigned short)rdp->th_opcode);
  1117. rdp->th_block = ntohs(rdp->th_block);
  1118. if(rdp->th_opcode == opcode_ERROR)
  1119. goto abort;
  1120. if(rdp->th_opcode == opcode_DATA) {
  1121. if(rdp->th_block == recvblock) {
  1122. break; /* normal */
  1123. }
  1124. /* Re-synchronize with the other side */
  1125. (void) synchnet(peer);
  1126. if(rdp->th_block == (recvblock-1))
  1127. goto send_ack; /* rexmit */
  1128. }
  1129. }
  1130. size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
  1131. if(size != (n-4)) { /* ahem */
  1132. if(size < 0)
  1133. nak(errno + 100);
  1134. else
  1135. nak(ENOSPACE);
  1136. goto abort;
  1137. }
  1138. } while(size == SEGSIZE);
  1139. write_behind(test, pf->f_convert);
  1140. /* close the output file as early as possible after upload completion */
  1141. if(test->ofile > 0) {
  1142. close(test->ofile);
  1143. test->ofile = 0;
  1144. }
  1145. rap->th_opcode = htons((unsigned short)opcode_ACK); /* send the "final"
  1146. ack */
  1147. rap->th_block = htons(recvblock);
  1148. (void) swrite(peer, &ackbuf.storage[0], 4);
  1149. #if defined(HAVE_ALARM) && defined(SIGALRM)
  1150. mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
  1151. alarm(rexmtval);
  1152. #endif
  1153. /* normally times out and quits */
  1154. n = sread(peer, &buf.storage[0], sizeof(buf.storage));
  1155. #ifdef HAVE_ALARM
  1156. alarm(0);
  1157. #endif
  1158. if(got_exit_signal)
  1159. goto abort;
  1160. if(n >= 4 && /* if read some data */
  1161. rdp->th_opcode == opcode_DATA && /* and got a data block */
  1162. recvblock == rdp->th_block) { /* then my last ack was lost */
  1163. (void) swrite(peer, &ackbuf.storage[0], 4); /* resend final ack */
  1164. }
  1165. abort:
  1166. /* make sure the output file is closed in case of abort */
  1167. if(test->ofile > 0) {
  1168. close(test->ofile);
  1169. test->ofile = 0;
  1170. }
  1171. return;
  1172. }
  1173. /*
  1174. * Send a nak packet (error message). Error code passed in is one of the
  1175. * standard TFTP codes, or a Unix errno offset by 100.
  1176. */
  1177. static void nak(int error)
  1178. {
  1179. struct tftphdr *tp;
  1180. int length;
  1181. struct errmsg *pe;
  1182. tp = &buf.hdr;
  1183. tp->th_opcode = htons((unsigned short)opcode_ERROR);
  1184. tp->th_code = htons((unsigned short)error);
  1185. for(pe = errmsgs; pe->e_code >= 0; pe++)
  1186. if(pe->e_code == error)
  1187. break;
  1188. if(pe->e_code < 0) {
  1189. pe->e_msg = strerror(error - 100);
  1190. tp->th_code = EUNDEF; /* set 'undef' errorcode */
  1191. }
  1192. length = (int)strlen(pe->e_msg);
  1193. /* we use memcpy() instead of strcpy() in order to avoid buffer overflow
  1194. * report from glibc with FORTIFY_SOURCE */
  1195. memcpy(tp->th_msg, pe->e_msg, length + 1);
  1196. length += 5;
  1197. if(swrite(peer, &buf.storage[0], length) != length)
  1198. logmsg("nak: fail\n");
  1199. }