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