tftpd.c 33 KB

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