volinfo: PrintFileNames is namei-only
[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     } else {
304         if (DumpInfo) {
305             printf("Inode %s: Good magic %x and version %x\n",
306                    PrintInode(NULL, ih->ih_ino), magic, version);
307         }
308     }
309     return 0;
310 }
311
312 /**
313  * Simplified attach volume
314  *
315  * param[in] dp       vice disk partition object
316  * param[in] volname  volume header file name
317  * param[in] header   volume header object
318  *
319  * @return volume object or null on error
320  */
321 Volume *
322 AttachVolume(struct DiskPartition64 * dp, char *volname,
323              struct VolumeHeader * header)
324 {
325     Volume *vp;
326     afs_int32 ec = 0;
327
328     vp = (Volume *) calloc(1, sizeof(Volume));
329     vp->specialStatus = 0;
330     vp->device = dp->device;
331     vp->partition = dp;
332     IH_INIT(vp->vnodeIndex[vLarge].handle, dp->device, header->parent,
333             header->largeVnodeIndex);
334     IH_INIT(vp->vnodeIndex[vSmall].handle, dp->device, header->parent,
335             header->smallVnodeIndex);
336     IH_INIT(vp->diskDataHandle, dp->device, header->parent,
337             header->volumeInfo);
338     IH_INIT(V_linkHandle(vp), dp->device, header->parent, header->linkTable);
339     vp->cacheCheck = 0;         /* XXXX */
340     vp->shuttingDown = 0;
341     vp->goingOffline = 0;
342     vp->nUsers = 1;
343     vp->header = (struct volHeader *)calloc(1, sizeof(*vp->header));
344     ec = ReadHdr1(V_diskDataHandle(vp), (char *)&V_disk(vp),
345                   sizeof(V_disk(vp)), VOLUMEINFOMAGIC, VOLUMEINFOVERSION);
346     if (!ec) {
347         struct IndexFileHeader iHead;
348         ec = ReadHdr1(vp->vnodeIndex[vSmall].handle, (char *)&iHead,
349                       sizeof(iHead), SMALLINDEXMAGIC, SMALLINDEXVERSION);
350     }
351     if (!ec) {
352         struct IndexFileHeader iHead;
353         ec = ReadHdr1(vp->vnodeIndex[vLarge].handle, (char *)&iHead,
354                       sizeof(iHead), LARGEINDEXMAGIC, LARGEINDEXVERSION);
355     }
356 #ifdef AFS_NAMEI_ENV
357     if (!ec) {
358         struct versionStamp stamp;
359         ec = ReadHdr1(V_linkHandle(vp), (char *)&stamp, sizeof(stamp),
360                       LINKTABLEMAGIC, LINKTABLEVERSION);
361     }
362 #endif
363     if (ec)
364         return (Volume *) 0;
365     return vp;
366 }
367
368 /**
369  * Convert the partition device number into a partition name.
370  *
371  * @param[in]   partId      partition number, 0 to 254
372  * @param[out]  partName    buffer to hold partition name (e.g. /vicepa)
373  * @param[in]   partNameSize    size of partName buffer
374  *
375  * @return status
376  *   @retval 0 success
377  *   @retval -1 error, partId is out of range
378  *   @retval -2 error, partition name exceeds partNameSize
379  */
380 static int
381 GetPartitionName(afs_uint32 partId, char *partName, afs_size_t partNameSize)
382 {
383     const int OLD_NUM_DEVICES = 26;     /* a..z */
384
385     if (partId < OLD_NUM_DEVICES) {
386         if (partNameSize < 8) {
387             return -2;
388         }
389         strlcpy(partName, "/vicep", partNameSize);
390         partName[6] = partId + 'a';
391         partName[7] = '\0';
392         return 0;
393     }
394     if (partId < VOLMAXPARTS) {
395         if (partNameSize < 9) {
396             return -2;
397         }
398         strlcpy(partName, "/vicep", partNameSize);
399         partId -= OLD_NUM_DEVICES;
400         partName[6] = 'a' + (partId / OLD_NUM_DEVICES);
401         partName[7] = 'a' + (partId % OLD_NUM_DEVICES);
402         partName[8] = '\0';
403         return 0;
404     }
405     return -1;
406 }
407
408 /**
409  * Process command line options and start scanning
410  *
411  * @param[in] as     command syntax object
412  * @param[in] arock  opaque object; not used
413  *
414  * @return error code
415  */
416 static int
417 handleit(struct cmd_syndesc *as, void *arock)
418 {
419     struct cmd_item *ti;
420     int err = 0;
421     afs_uint32 volumeId = 0;
422     char *partNameOrId = 0;
423     char partName[64] = "";
424     struct DiskPartition64 *partP = NULL;
425
426
427 #ifndef AFS_NT40_ENV
428     if (geteuid() != 0) {
429         fprintf(stderr, "%s: Must be run as root; sorry\n", progname);
430         return 1;
431     }
432 #endif
433
434     if (as->parms[P_ONLINE].items) {
435         fprintf(stderr, "%s: -online not supported\n", progname);
436         return 1;
437     }
438     if (as->parms[P_VNODE].items) {
439         DumpVnodes = 1;
440     }
441     if (as->parms[P_DATE].items) {
442         DumpDate = 1;
443     }
444     if (as->parms[P_INODE].items) {
445         DumpInodeNumber = 1;
446     }
447     if (as->parms[P_ITIME].items) {
448         InodeTimes = 1;
449     }
450     if ((ti = as->parms[P_PART].items)) {
451         partNameOrId = ti->data;
452     }
453     if ((ti = as->parms[P_VOLUMEID].items)) {
454         volumeId = strtoul(ti->data, NULL, 10);
455     }
456     if (as->parms[P_HEADER].items) {
457         DumpHeader = 1;
458     }
459     if (as->parms[P_SIZEONLY].items) {
460         ShowSizes = 1;
461     }
462     if (as->parms[P_FIXHEADER].items) {
463         FixHeader = 1;
464     }
465     if (as->parms[P_SAVEINODES].items) {
466         SaveInodes = 1;
467     }
468     if (as->parms[P_ORPHANED].items) {
469         ShowOrphaned = 1;
470     }
471 #if defined(AFS_NAMEI_ENV)
472     if (as->parms[P_FILENAMES].items) {
473         PrintFileNames = 1;
474     }
475 #endif
476
477     /* -saveinodes and -sizeOnly override the default mode.
478      * For compatibility with old versions of volinfo, -orphaned
479      * and -filename options imply -vnodes */
480     if (SaveInodes || ShowSizes) {
481         DumpInfo = 0;
482         DumpHeader = 0;
483         DumpVnodes = 0;
484         InodeTimes = 0;
485         ShowOrphaned = 0;
486     } else if (ShowOrphaned) {
487         DumpVnodes = 1;         /* implied */
488 #ifdef AFS_NAMEI_ENV
489     } else if (PrintFileNames) {
490         DumpVnodes = 1;         /* implied */
491 #endif
492     }
493
494     /* Allow user to specify partition by name or id. */
495     if (partNameOrId) {
496         afs_uint32 partId = volutil_GetPartitionID(partNameOrId);
497         if (partId == -1) {
498             fprintf(stderr, "%s: Could not parse '%s' as a partition name.\n",
499                     progname, partNameOrId);
500             return 1;
501         }
502         if (GetPartitionName(partId, partName, sizeof(partName))) {
503             fprintf(stderr,
504                     "%s: Could not format '%s' as a partition name.\n",
505                     progname, partNameOrId);
506             return 1;
507         }
508     }
509
510     DInit(10);
511
512     err = VAttachPartitions();
513     if (err) {
514         fprintf(stderr, "%s: %d partitions had errors during attach.\n",
515                 progname, err);
516     }
517
518     if (partName[0]) {
519         partP = VGetPartition(partName, 0);
520         if (!partP) {
521             fprintf(stderr,
522                     "%s: %s is not an AFS partition name on this server.\n",
523                     progname, partName);
524             return 1;
525         }
526     }
527
528     if (!volumeId) {
529         if (!partP) {
530             HandleAllPart();
531         } else {
532             HandlePart(partP);
533         }
534     } else {
535         char name1[128];
536
537         if (!partP) {
538             partP = FindCurrentPartition();
539             if (!partP) {
540                 fprintf(stderr,
541                         "%s: Current partition is not a vice partition.\n",
542                         progname);
543                 return 1;
544             }
545         }
546         snprintf(name1, sizeof name1, VFORMAT,
547                  afs_printable_uint32_lu(volumeId));
548         HandleVolume(partP, name1);
549     }
550     return 0;
551 }
552
553 /**
554  * Determine if the current directory is a vice partition
555  *
556  * @return disk partition object
557  */
558 #ifdef AFS_NT40_ENV
559 #include <direct.h>
560 struct DiskPartition64 *
561 FindCurrentPartition(void)
562 {
563     int dr = _getdrive();
564     struct DiskPartition64 *dp;
565
566     dr--;
567     for (dp = DiskPartitionList; dp; dp = dp->next) {
568         if (*dp->devName - 'A' == dr)
569             break;
570     }
571     if (!dp) {
572         fprintf(stderr, "%s: Current drive is not a valid vice partition.\n",
573                 progname);
574     }
575     return dp;
576 }
577 #else
578 struct DiskPartition64 *
579 FindCurrentPartition(void)
580 {
581     char partName[1024];
582     char tmp = '\0';
583     char *p;
584     struct DiskPartition64 *dp;
585
586     if (!getcwd(partName, 1023)) {
587         fprintf(stderr, "%s: Failed to get current working directory: ",
588                 progname);
589         perror("pwd");
590         return NULL;
591     }
592     p = strchr(&partName[1], OS_DIRSEPC);
593     if (p) {
594         tmp = *p;
595         *p = '\0';
596     }
597     if (!(dp = VGetPartition(partName, 0))) {
598         if (tmp)
599             *p = tmp;
600         fprintf(stderr, "%s: %s is not a valid vice partition.\n", progname,
601                 partName);
602         return NULL;
603     }
604     return dp;
605 }
606 #endif
607
608 /**
609  * Scan and handle all the partitions detected on this server
610  *
611  * @return none
612  */
613 void
614 HandleAllPart(void)
615 {
616     struct DiskPartition64 *partP;
617
618
619     for (partP = DiskPartitionList; partP; partP = partP->next) {
620         printf("Processing Partition %s:\n", partP->name);
621         HandlePart(partP);
622         if (ShowSizes) {
623             AddSizeTotals(&serverTotals, &partitionTotals);
624         }
625     }
626
627     if (ShowSizes) {
628         PrintServerTotals();
629     }
630 }
631
632 /**
633  * Scan the partition and handle volumes
634  *
635  * @param[in] partP  disk partition to scan
636  *
637  * @return none
638  */
639 void
640 HandlePart(struct DiskPartition64 *partP)
641 {
642     afs_int64 nvols = 0;
643     DIR *dirp;
644     struct dirent *dp;
645 #ifdef AFS_NT40_ENV
646     char pname[64];
647     char *p = pname;
648     (void)sprintf(pname, "%s\\", VPartitionPath(partP));
649 #else
650     char *p = VPartitionPath(partP);
651 #endif
652
653     if ((dirp = opendir(p)) == NULL) {
654         fprintf(stderr, "%s: Can't read directory %s; giving up\n", progname,
655                 p);
656         return;
657     }
658     while ((dp = readdir(dirp))) {
659         p = (char *)strrchr(dp->d_name, '.');
660         if (p != NULL && strcmp(p, VHDREXT) == 0) {
661             HandleVolume(partP, dp->d_name);
662             if (ShowSizes) {
663                 nvols++;
664                 AddSizeTotals(&partitionTotals, &volumeTotals);
665             }
666         }
667     }
668     closedir(dirp);
669     if (ShowSizes) {
670         PrintPartitionTotals(nvols);
671     }
672 }
673
674 /**
675  * Inspect a volume header special file.
676  *
677  * @param[in]  name       descriptive name of the type of header special file
678  * @param[in]  dp         partition object for this volume
679  * @param[in]  header     header object for this volume
680  * @param[in]  inode      fileserver inode number for this header special file
681  * @param[out] psize      total of the header special file
682  *
683  * @return none
684  */
685 void
686 HandleSpecialFile(const char *name, struct DiskPartition64 *dp,
687                   struct VolumeHeader *header, Inode inode,
688                   afs_sfsize_t * psize)
689 {
690     afs_sfsize_t size = 0;
691     IHandle_t *ih = NULL;
692     FdHandle_t *fdP = NULL;
693 #ifdef AFS_NAMEI_ENV
694     namei_t filename;
695 #endif /* AFS_NAMEI_ENV */
696
697     IH_INIT(ih, dp->device, header->parent, inode);
698     fdP = IH_OPEN(ih);
699     if (fdP == NULL) {
700         fprintf(stderr,
701                 "%s: Error opening header file '%s' for volume %u", progname,
702                 name, header->id);
703         perror("open");
704         goto error;
705     }
706     size = FDH_SIZE(fdP);
707     if (size == -1) {
708         fprintf(stderr,
709                 "%s: Error getting size of header file '%s' for volume %u",
710                 progname, name, header->id);
711         perror("fstat");
712         goto error;
713     }
714     if (DumpInfo) {
715         printf("\t%s inode\t= %s (size = %lld)\n",
716                name, PrintInode(NULL, inode), size);
717 #ifdef AFS_NAMEI_ENV
718         namei_HandleToName(&filename, ih);
719         printf("\t%s namei\t= %s\n", name, filename.n_path);
720 #endif /* AFS_NAMEI_ENV */
721     }
722     *psize += size;
723
724   error:
725     if (fdP != NULL) {
726         FDH_REALLYCLOSE(fdP);
727     }
728     if (ih != NULL) {
729         IH_RELEASE(ih);
730     }
731 }
732
733 /**
734  * Inspect this volume header files.
735  *
736  * @param[in]  dp         partition object for this volume
737  * @param[in]  header_fd  volume header file descriptor
738  * @param[in]  header     volume header object
739  * @param[out] psize      total of the header special file
740  *
741  * @return none
742  */
743 void
744 HandleHeaderFiles(struct DiskPartition64 *dp, FD_t header_fd,
745                   struct VolumeHeader *header)
746 {
747     afs_sfsize_t size = 0;
748
749     if (DumpInfo) {
750         size = OS_SIZE(header_fd);
751         printf("Volume header (size = %lld):\n", size);
752         printf("\tstamp\t= 0x%x\n", header->stamp.version);
753         printf("\tVolId\t= %u\n", header->id);
754         printf("\tparent\t= %u\n", header->parent);
755     }
756
757     HandleSpecialFile("Info", dp, header, header->volumeInfo, &size);
758     HandleSpecialFile("Small", dp, header, header->smallVnodeIndex,
759                       &size);
760     HandleSpecialFile("Large", dp, header, header->largeVnodeIndex,
761                       &size);
762 #ifdef AFS_NAMEI_ENV
763     HandleSpecialFile("Link", dp, header, header->linkTable, &size);
764 #endif /* AFS_NAMEI_ENV */
765
766     if (DumpInfo) {
767         printf("Total aux volume size = %lld\n\n", size);
768     }
769
770     if (ShowSizes) {
771         volumeTotals.auxsize = size;
772         volumeTotals.auxsize_k = size / 1024;
773     }
774 }
775
776 /**
777  * Attach and scan the volume and handle the header and vnodes
778  *
779  * Print the volume header and vnode information, depending on the
780  * current modes.
781  *
782  * @param[in] dp    vice partition object for this volume
783  * @param[in] name  volume header file name
784  *
785  * @return none
786  */
787 void
788 HandleVolume(struct DiskPartition64 *dp, char *name)
789 {
790     struct VolumeHeader header;
791     struct VolumeDiskHeader diskHeader;
792     FD_t fd = INVALID_FD;
793     Volume *vp;
794     char headerName[1024];
795     afs_sfsize_t n;
796
797     snprintf(headerName, sizeof headerName, "%s" OS_DIRSEP "%s",
798              VPartitionPath(dp), name);
799     if ((fd = OS_OPEN(headerName, O_RDONLY, 0666)) == INVALID_FD) {
800         fprintf(stderr, "%s: Cannot open volume header %s\n", progname, name);
801         return;
802     }
803     if (OS_SIZE(fd) < 0) {
804         fprintf(stderr, "%s: Cannot read volume header %s\n", progname, name);
805         OS_CLOSE(fd);
806         return;
807     }
808     n = OS_READ(fd, &diskHeader, sizeof(diskHeader));
809     if (n != sizeof(diskHeader)
810         || diskHeader.stamp.magic != VOLUMEHEADERMAGIC) {
811         fprintf(stderr, "%s: Error reading volume header %s\n", progname,
812                 name);
813         OS_CLOSE(fd);
814         return;
815     }
816     if (diskHeader.stamp.version != VOLUMEHEADERVERSION) {
817         fprintf(stderr,
818                 "%s: Volume %s, version number is incorrect; volume needs to be salvaged\n",
819                 progname, name);
820         OS_CLOSE(fd);
821         return;
822     }
823     DiskToVolumeHeader(&header, &diskHeader);
824     if (DumpHeader || ShowSizes) {
825         HandleHeaderFiles(dp, fd, &header);
826     }
827     OS_CLOSE(fd);
828     vp = AttachVolume(dp, name, &header);
829     if (!vp) {
830         fprintf(stderr, "%s: Error attaching volume header %s\n",
831                 progname, name);
832         return;
833     }
834     if (DumpInfo) {
835         PrintHeader(vp);
836     }
837     if (DumpVnodes || ShowSizes || ShowOrphaned) {
838         HandleVnodes(vp, vLarge);
839     }
840     if (DumpVnodes || ShowSizes || SaveInodes || ShowOrphaned) {
841         HandleVnodes(vp, vSmall);
842     }
843     if (ShowSizes) {
844         volumeTotals.diskused_k = V_diskused(vp);
845         volumeTotals.size_k =
846             volumeTotals.auxsize_k + volumeTotals.vnodesize_k;
847         PrintVolumeSizes(vp);
848     }
849     free(vp->header);
850     free(vp);
851 }
852
853
854 /**
855  * volinfo program entry
856  */
857 int
858 main(int argc, char **argv)
859 {
860     struct cmd_syndesc *ts;
861     afs_int32 code;
862
863     ts = cmd_CreateSyntax(NULL, handleit, NULL,
864                           "Dump volume's internal state");
865     cmd_AddParmAtOffset(ts, P_ONLINE, "-online", CMD_FLAG, CMD_OPTIONAL,
866                         "Get info from running fileserver");
867     cmd_AddParmAtOffset(ts, P_VNODE, "-vnode", CMD_FLAG, CMD_OPTIONAL,
868                         "Dump vnode info");
869     cmd_AddParmAtOffset(ts, P_DATE, "-date", CMD_FLAG, CMD_OPTIONAL,
870                         "Also dump vnode's mod date");
871     cmd_AddParmAtOffset(ts, P_INODE, "-inode", CMD_FLAG, CMD_OPTIONAL,
872                         "Also dump vnode's inode number");
873     cmd_AddParmAtOffset(ts, P_ITIME, "-itime", CMD_FLAG, CMD_OPTIONAL,
874                         "Dump special inode's mod times");
875     cmd_AddParmAtOffset(ts, P_PART, "-part", CMD_LIST, CMD_OPTIONAL,
876                         "AFS partition name or id (default current partition)");
877     cmd_AddParmAtOffset(ts, P_VOLUMEID, "-volumeid", CMD_LIST, CMD_OPTIONAL,
878                         "Volume id");
879     cmd_AddParmAtOffset(ts, P_HEADER, "-header", CMD_FLAG, CMD_OPTIONAL,
880                         "Dump volume's header info");
881     cmd_AddParmAtOffset(ts, P_SIZEONLY, "-sizeonly", CMD_FLAG, CMD_OPTIONAL,
882                         "Dump volume's size");
883     cmd_AddParmAtOffset(ts, P_FIXHEADER, "-fixheader", CMD_FLAG,
884                         CMD_OPTIONAL, "Try to fix header");
885     cmd_AddParmAtOffset(ts, P_SAVEINODES, "-saveinodes", CMD_FLAG,
886                         CMD_OPTIONAL, "Try to save all inodes");
887     cmd_AddParmAtOffset(ts, P_ORPHANED, "-orphaned", CMD_FLAG, CMD_OPTIONAL,
888                         "List all dir/files without a parent");
889 #if defined(AFS_NAMEI_ENV)
890     cmd_AddParmAtOffset(ts, P_FILENAMES, "-filenames", CMD_FLAG,
891                         CMD_OPTIONAL, "Also dump vnode's namei filename");
892 #endif
893
894     /* For compatibility with older versions. */
895     cmd_AddParmAlias(ts, P_SIZEONLY, "-sizeOnly");
896
897     code = cmd_Dispatch(argc, argv);
898     return code;
899 }
900
901 #define typestring(type) (type == RWVOL? "read/write": type == ROVOL? "readonly": type == BACKVOL? "backup": "unknown")
902
903 /**
904  * Print the volume header information
905  *
906  * @param[in]  volume object
907  *
908  * @return none
909  */
910 void
911 PrintHeader(Volume * vp)
912 {
913     printf("Volume header for volume %u (%s)\n", V_id(vp), V_name(vp));
914     printf("stamp.magic = %x, stamp.version = %u\n", V_stamp(vp).magic,
915            V_stamp(vp).version);
916     printf
917         ("inUse = %d, inService = %d, blessed = %d, needsSalvaged = %d, dontSalvage = %d\n",
918          V_inUse(vp), V_inService(vp), V_blessed(vp), V_needsSalvaged(vp),
919          V_dontSalvage(vp));
920     printf
921         ("type = %d (%s), uniquifier = %u, needsCallback = %d, destroyMe = %x\n",
922          V_type(vp), typestring(V_type(vp)), V_uniquifier(vp),
923          V_needsCallback(vp), V_destroyMe(vp));
924     printf
925         ("id = %u, parentId = %u, cloneId = %u, backupId = %u, restoredFromId = %u\n",
926          V_id(vp), V_parentId(vp), V_cloneId(vp), V_backupId(vp),
927          V_restoredFromId(vp));
928     printf
929         ("maxquota = %d, minquota = %d, maxfiles = %d, filecount = %d, diskused = %d\n",
930          V_maxquota(vp), V_minquota(vp), V_maxfiles(vp), V_filecount(vp),
931          V_diskused(vp));
932     printf("creationDate = %s, copyDate = %s\n", date(V_creationDate(vp)),
933            date(V_copyDate(vp)));
934     printf("backupDate = %s, expirationDate = %s\n", date(V_backupDate(vp)),
935            date(V_expirationDate(vp)));
936     printf("accessDate = %s, updateDate = %s\n", date(V_accessDate(vp)),
937            date(V_updateDate(vp)));
938     printf("owner = %u, accountNumber = %u\n", V_owner(vp),
939            V_accountNumber(vp));
940     printf
941         ("dayUse = %u; week = (%u, %u, %u, %u, %u, %u, %u), dayUseDate = %s\n",
942          V_dayUse(vp), V_weekUse(vp)[0], V_weekUse(vp)[1], V_weekUse(vp)[2],
943          V_weekUse(vp)[3], V_weekUse(vp)[4], V_weekUse(vp)[5],
944          V_weekUse(vp)[6], date(V_dayUseDate(vp)));
945     printf("volUpdateCounter = %u\n", V_volUpCounter(vp));
946 }
947
948 /**
949  * Get the size and times of a file
950  *
951  * @param[in]  fd     file descriptor of file to stat
952  * @param[out] size   size of the file
953  * @param[out] ctime  ctime of file as a formatted string
954  * @param[out] mtime  mtime of file as a formatted string
955  * @param[out] atime  atime of file as a formatted string
956  *
957  * @return error code
958  *   @retval 0 success
959  *   @retval -1 failed to retrieve file information
960  */
961 static int
962 GetFileInfo(FD_t fd, afs_sfsize_t * size, char **ctime, char **mtime,
963             char **atime)
964 {
965 #ifdef AFS_NT40_ENV
966     BY_HANDLE_FILE_INFORMATION fi;
967     LARGE_INTEGER fsize;
968     if (!GetFileInformationByHandle(fd, &fi)) {
969         fprintf(stderr, "%s: GetFileInformationByHandle failed\n", progname);
970         return -1;
971     }
972     if (!GetFileSizeEx(fd, &fsize)) {
973         fprintf(stderr, "%s: GetFileSizeEx failed\n", progname);
974         return -1;
975     }
976     *size = fsize.QuadPart;
977     *ctime = "N/A";
978     *mtime = NT_date(&fi.ftLastWriteTime);
979     *atime = NT_date(&fi.ftLastAccessTime);
980 #else
981     struct afs_stat_st status;
982     if (afs_fstat(fd, &status) == -1) {
983         fprintf(stderr, "%s: fstat failed %d\n", progname, errno);
984         return -1;
985     }
986     *size = status.st_size;
987     *ctime = date(status.st_ctime);
988     *mtime = date(status.st_mtime);
989     *atime = date(status.st_atime);
990 #endif
991     return 0;
992 }
993
994 /**
995  * Copy the inode data to a file in the current directory.
996  *
997  * @param[in] vp     volume object
998  * @param[in] vnode  vnode object
999  * @param[in] inode  inode of the source file
1000  *
1001  * @return none
1002  */
1003 static void
1004 SaveInode(Volume * vp, struct VnodeDiskObject *vnode, Inode ino)
1005 {
1006     IHandle_t *ih;
1007     FdHandle_t *fdP;
1008     char nfile[50], buffer[256];
1009     int ofd = 0;
1010     afs_foff_t total;
1011     ssize_t len;
1012
1013     if (!VALID_INO(ino)) {
1014         return;
1015     }
1016
1017     IH_INIT(ih, V_device(vp), V_parentId(vp), ino);
1018     fdP = IH_OPEN(ih);
1019     if (fdP == NULL) {
1020         fprintf(stderr,
1021                 "%s: Can't open inode %s error %d (ignored)\n",
1022                 progname, PrintInode(NULL, ino), errno);
1023         return;
1024     }
1025     snprintf(nfile, sizeof nfile, "TmpInode.%s", PrintInode(NULL, ino));
1026     ofd = afs_open(nfile, O_CREAT | O_RDWR | O_TRUNC, 0600);
1027     if (ofd < 0) {
1028         fprintf(stderr,
1029                 "%s: Can't create file %s; error %d (ignored)\n",
1030                 progname, nfile, errno);
1031
1032         FDH_REALLYCLOSE(fdP);
1033         IH_RELEASE(ih);
1034         return;
1035     }
1036     total = 0;
1037     while (1) {
1038         ssize_t nBytes;
1039         len = FDH_PREAD(fdP, buffer, sizeof(buffer), total);
1040         if (len < 0) {
1041             FDH_REALLYCLOSE(fdP);
1042             IH_RELEASE(ih);
1043             close(ofd);
1044             unlink(nfile);
1045             fprintf(stderr,
1046                     "%s: Error while reading from inode %s (%d)\n",
1047                     progname, PrintInode(NULL, ino), errno);
1048             return;
1049         }
1050         if (len == 0)
1051             break;              /* No more input */
1052         nBytes = write(ofd, buffer, len);
1053         if (nBytes != len) {
1054             FDH_REALLYCLOSE(fdP);
1055             IH_RELEASE(ih);
1056             close(ofd);
1057             unlink(nfile);
1058             fprintf(stderr,
1059                     "%s: Error while writing to \"%s\" (%d - ignored)\n",
1060                     progname, nfile, errno);
1061             return;
1062         }
1063         total += len;
1064     }
1065
1066     FDH_REALLYCLOSE(fdP);
1067     IH_RELEASE(ih);
1068     close(ofd);
1069     printf("... Copied inode %s to file %s (%lu bytes)\n",
1070            PrintInode(NULL, ino), nfile, (unsigned long)total);
1071 }
1072
1073 /**
1074  * Scan a volume index and handle each vnode
1075  *
1076  * @param[in] vp      volume object
1077  * @param[in] class   which index to scan
1078  *
1079  * @return none
1080  */
1081 void
1082 HandleVnodes(Volume * vp, VnodeClass class)
1083 {
1084     afs_int32 diskSize =
1085         (class == vSmall ? SIZEOF_SMALLDISKVNODE : SIZEOF_LARGEDISKVNODE);
1086     char buf[SIZEOF_LARGEDISKVNODE];
1087     struct VnodeDiskObject *vnode = (struct VnodeDiskObject *)buf;
1088     StreamHandle_t *file = NULL;
1089     int vnodeIndex;
1090     afs_sfsize_t nVnodes;
1091     afs_foff_t offset = 0;
1092     Inode ino;
1093     IHandle_t *ih = vp->vnodeIndex[class].handle;
1094     FdHandle_t *fdP = NULL;
1095     afs_sfsize_t size;
1096     char *ctime, *atime, *mtime;
1097
1098     /* print vnode table heading */
1099     if (class == vLarge) {
1100         if (DumpInfo) {
1101             printf("\nLarge vnodes (directories)\n");
1102         }
1103     } else {
1104         if (DumpInfo) {
1105             printf("\nSmall vnodes(files, symbolic links)\n");
1106             fflush(stdout);
1107         }
1108         if (SaveInodes) {
1109             printf("Saving all volume files to current directory ...\n");
1110             if (ShowSizes) {
1111                 PrintingVolumeSizes = 0;        /* print heading again */
1112             }
1113         }
1114     }
1115
1116     fdP = IH_OPEN(ih);
1117     if (fdP == NULL) {
1118         fprintf(stderr, "%s: open failed: ", progname);
1119         goto error;
1120     }
1121
1122     file = FDH_FDOPEN(fdP, "r");
1123     if (!file) {
1124         fprintf(stderr, "%s: fdopen failed\n", progname);
1125         goto error;
1126     }
1127
1128     if (GetFileInfo(fdP->fd_fd, &size, &ctime, &atime, &mtime) != 0) {
1129         goto error;
1130     }
1131     if (InodeTimes) {
1132         printf("ichanged : %s\nimodified: %s\niaccessed: %s\n\n", ctime,
1133                mtime, atime);
1134     }
1135
1136     nVnodes = (size / diskSize) - 1;
1137     if (nVnodes > 0) {
1138         STREAM_ASEEK(file, diskSize);
1139     } else
1140         nVnodes = 0;
1141
1142     for (vnodeIndex = 0;
1143          nVnodes && STREAM_READ(vnode, diskSize, 1, file) == 1;
1144          nVnodes--, vnodeIndex++, offset += diskSize) {
1145
1146         ino = VNDISK_GET_INO(vnode);
1147         if (ShowSizes) {
1148             afs_fsize_t fileLength;
1149
1150             VNDISK_GET_LEN(fileLength, vnode);
1151             if (fileLength > 0) {
1152                 volumeTotals.vnodesize += fileLength;
1153                 volumeTotals.vnodesize_k += fileLength / 1024;
1154             }
1155         }
1156         if (SaveInodes && (class == vSmall)) {
1157             SaveInode(vp, vnode, ino);
1158         }
1159         if (DumpVnodes || ShowOrphaned) {
1160             PrintVnode(offset, vnode,
1161                        bitNumberToVnodeNumber(vnodeIndex, class), ino, vp);
1162         }
1163     }
1164
1165   error:
1166     if (file) {
1167         STREAM_CLOSE(file);
1168     }
1169     if (fdP) {
1170         FDH_CLOSE(fdP);
1171     }
1172 }
1173
1174 /**
1175  * Print vnode information
1176  *
1177  * @param[in] offset       index offset of this vnode
1178  * @param[in] vnode        vnode object to be printed
1179  * @param[in] vnodeNumber  vnode number
1180  * @param[in] ino          fileserver inode number
1181  * @param[in] vp           parent volume of the vnode
1182  *
1183  * @return none
1184  */
1185 void
1186 PrintVnode(afs_foff_t offset, VnodeDiskObject * vnode, VnodeId vnodeNumber,
1187            Inode ino, Volume * vp)
1188 {
1189 #if defined(AFS_NAMEI_ENV)
1190     IHandle_t *ihtmpp;
1191     namei_t filename;
1192 #endif
1193     afs_fsize_t fileLength;
1194
1195     VNDISK_GET_LEN(fileLength, vnode);
1196
1197     /* The check for orphaned vnodes is currently limited to non-empty
1198      * vnodes with a parent of zero (and which are not the first entry
1199      * in the index). */
1200     if (ShowOrphaned && (fileLength == 0 || vnode->parent || !offset))
1201         return;
1202
1203     printf
1204         ("%10lld Vnode %u.%u.%u cloned: %u, length: %llu linkCount: %d parent: %u",
1205          (long long)offset, vnodeNumber, vnode->uniquifier, vnode->dataVersion,
1206          vnode->cloned, (afs_uintmax_t) fileLength, vnode->linkCount,
1207          vnode->parent);
1208     if (DumpInodeNumber)
1209         printf(" inode: %s", PrintInode(NULL, ino));
1210     if (DumpDate)
1211         printf(" ServerModTime: %s", date(vnode->serverModifyTime));
1212 #if defined(AFS_NAMEI_ENV)
1213     if (PrintFileNames) {
1214         IH_INIT(ihtmpp, V_device(vp), V_parentId(vp), ino);
1215         namei_HandleToName(&filename, ihtmpp);
1216 #if !defined(AFS_NT40_ENV)
1217         printf(" UFS-Filename: %s", filename.n_path);
1218 #else
1219         printf(" NTFS-Filename: %s", filename.n_path);
1220 #endif
1221     }
1222 #endif
1223     printf("\n");
1224 }