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