tftpd.c 35 KB

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