tftpd.c 34 KB

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