]> git.saurik.com Git - apple/network_cmds.git/blob - kdumpd.tproj/kdumpd.c
a279c28d56d6e4a2a89df74a2799fbc27fff6282
[apple/network_cmds.git] / kdumpd.tproj / kdumpd.c
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
35 static 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 /* Mac OS X kernel core dump server, based on the BSD trivial file
41 * transfer protocol server (FreeBSD distribution), with several
42 * modifications. This server is *not* compatible with tftp, as the
43 * protocol has changed considerably.
44 */
45
46 /*
47 * Based on the trivial file transfer protocol server.
48 *
49 * The original version included many modifications by Jim Guyton
50 * <guyton@rand-unix>.
51 */
52
53 #include <sys/param.h>
54 #include <sys/ioctl.h>
55 #include <sys/stat.h>
56 #include <sys/socket.h>
57 #include <sys/types.h>
58
59 #include <netinet/in.h>
60 #include "kdump.h"
61 #include <arpa/inet.h>
62
63 #include <ctype.h>
64 #include <errno.h>
65 #include <fcntl.h>
66 #include <netdb.h>
67 #include <pwd.h>
68 #include <setjmp.h>
69 #include <signal.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <syslog.h>
74 #include <unistd.h>
75
76 #include "kdumpsubs.h"
77
78 #define TIMEOUT 5
79
80 int peer;
81 int rexmtval = TIMEOUT;
82 int maxtimeout = 10*TIMEOUT;
83
84 #define PKTSIZE SEGSIZE+6
85 char buf[PKTSIZE];
86 char ackbuf[PKTSIZE];
87 struct sockaddr_in from;
88 socklen_t fromlen;
89
90 void kdump __P((struct kdumphdr *, int));
91
92 /*
93 * Null-terminated directory prefix list for absolute pathname requests and
94 * search list for relative pathname requests.
95 *
96 * MAXDIRS should be at least as large as the number of arguments that
97 * inetd allows (currently 20).
98 */
99 #define MAXDIRS 20
100 static struct dirlist {
101 char *name;
102 int len;
103 } dirs[MAXDIRS+1];
104 static int suppress_naks;
105 static int logging = 1;
106 static int ipchroot;
107
108 static char *errtomsg __P((int));
109 static void nak __P((int));
110 static char * __P(verifyhost(struct sockaddr_in *));
111
112 int
113 main(argc, argv)
114 int argc;
115 char *argv[];
116 {
117 register struct kdumphdr *tp;
118 register int n;
119 int ch, on;
120 struct sockaddr_in sin;
121 char *chroot_dir = NULL;
122 struct passwd *nobody;
123 char *chuser = "nobody";
124
125 openlog("kdumpd", LOG_PID | LOG_NDELAY, LOG_FTP);
126 while ((ch = getopt(argc, argv, "cClns:u:")) != -1) {
127 switch (ch) {
128 case 'c':
129 ipchroot = 1;
130 break;
131 case 'C':
132 ipchroot = 2;
133 break;
134 case 'l':
135 logging = 1;
136 break;
137 case 'n':
138 suppress_naks = 1;
139 break;
140 case 's':
141 chroot_dir = optarg;
142 break;
143 case 'u':
144 chuser = optarg;
145 break;
146 default:
147 syslog(LOG_WARNING, "ignoring unknown option -%c", ch);
148 }
149 }
150
151 if (optind < argc) {
152 struct dirlist *dirp;
153
154 /* Get list of directory prefixes. Skip relative pathnames. */
155 for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS];
156 optind++) {
157 if (argv[optind][0] == '/') {
158 dirp->name = argv[optind];
159 dirp->len = strlen(dirp->name);
160 dirp++;
161 }
162 }
163 }
164 else if (chroot_dir) {
165 dirs->name = "/";
166 dirs->len = 1;
167 }
168 if (ipchroot && chroot_dir == NULL) {
169 syslog(LOG_ERR, "-c requires -s");
170 exit(1);
171 }
172
173 on = 1;
174 if (ioctl(0, FIONBIO, &on) < 0) {
175 syslog(LOG_ERR, "ioctl(FIONBIO): %m");
176 exit(1);
177 }
178 fromlen = sizeof (from);
179 n = recvfrom(0, buf, sizeof (buf), 0,
180 (struct sockaddr *)&from, &fromlen);
181 if (n < 0) {
182 syslog(LOG_ERR, "recvfrom: %m");
183 exit(1);
184 }
185 /*
186 * Now that we have read the message out of the UDP
187 * socket, we fork and exit. Thus, inetd will go back
188 * to listening to the kdump port, and the next request
189 * to come in will start up a new instance of kdumpd.
190 *
191 * We do this so that inetd can run kdumpd in "wait" mode.
192 * The problem with kdumpd running in "nowait" mode is that
193 * inetd may get one or more successful "selects" on the
194 * kdump port before we do our receive, so more than one
195 * instance of kdumpd may be started up. Worse, if kdumpd
196 * breaks before doing the above "recvfrom", inetd would
197 * spawn endless instances, clogging the system.
198 */
199 {
200 int pid;
201 int i;
202 socklen_t 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 requests, 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 kdumpd 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[MAXPATHLEN];
245 char *tempaddr;
246 struct stat sb;
247 int statret;
248
249 tempaddr = inet_ntoa(from.sin_addr);
250 snprintf(tempchroot, sizeof(tempchroot), "%s/%s", chroot_dir, tempaddr);
251 statret = stat(tempchroot, &sb);
252 if ((sb.st_mode & S_IFDIR) &&
253 (statret == 0 || (statret == -1 && ipchroot == 1)))
254 chroot_dir = tempchroot;
255 }
256 /* Must get this before chroot because /etc might go away */
257 if ((nobody = getpwnam(chuser)) == NULL) {
258 syslog(LOG_ERR, "%s: no such user", chuser);
259 exit(1);
260 }
261 if (chroot(chroot_dir)) {
262 syslog(LOG_ERR, "chroot: %s: %m", chroot_dir);
263 exit(1);
264 }
265 chdir( "/" );
266 setuid(nobody->pw_uid);
267 }
268 else
269 if (0 != chdir(dirs->name))
270 syslog(LOG_ERR, "chdir%s: %m", dirs->name);
271
272 from.sin_family = AF_INET;
273 alarm(0);
274 close(0);
275 close(1);
276 peer = socket(AF_INET, SOCK_DGRAM, 0);
277 if (peer < 0) {
278 syslog(LOG_ERR, "socket: %m");
279 exit(1);
280 }
281 memset(&sin, 0, sizeof(sin));
282 sin.sin_family = AF_INET;
283 if (bind(peer, (struct sockaddr *)&sin, sizeof (sin)) < 0) {
284 syslog(LOG_ERR, "bind: %m");
285 exit(1);
286 }
287 if (connect(peer, (struct sockaddr *)&from, sizeof(from)) < 0) {
288 syslog(LOG_ERR, "connect: %m");
289 exit(1);
290 }
291 tp = (struct kdumphdr *)buf;
292 tp->th_opcode = ntohs(tp->th_opcode);
293 if (tp->th_opcode == WRQ)
294 kdump(tp, n);
295 exit(1);
296 }
297
298 struct formats;
299 int validate_access __P((char **, int));
300
301 void recvfile __P((struct formats *));
302
303 struct formats {
304 char *f_mode;
305 int (*f_validate) __P((char **, int));
306
307 void (*f_recv) __P((struct formats *));
308 int f_convert;
309 } formats[] = {
310 { "netascii", validate_access, recvfile, 1 },
311 { "octet", validate_access, recvfile, 0 },
312 { 0 }
313 };
314
315 /*
316 * Handle initial connection protocol.
317 */
318 void
319 kdump(tp, size)
320 struct kdumphdr *tp;
321 int size;
322 {
323 register char *cp;
324 int first = 1, ecode;
325 register struct formats *pf;
326 char *filename, *mode = NULL;
327
328 filename = cp = tp->th_stuff;
329 again:
330 while (cp < buf + size) {
331 if (*cp == '\0')
332 break;
333 cp++;
334 }
335 if (*cp != '\0') {
336 nak(EBADOP);
337 exit(1);
338 }
339 if (first) {
340 mode = ++cp;
341 first = 0;
342 goto again;
343 }
344 for (cp = mode; *cp; cp++)
345 if (isupper(*cp))
346 *cp = tolower(*cp);
347 for (pf = formats; pf->f_mode; pf++)
348 if (strcmp(pf->f_mode, mode) == 0)
349 break;
350 if (pf->f_mode == 0) {
351 nak(EBADOP);
352 exit(1);
353 }
354 ecode = (*pf->f_validate)(&filename, tp->th_opcode);
355 if (logging) {
356 syslog(LOG_INFO, "%s: %s request for %s: %s", verifyhost(&from),
357 tp->th_opcode == WRQ ? "write" : "read",
358 filename, errtomsg(ecode));
359 }
360 if (ecode) {
361 /*
362 * Avoid storms of naks to a RRQ broadcast for a relative
363 * bootfile pathname from a diskless Sun.
364 */
365 if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
366 exit(0);
367 nak(ecode);
368 exit(1);
369 }
370 if (tp->th_opcode == WRQ)
371 (*pf->f_recv)(pf);
372
373 exit(0);
374 }
375
376
377 FILE *file;
378
379 /*
380 * Validate file access. We only allow storage of files that do not already
381 * exist, and that do not include directory specifiers in their pathnames.
382 * This is because kernel coredump filenames should always be of the form
383 * "core-version-IP as dotted quad-random string" as in :
384 * core-custom-17.202.40.204-a75b4eec
385 * The file is written to the directory supplied as the first argument
386 * in inetd.conf
387 */
388
389 int
390 validate_access(char **filep, int mode)
391 {
392 struct stat stbuf;
393 int fd;
394 char *filename = *filep;
395 static char pathname[MAXPATHLEN];
396
397 if (strstr(filename, "/") || strstr(filename, ".."))
398 return (EACCESS);
399
400 snprintf(pathname, sizeof(pathname), "./%s", filename);
401
402 if (0 == stat(pathname, &stbuf))
403 return (EEXIST);
404
405 if (errno != ENOENT)
406 return (errno);
407
408
409 fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC);
410
411 if (fd < 0)
412 return (errno + 100);
413
414 file = fdopen(fd, (mode == RRQ)? "r":"w");
415 if (file == NULL) {
416 return errno+100;
417 }
418 if (fchmod(fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP) < 0)
419 return errno+100;
420
421 return (0);
422 }
423
424 int timeout;
425 jmp_buf timeoutbuf;
426
427 void
428 timer()
429 {
430
431 timeout += rexmtval;
432 if (timeout >= maxtimeout)
433 {
434 longjmp(timeoutbuf, 2);
435 }
436 longjmp(timeoutbuf, 1);
437 }
438
439 void
440 justquit()
441 {
442 exit(0);
443 }
444
445
446 /*
447 * Receive a file.
448 */
449 void
450 recvfile(pf)
451 struct formats *pf;
452 {
453 struct kdumphdr *dp, *w_init();
454 register struct kdumphdr *ap; /* ack buffer */
455 register int n, size;
456 volatile unsigned int block;
457 volatile unsigned int jmpval = 0;
458
459 signal(SIGALRM, timer);
460 dp = w_init();
461 ap = (struct kdumphdr *)ackbuf;
462 block = 0;
463 do {
464 send_seek_ack: timeout = 0;
465 ap->th_opcode = htons((u_short)ACK);
466 ap->th_block = htonl((unsigned int)block);
467 block++;
468 jmpval = setjmp(timeoutbuf);
469 if (2 == jmpval)
470 {
471 syslog (LOG_ERR, "Timing out and flushing file to disk");
472 goto flushfile;
473 }
474 send_ack:
475 if (send(peer, ackbuf, 6 , 0) != 6) {
476 syslog(LOG_ERR, "write: %m");
477 goto abort;
478 }
479 write_behind(file, pf->f_convert);
480 for ( ; ; ) {
481 alarm(rexmtval);
482 n = recv(peer, dp, PKTSIZE, 0);
483 alarm(0);
484 if (n < 0) { /* really? */
485 syslog(LOG_ERR, "read: %m");
486 goto abort;
487 }
488 dp->th_opcode = ntohs((u_short)dp->th_opcode);
489 dp->th_block = ntohl((unsigned int)dp->th_block);
490 if (dp->th_opcode == ERROR)
491 goto abort;
492 if (dp->th_opcode == KDP_EOF)
493 {
494 syslog (LOG_ERR, "Received last panic dump packet");
495 goto final_ack;
496 }
497 if (dp->th_opcode == KDP_SEEK)
498 {
499 if (dp->th_block == block)
500 {
501 unsigned int tempoff = 0;
502 bcopy (dp->th_data, &tempoff, sizeof(unsigned int));
503 lseek (fileno (file), ntohl(tempoff), SEEK_SET);
504 if (errno)
505 syslog (LOG_ERR, "lseek: %m");
506
507 goto send_seek_ack;
508 }
509 (void) synchnet(peer);
510 if (dp->th_block == (block-1))
511 {
512 syslog (LOG_DAEMON|LOG_ERR, "Retransmitting seek ack - current block %hu, received block %hu", block, dp->th_block);
513 goto send_ack; /* rexmit */
514 }
515 }
516
517 if (dp->th_opcode == DATA) {
518 if (dp->th_block == block) {
519 break; /* normal */
520 }
521 /* Re-synchronize with the other side */
522 (void) synchnet(peer);
523 if (dp->th_block == (block-1))
524 {
525 syslog (LOG_DAEMON|LOG_ERR, "Retransmitting ack - current block %hu, received block %hu", block, dp->th_block);
526 goto send_ack; /* rexmit */
527 }
528 else
529 syslog (LOG_DAEMON|LOG_ERR, "Not retransmitting ack - current block %hu, received block %hu", block, dp->th_block);
530 }
531 }
532
533 size = writeit(file, &dp, n - 6, pf->f_convert);
534 if (size != (n-6)) { /* ahem */
535 if (size < 0) nak(errno + 100);
536 else nak(ENOSPACE);
537 goto abort;
538 }
539 } while (dp->th_opcode != KDP_EOF);
540
541 final_ack:
542 ap->th_opcode = htons((u_short)ACK); /* send the "final" ack */
543 ap->th_block = htonl((unsigned int) (block));
544 (void) send(peer, ackbuf, 6, 0);
545 flushfile:
546 write_behind(file, pf->f_convert);
547 (void) fclose(file); /* close data file */
548 syslog (LOG_ERR, "file closed, sending final ACK\n");
549
550 signal(SIGALRM, justquit); /* just quit on timeout */
551 alarm(rexmtval);
552 n = recv(peer, buf, sizeof (buf), 0); /* normally times out and quits */
553 alarm(0);
554 if (n >= 6 && /* if read some data */
555 dp->th_opcode == DATA && /* and got a data block */
556 block == dp->th_block) { /* then my last ack was lost */
557 (void) send(peer, ackbuf, 6, 0); /* resend final ack */
558 }
559 abort:
560 return;
561 }
562
563 struct errmsg {
564 int e_code;
565 char *e_msg;
566 } errmsgs[] = {
567 { EUNDEF, "Undefined error code" },
568 { ENOTFOUND, "File not found" },
569 { EACCESS, "Access violation" },
570 { ENOSPACE, "Disk full or allocation exceeded" },
571 { EBADOP, "Illegal KDUMP operation" },
572 { EBADID, "Unknown transfer ID" },
573 { EEXISTS, "File already exists" },
574 { ENOUSER, "No such user" },
575 { -1, 0 }
576 };
577
578 static char *
579 errtomsg(error)
580 int error;
581 {
582 static char buf[20];
583 register struct errmsg *pe;
584 if (error == 0)
585 return "success";
586 for (pe = errmsgs; pe->e_code >= 0; pe++)
587 if (pe->e_code == error)
588 return pe->e_msg;
589 snprintf(buf, sizeof(buf), "error %d", error);
590 return buf;
591 }
592
593 /*
594 * Send a nak packet (error message).
595 * Error code passed in is one of the
596 * standard KDUMP codes, or a UNIX errno
597 * offset by 100.
598 */
599 static void
600 nak(error)
601 int error;
602 {
603 register struct kdumphdr *tp;
604 int length;
605 register struct errmsg *pe;
606
607 tp = (struct kdumphdr *)buf;
608 tp->th_opcode = htons((u_short)ERROR);
609 tp->th_code = htons((unsigned int)error);
610 for (pe = errmsgs; pe->e_code >= 0; pe++)
611 if (pe->e_code == error)
612 break;
613 if (pe->e_code < 0) {
614 pe->e_msg = strerror(error - 100);
615 tp->th_code = EUNDEF; /* set 'undef' errorcode */
616 }
617 strcpy(tp->th_msg, pe->e_msg);
618 length = strlen(pe->e_msg);
619 tp->th_msg[length] = '\0';
620 length += 5;
621 if (send(peer, buf, length, 0) != length)
622 syslog(LOG_ERR, "nak: %m");
623 }
624
625 static char *
626 verifyhost(fromp)
627 struct sockaddr_in *fromp;
628 {
629 struct hostent *hp;
630
631 hp = gethostbyaddr((char *)&fromp->sin_addr, sizeof(fromp->sin_addr),
632 fromp->sin_family);
633 if(hp)
634 return hp->h_name;
635 else
636 return inet_ntoa(fromp->sin_addr);
637 }