6d84faf6618df99a4f718e391e5d4e644e7d2b01
[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.18 2006/09/09 19:07:26 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 namecache *ncp, 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 namecache *ncp);
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_ncp, 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_ncp,
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.eflags & MAP_ENTRY_IS_SUB_MAP)
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 namecache *ncp, 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, ncp));
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 namecache *ncp)
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_copy;
640         static char path[1024];
641         int i;
642
643         /*
644          * If no ncp is passed try to find one via ncplist.
645          */
646         if (ncp == NULL) {
647                 ncp = ncplist->tqh_first;
648         }
649
650         /*
651          * If we have an ncp, traceback the path.  This is a kvm pointer.
652          */
653         if (ncp) {
654                 i = sizeof(path) - 1;
655                 path[i] = 0;
656                 while (ncp) {
657                         if (!kread(ncp, &ncp_copy, sizeof(ncp_copy))) {
658                                 warnx("can't read ncp at %p", ncp);
659                                 return (NULL);
660                         }
661                         if (ncp_copy.nc_flag & NCF_MOUNTPT) {
662                                 ncp = ncp_copy.nc_parent;
663                                 continue;
664                         }
665                         if (i <= ncp_copy.nc_nlen)
666                                 break;
667                         i -= ncp_copy.nc_nlen;
668                         if (!kread(ncp_copy.nc_name, path + i, ncp_copy.nc_nlen)) {
669                                 warnx("can't read ncp %p path component at %p", ncp, ncp_copy.nc_name);
670                                 return (NULL);
671                         }
672                         make_printable(path + i, ncp_copy.nc_nlen);
673                         path[--i] = '/';
674                         ncp = ncp_copy.nc_parent;
675                 }
676                 if (i == sizeof(path) - 1)
677                         path[--i] = '/';
678                 return(path + i);
679         }
680
681         /*
682          * If all else fails print out the mount point path
683          */
684         for (mt = mhead; mt != NULL; mt = mt->next) {
685                 if (m == mt->m)
686                         return (mt->mntonname);
687         }
688         if (!kread(m, &mount_l, sizeof(struct mount))) {
689                 warnx("can't read mount table at %p", (void *)m);
690                 return (NULL);
691         }
692         if ((mt = malloc(sizeof (struct mtab))) == NULL)
693                 err(1, NULL);
694         mt->m = m;
695         bcopy(&mount_l.mnt_stat.f_mntonname[0], &mt->mntonname[0], MNAMELEN);
696         mt->next = mhead;
697         mhead = mt;
698         return (mt->mntonname);
699 }
700
701 void
702 pipetrans(struct pipe *pi, int i, int flag)
703 {
704         struct pipe pip;
705         char rw[3];
706
707         PREFIX(i);
708
709         /* fill in socket */
710         if (!kread(pi, &pip, sizeof(struct pipe))) {
711                 dprintf(stderr, "can't read pipe at %p\n", (void *)pi);
712                 goto bad;
713         }
714
715         printf("* pipe %8lx <-> %8lx", (u_long)pi, (u_long)pip.pipe_peer);
716         printf(" %6d", (int)pip.pipe_buffer.cnt);
717         rw[0] = '\0';
718         if (flag & FREAD)
719                 strcat(rw, "r");
720         if (flag & FWRITE)
721                 strcat(rw, "w");
722         printf(" %2s", rw);
723         putchar('\n');
724         return;
725
726 bad:
727         printf("* error\n");
728 }
729
730 void
731 socktrans(struct socket *sock, int i)
732 {
733         static const char *stypename[] = {
734                 "unused",       /* 0 */
735                 "stream",       /* 1 */
736                 "dgram",        /* 2 */
737                 "raw",          /* 3 */
738                 "rdm",          /* 4 */
739                 "seqpak"        /* 5 */
740         };
741 #define STYPEMAX 5
742         struct socket   so;
743         struct protosw  proto;
744         struct domain   dom;
745         struct inpcb    inpcb;
746         struct unpcb    unpcb;
747         int len;
748         char dname[32];
749
750         PREFIX(i);
751
752         /* fill in socket */
753         if (!kread(sock, &so, sizeof(struct socket))) {
754                 dprintf(stderr, "can't read sock at %p\n", (void *)sock);
755                 goto bad;
756         }
757
758         /* fill in protosw entry */
759         if (!kread(so.so_proto, &proto, sizeof(struct protosw))) {
760                 dprintf(stderr, "can't read protosw at %p",
761                     (void *)so.so_proto);
762                 goto bad;
763         }
764
765         /* fill in domain */
766         if (!kread(proto.pr_domain, &dom, sizeof(struct domain))) {
767                 dprintf(stderr, "can't read domain at %p\n",
768                     (const void *)proto.pr_domain);
769                 goto bad;
770         }
771
772         if ((len = kvm_read(kd, (u_long)dom.dom_name, dname,
773             sizeof(dname) - 1)) < 0) {
774                 dprintf(stderr, "can't read domain name at %p\n",
775                     (void *)dom.dom_name);
776                 dname[0] = '\0';
777         }
778         else
779                 dname[len] = '\0';
780
781         if ((u_short)so.so_type > STYPEMAX)
782                 printf("* %s ?%d", dname, so.so_type);
783         else
784                 printf("* %s %s", dname, stypename[so.so_type]);
785
786         /*
787          * protocol specific formatting
788          *
789          * Try to find interesting things to print.  For tcp, the interesting
790          * thing is the address of the tcpcb, for udp and others, just the
791          * inpcb (socket pcb).  For unix domain, its the address of the socket
792          * pcb and the address of the connected pcb (if connected).  Otherwise
793          * just print the protocol number and address of the socket itself.
794          * The idea is not to duplicate netstat, but to make available enough
795          * information for further analysis.
796          */
797         switch(dom.dom_family) {
798         case AF_INET:
799         case AF_INET6:
800                 getinetproto(proto.pr_protocol);
801                 if (proto.pr_protocol == IPPROTO_TCP ) {
802                         if (so.so_pcb) {
803                                 if (kvm_read(kd, (u_long)so.so_pcb,
804                                     (char *)&inpcb, sizeof(struct inpcb))
805                                     != sizeof(struct inpcb)) {
806                                         dprintf(stderr,
807                                             "can't read inpcb at %p\n",
808                                             (void *)so.so_pcb);
809                                         goto bad;
810                                 }
811                                 printf(" %lx", (u_long)inpcb.inp_ppcb);
812                         }
813                 }
814                 else if (so.so_pcb)
815                         printf(" %lx", (u_long)so.so_pcb);
816                 break;
817         case AF_UNIX:
818                 /* print address of pcb and connected pcb */
819                 if (so.so_pcb) {
820                         printf(" %lx", (u_long)so.so_pcb);
821                         if (kvm_read(kd, (u_long)so.so_pcb, (char *)&unpcb,
822                             sizeof(struct unpcb)) != sizeof(struct unpcb)){
823                                 dprintf(stderr, "can't read unpcb at %p\n",
824                                     (void *)so.so_pcb);
825                                 goto bad;
826                         }
827                         if (unpcb.unp_conn) {
828                                 char shoconn[4], *cp;
829
830                                 cp = shoconn;
831                                 if (!(so.so_state & SS_CANTRCVMORE))
832                                         *cp++ = '<';
833                                 *cp++ = '-';
834                                 if (!(so.so_state & SS_CANTSENDMORE))
835                                         *cp++ = '>';
836                                 *cp = '\0';
837                                 printf(" %s %lx", shoconn,
838                                     (u_long)unpcb.unp_conn);
839                         }
840                 }
841                 break;
842         default:
843                 /* print protocol number and socket address */
844                 printf(" %d %lx", proto.pr_protocol, (u_long)sock);
845         }
846         printf("\n");
847         return;
848 bad:
849         printf("* error\n");
850 }
851
852
853 /*
854  * Read the cdev structure in the kernel (as pointed to by a dev_t)
855  * in order to work out the associated udev_t
856  */
857 udev_t
858 dev2udev(void *dev)
859 {
860         struct cdev si;
861
862         if (kread(dev, &si, sizeof si)) {
863                 return si.si_udev;
864         } else {
865                 dprintf(stderr, "can't convert dev_t %p to a udev_t\n", dev);
866                 return -1;
867         }
868 }
869
870 /*
871  * getinetproto --
872  *      print name of protocol number
873  */
874 void
875 getinetproto(int number)
876 {
877         static int isopen;
878         struct protoent *pe;
879
880         if (!isopen)
881                 setprotoent(++isopen);
882         if ((pe = getprotobynumber(number)) != NULL)
883                 printf(" %s", pe->p_name);
884         else
885                 printf(" %d", number);
886 }
887
888 int
889 getfname(const char *filename)
890 {
891         struct stat statbuf;
892         DEVS *cur;
893
894         if (stat(filename, &statbuf)) {
895                 warn("%s", filename);
896                 return(0);
897         }
898         if ((cur = malloc(sizeof(DEVS))) == NULL)
899                 err(1, NULL);
900         cur->next = devs;
901         devs = cur;
902
903         cur->ino = statbuf.st_ino;
904         cur->fsid = statbuf.st_dev;
905         cur->name = filename;
906         return(1);
907 }
908
909 void
910 usage(void)
911 {
912         (void)fprintf(stderr,
913  "usage: fstat [-fmnv] [-p pid] [-u user] [-N system] [-M core] [file ...]\n");
914         exit(1);
915 }
916
917 static 
918 void
919 make_printable(char *buf, int len)
920 {
921     while (len > 0) {
922         if (!isprint(*buf)) 
923                 *buf = '?';
924         ++buf;
925         --len;
926     }
927 }
928
929 ssize_t
930 kread(const void *kaddr, void *uaddr, size_t nbytes)
931 {
932     if (nbytes > 0x10000000)
933         return(0);
934
935     if (kvm_read(kd, (u_long)kaddr, (char *)uaddr, nbytes) == (ssize_t)nbytes)
936         return(1);
937     else
938         return(0);
939 }
940