Deleted Added
full compact
tftpd.c (71926) tftpd.c (84047)
1/*
2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1983, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93";
43#endif
44static const char rcsid[] =
1/*
2 * Copyright (c) 1983, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#ifndef lint
35static const char copyright[] =
36"@(#) Copyright (c) 1983, 1993\n\
37 The Regents of the University of California. All rights reserved.\n";
38#endif /* not lint */
39
40#ifndef lint
41#if 0
42static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93";
43#endif
44static const char rcsid[] =
45 "$FreeBSD: head/libexec/tftpd/tftpd.c 71926 2001-02-02 10:53:02Z asmodai $";
45 "$FreeBSD: head/libexec/tftpd/tftpd.c 84047 2001-09-27 20:50:14Z obrien $";
46#endif /* not lint */
47
48/*
49 * Trivial file transfer protocol server.
50 *
51 * This version includes many modifications by Jim Guyton
52 * <guyton@rand-unix>.
53 */
54
55#include <sys/param.h>
56#include <sys/ioctl.h>
57#include <sys/stat.h>
58#include <sys/socket.h>
59#include <sys/types.h>
60
61#include <netinet/in.h>
62#include <arpa/tftp.h>
63#include <arpa/inet.h>
64
65#include <ctype.h>
66#include <errno.h>
67#include <fcntl.h>
68#include <libutil.h>
69#include <netdb.h>
70#include <pwd.h>
71#include <setjmp.h>
72#include <signal.h>
73#include <stdio.h>
74#include <stdlib.h>
75#include <string.h>
76#include <syslog.h>
77#include <unistd.h>
78
79#include "tftpsubs.h"
80
81#define TIMEOUT 5
46#endif /* not lint */
47
48/*
49 * Trivial file transfer protocol server.
50 *
51 * This version includes many modifications by Jim Guyton
52 * <guyton@rand-unix>.
53 */
54
55#include <sys/param.h>
56#include <sys/ioctl.h>
57#include <sys/stat.h>
58#include <sys/socket.h>
59#include <sys/types.h>
60
61#include <netinet/in.h>
62#include <arpa/tftp.h>
63#include <arpa/inet.h>
64
65#include <ctype.h>
66#include <errno.h>
67#include <fcntl.h>
68#include <libutil.h>
69#include <netdb.h>
70#include <pwd.h>
71#include <setjmp.h>
72#include <signal.h>
73#include <stdio.h>
74#include <stdlib.h>
75#include <string.h>
76#include <syslog.h>
77#include <unistd.h>
78
79#include "tftpsubs.h"
80
81#define TIMEOUT 5
82#define MAX_TIMEOUTS 5
82
83int peer;
84int rexmtval = TIMEOUT;
83
84int peer;
85int rexmtval = TIMEOUT;
85int maxtimeout = 5*TIMEOUT;
86int max_rexmtval = 2*TIMEOUT;
86
87#define PKTSIZE SEGSIZE+4
88char buf[PKTSIZE];
89char ackbuf[PKTSIZE];
90struct sockaddr_in from;
91int fromlen;
92
93void tftp __P((struct tftphdr *, int));
94
95/*
96 * Null-terminated directory prefix list for absolute pathname requests and
97 * search list for relative pathname requests.
98 *
99 * MAXDIRS should be at least as large as the number of arguments that
100 * inetd allows (currently 20).
101 */
102#define MAXDIRS 20
103static struct dirlist {
104 char *name;
105 int len;
106} dirs[MAXDIRS+1];
107static int suppress_naks;
108static int logging;
109static int ipchroot;
110
111static char *errtomsg __P((int));
112static void nak __P((int));
87
88#define PKTSIZE SEGSIZE+4
89char buf[PKTSIZE];
90char ackbuf[PKTSIZE];
91struct sockaddr_in from;
92int fromlen;
93
94void tftp __P((struct tftphdr *, int));
95
96/*
97 * Null-terminated directory prefix list for absolute pathname requests and
98 * search list for relative pathname requests.
99 *
100 * MAXDIRS should be at least as large as the number of arguments that
101 * inetd allows (currently 20).
102 */
103#define MAXDIRS 20
104static struct dirlist {
105 char *name;
106 int len;
107} dirs[MAXDIRS+1];
108static int suppress_naks;
109static int logging;
110static int ipchroot;
111
112static char *errtomsg __P((int));
113static void nak __P((int));
114static void oack __P(());
113
114int
115main(argc, argv)
116 int argc;
117 char *argv[];
118{
119 register struct tftphdr *tp;
120 register int n;
121 int ch, on;
122 struct sockaddr_in sin;
123 char *chroot_dir = NULL;
124 struct passwd *nobody;
125 char *chuser = "nobody";
126
127 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
128 while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
129 switch (ch) {
130 case 'c':
131 ipchroot = 1;
132 break;
133 case 'C':
134 ipchroot = 2;
135 break;
136 case 'l':
137 logging = 1;
138 break;
139 case 'n':
140 suppress_naks = 1;
141 break;
142 case 's':
143 chroot_dir = optarg;
144 break;
145 case 'u':
146 chuser = optarg;
147 break;
148 default:
149 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
150 }
151 }
152 if (optind < argc) {
153 struct dirlist *dirp;
154
155 /* Get list of directory prefixes. Skip relative pathnames. */
156 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
157 optind++) {
158 if (argv[optind][0] == '/') {
159 dirp->name = argv[optind];
160 dirp->len = strlen(dirp->name);
161 dirp++;
162 }
163 }
164 }
165 else if (chroot_dir) {
166 dirs->name = "/";
167 dirs->len = 1;
168 }
169 if (ipchroot && chroot_dir == NULL) {
170 syslog(LOG_ERR, "-c requires -s");
171 exit(1);
172 }
173
174 on = 1;
175 if (ioctl(0, FIONBIO, &on) < 0) {
176 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
177 exit(1);
178 }
179 fromlen = sizeof (from);
180 n = recvfrom(0, buf, sizeof (buf), 0,
181 (struct sockaddr *)&from, &fromlen);
182 if (n < 0) {
183 syslog(LOG_ERR, "recvfrom: %m");
184 exit(1);
185 }
186 /*
187 * Now that we have read the message out of the UDP
188 * socket, we fork and exit. Thus, inetd will go back
189 * to listening to the tftp port, and the next request
190 * to come in will start up a new instance of tftpd.
191 *
192 * We do this so that inetd can run tftpd in "wait" mode.
193 * The problem with tftpd running in "nowait" mode is that
194 * inetd may get one or more successful "selects" on the
195 * tftp port before we do our receive, so more than one
196 * instance of tftpd may be started up. Worse, if tftpd
197 * break before doing the above "recvfrom", inetd would
198 * spawn endless instances, clogging the system.
199 */
200 {
201 int pid;
202 int i, j;
203
204 for (i = 1; i < 20; i++) {
205 pid = fork();
206 if (pid < 0) {
207 sleep(i);
208 /*
209 * flush out to most recently sent request.
210 *
211 * This may drop some request, but those
212 * will be resent by the clients when
213 * they timeout. The positive effect of
214 * this flush is to (try to) prevent more
215 * than one tftpd being started up to service
216 * a single request from a single client.
217 */
218 j = sizeof from;
219 i = recvfrom(0, buf, sizeof (buf), 0,
220 (struct sockaddr *)&from, &j);
221 if (i > 0) {
222 n = i;
223 fromlen = j;
224 }
225 } else {
226 break;
227 }
228 }
229 if (pid < 0) {
230 syslog(LOG_ERR, "fork: %m");
231 exit(1);
232 } else if (pid != 0) {
233 exit(0);
234 }
235 }
236
237 /*
238 * Since we exit here, we should do that only after the above
239 * recvfrom to keep inetd from constantly forking should there
240 * be a problem. See the above comment about system clogging.
241 */
242 if (chroot_dir) {
243 if (ipchroot) {
244 char *tempchroot;
245 struct stat sb;
246 int statret;
247
248 tempchroot = inet_ntoa(from.sin_addr);
249 asprintf(&tempchroot, "%s/%s", chroot_dir, tempchroot);
250 statret = stat(tempchroot, &sb);
251 if ((sb.st_mode & S_IFDIR) &&
252 (statret == 0 || (statret == -1 && ipchroot == 1)))
253 chroot_dir = tempchroot;
254 }
255 /* Must get this before chroot because /etc might go away */
256 if ((nobody = getpwnam(chuser)) == NULL) {
257 syslog(LOG_ERR, "%s: no such user", chuser);
258 exit(1);
259 }
260 if (chroot(chroot_dir)) {
261 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
262 exit(1);
263 }
264 chdir( "/" );
265 setuid(nobody->pw_uid);
266 }
267
268 from.sin_family = AF_INET;
269 alarm(0);
270 close(0);
271 close(1);
272 peer = socket(AF_INET, SOCK_DGRAM, 0);
273 if (peer < 0) {
274 syslog(LOG_ERR, "socket: %m");
275 exit(1);
276 }
277 memset(&sin, 0, sizeof(sin));
278 sin.sin_family = AF_INET;
279 if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
280 syslog(LOG_ERR, "bind: %m");
281 exit(1);
282 }
283 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
284 syslog(LOG_ERR, "connect: %m");
285 exit(1);
286 }
287 tp = (struct tftphdr *)buf;
288 tp->th_opcode = ntohs(tp->th_opcode);
289 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
290 tftp(tp, n);
291 exit(1);
292}
293
294struct formats;
295int validate_access __P((char **, int));
296void xmitfile __P((struct formats *));
297void recvfile __P((struct formats *));
298
299struct formats {
300 char *f_mode;
301 int (*f_validate) __P((char **, int));
302 void (*f_send) __P((struct formats *));
303 void (*f_recv) __P((struct formats *));
304 int f_convert;
305} formats[] = {
306 { "netascii", validate_access, xmitfile, recvfile, 1 },
307 { "octet", validate_access, xmitfile, recvfile, 0 },
308#ifdef notdef
309 { "mail", validate_user, sendmail, recvmail, 1 },
310#endif
311 { 0 }
312};
313
115
116int
117main(argc, argv)
118 int argc;
119 char *argv[];
120{
121 register struct tftphdr *tp;
122 register int n;
123 int ch, on;
124 struct sockaddr_in sin;
125 char *chroot_dir = NULL;
126 struct passwd *nobody;
127 char *chuser = "nobody";
128
129 openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP);
130 while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
131 switch (ch) {
132 case 'c':
133 ipchroot = 1;
134 break;
135 case 'C':
136 ipchroot = 2;
137 break;
138 case 'l':
139 logging = 1;
140 break;
141 case 'n':
142 suppress_naks = 1;
143 break;
144 case 's':
145 chroot_dir = optarg;
146 break;
147 case 'u':
148 chuser = optarg;
149 break;
150 default:
151 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
152 }
153 }
154 if (optind < argc) {
155 struct dirlist *dirp;
156
157 /* Get list of directory prefixes. Skip relative pathnames. */
158 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
159 optind++) {
160 if (argv[optind][0] == '/') {
161 dirp->name = argv[optind];
162 dirp->len = strlen(dirp->name);
163 dirp++;
164 }
165 }
166 }
167 else if (chroot_dir) {
168 dirs->name = "/";
169 dirs->len = 1;
170 }
171 if (ipchroot && chroot_dir == NULL) {
172 syslog(LOG_ERR, "-c requires -s");
173 exit(1);
174 }
175
176 on = 1;
177 if (ioctl(0, FIONBIO, &on) < 0) {
178 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
179 exit(1);
180 }
181 fromlen = sizeof (from);
182 n = recvfrom(0, buf, sizeof (buf), 0,
183 (struct sockaddr *)&from, &fromlen);
184 if (n < 0) {
185 syslog(LOG_ERR, "recvfrom: %m");
186 exit(1);
187 }
188 /*
189 * Now that we have read the message out of the UDP
190 * socket, we fork and exit. Thus, inetd will go back
191 * to listening to the tftp port, and the next request
192 * to come in will start up a new instance of tftpd.
193 *
194 * We do this so that inetd can run tftpd in "wait" mode.
195 * The problem with tftpd running in "nowait" mode is that
196 * inetd may get one or more successful "selects" on the
197 * tftp port before we do our receive, so more than one
198 * instance of tftpd may be started up. Worse, if tftpd
199 * break before doing the above "recvfrom", inetd would
200 * spawn endless instances, clogging the system.
201 */
202 {
203 int pid;
204 int i, j;
205
206 for (i = 1; i < 20; i++) {
207 pid = fork();
208 if (pid < 0) {
209 sleep(i);
210 /*
211 * flush out to most recently sent request.
212 *
213 * This may drop some request, but those
214 * will be resent by the clients when
215 * they timeout. The positive effect of
216 * this flush is to (try to) prevent more
217 * than one tftpd being started up to service
218 * a single request from a single client.
219 */
220 j = sizeof from;
221 i = recvfrom(0, buf, sizeof (buf), 0,
222 (struct sockaddr *)&from, &j);
223 if (i > 0) {
224 n = i;
225 fromlen = j;
226 }
227 } else {
228 break;
229 }
230 }
231 if (pid < 0) {
232 syslog(LOG_ERR, "fork: %m");
233 exit(1);
234 } else if (pid != 0) {
235 exit(0);
236 }
237 }
238
239 /*
240 * Since we exit here, we should do that only after the above
241 * recvfrom to keep inetd from constantly forking should there
242 * be a problem. See the above comment about system clogging.
243 */
244 if (chroot_dir) {
245 if (ipchroot) {
246 char *tempchroot;
247 struct stat sb;
248 int statret;
249
250 tempchroot = inet_ntoa(from.sin_addr);
251 asprintf(&tempchroot, "%s/%s", chroot_dir, tempchroot);
252 statret = stat(tempchroot, &sb);
253 if ((sb.st_mode & S_IFDIR) &&
254 (statret == 0 || (statret == -1 && ipchroot == 1)))
255 chroot_dir = tempchroot;
256 }
257 /* Must get this before chroot because /etc might go away */
258 if ((nobody = getpwnam(chuser)) == NULL) {
259 syslog(LOG_ERR, "%s: no such user", chuser);
260 exit(1);
261 }
262 if (chroot(chroot_dir)) {
263 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
264 exit(1);
265 }
266 chdir( "/" );
267 setuid(nobody->pw_uid);
268 }
269
270 from.sin_family = AF_INET;
271 alarm(0);
272 close(0);
273 close(1);
274 peer = socket(AF_INET, SOCK_DGRAM, 0);
275 if (peer < 0) {
276 syslog(LOG_ERR, "socket: %m");
277 exit(1);
278 }
279 memset(&sin, 0, sizeof(sin));
280 sin.sin_family = AF_INET;
281 if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
282 syslog(LOG_ERR, "bind: %m");
283 exit(1);
284 }
285 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
286 syslog(LOG_ERR, "connect: %m");
287 exit(1);
288 }
289 tp = (struct tftphdr *)buf;
290 tp->th_opcode = ntohs(tp->th_opcode);
291 if (tp->th_opcode == RRQ || tp->th_opcode == WRQ)
292 tftp(tp, n);
293 exit(1);
294}
295
296struct formats;
297int validate_access __P((char **, int));
298void xmitfile __P((struct formats *));
299void recvfile __P((struct formats *));
300
301struct formats {
302 char *f_mode;
303 int (*f_validate) __P((char **, int));
304 void (*f_send) __P((struct formats *));
305 void (*f_recv) __P((struct formats *));
306 int f_convert;
307} formats[] = {
308 { "netascii", validate_access, xmitfile, recvfile, 1 },
309 { "octet", validate_access, xmitfile, recvfile, 0 },
310#ifdef notdef
311 { "mail", validate_user, sendmail, recvmail, 1 },
312#endif
313 { 0 }
314};
315
316struct options {
317 char *o_type;
318 char *o_request;
319 int o_reply; /* turn into union if need be */
320} options[] = {
321 { "tsize" }, /* OPT_TSIZE */
322 { "timeout" }, /* OPT_TIMEOUT */
323 { NULL }
324};
325
326enum opt_enum {
327 OPT_TSIZE = 0,
328 OPT_TIMEOUT,
329};
330
314/*
315 * Handle initial connection protocol.
316 */
317void
318tftp(tp, size)
319 struct tftphdr *tp;
320 int size;
321{
322 register char *cp;
331/*
332 * Handle initial connection protocol.
333 */
334void
335tftp(tp, size)
336 struct tftphdr *tp;
337 int size;
338{
339 register char *cp;
323 int first = 1, ecode;
340 int i, first = 1, has_options = 0, ecode;
324 register struct formats *pf;
341 register struct formats *pf;
325 char *filename, *mode;
342 char *filename, *mode, *option, *ccp;
326
327 filename = cp = tp->th_stuff;
328again:
329 while (cp < buf + size) {
330 if (*cp == '\0')
331 break;
332 cp++;
333 }
334 if (*cp != '\0') {
335 nak(EBADOP);
336 exit(1);
337 }
338 if (first) {
339 mode = ++cp;
340 first = 0;
341 goto again;
342 }
343 for (cp = mode; *cp; cp++)
344 if (isupper(*cp))
345 *cp = tolower(*cp);
346 for (pf = formats; pf->f_mode; pf++)
347 if (strcmp(pf->f_mode, mode) == 0)
348 break;
349 if (pf->f_mode == 0) {
350 nak(EBADOP);
351 exit(1);
352 }
343
344 filename = cp = tp->th_stuff;
345again:
346 while (cp < buf + size) {
347 if (*cp == '\0')
348 break;
349 cp++;
350 }
351 if (*cp != '\0') {
352 nak(EBADOP);
353 exit(1);
354 }
355 if (first) {
356 mode = ++cp;
357 first = 0;
358 goto again;
359 }
360 for (cp = mode; *cp; cp++)
361 if (isupper(*cp))
362 *cp = tolower(*cp);
363 for (pf = formats; pf->f_mode; pf++)
364 if (strcmp(pf->f_mode, mode) == 0)
365 break;
366 if (pf->f_mode == 0) {
367 nak(EBADOP);
368 exit(1);
369 }
370 while (++cp < buf + size) {
371 for (i = 2, ccp = cp; i > 0; ccp++) {
372 if (ccp >= buf + size) {
373 nak(EBADOP);
374 exit(1);
375 } else if (*ccp == '\0')
376 i--;
377 }
378 for (option = cp; *cp; cp++)
379 if (isupper(*cp))
380 *cp = tolower(*cp);
381 for (i = 0; options[i].o_type != NULL; i++)
382 if (strcmp(option, options[i].o_type) == 0) {
383 options[i].o_request = ++cp;
384 has_options = 1;
385 }
386 cp = ccp-1;
387 }
388
389 if (options[OPT_TIMEOUT].o_request) {
390 int to = atoi(options[OPT_TIMEOUT].o_request);
391 if (to < 1 || to > 255) {
392 nak(EBADOP);
393 exit(1);
394 }
395 else if (to <= max_rexmtval)
396 options[OPT_TIMEOUT].o_reply = rexmtval = to;
397 else
398 options[OPT_TIMEOUT].o_request = NULL;
399 }
400
353 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
401 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
402 if (has_options)
403 oack();
354 if (logging) {
355 char host[MAXHOSTNAMELEN];
356
357 realhostname(host, sizeof(host) - 1, &from.sin_addr);
358 host[sizeof(host) - 1] = '\0';
359 syslog(LOG_INFO, "%s: %s request for %s: %s", host,
360 tp->th_opcode == WRQ ? "write" : "read",
361 filename, errtomsg(ecode));
362 }
363 if (ecode) {
364 /*
365 * Avoid storms of naks to a RRQ broadcast for a relative
366 * bootfile pathname from a diskless Sun.
367 */
368 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
369 exit(0);
370 nak(ecode);
371 exit(1);
372 }
373 if (tp->th_opcode == WRQ)
374 (*pf->f_recv)(pf);
375 else
376 (*pf->f_send)(pf);
377 exit(0);
378}
379
380
381FILE *file;
382
383/*
384 * Validate file access. Since we
385 * have no uid or gid, for now require
386 * file to exist and be publicly
387 * readable/writable.
388 * If we were invoked with arguments
389 * from inetd then the file must also be
390 * in one of the given directory prefixes.
391 * Note also, full path name must be
392 * given as we have no login directory.
393 */
394int
395validate_access(filep, mode)
396 char **filep;
397 int mode;
398{
399 struct stat stbuf;
400 int fd;
401 struct dirlist *dirp;
402 static char pathname[MAXPATHLEN];
403 char *filename = *filep;
404
405 /*
406 * Prevent tricksters from getting around the directory restrictions
407 */
408 if (strstr(filename, "/../"))
409 return (EACCESS);
410
411 if (*filename == '/') {
412 /*
413 * Allow the request if it's in one of the approved locations.
414 * Special case: check the null prefix ("/") by looking
415 * for length = 1 and relying on the arg. processing that
416 * it's a /.
417 */
418 for (dirp = dirs; dirp->name != NULL; dirp++) {
419 if (dirp->len == 1 ||
420 (!strncmp(filename, dirp->name, dirp->len) &&
421 filename[dirp->len] == '/'))
422 break;
423 }
424 /* If directory list is empty, allow access to any file */
425 if (dirp->name == NULL && dirp != dirs)
426 return (EACCESS);
427 if (stat(filename, &stbuf) < 0)
428 return (errno == ENOENT ? ENOTFOUND : EACCESS);
429 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
430 return (ENOTFOUND);
431 if (mode == RRQ) {
432 if ((stbuf.st_mode & S_IROTH) == 0)
433 return (EACCESS);
434 } else {
435 if ((stbuf.st_mode & S_IWOTH) == 0)
436 return (EACCESS);
437 }
438 } else {
439 int err;
440
441 /*
442 * Relative file name: search the approved locations for it.
443 * Don't allow write requests that avoid directory
444 * restrictions.
445 */
446
447 if (!strncmp(filename, "../", 3))
448 return (EACCESS);
449
450 /*
451 * If the file exists in one of the directories and isn't
452 * readable, continue looking. However, change the error code
453 * to give an indication that the file exists.
454 */
455 err = ENOTFOUND;
456 for (dirp = dirs; dirp->name != NULL; dirp++) {
457 snprintf(pathname, sizeof(pathname), "%s/%s",
458 dirp->name, filename);
459 if (stat(pathname, &stbuf) == 0 &&
460 (stbuf.st_mode & S_IFMT) == S_IFREG) {
461 if ((stbuf.st_mode & S_IROTH) != 0) {
462 break;
463 }
464 err = EACCESS;
465 }
466 }
467 if (dirp->name == NULL)
468 return (err);
469 *filep = filename = pathname;
470 }
404 if (logging) {
405 char host[MAXHOSTNAMELEN];
406
407 realhostname(host, sizeof(host) - 1, &from.sin_addr);
408 host[sizeof(host) - 1] = '\0';
409 syslog(LOG_INFO, "%s: %s request for %s: %s", host,
410 tp->th_opcode == WRQ ? "write" : "read",
411 filename, errtomsg(ecode));
412 }
413 if (ecode) {
414 /*
415 * Avoid storms of naks to a RRQ broadcast for a relative
416 * bootfile pathname from a diskless Sun.
417 */
418 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
419 exit(0);
420 nak(ecode);
421 exit(1);
422 }
423 if (tp->th_opcode == WRQ)
424 (*pf->f_recv)(pf);
425 else
426 (*pf->f_send)(pf);
427 exit(0);
428}
429
430
431FILE *file;
432
433/*
434 * Validate file access. Since we
435 * have no uid or gid, for now require
436 * file to exist and be publicly
437 * readable/writable.
438 * If we were invoked with arguments
439 * from inetd then the file must also be
440 * in one of the given directory prefixes.
441 * Note also, full path name must be
442 * given as we have no login directory.
443 */
444int
445validate_access(filep, mode)
446 char **filep;
447 int mode;
448{
449 struct stat stbuf;
450 int fd;
451 struct dirlist *dirp;
452 static char pathname[MAXPATHLEN];
453 char *filename = *filep;
454
455 /*
456 * Prevent tricksters from getting around the directory restrictions
457 */
458 if (strstr(filename, "/../"))
459 return (EACCESS);
460
461 if (*filename == '/') {
462 /*
463 * Allow the request if it's in one of the approved locations.
464 * Special case: check the null prefix ("/") by looking
465 * for length = 1 and relying on the arg. processing that
466 * it's a /.
467 */
468 for (dirp = dirs; dirp->name != NULL; dirp++) {
469 if (dirp->len == 1 ||
470 (!strncmp(filename, dirp->name, dirp->len) &&
471 filename[dirp->len] == '/'))
472 break;
473 }
474 /* If directory list is empty, allow access to any file */
475 if (dirp->name == NULL && dirp != dirs)
476 return (EACCESS);
477 if (stat(filename, &stbuf) < 0)
478 return (errno == ENOENT ? ENOTFOUND : EACCESS);
479 if ((stbuf.st_mode & S_IFMT) != S_IFREG)
480 return (ENOTFOUND);
481 if (mode == RRQ) {
482 if ((stbuf.st_mode & S_IROTH) == 0)
483 return (EACCESS);
484 } else {
485 if ((stbuf.st_mode & S_IWOTH) == 0)
486 return (EACCESS);
487 }
488 } else {
489 int err;
490
491 /*
492 * Relative file name: search the approved locations for it.
493 * Don't allow write requests that avoid directory
494 * restrictions.
495 */
496
497 if (!strncmp(filename, "../", 3))
498 return (EACCESS);
499
500 /*
501 * If the file exists in one of the directories and isn't
502 * readable, continue looking. However, change the error code
503 * to give an indication that the file exists.
504 */
505 err = ENOTFOUND;
506 for (dirp = dirs; dirp->name != NULL; dirp++) {
507 snprintf(pathname, sizeof(pathname), "%s/%s",
508 dirp->name, filename);
509 if (stat(pathname, &stbuf) == 0 &&
510 (stbuf.st_mode & S_IFMT) == S_IFREG) {
511 if ((stbuf.st_mode & S_IROTH) != 0) {
512 break;
513 }
514 err = EACCESS;
515 }
516 }
517 if (dirp->name == NULL)
518 return (err);
519 *filep = filename = pathname;
520 }
521 if (options[OPT_TSIZE].o_request) {
522 if (mode == RRQ)
523 options[OPT_TSIZE].o_reply = stbuf.st_size;
524 else
525 /* XXX Allows writes of all sizes. */
526 options[OPT_TSIZE].o_reply =
527 atoi(options[OPT_TSIZE].o_request);
528 }
471 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
472 if (fd < 0)
473 return (errno + 100);
474 file = fdopen(fd, (mode == RRQ)? "r":"w");
475 if (file == NULL) {
476 return errno+100;
477 }
478 return (0);
479}
480
529 fd = open(filename, mode == RRQ ? O_RDONLY : O_WRONLY|O_TRUNC);
530 if (fd < 0)
531 return (errno + 100);
532 file = fdopen(fd, (mode == RRQ)? "r":"w");
533 if (file == NULL) {
534 return errno+100;
535 }
536 return (0);
537}
538
481int timeout;
539int timeouts;
482jmp_buf timeoutbuf;
483
484void
485timer()
486{
540jmp_buf timeoutbuf;
541
542void
543timer()
544{
487
488 timeout += rexmtval;
489 if (timeout >= maxtimeout)
545 if (++timeouts > MAX_TIMEOUTS)
490 exit(1);
491 longjmp(timeoutbuf, 1);
492}
493
494/*
495 * Send the requested file.
496 */
497void
498xmitfile(pf)
499 struct formats *pf;
500{
501 struct tftphdr *dp, *r_init();
502 register struct tftphdr *ap; /* ack packet */
503 register int size, n;
504 volatile unsigned short block;
505
506 signal(SIGALRM, timer);
507 dp = r_init();
508 ap = (struct tftphdr *)ackbuf;
509 block = 1;
510 do {
511 size = readit(file, &dp, pf->f_convert);
512 if (size < 0) {
513 nak(errno + 100);
514 goto abort;
515 }
516 dp->th_opcode = htons((u_short)DATA);
517 dp->th_block = htons((u_short)block);
546 exit(1);
547 longjmp(timeoutbuf, 1);
548}
549
550/*
551 * Send the requested file.
552 */
553void
554xmitfile(pf)
555 struct formats *pf;
556{
557 struct tftphdr *dp, *r_init();
558 register struct tftphdr *ap; /* ack packet */
559 register int size, n;
560 volatile unsigned short block;
561
562 signal(SIGALRM, timer);
563 dp = r_init();
564 ap = (struct tftphdr *)ackbuf;
565 block = 1;
566 do {
567 size = readit(file, &dp, pf->f_convert);
568 if (size < 0) {
569 nak(errno + 100);
570 goto abort;
571 }
572 dp->th_opcode = htons((u_short)DATA);
573 dp->th_block = htons((u_short)block);
518 timeout = 0;
574 timeouts = 0;
519 (void)setjmp(timeoutbuf);
520
521send_data:
522 if (send(peer, dp, size + 4, 0) != size + 4) {
523 syslog(LOG_ERR, "write: %m");
524 goto abort;
525 }
526 read_ahead(file, pf->f_convert);
527 for ( ; ; ) {
528 alarm(rexmtval); /* read the ack */
529 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
530 alarm(0);
531 if (n < 0) {
532 syslog(LOG_ERR, "read: %m");
533 goto abort;
534 }
535 ap->th_opcode = ntohs((u_short)ap->th_opcode);
536 ap->th_block = ntohs((u_short)ap->th_block);
537
538 if (ap->th_opcode == ERROR)
539 goto abort;
540
541 if (ap->th_opcode == ACK) {
542 if (ap->th_block == block)
543 break;
544 /* Re-synchronize with the other side */
545 (void) synchnet(peer);
546 if (ap->th_block == (block -1))
547 goto send_data;
548 }
549
550 }
551 block++;
552 } while (size == SEGSIZE);
553abort:
554 (void) fclose(file);
555}
556
557void
558justquit()
559{
560 exit(0);
561}
562
563
564/*
565 * Receive a file.
566 */
567void
568recvfile(pf)
569 struct formats *pf;
570{
571 struct tftphdr *dp, *w_init();
572 register struct tftphdr *ap; /* ack buffer */
573 register int n, size;
574 volatile unsigned short block;
575
576 signal(SIGALRM, timer);
577 dp = w_init();
578 ap = (struct tftphdr *)ackbuf;
579 block = 0;
580 do {
575 (void)setjmp(timeoutbuf);
576
577send_data:
578 if (send(peer, dp, size + 4, 0) != size + 4) {
579 syslog(LOG_ERR, "write: %m");
580 goto abort;
581 }
582 read_ahead(file, pf->f_convert);
583 for ( ; ; ) {
584 alarm(rexmtval); /* read the ack */
585 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
586 alarm(0);
587 if (n < 0) {
588 syslog(LOG_ERR, "read: %m");
589 goto abort;
590 }
591 ap->th_opcode = ntohs((u_short)ap->th_opcode);
592 ap->th_block = ntohs((u_short)ap->th_block);
593
594 if (ap->th_opcode == ERROR)
595 goto abort;
596
597 if (ap->th_opcode == ACK) {
598 if (ap->th_block == block)
599 break;
600 /* Re-synchronize with the other side */
601 (void) synchnet(peer);
602 if (ap->th_block == (block -1))
603 goto send_data;
604 }
605
606 }
607 block++;
608 } while (size == SEGSIZE);
609abort:
610 (void) fclose(file);
611}
612
613void
614justquit()
615{
616 exit(0);
617}
618
619
620/*
621 * Receive a file.
622 */
623void
624recvfile(pf)
625 struct formats *pf;
626{
627 struct tftphdr *dp, *w_init();
628 register struct tftphdr *ap; /* ack buffer */
629 register int n, size;
630 volatile unsigned short block;
631
632 signal(SIGALRM, timer);
633 dp = w_init();
634 ap = (struct tftphdr *)ackbuf;
635 block = 0;
636 do {
581 timeout = 0;
637 timeouts = 0;
582 ap->th_opcode = htons((u_short)ACK);
583 ap->th_block = htons((u_short)block);
584 block++;
585 (void) setjmp(timeoutbuf);
586send_ack:
587 if (send(peer, ackbuf, 4, 0) != 4) {
588 syslog(LOG_ERR, "write: %m");
589 goto abort;
590 }
591 write_behind(file, pf->f_convert);
592 for ( ; ; ) {
593 alarm(rexmtval);
594 n = recv(peer, dp, PKTSIZE, 0);
595 alarm(0);
596 if (n < 0) { /* really? */
597 syslog(LOG_ERR, "read: %m");
598 goto abort;
599 }
600 dp->th_opcode = ntohs((u_short)dp->th_opcode);
601 dp->th_block = ntohs((u_short)dp->th_block);
602 if (dp->th_opcode == ERROR)
603 goto abort;
604 if (dp->th_opcode == DATA) {
605 if (dp->th_block == block) {
606 break; /* normal */
607 }
608 /* Re-synchronize with the other side */
609 (void) synchnet(peer);
610 if (dp->th_block == (block-1))
611 goto send_ack; /* rexmit */
612 }
613 }
614 /* size = write(file, dp->th_data, n - 4); */
615 size = writeit(file, &dp, n - 4, pf->f_convert);
616 if (size != (n-4)) { /* ahem */
617 if (size < 0) nak(errno + 100);
618 else nak(ENOSPACE);
619 goto abort;
620 }
621 } while (size == SEGSIZE);
622 write_behind(file, pf->f_convert);
623 (void) fclose(file); /* close data file */
624
625 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
626 ap->th_block = htons((u_short)(block));
627 (void) send(peer, ackbuf, 4, 0);
628
629 signal(SIGALRM, justquit); /* just quit on timeout */
630 alarm(rexmtval);
631 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
632 alarm(0);
633 if (n >= 4 && /* if read some data */
634 dp->th_opcode == DATA && /* and got a data block */
635 block == dp->th_block) { /* then my last ack was lost */
636 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
637 }
638abort:
639 return;
640}
641
642struct errmsg {
643 int e_code;
644 char *e_msg;
645} errmsgs[] = {
646 { EUNDEF, "Undefined error code" },
647 { ENOTFOUND, "File not found" },
648 { EACCESS, "Access violation" },
649 { ENOSPACE, "Disk full or allocation exceeded" },
650 { EBADOP, "Illegal TFTP operation" },
651 { EBADID, "Unknown transfer ID" },
652 { EEXISTS, "File already exists" },
653 { ENOUSER, "No such user" },
638 ap->th_opcode = htons((u_short)ACK);
639 ap->th_block = htons((u_short)block);
640 block++;
641 (void) setjmp(timeoutbuf);
642send_ack:
643 if (send(peer, ackbuf, 4, 0) != 4) {
644 syslog(LOG_ERR, "write: %m");
645 goto abort;
646 }
647 write_behind(file, pf->f_convert);
648 for ( ; ; ) {
649 alarm(rexmtval);
650 n = recv(peer, dp, PKTSIZE, 0);
651 alarm(0);
652 if (n < 0) { /* really? */
653 syslog(LOG_ERR, "read: %m");
654 goto abort;
655 }
656 dp->th_opcode = ntohs((u_short)dp->th_opcode);
657 dp->th_block = ntohs((u_short)dp->th_block);
658 if (dp->th_opcode == ERROR)
659 goto abort;
660 if (dp->th_opcode == DATA) {
661 if (dp->th_block == block) {
662 break; /* normal */
663 }
664 /* Re-synchronize with the other side */
665 (void) synchnet(peer);
666 if (dp->th_block == (block-1))
667 goto send_ack; /* rexmit */
668 }
669 }
670 /* size = write(file, dp->th_data, n - 4); */
671 size = writeit(file, &dp, n - 4, pf->f_convert);
672 if (size != (n-4)) { /* ahem */
673 if (size < 0) nak(errno + 100);
674 else nak(ENOSPACE);
675 goto abort;
676 }
677 } while (size == SEGSIZE);
678 write_behind(file, pf->f_convert);
679 (void) fclose(file); /* close data file */
680
681 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
682 ap->th_block = htons((u_short)(block));
683 (void) send(peer, ackbuf, 4, 0);
684
685 signal(SIGALRM, justquit); /* just quit on timeout */
686 alarm(rexmtval);
687 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
688 alarm(0);
689 if (n >= 4 && /* if read some data */
690 dp->th_opcode == DATA && /* and got a data block */
691 block == dp->th_block) { /* then my last ack was lost */
692 (void) send(peer, ackbuf, 4, 0); /* resend final ack */
693 }
694abort:
695 return;
696}
697
698struct errmsg {
699 int e_code;
700 char *e_msg;
701} errmsgs[] = {
702 { EUNDEF, "Undefined error code" },
703 { ENOTFOUND, "File not found" },
704 { EACCESS, "Access violation" },
705 { ENOSPACE, "Disk full or allocation exceeded" },
706 { EBADOP, "Illegal TFTP operation" },
707 { EBADID, "Unknown transfer ID" },
708 { EEXISTS, "File already exists" },
709 { ENOUSER, "No such user" },
710 { EOPTNEG, "Option negotiation" },
654 { -1, 0 }
655};
656
657static char *
658errtomsg(error)
659 int error;
660{
661 static char buf[20];
662 register struct errmsg *pe;
663 if (error == 0)
664 return "success";
665 for (pe = errmsgs; pe->e_code >= 0; pe++)
666 if (pe->e_code == error)
667 return pe->e_msg;
668 snprintf(buf, sizeof(buf), "error %d", error);
669 return buf;
670}
671
672/*
673 * Send a nak packet (error message).
674 * Error code passed in is one of the
675 * standard TFTP codes, or a UNIX errno
676 * offset by 100.
677 */
678static void
679nak(error)
680 int error;
681{
682 register struct tftphdr *tp;
683 int length;
684 register struct errmsg *pe;
685
686 tp = (struct tftphdr *)buf;
687 tp->th_opcode = htons((u_short)ERROR);
688 tp->th_code = htons((u_short)error);
689 for (pe = errmsgs; pe->e_code >= 0; pe++)
690 if (pe->e_code == error)
691 break;
692 if (pe->e_code < 0) {
693 pe->e_msg = strerror(error - 100);
694 tp->th_code = EUNDEF; /* set 'undef' errorcode */
695 }
696 strcpy(tp->th_msg, pe->e_msg);
697 length = strlen(pe->e_msg);
698 tp->th_msg[length] = '\0';
699 length += 5;
700 if (send(peer, buf, length, 0) != length)
701 syslog(LOG_ERR, "nak: %m");
702}
711 { -1, 0 }
712};
713
714static char *
715errtomsg(error)
716 int error;
717{
718 static char buf[20];
719 register struct errmsg *pe;
720 if (error == 0)
721 return "success";
722 for (pe = errmsgs; pe->e_code >= 0; pe++)
723 if (pe->e_code == error)
724 return pe->e_msg;
725 snprintf(buf, sizeof(buf), "error %d", error);
726 return buf;
727}
728
729/*
730 * Send a nak packet (error message).
731 * Error code passed in is one of the
732 * standard TFTP codes, or a UNIX errno
733 * offset by 100.
734 */
735static void
736nak(error)
737 int error;
738{
739 register struct tftphdr *tp;
740 int length;
741 register struct errmsg *pe;
742
743 tp = (struct tftphdr *)buf;
744 tp->th_opcode = htons((u_short)ERROR);
745 tp->th_code = htons((u_short)error);
746 for (pe = errmsgs; pe->e_code >= 0; pe++)
747 if (pe->e_code == error)
748 break;
749 if (pe->e_code < 0) {
750 pe->e_msg = strerror(error - 100);
751 tp->th_code = EUNDEF; /* set 'undef' errorcode */
752 }
753 strcpy(tp->th_msg, pe->e_msg);
754 length = strlen(pe->e_msg);
755 tp->th_msg[length] = '\0';
756 length += 5;
757 if (send(peer, buf, length, 0) != length)
758 syslog(LOG_ERR, "nak: %m");
759}
760
761/*
762 * Send an oack packet (option acknowledgement).
763 */
764static void
765oack()
766{
767 struct tftphdr *tp, *ap;
768 int size, i, n;
769 char *bp;
770
771 tp = (struct tftphdr *)buf;
772 bp = buf + 2;
773 size = sizeof(buf) - 2;
774 tp->th_opcode = htons((u_short)OACK);
775 for (i = 0; options[i].o_type != NULL; i++) {
776 if (options[i].o_request) {
777 n = snprintf(bp, size, "%s%c%d", options[i].o_type,
778 0, options[i].o_reply);
779 bp += n+1;
780 size -= n+1;
781 if (size < 0) {
782 syslog(LOG_ERR, "oack: buffer overflow");
783 exit(1);
784 }
785 }
786 }
787 size = bp - buf;
788 ap = (struct tftphdr *)ackbuf;
789 signal(SIGALRM, timer);
790 timeouts = 0;
791
792 (void)setjmp(timeoutbuf);
793 if (send(peer, buf, size, 0) != size) {
794 syslog(LOG_INFO, "oack: %m");
795 exit(1);
796 }
797
798 for (;;) {
799 alarm(rexmtval);
800 n = recv(peer, ackbuf, sizeof (ackbuf), 0);
801 alarm(0);
802 if (n < 0) {
803 syslog(LOG_ERR, "recv: %m");
804 exit(1);
805 }
806 ap->th_opcode = ntohs((u_short)ap->th_opcode);
807 ap->th_block = ntohs((u_short)ap->th_block);
808 if (ap->th_opcode == ERROR)
809 exit(1);
810 if (ap->th_opcode == ACK && ap->th_block == 0)
811 break;
812 }
813}