volinfo: release volume header ihandles when done
[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
33 #include "nfs.h"
34 #include "lock.h"
35 #include "ihandle.h"
36 #include "vnode.h"
37 #include "volume.h"
38 #include "partition.h"
39
40 #ifndef AFS_NT40_ENV
41 #include "AFS_component_version_number.c"
42 #endif
43
44 static const char *progname = "volinfo";
45
46 /* Command line options */
47 typedef enum {
48     P_ONLINE,
49     P_VNODE,
50     P_DATE,
51     P_INODE,
52     P_ITIME,
53     P_PART,
54     P_VOLUMEID,
55     P_HEADER,
56     P_SIZEONLY,
57     P_FIXHEADER,
58     P_SAVEINODES,
59     P_ORPHANED,
60     P_FILENAMES
61 } volinfo_parm_t;
62
63 /* Modes */
64 static int DumpInfo = 1;            /**< Dump volume information, defualt mode*/
65 static int DumpHeader = 0;          /**< Dump volume header files info */
66 static int DumpVnodes = 0;          /**< Dump vnode info */
67 static int DumpInodeNumber = 0;     /**< Dump inode numbers with vnodes */
68 static int DumpDate = 0;            /**< Dump vnode date (server modify date) with vnode */
69 static int InodeTimes = 0;          /**< Dump some of the dates associated with inodes */
70 #if defined(AFS_NAMEI_ENV)
71 static int PrintFileNames = 0;      /**< Dump vnode and special file name filenames */
72 #endif
73 static int ShowOrphaned = 0;        /**< Show "orphaned" vnodes (vnodes with parent of 0) */
74 static int ShowSizes = 0;           /**< Show volume size summary */
75 static int SaveInodes = 0;          /**< Save vnode data to files */
76 static int FixHeader = 0;           /**< Repair header files magic and version fields. */
77
78 /**
79  * Volume size running totals
80  */
81 struct sizeTotals {
82     afs_uint64 diskused_k;      /**< volume size from disk data file, in kilobytes */
83     afs_uint64 auxsize;         /**< size of header files, in bytes  */
84     afs_uint64 auxsize_k;       /**< size of header files, in kilobytes */
85     afs_uint64 vnodesize;       /**< size of the large and small vnodes, in bytes */
86     afs_uint64 vnodesize_k;     /**< size of the large and small vnodes, in kilobytes */
87     afs_uint64 size_k;          /**< size of headers and vnodes, in kilobytes */
88 };
89
90 static struct sizeTotals volumeTotals = { 0, 0, 0, 0, 0, 0 };
91 static struct sizeTotals partitionTotals = { 0, 0, 0, 0, 0, 0 };
92 static struct sizeTotals serverTotals = { 0, 0, 0, 0, 0, 0 };
93 static int PrintingVolumeSizes = 0;     /*print volume size lines */
94
95 /* Forward Declarations */
96 void PrintHeader(Volume * vp);
97 void HandleAllPart(void);
98 void HandlePart(struct DiskPartition64 *partP);
99 void HandleVolume(struct DiskPartition64 *partP, char *name);
100 struct DiskPartition64 *FindCurrentPartition(void);
101 Volume *AttachVolume(struct DiskPartition64 *dp, char *volname,
102                      struct VolumeHeader *header);
103 void PrintVnode(afs_foff_t offset, VnodeDiskObject * vnode, VnodeId vnodeNumber,
104                 Inode ino, Volume * vp);
105 void HandleVnodes(Volume * vp, VnodeClass class);
106
107 /**
108  * Format time as a timestamp string
109  *
110  * @param[in] date  time value to format
111  *
112  * @return timestamp string in the form YYYY/MM/DD.hh:mm:ss
113  *
114  * @note A static array of 8 strings are stored by this
115  *       function. The array slots are overwritten, so the
116  *       caller must not reference the returned string after
117  *       seven additional calls to this function.
118  */
119 char *
120 date(time_t date)
121 {
122 #define MAX_DATE_RESULT 100
123     static char results[8][MAX_DATE_RESULT];
124     static int next;
125     struct tm *tm = localtime(&date);
126     char buf[32];
127
128     (void)strftime(buf, 32, "%Y/%m/%d.%H:%M:%S", tm);   /* NT does not have %T */
129     snprintf(results[next = (next + 1) & 7], MAX_DATE_RESULT,
130              "%lu (%s)", (unsigned long)date, buf);
131     return results[next];
132 }
133
134 #ifdef AFS_NT40_ENV
135 /**
136  * Format file time as a timestamp string
137  *
138  * @param[in] ft  file time
139  *
140  * @return timestamp string in the form YYYY/MM/DD.hh:mm:ss
141  *
142  * @note A static array of 8 strings are stored by this
143  *       function. The array slots are overwritten, so the
144  *       caller must not reference the returned string after
145  *       seven additional calls to this function.
146  */
147 char *
148 NT_date(FILETIME * ft)
149 {
150     static char result[8][64];
151     static int next = 0;
152     SYSTEMTIME st;
153     FILETIME lft;
154
155     if (!FileTimeToLocalFileTime(ft, &lft)
156         || !FileTimeToSystemTime(&lft, &st)) {
157         fprintf(stderr, "%s: Time conversion failed.\n", progname);
158         exit(1);
159     }
160     sprintf(result[next = ((next + 1) & 7)], "%4d/%02d/%02d.%2d:%2d:%2d",
161             st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
162     return result[next];
163 }
164 #endif
165
166 /**
167  * Print the volume size table heading line, if needed.
168  *
169  * @return none
170  */
171 static void
172 PrintVolumeSizeHeading(void)
173 {
174     if (!PrintingVolumeSizes) {
175         printf
176             ("Volume-Id\t  Volsize  Auxsize Inodesize  AVolsize SizeDiff                (VolName)\n");
177         PrintingVolumeSizes = 1;
178     }
179 }
180
181 /**
182  * Accumulate totals.
183  *
184  * @return 0
185  */
186 static void
187 AddSizeTotals(struct sizeTotals *a, struct sizeTotals *b)
188 {
189     a->diskused_k += b->diskused_k;
190     a->auxsize += b->auxsize;
191     a->auxsize_k += b->auxsize_k;
192     a->vnodesize += b->vnodesize;
193     a->vnodesize_k += b->vnodesize_k;
194     a->size_k += b->size_k;
195 }
196
197 /**
198  * Print the sizes for a volume.
199  *
200  * @return none
201  */
202 static void
203 PrintVolumeSizes(Volume * vp)
204 {
205     afs_int64 diff_k = volumeTotals.size_k - volumeTotals.diskused_k;
206
207     PrintVolumeSizeHeading();
208     printf("%u\t%9llu%9llu%10llu%10llu%9lld\t%24s\n",
209            V_id(vp),
210            volumeTotals.diskused_k,
211            volumeTotals.auxsize_k, volumeTotals.vnodesize_k,
212            volumeTotals.size_k, diff_k, V_name(vp));
213 }
214
215 /**
216  * Print the size totals for the partition.
217  *
218  * @return none
219  */
220 static void
221 PrintPartitionTotals(afs_uint64 nvols)
222 {
223     afs_int64 diff_k = partitionTotals.size_k - partitionTotals.diskused_k;
224
225     PrintVolumeSizeHeading();
226     printf("\nPart Totals  %12llu%9llu%10llu%10llu%9lld (%llu volumes)\n\n",
227            partitionTotals.diskused_k, partitionTotals.auxsize,
228            partitionTotals.vnodesize, partitionTotals.size_k, diff_k, nvols);
229     PrintingVolumeSizes = 0;
230 }
231
232 /**
233  * Print the size totals for all the partitions.
234  *
235  * @return none
236  */
237 static void
238 PrintServerTotals(void)
239 {
240     afs_int64 diff_k = serverTotals.size_k - serverTotals.diskused_k;
241
242     printf("\nServer Totals%12lld%9lld%10lld%10lld%9lld\n",
243            serverTotals.diskused_k, serverTotals.auxsize,
244            serverTotals.vnodesize, serverTotals.size_k, diff_k);
245 }
246
247 /**
248  * Read a volume header file
249  *
250  * @param[in] ih        ihandle of the header file
251  * @param[in] to        destination
252  * @param[in] size      expected header size
253  * @param[in] magic     expected header magic number
254  * @param[in] version   expected header version number
255  *
256  * @return error code
257  *   @retval 0 success
258  *   @retval -1 failed to read file
259  */
260 int
261 ReadHdr1(IHandle_t * ih, char *to, int size, u_int magic, u_int version)
262 {
263     struct versionStamp *vsn;
264     int bad = 0;
265     int code;
266
267     vsn = (struct versionStamp *)to;
268
269     code = IH_IREAD(ih, 0, to, size);
270     if (code != size)
271         return -1;
272
273     if (vsn->magic != magic) {
274         bad++;
275         fprintf(stderr, "%s: Inode %s: Bad magic %x (%x): IGNORED\n",
276                 progname, PrintInode(NULL, ih->ih_ino), vsn->magic, magic);
277     }
278
279     /* Check is conditional, in case caller wants to inspect version himself */
280     if (version && vsn->version != version) {
281         bad++;
282         fprintf(stderr, "%s: Inode %s: Bad version %x (%x): IGNORED\n",
283                 progname,
284                 PrintInode(NULL, ih->ih_ino), vsn->version, version);
285     }
286     if (bad && FixHeader) {
287         vsn->magic = magic;
288         vsn->version = version;
289         printf("Special index inode %s has a bad header. Reconstructing...\n",
290                PrintInode(NULL, ih->ih_ino));
291         code = IH_IWRITE(ih, 0, to, size);
292         if (code != size) {
293             fprintf(stderr,
294                     "%s: Write failed for inode %s; header left in damaged state\n",
295                     progname, PrintInode(NULL, ih->ih_ino));
296         }
297     }
298     if (!bad && DumpInfo) {
299         printf("Inode %s: Good magic %x and version %x\n",
300                PrintInode(NULL, ih->ih_ino), magic, version);
301     }
302     return 0;
303 }
304
305 /**
306  * Simplified attach volume
307  *
308  * param[in] dp       vice disk partition object
309  * param[in] volname  volume header file name
310  * param[in] header   volume header object
311  *
312  * @return volume object or null on error
313  */
314 Volume *
315 AttachVolume(struct DiskPartition64 * dp, char *volname,
316              struct VolumeHeader * header)
317 {
318     Volume *vp;
319     afs_int32 ec = 0;
320
321     vp = (Volume *) calloc(1, sizeof(Volume));
322     if (!vp) {
323         fprintf(stderr, "%s: Failed to allocate volume object.\n", progname);
324         return NULL;
325     }
326     vp->specialStatus = 0;
327     vp->device = dp->device;
328     vp->partition = dp;
329     IH_INIT(vp->vnodeIndex[vLarge].handle, dp->device, header->parent,
330             header->largeVnodeIndex);
331     IH_INIT(vp->vnodeIndex[vSmall].handle, dp->device, header->parent,
332             header->smallVnodeIndex);
333     IH_INIT(vp->diskDataHandle, dp->device, header->parent,
334             header->volumeInfo);
335     IH_INIT(V_linkHandle(vp), dp->device, header->parent, header->linkTable);
336     vp->cacheCheck = 0;         /* XXXX */
337     vp->shuttingDown = 0;
338     vp->goingOffline = 0;
339     vp->nUsers = 1;
340     vp->header = (struct volHeader *)calloc(1, sizeof(*vp->header));
341     if (!vp->header) {
342         fprintf(stderr, "%s: Failed to allocate volume header.\n", progname);
343         free(vp);
344         return NULL;
345     }
346     ec = ReadHdr1(V_diskDataHandle(vp), (char *)&V_disk(vp),
347                   sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
348     if (!ec) {
349         struct IndexFileHeader iHead;
350         ec = ReadHdr1(vp->vnodeIndex[vSmall].handle, (char *)&iHead,
351                       sizeof(iHead), SMALLINDEXMAGIC, SMALLINDEXVERSION);
352     }
353     if (!ec) {
354         struct IndexFileHeader iHead;
355         ec = ReadHdr1(vp->vnodeIndex[vLarge].handle, (char *)&iHead,
356                       sizeof(iHead), LARGEINDEXMAGIC, LARGEINDEXVERSION);
357     }
358 #ifdef AFS_NAMEI_ENV
359     if (!ec) {
360         struct versionStamp stamp;
361         ec = ReadHdr1(V_linkHandle(vp), (char *)&stamp, sizeof(stamp),
362                       LINKTABLEMAGIC, LINKTABLEVERSION);
363     }
364 #endif
365     if (ec)
366         return (Volume *) 0;
367     return vp;
368 }
369
370 /**
371  * Simplified detach volume
372  *
373  * param[in] vp       volume object from AttachVolume
374  *
375  * @return none
376  */
377 static void
378 DetachVolume(Volume * vp)
379 {
380     IH_RELEASE(vp->vnodeIndex[vLarge].handle);
381     IH_RELEASE(vp->vnodeIndex[vSmall].handle);
382     IH_RELEASE(vp->diskDataHandle);
383     IH_RELEASE(V_linkHandle(vp));
384     free(vp->header);
385     free(vp);
386 }
387
388 /**
389  * Convert the partition device number into a partition name.
390  *
391  * @param[in]   partId      partition number, 0 to 254
392  * @param[out]  partName    buffer to hold partition name (e.g. /vicepa)
393  * @param[in]   partNameSize    size of partName buffer
394  *
395  * @return status
396  *   @retval 0 success
397  *   @retval -1 error, partId is out of range
398  *   @retval -2 error, partition name exceeds partNameSize
399  */
400 static int
401 GetPartitionName(afs_uint32 partId, char *partName, afs_size_t partNameSize)
402 {
403     const int OLD_NUM_DEVICES = 26;     /* a..z */
404
405     if (partId < OLD_NUM_DEVICES) {
406         if (partNameSize < 8) {
407             return -2;
408         }
409         strlcpy(partName, "/vicep", partNameSize);
410         partName[6] = partId + 'a';
411         partName[7] = '\0';
412         return 0;
413     }
414     if (partId < VOLMAXPARTS) {
415         if (partNameSize < 9) {
416             return -2;
417         }
418         strlcpy(partName, "/vicep", partNameSize);
419         partId -= OLD_NUM_DEVICES;
420         partName[6] = 'a' + (partId / OLD_NUM_DEVICES);
421         partName[7] = 'a' + (partId % OLD_NUM_DEVICES);
422         partName[8] = '\0';
423         return 0;
424     }
425     return -1;
426 }
427
428 /**
429  * Process command line options and start scanning
430  *
431  * @param[in] as     command syntax object
432  * @param[in] arock  opaque object; not used
433  *
434  * @return error code
435  */
436 static int
437 handleit(struct cmd_syndesc *as, void *arock)
438 {
439     struct cmd_item *ti;
440     int err = 0;
441     afs_uint32 volumeId = 0;
442     char *partNameOrId = 0;
443     char partName[64] = "";
444     struct DiskPartition64 *partP = NULL;
445
446
447 #ifndef AFS_NT40_ENV
448     if (geteuid() != 0) {
449         fprintf(stderr, "%s: Must be run as root; sorry\n", progname);
450         return 1;
451     }
452 #endif
453
454     if (as->parms[P_ONLINE].items) {
455         fprintf(stderr, "%s: -online not supported\n", progname);
456         return 1;
457     }
458     if (as->parms[P_VNODE].items) {
459         DumpVnodes = 1;
460     }
461     if (as->parms[P_DATE].items) {
462         DumpDate = 1;
463     }
464     if (as->parms[P_INODE].items) {
465         DumpInodeNumber = 1;
466     }
467     if (as->parms[P_ITIME].items) {
468         InodeTimes = 1;
469     }
470     if ((ti = as->parms[P_PART].items)) {
471         partNameOrId = ti->data;
472     }
473     if ((ti = as->parms[P_VOLUMEID].items)) {
474         volumeId = strtoul(ti->data, NULL, 10);
475     }
476     if (as->parms[P_HEADER].items) {
477         DumpHeader = 1;
478     }
479     if (as->parms[P_SIZEONLY].items) {
480         ShowSizes = 1;
481     }
482     if (as->parms[P_FIXHEADER].items) {
483         FixHeader = 1;
484     }
485     if (as->parms[P_SAVEINODES].items) {
486         SaveInodes = 1;
487     }
488     if (as->parms[P_ORPHANED].items) {
489         ShowOrphaned = 1;
490     }
491 #if defined(AFS_NAMEI_ENV)
492     if (as->parms[P_FILENAMES].items) {
493         PrintFileNames = 1;
494     }
495 #endif
496
497     /* -saveinodes and -sizeOnly override the default mode.
498      * For compatibility with old versions of volinfo, -orphaned
499      * and -filename options imply -vnodes */
500     if (SaveInodes || ShowSizes) {
501         DumpInfo = 0;
502         DumpHeader = 0;
503         DumpVnodes = 0;
504         InodeTimes = 0;
505         ShowOrphaned = 0;
506     } else if (ShowOrphaned) {
507         DumpVnodes = 1;         /* implied */
508 #ifdef AFS_NAMEI_ENV
509     } else if (PrintFileNames) {
510         DumpVnodes = 1;         /* implied */
511 #endif
512     }
513
514     /* Allow user to specify partition by name or id. */
515     if (partNameOrId) {
516         afs_uint32 partId = volutil_GetPartitionID(partNameOrId);
517         if (partId == -1) {
518             fprintf(stderr, "%s: Could not parse '%s' as a partition name.\n",
519                     progname, partNameOrId);
520             return 1;
521         }
522         if (GetPartitionName(partId, partName, sizeof(partName))) {
523             fprintf(stderr,
524                     "%s: Could not format '%s' as a partition name.\n",
525                     progname, partNameOrId);
526             return 1;
527         }
528     }
529
530     DInit(10);
531
532     err = VAttachPartitions();
533     if (err) {
534         fprintf(stderr, "%s: %d partitions had errors during attach.\n",
535                 progname, err);
536     }
537
538     if (partName[0]) {
539         partP = VGetPartition(partName, 0);
540         if (!partP) {
541             fprintf(stderr,
542                     "%s: %s is not an AFS partition name on this server.\n",
543                     progname, partName);
544             return 1;
545         }
546     }
547
548     if (!volumeId) {
549         if (!partP) {
550             HandleAllPart();
551         } else {
552             HandlePart(partP);
553         }
554     } else {
555         char name1[128];
556
557         if (!partP) {
558             partP = FindCurrentPartition();
559             if (!partP) {
560                 fprintf(stderr,
561                         "%s: Current partition is not a vice partition.\n",
562                         progname);
563                 return 1;
564             }
565         }
566         snprintf(name1, sizeof name1, VFORMAT,
567                  afs_printable_uint32_lu(volumeId));
568         HandleVolume(partP, name1);
569     }
570     return 0;
571 }
572
573 /**
574  * Determine if the current directory is a vice partition
575  *
576  * @return disk partition object
577  */
578 #ifdef AFS_NT40_ENV
579 #include <direct.h>
580 struct DiskPartition64 *
581 FindCurrentPartition(void)
582 {
583     int dr = _getdrive();
584     struct DiskPartition64 *dp;
585
586     dr--;
587     for (dp = DiskPartitionList; dp; dp = dp->next) {
588         if (*dp->devName - 'A' == dr)
589             break;
590     }
591     if (!dp) {
592         fprintf(stderr, "%s: Current drive is not a valid vice partition.\n",
593                 progname);
594     }
595     return dp;
596 }
597 #else
598 struct DiskPartition64 *
599 FindCurrentPartition(void)
600 {
601     char partName[1024];
602     char tmp = '\0';
603     char *p;
604     struct DiskPartition64 *dp;
605
606     if (!getcwd(partName, 1023)) {
607         fprintf(stderr, "%s: Failed to get current working directory: ",
608                 progname);
609         perror("pwd");
610         return NULL;
611     }
612     p = strchr(&partName[1], OS_DIRSEPC);
613     if (p) {
614         tmp = *p;
615         *p = '\0';
616     }
617     if (!(dp = VGetPartition(partName, 0))) {
618         if (tmp)
619             *p = tmp;
620         fprintf(stderr, "%s: %s is not a valid vice partition.\n", progname,
621                 partName);
622         return NULL;
623     }
624     return dp;
625 }
626 #endif
627
628 /**
629  * Scan and handle all the partitions detected on this server
630  *
631  * @return none
632  */
633 void
634 HandleAllPart(void)
635 {
636     struct DiskPartition64 *partP;
637
638
639     for (partP = DiskPartitionList; partP; partP = partP->next) {
640         printf("Processing Partition %s:\n", partP->name);
641         HandlePart(partP);
642         if (ShowSizes) {
643             AddSizeTotals(&serverTotals, &partitionTotals);
644         }
645     }
646
647     if (ShowSizes) {
648         PrintServerTotals();
649     }
650 }
651
652 /**
653  * Scan the partition and handle volumes
654  *
655  * @param[in] partP  disk partition to scan
656  *
657  * @return none
658  */
659 void
660 HandlePart(struct DiskPartition64 *partP)
661 {
662     afs_int64 nvols = 0;
663     DIR *dirp;
664     struct dirent *dp;
665 #ifdef AFS_NT40_ENV
666     char pname[64];
667     char *p = pname;
668     (void)sprintf(pname, "%s\\", VPartitionPath(partP));
669 #else
670     char *p = VPartitionPath(partP);
671 #endif
672
673     if ((dirp = opendir(p)) == NULL) {
674         fprintf(stderr, "%s: Can't read directory %s; giving up\n", progname,
675                 p);
676         return;
677     }
678     while ((dp = readdir(dirp))) {
679         p = (char *)strrchr(dp->d_name, '.');
680         if (p != NULL && strcmp(p, VHDREXT) == 0) {
681             HandleVolume(partP, dp->d_name);
682             if (ShowSizes) {
683                 nvols++;
684                 AddSizeTotals(&partitionTotals, &volumeTotals);
685             }
686         }
687     }
688     closedir(dirp);
689     if (ShowSizes) {
690         PrintPartitionTotals(nvols);
691     }
692 }
693
694 /**
695  * Inspect a volume header special file.
696  *
697  * @param[in]  name       descriptive name of the type of header special file
698  * @param[in]  dp         partition object for this volume
699  * @param[in]  header     header object for this volume
700  * @param[in]  inode      fileserver inode number for this header special file
701  * @param[out] psize      total of the header special file
702  *
703  * @return none
704  */
705 void
706 HandleSpecialFile(const char *name, struct DiskPartition64 *dp,
707                   struct VolumeHeader *header, Inode inode,
708                   afs_sfsize_t * psize)
709 {
710     afs_sfsize_t size = 0;
711     IHandle_t *ih = NULL;
712     FdHandle_t *fdP = NULL;
713 #ifdef AFS_NAMEI_ENV
714     namei_t filename;
715 #endif /* AFS_NAMEI_ENV */
716
717     IH_INIT(ih, dp->device, header->parent, inode);
718     fdP = IH_OPEN(ih);
719     if (fdP == NULL) {
720         fprintf(stderr,
721                 "%s: Error opening header file '%s' for volume %u", progname,
722                 name, header->id);
723         perror("open");
724         goto error;
725     }
726     size = FDH_SIZE(fdP);
727     if (size == -1) {
728         fprintf(stderr,
729                 "%s: Error getting size of header file '%s' for volume %u",
730                 progname, name, header->id);
731         perror("fstat");
732         goto error;
733     }
734     if (DumpInfo) {
735         printf("\t%s inode\t= %s (size = %lld)\n",
736                name, PrintInode(NULL, inode), size);
737 #ifdef AFS_NAMEI_ENV
738         namei_HandleToName(&filename, ih);
739         printf("\t%s namei\t= %s\n", name, filename.n_path);
740 #endif /* AFS_NAMEI_ENV */
741     }
742     *psize += size;
743
744   error:
745     if (fdP != NULL) {
746         FDH_REALLYCLOSE(fdP);
747     }
748     if (ih != NULL) {
749         IH_RELEASE(ih);
750     }
751 }
752
753 /**
754  * Inspect this volume header files.
755  *
756  * @param[in]  dp         partition object for this volume
757  * @param[in]  header_fd  volume header file descriptor
758  * @param[in]  header     volume header object
759  * @param[out] psize      total of the header special file
760  *
761  * @return none
762  */
763 void
764 HandleHeaderFiles(struct DiskPartition64 *dp, FD_t header_fd,
765                   struct VolumeHeader *header)
766 {
767     afs_sfsize_t size = 0;
768
769     if (DumpInfo) {
770         size = OS_SIZE(header_fd);
771         printf("Volume header (size = %lld):\n", size);
772         printf("\tstamp\t= 0x%x\n", header->stamp.version);
773         printf("\tVolId\t= %u\n", header->id);
774         printf("\tparent\t= %u\n", header->parent);
775     }
776
777     HandleSpecialFile("Info", dp, header, header->volumeInfo, &size);
778     HandleSpecialFile("Small", dp, header, header->smallVnodeIndex,
779                       &size);
780     HandleSpecialFile("Large", dp, header, header->largeVnodeIndex,
781                       &size);
782 #ifdef AFS_NAMEI_ENV
783     HandleSpecialFile("Link", dp, header, header->linkTable, &size);
784 #endif /* AFS_NAMEI_ENV */
785
786     if (DumpInfo) {
787         printf("Total aux volume size = %lld\n\n", size);
788     }
789
790     if (ShowSizes) {
791         volumeTotals.auxsize = size;
792         volumeTotals.auxsize_k = size / 1024;
793     }
794 }
795
796 /**
797  * Attach and scan the volume and handle the header and vnodes
798  *
799  * Print the volume header and vnode information, depending on the
800  * current modes.
801  *
802  * @param[in] dp    vice partition object for this volume
803  * @param[in] name  volume header file name
804  *
805  * @return none
806  */
807 void
808 HandleVolume(struct DiskPartition64 *dp, char *name)
809 {
810     struct VolumeHeader header;
811     struct VolumeDiskHeader diskHeader;
812     FD_t fd = INVALID_FD;
813     Volume *vp = NULL;
814     char headerName[1024];
815     afs_sfsize_t n;
816
817     snprintf(headerName, sizeof headerName, "%s" OS_DIRSEP "%s",
818              VPartitionPath(dp), name);
819     if ((fd = OS_OPEN(headerName, O_RDONLY, 0666)) == INVALID_FD) {
820         fprintf(stderr, "%s: Cannot open volume header %s\n", progname, name);
821         goto cleanup;
822     }
823     if (OS_SIZE(fd) < 0) {
824         fprintf(stderr, "%s: Cannot read volume header %s\n", progname, name);
825         goto cleanup;
826     }
827     n = OS_READ(fd, &diskHeader, sizeof(diskHeader));
828     if (n != sizeof(diskHeader)
829         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
830         fprintf(stderr, "%s: Error reading volume header %s\n", progname,
831                 name);
832         goto cleanup;
833     }
834     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
835         fprintf(stderr,
836                 "%s: Volume %s, version number is incorrect; volume needs to be salvaged\n",
837                 progname, name);
838         goto cleanup;
839     }
840
841     DiskToVolumeHeader(&header, &diskHeader);
842     if (DumpHeader || ShowSizes) {
843         HandleHeaderFiles(dp, fd, &header);
844     }
845
846     vp = AttachVolume(dp, name, &header);
847     if (!vp) {
848         fprintf(stderr, "%s: Error attaching volume header %s\n",
849                 progname, name);
850         goto cleanup;
851     }
852
853     if (DumpInfo) {
854         PrintHeader(vp);
855     }
856     if (DumpVnodes || ShowSizes || ShowOrphaned) {
857         HandleVnodes(vp, vLarge);
858     }
859     if (DumpVnodes || ShowSizes || SaveInodes || ShowOrphaned) {
860         HandleVnodes(vp, vSmall);
861     }
862     if (ShowSizes) {
863         volumeTotals.diskused_k = V_diskused(vp);
864         volumeTotals.size_k =
865             volumeTotals.auxsize_k + volumeTotals.vnodesize_k;
866         PrintVolumeSizes(vp);
867     }
868
869   cleanup:
870     if (fd != INVALID_FD) {
871         OS_CLOSE(fd);
872     }
873     if (vp) {
874         DetachVolume(vp);
875     }
876 }
877
878 /**
879  * volinfo program entry
880  */
881 int
882 main(int argc, char **argv)
883 {
884     struct cmd_syndesc *ts;
885     afs_int32 code;
886
887     ts = cmd_CreateSyntax(NULL, handleit, NULL,
888                           "Dump volume's internal state");
889     cmd_AddParmAtOffset(ts, P_ONLINE, "-online", CMD_FLAG, CMD_OPTIONAL,
890                         "Get info from running fileserver");
891     cmd_AddParmAtOffset(ts, P_VNODE, "-vnode", CMD_FLAG, CMD_OPTIONAL,
892                         "Dump vnode info");
893     cmd_AddParmAtOffset(ts, P_DATE, "-date", CMD_FLAG, CMD_OPTIONAL,
894                         "Also dump vnode's mod date");
895     cmd_AddParmAtOffset(ts, P_INODE, "-inode", CMD_FLAG, CMD_OPTIONAL,
896                         "Also dump vnode's inode number");
897     cmd_AddParmAtOffset(ts, P_ITIME, "-itime", CMD_FLAG, CMD_OPTIONAL,
898                         "Dump special inode's mod times");
899     cmd_AddParmAtOffset(ts, P_PART, "-part", CMD_LIST, CMD_OPTIONAL,
900                         "AFS partition name or id (default current partition)");
901     cmd_AddParmAtOffset(ts, P_VOLUMEID, "-volumeid", CMD_LIST, CMD_OPTIONAL,
902                         "Volume id");
903     cmd_AddParmAtOffset(ts, P_HEADER, "-header", CMD_FLAG, CMD_OPTIONAL,
904                         "Dump volume's header info");
905     cmd_AddParmAtOffset(ts, P_SIZEONLY, "-sizeonly", CMD_FLAG, CMD_OPTIONAL,
906                         "Dump volume's size");
907     cmd_AddParmAtOffset(ts, P_FIXHEADER, "-fixheader", CMD_FLAG,
908                         CMD_OPTIONAL, "Try to fix header");
909     cmd_AddParmAtOffset(ts, P_SAVEINODES, "-saveinodes", CMD_FLAG,
910                         CMD_OPTIONAL, "Try to save all inodes");
911     cmd_AddParmAtOffset(ts, P_ORPHANED, "-orphaned", CMD_FLAG, CMD_OPTIONAL,
912                         "List all dir/files without a parent");
913 #if defined(AFS_NAMEI_ENV)
914     cmd_AddParmAtOffset(ts, P_FILENAMES, "-filenames", CMD_FLAG,
915                         CMD_OPTIONAL, "Also dump vnode's namei filename");
916 #endif
917
918     /* For compatibility with older versions. */
919     cmd_AddParmAlias(ts, P_SIZEONLY, "-sizeOnly");
920
921     code = cmd_Dispatch(argc, argv);
922     return code;
923 }
924
925 #define typestring(type) (type == RWVOL? "read/write": type == ROVOL? "readonly": type == BACKVOL? "backup": "unknown")
926
927 /**
928  * Print the volume header information
929  *
930  * @param[in]  volume object
931  *
932  * @return none
933  */
934 void
935 PrintHeader(Volume * vp)
936 {
937     printf("Volume header for volume %u (%s)\n", V_id(vp), V_name(vp));
938     printf("stamp.magic = %x, stamp.version = %u\n", V_stamp(vp).magic,
939            V_stamp(vp).version);
940     printf
941         ("inUse = %d, inService = %d, blessed = %d, needsSalvaged = %d, dontSalvage = %d\n",
942          V_inUse(vp), V_inService(vp), V_blessed(vp), V_needsSalvaged(vp),
943          V_dontSalvage(vp));
944     printf
945         ("type = %d (%s), uniquifier = %u, needsCallback = %d, destroyMe = %x\n",
946          V_type(vp), typestring(V_type(vp)), V_uniquifier(vp),
947          V_needsCallback(vp), V_destroyMe(vp));
948     printf
949         ("id = %u, parentId = %u, cloneId = %u, backupId = %u, restoredFromId = %u\n",
950          V_id(vp), V_parentId(vp), V_cloneId(vp), V_backupId(vp),
951          V_restoredFromId(vp));
952     printf
953         ("maxquota = %d, minquota = %d, maxfiles = %d, filecount = %d, diskused = %d\n",
954          V_maxquota(vp), V_minquota(vp), V_maxfiles(vp), V_filecount(vp),
955          V_diskused(vp));
956     printf("creationDate = %s, copyDate = %s\n", date(V_creationDate(vp)),
957            date(V_copyDate(vp)));
958     printf("backupDate = %s, expirationDate = %s\n", date(V_backupDate(vp)),
959            date(V_expirationDate(vp)));
960     printf("accessDate = %s, updateDate = %s\n", date(V_accessDate(vp)),
961            date(V_updateDate(vp)));
962     printf("owner = %u, accountNumber = %u\n", V_owner(vp),
963            V_accountNumber(vp));
964     printf
965         ("dayUse = %u; week = (%u, %u, %u, %u, %u, %u, %u), dayUseDate = %s\n",
966          V_dayUse(vp), V_weekUse(vp)[0], V_weekUse(vp)[1], V_weekUse(vp)[2],
967          V_weekUse(vp)[3], V_weekUse(vp)[4], V_weekUse(vp)[5],
968          V_weekUse(vp)[6], date(V_dayUseDate(vp)));
969     printf("volUpdateCounter = %u\n", V_volUpCounter(vp));
970 }
971
972 /**
973  * Get the size and times of a file
974  *
975  * @param[in]  fd     file descriptor of file to stat
976  * @param[out] size   size of the file
977  * @param[out] ctime  ctime of file as a formatted string
978  * @param[out] mtime  mtime of file as a formatted string
979  * @param[out] atime  atime of file as a formatted string
980  *
981  * @return error code
982  *   @retval 0 success
983  *   @retval -1 failed to retrieve file information
984  */
985 static int
986 GetFileInfo(FD_t fd, afs_sfsize_t * size, char **ctime, char **mtime,
987             char **atime)
988 {
989 #ifdef AFS_NT40_ENV
990     BY_HANDLE_FILE_INFORMATION fi;
991     LARGE_INTEGER fsize;
992     if (!GetFileInformationByHandle(fd, &fi)) {
993         fprintf(stderr, "%s: GetFileInformationByHandle failed\n", progname);
994         return -1;
995     }
996     if (!GetFileSizeEx(fd, &fsize)) {
997         fprintf(stderr, "%s: GetFileSizeEx failed\n", progname);
998         return -1;
999     }
1000     *size = fsize.QuadPart;
1001     *ctime = "N/A";
1002     *mtime = NT_date(&fi.ftLastWriteTime);
1003     *atime = NT_date(&fi.ftLastAccessTime);
1004 #else
1005     struct afs_stat_st status;
1006     if (afs_fstat(fd, &status) == -1) {
1007         fprintf(stderr, "%s: fstat failed %d\n", progname, errno);
1008         return -1;
1009     }
1010     *size = status.st_size;
1011     *ctime = date(status.st_ctime);
1012     *mtime = date(status.st_mtime);
1013     *atime = date(status.st_atime);
1014 #endif
1015     return 0;
1016 }
1017
1018 /**
1019  * Copy the inode data to a file in the current directory.
1020  *
1021  * @param[in] vp     volume object
1022  * @param[in] vnode  vnode object
1023  * @param[in] inode  inode of the source file
1024  *
1025  * @return none
1026  */
1027 static void
1028 SaveInode(Volume * vp, struct VnodeDiskObject *vnode, Inode ino)
1029 {
1030     IHandle_t *ih;
1031     FdHandle_t *fdP;
1032     char nfile[50], buffer[256];
1033     int ofd = 0;
1034     afs_foff_t total;
1035     ssize_t len;
1036
1037     if (!VALID_INO(ino)) {
1038         return;
1039     }
1040
1041     IH_INIT(ih, V_device(vp), V_parentId(vp), ino);
1042     fdP = IH_OPEN(ih);
1043     if (fdP == NULL) {
1044         fprintf(stderr,
1045                 "%s: Can't open inode %s error %d (ignored)\n",
1046                 progname, PrintInode(NULL, ino), errno);
1047         return;
1048     }
1049     snprintf(nfile, sizeof nfile, "TmpInode.%s", PrintInode(NULL, ino));
1050     ofd = afs_open(nfile, O_CREAT | O_RDWR | O_TRUNC, 0600);
1051     if (ofd < 0) {
1052         fprintf(stderr,
1053                 "%s: Can't create file %s; error %d (ignored)\n",
1054                 progname, nfile, errno);
1055
1056         FDH_REALLYCLOSE(fdP);
1057         IH_RELEASE(ih);
1058         return;
1059     }
1060     total = 0;
1061     while (1) {
1062         ssize_t nBytes;
1063         len = FDH_PREAD(fdP, buffer, sizeof(buffer), total);
1064         if (len < 0) {
1065             FDH_REALLYCLOSE(fdP);
1066             IH_RELEASE(ih);
1067             close(ofd);
1068             unlink(nfile);
1069             fprintf(stderr,
1070                     "%s: Error while reading from inode %s (%d)\n",
1071                     progname, PrintInode(NULL, ino), errno);
1072             return;
1073         }
1074         if (len == 0)
1075             break;              /* No more input */
1076         nBytes = write(ofd, buffer, len);
1077         if (nBytes != len) {
1078             FDH_REALLYCLOSE(fdP);
1079             IH_RELEASE(ih);
1080             close(ofd);
1081             unlink(nfile);
1082             fprintf(stderr,
1083                     "%s: Error while writing to \"%s\" (%d - ignored)\n",
1084                     progname, nfile, errno);
1085             return;
1086         }
1087         total += len;
1088     }
1089
1090     FDH_REALLYCLOSE(fdP);
1091     IH_RELEASE(ih);
1092     close(ofd);
1093     printf("... Copied inode %s to file %s (%lu bytes)\n",
1094            PrintInode(NULL, ino), nfile, (unsigned long)total);
1095 }
1096
1097 /**
1098  * Scan a volume index and handle each vnode
1099  *
1100  * @param[in] vp      volume object
1101  * @param[in] class   which index to scan
1102  *
1103  * @return none
1104  */
1105 void
1106 HandleVnodes(Volume * vp, VnodeClass class)
1107 {
1108     afs_int32 diskSize =
1109         (class == vSmall ? SIZEOF_SMALLDISKVNODE : SIZEOF_LARGEDISKVNODE);
1110     char buf[SIZEOF_LARGEDISKVNODE];
1111     struct VnodeDiskObject *vnode = (struct VnodeDiskObject *)buf;
1112     StreamHandle_t *file = NULL;
1113     int vnodeIndex;
1114     afs_sfsize_t nVnodes;
1115     afs_foff_t offset = 0;
1116     Inode ino;
1117     IHandle_t *ih = vp->vnodeIndex[class].handle;
1118     FdHandle_t *fdP = NULL;
1119     afs_sfsize_t size;
1120     char *ctime, *atime, *mtime;
1121
1122     /* print vnode table heading */
1123     if (class == vLarge) {
1124         if (DumpInfo) {
1125             printf("\nLarge vnodes (directories)\n");
1126         }
1127     } else {
1128         if (DumpInfo) {
1129             printf("\nSmall vnodes(files, symbolic links)\n");
1130             fflush(stdout);
1131         }
1132         if (SaveInodes) {
1133             printf("Saving all volume files to current directory ...\n");
1134             if (ShowSizes) {
1135                 PrintingVolumeSizes = 0;        /* print heading again */
1136             }
1137         }
1138     }
1139
1140     fdP = IH_OPEN(ih);
1141     if (fdP == NULL) {
1142         fprintf(stderr, "%s: open failed: ", progname);
1143         goto error;
1144     }
1145
1146     file = FDH_FDOPEN(fdP, "r");
1147     if (!file) {
1148         fprintf(stderr, "%s: fdopen failed\n", progname);
1149         goto error;
1150     }
1151
1152     if (GetFileInfo(fdP->fd_fd, &size, &ctime, &atime, &mtime) != 0) {
1153         goto error;
1154     }
1155     if (InodeTimes) {
1156         printf("ichanged : %s\nimodified: %s\niaccessed: %s\n\n", ctime,
1157                mtime, atime);
1158     }
1159
1160     nVnodes = (size / diskSize) - 1;
1161     if (nVnodes > 0) {
1162         STREAM_ASEEK(file, diskSize);
1163     } else
1164         nVnodes = 0;
1165
1166     for (vnodeIndex = 0;
1167          nVnodes && STREAM_READ(vnode, diskSize, 1, file) == 1;
1168          nVnodes--, vnodeIndex++, offset += diskSize) {
1169
1170         ino = VNDISK_GET_INO(vnode);
1171         if (ShowSizes) {
1172             afs_fsize_t fileLength;
1173
1174             VNDISK_GET_LEN(fileLength, vnode);
1175             if (fileLength > 0) {
1176                 volumeTotals.vnodesize += fileLength;
1177                 volumeTotals.vnodesize_k += fileLength / 1024;
1178             }
1179         }
1180         if (SaveInodes && (class == vSmall)) {
1181             SaveInode(vp, vnode, ino);
1182         }
1183         if (DumpVnodes || ShowOrphaned) {
1184             PrintVnode(offset, vnode,
1185                        bitNumberToVnodeNumber(vnodeIndex, class), ino, vp);
1186         }
1187     }
1188
1189   error:
1190     if (file) {
1191         STREAM_CLOSE(file);
1192     }
1193     if (fdP) {
1194         FDH_CLOSE(fdP);
1195     }
1196 }
1197
1198 /**
1199  * Print vnode information
1200  *
1201  * @param[in] offset       index offset of this vnode
1202  * @param[in] vnode        vnode object to be printed
1203  * @param[in] vnodeNumber  vnode number
1204  * @param[in] ino          fileserver inode number
1205  * @param[in] vp           parent volume of the vnode
1206  *
1207  * @return none
1208  */
1209 void
1210 PrintVnode(afs_foff_t offset, VnodeDiskObject * vnode, VnodeId vnodeNumber,
1211            Inode ino, Volume * vp)
1212 {
1213 #if defined(AFS_NAMEI_ENV)
1214     IHandle_t *ihtmpp;
1215     namei_t filename;
1216 #endif
1217     afs_fsize_t fileLength;
1218
1219     VNDISK_GET_LEN(fileLength, vnode);
1220
1221     /* The check for orphaned vnodes is currently limited to non-empty
1222      * vnodes with a parent of zero (and which are not the first entry
1223      * in the index). */
1224     if (ShowOrphaned && (fileLength == 0 || vnode->parent || !offset))
1225         return;
1226
1227     printf
1228         ("%10lld Vnode %u.%u.%u cloned: %u, length: %llu linkCount: %d parent: %u",
1229          (long long)offset, vnodeNumber, vnode->uniquifier, vnode->dataVersion,
1230          vnode->cloned, (afs_uintmax_t) fileLength, vnode->linkCount,
1231          vnode->parent);
1232     if (DumpInodeNumber)
1233         printf(" inode: %s", PrintInode(NULL, ino));
1234     if (DumpDate)
1235         printf(" ServerModTime: %s", date(vnode->serverModifyTime));
1236 #if defined(AFS_NAMEI_ENV)
1237     if (PrintFileNames) {
1238         IH_INIT(ihtmpp, V_device(vp), V_parentId(vp), ino);
1239         namei_HandleToName(&filename, ihtmpp);
1240 #if !defined(AFS_NT40_ENV)
1241         printf(" UFS-Filename: %s", filename.n_path);
1242 #else
1243         printf(" NTFS-Filename: %s", filename.n_path);
1244 #endif
1245     }
1246 #endif
1247     printf("\n");
1248 }