tftpd.c 35 KB

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