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