tftpd.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  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 testno; /* test case number */
  101. int ofile; /* file descriptor for output file when uploading to us */
  102. int writedelay; /* number of seconds between each packet */
  103. };
  104. struct formats {
  105. const char *f_mode;
  106. int f_convert;
  107. };
  108. struct errmsg {
  109. int e_code;
  110. const char *e_msg;
  111. };
  112. typedef union {
  113. struct tftphdr hdr;
  114. char storage[PKTSIZE];
  115. } tftphdr_storage_t;
  116. /*
  117. * bf.counter values in range [-1 .. SEGSIZE] represents size of data in the
  118. * bf.buf buffer. Additionally it can also hold flags BF_ALLOC or BF_FREE.
  119. */
  120. struct bf {
  121. int counter; /* size of data in buffer, or flag */
  122. tftphdr_storage_t buf; /* room for data packet */
  123. };
  124. #define BF_ALLOC -3 /* alloc'd but not yet filled */
  125. #define BF_FREE -2 /* free */
  126. #define opcode_RRQ 1
  127. #define opcode_WRQ 2
  128. #define opcode_DATA 3
  129. #define opcode_ACK 4
  130. #define opcode_ERROR 5
  131. #define TIMEOUT 5
  132. #undef MIN
  133. #define MIN(x,y) ((x)<(y)?(x):(y))
  134. #ifndef DEFAULT_LOGFILE
  135. #define DEFAULT_LOGFILE "log/tftpd.log"
  136. #endif
  137. #define REQUEST_DUMP "log/server.input"
  138. #define DEFAULT_PORT 8999 /* UDP */
  139. /*****************************************************************************
  140. * GLOBAL VARIABLES *
  141. *****************************************************************************/
  142. static struct errmsg errmsgs[] = {
  143. { EUNDEF, "Undefined error code" },
  144. { ENOTFOUND, "File not found" },
  145. { EACCESS, "Access violation" },
  146. { ENOSPACE, "Disk full or allocation exceeded" },
  147. { EBADOP, "Illegal TFTP operation" },
  148. { EBADID, "Unknown transfer ID" },
  149. { EEXISTS, "File already exists" },
  150. { ENOUSER, "No such user" },
  151. { -1, 0 }
  152. };
  153. static struct formats formata[] = {
  154. { "netascii", 1 },
  155. { "octet", 0 },
  156. { NULL, 0 }
  157. };
  158. static struct bf bfs[2];
  159. static int nextone; /* index of next buffer to use */
  160. static int current; /* index of buffer in use */
  161. /* control flags for crlf conversions */
  162. static int newline = 0; /* fillbuf: in middle of newline expansion */
  163. static int prevchar = -1; /* putbuf: previous char (cr check) */
  164. static tftphdr_storage_t buf;
  165. static tftphdr_storage_t ackbuf;
  166. static srvr_sockaddr_union_t from;
  167. static curl_socklen_t fromlen;
  168. static curl_socket_t peer = CURL_SOCKET_BAD;
  169. static unsigned int timeout;
  170. static unsigned int maxtimeout = 5 * TIMEOUT;
  171. #ifdef ENABLE_IPV6
  172. static bool use_ipv6 = FALSE;
  173. #endif
  174. static const char *ipv_inuse = "IPv4";
  175. const char *serverlogfile = DEFAULT_LOGFILE;
  176. static const char *pidname = ".tftpd.pid";
  177. static int serverlogslocked = 0;
  178. static int wrotepidfile = 0;
  179. #ifdef HAVE_SIGSETJMP
  180. static sigjmp_buf timeoutbuf;
  181. #endif
  182. #if defined(HAVE_ALARM) && defined(SIGALRM)
  183. static const unsigned int rexmtval = TIMEOUT;
  184. #endif
  185. /* do-nothing macro replacement for systems which lack siginterrupt() */
  186. #ifndef HAVE_SIGINTERRUPT
  187. #define siginterrupt(x,y) do {} while(0)
  188. #endif
  189. /* vars used to keep around previous signal handlers */
  190. typedef RETSIGTYPE (*SIGHANDLER_T)(int);
  191. #ifdef SIGHUP
  192. static SIGHANDLER_T old_sighup_handler = SIG_ERR;
  193. #endif
  194. #ifdef SIGPIPE
  195. static SIGHANDLER_T old_sigpipe_handler = SIG_ERR;
  196. #endif
  197. #ifdef SIGINT
  198. static SIGHANDLER_T old_sigint_handler = SIG_ERR;
  199. #endif
  200. #ifdef SIGTERM
  201. static SIGHANDLER_T old_sigterm_handler = SIG_ERR;
  202. #endif
  203. #if defined(SIGBREAK) && defined(WIN32)
  204. static SIGHANDLER_T old_sigbreak_handler = SIG_ERR;
  205. #endif
  206. /* var which if set indicates that the program should finish execution */
  207. SIG_ATOMIC_T got_exit_signal = 0;
  208. /* if next is set indicates the first signal handled in exit_signal_handler */
  209. static volatile int exit_signal = 0;
  210. /*****************************************************************************
  211. * FUNCTION PROTOTYPES *
  212. *****************************************************************************/
  213. static struct tftphdr *rw_init(int);
  214. static struct tftphdr *w_init(void);
  215. static struct tftphdr *r_init(void);
  216. static void read_ahead(struct testcase *test, int convert);
  217. static ssize_t write_behind(struct testcase *test, int convert);
  218. static int synchnet(curl_socket_t);
  219. static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size);
  220. static int validate_access(struct testcase *test, const char *fname, int mode);
  221. static void sendtftp(struct testcase *test, struct formats *pf);
  222. static void recvtftp(struct testcase *test, struct formats *pf);
  223. static void nak(int error);
  224. #if defined(HAVE_ALARM) && defined(SIGALRM)
  225. static void mysignal(int sig, void (*handler)(int));
  226. static void timer(int signum);
  227. static void justtimeout(int signum);
  228. #endif /* HAVE_ALARM && SIGALRM */
  229. static RETSIGTYPE exit_signal_handler(int signum);
  230. static void install_signal_handlers(void);
  231. static void restore_signal_handlers(void);
  232. /*****************************************************************************
  233. * FUNCTION IMPLEMENTATIONS *
  234. *****************************************************************************/
  235. #if defined(HAVE_ALARM) && defined(SIGALRM)
  236. /*
  237. * Like signal(), but with well-defined semantics.
  238. */
  239. static void mysignal(int sig, void (*handler)(int))
  240. {
  241. struct sigaction sa;
  242. memset(&sa, 0, sizeof(sa));
  243. sa.sa_handler = handler;
  244. sigaction(sig, &sa, NULL);
  245. }
  246. static void timer(int signum)
  247. {
  248. (void)signum;
  249. logmsg("alarm!");
  250. timeout += rexmtval;
  251. if(timeout >= maxtimeout) {
  252. if(wrotepidfile) {
  253. wrotepidfile = 0;
  254. unlink(pidname);
  255. }
  256. if(serverlogslocked) {
  257. serverlogslocked = 0;
  258. clear_advisor_read_lock(SERVERLOGS_LOCK);
  259. }
  260. exit(1);
  261. }
  262. #ifdef HAVE_SIGSETJMP
  263. siglongjmp(timeoutbuf, 1);
  264. #endif
  265. }
  266. static void justtimeout(int signum)
  267. {
  268. (void)signum;
  269. }
  270. #endif /* HAVE_ALARM && SIGALRM */
  271. /* signal handler that will be triggered to indicate that the program
  272. should finish its execution in a controlled manner as soon as possible.
  273. The first time this is called it will set got_exit_signal to one and
  274. store in exit_signal the signal that triggered its execution. */
  275. static RETSIGTYPE exit_signal_handler(int signum)
  276. {
  277. int old_errno = errno;
  278. if(got_exit_signal == 0) {
  279. got_exit_signal = 1;
  280. exit_signal = signum;
  281. }
  282. (void)signal(signum, exit_signal_handler);
  283. errno = old_errno;
  284. }
  285. static void install_signal_handlers(void)
  286. {
  287. #ifdef SIGHUP
  288. /* ignore SIGHUP signal */
  289. old_sighup_handler = signal(SIGHUP, SIG_IGN);
  290. if(old_sighup_handler == SIG_ERR)
  291. logmsg("cannot install SIGHUP handler: %s", strerror(errno));
  292. #endif
  293. #ifdef SIGPIPE
  294. /* ignore SIGPIPE signal */
  295. old_sigpipe_handler = signal(SIGPIPE, SIG_IGN);
  296. if(old_sigpipe_handler == SIG_ERR)
  297. logmsg("cannot install SIGPIPE handler: %s", strerror(errno));
  298. #endif
  299. #ifdef SIGINT
  300. /* handle SIGINT signal with our exit_signal_handler */
  301. old_sigint_handler = signal(SIGINT, exit_signal_handler);
  302. if(old_sigint_handler == SIG_ERR)
  303. logmsg("cannot install SIGINT handler: %s", strerror(errno));
  304. else
  305. siginterrupt(SIGINT, 1);
  306. #endif
  307. #ifdef SIGTERM
  308. /* handle SIGTERM signal with our exit_signal_handler */
  309. old_sigterm_handler = signal(SIGTERM, exit_signal_handler);
  310. if(old_sigterm_handler == SIG_ERR)
  311. logmsg("cannot install SIGTERM handler: %s", strerror(errno));
  312. else
  313. siginterrupt(SIGTERM, 1);
  314. #endif
  315. #if defined(SIGBREAK) && defined(WIN32)
  316. /* handle SIGBREAK signal with our exit_signal_handler */
  317. old_sigbreak_handler = signal(SIGBREAK, exit_signal_handler);
  318. if(old_sigbreak_handler == SIG_ERR)
  319. logmsg("cannot install SIGBREAK handler: %s", strerror(errno));
  320. else
  321. siginterrupt(SIGBREAK, 1);
  322. #endif
  323. }
  324. static void restore_signal_handlers(void)
  325. {
  326. #ifdef SIGHUP
  327. if(SIG_ERR != old_sighup_handler)
  328. (void)signal(SIGHUP, old_sighup_handler);
  329. #endif
  330. #ifdef SIGPIPE
  331. if(SIG_ERR != old_sigpipe_handler)
  332. (void)signal(SIGPIPE, old_sigpipe_handler);
  333. #endif
  334. #ifdef SIGINT
  335. if(SIG_ERR != old_sigint_handler)
  336. (void)signal(SIGINT, old_sigint_handler);
  337. #endif
  338. #ifdef SIGTERM
  339. if(SIG_ERR != old_sigterm_handler)
  340. (void)signal(SIGTERM, old_sigterm_handler);
  341. #endif
  342. #if defined(SIGBREAK) && defined(WIN32)
  343. if(SIG_ERR != old_sigbreak_handler)
  344. (void)signal(SIGBREAK, old_sigbreak_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 * volatile *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. msnprintf(outfile, sizeof(outfile), "log/upload.%ld", test->testno);
  474. #ifdef WIN32
  475. test->ofile = open(outfile, O_CREAT|O_RDWR|O_BINARY, 0777);
  476. #else
  477. test->ofile = open(outfile, O_CREAT|O_RDWR, 0777);
  478. #endif
  479. if(test->ofile == -1) {
  480. logmsg("Couldn't create and/or open file %s for upload!", outfile);
  481. return -1; /* failure! */
  482. }
  483. }
  484. count = b->counter; /* remember byte count */
  485. b->counter = BF_FREE; /* reset flag */
  486. dp = &b->buf.hdr;
  487. nextone = !nextone; /* incr for next time */
  488. writebuf = dp->th_data;
  489. if(count <= 0)
  490. return -1; /* nak logic? */
  491. if(convert == 0)
  492. return write(test->ofile, writebuf, count);
  493. p = writebuf;
  494. ct = count;
  495. while(ct--) { /* loop over the buffer */
  496. c = *p++; /* pick up a character */
  497. if(prevchar == '\r') { /* if prev char was cr */
  498. if(c == '\n') /* if have cr,lf then just */
  499. lseek(test->ofile, -1, SEEK_CUR); /* smash lf on top of the cr */
  500. else
  501. if(c == '\0') /* if have cr,nul then */
  502. goto skipit; /* just skip over the putc */
  503. /* else just fall through and allow it */
  504. }
  505. /* formerly
  506. putc(c, file); */
  507. if(1 != write(test->ofile, &c, 1))
  508. break;
  509. skipit:
  510. prevchar = c;
  511. }
  512. return count;
  513. }
  514. /* When an error has occurred, it is possible that the two sides are out of
  515. * synch. Ie: that what I think is the other side's response to packet N is
  516. * really their response to packet N-1.
  517. *
  518. * So, to try to prevent that, we flush all the input queued up for us on the
  519. * network connection on our host.
  520. *
  521. * We return the number of packets we flushed (mostly for reporting when trace
  522. * is active).
  523. */
  524. static int synchnet(curl_socket_t f /* socket to flush */)
  525. {
  526. #if defined(HAVE_IOCTLSOCKET)
  527. unsigned long i;
  528. #else
  529. int i;
  530. #endif
  531. int j = 0;
  532. char rbuf[PKTSIZE];
  533. srvr_sockaddr_union_t fromaddr;
  534. curl_socklen_t fromaddrlen;
  535. for(;;) {
  536. #if defined(HAVE_IOCTLSOCKET)
  537. (void) ioctlsocket(f, FIONREAD, &i);
  538. #else
  539. (void) ioctl(f, FIONREAD, &i);
  540. #endif
  541. if(i) {
  542. j++;
  543. #ifdef ENABLE_IPV6
  544. if(!use_ipv6)
  545. #endif
  546. fromaddrlen = sizeof(fromaddr.sa4);
  547. #ifdef ENABLE_IPV6
  548. else
  549. fromaddrlen = sizeof(fromaddr.sa6);
  550. #endif
  551. (void) recvfrom(f, rbuf, sizeof(rbuf), 0,
  552. &fromaddr.sa, &fromaddrlen);
  553. }
  554. else
  555. break;
  556. }
  557. return j;
  558. }
  559. int main(int argc, char **argv)
  560. {
  561. srvr_sockaddr_union_t me;
  562. struct tftphdr *tp;
  563. ssize_t n = 0;
  564. int arg = 1;
  565. unsigned short port = DEFAULT_PORT;
  566. curl_socket_t sock = CURL_SOCKET_BAD;
  567. int flag;
  568. int rc;
  569. int error;
  570. long pid;
  571. struct testcase test;
  572. int result = 0;
  573. memset(&test, 0, sizeof(test));
  574. while(argc>arg) {
  575. if(!strcmp("--version", argv[arg])) {
  576. printf("tftpd IPv4%s\n",
  577. #ifdef ENABLE_IPV6
  578. "/IPv6"
  579. #else
  580. ""
  581. #endif
  582. );
  583. return 0;
  584. }
  585. else if(!strcmp("--pidfile", argv[arg])) {
  586. arg++;
  587. if(argc>arg)
  588. pidname = argv[arg++];
  589. }
  590. else if(!strcmp("--logfile", argv[arg])) {
  591. arg++;
  592. if(argc>arg)
  593. serverlogfile = argv[arg++];
  594. }
  595. else if(!strcmp("--ipv4", argv[arg])) {
  596. #ifdef ENABLE_IPV6
  597. ipv_inuse = "IPv4";
  598. use_ipv6 = FALSE;
  599. #endif
  600. arg++;
  601. }
  602. else if(!strcmp("--ipv6", argv[arg])) {
  603. #ifdef ENABLE_IPV6
  604. ipv_inuse = "IPv6";
  605. use_ipv6 = TRUE;
  606. #endif
  607. arg++;
  608. }
  609. else if(!strcmp("--port", argv[arg])) {
  610. arg++;
  611. if(argc>arg) {
  612. char *endptr;
  613. unsigned long ulnum = strtoul(argv[arg], &endptr, 10);
  614. if((endptr != argv[arg] + strlen(argv[arg])) ||
  615. (ulnum < 1025UL) || (ulnum > 65535UL)) {
  616. fprintf(stderr, "tftpd: invalid --port argument (%s)\n",
  617. argv[arg]);
  618. return 0;
  619. }
  620. port = curlx_ultous(ulnum);
  621. arg++;
  622. }
  623. }
  624. else if(!strcmp("--srcdir", argv[arg])) {
  625. arg++;
  626. if(argc>arg) {
  627. path = argv[arg];
  628. arg++;
  629. }
  630. }
  631. else {
  632. puts("Usage: tftpd [option]\n"
  633. " --version\n"
  634. " --logfile [file]\n"
  635. " --pidfile [file]\n"
  636. " --ipv4\n"
  637. " --ipv6\n"
  638. " --port [port]\n"
  639. " --srcdir [path]");
  640. return 0;
  641. }
  642. }
  643. #ifdef WIN32
  644. win32_init();
  645. atexit(win32_cleanup);
  646. #endif
  647. install_signal_handlers();
  648. pid = (long)getpid();
  649. #ifdef ENABLE_IPV6
  650. if(!use_ipv6)
  651. #endif
  652. sock = socket(AF_INET, SOCK_DGRAM, 0);
  653. #ifdef ENABLE_IPV6
  654. else
  655. sock = socket(AF_INET6, SOCK_DGRAM, 0);
  656. #endif
  657. if(CURL_SOCKET_BAD == sock) {
  658. error = SOCKERRNO;
  659. logmsg("Error creating socket: (%d) %s",
  660. error, strerror(error));
  661. result = 1;
  662. goto tftpd_cleanup;
  663. }
  664. flag = 1;
  665. if(0 != setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  666. (void *)&flag, sizeof(flag))) {
  667. error = SOCKERRNO;
  668. logmsg("setsockopt(SO_REUSEADDR) failed with error: (%d) %s",
  669. error, strerror(error));
  670. result = 1;
  671. goto tftpd_cleanup;
  672. }
  673. #ifdef ENABLE_IPV6
  674. if(!use_ipv6) {
  675. #endif
  676. memset(&me.sa4, 0, sizeof(me.sa4));
  677. me.sa4.sin_family = AF_INET;
  678. me.sa4.sin_addr.s_addr = INADDR_ANY;
  679. me.sa4.sin_port = htons(port);
  680. rc = bind(sock, &me.sa, sizeof(me.sa4));
  681. #ifdef ENABLE_IPV6
  682. }
  683. else {
  684. memset(&me.sa6, 0, sizeof(me.sa6));
  685. me.sa6.sin6_family = AF_INET6;
  686. me.sa6.sin6_addr = in6addr_any;
  687. me.sa6.sin6_port = htons(port);
  688. rc = bind(sock, &me.sa, sizeof(me.sa6));
  689. }
  690. #endif /* ENABLE_IPV6 */
  691. if(0 != rc) {
  692. error = SOCKERRNO;
  693. logmsg("Error binding socket on port %hu: (%d) %s",
  694. port, error, strerror(error));
  695. result = 1;
  696. goto tftpd_cleanup;
  697. }
  698. wrotepidfile = write_pidfile(pidname);
  699. if(!wrotepidfile) {
  700. result = 1;
  701. goto tftpd_cleanup;
  702. }
  703. logmsg("Running %s version on port UDP/%d", ipv_inuse, (int)port);
  704. for(;;) {
  705. fromlen = sizeof(from);
  706. #ifdef ENABLE_IPV6
  707. if(!use_ipv6)
  708. #endif
  709. fromlen = sizeof(from.sa4);
  710. #ifdef ENABLE_IPV6
  711. else
  712. fromlen = sizeof(from.sa6);
  713. #endif
  714. n = (ssize_t)recvfrom(sock, &buf.storage[0], sizeof(buf.storage), 0,
  715. &from.sa, &fromlen);
  716. if(got_exit_signal)
  717. break;
  718. if(n < 0) {
  719. logmsg("recvfrom");
  720. result = 3;
  721. break;
  722. }
  723. set_advisor_read_lock(SERVERLOGS_LOCK);
  724. serverlogslocked = 1;
  725. #ifdef ENABLE_IPV6
  726. if(!use_ipv6) {
  727. #endif
  728. from.sa4.sin_family = AF_INET;
  729. peer = socket(AF_INET, SOCK_DGRAM, 0);
  730. if(CURL_SOCKET_BAD == peer) {
  731. logmsg("socket");
  732. result = 2;
  733. break;
  734. }
  735. if(connect(peer, &from.sa, sizeof(from.sa4)) < 0) {
  736. logmsg("connect: fail");
  737. result = 1;
  738. break;
  739. }
  740. #ifdef ENABLE_IPV6
  741. }
  742. else {
  743. from.sa6.sin6_family = AF_INET6;
  744. peer = socket(AF_INET6, SOCK_DGRAM, 0);
  745. if(CURL_SOCKET_BAD == peer) {
  746. logmsg("socket");
  747. result = 2;
  748. break;
  749. }
  750. if(connect(peer, &from.sa, sizeof(from.sa6)) < 0) {
  751. logmsg("connect: fail");
  752. result = 1;
  753. break;
  754. }
  755. }
  756. #endif
  757. maxtimeout = 5*TIMEOUT;
  758. tp = &buf.hdr;
  759. tp->th_opcode = ntohs(tp->th_opcode);
  760. if(tp->th_opcode == opcode_RRQ || tp->th_opcode == opcode_WRQ) {
  761. memset(&test, 0, sizeof(test));
  762. if(do_tftp(&test, tp, n) < 0)
  763. break;
  764. free(test.buffer);
  765. }
  766. sclose(peer);
  767. peer = CURL_SOCKET_BAD;
  768. if(test.ofile > 0) {
  769. close(test.ofile);
  770. test.ofile = 0;
  771. }
  772. if(got_exit_signal)
  773. break;
  774. if(serverlogslocked) {
  775. serverlogslocked = 0;
  776. clear_advisor_read_lock(SERVERLOGS_LOCK);
  777. }
  778. logmsg("end of one transfer");
  779. }
  780. tftpd_cleanup:
  781. if(test.ofile > 0)
  782. close(test.ofile);
  783. if((peer != sock) && (peer != CURL_SOCKET_BAD))
  784. sclose(peer);
  785. if(sock != CURL_SOCKET_BAD)
  786. sclose(sock);
  787. if(got_exit_signal)
  788. logmsg("signalled to die");
  789. if(wrotepidfile)
  790. unlink(pidname);
  791. if(serverlogslocked) {
  792. serverlogslocked = 0;
  793. clear_advisor_read_lock(SERVERLOGS_LOCK);
  794. }
  795. restore_signal_handlers();
  796. if(got_exit_signal) {
  797. logmsg("========> %s tftpd (port: %d pid: %ld) exits with signal (%d)",
  798. ipv_inuse, (int)port, pid, exit_signal);
  799. /*
  800. * To properly set the return status of the process we
  801. * must raise the same signal SIGINT or SIGTERM that we
  802. * caught and let the old handler take care of it.
  803. */
  804. raise(exit_signal);
  805. }
  806. logmsg("========> tftpd quits");
  807. return result;
  808. }
  809. /*
  810. * Handle initial connection protocol.
  811. */
  812. static int do_tftp(struct testcase *test, struct tftphdr *tp, ssize_t size)
  813. {
  814. char *cp;
  815. int first = 1, ecode;
  816. struct formats *pf;
  817. char *filename, *mode = NULL;
  818. #ifdef USE_WINSOCK
  819. DWORD recvtimeout, recvtimeoutbak;
  820. #endif
  821. const char *option = "mode"; /* mode is implicit */
  822. int toggle = 1;
  823. /* Open request dump file. */
  824. FILE *server = fopen(REQUEST_DUMP, "ab");
  825. if(!server) {
  826. int error = errno;
  827. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  828. logmsg("Error opening file: %s", REQUEST_DUMP);
  829. return -1;
  830. }
  831. /* store input protocol */
  832. fprintf(server, "opcode: %x\n", tp->th_opcode);
  833. cp = (char *)&tp->th_stuff;
  834. filename = cp;
  835. do {
  836. bool endofit = true;
  837. while(cp < &buf.storage[size]) {
  838. if(*cp == '\0') {
  839. endofit = false;
  840. break;
  841. }
  842. cp++;
  843. }
  844. if(endofit)
  845. /* no more options */
  846. break;
  847. /* before increasing pointer, make sure it is still within the legal
  848. space */
  849. if((cp + 1) < &buf.storage[size]) {
  850. ++cp;
  851. if(first) {
  852. /* store the mode since we need it later */
  853. mode = cp;
  854. first = 0;
  855. }
  856. if(toggle)
  857. /* name/value pair: */
  858. fprintf(server, "%s: %s\n", option, cp);
  859. else {
  860. /* store the name pointer */
  861. option = cp;
  862. }
  863. toggle ^= 1;
  864. }
  865. else
  866. /* No more options */
  867. break;
  868. } while(1);
  869. if(*cp) {
  870. nak(EBADOP);
  871. fclose(server);
  872. return 3;
  873. }
  874. /* store input protocol */
  875. fprintf(server, "filename: %s\n", filename);
  876. for(cp = mode; cp && *cp; cp++)
  877. if(ISUPPER(*cp))
  878. *cp = (char)tolower((int)*cp);
  879. /* store input protocol */
  880. fclose(server);
  881. for(pf = formata; pf->f_mode; pf++)
  882. if(strcmp(pf->f_mode, mode) == 0)
  883. break;
  884. if(!pf->f_mode) {
  885. nak(EBADOP);
  886. return 2;
  887. }
  888. ecode = validate_access(test, filename, tp->th_opcode);
  889. if(ecode) {
  890. nak(ecode);
  891. return 1;
  892. }
  893. #ifdef USE_WINSOCK
  894. recvtimeout = sizeof(recvtimeoutbak);
  895. getsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
  896. (char *)&recvtimeoutbak, (int *)&recvtimeout);
  897. recvtimeout = TIMEOUT*1000;
  898. setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
  899. (const char *)&recvtimeout, sizeof(recvtimeout));
  900. #endif
  901. if(tp->th_opcode == opcode_WRQ)
  902. recvtftp(test, pf);
  903. else
  904. sendtftp(test, pf);
  905. #ifdef USE_WINSOCK
  906. recvtimeout = recvtimeoutbak;
  907. setsockopt(peer, SOL_SOCKET, SO_RCVTIMEO,
  908. (const char *)&recvtimeout, sizeof(recvtimeout));
  909. #endif
  910. return 0;
  911. }
  912. /* Based on the testno, parse the correct server commands. */
  913. static int parse_servercmd(struct testcase *req)
  914. {
  915. FILE *stream;
  916. char *filename;
  917. int error;
  918. filename = test2file(req->testno);
  919. stream = fopen(filename, "rb");
  920. if(!stream) {
  921. error = errno;
  922. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  923. logmsg(" [1] Error opening file: %s", filename);
  924. logmsg(" Couldn't open test file %ld", req->testno);
  925. return 1; /* done */
  926. }
  927. else {
  928. char *orgcmd = NULL;
  929. char *cmd = NULL;
  930. size_t cmdsize = 0;
  931. int num = 0;
  932. /* get the custom server control "commands" */
  933. error = getpart(&orgcmd, &cmdsize, "reply", "servercmd", stream);
  934. fclose(stream);
  935. if(error) {
  936. logmsg("getpart() failed with error: %d", error);
  937. return 1; /* done */
  938. }
  939. cmd = orgcmd;
  940. while(cmd && cmdsize) {
  941. char *check;
  942. if(1 == sscanf(cmd, "writedelay: %d", &num)) {
  943. logmsg("instructed to delay %d secs between packets", num);
  944. req->writedelay = num;
  945. }
  946. else {
  947. logmsg("Unknown <servercmd> instruction found: %s", cmd);
  948. }
  949. /* try to deal with CRLF or just LF */
  950. check = strchr(cmd, '\r');
  951. if(!check)
  952. check = strchr(cmd, '\n');
  953. if(check) {
  954. /* get to the letter following the newline */
  955. while((*check == '\r') || (*check == '\n'))
  956. check++;
  957. if(!*check)
  958. /* if we reached a zero, get out */
  959. break;
  960. cmd = check;
  961. }
  962. else
  963. break;
  964. }
  965. free(orgcmd);
  966. }
  967. return 0; /* OK! */
  968. }
  969. /*
  970. * Validate file access.
  971. */
  972. static int validate_access(struct testcase *test,
  973. const char *filename, int mode)
  974. {
  975. char *ptr;
  976. logmsg("trying to get file: %s mode %x", filename, mode);
  977. if(!strncmp("verifiedserver", filename, 14)) {
  978. char weare[128];
  979. size_t count = msnprintf(weare, sizeof(weare),
  980. "WE ROOLZ: %ld\r\n", (long)getpid());
  981. logmsg("Are-we-friendly question received");
  982. test->buffer = strdup(weare);
  983. test->rptr = test->buffer; /* set read pointer */
  984. test->bufsize = count; /* set total count */
  985. test->rcount = count; /* set data left to read */
  986. return 0; /* fine */
  987. }
  988. /* find the last slash */
  989. ptr = strrchr(filename, '/');
  990. if(ptr) {
  991. char partbuf[80]="data";
  992. long partno;
  993. long testno;
  994. char *file;
  995. ptr++; /* skip the slash */
  996. /* skip all non-numericals following the slash */
  997. while(*ptr && !ISDIGIT(*ptr))
  998. ptr++;
  999. /* get the number */
  1000. testno = strtol(ptr, &ptr, 10);
  1001. if(testno > 10000) {
  1002. partno = testno % 10000;
  1003. testno /= 10000;
  1004. }
  1005. else
  1006. partno = 0;
  1007. logmsg("requested test number %ld part %ld", testno, partno);
  1008. test->testno = testno;
  1009. (void)parse_servercmd(test);
  1010. file = test2file(testno);
  1011. if(0 != partno)
  1012. msnprintf(partbuf, sizeof(partbuf), "data%ld", partno);
  1013. if(file) {
  1014. FILE *stream = fopen(file, "rb");
  1015. if(!stream) {
  1016. int error = errno;
  1017. logmsg("fopen() failed with error: %d %s", error, strerror(error));
  1018. logmsg("Error opening file: %s", file);
  1019. logmsg("Couldn't open test file: %s", file);
  1020. return EACCESS;
  1021. }
  1022. else {
  1023. size_t count;
  1024. int error = getpart(&test->buffer, &count, "reply", partbuf, stream);
  1025. fclose(stream);
  1026. if(error) {
  1027. logmsg("getpart() failed with error: %d", error);
  1028. return EACCESS;
  1029. }
  1030. if(test->buffer) {
  1031. test->rptr = test->buffer; /* set read pointer */
  1032. test->bufsize = count; /* set total count */
  1033. test->rcount = count; /* set data left to read */
  1034. }
  1035. else
  1036. return EACCESS;
  1037. }
  1038. }
  1039. else
  1040. return EACCESS;
  1041. }
  1042. else {
  1043. logmsg("no slash found in path");
  1044. return EACCESS; /* failure */
  1045. }
  1046. logmsg("file opened and all is good");
  1047. return 0;
  1048. }
  1049. /*
  1050. * Send the requested file.
  1051. */
  1052. static void sendtftp(struct testcase *test, struct formats *pf)
  1053. {
  1054. int size;
  1055. ssize_t n;
  1056. /* These are volatile to live through a siglongjmp */
  1057. volatile unsigned short sendblock; /* block count */
  1058. struct tftphdr * volatile sdp = r_init(); /* data buffer */
  1059. struct tftphdr * const sap = &ackbuf.hdr; /* ack buffer */
  1060. sendblock = 1;
  1061. #if defined(HAVE_ALARM) && defined(SIGALRM)
  1062. mysignal(SIGALRM, timer);
  1063. #endif
  1064. do {
  1065. size = readit(test, (struct tftphdr **)&sdp, pf->f_convert);
  1066. if(size < 0) {
  1067. nak(errno + 100);
  1068. return;
  1069. }
  1070. sdp->th_opcode = htons((unsigned short)opcode_DATA);
  1071. sdp->th_block = htons(sendblock);
  1072. timeout = 0;
  1073. #ifdef HAVE_SIGSETJMP
  1074. (void) sigsetjmp(timeoutbuf, 1);
  1075. #endif
  1076. if(test->writedelay) {
  1077. logmsg("Pausing %d seconds before %d bytes", test->writedelay,
  1078. size);
  1079. wait_ms(1000*test->writedelay);
  1080. }
  1081. send_data:
  1082. if(swrite(peer, sdp, size + 4) != size + 4) {
  1083. logmsg("write");
  1084. return;
  1085. }
  1086. read_ahead(test, pf->f_convert);
  1087. for(;;) {
  1088. #ifdef HAVE_ALARM
  1089. alarm(rexmtval); /* read the ack */
  1090. #endif
  1091. n = sread(peer, &ackbuf.storage[0], sizeof(ackbuf.storage));
  1092. #ifdef HAVE_ALARM
  1093. alarm(0);
  1094. #endif
  1095. if(got_exit_signal)
  1096. return;
  1097. if(n < 0) {
  1098. logmsg("read: fail");
  1099. return;
  1100. }
  1101. sap->th_opcode = ntohs((unsigned short)sap->th_opcode);
  1102. sap->th_block = ntohs(sap->th_block);
  1103. if(sap->th_opcode == opcode_ERROR) {
  1104. logmsg("got ERROR");
  1105. return;
  1106. }
  1107. if(sap->th_opcode == opcode_ACK) {
  1108. if(sap->th_block == sendblock) {
  1109. break;
  1110. }
  1111. /* Re-synchronize with the other side */
  1112. (void) synchnet(peer);
  1113. if(sap->th_block == (sendblock-1)) {
  1114. goto send_data;
  1115. }
  1116. }
  1117. }
  1118. sendblock++;
  1119. } while(size == SEGSIZE);
  1120. }
  1121. /*
  1122. * Receive a file.
  1123. */
  1124. static void recvtftp(struct testcase *test, struct formats *pf)
  1125. {
  1126. ssize_t n, size;
  1127. /* These are volatile to live through a siglongjmp */
  1128. volatile unsigned short recvblock; /* block count */
  1129. struct tftphdr * volatile rdp; /* data buffer */
  1130. struct tftphdr *rap; /* ack buffer */
  1131. recvblock = 0;
  1132. rdp = w_init();
  1133. #if defined(HAVE_ALARM) && defined(SIGALRM)
  1134. mysignal(SIGALRM, timer);
  1135. #endif
  1136. rap = &ackbuf.hdr;
  1137. do {
  1138. timeout = 0;
  1139. rap->th_opcode = htons((unsigned short)opcode_ACK);
  1140. rap->th_block = htons(recvblock);
  1141. recvblock++;
  1142. #ifdef HAVE_SIGSETJMP
  1143. (void) sigsetjmp(timeoutbuf, 1);
  1144. #endif
  1145. send_ack:
  1146. if(swrite(peer, &ackbuf.storage[0], 4) != 4) {
  1147. logmsg("write: fail\n");
  1148. goto abort;
  1149. }
  1150. write_behind(test, pf->f_convert);
  1151. for(;;) {
  1152. #ifdef HAVE_ALARM
  1153. alarm(rexmtval);
  1154. #endif
  1155. n = sread(peer, rdp, PKTSIZE);
  1156. #ifdef HAVE_ALARM
  1157. alarm(0);
  1158. #endif
  1159. if(got_exit_signal)
  1160. goto abort;
  1161. if(n < 0) { /* really? */
  1162. logmsg("read: fail\n");
  1163. goto abort;
  1164. }
  1165. rdp->th_opcode = ntohs((unsigned short)rdp->th_opcode);
  1166. rdp->th_block = ntohs(rdp->th_block);
  1167. if(rdp->th_opcode == opcode_ERROR)
  1168. goto abort;
  1169. if(rdp->th_opcode == opcode_DATA) {
  1170. if(rdp->th_block == recvblock) {
  1171. break; /* normal */
  1172. }
  1173. /* Re-synchronize with the other side */
  1174. (void) synchnet(peer);
  1175. if(rdp->th_block == (recvblock-1))
  1176. goto send_ack; /* rexmit */
  1177. }
  1178. }
  1179. size = writeit(test, &rdp, (int)(n - 4), pf->f_convert);
  1180. if(size != (n-4)) { /* ahem */
  1181. if(size < 0)
  1182. nak(errno + 100);
  1183. else
  1184. nak(ENOSPACE);
  1185. goto abort;
  1186. }
  1187. } while(size == SEGSIZE);
  1188. write_behind(test, pf->f_convert);
  1189. rap->th_opcode = htons((unsigned short)opcode_ACK); /* send the "final"
  1190. ack */
  1191. rap->th_block = htons(recvblock);
  1192. (void) swrite(peer, &ackbuf.storage[0], 4);
  1193. #if defined(HAVE_ALARM) && defined(SIGALRM)
  1194. mysignal(SIGALRM, justtimeout); /* just abort read on timeout */
  1195. alarm(rexmtval);
  1196. #endif
  1197. /* normally times out and quits */
  1198. n = sread(peer, &buf.storage[0], sizeof(buf.storage));
  1199. #ifdef HAVE_ALARM
  1200. alarm(0);
  1201. #endif
  1202. if(got_exit_signal)
  1203. goto abort;
  1204. if(n >= 4 && /* if read some data */
  1205. rdp->th_opcode == opcode_DATA && /* and got a data block */
  1206. recvblock == rdp->th_block) { /* then my last ack was lost */
  1207. (void) swrite(peer, &ackbuf.storage[0], 4); /* resend final ack */
  1208. }
  1209. abort:
  1210. return;
  1211. }
  1212. /*
  1213. * Send a nak packet (error message). Error code passed in is one of the
  1214. * standard TFTP codes, or a Unix errno offset by 100.
  1215. */
  1216. static void nak(int error)
  1217. {
  1218. struct tftphdr *tp;
  1219. int length;
  1220. struct errmsg *pe;
  1221. tp = &buf.hdr;
  1222. tp->th_opcode = htons((unsigned short)opcode_ERROR);
  1223. tp->th_code = htons((unsigned short)error);
  1224. for(pe = errmsgs; pe->e_code >= 0; pe++)
  1225. if(pe->e_code == error)
  1226. break;
  1227. if(pe->e_code < 0) {
  1228. pe->e_msg = strerror(error - 100);
  1229. tp->th_code = EUNDEF; /* set 'undef' errorcode */
  1230. }
  1231. length = (int)strlen(pe->e_msg);
  1232. /* we use memcpy() instead of strcpy() in order to avoid buffer overflow
  1233. * report from glibc with FORTIFY_SOURCE */
  1234. memcpy(tp->th_msg, pe->e_msg, length + 1);
  1235. length += 5;
  1236. if(swrite(peer, &buf.storage[0], length) != length)
  1237. logmsg("nak: fail\n");
  1238. }