e73ac4ea0e247274919c66eee56b2c3bb8fa5ff6
[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 = " ";     /**< 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
935     /* Limit types of volumes to scan. */
936     if (!as->parms[P_TYPE].items) {
937         ScanVolType = (SCAN_RW | SCAN_RO | SCAN_BK);
938     } else {
939         ScanVolType = 0;
940         for (ti = as->parms[P_TYPE].items; ti; ti = ti->next) {
941             if (strcmp(ti->data, "rw") == 0) {
942                 ScanVolType |= SCAN_RW;
943             } else if (strcmp(ti->data, "ro") == 0) {
944                 ScanVolType |= SCAN_RO;
945             } else if (strcmp(ti->data, "bk") == 0) {
946                 ScanVolType |= SCAN_BK;
947             } else {
948                 fprintf(stderr, "%s: Unknown -type value: %s\n", progname,
949                         ti->data);
950                 return 1;
951             }
952         }
953     }
954
955     /* Limit types of vnodes to find (plus access entries) */
956     if (!as->parms[P_FIND].items) {
957         FindVnType = (FIND_FILE | FIND_DIR | FIND_MOUNT | FIND_SYMLINK);
958     } else {
959         FindVnType = 0;
960         for (ti = as->parms[P_FIND].items; ti; ti = ti->next) {
961             if (strcmp(ti->data, "file") == 0) {
962                 FindVnType |= FIND_FILE;
963             } else if (strcmp(ti->data, "dir") == 0) {
964                 FindVnType |= FIND_DIR;
965             } else if (strcmp(ti->data, "mount") == 0) {
966                 FindVnType |= FIND_MOUNT;
967             } else if (strcmp(ti->data, "symlink") == 0) {
968                 FindVnType |= FIND_SYMLINK;
969             } else if (strcmp(ti->data, "acl") == 0) {
970                 FindVnType |= FIND_ACL;
971             } else {
972                 fprintf(stderr, "%s: Unknown -find value: %s\n", progname,
973                         ti->data);
974                 return 1;
975             }
976         }
977     }
978
979     /* Show vnodes matching one of the mode masks */
980     for (i = 0, ti = as->parms[P_MASK].items; ti; i++, ti = ti->next) {
981         if (i >= (sizeof(ModeMask) / sizeof(*ModeMask))) {
982             fprintf(stderr, "Too many -mask values\n");
983             return -1;
984         }
985         ModeMask[i] = strtol(ti->data, NULL, 8);
986         if (!ModeMask[i]) {
987             fprintf(stderr, "Invalid -mask value: %s\n", ti->data);
988             return 1;
989         }
990     }
991
992     /* Set which columns to be printed. */
993     if (!as->parms[P_OUTPUT].items) {
994         AddOutputColumn("host");
995         AddOutputColumn("desc");
996         AddOutputColumn("fid");
997         AddOutputColumn("dv");
998         if (FindVnType & FIND_ACL) {
999             AddOutputColumn("aid");
1000             AddOutputColumn("arights");
1001         }
1002         AddOutputColumn("path");
1003     } else {
1004         for (ti = as->parms[P_OUTPUT].items; ti; ti = ti->next) {
1005             if (AddOutputColumn(ti->data) != 0) {;
1006                 fprintf(stderr, "%s: Unknown -output value: %s\n", progname,
1007                         ti->data);
1008                 return 1;
1009             }
1010         }
1011     }
1012
1013     if (FindVnType & FIND_DIR) {
1014         AddVnodeHandler(vLarge, PrintVnodeDetails, NULL);
1015     }
1016     if (FindVnType & (FIND_FILE | FIND_MOUNT | FIND_SYMLINK)) {
1017         AddVnodeHandler(vSmall, PrintVnodeDetails, NULL);
1018     }
1019     if (FindVnType & FIND_ACL) {
1020         AddVnodeHandler(vLarge, ScanAcl, NULL);
1021     }
1022
1023     return ScanPartitions(partNameOrId, volumeId);
1024 }
1025
1026 /**
1027  * Determine if the current directory is a vice partition
1028  *
1029  * @return disk partition object
1030  */
1031 #ifdef AFS_NT40_ENV
1032 #include <direct.h>
1033 struct DiskPartition64 *
1034 FindCurrentPartition(void)
1035 {
1036     int dr = _getdrive();
1037     struct DiskPartition64 *dp;
1038
1039     dr--;
1040     for (dp = DiskPartitionList; dp; dp = dp->next) {
1041         if (*dp->devName - 'A' == dr)
1042             break;
1043     }
1044     if (!dp) {
1045         fprintf(stderr, "%s: Current drive is not a valid vice partition.\n",
1046                 progname);
1047     }
1048     return dp;
1049 }
1050 #else
1051 struct DiskPartition64 *
1052 FindCurrentPartition(void)
1053 {
1054     char partName[1024];
1055     char tmp = '\0';
1056     char *p;
1057     struct DiskPartition64 *dp;
1058
1059     if (!getcwd(partName, 1023)) {
1060         fprintf(stderr, "%s: Failed to get current working directory: ",
1061                 progname);
1062         perror("pwd");
1063         return NULL;
1064     }
1065     p = strchr(&partName[1], OS_DIRSEPC);
1066     if (p) {
1067         tmp = *p;
1068         *p = '\0';
1069     }
1070     if (!(dp = VGetPartition(partName, 0))) {
1071         if (tmp)
1072             *p = tmp;
1073         fprintf(stderr, "%s: %s is not a valid vice partition.\n", progname,
1074                 partName);
1075         return NULL;
1076     }
1077     return dp;
1078 }
1079 #endif
1080
1081 /**
1082  * Scan and handle all the partitions detected on this server
1083  *
1084  * @return none
1085  */
1086 void
1087 HandleAllPart(void)
1088 {
1089     struct DiskPartition64 *partP;
1090
1091
1092     for (partP = DiskPartitionList; partP; partP = partP->next) {
1093         if (DumpInfo || SaveInodes || ShowSizes) {
1094             printf("Processing Partition %s:\n", partP->name);
1095         }
1096         HandlePart(partP);
1097         if (ShowSizes) {
1098             AddSizeTotals(&serverTotals, &partitionTotals);
1099         }
1100     }
1101
1102     if (ShowSizes) {
1103         PrintServerTotals();
1104     }
1105 }
1106
1107 /**
1108  * Scan the partition and handle volumes
1109  *
1110  * @param[in] partP  disk partition to scan
1111  *
1112  * @return none
1113  */
1114 void
1115 HandlePart(struct DiskPartition64 *partP)
1116 {
1117     afs_int64 nvols = 0;
1118     DIR *dirp;
1119     struct dirent *dp;
1120 #ifdef AFS_NT40_ENV
1121     char pname[64];
1122     char *p = pname;
1123     (void)sprintf(pname, "%s\\", VPartitionPath(partP));
1124 #else
1125     char *p = VPartitionPath(partP);
1126 #endif
1127
1128     if ((dirp = opendir(p)) == NULL) {
1129         fprintf(stderr, "%s: Can't read directory %s; giving up\n", progname,
1130                 p);
1131         return;
1132     }
1133     while ((dp = readdir(dirp))) {
1134         p = (char *)strrchr(dp->d_name, '.');
1135         if (p != NULL && strcmp(p, VHDREXT) == 0) {
1136             HandleVolume(partP, dp->d_name);
1137             if (ShowSizes) {
1138                 nvols++;
1139                 AddSizeTotals(&partitionTotals, &volumeTotals);
1140             }
1141         }
1142     }
1143     closedir(dirp);
1144     if (ShowSizes) {
1145         PrintPartitionTotals(nvols);
1146     }
1147 }
1148
1149 /**
1150  * Inspect a volume header special file.
1151  *
1152  * @param[in]  name       descriptive name of the type of header special file
1153  * @param[in]  dp         partition object for this volume
1154  * @param[in]  header     header object for this volume
1155  * @param[in]  inode      fileserver inode number for this header special file
1156  * @param[out] psize      total of the header special file
1157  *
1158  * @return none
1159  */
1160 void
1161 HandleSpecialFile(const char *name, struct DiskPartition64 *dp,
1162                   struct VolumeHeader *header, Inode inode,
1163                   afs_sfsize_t * psize)
1164 {
1165     afs_sfsize_t size = 0;
1166     IHandle_t *ih = NULL;
1167     FdHandle_t *fdP = NULL;
1168 #ifdef AFS_NAMEI_ENV
1169     namei_t filename;
1170 #endif /* AFS_NAMEI_ENV */
1171
1172     IH_INIT(ih, dp->device, header->parent, inode);
1173     fdP = IH_OPEN(ih);
1174     if (fdP == NULL) {
1175         fprintf(stderr,
1176                 "%s: Error opening header file '%s' for volume %u", progname,
1177                 name, header->id);
1178         perror("open");
1179         goto error;
1180     }
1181     size = FDH_SIZE(fdP);
1182     if (size == -1) {
1183         fprintf(stderr,
1184                 "%s: Error getting size of header file '%s' for volume %u",
1185                 progname, name, header->id);
1186         perror("fstat");
1187         goto error;
1188     }
1189     if (DumpInfo) {
1190         printf("\t%s inode\t= %s (size = %lld)\n",
1191                name, PrintInode(NULL, inode), size);
1192 #ifdef AFS_NAMEI_ENV
1193         namei_HandleToName(&filename, ih);
1194         printf("\t%s namei\t= %s\n", name, filename.n_path);
1195 #endif /* AFS_NAMEI_ENV */
1196     }
1197     *psize += size;
1198
1199   error:
1200     if (fdP != NULL) {
1201         FDH_REALLYCLOSE(fdP);
1202     }
1203     if (ih != NULL) {
1204         IH_RELEASE(ih);
1205     }
1206 }
1207
1208 /**
1209  * Inspect this volume header files.
1210  *
1211  * @param[in]  dp         partition object for this volume
1212  * @param[in]  header_fd  volume header file descriptor
1213  * @param[in]  header     volume header object
1214  * @param[out] psize      total of the header special file
1215  *
1216  * @return none
1217  */
1218 void
1219 HandleHeaderFiles(struct DiskPartition64 *dp, FD_t header_fd,
1220                   struct VolumeHeader *header)
1221 {
1222     afs_sfsize_t size = 0;
1223
1224     if (DumpInfo) {
1225         size = OS_SIZE(header_fd);
1226         printf("Volume header (size = %lld):\n", size);
1227         printf("\tstamp\t= 0x%x\n", header->stamp.version);
1228         printf("\tVolId\t= %u\n", header->id);
1229         printf("\tparent\t= %u\n", header->parent);
1230     }
1231
1232     HandleSpecialFile("Info", dp, header, header->volumeInfo, &size);
1233     HandleSpecialFile("Small", dp, header, header->smallVnodeIndex,
1234                       &size);
1235     HandleSpecialFile("Large", dp, header, header->largeVnodeIndex,
1236                       &size);
1237 #ifdef AFS_NAMEI_ENV
1238     HandleSpecialFile("Link", dp, header, header->linkTable, &size);
1239 #endif /* AFS_NAMEI_ENV */
1240
1241     if (DumpInfo) {
1242         printf("Total aux volume size = %lld\n\n", size);
1243     }
1244
1245     if (ShowSizes) {
1246         volumeTotals.auxsize = size;
1247         volumeTotals.auxsize_k = size / 1024;
1248     }
1249 }
1250
1251 /**
1252  * Determine if the vnodes of this volume should be scanned.
1253  *
1254  * @param[in]  vp   volume object
1255  *
1256  * @return true if vnodes should be scanned
1257  */
1258 static int
1259 IsScannable(Volume * vp)
1260 {
1261     if (opr_queue_IsEmpty(&VnodeScanLists[vLarge]) &&
1262         opr_queue_IsEmpty(&VnodeScanLists[vSmall])) {
1263         return 0;
1264     }
1265     if (!ScanVolType) {
1266         return 1;               /* filtering disabled; do not check vol type */
1267     }
1268     switch (V_type(vp)) {
1269     case RWVOL:
1270         return ScanVolType & SCAN_RW;
1271     case ROVOL:
1272         return ScanVolType & SCAN_RO;
1273     case BACKVOL:
1274         return ScanVolType & SCAN_BK;
1275     default:
1276         fprintf(stderr, "%s: Volume %u; Unknown volume type %d\n", progname,
1277                 V_id(vp), V_type(vp));
1278         break;
1279     }
1280     return 0;
1281 }
1282
1283 /**
1284  * Attach and scan the volume and handle the header and vnodes
1285  *
1286  * Print the volume header and vnode information, depending on the
1287  * current modes.
1288  *
1289  * @param[in] dp    vice partition object for this volume
1290  * @param[in] name  volume header file name
1291  *
1292  * @return none
1293  */
1294 void
1295 HandleVolume(struct DiskPartition64 *dp, char *name)
1296 {
1297     struct VolumeHeader header;
1298     struct VolumeDiskHeader diskHeader;
1299     FD_t fd = INVALID_FD;
1300     Volume *vp = NULL;
1301     char headerName[1024];
1302     afs_sfsize_t n;
1303
1304     snprintf(headerName, sizeof headerName, "%s" OS_DIRSEP "%s",
1305              VPartitionPath(dp), name);
1306     if ((fd = OS_OPEN(headerName, O_RDONLY, 0666)) == INVALID_FD) {
1307         fprintf(stderr, "%s: Cannot open volume header %s\n", progname, name);
1308         goto cleanup;
1309     }
1310     if (OS_SIZE(fd) < 0) {
1311         fprintf(stderr, "%s: Cannot read volume header %s\n", progname, name);
1312         goto cleanup;
1313     }
1314     n = OS_READ(fd, &diskHeader, sizeof(diskHeader));
1315     if (n != sizeof(diskHeader)
1316         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
1317         fprintf(stderr, "%s: Error reading volume header %s\n", progname,
1318                 name);
1319         goto cleanup;
1320     }
1321     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
1322         fprintf(stderr,
1323                 "%s: Volume %s, version number is incorrect; volume needs to be salvaged\n",
1324                 progname, name);
1325         goto cleanup;
1326     }
1327
1328     DiskToVolumeHeader(&header, &diskHeader);
1329     if (DumpHeader || ShowSizes) {
1330         HandleHeaderFiles(dp, fd, &header);
1331     }
1332
1333     vp = AttachVolume(dp, name, &header);
1334     if (!vp) {
1335         fprintf(stderr, "%s: Error attaching volume header %s\n",
1336                 progname, name);
1337         goto cleanup;
1338     }
1339
1340     if (DumpInfo) {
1341         PrintHeader(vp);
1342     }
1343     if (IsScannable(vp)) {
1344         if (NeedDirIndex) {
1345             IHandle_t *ih = vp->vnodeIndex[vLarge].handle;
1346             DirIndexFd = IH_OPEN(ih);
1347             if (DirIndexFd == NULL) {
1348                 fprintf(stderr, "%s: Failed to open index for directories.",
1349                         progname);
1350             }
1351         }
1352
1353         HandleVnodes(vp, vLarge);
1354         HandleVnodes(vp, vSmall);
1355
1356         if (DirIndexFd) {
1357             FDH_CLOSE(DirIndexFd);
1358             DirIndexFd = NULL;
1359         }
1360     }
1361     if (ShowSizes) {
1362         volumeTotals.diskused_k = V_diskused(vp);
1363         volumeTotals.size_k =
1364             volumeTotals.auxsize_k + volumeTotals.vnodesize_k;
1365         if (SaveInodes) {
1366             PrintingVolumeSizes = 0;    /* print heading again */
1367         }
1368         PrintVolumeSizes(vp);
1369     }
1370
1371   cleanup:
1372     if (fd != INVALID_FD) {
1373         OS_CLOSE(fd);
1374     }
1375     if (vp) {
1376         DetachVolume(vp);
1377     }
1378 }
1379
1380 /**
1381  * Declare volinfo command line syntax
1382  *
1383  * @returns none
1384  */
1385 static void
1386 VolInfoSyntax(void)
1387 {
1388     struct cmd_syndesc *ts;
1389
1390     ts = cmd_CreateSyntax(NULL, VolInfo, NULL,
1391                           "Dump volume's internal state");
1392     cmd_AddParmAtOffset(ts, P_CHECKOUT, "-checkout", CMD_FLAG, CMD_OPTIONAL,
1393                         "Checkout volumes from running fileserver");
1394     cmd_AddParmAtOffset(ts, P_VNODE, "-vnode", CMD_FLAG, CMD_OPTIONAL,
1395                         "Dump vnode info");
1396     cmd_AddParmAtOffset(ts, P_DATE, "-date", CMD_FLAG, CMD_OPTIONAL,
1397                         "Also dump vnode's mod date");
1398     cmd_AddParmAtOffset(ts, P_INODE, "-inode", CMD_FLAG, CMD_OPTIONAL,
1399                         "Also dump vnode's inode number");
1400     cmd_AddParmAtOffset(ts, P_ITIME, "-itime", CMD_FLAG, CMD_OPTIONAL,
1401                         "Dump special inode's mod times");
1402     cmd_AddParmAtOffset(ts, P_PART, "-part", CMD_LIST, CMD_OPTIONAL,
1403                         "AFS partition name or id (default current partition)");
1404     cmd_AddParmAtOffset(ts, P_VOLUMEID, "-volumeid", CMD_LIST, CMD_OPTIONAL,
1405                         "Volume id");
1406     cmd_AddParmAtOffset(ts, P_HEADER, "-header", CMD_FLAG, CMD_OPTIONAL,
1407                         "Dump volume's header info");
1408     cmd_AddParmAtOffset(ts, P_SIZEONLY, "-sizeonly", CMD_FLAG, CMD_OPTIONAL,
1409                         "Dump volume's size");
1410     cmd_AddParmAtOffset(ts, P_FIXHEADER, "-fixheader", CMD_FLAG,
1411                         CMD_OPTIONAL, "Try to fix header");
1412     cmd_AddParmAtOffset(ts, P_SAVEINODES, "-saveinodes", CMD_FLAG,
1413                         CMD_OPTIONAL, "Try to save all inodes");
1414     cmd_AddParmAtOffset(ts, P_ORPHANED, "-orphaned", CMD_FLAG, CMD_OPTIONAL,
1415                         "List all dir/files without a parent");
1416 #if defined(AFS_NAMEI_ENV)
1417     cmd_AddParmAtOffset(ts, P_FILENAMES, "-filenames", CMD_FLAG,
1418                         CMD_OPTIONAL, "Also dump vnode's namei filename");
1419 #endif
1420
1421     /* For compatibility with older versions. */
1422     cmd_AddParmAlias(ts, P_SIZEONLY, "-sizeOnly");
1423 }
1424
1425 /**
1426  * Declare volscan command line syntax
1427  *
1428  * @returns none
1429  */
1430 static void
1431 VolScanSyntax(void)
1432 {
1433     struct cmd_syndesc *ts;
1434
1435     ts = cmd_CreateSyntax(NULL, VolScan, NULL,
1436                           "Print volume vnode information");
1437
1438     cmd_AddParmAtOffset(ts, P_CHECKOUT, "-checkout", CMD_FLAG, CMD_OPTIONAL,
1439                         "Checkout volumes from running fileserver");
1440     cmd_AddParmAtOffset(ts, P_PART, "-partition", CMD_SINGLE, CMD_OPTIONAL,
1441                         "AFS partition name or id (default current partition)");
1442     cmd_AddParmAtOffset(ts, P_VOLUMEID, "-volumeid", CMD_SINGLE, CMD_OPTIONAL,
1443                         "Volume id (-partition required)");
1444     cmd_AddParmAtOffset(ts, P_TYPE, "-type", CMD_LIST, CMD_OPTIONAL,
1445                         "Volume types: rw, ro, bk");
1446     cmd_AddParmAtOffset(ts, P_FIND, "-find", CMD_LIST, CMD_OPTIONAL,
1447                         "Objects to find: file, dir, mount, symlink, acl");
1448     cmd_AddParmAtOffset(ts, P_MASK, "-mask", CMD_LIST, CMD_OPTIONAL,
1449                         "Unix mode mask (example: 06000)");
1450     cmd_AddParmAtOffset(ts, P_OUTPUT, "-output", CMD_LIST, CMD_OPTIONAL,
1451                         ColumnNames);
1452     cmd_AddParmAtOffset(ts, P_DELIM, "-delim", CMD_SINGLE, CMD_OPTIONAL,
1453                         "Output field delimiter");
1454     cmd_AddParmAtOffset(ts, P_NOHEADING, "-noheading", CMD_FLAG, CMD_OPTIONAL,
1455                         "Do not print the heading line");
1456 }
1457
1458 /**
1459  * volinfo/volscan program entry
1460  */
1461 int
1462 main(int argc, char **argv)
1463 {
1464     afs_int32 code;
1465     char *base;
1466
1467     opr_queue_Init(&VnodeScanLists[vLarge]);
1468     opr_queue_Init(&VnodeScanLists[vSmall]);
1469     memset(ModeMask, 0, sizeof(ModeMask) / sizeof(*ModeMask));
1470     gethostname(Hostname, sizeof(Hostname));
1471
1472     base = strrchr(argv[0], '/');
1473 #ifdef AFS_NT40_ENV
1474     if (!base) {
1475         base = strrchr(argv[0], '\\');
1476     }
1477 #endif /* AFS_NT40_ENV */
1478     if (!base) {
1479         base = argv[0];
1480     }
1481 #ifdef AFS_NT40_ENV
1482     if ((base[0] == '/' || base[0] == '\\') && base[1] != '\0') {
1483 #else /* AFS_NT40_ENV */
1484     if (base[0] == '/' && base[1] != '\0') {
1485 #endif /* AFS_NT40_ENV */
1486         base++;
1487     }
1488     progname = base;
1489
1490 #ifdef AFS_NT40_ENV
1491     if (stricmp(progname, "volscan") == 0
1492         || stricmp(progname, "volscan.exe") == 0) {
1493 #else /* AFS_NT40_ENV */
1494     if (strcmp(progname, "volscan") == 0) {
1495 #endif /* AFS_NT40_ENV */
1496         VolScanSyntax();
1497     } else {
1498         VolInfoSyntax();
1499     }
1500
1501     code = cmd_Dispatch(argc, argv);
1502     return code;
1503 }
1504
1505 /**
1506  * Return a display string for the volume type.
1507  *
1508  * @param[in]  type  volume type
1509  *
1510  * @return volume type description string
1511  */
1512 static_inline char *
1513 volumeTypeString(int type)
1514 {
1515     return
1516         (type == RWVOL ? "read/write" :
1517          (type == ROVOL ? "readonly" :
1518           (type == BACKVOL ? "backup" : "unknown")));
1519 }
1520
1521 /**
1522  * Return a short display string for the volume type.
1523  *
1524  * @param[in]  type  volume type
1525  *
1526  * @return volume type short description string
1527  */
1528 static_inline char *
1529 volumeTypeShortString(int type)
1530 {
1531     return
1532         (type == RWVOL ? "RW" :
1533          (type == ROVOL ? "RO" : (type == BACKVOL ? "BK" : "??")));
1534 }
1535
1536 /**
1537  * Print the volume header information
1538  *
1539  * @param[in]  volume object
1540  *
1541  * @return none
1542  */
1543 void
1544 PrintHeader(Volume * vp)
1545 {
1546     printf("Volume header for volume %u (%s)\n", V_id(vp), V_name(vp));
1547     printf("stamp.magic = %x, stamp.version = %u\n", V_stamp(vp).magic,
1548            V_stamp(vp).version);
1549     printf
1550         ("inUse = %d, inService = %d, blessed = %d, needsSalvaged = %d, dontSalvage = %d\n",
1551          V_inUse(vp), V_inService(vp), V_blessed(vp), V_needsSalvaged(vp),
1552          V_dontSalvage(vp));
1553     printf
1554         ("type = %d (%s), uniquifier = %u, needsCallback = %d, destroyMe = %x\n",
1555          V_type(vp), volumeTypeString(V_type(vp)), V_uniquifier(vp),
1556          V_needsCallback(vp), V_destroyMe(vp));
1557     printf
1558         ("id = %u, parentId = %u, cloneId = %u, backupId = %u, restoredFromId = %u\n",
1559          V_id(vp), V_parentId(vp), V_cloneId(vp), V_backupId(vp),
1560          V_restoredFromId(vp));
1561     printf
1562         ("maxquota = %d, minquota = %d, maxfiles = %d, filecount = %d, diskused = %d\n",
1563          V_maxquota(vp), V_minquota(vp), V_maxfiles(vp), V_filecount(vp),
1564          V_diskused(vp));
1565     printf("creationDate = %s, copyDate = %s\n", date(V_creationDate(vp)),
1566            date(V_copyDate(vp)));
1567     printf("backupDate = %s, expirationDate = %s\n", date(V_backupDate(vp)),
1568            date(V_expirationDate(vp)));
1569     printf("accessDate = %s, updateDate = %s\n", date(V_accessDate(vp)),
1570            date(V_updateDate(vp)));
1571     printf("owner = %u, accountNumber = %u\n", V_owner(vp),
1572            V_accountNumber(vp));
1573     printf
1574         ("dayUse = %u; week = (%u, %u, %u, %u, %u, %u, %u), dayUseDate = %s\n",
1575          V_dayUse(vp), V_weekUse(vp)[0], V_weekUse(vp)[1], V_weekUse(vp)[2],
1576          V_weekUse(vp)[3], V_weekUse(vp)[4], V_weekUse(vp)[5],
1577          V_weekUse(vp)[6], date(V_dayUseDate(vp)));
1578     printf("volUpdateCounter = %u\n", V_volUpCounter(vp));
1579 }
1580
1581 /**
1582  * Get the size and times of a file
1583  *
1584  * @param[in]  fd     file descriptor of file to stat
1585  * @param[out] size   size of the file
1586  * @param[out] ctime  ctime of file as a formatted string
1587  * @param[out] mtime  mtime of file as a formatted string
1588  * @param[out] atime  atime of file as a formatted string
1589  *
1590  * @return error code
1591  *   @retval 0 success
1592  *   @retval -1 failed to retrieve file information
1593  */
1594 static int
1595 GetFileInfo(FD_t fd, afs_sfsize_t * size, char **ctime, char **mtime,
1596             char **atime)
1597 {
1598 #ifdef AFS_NT40_ENV
1599     BY_HANDLE_FILE_INFORMATION fi;
1600     LARGE_INTEGER fsize;
1601     if (!GetFileInformationByHandle(fd, &fi)) {
1602         fprintf(stderr, "%s: GetFileInformationByHandle failed\n", progname);
1603         return -1;
1604     }
1605     if (!GetFileSizeEx(fd, &fsize)) {
1606         fprintf(stderr, "%s: GetFileSizeEx failed\n", progname);
1607         return -1;
1608     }
1609     *size = fsize.QuadPart;
1610     *ctime = "N/A";
1611     *mtime = NT_date(&fi.ftLastWriteTime);
1612     *atime = NT_date(&fi.ftLastAccessTime);
1613 #else
1614     struct afs_stat_st status;
1615     if (afs_fstat(fd, &status) == -1) {
1616         fprintf(stderr, "%s: fstat failed %d\n", progname, errno);
1617         return -1;
1618     }
1619     *size = status.st_size;
1620     *ctime = date(status.st_ctime);
1621     *mtime = date(status.st_mtime);
1622     *atime = date(status.st_atime);
1623 #endif
1624     return 0;
1625 }
1626
1627 /**
1628  * Copy the inode data to a file in the current directory.
1629  *
1630  * @param[in] vdp     vnode details object
1631  *
1632  * @return none
1633  */
1634 static void
1635 SaveInode(struct VnodeDetails *vdp)
1636 {
1637     IHandle_t *ih;
1638     FdHandle_t *fdP;
1639     char nfile[50], buffer[256];
1640     int ofd = 0;
1641     afs_foff_t total;
1642     ssize_t len;
1643     Inode ino = VNDISK_GET_INO(vdp->vnode);
1644
1645     if (!VALID_INO(ino)) {
1646         return;
1647     }
1648
1649     IH_INIT(ih, V_device(vdp->vp), V_parentId(vdp->vp), ino);
1650     fdP = IH_OPEN(ih);
1651     if (fdP == NULL) {
1652         fprintf(stderr,
1653                 "%s: Can't open inode %s error %d (ignored)\n",
1654                 progname, PrintInode(NULL, ino), errno);
1655         return;
1656     }
1657     snprintf(nfile, sizeof nfile, "TmpInode.%s", PrintInode(NULL, ino));
1658     ofd = afs_open(nfile, O_CREAT | O_RDWR | O_TRUNC, 0600);
1659     if (ofd < 0) {
1660         fprintf(stderr,
1661                 "%s: Can't create file %s; error %d (ignored)\n",
1662                 progname, nfile, errno);
1663
1664         FDH_REALLYCLOSE(fdP);
1665         IH_RELEASE(ih);
1666         return;
1667     }
1668     total = 0;
1669     while (1) {
1670         ssize_t nBytes;
1671         len = FDH_PREAD(fdP, buffer, sizeof(buffer), total);
1672         if (len < 0) {
1673             FDH_REALLYCLOSE(fdP);
1674             IH_RELEASE(ih);
1675             close(ofd);
1676             unlink(nfile);
1677             fprintf(stderr,
1678                     "%s: Error while reading from inode %s (%d)\n",
1679                     progname, PrintInode(NULL, ino), errno);
1680             return;
1681         }
1682         if (len == 0)
1683             break;              /* No more input */
1684         nBytes = write(ofd, buffer, (size_t)len);
1685         if (nBytes != len) {
1686             FDH_REALLYCLOSE(fdP);
1687             IH_RELEASE(ih);
1688             close(ofd);
1689             unlink(nfile);
1690             fprintf(stderr,
1691                     "%s: Error while writing to \"%s\" (%d - ignored)\n",
1692                     progname, nfile, errno);
1693             return;
1694         }
1695         total += len;
1696     }
1697
1698     FDH_REALLYCLOSE(fdP);
1699     IH_RELEASE(ih);
1700     close(ofd);
1701     printf("... Copied inode %s to file %s (%lu bytes)\n",
1702            PrintInode(NULL, ino), nfile, (unsigned long)total);
1703 }
1704
1705 /**
1706  * get the VnodeDiskObject for a directory given its vnode id.
1707  *
1708  * @param[in]   vp       volume object
1709  * @param[in]   parent   vnode id to read
1710  * @param[out]  pvn      vnode disk object to populate
1711  *
1712  * @post pvn contains copy of disk object for parent id
1713  *
1714  * @return operation status
1715  *   @retval 0   success
1716  *   @retval -1  failure
1717  */
1718 int
1719 GetDirVnode(Volume * vp, VnodeId parent, VnodeDiskObject * pvn)
1720 {
1721     afs_int32 code;
1722     afs_foff_t offset;
1723
1724     if (!DirIndexFd) {
1725         return -1;              /* previously failed to open the large vnode index. */
1726     }
1727     if (parent % 2 == 0) {
1728         fprintf(stderr, "%s: Invalid parent vnode id %lu in volume %lu\n",
1729                 progname,
1730                 afs_printable_uint32_lu(parent),
1731                 afs_printable_uint32_lu(V_id(vp)));
1732     }
1733     offset = vnodeIndexOffset(&VnodeClassInfo[vLarge], parent);
1734     code = FDH_SEEK(DirIndexFd, offset, 0);
1735     if (code == -1) {
1736         fprintf(stderr,
1737                 "%s: GetDirVnode: seek failed for %lu.%lu to offset %llu\n",
1738                 progname, afs_printable_uint32_lu(V_id(vp)),
1739                 afs_printable_uint32_lu(parent), (long long unsigned)offset);
1740         return -1;
1741     }
1742     code = FDH_READ(DirIndexFd, pvn, SIZEOF_LARGEDISKVNODE);
1743     if (code != SIZEOF_LARGEDISKVNODE) {
1744         fprintf(stderr,
1745                 "%s: GetDirVnode: read failed for %lu.%lu at offset %llu\n",
1746                 progname, afs_printable_uint32_lu(V_id(vp)),
1747                 afs_printable_uint32_lu(parent), (long long unsigned)offset);
1748         return -1;
1749     }
1750     if (pvn->vnodeMagic != LARGEVNODEMAGIC) {
1751         fprintf(stderr, "%s: GetDirVnode: bad vnode magic\n", progname);
1752         return -1;
1753     }
1754     if (!pvn->dataVersion) {
1755         fprintf(stderr, "%s: GetDirVnode: dv is zero\n", progname);
1756         return -1;
1757     }
1758     return 0;
1759 }
1760
1761 /**
1762  * Perform inverse lookup on a vice directory object to map a fid onto a dirent string.
1763  *
1764  * @param[in]   vp          volume object
1765  * @param[in]   pvnode      parent directory vnode object
1766  * @param[in]   cvnid       child vnode id to inverse lookup
1767  * @param[in]   cuniq       child uniquifier to inverse lookup
1768  * @param[out]  dirent      buffer in which to store dirent string
1769  * @param[out]  dirent_len  length of dirent buffer
1770  *
1771  * @post dirent contains string for the (cvnid, cuniq) entry
1772  *
1773  * @return operation status
1774  *    @retval 0 success
1775  */
1776 static int
1777 GetDirEntry(Volume * vp, VnodeDiskObject * pvnode, VnodeId cvnid,
1778             afs_uint32 cuniq, char *dirent, size_t dirent_len)
1779 {
1780     DirHandle dir;
1781     Inode ino;
1782     int volumeChanged;
1783     afs_int32 code;
1784
1785     ino = VNDISK_GET_INO(pvnode);
1786     if (!VALID_INO(ino)) {
1787         fprintf(stderr, "%s: GetDirEntry invalid parent ino\n", progname);
1788         return -1;
1789     }
1790     SetSalvageDirHandle(&dir, V_parentId(vp), V_device(vp), ino,
1791                         &volumeChanged);
1792     code = afs_dir_InverseLookup(&dir, cvnid, cuniq, dirent, dirent_len);
1793     if (code) {
1794         fprintf(stderr, "%s: afs_dir_InverseLookup failed with code %d\n",
1795                 progname, code);
1796     }
1797     FidZap(&dir);
1798     return code;
1799 }
1800
1801 /**
1802  * Lookup the path of this vnode, relative to the root of the volume.
1803  *
1804  * @param[in] vdp    vnode details
1805  *
1806  * @return status
1807  *   @retval 0 success
1808  *   @retval -1 error
1809  */
1810 int
1811 LookupPath(struct VnodeDetails *vdp)
1812 {
1813 #define MAX_PATH_LEN 1023
1814     static char path_buffer[MAX_PATH_LEN + 1];
1815     static char dirent[MAX_PATH_LEN + 1];
1816     char vnode_buffer[SIZEOF_LARGEDISKVNODE];
1817     struct VnodeDiskObject *pvn = (struct VnodeDiskObject *)vnode_buffer;
1818     int code = 0;
1819     int space;
1820     char *cursor;
1821     Volume *vp = vdp->vp;
1822     VnodeId parent = vdp->vnode->parent;
1823     VnodeId cvnid = vdp->vnodeNumber;
1824     afs_uint32 cuniq = vdp->vnode->uniquifier;
1825
1826     if (!parent) {
1827         vdp->path = "/";        /* this is root */
1828         return 0;
1829     }
1830
1831     space = sizeof(path_buffer) - 1;
1832     cursor = &path_buffer[space];
1833     *cursor = '\0';
1834
1835     while (parent) {
1836         int len;
1837
1838         code = GetDirVnode(vp, parent, pvn);
1839         if (code) {
1840             cursor = NULL;
1841             break;
1842         }
1843         code = GetDirEntry(vp, pvn, cvnid, cuniq, dirent, MAX_PATH_LEN);
1844         if (code) {
1845             cursor = NULL;
1846             break;
1847         }
1848
1849         len = strlen(dirent);
1850         if (len == 0) {
1851             fprintf(stderr,
1852                     "%s: Failed to lookup path for fid %lu.%lu.%lu: empty dir entry\n",
1853                     progname, afs_printable_uint32_lu(V_id(vdp->vp)),
1854                     afs_printable_uint32_lu(vdp->vnodeNumber),
1855                     afs_printable_uint32_lu(vdp->vnode->uniquifier));
1856             cursor = NULL;
1857             code = -1;
1858             break;
1859         }
1860
1861         if (space < (len + 1)) {
1862             fprintf(stderr,
1863                     "%s: Failed to lookup path for fid %lu.%lu.%lu: path exceeds max length (%u).\n",
1864                     progname, afs_printable_uint32_lu(V_id(vdp->vp)),
1865                     afs_printable_uint32_lu(vdp->vnodeNumber),
1866                     afs_printable_uint32_lu(vdp->vnode->uniquifier),
1867                     MAX_PATH_LEN);
1868             cursor = NULL;
1869             code = -1;
1870             break;
1871         }
1872
1873         /* prepend path component */
1874         cursor -= len;
1875         memcpy(cursor, dirent, len);
1876         *--cursor = '/';
1877         space -= (len + 1);
1878
1879         /* next parent */
1880         cvnid = parent;
1881         cuniq = pvn->uniquifier;
1882         parent = pvn->parent;
1883     }
1884
1885     if (cursor) {
1886         vdp->path = cursor;
1887     }
1888     return code;
1889 }
1890
1891 /**
1892  * Read the symlink target and determine if this vnode is a mount point.
1893  *
1894  * @param[inout]   vdp    vnode details object
1895  *
1896  * @return error code
1897  *   @retval 0 success
1898  *   @retval -1 failure
1899  */
1900 static int
1901 ReadSymlinkTarget(struct VnodeDetails *vdp)
1902 {
1903 #define MAX_SYMLINK_LEN 1023
1904     static char buffer[MAX_SYMLINK_LEN + 1];
1905     int code;
1906     Volume *vp = vdp->vp;
1907     VnodeDiskObject *vnode = vdp->vnode;
1908     VnodeId vnodeNumber = vdp->vnodeNumber;
1909     IHandle_t *ihP = NULL;
1910     FdHandle_t *fdP = NULL;
1911     afs_fsize_t fileLength;
1912     int readLength;
1913     Inode ino;
1914
1915     ino = VNDISK_GET_INO(vnode);
1916     VNDISK_GET_LEN(fileLength, vnode);
1917
1918     if (fileLength > MAX_SYMLINK_LEN) {
1919         fprintf(stderr,
1920                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) exceeds "
1921                 "%u, file length is %llu)!\n", progname,
1922                 afs_printable_uint32_lu(V_id(vp)),
1923                 afs_printable_uint32_lu(vnodeNumber),
1924                 afs_printable_uint32_lu(vnode->uniquifier),
1925                 afs_printable_uint32_lu(vnode->dataVersion),
1926                 MAX_SYMLINK_LEN,
1927                 fileLength);
1928         return -1;
1929     }
1930     if (fileLength == 0) {
1931         fprintf(stderr,
1932                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) is empty.\n",
1933                 progname,
1934                 afs_printable_uint32_lu(V_id(vp)),
1935                 afs_printable_uint32_lu(vnodeNumber),
1936                 afs_printable_uint32_lu(vnode->uniquifier),
1937                 afs_printable_uint32_lu(vnode->dataVersion));
1938         return -1;
1939     }
1940
1941     IH_INIT(ihP, V_device(vp), V_parentId(vp), ino);
1942     fdP = IH_OPEN(ihP);
1943     if (fdP == NULL) {
1944         code = -1;
1945         goto cleanup;
1946     }
1947     if (FDH_SEEK(fdP, 0, SEEK_SET) < 0) {
1948         code = -1;
1949         goto cleanup;
1950     }
1951     readLength = FDH_READ(fdP, buffer, fileLength);
1952     if (readLength < 0) {
1953         fprintf(stderr,
1954                 "%s: Error reading symlink contents for fid (%lu.%lu.%lu.%lu); "
1955                 "errno %d\n",
1956                 progname,
1957                 afs_printable_uint32_lu(V_id(vp)),
1958                 afs_printable_uint32_lu(vnodeNumber),
1959                 afs_printable_uint32_lu(vnode->uniquifier),
1960                 afs_printable_uint32_lu(vnode->dataVersion), errno);
1961         code = -1;
1962         goto cleanup;
1963     } else if (readLength != fileLength) {
1964         fprintf(stderr,
1965                 "%s: Symlink contents for fid (%lu.%lu.%lu.%lu) don't match "
1966                 "vnode file length metadata (len=%llu, actual=%lld)!\n",
1967                 progname,
1968                 afs_printable_uint32_lu(V_id(vp)),
1969                 afs_printable_uint32_lu(vnodeNumber),
1970                 afs_printable_uint32_lu(vnode->uniquifier),
1971                 afs_printable_uint32_lu(vnode->dataVersion), fileLength,
1972                 (long long)readLength);
1973         code = -1;
1974         goto cleanup;
1975     }
1976     code = 0;
1977
1978     if (readLength > 1 && (buffer[0] == '#' || buffer[0] == '%')
1979         && buffer[readLength - 1] == '.') {
1980         char *sep;
1981         buffer[readLength - 1] = '\0';  /* stringify; clobbers trailing dot */
1982         sep = strchr(buffer, ':');
1983         vdp->t = VNODE_U_MOUNT;
1984         vdp->u.mnt.type = buffer[0];
1985         if (!sep) {
1986             vdp->u.mnt.cell = NULL;
1987             vdp->u.mnt.vol = buffer + 1;
1988         } else {
1989             *sep = '\0';
1990             vdp->u.mnt.cell = buffer + 1;
1991             vdp->u.mnt.vol = sep + 1;
1992         }
1993     } else {
1994         buffer[readLength] = '\0';
1995         vdp->t = VNODE_U_SYMLINK;
1996         vdp->u.target = buffer;
1997     }
1998
1999   cleanup:
2000     if (fdP) {
2001         FDH_CLOSE(fdP);
2002     }
2003     if (ihP) {
2004         IH_RELEASE(ihP);
2005     }
2006     return code;
2007 }
2008
2009 /**
2010  * Print vnode details line
2011  *
2012  * @param[inout]  vdp   vnode details object
2013  *
2014  * @return none
2015  */
2016 static void
2017 PrintVnodeDetails(struct VnodeDetails *vdp)
2018 {
2019     switch (vdp->vnode->type) {
2020     case vNull:
2021         break;
2022     case vFile:
2023         if (FindVnType & FIND_FILE) {
2024             PrintColumns(vdp, "file");
2025         }
2026         break;
2027     case vDirectory:
2028         if (FindVnType & FIND_DIR) {
2029             PrintColumns(vdp, "dir");
2030         }
2031         break;
2032     case vSymlink:
2033         if (FindVnType & (FIND_MOUNT | FIND_SYMLINK)) {
2034             ReadSymlinkTarget(vdp);
2035             if ((FindVnType & FIND_MOUNT) && (vdp->t == VNODE_U_MOUNT)) {
2036                 PrintColumns(vdp, "mount");
2037             }
2038             if ((FindVnType & FIND_SYMLINK) && (vdp->t == VNODE_U_SYMLINK)) {
2039                 PrintColumns(vdp, "symlink");
2040             }
2041         }
2042         break;
2043     default:
2044         fprintf(stderr,
2045                 "%s: Warning: unexpected vnode type %u on fid %lu.%lu.%lu",
2046                 progname, vdp->vnode->type,
2047                 afs_printable_uint32_lu(V_id(vdp->vp)),
2048                 afs_printable_uint32_lu(vdp->vnodeNumber),
2049                 afs_printable_uint32_lu(vdp->vnode->uniquifier));
2050     }
2051 }
2052
2053 /**
2054  * Print each access entry of a vnode
2055  *
2056  * @param[in]  vdp   vnode details object
2057  *
2058  * @return none
2059  */
2060 static void
2061 ScanAcl(struct VnodeDetails *vdp)
2062 {
2063     int i;
2064     struct acl_accessList *acl;
2065     VnodeDiskObject *vnode = vdp->vnode;
2066
2067     if (vnode->type == vNull) {
2068         return;
2069     }
2070
2071     acl = VVnodeDiskACL(vnode);
2072     for (i = 0; i < acl->positive; i++) {
2073         vdp->t = VNODE_U_POS_ACCESS;
2074         vdp->u.access = &(acl->entries[i]);
2075         PrintColumns(vdp, "acl");
2076     }
2077     for (i = (acl->total - 1); i >= (acl->total - acl->negative); i--) {
2078         vdp->t = VNODE_U_NEG_ACCESS;
2079         vdp->u.access = &(acl->entries[i]);
2080         PrintColumns(vdp, "acl");
2081     }
2082 }
2083
2084 /**
2085  * Determine if the mode matches all the given masks.
2086  *
2087  * Returns true if the mode bits match all the given masks. A mask matches if at
2088  * least one bit in the mask is present in the mode bits.  An empty mode mask
2089  * list matches all modes (even if all the mode bits are zero.)
2090  *
2091  * param[in]  modeBits  unix mode bits of a vnode
2092  *
2093  */
2094 static int
2095 ModeMaskMatch(unsigned int modeBits)
2096 {
2097     int i;
2098
2099     for (i = 0; ModeMask[i] && i <= sizeof(ModeMask) / sizeof(*ModeMask); i++) {
2100         if ((ModeMask[i] & modeBits) == 0) {
2101             return 0;           /* at least one mode bit is not present */
2102         }
2103     }
2104     return 1;
2105 }
2106
2107 /**
2108  * Scan a volume index and handle each vnode
2109  *
2110  * @param[in] vp      volume object
2111  * @param[in] class   which index to scan
2112  *
2113  * @return none
2114  */
2115 void
2116 HandleVnodes(Volume * vp, VnodeClass class)
2117 {
2118     afs_int32 diskSize =
2119         (class == vSmall ? SIZEOF_SMALLDISKVNODE : SIZEOF_LARGEDISKVNODE);
2120     char buf[SIZEOF_LARGEDISKVNODE];
2121     struct VnodeDiskObject *vnode = (struct VnodeDiskObject *)buf;
2122     StreamHandle_t *file = NULL;
2123     int vnodeIndex;
2124     afs_sfsize_t nVnodes;
2125     afs_foff_t offset = 0;
2126     IHandle_t *ih = vp->vnodeIndex[class].handle;
2127     FdHandle_t *fdP = NULL;
2128     afs_sfsize_t size;
2129     char *ctime, *atime, *mtime;
2130     struct opr_queue *scanList = &VnodeScanLists[class];
2131     struct opr_queue *cursor;
2132
2133     if (opr_queue_IsEmpty(scanList)) {
2134         return;
2135     }
2136
2137     for (opr_queue_Scan(scanList, cursor)) {
2138         struct VnodeScanProc *entry = (struct VnodeScanProc *)cursor;
2139         if (entry->heading) {
2140             printf("%s", entry->heading);
2141         }
2142     }
2143
2144     fdP = IH_OPEN(ih);
2145     if (fdP == NULL) {
2146         fprintf(stderr, "%s: open failed: ", progname);
2147         goto error;
2148     }
2149
2150     file = FDH_FDOPEN(fdP, "r");
2151     if (!file) {
2152         fprintf(stderr, "%s: fdopen failed\n", progname);
2153         goto error;
2154     }
2155
2156     if (GetFileInfo(fdP->fd_fd, &size, &ctime, &atime, &mtime) != 0) {
2157         goto error;
2158     }
2159     if (InodeTimes) {
2160         printf("ichanged : %s\nimodified: %s\niaccessed: %s\n\n", ctime,
2161                mtime, atime);
2162     }
2163
2164     nVnodes = (size / diskSize) - 1;
2165     if (nVnodes > 0) {
2166         STREAM_ASEEK(file, diskSize);
2167     } else
2168         nVnodes = 0;
2169
2170     for (vnodeIndex = 0;
2171          nVnodes && STREAM_READ(vnode, diskSize, 1, file) == 1;
2172          nVnodes--, vnodeIndex++, offset += diskSize) {
2173
2174         struct VnodeDetails vnodeDetails;
2175
2176         if (!ModeMaskMatch(vnode->modeBits)) {
2177             continue;
2178         }
2179
2180         memset(&vnodeDetails, 0, sizeof(struct VnodeDetails));
2181         vnodeDetails.vp = vp;
2182         vnodeDetails.class = class;
2183         vnodeDetails.vnode = vnode;
2184         vnodeDetails.vnodeNumber = bitNumberToVnodeNumber(vnodeIndex, class);
2185         vnodeDetails.offset = offset;
2186         vnodeDetails.index = vnodeIndex;
2187
2188         for (opr_queue_Scan(scanList, cursor)) {
2189             struct VnodeScanProc *entry = (struct VnodeScanProc *)cursor;
2190             if (entry->proc) {
2191                 (*entry->proc) (&vnodeDetails);
2192             }
2193         }
2194     }
2195
2196   error:
2197     if (file) {
2198         STREAM_CLOSE(file);
2199     }
2200     if (fdP) {
2201         FDH_CLOSE(fdP);
2202     }
2203 }
2204
2205 /**
2206  * Print vnode information
2207  *
2208  * @param[in] vdp          vnode details object
2209  *
2210  * @return none
2211  */
2212 void
2213 PrintVnode(struct VnodeDetails *vdp)
2214 {
2215 #if defined(AFS_NAMEI_ENV)
2216     IHandle_t *ihtmpp;
2217     namei_t filename;
2218 #endif
2219     afs_foff_t offset = vdp->offset;
2220     VnodeDiskObject *vnode = vdp->vnode;
2221     afs_fsize_t fileLength;
2222     Inode ino;
2223
2224     ino = VNDISK_GET_INO(vnode);
2225     VNDISK_GET_LEN(fileLength, vnode);
2226
2227     /* The check for orphaned vnodes is currently limited to non-empty
2228      * vnodes with a parent of zero (and which are not the first entry
2229      * in the index). */
2230     if (ShowOrphaned && (fileLength == 0 || vnode->parent || !offset))
2231         return;
2232
2233     printf
2234         ("%10lld Vnode %u.%u.%u cloned: %u, length: %llu linkCount: %d parent: %u",
2235          (long long)offset, vdp->vnodeNumber, vnode->uniquifier,
2236          vnode->dataVersion, vnode->cloned, (afs_uintmax_t) fileLength,
2237          vnode->linkCount, vnode->parent);
2238     if (DumpInodeNumber)
2239         printf(" inode: %s", PrintInode(NULL, ino));
2240     if (DumpDate)
2241         printf(" ServerModTime: %s", date(vnode->serverModifyTime));
2242 #if defined(AFS_NAMEI_ENV)
2243     if (PrintFileNames) {
2244         IH_INIT(ihtmpp, V_device(vdp->vp), V_parentId(vdp->vp), ino);
2245         namei_HandleToName(&filename, ihtmpp);
2246 #if !defined(AFS_NT40_ENV)
2247         printf(" UFS-Filename: %s", filename.n_path);
2248 #else
2249         printf(" NTFS-Filename: %s", filename.n_path);
2250 #endif
2251     }
2252 #endif
2253     printf("\n");
2254 }
2255
2256 /**
2257  * Print the volume partition id
2258  *
2259  * @param[in]  vp  volume object
2260  *
2261  * @return none
2262  */
2263 static void
2264 PrintPartitionId(Volume * vp)
2265 {
2266     char *partition = VPartitionPath(V_partition(vp));
2267
2268     if (!strncmp(partition, "/vicep", 6)) {
2269         printf("%s", partition + 6);
2270     } else if (!strncmp(partition, "vicep", 5)) {
2271         printf("%s", partition + 5);
2272     } else {
2273         fprintf(stderr, "Invalid partition for volume id %lu\n",
2274                 afs_printable_uint32_lu(V_id(vp)));
2275         printf("%s", PLACEHOLDER);
2276     }
2277 }
2278
2279 /**
2280  * Print the vnode type description string
2281  *
2282  * @param[in]  type  vnode type
2283  *
2284  * @return none
2285  */
2286 static void
2287 PrintVnodeType(int type)
2288 {
2289     switch (type) {
2290     case vNull:
2291         printf("null");
2292         break;
2293     case vFile:
2294         printf("file");
2295         break;
2296     case vDirectory:
2297         printf("dir");
2298         break;
2299     case vSymlink:
2300         printf("symlink");
2301         break;
2302     default:
2303         printf("unknown");
2304     }
2305 }
2306
2307 /**
2308  * Print right bits as string.
2309  *
2310  * param[in] rights  rights bitmap
2311  */
2312 static void
2313 PrintRights(int rights)
2314 {
2315     if (rights & PRSFS_READ) {
2316         printf("r");
2317     }
2318     if (rights & PRSFS_LOOKUP) {
2319         printf("l");
2320     }
2321     if (rights & PRSFS_INSERT) {
2322         printf("i");
2323     }
2324     if (rights & PRSFS_DELETE) {
2325         printf("d");
2326     }
2327     if (rights & PRSFS_WRITE) {
2328         printf("w");
2329     }
2330     if (rights & PRSFS_LOCK) {
2331         printf("k");
2332     }
2333     if (rights & PRSFS_ADMINISTER) {
2334         printf("a");
2335     }
2336     if (rights & PRSFS_USR0) {
2337         printf("A");
2338     }
2339     if (rights & PRSFS_USR1) {
2340         printf("B");
2341     }
2342     if (rights & PRSFS_USR2) {
2343         printf("C");
2344     }
2345     if (rights & PRSFS_USR3) {
2346         printf("D");
2347     }
2348     if (rights & PRSFS_USR4) {
2349         printf("E");
2350     }
2351     if (rights & PRSFS_USR5) {
2352         printf("F");
2353     }
2354     if (rights & PRSFS_USR6) {
2355         printf("G");
2356     }
2357     if (rights & PRSFS_USR7) {
2358         printf("H");
2359     }
2360 }
2361
2362 /**
2363  * Print the path to the namei file.
2364  */
2365 static void
2366 PrintNamei(Volume * vp, VnodeDiskObject * vnode)
2367 {
2368 #ifdef AFS_NAMEI_ENV
2369     namei_t name;
2370     IHandle_t *ihP = NULL;
2371     Inode ino;
2372     ino = VNDISK_GET_INO(vnode);
2373     IH_INIT(ihP, V_device(vp), V_parentId(vp), ino);
2374     namei_HandleToName(&name, ihP);
2375     printf("%s", name.n_path);
2376     IH_RELEASE(ihP);
2377 #else
2378     printf("%s", PLACEHOLDER);
2379 #endif
2380 }
2381
2382 /**
2383  * Print the column heading line.
2384  */
2385 static void
2386 PrintColumnHeading(void)
2387 {
2388     int i;
2389     const char *name;
2390
2391     for (i = 0; i < NumOutputColumns; i++) {
2392         if (i > 0) {
2393             printf("%s", ColumnDelim);
2394         }
2395         name = ColumnName[OutputColumn[i]].name;
2396         while (*name) {
2397             putchar(toupper(*name++));
2398         }
2399     }
2400     printf("\n");
2401 }
2402
2403 /**
2404  * Print output columns for the vnode/acess entry.
2405  *
2406  * @param[in]  vdp   vnode details object
2407  * @param[in]  desc  type of line to be printed
2408  *
2409  * @return none
2410  */
2411 static void
2412 PrintColumns(struct VnodeDetails *vdp, const char *desc)
2413 {
2414     int i;
2415     afs_fsize_t length;
2416
2417     for (i = 0; i < NumOutputColumns; i++) {
2418         if (i > 0) {
2419             printf("%s", ColumnDelim);
2420         }
2421         switch (OutputColumn[i]) {
2422         case col_host:
2423             printf("%s", Hostname);
2424             break;
2425         case col_desc:
2426             printf("%s", desc);
2427             break;
2428         case col_vid:
2429             printf("%lu", afs_printable_uint32_lu(V_id(vdp->vp)));
2430             break;
2431         case col_vtype:
2432             printf("%s", volumeTypeShortString(V_type(vdp->vp)));
2433             break;
2434         case col_vname:
2435             printf("%s", V_name(vdp->vp));
2436             break;
2437         case col_part:
2438             printf("%s", VPartitionPath(V_partition(vdp->vp)));
2439             break;
2440         case col_partid:
2441             PrintPartitionId(vdp->vp);
2442             break;
2443         case col_fid:
2444             printf("%lu.%lu.%lu",
2445                    afs_printable_uint32_lu(V_id(vdp->vp)),
2446                    afs_printable_uint32_lu(vdp->vnodeNumber),
2447                    afs_printable_uint32_lu(vdp->vnode->uniquifier));
2448             break;
2449         case col_path:
2450             if (!vdp->path) {
2451                 LookupPath(vdp);
2452             }
2453             printf("%s", vdp->path ? vdp->path : PLACEHOLDER);
2454             break;
2455         case col_target:
2456             printf("%s",
2457                    (vdp->t == VNODE_U_SYMLINK ? vdp->u.target : PLACEHOLDER));
2458             break;
2459         case col_mount:
2460             if (vdp->t != VNODE_U_MOUNT) {
2461                 printf("%s", PLACEHOLDER);
2462             } else {
2463                 printf("%c", vdp->u.mnt.type);
2464                 if (vdp->u.mnt.cell) {
2465                     printf("%s:", vdp->u.mnt.cell);
2466                 }
2467                 printf("%s.", vdp->u.mnt.vol);
2468             }
2469             break;
2470         case col_mtype:
2471             printf("%c", (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.type : '-'));
2472             break;
2473         case col_mcell:
2474             printf("%s",
2475                    (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.cell : PLACEHOLDER));
2476             break;
2477         case col_mvol:
2478             printf("%s",
2479                    (vdp->t == VNODE_U_MOUNT ? vdp->u.mnt.vol : PLACEHOLDER));
2480             break;
2481         case col_aid:
2482             if (vdp->t == VNODE_U_POS_ACCESS || vdp->t == VNODE_U_NEG_ACCESS) {
2483                 printf("%d", vdp->u.access->id);
2484             } else {
2485                 printf("%s", PLACEHOLDER);
2486             }
2487             break;
2488         case col_arights:
2489             if (vdp->t == VNODE_U_POS_ACCESS) {
2490                 printf("+");
2491                 PrintRights(vdp->u.access->rights);
2492             } else if (vdp->t == VNODE_U_NEG_ACCESS) {
2493                 printf("-");
2494                 PrintRights(vdp->u.access->rights);
2495             }
2496             break;
2497         case col_vntype:
2498             PrintVnodeType(vdp->vnode->type);
2499             break;
2500         case col_cloned:
2501             printf("%c", vdp->vnode->cloned ? 'y' : 'n');
2502             break;
2503         case col_mode:
2504             printf("0%o", vdp->vnode->modeBits);
2505             break;
2506         case col_links:
2507             printf("%lu", afs_printable_uint32_lu(vdp->vnode->linkCount));
2508             break;
2509         case col_length:
2510             VNDISK_GET_LEN(length, vdp->vnode);
2511             printf("%llu", length);
2512             break;
2513         case col_uniq:
2514             printf("%lu", afs_printable_uint32_lu(vdp->vnode->uniquifier));
2515             break;
2516         case col_dv:
2517             printf("%lu", afs_printable_uint32_lu(vdp->vnode->dataVersion));
2518             break;
2519         case col_inode:
2520             printf("%" AFS_UINT64_FMT, VNDISK_GET_INO(vdp->vnode));
2521             break;
2522         case col_namei:
2523             PrintNamei(vdp->vp, vdp->vnode);
2524             break;
2525         case col_modtime:
2526             printf("%lu",
2527                    afs_printable_uint32_lu(vdp->vnode->unixModifyTime));
2528             break;
2529         case col_author:
2530             printf("%lu", afs_printable_uint32_lu(vdp->vnode->author));
2531             break;
2532         case col_owner:
2533             printf("%lu", afs_printable_uint32_lu(vdp->vnode->owner));
2534             break;
2535         case col_parent:
2536             printf("%lu", afs_printable_uint32_lu(vdp->vnode->parent));
2537             break;
2538         case col_magic:
2539             printf("0x%08X", vdp->vnode->vnodeMagic);
2540             break;
2541         case col_lock:
2542             printf("%lu.%lu",
2543                    afs_printable_uint32_lu(vdp->vnode->lock.lockCount),
2544                    afs_printable_uint32_lu(vdp->vnode->lock.lockTime));
2545             break;
2546         case col_smodtime:
2547             printf("%lu",
2548                    afs_printable_uint32_lu(vdp->vnode->serverModifyTime));
2549             break;
2550         case col_group:
2551             printf("%lu", afs_printable_uint32_lu(vdp->vnode->group));
2552             break;
2553         default:
2554             fprintf(stderr, "%s: Unknown column type: %d (%d)\n", progname,
2555                     OutputColumn[i], i);
2556             break;
2557         }
2558     }
2559     printf("\n");
2560 }