Merge branch 'vendor/OPENSSL'
[dragonfly.git] / usr.bin / fstat / fstat.c
1 /*-
2  * Copyright (c) 1988, 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  * @(#) Copyright (c) 1988, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)fstat.c  8.3 (Berkeley) 5/2/95
35  * $FreeBSD: src/usr.bin/fstat/fstat.c,v 1.21.2.7 2001/11/21 10:49:37 dwmalone Exp $
36  * $DragonFly: src/usr.bin/fstat/fstat.c,v 1.26 2008/05/03 04:13:12 dillon Exp $
37  */
38
39 #include <sys/user.h>
40 #include <sys/param.h>
41 #include <sys/time.h>
42 #include <sys/stat.h>
43 #include <sys/vnode.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/domain.h>
47 #include <sys/protosw.h>
48 #include <sys/un.h>
49 #include <sys/unpcb.h>
50 #include <sys/sysctl.h>
51 #include <sys/filedesc.h>
52 #include <sys/queue.h>
53 #include <sys/pipe.h>
54 #include <sys/conf.h>
55 #include <sys/file.h>
56 #include <sys/ktrace.h>
57 #include <vfs/ufs/quota.h>
58 #include <vfs/ufs/inode.h>
59 #include <sys/mount.h>
60 #include <sys/namecache.h>
61 #include <nfs/nfsproto.h>
62 #include <nfs/rpcv2.h>
63 #include <nfs/nfs.h>
64 #include <nfs/nfsnode.h>
65
66
67 #include <vm/vm.h>
68 #include <vm/vm_map.h>
69 #include <vm/vm_object.h>
70
71 #include <net/route.h>
72 #include <netinet/in.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/ip.h>
75 #include <netinet/in_pcb.h>
76
77 #include <ctype.h>
78 #include <err.h>
79 #include <fcntl.h>
80 #include <kvm.h>
81 #include <limits.h>
82 #include <nlist.h>
83 #include <paths.h>
84 #include <pwd.h>
85 #include <stdio.h>
86 #include <stdlib.h>
87 #include <string.h>
88 #include <unistd.h>
89 #include <netdb.h>
90
91 #include "fstat.h"
92
93 #define TEXT    -1
94 #define CDIR    -2
95 #define RDIR    -3
96 #define TRACE   -4
97 #define MMAP    -5
98
99 DEVS *devs;
100
101 static void make_printable(char *buf, int len);
102
103 #ifdef notdef
104 struct nlist nl[] = {
105         { "" },
106 };
107 #endif
108
109 int     fsflg,  /* show files on same filesystem as file(s) argument */
110         pflg,   /* show files open by a particular pid */
111         uflg;   /* show files open by a particular (effective) user */
112 int     checkfile; /* true if restricting to particular files or filesystems */
113 int     nflg;   /* (numerical) display f.s. and rdev as dev_t */
114 int     vflg;   /* display errors in locating kernel data objects etc... */
115 int     mflg;   /* include memory-mapped files */
116 int     wflg_mnt = 16;
117 int     wflg_cmd = 10;
118 int     pid_width = 5;
119 int     ino_width = 6;
120
121
122 struct fdnode *ofiles;  /* buffer of pointers to file structures */
123 int maxfiles;
124
125 #define ALLOC_OFILES(d) \
126         if ((d) > maxfiles) { \
127                 free(ofiles); \
128                 ofiles = malloc((d) * sizeof(struct fdnode)); \
129                 if (ofiles == NULL) { \
130                         err(1, NULL); \
131                 } \
132                 maxfiles = (d); \
133         }
134
135 kvm_t *kd;
136
137 void dofiles(struct kinfo_proc *kp, struct proc *p);
138 void dommap(struct proc *p);
139 void vtrans(struct vnode *vp, struct nchandle *ncr, int i, int flag);
140 int  ufs_filestat(struct vnode *vp, struct filestat *fsp);
141 int  nfs_filestat(struct vnode *vp, struct filestat *fsp);
142 char *getmnton(struct mount *m, struct namecache_list *ncplist, struct nchandle *ncr);
143 void pipetrans(struct pipe *pi, int i, int flag);
144 void socktrans(struct socket *sock, int i);
145 void getinetproto(int number);
146 int  getfname(const char *filename);
147 void usage(void);
148
149
150 int
151 main(int argc, char **argv)
152 {
153         struct passwd *passwd;
154         struct kinfo_proc *p, *plast;
155         struct proc proc;
156         int arg, ch, what;
157         char *memf, *nlistf;
158         char buf[_POSIX2_LINE_MAX];
159         int cnt;
160
161         arg = 0;
162         what = KERN_PROC_ALL;
163         nlistf = memf = NULL;
164         while ((ch = getopt(argc, argv, "fmnp:u:vwN:M:")) != -1)
165                 switch((char)ch) {
166                 case 'f':
167                         fsflg = 1;
168                         break;
169                 case 'M':
170                         memf = optarg;
171                         break;
172                 case 'N':
173                         nlistf = optarg;
174                         break;
175                 case 'm':
176                         mflg = 1;
177                         break;
178                 case 'n':
179                         nflg = 1;
180                         break;
181                 case 'p':
182                         if (pflg++)
183                                 usage();
184                         if (!isdigit(*optarg)) {
185                                 warnx("-p requires a process id");
186                                 usage();
187                         }
188                         what = KERN_PROC_PID;
189                         arg = atoi(optarg);
190                         break;
191                 case 'u':
192                         if (uflg++)
193                                 usage();
194                         if (!(passwd = getpwnam(optarg)))
195                                 errx(1, "%s: unknown uid", optarg);
196                         what = KERN_PROC_UID;
197                         arg = passwd->pw_uid;
198                         break;
199                 case 'v':
200                         vflg = 1;
201                         break;
202                 case 'w':
203                         wflg_mnt = 40;
204                         wflg_cmd = 16;
205                         break;
206                 case '?':
207                 default:
208                         usage();
209                 }
210
211         if (*(argv += optind)) {
212                 for (; *argv; ++argv) {
213                         if (getfname(*argv))
214                                 checkfile = 1;
215                 }
216                 if (!checkfile) /* file(s) specified, but none accessable */
217                         exit(1);
218         }
219
220         ALLOC_OFILES(256);      /* reserve space for file pointers */
221
222         if (fsflg && !checkfile) {
223                 /* -f with no files means use wd */
224                 if (getfname(".") == 0)
225                         exit(1);
226                 checkfile = 1;
227         }
228
229         /*
230          * Discard setgid privileges if not the running kernel so that bad
231          * guys can't print interesting stuff from kernel memory.
232          */
233         if (nlistf != NULL || memf != NULL)
234                 setgid(getgid());
235
236         if ((kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, buf)) == NULL)
237                 errx(1, "%s", buf);
238 #ifdef notdef
239         if (kvm_nlist(kd, nl) != 0)
240                 errx(1, "no namelist: %s", kvm_geterr(kd));
241 #endif
242         if ((p = kvm_getprocs(kd, what, arg, &cnt)) == NULL)
243                 errx(1, "%s", kvm_geterr(kd));
244         if (nflg)
245                 printf("USER     %-*.*s %*.*s   FD DEV              %*.*s MODE   SZ|DV R/W", 
246                         wflg_cmd, wflg_cmd, "CMD",
247                         pid_width, pid_width, "PID",
248                         ino_width, ino_width, "INUM");
249         else
250                 printf("USER     %-*.*s %*.*s   FD %-*.*s %*.*s MODE           SZ|DV R/W", 
251                         wflg_cmd, wflg_cmd, "CMD", 
252                         pid_width, pid_width, "PID",
253                         wflg_mnt, wflg_mnt, "PATH",
254                         ino_width, ino_width, "INUM");
255         if (checkfile && fsflg == 0)
256                 printf(" NAME\n");
257         else
258                 putchar('\n');
259
260         for (plast = &p[cnt]; p < plast; ++p) {
261                 if (p->kp_stat == SZOMB)
262                         continue;
263                 if (!kread((void *)p->kp_paddr, &proc, sizeof(proc))) {
264                         dprintf(stderr, "can't read proc at %p for pid %d\n",
265                             (void *)p->kp_paddr, Pid);
266                         continue;
267                 }
268                 dofiles(p, &proc);
269                 if (mflg)
270                         dommap(&proc);
271         }
272         exit(0);
273 }
274
275 char    *Uname, *Comm;
276 int     Pid;
277
278 #define PREFIX(i) \
279         printf("%-8.8s %-*s %*d", Uname, wflg_cmd, Comm, pid_width, Pid); \
280         switch(i) { \
281         case TEXT: \
282                 printf(" text"); \
283                 break; \
284         case CDIR: \
285                 printf("   wd"); \
286                 break; \
287         case RDIR: \
288                 printf(" root"); \
289                 break; \
290         case TRACE: \
291                 printf("   tr"); \
292                 break; \
293         case MMAP: \
294                 printf(" mmap"); \
295                 break; \
296         default: \
297                 printf(" %4d", i); \
298                 break; \
299         }
300
301 /*
302  * print open files attributed to this process
303  */
304 void
305 dofiles(struct kinfo_proc *kp, struct proc *p)
306 {
307         int i;
308         struct file file;
309         struct filedesc filed;
310         struct ktrace_node ktrace_node;
311
312         Uname = user_from_uid(kp->kp_uid, 0);
313         Pid = kp->kp_pid;
314         Comm = kp->kp_comm;
315         make_printable(Comm, strlen(Comm));
316
317         if (p->p_fd == NULL)
318                 return;
319         if (!kread(p->p_fd, &filed, sizeof (filed))) {
320                 dprintf(stderr, "can't read filedesc at %p for pid %d\n",
321                     (void *)p->p_fd, Pid);
322                 return;
323         }
324         /*
325          * root directory vnode, if one
326          */
327         if (filed.fd_rdir)
328                 vtrans(filed.fd_rdir, &filed.fd_nrdir, RDIR, FREAD);
329         /*
330          * current working directory vnode
331          */
332         vtrans(filed.fd_cdir, &filed.fd_ncdir, CDIR, FREAD);
333         /*
334          * ktrace vnode, if one
335          */
336         if (p->p_tracenode) {
337                 if (kread(p->p_tracenode, &ktrace_node, sizeof (ktrace_node)))
338                         vtrans(ktrace_node.kn_vp, NULL, TRACE, FREAD|FWRITE);
339         }
340         /*
341          * text vnode, if one
342          */
343         if (p->p_textvp)
344                 vtrans(p->p_textvp, NULL, TEXT, FREAD);
345         /*
346          * open files
347          */
348         ALLOC_OFILES(filed.fd_lastfile+1);
349         if (!kread(filed.fd_files, ofiles,
350             (filed.fd_lastfile+1) * sizeof(struct fdnode))) {
351                 dprintf(stderr,
352                     "can't read file structures at %p for pid %d\n",
353                     (void *)filed.fd_files, Pid);
354                 return;
355         }
356         for (i = 0; i <= filed.fd_lastfile; i++) {
357                 if (ofiles[i].fp == NULL)
358                         continue;
359                 if (!kread(ofiles[i].fp, &file, sizeof (struct file))) {
360                         dprintf(stderr, "can't read file %d at %p for pid %d\n",
361                             i, (void *)ofiles[i].fp, Pid);
362                         continue;
363                 }
364                 if (file.f_type == DTYPE_VNODE) {
365                         vtrans((struct vnode *)file.f_data, &file.f_nchandle, i, 
366                                 file.f_flag);
367                 } else if (file.f_type == DTYPE_SOCKET) {
368                         if (checkfile == 0)
369                                 socktrans((struct socket *)file.f_data, i);
370                 }
371 #ifdef DTYPE_PIPE
372                 else if (file.f_type == DTYPE_PIPE) {
373                         if (checkfile == 0)
374                                 pipetrans((struct pipe *)file.f_data, i,
375                                     file.f_flag);
376                 }
377 #endif
378 #ifdef DTYPE_FIFO
379                 else if (file.f_type == DTYPE_FIFO) {
380                         if (checkfile == 0)
381                                 vtrans((struct vnode *)file.f_data, &file.f_nchandle,
382                                         i, file.f_flag);
383                 }
384 #endif
385                 else {
386                         dprintf(stderr,
387                             "unknown file type %d for file %d of pid %d\n",
388                             file.f_type, i, Pid);
389                 }
390         }
391 }
392
393 void
394 dommap(struct proc *p)
395 {
396         struct vmspace vmspace;
397         vm_map_t map;
398         struct vm_map_entry entry;
399         vm_map_entry_t entryp;
400         struct vm_object object;
401         vm_object_t objp;
402         int prot, fflags;
403
404         if (!kread(p->p_vmspace, &vmspace, sizeof(vmspace))) {
405                 dprintf(stderr, "can't read vmspace at %p for pid %d\n",
406                     (void *)p->p_vmspace, Pid);
407                 return;
408         }
409
410         map = &vmspace.vm_map;
411
412         for (entryp = map->header.next; entryp != &p->p_vmspace->vm_map.header;
413             entryp = entry.next) {
414                 if (!kread(entryp, &entry, sizeof(entry))) {
415                         dprintf(stderr,
416                             "can't read vm_map_entry at %p for pid %d\n",
417                             (void *)entryp, Pid);
418                         return;
419                 }
420
421                 if (entry.maptype == VM_MAPTYPE_SUBMAP)
422                         continue;
423
424                 if ((objp = entry.object.vm_object) == NULL)
425                         continue;
426
427                 for (; objp; objp = object.backing_object) {
428                         if (!kread(objp, &object, sizeof(object))) {
429                                 dprintf(stderr,
430                                     "can't read vm_object at %p for pid %d\n",
431                                     (void *)objp, Pid);
432                                 return;
433                         }
434                 }
435
436                 prot = entry.protection;
437                 fflags = (prot & VM_PROT_READ ? FREAD : 0) |
438                     (prot & VM_PROT_WRITE ? FWRITE : 0);
439
440                 switch (object.type) {
441                 case OBJT_VNODE:
442                         vtrans((struct vnode *)object.handle, NULL, 
443                                 MMAP, fflags);
444                         break;
445                 default:
446                         break;
447                 }
448         }
449 }
450
451 void
452 vtrans(struct vnode *vp, struct nchandle *ncr, int i, int flag)
453 {
454         struct vnode vn;
455         struct filestat fst;
456         char rw[3], mode[15];
457         const char *badtype = NULL, *filename;
458
459         filename = badtype = NULL;
460         if (!kread(vp, &vn, sizeof (struct vnode))) {
461                 dprintf(stderr, "can't read vnode at %p for pid %d\n",
462                     (void *)vp, Pid);
463                 return;
464         }
465         if (vn.v_type == VNON || vn.v_tag == VT_NON)
466                 badtype = "none";
467         else if (vn.v_type == VBAD)
468                 badtype = "bad";
469         else
470                 switch (vn.v_tag) {
471                 case VT_UFS:
472                         if (!ufs_filestat(&vn, &fst))
473                                 badtype = "error";
474                         break;
475                 case VT_MFS:
476                         if (!ufs_filestat(&vn, &fst))
477                                 badtype = "error";
478                         break;
479                 case VT_NFS:
480                         if (!nfs_filestat(&vn, &fst))
481                                 badtype = "error";
482                         break;
483
484                 case VT_MSDOSFS:
485                         if (!msdosfs_filestat(&vn, &fst))
486                                 badtype = "error";
487                         break;
488
489                 case VT_ISOFS:
490                         if (!isofs_filestat(&vn, &fst))
491                                 badtype = "error";
492                         break;
493
494                 default: {
495                         static char unknown[10];
496                         sprintf(unknown, "?(%x)", vn.v_tag);
497                         badtype=unknown;
498                         break;
499                 }
500         }
501         if (checkfile) {
502                 int fsmatch = 0;
503                 DEVS *d;
504
505                 if (badtype)
506                         return;
507                 for (d = devs; d != NULL; d = d->next)
508                         if (d->fsid == fst.fsid) {
509                                 fsmatch = 1;
510                                 if (d->ino == (ino_t)fst.fileid) {
511                                         filename = d->name;
512                                         break;
513                                 }
514                         }
515                 if (fsmatch == 0 || (filename == NULL && fsflg == 0))
516                         return;
517         }
518         PREFIX(i);
519         if (badtype) {
520                 (void)printf(" %-*s  %10s    -\n", 
521                              wflg_mnt,
522                              getmnton(vn.v_mount, &vn.v_namecache, ncr),
523                              badtype);
524                 return;
525         }
526         if (nflg)
527                 (void)printf(" %3d,%-9d   ", major(fst.fsid), minor(fst.fsid));
528         else
529                 (void)printf(" %-*s", wflg_mnt, getmnton(vn.v_mount, &vn.v_namecache, ncr));
530         if (nflg)
531                 (void)sprintf(mode, "%o", fst.mode);
532         else
533                 strmode(fst.mode, mode);
534         (void)printf(" %*ld %10s", ino_width, fst.fileid, mode);
535         switch (vn.v_type) {
536         case VBLK:
537         case VCHR: {
538                 char *name;
539
540                 if (nflg || ((name = devname(fst.rdev, vn.v_type == VCHR ?
541                     S_IFCHR : S_IFBLK)) == NULL))
542                         printf(" %3d,%-4d", major(fst.rdev), minor(fst.rdev));
543                 else
544                         printf(" %8s", name);
545                 break;
546         }
547         default:
548                 printf(" %8llu", fst.size);
549         }
550         rw[0] = '\0';
551         if (flag & FREAD)
552                 strcat(rw, "r");
553         if (flag & FWRITE)
554                 strcat(rw, "w");
555         printf(" %2s", rw);
556         if (filename && !fsflg)
557                 printf("  %s", filename);
558         putchar('\n');
559 }
560
561 int
562 ufs_filestat(struct vnode *vp, struct filestat *fsp)
563 {
564         struct inode inode;
565
566         if (!kread(VTOI(vp), &inode, sizeof (inode))) {
567                 dprintf(stderr, "can't read inode at %p for pid %d\n",
568                     (void *)VTOI(vp), Pid);
569                 return 0;
570         }
571         /*
572          * The st_dev from stat(2) is a udev_t. These kernel structures
573          * contain dev_t structures. We need to convert to udev to make
574          * comparisons
575          */
576         fsp->fsid = dev2udev(inode.i_dev);
577         fsp->fileid = (long)inode.i_number;
578         fsp->mode = (mode_t)inode.i_mode;
579         fsp->size = inode.i_size;
580         fsp->rdev = inode.i_rdev;
581
582         return 1;
583 }
584
585 int
586 nfs_filestat(struct vnode *vp, struct filestat *fsp)
587 {
588         struct nfsnode nfsnode;
589         mode_t mode;
590
591         if (!kread(VTONFS(vp), &nfsnode, sizeof (nfsnode))) {
592                 dprintf(stderr, "can't read nfsnode at %p for pid %d\n",
593                     (void *)VTONFS(vp), Pid);
594                 return 0;
595         }
596         fsp->fsid = nfsnode.n_vattr.va_fsid;
597         fsp->fileid = nfsnode.n_vattr.va_fileid;
598         fsp->size = nfsnode.n_size;
599         fsp->rdev = makeudev(nfsnode.n_vattr.va_rmajor,
600                              nfsnode.n_vattr.va_rminor);
601         mode = (mode_t)nfsnode.n_vattr.va_mode;
602         switch (vp->v_type) {
603         case VREG:
604                 mode |= S_IFREG;
605                 break;
606         case VDIR:
607                 mode |= S_IFDIR;
608                 break;
609         case VBLK:
610                 mode |= S_IFBLK;
611                 break;
612         case VCHR:
613                 mode |= S_IFCHR;
614                 break;
615         case VLNK:
616                 mode |= S_IFLNK;
617                 break;
618         case VSOCK:
619                 mode |= S_IFSOCK;
620                 break;
621         case VFIFO:
622                 mode |= S_IFIFO;
623                 break;
624         case VDATABASE:
625                 break;
626         case VNON:
627         case VBAD:
628                 return 0;
629         };
630         fsp->mode = mode;
631
632         return 1;
633 }
634
635
636 char *
637 getmnton(struct mount *m, struct namecache_list *ncplist, struct nchandle *ncr)
638 {
639         static struct mount mount_l;
640         static struct mtab {
641                 struct mtab *next;
642                 struct mount *m;
643                 char mntonname[MNAMELEN];
644         } *mhead = NULL;
645         struct mtab *mt;
646         struct namecache *ncp;
647         struct namecache ncp_copy;
648         static char path[1024];
649         int i;
650
651         /*
652          * If no ncp is passed try to find one via ncplist.  Make sure
653          * we are using the correct mount pointer or the matching code
654          * will not know how to transition mount points properly.
655          */
656         if (ncr == NULL || ncr->ncp == NULL) {
657                 ncp = ncplist->tqh_first;
658         } else {
659                 ncp = ncr->ncp;
660                 if (ncr->mount)
661                         m = ncr->mount;
662         }
663
664         /*
665          * If we have an ncp, traceback the path.  This is a kvm pointer.
666          */
667         if (ncp) {
668                 if (!kread(m, &mount_l, sizeof(struct mount))) {
669                         warnx("can't read mount table at %p", (void *)m);
670                         return (NULL);
671                 }
672                 i = sizeof(path) - 1;
673                 path[i] = 0;
674                 while (ncp) {
675                         /*
676                          * If this is the root of the mount then traverse
677                          * to the parent mount.
678                          */
679                         if (ncp == mount_l.mnt_ncmountpt.ncp) {
680                                 ncp = mount_l.mnt_ncmounton.ncp;
681                                 if (ncp == NULL)
682                                         break;
683                                 m = mount_l.mnt_ncmounton.mount;
684                                 if (!kread(m, &mount_l, sizeof(struct mount))) {
685                                         warnx("can't read mount table at %p", (void *)m);
686                                         return (NULL);
687                                 }
688                         }
689
690                         /*
691                          * Ok, pull out the ncp and extract the name
692                          */
693                         if (!kread(ncp, &ncp_copy, sizeof(ncp_copy))) {
694                                 warnx("can't read ncp at %p", ncp);
695                                 return (NULL);
696                         }
697                         if (i <= ncp_copy.nc_nlen)
698                                 break;
699                         i -= ncp_copy.nc_nlen;
700                         if (!kread(ncp_copy.nc_name, path + i, ncp_copy.nc_nlen)) {
701                                 warnx("can't read ncp %p path component at %p", ncp, ncp_copy.nc_name);
702                                 return (NULL);
703                         }
704                         make_printable(path + i, ncp_copy.nc_nlen);
705                         path[--i] = '/';
706                         ncp = ncp_copy.nc_parent;
707                 }
708                 if (i == sizeof(path) - 1)
709                         path[--i] = '/';
710                 return(path + i);
711         }
712
713         /*
714          * If all else fails print out the mount point path
715          */
716         for (mt = mhead; mt != NULL; mt = mt->next) {
717                 if (m == mt->m)
718                         return (mt->mntonname);
719         }
720         if (!kread(m, &mount_l, sizeof(struct mount))) {
721                 warnx("can't read mount table at %p", (void *)m);
722                 return (NULL);
723         }
724         if ((mt = malloc(sizeof (struct mtab))) == NULL)
725                 err(1, NULL);
726         mt->m = m;
727         bcopy(&mount_l.mnt_stat.f_mntonname[0], &mt->mntonname[0], MNAMELEN);
728         mt->next = mhead;
729         mhead = mt;
730         return (mt->mntonname);
731 }
732
733 void
734 pipetrans(struct pipe *pi, int i, int flag)
735 {
736         struct pipe pip;
737         char rw[3];
738
739         PREFIX(i);
740
741         /* fill in socket */
742         if (!kread(pi, &pip, sizeof(struct pipe))) {
743                 dprintf(stderr, "can't read pipe at %p\n", (void *)pi);
744                 goto bad;
745         }
746
747         printf("* pipe %8lx <-> %8lx", (u_long)pi, (u_long)pip.pipe_peer);
748         printf(" %6d", (int)(pip.pipe_buffer.windex - pip.pipe_buffer.rindex));
749         rw[0] = '\0';
750         if (flag & FREAD)
751                 strcat(rw, "r");
752         if (flag & FWRITE)
753                 strcat(rw, "w");
754         printf(" %2s", rw);
755         putchar('\n');
756         return;
757
758 bad:
759         printf("* error\n");
760 }
761
762 void
763 socktrans(struct socket *sock, int i)
764 {
765         static const char *stypename[] = {
766                 "unused",       /* 0 */
767                 "stream",       /* 1 */
768                 "dgram",        /* 2 */
769                 "raw",          /* 3 */
770                 "rdm",          /* 4 */
771                 "seqpak"        /* 5 */
772         };
773 #define STYPEMAX 5
774         struct socket   so;
775         struct protosw  proto;
776         struct domain   dom;
777         struct inpcb    inpcb;
778         struct unpcb    unpcb;
779         int len;
780         char dname[32];
781
782         PREFIX(i);
783
784         /* fill in socket */
785         if (!kread(sock, &so, sizeof(struct socket))) {
786                 dprintf(stderr, "can't read sock at %p\n", (void *)sock);
787                 goto bad;
788         }
789
790         /* fill in protosw entry */
791         if (!kread(so.so_proto, &proto, sizeof(struct protosw))) {
792                 dprintf(stderr, "can't read protosw at %p",
793                     (void *)so.so_proto);
794                 goto bad;
795         }
796
797         /* fill in domain */
798         if (!kread(proto.pr_domain, &dom, sizeof(struct domain))) {
799                 dprintf(stderr, "can't read domain at %p\n",
800                     (const void *)proto.pr_domain);
801                 goto bad;
802         }
803
804         if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
805             sizeof(dname) - 1)) < 0) {
806                 dprintf(stderr, "can't read domain name at %p\n",
807                     (void *)dom.dom_name);
808                 dname[0] = '\0';
809         }
810         else
811                 dname[len] = '\0';
812
813         if ((u_short)so.so_type > STYPEMAX)
814                 printf("* %s ?%d", dname, so.so_type);
815         else
816                 printf("* %s %s", dname, stypename[so.so_type]);
817
818         /*
819          * protocol specific formatting
820          *
821          * Try to find interesting things to print.  For tcp, the interesting
822          * thing is the address of the tcpcb, for udp and others, just the
823          * inpcb (socket pcb).  For unix domain, its the address of the socket
824          * pcb and the address of the connected pcb (if connected).  Otherwise
825          * just print the protocol number and address of the socket itself.
826          * The idea is not to duplicate netstat, but to make available enough
827          * information for further analysis.
828          */
829         switch(dom.dom_family) {
830         case AF_INET:
831         case AF_INET6:
832                 getinetproto(proto.pr_protocol);
833                 if (proto.pr_protocol == IPPROTO_TCP ) {
834                         if (so.so_pcb) {
835                                 if (kvm_read(kd, (u_long)so.so_pcb,
836                                     (char *)&inpcb, sizeof(struct inpcb))
837                                     != sizeof(struct inpcb)) {
838                                         dprintf(stderr,
839                                             "can't read inpcb at %p\n",
840                                             (void *)so.so_pcb);
841                                         goto bad;
842                                 }
843                                 printf(" %lx", (u_long)inpcb.inp_ppcb);
844                         }
845                 }
846                 else if (so.so_pcb)
847                         printf(" %lx", (u_long)so.so_pcb);
848                 break;
849         case AF_UNIX:
850                 /* print address of pcb and connected pcb */
851                 if (so.so_pcb) {
852                         printf(" %lx", (u_long)so.so_pcb);
853                         if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
854                             sizeof(struct unpcb)) != sizeof(struct unpcb)){
855                                 dprintf(stderr, "can't read unpcb at %p\n",
856                                     (void *)so.so_pcb);
857                                 goto bad;
858                         }
859                         if (unpcb.unp_conn) {
860                                 char shoconn[4], *cp;
861
862                                 cp = shoconn;
863                                 if (!(so.so_state & SS_CANTRCVMORE))
864                                         *cp++ = '<';
865                                 *cp++ = '-';
866                                 if (!(so.so_state & SS_CANTSENDMORE))
867                                         *cp++ = '>';
868                                 *cp = '\0';
869                                 printf(" %s %lx", shoconn,
870                                     (u_long)unpcb.unp_conn);
871                         }
872                 }
873                 break;
874         default:
875                 /* print protocol number and socket address */
876                 printf(" %d %lx", proto.pr_protocol, (u_long)sock);
877         }
878         printf("\n");
879         return;
880 bad:
881         printf("* error\n");
882 }
883
884
885 /*
886  * Read the cdev structure in the kernel (as pointed to by a dev_t)
887  * in order to work out the associated udev_t
888  */
889 udev_t
890 dev2udev(void *dev)
891 {
892         struct cdev si;
893
894         if (kread(dev, &si, sizeof si)) {
895                 if ((si.si_umajor & 0xffffff00) ||
896                     (si.si_uminor & 0x0000ff00)) {
897                         return NOUDEV;
898                 }
899                 return((si.si_umajor << 8) | si.si_uminor);
900         } else {
901                 dprintf(stderr, "can't convert dev_t %p to a udev_t\n", dev);
902                 return NOUDEV;
903         }
904 }
905
906 udev_t
907 makeudev(int x, int y)
908 {
909         if ((x & 0xffffff00) || (y & 0x0000ff00))
910                 return NOUDEV;
911         return ((x << 8) | y);
912 }
913
914 /*
915  * getinetproto --
916  *      print name of protocol number
917  */
918 void
919 getinetproto(int number)
920 {
921         static int isopen;
922         struct protoent *pe;
923
924         if (!isopen)
925                 setprotoent(++isopen);
926         if ((pe = getprotobynumber(number)) != NULL)
927                 printf(" %s", pe->p_name);
928         else
929                 printf(" %d", number);
930 }
931
932 int
933 getfname(const char *filename)
934 {
935         struct stat statbuf;
936         DEVS *cur;
937
938         if (stat(filename, &statbuf)) {
939                 warn("%s", filename);
940                 return(0);
941         }
942         if ((cur = malloc(sizeof(DEVS))) == NULL)
943                 err(1, NULL);
944         cur->next = devs;
945         devs = cur;
946
947         cur->ino = statbuf.st_ino;
948         cur->fsid = statbuf.st_dev;
949         cur->name = filename;
950         return(1);
951 }
952
953 void
954 usage(void)
955 {
956         (void)fprintf(stderr,
957  "usage: fstat [-fmnv] [-p pid] [-u user] [-N system] [-M core] [file ...]\n");
958         exit(1);
959 }
960
961 static 
962 void
963 make_printable(char *buf, int len)
964 {
965     while (len > 0) {
966         if (!isprint(*buf)) 
967                 *buf = '?';
968         ++buf;
969         --len;
970     }
971 }
972
973 ssize_t
974 kread(const void *kaddr, void *uaddr, size_t nbytes)
975 {
976     if (nbytes > 0x10000000)
977         return(0);
978
979     if (kvm_read(kd, (u_long)kaddr, (char *)uaddr, nbytes) == (ssize_t)nbytes)
980         return(1);
981     else
982         return(0);
983 }
984