Salvager: Don't use garbage vnodes when Testing
[openafs.git] / src / vol / vol-info.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11    System:              VICE-TWO
12    Module:              vol-info.c
13    Institution: The Information Technology Center, Carnegie-Mellon University
14
15    */
16
17 #include <afsconfig.h>
18 #include <afs/param.h>
19
20 #include <roken.h>
21
22 #include <ctype.h>
23
24 #ifdef HAVE_SYS_FILE_H
25 #include <sys/file.h>
26 #endif
27
28 #include <afs/cmd.h>
29 #include <afs/dir.h>
30 #include <afs/afsint.h>
31 #include <afs/errors.h>
32 #include <afs/acl.h>
33 #include <afs/prs_fs.h>
34 #include <opr/queue.h>
35
36 #include "nfs.h"
37 #include "lock.h"
38 #include "ihandle.h"
39 #include "vnode.h"
40 #include "volume.h"
41 #include "partition.h"
42 #include "salvage.h"
43 #include "daemon_com_inline.h"
44 #include "fssync_inline.h"
45
46 #ifndef AFS_NT40_ENV
47 #include "AFS_component_version_number.c"
48 #endif
49
50 static const char *progname = NULL;
51 static const char *PLACEHOLDER = "-";
52
53 /* Command line options */
54 typedef enum {
55     P_CHECKOUT,
56     P_VNODE,
57     P_DATE,
58     P_INODE,
59     P_ITIME,
60     P_PART,
61     P_VOLUMEID,
62     P_HEADER,
63     P_SIZEONLY,
64     P_FIXHEADER,
65     P_SAVEINODES,
66     P_ORPHANED,
67     P_FILENAMES,
68     P_TYPE,
69     P_FIND,
70     P_MASK,
71     P_OUTPUT,
72     P_DELIM,
73     P_NOHEADING,
74 } volinfo_parm_t;
75
76 /*
77  * volscan output columns
78  */
79 #define VOLSCAN_COLUMNS \
80     c(host) \
81     c(desc) \
82     c(vid) \
83     c(vtype) \
84     c(vname) \
85     c(part) \
86     c(partid) \
87     c(fid) \
88     c(path) \
89     c(target) \
90     c(mount) \
91     c(mtype) \
92     c(mcell) \
93     c(mvol) \
94     c(aid) \
95     c(arights) \
96     c(vntype) \
97     c(cloned) \
98     c(mode) \
99     c(links) \
100     c(length) \
101     c(uniq) \
102     c(dv) \
103     c(inode) \
104     c(namei) \
105     c(modtime) \
106     c(author) \
107     c(owner) \
108     c(parent) \
109     c(magic) \
110     c(lock) \
111     c(smodtime) \
112     c(group)
113
114 /* Numeric column type ids */
115 typedef enum columnType {
116 #define c(x) col_##x,
117     VOLSCAN_COLUMNS
118 #undef c
119     max_column_type
120 } columnType;
121
122 struct columnName {
123     columnType type;
124     const char *name;
125 };
126
127 /* Table of id:name tuples of possible columns. */
128 struct columnName ColumnName[] = {
129 #define c(x) { col_##x, #x },
130     VOLSCAN_COLUMNS
131 #undef c
132     {max_column_type, NULL}
133 };
134
135 /* All columns names as a single string. */
136 #define c(x) #x " "
137 static char *ColumnNames = VOLSCAN_COLUMNS;
138 #undef c
139 #undef VOLSCAN_COLUMNS
140
141
142 /* VnodeDetails union descriminator */
143 typedef enum {
144     VNODE_U_NONE,
145     VNODE_U_MOUNT,
146     VNODE_U_SYMLINK,
147     VNODE_U_POS_ACCESS,
148     VNODE_U_NEG_ACCESS
149 } vnode_details_u_t;
150
151 struct VnodeDetails {
152     Volume *vp;
153     VnodeClass class;
154     VnodeDiskObject *vnode;
155     VnodeId vnodeNumber;
156     afs_foff_t offset;
157     int index;
158     char *path;
159     vnode_details_u_t t;
160     union {
161         struct {
162             char type;
163             char *cell;
164             char *vol;
165         } mnt;
166         char *target;
167         struct acl_accessEntry *access;
168     } u;
169 };
170
171 /* Modes */
172 static int Checkout = 0;            /**< Use FSSYNC to checkout volumes from the fileserver. */
173 static int DumpInfo = 0;            /**< Dump volume information */
174 static int DumpHeader = 0;          /**< Dump volume header files info */
175 static int DumpVnodes = 0;          /**< Dump vnode info */
176 static int DumpInodeNumber = 0;     /**< Dump inode numbers with vnodes */
177 static int DumpDate = 0;            /**< Dump vnode date (server modify date) with vnode */
178 static int InodeTimes = 0;          /**< Dump some of the dates associated with inodes */
179 #if defined(AFS_NAMEI_ENV)
180 static int PrintFileNames = 0;      /**< Dump vnode and special file name filenames */
181 #endif
182 static int ShowOrphaned = 0;        /**< Show "orphaned" vnodes (vnodes with parent of 0) */
183 static int ShowSizes = 0;           /**< Show volume size summary */
184 static int SaveInodes = 0;          /**< Save vnode data to files */
185 static int FixHeader = 0;           /**< Repair header files magic and version fields. */
186 static char Hostname[64] = "";      /**< This hostname, for volscan output. */
187 static int NeedDirIndex = 0;        /**< Large vnode index handle is needed for path lookups. */
188 static char ColumnDelim[16] = " ";  /**< Column delimiter char(s) */
189 static char PrintHeading = 0;       /**< Print column heading */
190 static unsigned int ModeMask[64];
191
192 static FdHandle_t *DirIndexFd = NULL; /**< Current large vnode index handle for path lookups. */
193
194 static int NumOutputColumns = 0;
195 static columnType OutputColumn[max_column_type];
196
197 #define SCAN_RW  0x01           /**< scan read-write volumes vnodes */
198 #define SCAN_RO  0x02           /**< scan read-only volume vnodes */
199 #define SCAN_BK  0x04           /**< scan backup volume vnodes */
200 static int ScanVolType = 0;     /**< volume types to scan; zero means do not check */
201
202 #define FIND_FILE       0x01    /**< find regular files */
203 #define FIND_DIR        0x02    /**< find directories */
204 #define FIND_MOUNT      0x04    /**< find afs mount points */
205 #define FIND_SYMLINK    0x08    /**< find symlinks */
206 #define FIND_ACL        0x10    /**< find access entiries */
207 static int FindVnType = 0;      /**< types of objects to find */
208
209 /**
210  * Volume size running totals
211  */
212 struct sizeTotals {
213     afs_uint64 diskused_k;      /**< volume size from disk data file, in kilobytes */
214     afs_uint64 auxsize;         /**< size of header files, in bytes  */
215     afs_uint64 auxsize_k;       /**< size of header files, in kilobytes */
216     afs_uint64 vnodesize;       /**< size of the large and small vnodes, in bytes */
217     afs_uint64 vnodesize_k;     /**< size of the large and small vnodes, in kilobytes */
218     afs_uint64 size_k;          /**< size of headers and vnodes, in kilobytes */
219 };
220
221 static struct sizeTotals volumeTotals = { 0, 0, 0, 0, 0, 0 };
222 static struct sizeTotals partitionTotals = { 0, 0, 0, 0, 0, 0 };
223 static struct sizeTotals serverTotals = { 0, 0, 0, 0, 0, 0 };
224 static int PrintingVolumeSizes = 0;     /*print volume size lines */
225
226 /**
227  * List of procedures to call when scanning vnodes.
228  */
229 struct VnodeScanProc {
230     struct opr_queue link;
231     const char *heading;
232     void (*proc) (struct VnodeDetails * vdp);
233 };
234 static struct opr_queue VnodeScanLists[nVNODECLASSES];
235
236 /* Forward Declarations */
237 void PrintHeader(Volume * vp);
238 void HandleAllPart(void);
239 void HandlePart(struct DiskPartition64 *partP);
240 void HandleVolume(struct DiskPartition64 *partP, char *name);
241 struct DiskPartition64 *FindCurrentPartition(void);
242 Volume *AttachVolume(struct DiskPartition64 *dp, char *volname,
243                      struct VolumeHeader *header);
244 void HandleVnodes(Volume * vp, VnodeClass class);
245 static void AddVnodeToSizeTotals(struct VnodeDetails *vdp);
246 static void SaveInode(struct VnodeDetails *vdp);
247 static void PrintVnode(struct VnodeDetails *vdp);
248 static void PrintVnodeDetails(struct VnodeDetails *vdp);
249 static void ScanAcl(struct VnodeDetails *vdp);
250 static void PrintColumnHeading(void);
251 static void PrintColumns(struct VnodeDetails *vdp, const char *desc);
252
253 /* externs */
254 extern void SetSalvageDirHandle(DirHandle * dir, afs_int32 volume,
255                                 Device device, Inode inode,
256                                 int *volumeChanged);
257 extern void FidZap(DirHandle * file);
258
259 /**
260  * Format time as a timestamp string
261  *
262  * @param[in] date  time value to format
263  *
264  * @return timestamp string in the form YYYY/MM/DD.hh:mm:ss
265  *
266  * @note A static array of 8 strings are stored by this
267  *       function. The array slots are overwritten, so the
268  *       caller must not reference the returned string after
269  *       seven additional calls to this function.
270  */
271 char *
272 date(time_t date)
273 {
274 #define MAX_DATE_RESULT 100
275     static char results[8][MAX_DATE_RESULT];
276     static int next;
277     struct tm *tm = localtime(&date);
278     char buf[32];
279
280     (void)strftime(buf, 32, "%Y/%m/%d.%H:%M:%S", tm);   /* NT does not have %T */
281     snprintf(results[next = (next + 1) & 7], MAX_DATE_RESULT,
282              "%lu (%s)", (unsigned long)date, buf);
283     return results[next];
284 }
285
286 #ifdef AFS_NT40_ENV
287 /**
288  * Format file time as a timestamp string
289  *
290  * @param[in] ft  file time
291  *
292  * @return timestamp string in the form YYYY/MM/DD.hh:mm:ss
293  *
294  * @note A static array of 8 strings are stored by this
295  *       function. The array slots are overwritten, so the
296  *       caller must not reference the returned string after
297  *       seven additional calls to this function.
298  */
299 char *
300 NT_date(FILETIME * ft)
301 {
302     static char result[8][64];
303     static int next = 0;
304     SYSTEMTIME st;
305     FILETIME lft;
306
307     if (!FileTimeToLocalFileTime(ft, &lft)
308         || !FileTimeToSystemTime(&lft, &st)) {
309         fprintf(stderr, "%s: Time conversion failed.\n", progname);
310         exit(1);
311     }
312     sprintf(result[next = ((next + 1) & 7)], "%4d/%02d/%02d.%2d:%2d:%2d",
313             st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
314     return result[next];
315 }
316 #endif
317
318 /**
319  * Add vnode size to the running volume totals.
320  *
321  * @param[in]  vdp   vnode details object
322  *
323  * @return none
324  */
325 static void
326 AddVnodeToSizeTotals(struct VnodeDetails *vdp)
327 {
328     afs_fsize_t fileLength;
329
330     VNDISK_GET_LEN(fileLength, vdp->vnode);
331     if (fileLength > 0) {
332         volumeTotals.vnodesize += fileLength;
333         volumeTotals.vnodesize_k += fileLength / 1024;
334     }
335 }
336
337 /**
338  * Print the volume size table heading line, if needed.
339  *
340  * @return none
341  */
342 static void
343 PrintVolumeSizeHeading(void)
344 {
345     if (!PrintingVolumeSizes) {
346         printf
347             ("Volume-Id\t  Volsize  Auxsize Inodesize  AVolsize SizeDiff                (VolName)\n");
348         PrintingVolumeSizes = 1;
349     }
350 }
351
352 /**
353  * Accumulate totals.
354  *
355  * @return 0
356  */
357 static void
358 AddSizeTotals(struct sizeTotals *a, struct sizeTotals *b)
359 {
360     a->diskused_k += b->diskused_k;
361     a->auxsize += b->auxsize;
362     a->auxsize_k += b->auxsize_k;
363     a->vnodesize += b->vnodesize;
364     a->vnodesize_k += b->vnodesize_k;
365     a->size_k += b->size_k;
366 }
367
368 /**
369  * Print the sizes for a volume.
370  *
371  * @return none
372  */
373 static void
374 PrintVolumeSizes(Volume * vp)
375 {
376     afs_int64 diff_k = volumeTotals.size_k - volumeTotals.diskused_k;
377
378     PrintVolumeSizeHeading();
379     printf("%u\t%9llu%9llu%10llu%10llu%9lld\t%24s\n",
380            V_id(vp),
381            volumeTotals.diskused_k,
382            volumeTotals.auxsize_k, volumeTotals.vnodesize_k,
383            volumeTotals.size_k, diff_k, V_name(vp));
384 }
385
386 /**
387  * Print the size totals for the partition.
388  *
389  * @return none
390  */
391 static void
392 PrintPartitionTotals(afs_uint64 nvols)
393 {
394     afs_int64 diff_k = partitionTotals.size_k - partitionTotals.diskused_k;
395
396     PrintVolumeSizeHeading();
397     printf("\nPart Totals  %12llu%9llu%10llu%10llu%9lld (%llu volumes)\n\n",
398            partitionTotals.diskused_k, partitionTotals.auxsize,
399            partitionTotals.vnodesize, partitionTotals.size_k, diff_k, nvols);
400     PrintingVolumeSizes = 0;
401 }
402
403 /**
404  * Print the size totals for all the partitions.
405  *
406  * @return none
407  */
408 static void
409 PrintServerTotals(void)
410 {
411     afs_int64 diff_k = serverTotals.size_k - serverTotals.diskused_k;
412
413     printf("\nServer Totals%12lld%9lld%10lld%10lld%9lld\n",
414            serverTotals.diskused_k, serverTotals.auxsize,
415            serverTotals.vnodesize, serverTotals.size_k, diff_k);
416 }
417
418 /**
419  * Read a volume header file
420  *
421  * @param[in] ih        ihandle of the header file
422  * @param[in] to        destination
423  * @param[in] size      expected header size
424  * @param[in] magic     expected header magic number
425  * @param[in] version   expected header version number
426  *
427  * @return error code
428  *   @retval 0 success
429  *   @retval -1 failed to read file
430  */
431 int
432 ReadHdr1(IHandle_t * ih, char *to, afs_sfsize_t size, u_int magic, u_int version)
433 {
434     struct versionStamp *vsn;
435     int bad = 0;
436     int code;
437
438     vsn = (struct versionStamp *)to;
439
440     code = IH_IREAD(ih, 0, to, size);
441     if (code != size)
442         return -1;
443
444     if (vsn->magic != magic) {
445         bad++;
446         fprintf(stderr, "%s: Inode %s: Bad magic %x (%x): IGNORED\n",
447                 progname, PrintInode(NULL, ih->ih_ino), vsn->magic, magic);
448     }
449
450     /* Check is conditional, in case caller wants to inspect version himself */
451     if (version && vsn->version != version) {
452         bad++;
453         fprintf(stderr, "%s: Inode %s: Bad version %x (%x): IGNORED\n",
454                 progname,
455                 PrintInode(NULL, ih->ih_ino), vsn->version, version);
456     }
457     if (bad && FixHeader) {
458         vsn->magic = magic;
459         vsn->version = version;
460         printf("Special index inode %s has a bad header. Reconstructing...\n",
461                PrintInode(NULL, ih->ih_ino));
462         code = IH_IWRITE(ih, 0, to, size);
463         if (code != size) {
464             fprintf(stderr,
465                     "%s: Write failed for inode %s; header left in damaged state\n",
466                     progname, PrintInode(NULL, ih->ih_ino));
467         }
468     }
469     if (!bad && DumpInfo) {
470         printf("Inode %s: Good magic %x and version %x\n",
471                PrintInode(NULL, ih->ih_ino), magic, version);
472     }
473     return 0;
474 }
475
476 /**
477  * Simplified attach volume
478  *
479  * param[in] dp       vice disk partition object
480  * param[in] volname  volume header file name
481  * param[in] header   volume header object
482  *
483  * @return volume object or null on error
484  */
485 Volume *
486 AttachVolume(struct DiskPartition64 * dp, char *volname,
487              struct VolumeHeader * header)
488 {
489     Volume *vp;
490     afs_int32 ec = 0;
491
492     if (Checkout) {
493         afs_int32 code;
494         SYNC_response response;
495         VolumeId volid = header->id;
496
497         memset(&response, 0, sizeof(response));
498         code =
499             FSYNC_VolOp(volid, dp->name, FSYNC_VOL_NEEDVOLUME, V_DUMP,
500                         &response);
501         if (code != SYNC_OK) {
502             if (response.hdr.reason == FSYNC_SALVAGE) {
503                 fprintf(stderr,
504                         "%s: file server says volume %lu is salvaging.\n",
505                         progname, afs_printable_uint32_lu(volid));
506                 return NULL;
507             } else {
508                 fprintf(stderr,
509                         "%s: attach of volume %lu denied by file server.\n",
510                         progname, afs_printable_uint32_lu(volid));
511                 return NULL;
512             }
513         }
514     }
515
516     vp = (Volume *) calloc(1, sizeof(Volume));
517     if (!vp) {
518         fprintf(stderr, "%s: Failed to allocate volume object.\n", progname);
519         return NULL;
520     }
521     vp->specialStatus = 0;
522     vp->device = dp->device;
523     vp->partition = dp;
524     IH_INIT(vp->vnodeIndex[vLarge].handle, dp->device, header->parent,
525             header->largeVnodeIndex);
526     IH_INIT(vp->vnodeIndex[vSmall].handle, dp->device, header->parent,
527             header->smallVnodeIndex);
528     IH_INIT(vp->diskDataHandle, dp->device, header->parent,
529             header->volumeInfo);
530     IH_INIT(V_linkHandle(vp), dp->device, header->parent, header->linkTable);
531     vp->cacheCheck = 0;         /* XXXX */
532     vp->shuttingDown = 0;
533     vp->goingOffline = 0;
534     vp->nUsers = 1;
535     vp->header = (struct volHeader *)calloc(1, sizeof(*vp->header));
536     if (!vp->header) {
537         fprintf(stderr, "%s: Failed to allocate volume header.\n", progname);
538         free(vp);
539         return NULL;
540     }
541     ec = ReadHdr1(V_diskDataHandle(vp), (char *)&V_disk(vp),
542                   sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
543     if (!ec) {
544         struct IndexFileHeader iHead;
545         ec = ReadHdr1(vp->vnodeIndex[vSmall].handle, (char *)&iHead,
546                       sizeof(iHead), SMALLINDEXMAGIC, SMALLINDEXVERSION);
547     }
548     if (!ec) {
549         struct IndexFileHeader iHead;
550         ec = ReadHdr1(vp->vnodeIndex[vLarge].handle, (char *)&iHead,
551                       sizeof(iHead), LARGEINDEXMAGIC, LARGEINDEXVERSION);
552     }
553 #ifdef AFS_NAMEI_ENV
554     if (!ec) {
555         struct versionStamp stamp;
556         ec = ReadHdr1(V_linkHandle(vp), (char *)&stamp, sizeof(stamp),
557                       LINKTABLEMAGIC, LINKTABLEVERSION);
558     }
559 #endif
560     if (ec)
561         return (Volume *) 0;
562     return vp;
563 }
564
565 /**
566  * Simplified detach volume
567  *
568  * param[in] vp       volume object from AttachVolume
569  *
570  * @return none
571  */
572 static void
573 DetachVolume(Volume * vp)
574 {
575     if (Checkout) {
576         afs_int32 code;
577         SYNC_response response;
578         memset(&response, 0, sizeof(response));
579
580         code = FSYNC_VolOp(V_id(vp), V_partition(vp)->name,
581                            FSYNC_VOL_ON, FSYNC_WHATEVER, &response);
582         if (code != SYNC_OK) {
583             fprintf(stderr, "%s: FSSYNC error %d (%s)\n", progname, code,
584                     SYNC_res2string(code));
585             fprintf(stderr, "%s:  protocol response code was %d (%s)\n",
586                     progname, response.hdr.response,
587                     SYNC_res2string(response.hdr.response));
588             fprintf(stderr, "%s:  protocol reason code was %d (%s)\n",
589                     progname, response.hdr.reason,
590                     FSYNC_reason2string(response.hdr.reason));
591         }
592     }
593
594     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
595     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
596     IH_RELEASE(vp->diskDataHandle);
597     IH_RELEASE(V_linkHandle(vp));
598     free(vp->header);
599     free(vp);
600 }
601
602 /**
603  * Convert the partition device number into a partition name.
604  *
605  * @param[in]   partId      partition number, 0 to 254
606  * @param[out]  partName    buffer to hold partition name (e.g. /vicepa)
607  * @param[in]   partNameSize    size of partName buffer
608  *
609  * @return status
610  *   @retval 0 success
611  *   @retval -1 error, partId is out of range
612  *   @retval -2 error, partition name exceeds partNameSize
613  */
614 static int
615 GetPartitionName(afs_uint32 partId, char *partName, afs_size_t partNameSize)
616 {
617     const afs_uint32 OLD_NUM_DEVICES = 26;      /* a..z */
618
619     if (partId < OLD_NUM_DEVICES) {
620         if (partNameSize < 8) {
621             return -2;
622         }
623         strlcpy(partName, "/vicep", partNameSize);
624         partName[6] = partId + 'a';
625         partName[7] = '\0';
626         return 0;
627     }
628     if (partId < VOLMAXPARTS) {
629         if (partNameSize < 9) {
630             return -2;
631         }
632         strlcpy(partName, "/vicep", partNameSize);
633         partId -= OLD_NUM_DEVICES;
634         partName[6] = 'a' + (partId / OLD_NUM_DEVICES);
635         partName[7] = 'a' + (partId % OLD_NUM_DEVICES);
636         partName[8] = '\0';
637         return 0;
638     }
639     return -1;
640 }
641
642 /**
643  * Scan the volumes in the partitions
644  *
645  * Scan the specified volume in the specified partition if both
646  * are given. Scan all the volumes in the specified partition if
647  * only the partition is given.  If neither a partition nor volume
648  * is given, scan all the volumes in all the partitions.  If only
649  * the volume is given, attempt to find it in the current working
650  * directory.
651  *
652  * @param[in] partNameOrId   partition name or id to be scannned
653  * @param[in] volumeId       volume id to be scanned
654  *
655  * @return 0 if successful
656  */
657 static int
658 ScanPartitions(char *partNameOrId, afs_uint32 volumeId)
659 {
660     int err = 0;
661     char partName[64] = "";
662     struct DiskPartition64 *partP = NULL;
663
664 #ifndef AFS_NT40_ENV
665     if (geteuid() != 0) {
666         fprintf(stderr, "%s: Must be run as root; sorry\n", progname);
667         return 1;
668     }
669 #endif
670
671     if (Checkout) {
672         if (!FSYNC_clientInit()) {
673             fprintf(stderr, "%s: Failed to connect to fileserver.\n",
674                     progname);
675             return 1;
676         }
677     }
678
679     DInit(1024);
680     VInitVnodes(vLarge, 0);
681     VInitVnodes(vSmall, 0);
682
683     /* Allow user to specify partition by name or id. */
684     if (partNameOrId) {
685         afs_uint32 partId = volutil_GetPartitionID(partNameOrId);
686         if (partId == -1) {
687             fprintf(stderr, "%s: Could not parse '%s' as a partition name.\n",
688                     progname, partNameOrId);
689             err = 1;
690             goto cleanup;
691         }
692         if (GetPartitionName(partId, partName, sizeof(partName))) {
693             fprintf(stderr,
694                     "%s: Could not format '%s' as a partition name.\n",
695                     progname, partNameOrId);
696             err = 1;
697             goto cleanup;
698         }
699     }
700
701     err = VAttachPartitions();
702     if (err) {
703         fprintf(stderr, "%s: %d partitions had errors during attach.\n",
704                 progname, err);
705         err = 1;
706         goto cleanup;
707     }
708
709     if (partName[0]) {
710         partP = VGetPartition(partName, 0);
711         if (!partP) {
712             fprintf(stderr,
713                     "%s: %s is not an AFS partition name on this server.\n",
714                     progname, partName);
715             err = 1;
716             goto cleanup;
717         }
718     }
719
720     if (!volumeId) {
721         if (PrintHeading) {
722             PrintColumnHeading();
723         }
724         if (!partP) {
725             HandleAllPart();
726         } else {
727             HandlePart(partP);
728         }
729     } else {
730         char name1[128];
731
732         if (!partP) {
733             partP = FindCurrentPartition();
734             if (!partP) {
735                 fprintf(stderr,
736                         "%s: Current partition is not a vice partition.\n",
737                         progname);
738                 err = 1;
739                 goto cleanup;
740             }
741         }
742         snprintf(name1, sizeof name1, VFORMAT,
743                  afs_printable_uint32_lu(volumeId));
744         if (PrintHeading) {
745             PrintColumnHeading();
746         }
747         HandleVolume(partP, name1);
748     }
749
750   cleanup:
751     if (Checkout) {
752         FSYNC_clientFinis();
753     }
754     return err;
755 }
756
757 /**
758  * Add a vnode scanning procedure
759  *
760  * @param[in]   class   vnode class for this handler
761  * @param[in]   proc    handler proc to be called by HandleVnodes
762  * @param[in]   heading optional string to pring before scanning vnodes
763  *
764  * @return none
765  */
766 static void
767 AddVnodeHandler(VnodeClass class, void (*proc) (struct VnodeDetails * vdp),
768                 const char *heading)
769 {
770     struct VnodeScanProc *entry = malloc(sizeof(struct VnodeScanProc));
771     entry->proc = proc;
772     entry->heading = heading;
773     opr_queue_Append(&VnodeScanLists[class], (struct opr_queue *)entry);
774 }
775
776 /**
777  * Process command line options and start scanning
778  *
779  * @param[in] as     command syntax object
780  * @param[in] arock  opaque object; not used
781  *
782  * @return error code
783  */
784 static int
785 VolInfo(struct cmd_syndesc *as, void *arock)
786 {
787     struct cmd_item *ti;
788     afs_uint32 volumeId = 0;
789     char *partNameOrId = NULL;
790
791     DumpInfo = 1;               /* volinfo default mode */
792
793     if (as->parms[P_CHECKOUT].items) {
794         Checkout = 1;
795     }
796     if (as->parms[P_VNODE].items) {
797         DumpVnodes = 1;
798     }
799     if (as->parms[P_DATE].items) {
800         DumpDate = 1;
801     }
802     if (as->parms[P_INODE].items) {
803         DumpInodeNumber = 1;
804     }
805     if (as->parms[P_ITIME].items) {
806         InodeTimes = 1;
807     }
808     if ((ti = as->parms[P_PART].items)) {
809         partNameOrId = ti->data;
810     }
811     if ((ti = as->parms[P_VOLUMEID].items)) {
812         volumeId = strtoul(ti->data, NULL, 10);
813     }
814     if (as->parms[P_HEADER].items) {
815         DumpHeader = 1;
816     }
817     if (as->parms[P_SIZEONLY].items) {
818         ShowSizes = 1;
819     }
820     if (as->parms[P_FIXHEADER].items) {
821         FixHeader = 1;
822     }
823     if (as->parms[P_SAVEINODES].items) {
824         SaveInodes = 1;
825     }
826     if (as->parms[P_ORPHANED].items) {
827         ShowOrphaned = 1;
828     }
829 #if defined(AFS_NAMEI_ENV)
830     if (as->parms[P_FILENAMES].items) {
831         PrintFileNames = 1;
832     }
833 #endif
834
835     /* -saveinodes and -sizeOnly override the default mode.
836      * For compatibility with old versions of volinfo, -orphaned
837      * and -filename options imply -vnodes */
838     if (SaveInodes || ShowSizes) {
839         DumpInfo = 0;
840         DumpHeader = 0;
841         DumpVnodes = 0;
842         InodeTimes = 0;
843         ShowOrphaned = 0;
844     } else if (ShowOrphaned) {
845         DumpVnodes = 1;         /* implied */
846 #ifdef AFS_NAMEI_ENV
847     } else if (PrintFileNames) {
848         DumpVnodes = 1;         /* implied */
849 #endif
850     }
851
852     if (SaveInodes) {
853         AddVnodeHandler(vSmall, SaveInode,
854                         "Saving all volume files to current directory ...\n");
855     }
856     if (ShowSizes) {
857         AddVnodeHandler(vLarge, AddVnodeToSizeTotals, NULL);
858         AddVnodeHandler(vSmall, AddVnodeToSizeTotals, NULL);
859     }
860     if (DumpVnodes) {
861         AddVnodeHandler(vLarge, PrintVnode, "\nLarge vnodes (directories)\n");
862         AddVnodeHandler(vSmall, PrintVnode,
863                         "\nSmall vnodes(files, symbolic links)\n");
864     }
865     return ScanPartitions(partNameOrId, volumeId);
866 }
867
868 /**
869  * Add a column type to be displayed.
870  *
871  * @param[in]  name   column type name
872  *
873  * @return error code
874  *   @retval 0 success
875  *   @retval 1 too many columns
876  *   @retval 2 invalid column name
877  */
878 static int
879 AddOutputColumn(char *name)
880 {
881     int i;
882
883     if (NumOutputColumns >= sizeof(OutputColumn) / sizeof(*OutputColumn)) {
884         fprintf(stderr, "%s: Too many output columns (%d).\n", progname,
885                 NumOutputColumns);
886         return 1;
887     }
888     for (i = 0; i < max_column_type; i++) {
889         if (!strcmp(ColumnName[i].name, name)) {
890             columnType t = ColumnName[i].type;
891             OutputColumn[NumOutputColumns++] = t;
892
893             if (t == col_path) {
894                 NeedDirIndex = 1;
895             }
896             return 0;
897         }
898     }
899     return 2;
900 }
901
902 /**
903  * Process command line options and start scanning
904  *
905  * @param[in] as     command syntax object
906  * @param[in] arock  opaque object; not used
907  *
908  * @return error code
909  *    @retval 0 success
910  *    @retvol 1 failure
911  */
912 static int
913 VolScan(struct cmd_syndesc *as, void *arock)
914 {
915     struct cmd_item *ti;
916     afs_uint32 volumeId = 0;
917     char *partNameOrId = NULL;
918     int i;
919
920     if (as->parms[P_CHECKOUT].items) {
921         Checkout = 1;
922     }
923     if ((ti = as->parms[P_PART].items)) {
924         partNameOrId = ti->data;
925     }
926     if ((ti = as->parms[P_VOLUMEID].items)) {
927         volumeId = strtoul(ti->data, NULL, 10);
928     }
929     if (as->parms[P_NOHEADING].items) {
930         PrintHeading = 0;
931     } else {
932         PrintHeading = 1;
933     }
934     if ((ti = as->parms[P_DELIM].items)) {
935         strncpy(ColumnDelim, ti->data, 15);
936         ColumnDelim[15] = '\0';
937     }
938
939     /* Limit types of volumes to scan. */
940     if (!as->parms[P_TYPE].items) {
941         ScanVolType = (SCAN_RW | SCAN_RO | SCAN_BK);
942     } else {
943         ScanVolType = 0;
944         for (ti = as->parms[P_TYPE].items; ti; ti = ti->next) {
945             if (strcmp(ti->data, "rw") == 0) {
946                 ScanVolType |= SCAN_RW;
947             } else if (strcmp(ti->data, "ro") == 0) {
948                 ScanVolType |= SCAN_RO;
949             } else if (strcmp(ti->data, "bk") == 0) {
950                 ScanVolType |= SCAN_BK;
951             } else {
952                 fprintf(stderr, "%s: Unknown -type value: %s\n", progname,
953                         ti->data);
954                 return 1;
955             }
956         }
957     }
958
959     /* Limit types of vnodes to find (plus access entries) */
960     if (!as->parms[P_FIND].items) {
961         FindVnType = (FIND_FILE | FIND_DIR | FIND_MOUNT | FIND_SYMLINK);
962     } else {
963         FindVnType = 0;
964         for (ti = as->parms[P_FIND].items; ti; ti = ti->next) {
965             if (strcmp(ti->data, "file") == 0) {
966                 FindVnType |= FIND_FILE;
967             } else if (strcmp(ti->data, "dir") == 0) {
968                 FindVnType |= FIND_DIR;
969             } else if (strcmp(ti->data, "mount") == 0) {
970                 FindVnType |= FIND_MOUNT;
971             } else if (strcmp(ti->data, "symlink") == 0) {
972                 FindVnType |= FIND_SYMLINK;
973             } else if (strcmp(ti->data, "acl") == 0) {
974                 FindVnType |= FIND_ACL;
975             } else {
976                 fprintf(stderr, "%s: Unknown -find value: %s\n", progname,
977                         ti->data);
978                 return 1;
979             }
980         }
981     }
982
983     /* Show vnodes matching one of the mode masks */
984     for (i = 0, ti = as->parms[P_MASK].items; ti; i++, ti = ti->next) {
985         if (i >= (sizeof(ModeMask) / sizeof(*ModeMask))) {
986             fprintf(stderr, "Too many -mask values\n");
987             return -1;
988         }
989         ModeMask[i] = strtol(ti->data, NULL, 8);
990         if (!ModeMask[i]) {
991             fprintf(stderr, "Invalid -mask value: %s\n", ti->data);
992             return 1;
993         }
994     }
995
996     /* Set which columns to be printed. */
997     if (!as->parms[P_OUTPUT].items) {
998         AddOutputColumn("host");
999         AddOutputColumn("desc");
1000         AddOutputColumn("fid");
1001         AddOutputColumn("dv");
1002         if (FindVnType & FIND_ACL) {
1003             AddOutputColumn("aid");
1004             AddOutputColumn("arights");
1005         }
1006         AddOutputColumn("path");
1007     } else {
1008         for (ti = as->parms[P_OUTPUT].items; ti; ti = ti->next) {
1009             if (AddOutputColumn(ti->data) != 0) {;
1010                 fprintf(stderr, "%s: Unknown -output value: %s\n", progname,
1011                         ti->data);
1012                 return 1;
1013             }
1014         }
1015     }
1016
1017     if (FindVnType & FIND_DIR) {
1018         AddVnodeHandler(vLarge, PrintVnodeDetails, NULL);
1019     }
1020     if (FindVnType & (FIND_FILE | FIND_MOUNT | FIND_SYMLINK)) {
1021         AddVnodeHandler(vSmall, PrintVnodeDetails, NULL);
1022     }
1023     if (FindVnType & FIND_ACL) {
1024         AddVnodeHandler(vLarge, ScanAcl, NULL);
1025     }
1026
1027     return ScanPartitions(partNameOrId, volumeId);
1028 }
1029
1030 /**
1031  * Determine if the current directory is a vice partition
1032  *
1033  * @return disk partition object
1034  */
1035 #ifdef AFS_NT40_ENV
1036 #include <direct.h>
1037 struct DiskPartition64 *
1038 FindCurrentPartition(void)
1039 {
1040     int dr = _getdrive();
1041     struct DiskPartition64 *dp;
1042
1043     dr--;
1044     for (dp = DiskPartitionList; dp; dp = dp->next) {
1045         if (*dp->devName - 'A' == dr)
1046             break;
1047     }
1048     if (!dp) {
1049         fprintf(stderr, "%s: Current drive is not a valid vice partition.\n",
1050                 progname);
1051     }
1052     return dp;
1053 }
1054 #else
1055 struct DiskPartition64 *
1056 FindCurrentPartition(void)
1057 {
1058     char partName[1024];
1059     char tmp = '\0';
1060     char *p;
1061     struct DiskPartition64 *dp;
1062
1063     if (!getcwd(partName, 1023)) {
1064         fprintf(stderr, "%s: Failed to get current working directory: ",
1065                 progname);
1066         perror("pwd");
1067         return NULL;
1068     }
1069     p = strchr(&partName[1], OS_DIRSEPC);
1070     if (p) {
1071         tmp = *p;
1072         *p = '\0';
1073     }
1074     if (!(dp = VGetPartition(partName, 0))) {
1075         if (tmp)
1076             *p = tmp;
1077         fprintf(stderr, "%s: %s is not a valid vice partition.\n", progname,
1078                 partName);
1079         return NULL;
1080     }
1081     return dp;
1082 }
1083 #endif
1084
1085 /**
1086  * Scan and handle all the partitions detected on this server
1087  *
1088  * @return none
1089  */
1090 void
1091 HandleAllPart(void)
1092 {
1093     struct DiskPartition64 *partP;
1094
1095
1096     for (partP = DiskPartitionList; partP; partP = partP->next) {
1097         if (DumpInfo || SaveInodes || ShowSizes) {
1098             printf("Processing Partition %s:\n", partP->name);
1099         }
1100         HandlePart(partP);
1101         if (ShowSizes) {
1102             AddSizeTotals(&serverTotals, &partitionTotals);
1103         }
1104     }
1105
1106     if (ShowSizes) {
1107         PrintServerTotals();
1108     }
1109 }
1110
1111 /**
1112  * Scan the partition and handle volumes
1113  *
1114  * @param[in] partP  disk partition to scan
1115  *
1116  * @return none
1117  */
1118 void
1119 HandlePart(struct DiskPartition64 *partP)
1120 {
1121     afs_int64 nvols = 0;
1122     DIR *dirp;
1123     struct dirent *dp;
1124 #ifdef AFS_NT40_ENV
1125     char pname[64];
1126     char *p = pname;
1127     (void)sprintf(pname, "%s\\", VPartitionPath(partP));
1128 #else
1129     char *p = VPartitionPath(partP);
1130 #endif
1131
1132     if ((dirp = opendir(p)) == NULL) {
1133         fprintf(stderr, "%s: Can't read directory %s; giving up\n", progname,
1134                 p);
1135         return;
1136     }
1137     while ((dp = readdir(dirp))) {
1138         p = (char *)strrchr(dp->d_name, '.');
1139         if (p != NULL && strcmp(p, VHDREXT) == 0) {
1140             HandleVolume(partP, dp->d_name);
1141             if (ShowSizes) {
1142                 nvols++;
1143                 AddSizeTotals(&partitionTotals, &volumeTotals);
1144             }
1145         }
1146     }
1147     closedir(dirp);
1148     if (ShowSizes) {
1149         PrintPartitionTotals(nvols);
1150     }
1151 }
1152
1153 /**
1154  * Inspect a volume header special file.
1155  *
1156  * @param[in]  name       descriptive name of the type of header special file
1157  * @param[in]  dp         partition object for this volume
1158  * @param[in]  header     header object for this volume
1159  * @param[in]  inode      fileserver inode number for this header special file
1160  * @param[out] psize      total of the header special file
1161  *
1162  * @return none
1163  */
1164 void
1165 HandleSpecialFile(const char *name, struct DiskPartition64 *dp,
1166                   struct VolumeHeader *header, Inode inode,
1167                   afs_sfsize_t * psize)
1168 {
1169     afs_sfsize_t size = 0;
1170     IHandle_t *ih = NULL;
1171     FdHandle_t *fdP = NULL;
1172 #ifdef AFS_NAMEI_ENV
1173     namei_t filename;
1174 #endif /* AFS_NAMEI_ENV */
1175
1176     IH_INIT(ih, dp->device, header->parent, inode);
1177     fdP = IH_OPEN(ih);
1178     if (fdP == NULL) {
1179         fprintf(stderr,
1180                 "%s: Error opening header file '%s' for volume %u", progname,
1181                 name, header->id);
1182         perror("open");
1183         goto error;
1184     }
1185     size = FDH_SIZE(fdP);
1186     if (size == -1) {
1187         fprintf(stderr,
1188                 "%s: Error getting size of header file '%s' for volume %u",
1189                 progname, name, header->id);
1190         perror("fstat");
1191         goto error;
1192     }
1193     if (DumpInfo) {
1194         printf("\t%s inode\t= %s (size = %lld)\n",
1195                name, PrintInode(NULL, inode), size);
1196 #ifdef AFS_NAMEI_ENV
1197         namei_HandleToName(&filename, ih);
1198         printf("\t%s namei\t= %s\n", name, filename.n_path);
1199 #endif /* AFS_NAMEI_ENV */
1200     }
1201     *psize += size;
1202
1203   error:
1204     if (fdP != NULL) {
1205         FDH_REALLYCLOSE(fdP);
1206     }
1207     if (ih != NULL) {
1208         IH_RELEASE(ih);
1209     }
1210 }
1211
1212 /**
1213  * Inspect this volume header files.
1214  *
1215  * @param[in]  dp         partition object for this volume
1216  * @param[in]  header_fd  volume header file descriptor
1217  * @param[in]  header     volume header object
1218  * @param[out] psize      total of the header special file
1219  *
1220  * @return none
1221  */
1222 void
1223 HandleHeaderFiles(struct DiskPartition64 *dp, FD_t header_fd,
1224                   struct VolumeHeader *header)
1225 {
1226     afs_sfsize_t size = 0;
1227
1228     if (DumpInfo) {
1229         size = OS_SIZE(header_fd);
1230         printf("Volume header (size = %lld):\n", size);
1231         printf("\tstamp\t= 0x%x\n", header->stamp.version);
1232         printf("\tVolId\t= %u\n", header->id);
1233         printf("\tparent\t= %u\n", header->parent);
1234     }
1235
1236     HandleSpecialFile("Info", dp, header, header->volumeInfo, &size);
1237     HandleSpecialFile("Small", dp, header, header->smallVnodeIndex,
1238                       &size);
1239     HandleSpecialFile("Large", dp, header, header->largeVnodeIndex,
1240                       &size);
1241 #ifdef AFS_NAMEI_ENV
1242     HandleSpecialFile("Link", dp, header, header->linkTable, &size);
1243 #endif /* AFS_NAMEI_ENV */
1244
1245     if (DumpInfo) {
1246         printf("Total aux volume size = %lld\n\n", size);
1247     }
1248
1249     if (ShowSizes) {
1250         volumeTotals.auxsize = size;
1251         volumeTotals.auxsize_k = size / 1024;
1252     }
1253 }
1254
1255 /**
1256  * Determine if the vnodes of this volume should be scanned.
1257  *
1258  * @param[in]  vp   volume object
1259  *
1260  * @return true if vnodes should be scanned
1261  */
1262 static int
1263 IsScannable(Volume * vp)
1264 {
1265     if (opr_queue_IsEmpty(&VnodeScanLists[vLarge]) &&
1266         opr_queue_IsEmpty(&VnodeScanLists[vSmall])) {
1267         return 0;
1268     }
1269     if (!ScanVolType) {
1270         return 1;               /* filtering disabled; do not check vol type */
1271     }
1272     switch (V_type(vp)) {
1273     case RWVOL:
1274         return ScanVolType & SCAN_RW;
1275     case ROVOL:
1276         return ScanVolType & SCAN_RO;
1277     case BACKVOL:
1278         return ScanVolType & SCAN_BK;
1279     default:
1280         fprintf(stderr, "%s: Volume %u; Unknown volume type %d\n", progname,
1281                 V_id(vp), V_type(vp));
1282         break;
1283     }
1284     return 0;
1285 }
1286
1287 /**
1288  * Attach and scan the volume and handle the header and vnodes
1289  *
1290  * Print the volume header and vnode information, depending on the
1291  * current modes.
1292  *
1293  * @param[in] dp    vice partition object for this volume
1294  * @param[in] name  volume header file name
1295  *
1296  * @return none
1297  */
1298 void
1299 HandleVolume(struct DiskPartition64 *dp, char *name)
1300 {
1301     struct VolumeHeader header;
1302     struct VolumeDiskHeader diskHeader;
1303     FD_t fd = INVALID_FD;
1304     Volume *vp = NULL;
1305     char headerName[1024];
1306     afs_sfsize_t n;
1307
1308     snprintf(headerName, sizeof headerName, "%s" OS_DIRSEP "%s",
1309              VPartitionPath(dp), name);
1310     if ((fd = OS_OPEN(headerName, O_RDONLY, 0666)) == INVALID_FD) {
1311         fprintf(stderr, "%s: Cannot open volume header %s\n", progname, name);
1312         goto cleanup;
1313     }
1314     if (OS_SIZE(fd) < 0) {
1315         fprintf(stderr, "%s: Cannot read volume header %s\n", progname, name);
1316         goto cleanup;
1317     }
1318     n = OS_READ(fd, &diskHeader, sizeof(diskHeader));
1319     if (n != sizeof(diskHeader)
1320         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1321         fprintf(stderr, "%s: Error reading volume header %s\n", progname,
1322                 name);
1323         goto cleanup;
1324     }
1325     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1326         fprintf(stderr,
1327                 "%s: Volume %s, version number is incorrect; volume needs to be salvaged\n",
1328                 progname, name);
1329         goto cleanup;
1330     }
1331
1332     DiskToVolumeHeader(&header, &diskHeader);
1333     if (DumpHeader || ShowSizes) {
1334         HandleHeaderFiles(dp, fd, &header);
1335     }
1336
1337     vp = AttachVolume(dp, name, &header);
1338     if (!vp) {
1339         fprintf(stderr, "%s: Error attaching volume header %s\n",
1340                 progname, name);
1341         goto cleanup;
1342     }
1343
1344     if (DumpInfo) {
1345         PrintHeader(vp);
1346     }
1347     if (IsScannable(vp)) {
1348         if (NeedDirIndex) {
1349             IHandle_t *ih = vp->vnodeIndex[vLarge].handle;
1350             DirIndexFd = IH_OPEN(ih);
1351             if (DirIndexFd == NULL) {
1352                 fprintf(stderr, "%s: Failed to open index for directories.",
1353                         progname);
1354             }
1355         }
1356
1357         HandleVnodes(vp, vLarge);
1358         HandleVnodes(vp, vSmall);
1359
1360         if (DirIndexFd) {
1361             FDH_CLOSE(DirIndexFd);
1362             DirIndexFd = NULL;
1363         }
1364     }
1365     if (ShowSizes) {
1366         volumeTotals.diskused_k = V_diskused(vp);
1367         volumeTotals.size_k =
1368             volumeTotals.auxsize_k + volumeTotals.vnodesize_k;
1369         if (SaveInodes) {
1370             PrintingVolumeSizes = 0;    /* print heading again */
1371         }
1372         PrintVolumeSizes(vp);
1373     }
1374
1375   cleanup:
1376     if (fd != INVALID_FD) {
1377         OS_CLOSE(fd);
1378     }
1379     if (vp) {
1380         DetachVolume(vp);
1381     }
1382 }
1383
1384 /**
1385  * Declare volinfo command line syntax
1386  *
1387  * @returns none
1388  */
1389 static void
1390 VolInfoSyntax(void)
1391 {
1392     struct cmd_syndesc *ts;
1393
1394     ts = cmd_CreateSyntax(NULL, VolInfo, NULL,
1395                           "Dump volume's internal state");
1396     cmd_AddParmAtOffset(ts, P_CHECKOUT, "-checkout", CMD_FLAG, CMD_OPTIONAL,
1397                         "Checkout volumes from running fileserver");
1398     cmd_AddParmAtOffset(ts, P_VNODE, "-vnode", CMD_FLAG, CMD_OPTIONAL,
1399                         "Dump vnode info");
1400     cmd_AddParmAtOffset(ts, P_DATE, "-date", CMD_FLAG, CMD_OPTIONAL,
1401                         "Also dump vnode's mod date");
1402     cmd_AddParmAtOffset(ts, P_INODE, "-inode", CMD_FLAG, CMD_OPTIONAL,
1403                         "Also dump vnode's inode number");
1404     cmd_AddParmAtOffset(ts, P_ITIME, "-itime", CMD_FLAG, CMD_OPTIONAL,
1405                         "Dump special inode's mod times");
1406     cmd_AddParmAtOffset(ts, P_PART, "-part", CMD_LIST, CMD_OPTIONAL,
1407                         "AFS partition name or id (default current partition)");
1408     cmd_AddParmAtOffset(ts, P_VOLUMEID, "-volumeid", CMD_LIST, CMD_OPTIONAL,
1409                         "Volume id");
1410     cmd_AddParmAtOffset(ts, P_HEADER, "-header", CMD_FLAG, CMD_OPTIONAL,
1411                         "Dump volume's header info");
1412     cmd_AddParmAtOffset(ts, P_SIZEONLY, "-sizeonly", CMD_FLAG, CMD_OPTIONAL,
1413                         "Dump volume's size");
1414     cmd_AddParmAtOffset(ts, P_FIXHEADER, "-fixheader", CMD_FLAG,
1415                         CMD_OPTIONAL, "Try to fix header");
1416     cmd_AddParmAtOffset(ts, P_SAVEINODES, "-saveinodes", CMD_FLAG,
1417                         CMD_OPTIONAL, "Try to save all inodes");
1418     cmd_AddParmAtOffset(ts, P_ORPHANED, "-orphaned", CMD_FLAG, CMD_OPTIONAL,
1419                         "List all dir/files without a parent");
1420 #if defined(AFS_NAMEI_ENV)
1421     cmd_AddParmAtOffset(ts, P_FILENAMES, "-filenames", CMD_FLAG,
1422                         CMD_OPTIONAL, "Also dump vnode's namei filename");
1423 #endif
1424
1425     /* For compatibility with older versions. */
1426     cmd_AddParmAlias(ts, P_SIZEONLY, "-sizeOnly");
1427 }
1428
1429 /**
1430  * Declare volscan command line syntax
1431  *
1432  * @returns none
1433  */
1434 static void
1435 VolScanSyntax(void)
1436 {
1437     struct cmd_syndesc *ts;
1438
1439     ts = cmd_CreateSyntax(NULL, VolScan, NULL,
1440                           "Print volume vnode information");
1441
1442     cmd_AddParmAtOffset(ts, P_CHECKOUT, "-checkout", CMD_FLAG, CMD_OPTIONAL,
1443                         "Checkout volumes from running fileserver");
1444     cmd_AddParmAtOffset(ts, P_PART, "-partition", CMD_SINGLE, CMD_OPTIONAL,
1445                         "AFS partition name or id (default current partition)");
1446     cmd_AddParmAtOffset(ts, P_VOLUMEID, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
1447                         "Volume id (-partition required)");
1448     cmd_AddParmAtOffset(ts, P_TYPE, "-type", CMD_LIST, CMD_OPTIONAL,
1449                         "Volume types: rw, ro, bk");
1450     cmd_AddParmAtOffset(ts, P_FIND, "-find", CMD_LIST, CMD_OPTIONAL,
1451                         "Objects to find: file, dir, mount, symlink, acl");
1452     cmd_AddParmAtOffset(ts, P_MASK, "-mask", CMD_LIST, CMD_OPTIONAL,
1453                         "Unix mode mask (example: 06000)");
1454     cmd_AddParmAtOffset(ts, P_OUTPUT, "-output", CMD_LIST, CMD_OPTIONAL,
1455                         ColumnNames);
1456     cmd_AddParmAtOffset(ts, P_DELIM, "-delim", CMD_SINGLE, CMD_OPTIONAL,
1457                         "Output field delimiter");
1458     cmd_AddParmAtOffset(ts, P_NOHEADING, "-noheading", CMD_FLAG, CMD_OPTIONAL,
1459                         "Do not print the heading line");
1460 }
1461
1462 /**
1463  * volinfo/volscan program entry
1464  */
1465 int
1466 main(int argc, char **argv)
1467 {
1468     afs_int32 code;
1469     char *base;
1470
1471     opr_queue_Init(&VnodeScanLists[vLarge]);
1472     opr_queue_Init(&VnodeScanLists[vSmall]);
1473     memset(ModeMask, 0, sizeof(ModeMask) / sizeof(*ModeMask));
1474     gethostname(Hostname, sizeof(Hostname));
1475
1476     base = strrchr(argv[0], '/');
1477 #ifdef AFS_NT40_ENV
1478     if (!base) {
1479         base = strrchr(argv[0], '\\');
1480     }
1481 #endif /* AFS_NT40_ENV */
1482     if (!base) {
1483         base = argv[0];
1484     }
1485 #ifdef AFS_NT40_ENV
1486     if ((base[0] == '/' || base[0] == '\\') && base[1] != '\0') {
1487 #else /* AFS_NT40_ENV */
1488     if (base[0] == '/' && base[1] != '\0') {
1489 #endif /* AFS_NT40_ENV */
1490         base++;
1491     }
1492     progname = base;
1493
1494 #ifdef AFS_NT40_ENV
1495     if (stricmp(progname, "volscan") == 0
1496         || stricmp(progname, "volscan.exe") == 0) {
1497 #else /* AFS_NT40_ENV */
1498     if (strcmp(progname, "volscan") == 0) {
1499 #endif /* AFS_NT40_ENV */
1500         VolScanSyntax();
1501     } else {
1502         VolInfoSyntax();
1503     }
1504
1505     code = cmd_Dispatch(argc, argv);
1506     return code;
1507 }
1508
1509 /**
1510  * Return a display string for the volume type.
1511  *
1512  * @param[in]  type  volume type
1513  *
1514  * @return volume type description string
1515  */
1516 static_inline char *
1517 volumeTypeString(int type)
1518 {
1519     return
1520         (type == RWVOL ? "read/write" :
1521          (type == ROVOL ? "readonly" :
1522           (type == BACKVOL ? "backup" : "unknown")));
1523 }
1524
1525 /**
1526  * Return a short display string for the volume type.
1527  *
1528  * @param[in]  type  volume type
1529  *
1530  * @return volume type short description string
1531  */
1532 static_inline char *
1533 volumeTypeShortString(int type)
1534 {
1535     return
1536         (type == RWVOL ? "RW" :
1537          (type == ROVOL ? "RO" : (type == BACKVOL ? "BK" : "??")));
1538 }
1539
1540 /**
1541  * Print the volume header information
1542  *
1543  * @param[in]  volume object
1544  *
1545  * @return none
1546  */
1547 void
1548 PrintHeader(Volume * vp)
1549 {
1550     printf("Volume header for volume %u (%s)\n", V_id(vp), V_name(vp));
1551     printf("stamp.magic = %x, stamp.version = %u\n", V_stamp(vp).magic,
1552            V_stamp(vp).version);
1553     printf
1554         ("inUse = %d, inService = %d, blessed = %d, needsSalvaged = %d, dontSalvage = %d\n",
1555          V_inUse(vp), V_inService(vp), V_blessed(vp), V_needsSalvaged(vp),
1556          V_dontSalvage(vp));
1557     printf
1558         ("type = %d (%s), uniquifier = %u, needsCallback = %d, destroyMe = %x\n",
1559          V_type(vp), volumeTypeString(V_type(vp)), V_uniquifier(vp),
1560          V_needsCallback(vp), V_destroyMe(vp));
1561     printf
1562         ("id = %u, parentId = %u, cloneId = %u, backupId = %u, restoredFromId = %u\n",
1563          V_id(vp), V_parentId(vp), V_cloneId(vp), V_backupId(vp),
1564          V_restoredFromId(vp));
1565     printf
1566         ("maxquota = %d, minquota = %d, maxfiles = %d, filecount = %d, diskused = %d\n",
1567          V_maxquota(vp), V_minquota(vp), V_maxfiles(vp), V_filecount(vp),
1568          V_diskused(vp));
1569     printf("creationDate = %s, copyDate = %s\n", date(V_creationDate(vp)),
1570            date(V_copyDate(vp)));
1571     printf("backupDate = %s, expirationDate = %s\n", date(V_backupDate(vp)),
1572            date(V_expirationDate(vp)));
1573     printf("accessDate = %s, updateDate = %s\n", date(V_accessDate(vp)),
1574            date(V_updateDate(vp)));
1575     printf("owner = %u, accountNumber = %u\n", V_owner(vp),
1576            V_accountNumber(vp));
1577     printf
1578         ("dayUse = %u; week = (%u, %u, %u, %u, %u, %u, %u), dayUseDate = %s\n",
1579          V_dayUse(vp), V_weekUse(vp)[0], V_weekUse(vp)[1], V_weekUse(vp)[2],
1580          V_weekUse(vp)[3], V_weekUse(vp)[4], V_weekUse(vp)[5],
1581          V_weekUse(vp)[6], date(V_dayUseDate(vp)));
1582     printf("volUpdateCounter = %u\n", V_volUpCounter(vp));
1583 }
1584
1585 /**
1586  * Get the size and times of a file
1587  *
1588  * @param[in]  fd     file descriptor of file to stat
1589  * @param[out] size   size of the file
1590  * @param[out] ctime  ctime of file as a formatted string
1591  * @param[out] mtime  mtime of file as a formatted string
1592  * @param[out] atime  atime of file as a formatted string
1593  *
1594  * @return error code
1595  *   @retval 0 success
1596  *   @retval -1 failed to retrieve file information
1597  */
1598 static int
1599 GetFileInfo(FD_t fd, afs_sfsize_t * size, char **ctime, char **mtime,
1600             char **atime)
1601 {
1602 #ifdef AFS_NT40_ENV
1603     BY_HANDLE_FILE_INFORMATION fi;
1604     LARGE_INTEGER fsize;
1605     if (!GetFileInformationByHandle(fd, &fi)) {
1606         fprintf(stderr, "%s: GetFileInformationByHandle failed\n", progname);
1607         return -1;
1608     }
1609     if (!GetFileSizeEx(fd, &fsize)) {
1610         fprintf(stderr, "%s: GetFileSizeEx failed\n", progname);
1611         return -1;
1612     }
1613     *size = fsize.QuadPart;
1614     *ctime = "N/A";
1615     *mtime = NT_date(&fi.ftLastWriteTime);
1616     *atime = NT_date(&fi.ftLastAccessTime);
1617 #else
1618     struct afs_stat_st status;
1619     if (afs_fstat(fd, &status) == -1) {
1620         fprintf(stderr, "%s: fstat failed %d\n", progname, errno);
1621         return -1;
1622     }
1623     *size = status.st_size;
1624     *ctime = date(status.st_ctime);
1625     *mtime = date(status.st_mtime);
1626     *atime = date(status.st_atime);
1627 #endif
1628     return 0;
1629 }
1630
1631 /**
1632  * Copy the inode data to a file in the current directory.
1633  *
1634  * @param[in] vdp     vnode details object
1635  *
1636  * @return none
1637  */
1638 static void
1639 SaveInode(struct VnodeDetails *vdp)
1640 {
1641     IHandle_t *ih;
1642     FdHandle_t *fdP;
1643     char nfile[50], buffer[256];
1644     int ofd = 0;
1645     afs_foff_t total;
1646     ssize_t len;
1647     Inode ino = VNDISK_GET_INO(vdp->vnode);
1648
1649     if (!VALID_INO(ino)) {
1650         return;
1651     }
1652
1653     IH_INIT(ih, V_device(vdp->vp), V_parentId(vdp->vp), ino);
1654     fdP = IH_OPEN(ih);
1655     if (fdP == NULL) {
1656         fprintf(stderr,
1657                 "%s: Can't open inode %s error %d (ignored)\n",
1658                 progname, PrintInode(NULL, ino), errno);
1659         return;
1660     }
1661     snprintf(nfile, sizeof nfile, "TmpInode.%s", PrintInode(NULL, ino));
1662     ofd = afs_open(nfile, O_CREAT | O_RDWR | O_TRUNC, 0600);
1663     if (ofd < 0) {
1664         fprintf(stderr,
1665                 "%s: Can't create file %s; error %d (ignored)\n",
1666                 progname, nfile, errno);
1667
1668         FDH_REALLYCLOSE(fdP);
1669         IH_RELEASE(ih);
1670         return;
1671     }
1672     total = 0;
1673     while (1) {
1674         ssize_t nBytes;
1675         len = FDH_PREAD(fdP, buffer, sizeof(buffer), total);
1676         if (len < 0) {
1677             FDH_REALLYCLOSE(fdP);
1678             IH_RELEASE(ih);
1679             close(ofd);
1680             unlink(nfile);
1681             fprintf(stderr,
1682                     "%s: Error while reading from inode %s (%d)\n",
1683                     progname, PrintInode(NULL, ino), errno);
1684             return;
1685         }
1686         if (len == 0)
1687             break;              /* No more input */
1688         nBytes = write(ofd, buffer, (size_t)len);
1689         if (nBytes != len) {
1690             FDH_REALLYCLOSE(fdP);
1691             IH_RELEASE(ih);
1692             close(ofd);
1693             unlink(nfile);
1694             fprintf(stderr,
1695                     "%s: Error while writing to \"%s\" (%d - ignored)\n",
1696                     progname, nfile, errno);
1697             return;
1698         }
1699         total += len;
1700     }
1701
1702     FDH_REALLYCLOSE(fdP);
1703     IH_RELEASE(ih);
1704     close(ofd);
1705     printf("... Copied inode %s to file %s (%lu bytes)\n",
1706            PrintInode(NULL, ino), nfile, (unsigned long)total);
1707 }
1708
1709 /**
1710  * get the VnodeDiskObject for a directory given its vnode id.
1711  *
1712  * @param[in]   vp       volume object
1713  * @param[in]   parent   vnode id to read
1714  * @param[out]  pvn      vnode disk object to populate
1715  *
1716  * @post pvn contains copy of disk object for parent id
1717  *
1718  * @return operation status
1719  *   @retval 0   success
1720  *   @retval -1  failure
1721  */
1722 int
1723 GetDirVnode(Volume * vp, VnodeId parent, VnodeDiskObject * pvn)
1724 {
1725     afs_int32 code;
1726     afs_foff_t offset;
1727
1728     if (!DirIndexFd) {
1729         return -1;              /* previously failed to open the large vnode index. */
1730     }
1731     if (parent % 2 == 0) {
1732         fprintf(stderr, "%s: Invalid parent vnode id %lu in volume %lu\n",
1733                 progname,
1734                 afs_printable_uint32_lu(parent),
1735                 afs_printable_uint32_lu(V_id(vp)));
1736     }
1737     offset = vnodeIndexOffset(&VnodeClassInfo[vLarge], parent);
1738     code = FDH_SEEK(DirIndexFd, offset, 0);
1739     if (code == -1) {
1740         fprintf(stderr,
1741                 "%s: GetDirVnode: seek failed for %lu.%lu to offset %llu\n",
1742                 progname, afs_printable_uint32_lu(V_id(vp)),
1743                 afs_printable_uint32_lu(parent), (long long unsigned)offset);
1744         return -1;
1745     }
1746     code = FDH_READ(DirIndexFd, pvn, SIZEOF_LARGEDISKVNODE);
1747     if (code != SIZEOF_LARGEDISKVNODE) {
1748         fprintf(stderr,
1749                 "%s: GetDirVnode: read failed for %lu.%lu at offset %llu\n",
1750                 progname, afs_printable_uint32_lu(V_id(vp)),
1751                 afs_printable_uint32_lu(parent), (long long unsigned)offset);
1752         return -1;
1753     }
1754     if (pvn->vnodeMagic != LARGEVNODEMAGIC) {
1755         fprintf(stderr, "%s: GetDirVnode: bad vnode magic\n", progname);
1756         return -1;
1757     }
1758     if (!pvn->dataVersion) {
1759         fprintf(stderr, "%s: GetDirVnode: dv is zero\n", progname);
1760         return -1;
1761     }
1762     return 0;
1763 }
1764
1765 /**
1766  * Perform inverse lookup on a vice directory object to map a fid onto a dirent string.
1767  *
1768  * @param[in]   vp          volume object
1769  * @param[in]   pvnode      parent directory vnode object
1770  * @param[in]   cvnid       child vnode id to inverse lookup
1771  * @param[in]   cuniq       child uniquifier to inverse lookup
1772  * @param[out]  dirent      buffer in which to store dirent string
1773  * @param[out]  dirent_len  length of dirent buffer
1774  *
1775  * @post dirent contains string for the (cvnid, cuniq) entry
1776  *
1777  * @return operation status
1778  *    @retval 0 success
1779  */
1780 static int
1781 GetDirEntry(Volume * vp, VnodeDiskObject * pvnode, VnodeId cvnid,
1782             afs_uint32 cuniq, char *dirent, size_t dirent_len)
1783 {
1784     DirHandle dir;
1785     Inode ino;
1786     int volumeChanged;
1787     afs_int32 code;
1788
1789     ino = VNDISK_GET_INO(pvnode);
1790     if (!VALID_INO(ino)) {
1791         fprintf(stderr, "%s: GetDirEntry invalid parent ino\n", progname);
1792         return -1;
1793     }
1794     SetSalvageDirHandle(&dir, V_parentId(vp), V_device(vp), ino,
1795                         &volumeChanged);
1796     code = afs_dir_InverseLookup(&dir, cvnid, cuniq, dirent, dirent_len);
1797     if (code) {
1798         fprintf(stderr, "%s: afs_dir_InverseLookup failed with code %d\n",
1799                 progname, code);
1800     }
1801     FidZap(&dir);
1802     return code;
1803 }
1804
1805 /**
1806  * Lookup the path of this vnode, relative to the root of the volume.
1807  *
1808  * @param[in] vdp    vnode details
1809  *
1810  * @return status
1811  *   @retval 0 success
1812  *   @retval -1 error
1813  */
1814 int
1815 LookupPath(struct VnodeDetails *vdp)
1816 {
1817 #define MAX_PATH_LEN 1023
1818     static char path_buffer[MAX_PATH_LEN + 1];
1819     static char dirent[MAX_PATH_LEN + 1];
1820     char vnode_buffer[SIZEOF_LARGEDISKVNODE];
1821     struct VnodeDiskObject *pvn = (struct VnodeDiskObject *)vnode_buffer;
1822     int code = 0;
1823     int space;
1824     char *cursor;
1825     Volume *vp = vdp->vp;
1826     VnodeId parent = vdp->vnode->parent;
1827     VnodeId cvnid = vdp->vnodeNumber;
1828     afs_uint32 cuniq = vdp->vnode->uniquifier;
1829
1830     if (!parent) {
1831         vdp->path = "/";        /* this is root */
1832         return 0;
1833     }
1834
1835     space = sizeof(path_buffer) - 1;
1836     cursor = &path_buffer[space];
1837     *cursor = '\0';
1838
1839     while (parent) {
1840         int len;
1841
1842         code = GetDirVnode(vp, parent, pvn);
1843         if (code) {
1844             cursor = NULL;
1845             break;
1846         }
1847         code = GetDirEntry(vp, pvn, cvnid, cuniq, dirent, MAX_PATH_LEN);
1848         if (code) {
1849             cursor = NULL;
1850             break;
1851         }
1852
1853         len = strlen(dirent);
1854         if (len == 0) {
1855             fprintf(stderr,
1856                     "%s: Failed to lookup path for fid %lu.%lu.%lu: empty dir entry\n",
1857                     progname, afs_printable_uint32_lu(V_id(vdp->vp)),
1858                     afs_printable_uint32_lu(vdp->vnodeNumber),
1859                     afs_printable_uint32_lu(vdp->vnode->uniquifier));
1860             cursor = NULL;
1861             code = -1;
1862             break;
1863         }
1864
1865         if (space < (len + 1)) {
1866             fprintf(stderr,
1867                     "%s: Failed to lookup path for fid %lu.%lu.%lu: path exceeds max length (%u).\n",
1868                     progname, afs_printable_uint32_lu(V_id(vdp->vp)),
1869                     afs_printable_uint32_lu(vdp->vnodeNumber),
1870                     afs_printable_uint32_lu(vdp->vnode->uniquifier),
1871                     MAX_PATH_LEN);
1872             cursor = NULL;
1873             code = -1;
1874             break;
1875         }
1876
1877         /* prepend path component */
1878         cursor -= len;
1879         memcpy(cursor, dirent, len);
1880         *--cursor = '/';
1881         space -= (len + 1);
1882
1883         /* next parent */
1884         cvnid = parent;
1885         cuniq = pvn->uniquifier;
1886         parent = pvn->parent;
1887     }
1888
1889     if (cursor) {
1890         vdp->path = cursor;
1891     }
1892     return code;
1893 }
1894
1895 /**
1896  * Read the symlink target and determine if this vnode is a mount point.
1897  *
1898  * @param[inout]   vdp    vnode details object
1899  *
1900  * @return error code
1901  *   @retval 0 success
1902  *   @retval -1 failure
1903  */
1904 static int
1905 ReadSymlinkTarget(struct VnodeDetails *vdp)
1906 {
1907 #define MAX_SYMLINK_LEN 1023
1908     static char buffer[MAX_SYMLINK_LEN + 1];
1909     int code;
1910     Volume *vp = vdp->vp;
1911     VnodeDiskObject *vnode = vdp->vnode;
1912     VnodeId vnodeNumber = vdp->vnodeNumber;
1913     IHandle_t *ihP = NULL;
1914     FdHandle_t *fdP = NULL;
1915     afs_fsize_t fileLength;
1916     int readLength;
1917     Inode ino;
1918
1919     ino = VNDISK_GET_INO(vnode);
1920     VNDISK_GET_LEN(fileLength, vnode);
1921
1922     if (fileLength > MAX_SYMLINK_LEN) {
1923         fprintf(stderr,
1924                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) exceeds "
1925                 "%u, file length is %llu)!\n", progname,
1926                 afs_printable_uint32_lu(V_id(vp)),
1927                 afs_printable_uint32_lu(vnodeNumber),
1928                 afs_printable_uint32_lu(vnode->uniquifier),
1929                 afs_printable_uint32_lu(vnode->dataVersion),
1930                 MAX_SYMLINK_LEN,
1931                 fileLength);
1932         return -1;
1933     }
1934     if (fileLength == 0) {
1935         fprintf(stderr,
1936                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) is empty.\n",
1937                 progname,
1938                 afs_printable_uint32_lu(V_id(vp)),
1939                 afs_printable_uint32_lu(vnodeNumber),
1940                 afs_printable_uint32_lu(vnode->uniquifier),
1941                 afs_printable_uint32_lu(vnode->dataVersion));
1942         return -1;
1943     }
1944
1945     IH_INIT(ihP, V_device(vp), V_parentId(vp), ino);
1946     fdP = IH_OPEN(ihP);
1947     if (fdP == NULL) {
1948         code = -1;
1949         goto cleanup;
1950     }
1951     if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1952         code = -1;
1953         goto cleanup;
1954     }
1955     readLength = FDH_READ(fdP, buffer, fileLength);
1956     if (readLength < 0) {
1957         fprintf(stderr,
1958                 "%s: Error reading symlink contents for fid (%lu.%lu.%lu.%lu); "
1959                 "errno %d\n",
1960                 progname,
1961                 afs_printable_uint32_lu(V_id(vp)),
1962                 afs_printable_uint32_lu(vnodeNumber),
1963                 afs_printable_uint32_lu(vnode->uniquifier),
1964                 afs_printable_uint32_lu(vnode->dataVersion), errno);
1965         code = -1;
1966         goto cleanup;
1967     } else if (readLength != fileLength) {
1968         fprintf(stderr,
1969                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) don't match "
1970                 "vnode file length metadata (len=%llu, actual=%lld)!\n",
1971                 progname,
1972                 afs_printable_uint32_lu(V_id(vp)),
1973                 afs_printable_uint32_lu(vnodeNumber),
1974                 afs_printable_uint32_lu(vnode->uniquifier),
1975                 afs_printable_uint32_lu(vnode->dataVersion), fileLength,
1976                 (long long)readLength);
1977         code = -1;
1978         goto cleanup;
1979     }
1980     code = 0;
1981
1982     if (readLength > 1 && (buffer[0] == '#' || buffer[0] == '%')
1983         && buffer[readLength - 1] == '.') {
1984         char *sep;
1985         buffer[readLength - 1] = '\0';  /* stringify; clobbers trailing dot */
1986         sep = strchr(buffer, ':');
1987         vdp->t = VNODE_U_MOUNT;
1988         vdp->u.mnt.type = buffer[0];
1989         if (!sep) {
1990             vdp->u.mnt.cell = NULL;
1991             vdp->u.mnt.vol = buffer + 1;
1992         } else {
1993             *sep = '\0';
1994             vdp->u.mnt.cell = buffer + 1;
1995             vdp->u.mnt.vol = sep + 1;
1996         }
1997     } else {
1998         buffer[readLength] = '\0';
1999         vdp->t = VNODE_U_SYMLINK;
2000         vdp->u.target = buffer;
2001     }
2002
2003   cleanup:
2004     if (fdP) {
2005         FDH_CLOSE(fdP);
2006     }
2007     if (ihP) {
2008         IH_RELEASE(ihP);
2009     }
2010     return code;
2011 }
2012
2013 /**
2014  * Print vnode details line
2015  *
2016  * @param[inout]  vdp   vnode details object
2017  *
2018  * @return none
2019  */
2020 static void
2021 PrintVnodeDetails(struct VnodeDetails *vdp)
2022 {
2023     switch (vdp->vnode->type) {
2024     case vNull:
2025         break;
2026     case vFile:
2027         if (FindVnType & FIND_FILE) {
2028             PrintColumns(vdp, "file");
2029         }
2030         break;
2031     case vDirectory:
2032         if (FindVnType & FIND_DIR) {
2033             PrintColumns(vdp, "dir");
2034         }
2035         break;
2036     case vSymlink:
2037         if (FindVnType & (FIND_MOUNT | FIND_SYMLINK)) {
2038             ReadSymlinkTarget(vdp);
2039             if ((FindVnType & FIND_MOUNT) && (vdp->t == VNODE_U_MOUNT)) {
2040                 PrintColumns(vdp, "mount");
2041             }
2042             if ((FindVnType & FIND_SYMLINK) && (vdp->t == VNODE_U_SYMLINK)) {
2043                 PrintColumns(vdp, "symlink");
2044             }
2045         }
2046         break;
2047     default:
2048         fprintf(stderr,
2049                 "%s: Warning: unexpected vnode type %u on fid %lu.%lu.%lu",
2050                 progname, vdp->vnode->type,
2051                 afs_printable_uint32_lu(V_id(vdp->vp)),
2052                 afs_printable_uint32_lu(vdp->vnodeNumber),
2053                 afs_printable_uint32_lu(vdp->vnode->uniquifier));
2054     }
2055 }
2056
2057 /**
2058  * Print each access entry of a vnode
2059  *
2060  * @param[in]  vdp   vnode details object
2061  *
2062  * @return none
2063  */
2064 static void
2065 ScanAcl(struct VnodeDetails *vdp)
2066 {
2067     int i;
2068     struct acl_accessList *acl;
2069     VnodeDiskObject *vnode = vdp->vnode;
2070
2071     if (vnode->type == vNull) {
2072         return;
2073     }
2074
2075     acl = VVnodeDiskACL(vnode);
2076     for (i = 0; i < acl->positive; i++) {
2077         vdp->t = VNODE_U_POS_ACCESS;
2078         vdp->u.access = &(acl->entries[i]);
2079         PrintColumns(vdp, "acl");
2080     }
2081     for (i = (acl->total - 1); i >= (acl->total - acl->negative); i--) {
2082         vdp->t = VNODE_U_NEG_ACCESS;
2083         vdp->u.access = &(acl->entries[i]);
2084         PrintColumns(vdp, "acl");
2085     }
2086 }
2087
2088 /**
2089  * Determine if the mode matches all the given masks.
2090  *
2091  * Returns true if the mode bits match all the given masks. A mask matches if at
2092  * least one bit in the mask is present in the mode bits.  An empty mode mask
2093  * list matches all modes (even if all the mode bits are zero.)
2094  *
2095  * param[in]  modeBits  unix mode bits of a vnode
2096  *
2097  */
2098 static int
2099 ModeMaskMatch(unsigned int modeBits)
2100 {
2101     int i;
2102
2103     for (i = 0; ModeMask[i] && i <= sizeof(ModeMask) / sizeof(*ModeMask); i++) {
2104         if ((ModeMask[i] & modeBits) == 0) {
2105             return 0;           /* at least one mode bit is not present */
2106         }
2107     }
2108     return 1;
2109 }
2110
2111 /**
2112  * Scan a volume index and handle each vnode
2113  *
2114  * @param[in] vp      volume object
2115  * @param[in] class   which index to scan
2116  *
2117  * @return none
2118  */
2119 void
2120 HandleVnodes(Volume * vp, VnodeClass class)
2121 {
2122     afs_int32 diskSize =
2123         (class == vSmall ? SIZEOF_SMALLDISKVNODE : SIZEOF_LARGEDISKVNODE);
2124     char buf[SIZEOF_LARGEDISKVNODE];
2125     struct VnodeDiskObject *vnode = (struct VnodeDiskObject *)buf;
2126     StreamHandle_t *file = NULL;
2127     int vnodeIndex;
2128     afs_sfsize_t nVnodes;
2129     afs_foff_t offset = 0;
2130     IHandle_t *ih = vp->vnodeIndex[class].handle;
2131     FdHandle_t *fdP = NULL;
2132     afs_sfsize_t size;
2133     char *ctime, *atime, *mtime;
2134     struct opr_queue *scanList = &VnodeScanLists[class];
2135     struct opr_queue *cursor;
2136
2137     if (opr_queue_IsEmpty(scanList)) {
2138         return;
2139     }
2140
2141     for (opr_queue_Scan(scanList, cursor)) {
2142         struct VnodeScanProc *entry = (struct VnodeScanProc *)cursor;
2143         if (entry->heading) {
2144             printf("%s", entry->heading);
2145         }
2146     }
2147
2148     fdP = IH_OPEN(ih);
2149     if (fdP == NULL) {
2150         fprintf(stderr, "%s: open failed: ", progname);
2151         goto error;
2152     }
2153
2154     file = FDH_FDOPEN(fdP, "r");
2155     if (!file) {
2156         fprintf(stderr, "%s: fdopen failed\n", progname);
2157         goto error;
2158     }
2159
2160     if (GetFileInfo(fdP->fd_fd, &size, &ctime, &atime, &mtime) != 0) {
2161         goto error;
2162     }
2163     if (InodeTimes) {
2164         printf("ichanged : %s\nimodified: %s\niaccessed: %s\n\n", ctime,
2165                mtime, atime);
2166     }
2167
2168     nVnodes = (size / diskSize) - 1;
2169     if (nVnodes > 0) {
2170         STREAM_ASEEK(file, diskSize);
2171     } else
2172         nVnodes = 0;
2173
2174     for (vnodeIndex = 0;
2175          nVnodes && STREAM_READ(vnode, diskSize, 1, file) == 1;
2176          nVnodes--, vnodeIndex++, offset += diskSize) {
2177
2178         struct VnodeDetails vnodeDetails;
2179
2180         if (!ModeMaskMatch(vnode->modeBits)) {
2181             continue;
2182         }
2183
2184         memset(&vnodeDetails, 0, sizeof(struct VnodeDetails));
2185         vnodeDetails.vp = vp;
2186         vnodeDetails.class = class;
2187         vnodeDetails.vnode = vnode;
2188         vnodeDetails.vnodeNumber = bitNumberToVnodeNumber(vnodeIndex, class);
2189         vnodeDetails.offset = offset;
2190         vnodeDetails.index = vnodeIndex;
2191
2192         for (opr_queue_Scan(scanList, cursor)) {
2193             struct VnodeScanProc *entry = (struct VnodeScanProc *)cursor;
2194             if (entry->proc) {
2195                 (*entry->proc) (&vnodeDetails);
2196             }
2197         }
2198     }
2199
2200   error:
2201     if (file) {
2202         STREAM_CLOSE(file);
2203     }
2204     if (fdP) {
2205         FDH_CLOSE(fdP);
2206     }
2207 }
2208
2209 /**
2210  * Print vnode information
2211  *
2212  * @param[in] vdp          vnode details object
2213  *
2214  * @return none
2215  */
2216 void
2217 PrintVnode(struct VnodeDetails *vdp)
2218 {
2219 #if defined(AFS_NAMEI_ENV)
2220     IHandle_t *ihtmpp;
2221     namei_t filename;
2222 #endif
2223     afs_foff_t offset = vdp->offset;
2224     VnodeDiskObject *vnode = vdp->vnode;
2225     afs_fsize_t fileLength;
2226     Inode ino;
2227
2228     ino = VNDISK_GET_INO(vnode);
2229     VNDISK_GET_LEN(fileLength, vnode);
2230
2231     /* The check for orphaned vnodes is currently limited to non-empty
2232      * vnodes with a parent of zero (and which are not the first entry
2233      * in the index). */
2234     if (ShowOrphaned && (fileLength == 0 || vnode->parent || !offset))
2235         return;
2236
2237     printf
2238         ("%10lld Vnode %u.%u.%u cloned: %u, length: %llu linkCount: %d parent: %u",
2239          (long long)offset, vdp->vnodeNumber, vnode->uniquifier,
2240          vnode->dataVersion, vnode->cloned, (afs_uintmax_t) fileLength,
2241          vnode->linkCount, vnode->parent);
2242     if (DumpInodeNumber)
2243         printf(" inode: %s", PrintInode(NULL, ino));
2244     if (DumpDate)
2245         printf(" ServerModTime: %s", date(vnode->serverModifyTime));
2246 #if defined(AFS_NAMEI_ENV)
2247     if (PrintFileNames) {
2248         IH_INIT(ihtmpp, V_device(vdp->vp), V_parentId(vdp->vp), ino);
2249         namei_HandleToName(&filename, ihtmpp);
2250 #if !defined(AFS_NT40_ENV)
2251         printf(" UFS-Filename: %s", filename.n_path);
2252 #else
2253         printf(" NTFS-Filename: %s", filename.n_path);
2254 #endif
2255     }
2256 #endif
2257     printf("\n");
2258 }
2259
2260 /**
2261  * Print the volume partition id
2262  *
2263  * @param[in]  vp  volume object
2264  *
2265  * @return none
2266  */
2267 static void
2268 PrintPartitionId(Volume * vp)
2269 {
2270     char *partition = VPartitionPath(V_partition(vp));
2271
2272     if (!strncmp(partition, "/vicep", 6)) {
2273         printf("%s", partition + 6);
2274     } else if (!strncmp(partition, "vicep", 5)) {
2275         printf("%s", partition + 5);
2276     } else {
2277         fprintf(stderr, "Invalid partition for volume id %lu\n",
2278                 afs_printable_uint32_lu(V_id(vp)));
2279         printf("%s", PLACEHOLDER);
2280     }
2281 }
2282
2283 /**
2284  * Print the vnode type description string
2285  *
2286  * @param[in]  type  vnode type
2287  *
2288  * @return none
2289  */
2290 static void
2291 PrintVnodeType(int type)
2292 {
2293     switch (type) {
2294     case vNull:
2295         printf("null");
2296         break;
2297     case vFile:
2298         printf("file");
2299         break;
2300     case vDirectory:
2301         printf("dir");
2302         break;
2303     case vSymlink:
2304         printf("symlink");
2305         break;
2306     default:
2307         printf("unknown");
2308     }
2309 }
2310
2311 /**
2312  * Print right bits as string.
2313  *
2314  * param[in] rights  rights bitmap
2315  */
2316 static void
2317 PrintRights(int rights)
2318 {
2319     if (rights & PRSFS_READ) {
2320         printf("r");
2321     }
2322     if (rights & PRSFS_LOOKUP) {
2323         printf("l");
2324     }
2325     if (rights & PRSFS_INSERT) {
2326         printf("i");
2327     }
2328     if (rights & PRSFS_DELETE) {
2329         printf("d");
2330     }
2331     if (rights & PRSFS_WRITE) {
2332         printf("w");
2333     }
2334     if (rights & PRSFS_LOCK) {
2335         printf("k");
2336     }
2337     if (rights & PRSFS_ADMINISTER) {
2338         printf("a");
2339     }
2340     if (rights & PRSFS_USR0) {
2341         printf("A");
2342     }
2343     if (rights & PRSFS_USR1) {
2344         printf("B");
2345     }
2346     if (rights & PRSFS_USR2) {
2347         printf("C");
2348     }
2349     if (rights & PRSFS_USR3) {
2350         printf("D");
2351     }
2352     if (rights & PRSFS_USR4) {
2353         printf("E");
2354     }
2355     if (rights & PRSFS_USR5) {
2356         printf("F");
2357     }
2358     if (rights & PRSFS_USR6) {
2359         printf("G");
2360     }
2361     if (rights & PRSFS_USR7) {
2362         printf("H");
2363     }
2364 }
2365
2366 /**
2367  * Print the path to the namei file.
2368  */
2369 static void
2370 PrintNamei(Volume * vp, VnodeDiskObject * vnode)
2371 {
2372 #ifdef AFS_NAMEI_ENV
2373     namei_t name;
2374     IHandle_t *ihP = NULL;
2375     Inode ino;
2376     ino = VNDISK_GET_INO(vnode);
2377     IH_INIT(ihP, V_device(vp), V_parentId(vp), ino);
2378     namei_HandleToName(&name, ihP);
2379     printf("%s", name.n_path);
2380     IH_RELEASE(ihP);
2381 #else
2382     printf("%s", PLACEHOLDER);
2383 #endif
2384 }
2385
2386 /**
2387  * Print the column heading line.
2388  */
2389 static void
2390 PrintColumnHeading(void)
2391 {
2392     int i;
2393     const char *name;
2394
2395     for (i = 0; i < NumOutputColumns; i++) {
2396         if (i > 0) {
2397             printf("%s", ColumnDelim);
2398         }
2399         name = ColumnName[OutputColumn[i]].name;
2400         while (*name) {
2401             putchar(toupper(*name++));
2402         }
2403     }
2404     printf("\n");
2405 }
2406
2407 /**
2408  * Print output columns for the vnode/acess entry.
2409  *
2410  * @param[in]  vdp   vnode details object
2411  * @param[in]  desc  type of line to be printed
2412  *
2413  * @return none
2414  */
2415 static void
2416 PrintColumns(struct VnodeDetails *vdp, const char *desc)
2417 {
2418     int i;
2419     afs_fsize_t length;
2420
2421     for (i = 0; i < NumOutputColumns; i++) {
2422         if (i > 0) {
2423             printf("%s", ColumnDelim);
2424         }
2425         switch (OutputColumn[i]) {
2426         case col_host:
2427             printf("%s", Hostname);
2428             break;
2429         case col_desc:
2430             printf("%s", desc);
2431             break;
2432         case col_vid:
2433             printf("%lu", afs_printable_uint32_lu(V_id(vdp->vp)));
2434             break;
2435         case col_vtype:
2436             printf("%s", volumeTypeShortString(V_type(vdp->vp)));
2437             break;
2438         case col_vname:
2439             printf("%s", V_name(vdp->vp));
2440             break;
2441         case col_part:
2442             printf("%s", VPartitionPath(V_partition(vdp->vp)));
2443             break;
2444         case col_partid:
2445             PrintPartitionId(vdp->vp);
2446             break;
2447         case col_fid:
2448             printf("%lu.%lu.%lu",
2449                    afs_printable_uint32_lu(V_id(vdp->vp)),
2450                    afs_printable_uint32_lu(vdp->vnodeNumber),
2451                    afs_printable_uint32_lu(vdp->vnode->uniquifier));
2452             break;
2453         case col_path:
2454             if (!vdp->path) {
2455                 LookupPath(vdp);
2456             }
2457             printf("%s", vdp->path ? vdp->path : PLACEHOLDER);
2458             break;
2459         case col_target:
2460             printf("%s",
2461                    (vdp->t == VNODE_U_SYMLINK ? vdp->u.target : PLACEHOLDER));
2462             break;
2463         case col_mount:
2464             if (vdp->t != VNODE_U_MOUNT) {
2465                 printf("%s", PLACEHOLDER);
2466             } else {
2467                 printf("%c", vdp->u.mnt.type);
2468                 if (vdp->u.mnt.cell) {
2469                     printf("%s:", vdp->u.mnt.cell);
2470                 }
2471                 printf("%s.", vdp->u.mnt.vol);
2472             }
2473             break;
2474         case col_mtype:
2475             printf("%c", (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.type : '-'));
2476             break;
2477         case col_mcell:
2478             printf("%s",
2479                    (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.cell : PLACEHOLDER));
2480             break;
2481         case col_mvol:
2482             printf("%s",
2483                    (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.vol : PLACEHOLDER));
2484             break;
2485         case col_aid:
2486             if (vdp->t == VNODE_U_POS_ACCESS || vdp->t == VNODE_U_NEG_ACCESS) {
2487                 printf("%d", vdp->u.access->id);
2488             } else {
2489                 printf("%s", PLACEHOLDER);
2490             }
2491             break;
2492         case col_arights:
2493             if (vdp->t == VNODE_U_POS_ACCESS) {
2494                 printf("+");
2495                 PrintRights(vdp->u.access->rights);
2496             } else if (vdp->t == VNODE_U_NEG_ACCESS) {
2497                 printf("-");
2498                 PrintRights(vdp->u.access->rights);
2499             }
2500             break;
2501         case col_vntype:
2502             PrintVnodeType(vdp->vnode->type);
2503             break;
2504         case col_cloned:
2505             printf("%c", vdp->vnode->cloned ? 'y' : 'n');
2506             break;
2507         case col_mode:
2508             printf("0%o", vdp->vnode->modeBits);
2509             break;
2510         case col_links:
2511             printf("%lu", afs_printable_uint32_lu(vdp->vnode->linkCount));
2512             break;
2513         case col_length:
2514             VNDISK_GET_LEN(length, vdp->vnode);
2515             printf("%llu", length);
2516             break;
2517         case col_uniq:
2518             printf("%lu", afs_printable_uint32_lu(vdp->vnode->uniquifier));
2519             break;
2520         case col_dv:
2521             printf("%lu", afs_printable_uint32_lu(vdp->vnode->dataVersion));
2522             break;
2523         case col_inode:
2524             printf("%" AFS_UINT64_FMT, VNDISK_GET_INO(vdp->vnode));
2525             break;
2526         case col_namei:
2527             PrintNamei(vdp->vp, vdp->vnode);
2528             break;
2529         case col_modtime:
2530             printf("%lu",
2531                    afs_printable_uint32_lu(vdp->vnode->unixModifyTime));
2532             break;
2533         case col_author:
2534             printf("%lu", afs_printable_uint32_lu(vdp->vnode->author));
2535             break;
2536         case col_owner:
2537             printf("%lu", afs_printable_uint32_lu(vdp->vnode->owner));
2538             break;
2539         case col_parent:
2540             printf("%lu", afs_printable_uint32_lu(vdp->vnode->parent));
2541             break;
2542         case col_magic:
2543             printf("0x%08X", vdp->vnode->vnodeMagic);
2544             break;
2545         case col_lock:
2546             printf("%lu.%lu",
2547                    afs_printable_uint32_lu(vdp->vnode->lock.lockCount),
2548                    afs_printable_uint32_lu(vdp->vnode->lock.lockTime));
2549             break;
2550         case col_smodtime:
2551             printf("%lu",
2552                    afs_printable_uint32_lu(vdp->vnode->serverModifyTime));
2553             break;
2554         case col_group:
2555             printf("%lu", afs_printable_uint32_lu(vdp->vnode->group));
2556             break;
2557         default:
2558             fprintf(stderr, "%s: Unknown column type: %d (%d)\n", progname,
2559                     OutputColumn[i], i);
2560             break;
2561         }
2562     }
2563     printf("\n");
2564 }