tftpd.c 34 KB

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