tftpd.c 34 KB

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