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