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