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