Whamcloud - gitweb
Remove trailing whitespace for the entire source tree
[tools/e2fsprogs.git] / lib / blkid / probe.c
1 /*
2  * probe.c - identify a block device by its contents, and return a dev
3  *           struct with the details
4  *
5  * Copyright (C) 1999 by Andries Brouwer
6  * Copyright (C) 1999, 2000, 2003 by Theodore Ts'o
7  * Copyright (C) 2001 by Andreas Dilger
8  * Copyright (C) 2004 Kay Sievers <kay.sievers@vrfy.org>
9  *
10  * %Begin-Header%
11  * This file may be redistributed under the terms of the
12  * GNU Lesser General Public License.
13  * %End-Header%
14  */
15
16 #include <stdio.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <fcntl.h>
21 #include <ctype.h>
22 #include <sys/types.h>
23 #ifdef HAVE_SYS_STAT_H
24 #include <sys/stat.h>
25 #endif
26 #ifdef HAVE_SYS_MKDEV_H
27 #include <sys/mkdev.h>
28 #endif
29 #include <sys/utsname.h>
30 #ifdef HAVE_ERRNO_H
31 #include <errno.h>
32 #endif
33 #include "blkidP.h"
34 #include "uuid/uuid.h"
35 #include "probe.h"
36
37 static int figure_label_len(const unsigned char *label, int len)
38 {
39         const unsigned char *end = label + len - 1;
40
41         while ((*end == ' ' || *end == 0) && end >= label)
42                 --end;
43         if (end >= label) {
44                 label = label;
45                 return end - label + 1;
46         }
47         return 0;
48 }
49
50 static unsigned char *get_buffer(struct blkid_probe *pr,
51                           blkid_loff_t off, size_t len)
52 {
53         ssize_t         ret_read;
54         unsigned char   *newbuf;
55
56         if (off + len <= SB_BUFFER_SIZE) {
57                 if (!pr->sbbuf) {
58                         pr->sbbuf = malloc(SB_BUFFER_SIZE);
59                         if (!pr->sbbuf)
60                                 return NULL;
61                         if (lseek(pr->fd, 0, SEEK_SET) < 0)
62                                 return NULL;
63                         ret_read = read(pr->fd, pr->sbbuf, SB_BUFFER_SIZE);
64                         if (ret_read < 0)
65                                 ret_read = 0;
66                         pr->sb_valid = ret_read;
67                 }
68                 if (off+len > pr->sb_valid)
69                         return NULL;
70                 return pr->sbbuf + off;
71         } else {
72                 if (len > pr->buf_max) {
73                         newbuf = realloc(pr->buf, len);
74                         if (newbuf == NULL)
75                                 return NULL;
76                         pr->buf = newbuf;
77                         pr->buf_max = len;
78                 }
79                 if (blkid_llseek(pr->fd, off, SEEK_SET) < 0)
80                         return NULL;
81                 ret_read = read(pr->fd, pr->buf, len);
82                 if (ret_read != (ssize_t) len)
83                         return NULL;
84                 return pr->buf;
85         }
86 }
87
88
89 /*
90  * This is a special case code to check for an MDRAID device.  We do
91  * this special since it requires checking for a superblock at the end
92  * of the device.
93  */
94 static int check_mdraid(int fd, unsigned char *ret_uuid)
95 {
96         struct mdp_superblock_s *md;
97         blkid_loff_t            offset;
98         char                    buf[4096];
99
100         if (fd < 0)
101                 return -BLKID_ERR_PARAM;
102
103         offset = (blkid_get_dev_size(fd) & ~((blkid_loff_t)65535)) - 65536;
104
105         if (blkid_llseek(fd, offset, 0) < 0 ||
106             read(fd, buf, 4096) != 4096)
107                 return -BLKID_ERR_IO;
108
109         /* Check for magic number */
110         if (memcmp("\251+N\374", buf, 4) && memcmp("\374N+\251", buf, 4))
111                 return -BLKID_ERR_PARAM;
112
113         if (!ret_uuid)
114                 return 0;
115         *ret_uuid = 0;
116
117         /* The MD UUID is not contiguous in the superblock, make it so */
118         md = (struct mdp_superblock_s *)buf;
119         if (md->set_uuid0 || md->set_uuid1 || md->set_uuid2 || md->set_uuid3) {
120                 memcpy(ret_uuid, &md->set_uuid0, 4);
121                 memcpy(ret_uuid + 4, &md->set_uuid1, 12);
122         }
123         return 0;
124 }
125
126 static void set_uuid(blkid_dev dev, uuid_t uuid, const char *tag)
127 {
128         char    str[37];
129
130         if (!uuid_is_null(uuid)) {
131                 uuid_unparse(uuid, str);
132                 blkid_set_tag(dev, tag ? tag : "UUID", str, sizeof(str));
133         }
134 }
135
136 static void get_ext2_info(blkid_dev dev, struct blkid_magic *id,
137                           unsigned char *buf)
138 {
139         struct ext2_super_block *es = (struct ext2_super_block *) buf;
140         const char *label = 0;
141
142         DBG(DEBUG_PROBE, printf("ext2_sb.compat = %08X:%08X:%08X\n",
143                    blkid_le32(es->s_feature_compat),
144                    blkid_le32(es->s_feature_incompat),
145                    blkid_le32(es->s_feature_ro_compat)));
146
147         if (strlen(es->s_volume_name))
148                 label = es->s_volume_name;
149         blkid_set_tag(dev, "LABEL", label, sizeof(es->s_volume_name));
150
151         set_uuid(dev, es->s_uuid, 0);
152
153         if ((es->s_feature_compat & EXT3_FEATURE_COMPAT_HAS_JOURNAL) &&
154             !uuid_is_null(es->s_journal_uuid))
155                 set_uuid(dev, es->s_journal_uuid, "EXT_JOURNAL");
156
157         if (strcmp(id->bim_type, "ext2") &&
158             ((blkid_le32(es->s_feature_incompat) &
159               EXT2_FEATURE_INCOMPAT_UNSUPPORTED) == 0))
160                 blkid_set_tag(dev, "SEC_TYPE", "ext2", sizeof("ext2"));
161 }
162
163 /*
164  * Check to see if a filesystem is in /proc/filesystems.
165  * Returns 1 if found, 0 if not
166  */
167 static int fs_proc_check(const char *fs_name)
168 {
169         FILE    *f;
170         char    buf[80], *cp, *t;
171
172         f = fopen("/proc/filesystems", "r");
173         if (!f)
174                 return (0);
175         while (!feof(f)) {
176                 if (!fgets(buf, sizeof(buf), f))
177                         break;
178                 cp = buf;
179                 if (!isspace(*cp)) {
180                         while (*cp && !isspace(*cp))
181                                 cp++;
182                 }
183                 while (*cp && isspace(*cp))
184                         cp++;
185                 if ((t = strchr(cp, '\n')) != NULL)
186                         *t = 0;
187                 if ((t = strchr(cp, '\t')) != NULL)
188                         *t = 0;
189                 if ((t = strchr(cp, ' ')) != NULL)
190                         *t = 0;
191                 if (!strcmp(fs_name, cp)) {
192                         fclose(f);
193                         return (1);
194                 }
195         }
196         fclose(f);
197         return (0);
198 }
199
200 /*
201  * Check to see if a filesystem is available as a module
202  * Returns 1 if found, 0 if not
203  */
204 static int check_for_modules(const char *fs_name)
205 {
206         struct utsname  uts;
207         FILE            *f;
208         char            buf[1024], *cp, *t;
209         int             i;
210
211         if (uname(&uts))
212                 return (0);
213         snprintf(buf, sizeof(buf), "/lib/modules/%s/modules.dep", uts.release);
214
215         f = fopen(buf, "r");
216         if (!f)
217                 return (0);
218         while (!feof(f)) {
219                 if (!fgets(buf, sizeof(buf), f))
220                         break;
221                 if ((cp = strchr(buf, ':')) != NULL)
222                         *cp = 0;
223                 else
224                         continue;
225                 if ((cp = strrchr(buf, '/')) != NULL)
226                         cp++;
227                 i = strlen(cp);
228                 if (i > 3) {
229                         t = cp + i - 3;
230                         if (!strcmp(t, ".ko"))
231                                 *t = 0;
232                 }
233                 if (!strcmp(cp, fs_name))
234                         return (1);
235         }
236         fclose(f);
237         return (0);
238 }
239
240 static int system_supports_ext4(void)
241 {
242         static time_t   last_check = 0;
243         static int      ret = -1;
244         time_t          now = time(0);
245
246         if (ret != -1 || (last_check - now) < 5)
247                 return ret;
248         last_check = now;
249         ret = (fs_proc_check("ext4") || check_for_modules("ext4"));
250         return ret;
251 }
252
253 static int system_supports_ext4dev(void)
254 {
255         static time_t   last_check = 0;
256         static int      ret = -1;
257         time_t          now = time(0);
258
259         if (ret != -1 || (last_check - now) < 5)
260                 return ret;
261         last_check = now;
262         ret = (fs_proc_check("ext4dev") || check_for_modules("ext4dev"));
263         return ret;
264 }
265
266 static int probe_ext4dev(struct blkid_probe *probe,
267                          struct blkid_magic *id,
268                          unsigned char *buf)
269 {
270         struct ext2_super_block *es;
271         es = (struct ext2_super_block *)buf;
272
273         /* Distinguish from jbd */
274         if (blkid_le32(es->s_feature_incompat) &
275             EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)
276                 return -BLKID_ERR_PARAM;
277
278         /* ext4dev requires a journal */
279         if (!(blkid_le32(es->s_feature_compat) &
280               EXT3_FEATURE_COMPAT_HAS_JOURNAL))
281                 return -BLKID_ERR_PARAM;
282
283         /*
284          * If the filesystem is marked as OK for use by in-development
285          * filesystem code, but ext4dev is not supported, and ext4 is,
286          * then don't call ourselves ext4dev, since we should be
287          * detected as ext4 in that case.
288          *
289          * If the filesystem is marked as in use by production
290          * filesystem, then it can only be used by ext4 and NOT by
291          * ext4dev, so always disclaim we are ext4dev in that case.
292          */
293         if (blkid_le32(es->s_flags) & EXT2_FLAGS_TEST_FILESYS) {
294                 if (!system_supports_ext4dev() && system_supports_ext4())
295                         return -BLKID_ERR_PARAM;
296         } else
297                 return -BLKID_ERR_PARAM;
298
299         get_ext2_info(probe->dev, id, buf);
300         return 0;
301 }
302
303 static int probe_ext4(struct blkid_probe *probe, struct blkid_magic *id,
304                       unsigned char *buf)
305 {
306         struct ext2_super_block *es;
307         es = (struct ext2_super_block *)buf;
308
309         /* Distinguish from jbd */
310         if (blkid_le32(es->s_feature_incompat) &
311             EXT3_FEATURE_INCOMPAT_JOURNAL_DEV)
312                 return -BLKID_ERR_PARAM;
313
314         /* ext4 requires journal */
315         if (!(blkid_le32(es->s_feature_compat) &
316               EXT3_FEATURE_COMPAT_HAS_JOURNAL))
317                 return -BLKID_ERR_PARAM;
318
319         /* Ext4 has at least one feature which ext3 doesn't understand */
320         if (!(blkid_le32(es->s_feature_ro_compat) &
321               EXT3_FEATURE_RO_COMPAT_UNSUPPORTED) &&
322             !(blkid_le32(es->s_feature_incompat) &
323               EXT3_FEATURE_INCOMPAT_UNSUPPORTED))
324                 return -BLKID_ERR_PARAM;
325
326         /*
327          * If the filesystem is a OK for use by in-development
328          * filesystem code, and ext4dev is supported or ext4 is not
329          * supported, then don't call ourselves ext4, so we can redo
330          * the detection and mark the filesystem as ext4dev.
331          *
332          * If the filesystem is marked as in use by production
333          * filesystem, then it can only be used by ext4 and NOT by
334          * ext4dev.
335          */
336         if (blkid_le32(es->s_flags) & EXT2_FLAGS_TEST_FILESYS) {
337                 if (system_supports_ext4dev() || !system_supports_ext4())
338                         return -BLKID_ERR_PARAM;
339         }
340         get_ext2_info(probe->dev, id, buf);
341         return 0;
342 }
343
344 static int probe_ext3(struct blkid_probe *probe, struct blkid_magic *id,
345                       unsigned char *buf)
346 {
347         struct ext2_super_block *es;
348         es = (struct ext2_super_block *)buf;
349
350         /* Distinguish from ext4dev */
351         if (blkid_le32(es->s_flags) & EXT2_FLAGS_TEST_FILESYS)
352                 return -BLKID_ERR_PARAM;
353
354         /* ext3 requires journal */
355         if (!(blkid_le32(es->s_feature_compat) &
356               EXT3_FEATURE_COMPAT_HAS_JOURNAL))
357                 return -BLKID_ERR_PARAM;
358
359         /* Any features which ext3 doesn't understand */
360         if ((blkid_le32(es->s_feature_ro_compat) &
361              EXT3_FEATURE_RO_COMPAT_UNSUPPORTED) ||
362             (blkid_le32(es->s_feature_incompat) &
363              EXT3_FEATURE_INCOMPAT_UNSUPPORTED))
364                 return -BLKID_ERR_PARAM;
365
366         get_ext2_info(probe->dev, id, buf);
367         return 0;
368 }
369
370 static int probe_ext2(struct blkid_probe *probe, struct blkid_magic *id,
371                       unsigned char *buf)
372 {
373         struct ext2_super_block *es;
374
375         es = (struct ext2_super_block *)buf;
376
377         /* Distinguish between ext3 and ext2 */
378         if ((blkid_le32(es->s_feature_compat) &
379               EXT3_FEATURE_COMPAT_HAS_JOURNAL))
380                 return -BLKID_ERR_PARAM;
381
382         /* Any features which ext2 doesn't understand */
383         if ((blkid_le32(es->s_feature_ro_compat) &
384              EXT2_FEATURE_RO_COMPAT_UNSUPPORTED) ||
385             (blkid_le32(es->s_feature_incompat) &
386              EXT2_FEATURE_INCOMPAT_UNSUPPORTED))
387                 return -BLKID_ERR_PARAM;
388
389         get_ext2_info(probe->dev, id, buf);
390         return 0;
391 }
392
393 static int probe_jbd(struct blkid_probe *probe, struct blkid_magic *id,
394                      unsigned char *buf)
395 {
396         struct ext2_super_block *es = (struct ext2_super_block *) buf;
397
398         if (!(blkid_le32(es->s_feature_incompat) &
399               EXT3_FEATURE_INCOMPAT_JOURNAL_DEV))
400                 return -BLKID_ERR_PARAM;
401
402         get_ext2_info(probe->dev, id, buf);
403
404         return 0;
405 }
406
407 #define FAT_ATTR_VOLUME_ID              0x08
408 #define FAT_ATTR_DIR                    0x10
409 #define FAT_ATTR_LONG_NAME              0x0f
410 #define FAT_ATTR_MASK                   0x3f
411 #define FAT_ENTRY_FREE                  0xe5
412
413 static const char *no_name = "NO NAME    ";
414
415 static unsigned char *search_fat_label(struct vfat_dir_entry *dir, int count)
416 {
417         int i;
418
419         for (i = 0; i < count; i++) {
420                 if (dir[i].name[0] == 0x00)
421                         break;
422
423                 if ((dir[i].name[0] == FAT_ENTRY_FREE) ||
424                     (dir[i].cluster_high != 0 || dir[i].cluster_low != 0) ||
425                     ((dir[i].attr & FAT_ATTR_MASK) == FAT_ATTR_LONG_NAME))
426                         continue;
427
428                 if ((dir[i].attr & (FAT_ATTR_VOLUME_ID | FAT_ATTR_DIR)) ==
429                     FAT_ATTR_VOLUME_ID) {
430                         return dir[i].name;
431                 }
432         }
433         return 0;
434 }
435
436 /* FAT label extraction from the root directory taken from Kay
437  * Sievers's volume_id library */
438 static int probe_fat(struct blkid_probe *probe,
439                       struct blkid_magic *id __BLKID_ATTR((unused)),
440                       unsigned char *buf)
441 {
442         struct vfat_super_block *vs = (struct vfat_super_block *) buf;
443         struct msdos_super_block *ms = (struct msdos_super_block *) buf;
444         struct vfat_dir_entry *dir;
445         char serno[10];
446         const unsigned char *label = 0, *vol_label = 0, *tmp;
447         unsigned char   *vol_serno;
448         int label_len = 0, maxloop = 100;
449         __u16 sector_size, dir_entries, reserved;
450         __u32 sect_count, fat_size, dir_size, cluster_count, fat_length;
451         __u32 buf_size, start_data_sect, next, root_start, root_dir_entries;
452
453         /* sector size check */
454         tmp = (unsigned char *)&ms->ms_sector_size;
455         sector_size = tmp[0] + (tmp[1] << 8);
456         if (sector_size != 0x200 && sector_size != 0x400 &&
457             sector_size != 0x800 && sector_size != 0x1000)
458                 return 1;
459
460         tmp = (unsigned char *)&ms->ms_dir_entries;
461         dir_entries = tmp[0] + (tmp[1] << 8);
462         reserved =  blkid_le16(ms->ms_reserved);
463         tmp = (unsigned char *)&ms->ms_sectors;
464         sect_count = tmp[0] + (tmp[1] << 8);
465         if (sect_count == 0)
466                 sect_count = blkid_le32(ms->ms_total_sect);
467
468         fat_length = blkid_le16(ms->ms_fat_length);
469         if (fat_length == 0)
470                 fat_length = blkid_le32(vs->vs_fat32_length);
471
472         fat_size = fat_length * ms->ms_fats;
473         dir_size = ((dir_entries * sizeof(struct vfat_dir_entry)) +
474                         (sector_size-1)) / sector_size;
475
476         cluster_count = sect_count - (reserved + fat_size + dir_size);
477         if (ms->ms_cluster_size == 0)
478                 return 1;
479         cluster_count /= ms->ms_cluster_size;
480
481         if (cluster_count > FAT32_MAX)
482                 return 1;
483
484         if (ms->ms_fat_length) {
485                 /* the label may be an attribute in the root directory */
486                 root_start = (reserved + fat_size) * sector_size;
487                 root_dir_entries = vs->vs_dir_entries[0] +
488                         (vs->vs_dir_entries[1] << 8);
489
490                 buf_size = root_dir_entries * sizeof(struct vfat_dir_entry);
491                 dir = (struct vfat_dir_entry *) get_buffer(probe, root_start,
492                                                            buf_size);
493                 if (dir)
494                         vol_label = search_fat_label(dir, root_dir_entries);
495
496                 if (!vol_label || !memcmp(vol_label, no_name, 11))
497                         vol_label = ms->ms_label;
498                 vol_serno = ms->ms_serno;
499
500                 blkid_set_tag(probe->dev, "SEC_TYPE", "msdos",
501                               sizeof("msdos"));
502         } else {
503                 /* Search the FAT32 root dir for the label attribute */
504                 buf_size = vs->vs_cluster_size * sector_size;
505                 start_data_sect = reserved + fat_size;
506
507                 next = blkid_le32(vs->vs_root_cluster);
508                 while (next && --maxloop) {
509                         __u32 next_sect_off;
510                         __u64 next_off, fat_entry_off;
511                         int count;
512
513                         next_sect_off = (next - 2) * vs->vs_cluster_size;
514                         next_off = (start_data_sect + next_sect_off) *
515                                 sector_size;
516
517                         dir = (struct vfat_dir_entry *)
518                                 get_buffer(probe, next_off, buf_size);
519                         if (dir == NULL)
520                                 break;
521
522                         count = buf_size / sizeof(struct vfat_dir_entry);
523
524                         vol_label = search_fat_label(dir, count);
525                         if (vol_label)
526                                 break;
527
528                         /* get FAT entry */
529                         fat_entry_off = (reserved * sector_size) +
530                                 (next * sizeof(__u32));
531                         buf = get_buffer(probe, fat_entry_off, buf_size);
532                         if (buf == NULL)
533                                 break;
534
535                         /* set next cluster */
536                         next = blkid_le32(*((__u32 *) buf) & 0x0fffffff);
537                 }
538
539                 if (!vol_label || !memcmp(vol_label, no_name, 11))
540                         vol_label = vs->vs_label;
541                 vol_serno = vs->vs_serno;
542         }
543
544         if (vol_label && memcmp(vol_label, no_name, 11)) {
545                 if ((label_len = figure_label_len(vol_label, 11)))
546                         label = vol_label;
547         }
548
549         /* We can't just print them as %04X, because they are unaligned */
550         sprintf(serno, "%02X%02X-%02X%02X", vol_serno[3], vol_serno[2],
551                 vol_serno[1], vol_serno[0]);
552
553         blkid_set_tag(probe->dev, "LABEL", (const char *) label, label_len);
554         blkid_set_tag(probe->dev, "UUID", serno, sizeof(serno)-1);
555
556         return 0;
557 }
558
559 /*
560  * The FAT filesystem could be without a magic string in superblock
561  * (e.g. old floppies).  This heuristic for FAT detection is inspired
562  * by http://vrfy.org/projects/volume_id/ and Linux kernel.
563  * [7-Jul-2005, Karel Zak <kzak@redhat.com>]
564  */
565 static int probe_fat_nomagic(struct blkid_probe *probe,
566                              struct blkid_magic *id __BLKID_ATTR((unused)),
567                              unsigned char *buf)
568 {
569         struct msdos_super_block *ms;
570
571         ms = (struct msdos_super_block *)buf;
572
573         /* heads check */
574         if (ms->ms_heads == 0)
575                 return 1;
576
577         /* cluster size check*/
578         if (ms->ms_cluster_size == 0 ||
579             (ms->ms_cluster_size & (ms->ms_cluster_size-1)))
580                 return 1;
581
582         /* media check */
583         if (ms->ms_media < 0xf8 && ms->ms_media != 0xf0)
584                 return 1;
585
586         /* fat counts(Linux kernel expects at least 1 FAT table) */
587         if (!ms->ms_fats)
588                 return 1;
589
590         /*
591          * OS/2 and apparently DFSee will place a FAT12/16-like
592          * pseudo-superblock in the first 512 bytes of non-FAT
593          * filesystems --- at least JFS and HPFS, and possibly others.
594          * So we explicitly check for those filesystems at the
595          * FAT12/16 filesystem magic field identifier, and if they are
596          * present, we rule this out as a FAT filesystem, despite the
597          * FAT-like pseudo-header.
598          */
599         if ((memcmp(ms->ms_magic, "JFS     ", 8) == 0) ||
600             (memcmp(ms->ms_magic, "HPFS    ", 8) == 0))
601                 return 1;
602
603         return probe_fat(probe, id, buf);
604 }
605
606 static int probe_ntfs(struct blkid_probe *probe,
607                       struct blkid_magic *id __BLKID_ATTR((unused)),
608                       unsigned char *buf)
609 {
610         struct ntfs_super_block *ns;
611         struct master_file_table_record *mft;
612         struct file_attribute *attr;
613         char            uuid_str[17], label_str[129], *cp;
614         int             bytes_per_sector, sectors_per_cluster;
615         int             mft_record_size, attr_off, attr_len;
616         unsigned int    i, attr_type, val_len;
617         int             val_off;
618         __u64           nr_clusters;
619         blkid_loff_t off;
620         unsigned char *buf_mft, *val;
621
622         ns = (struct ntfs_super_block *) buf;
623
624         bytes_per_sector = ns->bios_parameter_block[0] +
625                 (ns->bios_parameter_block[1]  << 8);
626         sectors_per_cluster = ns->bios_parameter_block[2];
627
628         if ((bytes_per_sector < 512) || (sectors_per_cluster == 0))
629                 return 1;
630
631         if (ns->cluster_per_mft_record < 0)
632                 mft_record_size = 1 << (0-ns->cluster_per_mft_record);
633         else
634                 mft_record_size = ns->cluster_per_mft_record *
635                         sectors_per_cluster * bytes_per_sector;
636         nr_clusters = blkid_le64(ns->number_of_sectors) / sectors_per_cluster;
637
638         if ((blkid_le64(ns->mft_cluster_location) > nr_clusters) ||
639             (blkid_le64(ns->mft_mirror_cluster_location) > nr_clusters))
640                 return 1;
641
642         off = blkid_le64(ns->mft_mirror_cluster_location) *
643                 bytes_per_sector * sectors_per_cluster;
644
645         buf_mft = get_buffer(probe, off, mft_record_size);
646         if (!buf_mft)
647                 return 1;
648
649         if (memcmp(buf_mft, "FILE", 4))
650                 return 1;
651
652         off = blkid_le64(ns->mft_cluster_location) * bytes_per_sector *
653                 sectors_per_cluster;
654
655         buf_mft = get_buffer(probe, off, mft_record_size);
656         if (!buf_mft)
657                 return 1;
658
659         if (memcmp(buf_mft, "FILE", 4))
660                 return 1;
661
662         off += MFT_RECORD_VOLUME * mft_record_size;
663
664         buf_mft = get_buffer(probe, off, mft_record_size);
665         if (!buf_mft)
666                 return 1;
667
668         if (memcmp(buf_mft, "FILE", 4))
669                 return 1;
670
671         mft = (struct master_file_table_record *) buf_mft;
672
673         attr_off = blkid_le16(mft->attrs_offset);
674         label_str[0] = 0;
675
676         while (1) {
677                 attr = (struct file_attribute *) (buf_mft + attr_off);
678                 attr_len = blkid_le16(attr->len);
679                 attr_type = blkid_le32(attr->type);
680                 val_off = blkid_le16(attr->value_offset);
681                 val_len = blkid_le32(attr->value_len);
682
683                 attr_off += attr_len;
684
685                 if ((attr_off > mft_record_size) ||
686                     (attr_len == 0))
687                         break;
688
689                 if (attr_type == MFT_RECORD_ATTR_END)
690                         break;
691
692                 if (attr_type == MFT_RECORD_ATTR_VOLUME_NAME) {
693                         if (val_len > sizeof(label_str))
694                                 val_len = sizeof(label_str)-1;
695
696                         for (i=0, cp=label_str; i < val_len; i+=2,cp++) {
697                                 val = ((__u8 *) attr) + val_off + i;
698                                 *cp = val[0];
699                                 if (val[1])
700                                         *cp = '?';
701                         }
702                         *cp = 0;
703                 }
704         }
705
706         sprintf(uuid_str, "%016llX", blkid_le64(ns->volume_serial));
707         blkid_set_tag(probe->dev, "UUID", uuid_str, 0);
708         if (label_str[0])
709                 blkid_set_tag(probe->dev, "LABEL", label_str, 0);
710         return 0;
711 }
712
713
714 static int probe_xfs(struct blkid_probe *probe,
715                      struct blkid_magic *id __BLKID_ATTR((unused)),
716                      unsigned char *buf)
717 {
718         struct xfs_super_block *xs;
719         const char *label = 0;
720
721         xs = (struct xfs_super_block *)buf;
722
723         if (strlen(xs->xs_fname))
724                 label = xs->xs_fname;
725         blkid_set_tag(probe->dev, "LABEL", label, sizeof(xs->xs_fname));
726         set_uuid(probe->dev, xs->xs_uuid, 0);
727         return 0;
728 }
729
730 static int probe_reiserfs(struct blkid_probe *probe,
731                           struct blkid_magic *id, unsigned char *buf)
732 {
733         struct reiserfs_super_block *rs = (struct reiserfs_super_block *) buf;
734         unsigned int blocksize;
735         const char *label = 0;
736
737         blocksize = blkid_le16(rs->rs_blocksize);
738
739         /* The blocksize must be at least 1k */
740         if ((blocksize >> 10) == 0)
741                 return -BLKID_ERR_PARAM;
742
743         /* If the superblock is inside the journal, we have the wrong one */
744         if (id->bim_kboff/(blocksize>>10) > blkid_le32(rs->rs_journal_block))
745                 return -BLKID_ERR_BIG;
746
747         /* LABEL/UUID are only valid for later versions of Reiserfs v3.6. */
748         if (id->bim_magic[6] == '2' || id->bim_magic[6] == '3') {
749                 if (strlen(rs->rs_label))
750                         label = rs->rs_label;
751                 set_uuid(probe->dev, rs->rs_uuid, 0);
752         }
753         blkid_set_tag(probe->dev, "LABEL", label, sizeof(rs->rs_label));
754
755         return 0;
756 }
757
758 static int probe_reiserfs4(struct blkid_probe *probe,
759                            struct blkid_magic *id __BLKID_ATTR((unused)),
760                            unsigned char *buf)
761 {
762         struct reiser4_super_block *rs4 = (struct reiser4_super_block *) buf;
763         const unsigned char *label = 0;
764
765         if (strlen((char *) rs4->rs4_label))
766                 label = rs4->rs4_label;
767         set_uuid(probe->dev, rs4->rs4_uuid, 0);
768         blkid_set_tag(probe->dev, "LABEL", (const char *) label,
769                       sizeof(rs4->rs4_label));
770
771         return 0;
772 }
773
774 static int probe_jfs(struct blkid_probe *probe,
775                      struct blkid_magic *id __BLKID_ATTR((unused)),
776                      unsigned char *buf)
777 {
778         struct jfs_super_block *js;
779         const char *label = 0;
780
781         js = (struct jfs_super_block *)buf;
782
783         if (blkid_le32(js->js_bsize) != (1 << blkid_le16(js->js_l2bsize)))
784                 return 1;
785
786         if (blkid_le32(js->js_pbsize) != (1 << blkid_le16(js->js_l2pbsize)))
787                 return 1;
788
789         if ((blkid_le16(js->js_l2bsize) - blkid_le16(js->js_l2pbsize)) !=
790             blkid_le16(js->js_l2bfactor))
791                 return 1;
792
793         if (strlen((char *) js->js_label))
794                 label = (char *) js->js_label;
795         blkid_set_tag(probe->dev, "LABEL", label, sizeof(js->js_label));
796         set_uuid(probe->dev, js->js_uuid, 0);
797         return 0;
798 }
799
800 static int probe_zfs(struct blkid_probe *probe, struct blkid_magic *id,
801                      unsigned char *buf)
802 {
803 #if 0
804         char *vdev_label;
805         const char *pool_name = 0;
806
807         /* read nvpair data for pool name, pool GUID (complex) */
808         blkid_set_tag(probe->dev, "LABEL", pool_name, sizeof(pool_name));
809         set_uuid(probe->dev, pool_guid, 0);
810 #endif
811         return 0;
812 }
813
814 static int probe_luks(struct blkid_probe *probe,
815                        struct blkid_magic *id __BLKID_ATTR((unused)),
816                        unsigned char *buf)
817 {
818         char uuid[40];
819
820         /* 168 is the offset to the 40 character uuid:
821          * http://luks.endorphin.org/LUKS-on-disk-format.pdf */
822         strncpy(uuid, (char *) buf+168, 40);
823         blkid_set_tag(probe->dev, "UUID", uuid, sizeof(uuid));
824         return 0;
825 }
826
827 static int probe_romfs(struct blkid_probe *probe,
828                        struct blkid_magic *id __BLKID_ATTR((unused)),
829                        unsigned char *buf)
830 {
831         struct romfs_super_block *ros;
832         const char *label = 0;
833
834         ros = (struct romfs_super_block *)buf;
835
836         if (strlen((char *) ros->ros_volume))
837                 label = (char *) ros->ros_volume;
838         blkid_set_tag(probe->dev, "LABEL", label, 0);
839         return 0;
840 }
841
842 static int probe_cramfs(struct blkid_probe *probe,
843                         struct blkid_magic *id __BLKID_ATTR((unused)),
844                         unsigned char *buf)
845 {
846         struct cramfs_super_block *csb;
847         const char *label = 0;
848
849         csb = (struct cramfs_super_block *)buf;
850
851         if (strlen((char *) csb->name))
852                 label = (char *) csb->name;
853         blkid_set_tag(probe->dev, "LABEL", label, 0);
854         return 0;
855 }
856
857 static int probe_swap0(struct blkid_probe *probe,
858                        struct blkid_magic *id __BLKID_ATTR((unused)),
859                        unsigned char *buf __BLKID_ATTR((unused)))
860 {
861         blkid_set_tag(probe->dev, "UUID", 0, 0);
862         blkid_set_tag(probe->dev, "LABEL", 0, 0);
863         return 0;
864 }
865
866 static int probe_swap1(struct blkid_probe *probe,
867                        struct blkid_magic *id,
868                        unsigned char *buf __BLKID_ATTR((unused)))
869 {
870         struct swap_id_block *sws;
871
872         probe_swap0(probe, id, buf);
873         /*
874          * Version 1 swap headers are always located at offset of 1024
875          * bytes, although the swap signature itself is located at the
876          * end of the page (which may vary depending on hardware
877          * pagesize).
878          */
879         sws = (struct swap_id_block *) get_buffer(probe, 1024, 1024);
880         if (!sws)
881                 return 1;
882
883         /* check for wrong version or zeroed pagecount, for sanity */
884         if (!memcmp(id->bim_magic, "SWAPSPACE2", id->bim_len) &&
885                         (sws->sws_version != 1 || sws->sws_lastpage == 0))
886                 return 1;
887
888         /* arbitrary sanity check.. is there any garbage down there? */
889         if (sws->sws_pad[32] == 0 && sws->sws_pad[33] == 0)  {
890                 if (sws->sws_volume[0])
891                         blkid_set_tag(probe->dev, "LABEL", sws->sws_volume,
892                                       sizeof(sws->sws_volume));
893                 if (sws->sws_uuid[0])
894                         set_uuid(probe->dev, sws->sws_uuid, 0);
895         }
896         return 0;
897 }
898
899 static int probe_iso9660(struct blkid_probe *probe,
900                          struct blkid_magic *id __BLKID_ATTR((unused)),
901                          unsigned char *buf)
902 {
903         struct iso_volume_descriptor *iso;
904         const unsigned char *label;
905
906         iso = (struct iso_volume_descriptor *) buf;
907         label = iso->volume_id;
908
909         blkid_set_tag(probe->dev, "LABEL", (const char *) label,
910                       figure_label_len(label, 32));
911         return 0;
912 }
913
914
915 static const char
916 *udf_magic[] = { "BEA01", "BOOT2", "CD001", "CDW02", "NSR02",
917                  "NSR03", "TEA01", 0 };
918
919 static int probe_udf(struct blkid_probe *probe,
920                      struct blkid_magic *id __BLKID_ATTR((unused)),
921                      unsigned char *buf __BLKID_ATTR((unused)))
922 {
923         int j, bs;
924         struct iso_volume_descriptor *isosb;
925         const char ** m;
926
927         /* determine the block size by scanning in 2K increments
928            (block sizes larger than 2K will be null padded) */
929         for (bs = 1; bs < 16; bs++) {
930                 isosb = (struct iso_volume_descriptor *)
931                         get_buffer(probe, bs*2048+32768, sizeof(isosb));
932                 if (!isosb)
933                         return 1;
934                 if (isosb->vd_id[0])
935                         break;
936         }
937
938         /* Scan up to another 64 blocks looking for additional VSD's */
939         for (j = 1; j < 64; j++) {
940                 if (j > 1) {
941                         isosb = (struct iso_volume_descriptor *)
942                                 get_buffer(probe, j*bs*2048+32768,
943                                            sizeof(isosb));
944                         if (!isosb)
945                                 return 1;
946                 }
947                 /* If we find NSR0x then call it udf:
948                    NSR01 for UDF 1.00
949                    NSR02 for UDF 1.50
950                    NSR03 for UDF 2.00 */
951                 if (!memcmp(isosb->vd_id, "NSR0", 4))
952                         return probe_iso9660(probe, id, buf);
953                 for (m = udf_magic; *m; m++)
954                         if (!memcmp(*m, isosb->vd_id, 5))
955                                 break;
956                 if (*m == 0)
957                         return 1;
958         }
959         return 1;
960 }
961
962 static int probe_ocfs(struct blkid_probe *probe,
963                       struct blkid_magic *id __BLKID_ATTR((unused)),
964                       unsigned char *buf)
965 {
966         struct ocfs_volume_header ovh;
967         struct ocfs_volume_label ovl;
968         __u32 major;
969
970         memcpy(&ovh, buf, sizeof(ovh));
971         memcpy(&ovl, buf+512, sizeof(ovl));
972
973         major = ocfsmajor(ovh);
974         if (major == 1)
975                 blkid_set_tag(probe->dev,"SEC_TYPE","ocfs1",sizeof("ocfs1"));
976         else if (major >= 9)
977                 blkid_set_tag(probe->dev,"SEC_TYPE","ntocfs",sizeof("ntocfs"));
978
979         blkid_set_tag(probe->dev, "LABEL", ovl.label, ocfslabellen(ovl));
980         blkid_set_tag(probe->dev, "MOUNT", ovh.mount, ocfsmountlen(ovh));
981         set_uuid(probe->dev, ovl.vol_id, 0);
982         return 0;
983 }
984
985 static int probe_ocfs2(struct blkid_probe *probe,
986                        struct blkid_magic *id __BLKID_ATTR((unused)),
987                        unsigned char *buf)
988 {
989         struct ocfs2_super_block *osb;
990
991         osb = (struct ocfs2_super_block *)buf;
992
993         blkid_set_tag(probe->dev, "LABEL", osb->s_label, sizeof(osb->s_label));
994         set_uuid(probe->dev, osb->s_uuid, 0);
995         return 0;
996 }
997
998 static int probe_oracleasm(struct blkid_probe *probe,
999                            struct blkid_magic *id __BLKID_ATTR((unused)),
1000                            unsigned char *buf)
1001 {
1002         struct oracle_asm_disk_label *dl;
1003
1004         dl = (struct oracle_asm_disk_label *)buf;
1005
1006         blkid_set_tag(probe->dev, "LABEL", dl->dl_id, sizeof(dl->dl_id));
1007         return 0;
1008 }
1009
1010 static int probe_gfs(struct blkid_probe *probe,
1011                      struct blkid_magic *id __BLKID_ATTR((unused)),
1012                      unsigned char *buf)
1013 {
1014         struct gfs2_sb *sbd;
1015         const char *label = 0;
1016
1017         sbd = (struct gfs2_sb *)buf;
1018
1019         if (blkid_be32(sbd->sb_fs_format) == GFS_FORMAT_FS &&
1020             blkid_be32(sbd->sb_multihost_format) == GFS_FORMAT_MULTI)
1021         {
1022                 blkid_set_tag(probe->dev, "UUID", 0, 0);
1023
1024                 if (strlen(sbd->sb_locktable))
1025                         label = sbd->sb_locktable;
1026                 blkid_set_tag(probe->dev, "LABEL", label, sizeof(sbd->sb_locktable));
1027                 return 0;
1028         }
1029         return 1;
1030 }
1031
1032 static int probe_gfs2(struct blkid_probe *probe,
1033                      struct blkid_magic *id __BLKID_ATTR((unused)),
1034                      unsigned char *buf)
1035 {
1036         struct gfs2_sb *sbd;
1037         const char *label = 0;
1038
1039         sbd = (struct gfs2_sb *)buf;
1040
1041         if (blkid_be32(sbd->sb_fs_format) == GFS2_FORMAT_FS &&
1042             blkid_be32(sbd->sb_multihost_format) == GFS2_FORMAT_MULTI)
1043         {
1044                 blkid_set_tag(probe->dev, "UUID", 0, 0);
1045
1046                 if (strlen(sbd->sb_locktable))
1047                         label = sbd->sb_locktable;
1048                 blkid_set_tag(probe->dev, "LABEL", label, sizeof(sbd->sb_locktable));
1049                 return 0;
1050         }
1051         return 1;
1052 }
1053
1054 static void unicode_16be_to_utf8(unsigned char *str, int out_len,
1055                                  const unsigned char *buf, int in_len)
1056 {
1057         int i, j;
1058         unsigned int c;
1059
1060         for (i = j = 0; i + 2 <= in_len; i += 2) {
1061                 c = (buf[i] << 8) | buf[i+1];
1062                 if (c == 0) {
1063                         str[j] = '\0';
1064                         break;
1065                 } else if (c < 0x80) {
1066                         if (j+1 >= out_len)
1067                                 break;
1068                         str[j++] = (unsigned char) c;
1069                 } else if (c < 0x800) {
1070                         if (j+2 >= out_len)
1071                                 break;
1072                         str[j++] = (unsigned char) (0xc0 | (c >> 6));
1073                         str[j++] = (unsigned char) (0x80 | (c & 0x3f));
1074                 } else {
1075                         if (j+3 >= out_len)
1076                                 break;
1077                         str[j++] = (unsigned char) (0xe0 | (c >> 12));
1078                         str[j++] = (unsigned char) (0x80 | ((c >> 6) & 0x3f));
1079                         str[j++] = (unsigned char) (0x80 | (c & 0x3f));
1080                 }
1081         }
1082         str[j] = '\0';
1083 }
1084
1085 static int probe_hfs(struct blkid_probe *probe __BLKID_ATTR((unused)),
1086                          struct blkid_magic *id __BLKID_ATTR((unused)),
1087                          unsigned char *buf)
1088 {
1089         struct hfs_mdb *hfs = (struct hfs_mdb *) buf;
1090         char    uuid_str[17];
1091         __u64   uuid;
1092
1093         if ((memcmp(hfs->embed_sig, "H+", 2) == 0) ||
1094             (memcmp(hfs->embed_sig, "HX", 2) == 0))
1095                 return 1;       /* Not hfs, but an embedded HFS+ */
1096
1097         uuid = blkid_le64(*((unsigned long long *) hfs->finder_info.id));
1098         if (uuid) {
1099                 sprintf(uuid_str, "%016llX", uuid);
1100                 blkid_set_tag(probe->dev, "UUID", uuid_str, 0);
1101         }
1102         blkid_set_tag(probe->dev, "LABEL", hfs->label, hfs->label_len);
1103         return 0;
1104 }
1105
1106
1107 static int probe_hfsplus(struct blkid_probe *probe,
1108                          struct blkid_magic *id,
1109                          unsigned char *buf)
1110 {
1111         struct hfsplus_extent extents[HFSPLUS_EXTENT_COUNT];
1112         struct hfsplus_bnode_descriptor *descr;
1113         struct hfsplus_bheader_record *bnode;
1114         struct hfsplus_catalog_key *key;
1115         struct hfsplus_vol_header *hfsplus;
1116         struct hfs_mdb *sbd = (struct hfs_mdb *) buf;
1117         unsigned int alloc_block_size;
1118         unsigned int alloc_first_block;
1119         unsigned int embed_first_block;
1120         unsigned int off = 0;
1121         unsigned int blocksize;
1122         unsigned int cat_block;
1123         unsigned int ext_block_start;
1124         unsigned int ext_block_count;
1125         unsigned int record_count;
1126         unsigned int leaf_node_head;
1127         unsigned int leaf_node_count;
1128         unsigned int leaf_node_size;
1129         unsigned int leaf_block;
1130         unsigned int label_len;
1131         int ext;
1132         __u64 leaf_off, uuid;
1133         char    uuid_str[17], label[512];
1134
1135         /* Check for a HFS+ volume embedded in a HFS volume */
1136         if (memcmp(sbd->signature, "BD", 2) == 0) {
1137                 if ((memcmp(sbd->embed_sig, "H+", 2) != 0) &&
1138                     (memcmp(sbd->embed_sig, "HX", 2) != 0))
1139                         /* This must be an HFS volume, so fail */
1140                         return 1;
1141
1142                 alloc_block_size = blkid_be32(sbd->al_blk_size);
1143                 alloc_first_block = blkid_be16(sbd->al_bl_st);
1144                 embed_first_block = blkid_be16(sbd->embed_startblock);
1145                 off = (alloc_first_block * 512) +
1146                         (embed_first_block * alloc_block_size);
1147                 buf = get_buffer(probe, off + (id->bim_kboff * 1024),
1148                                  sizeof(sbd));
1149                 if (!buf)
1150                         return 1;
1151
1152                 hfsplus = (struct hfsplus_vol_header *) buf;
1153         }
1154
1155         hfsplus = (struct hfsplus_vol_header *) buf;
1156
1157         if ((memcmp(hfsplus->signature, "H+", 2) != 0) &&
1158             (memcmp(hfsplus->signature, "HX", 2) != 0))
1159                 return 1;
1160
1161         uuid = blkid_le64(*((unsigned long long *) hfsplus->finder_info.id));
1162         if (uuid) {
1163                 sprintf(uuid_str, "%016llX", uuid);
1164                 blkid_set_tag(probe->dev, "UUID", uuid_str, 0);
1165         }
1166
1167         blocksize = blkid_be32(hfsplus->blocksize);
1168         memcpy(extents, hfsplus->cat_file.extents, sizeof(extents));
1169         cat_block = blkid_be32(extents[0].start_block);
1170
1171         buf = get_buffer(probe, off + (cat_block * blocksize), 0x2000);
1172         if (!buf)
1173                 return 0;
1174
1175         bnode = (struct hfsplus_bheader_record *)
1176                 &buf[sizeof(struct hfsplus_bnode_descriptor)];
1177
1178         leaf_node_head = blkid_be32(bnode->leaf_head);
1179         leaf_node_size = blkid_be16(bnode->node_size);
1180         leaf_node_count = blkid_be32(bnode->leaf_count);
1181         if (leaf_node_count == 0)
1182                 return 0;
1183
1184         leaf_block = (leaf_node_head * leaf_node_size) / blocksize;
1185
1186         /* get physical location */
1187         for (ext = 0; ext < HFSPLUS_EXTENT_COUNT; ext++) {
1188                 ext_block_start = blkid_be32(extents[ext].start_block);
1189                 ext_block_count = blkid_be32(extents[ext].block_count);
1190                 if (ext_block_count == 0)
1191                         return 0;
1192
1193                 /* this is our extent */
1194                 if (leaf_block < ext_block_count)
1195                         break;
1196
1197                 leaf_block -= ext_block_count;
1198         }
1199         if (ext == HFSPLUS_EXTENT_COUNT)
1200                 return 0;
1201
1202         leaf_off = (ext_block_start + leaf_block) * blocksize;
1203
1204         buf = get_buffer(probe, off + leaf_off, leaf_node_size);
1205         if (!buf)
1206                 return 0;
1207
1208         descr = (struct hfsplus_bnode_descriptor *) buf;
1209         record_count = blkid_be16(descr->num_recs);
1210         if (record_count == 0)
1211                 return 0;
1212
1213         if (descr->type != HFS_NODE_LEAF)
1214                 return 0;
1215
1216         key = (struct hfsplus_catalog_key *)
1217                 &buf[sizeof(struct hfsplus_bnode_descriptor)];
1218
1219         if (blkid_be32(key->parent_id) != HFSPLUS_POR_CNID)
1220                 return 0;
1221
1222         label_len = blkid_be16(key->unicode_len) * 2;
1223         unicode_16be_to_utf8(label, sizeof(label), key->unicode, label_len);
1224         blkid_set_tag(probe->dev, "LABEL", label, 0);
1225         return 0;
1226 }
1227
1228 #define LVM2_LABEL_SIZE 512
1229 static unsigned int lvm2_calc_crc(const void *buf, unsigned int size)
1230 {
1231         static const unsigned int crctab[] = {
1232                 0x00000000, 0x1db71064, 0x3b6e20c8, 0x26d930ac,
1233                 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
1234                 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
1235                 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c
1236         };
1237         unsigned int i, crc = 0xf597a6cf;
1238         const __u8 *data = (const __u8 *) buf;
1239
1240         for (i = 0; i < size; i++) {
1241                 crc ^= *data++;
1242                 crc = (crc >> 4) ^ crctab[crc & 0xf];
1243                 crc = (crc >> 4) ^ crctab[crc & 0xf];
1244         }
1245         return crc;
1246 }
1247
1248 static int probe_lvm2(struct blkid_probe *probe,
1249                         struct blkid_magic *id,
1250                         unsigned char *buf)
1251 {
1252         int sector = (id->bim_kboff) << 1;
1253         struct lvm2_pv_label_header *label= (struct lvm2_pv_label_header *)buf;
1254         char *p, *q, uuid[40];
1255         unsigned int i, b;
1256
1257         /* buf is at 0k or 1k offset; find label inside */
1258         if (memcmp(buf, "LABELONE", 8) == 0) {
1259                 label = (struct lvm2_pv_label_header *)buf;
1260         } else if (memcmp(buf + 512, "LABELONE", 8) == 0) {
1261                 label = (struct lvm2_pv_label_header *)(buf + 512);
1262                 sector++;
1263         } else {
1264                 return 1;
1265         }
1266
1267         if (blkid_le64(label->sector_xl) != (unsigned) sector) {
1268                 DBG(DEBUG_PROBE,
1269                     printf("LVM2: label for sector %llu found at sector %d\n",
1270                            blkid_le64(label->sector_xl), sector));
1271                 return 1;
1272         }
1273
1274         if (lvm2_calc_crc(&label->offset_xl, LVM2_LABEL_SIZE -
1275                           ((char *)&label->offset_xl - (char *)label)) !=
1276                         blkid_le32(label->crc_xl)) {
1277                 DBG(DEBUG_PROBE,
1278                     printf("LVM2: label checksum incorrect at sector %d\n",
1279                            sector));
1280                 return 1;
1281         }
1282
1283         for (i=0, b=1, p=uuid, q= (char *) label->pv_uuid; i <= 32;
1284              i++, b <<= 1) {
1285                 if (b & 0x4444440)
1286                         *p++ = '-';
1287                 *p++ = *q++;
1288         }
1289
1290         blkid_set_tag(probe->dev, "UUID", uuid, LVM2_ID_LEN+6);
1291
1292         return 0;
1293 }
1294 /*
1295  * Various filesystem magics that we can check for.  Note that kboff and
1296  * sboff are in kilobytes and bytes respectively.  All magics are in
1297  * byte strings so we don't worry about endian issues.
1298  */
1299 static struct blkid_magic type_array[] = {
1300 /*  type     kboff   sboff len  magic                   probe */
1301   { "oracleasm", 0,     32,  8, "ORCLDISK",             probe_oracleasm },
1302   { "ntfs",      0,      3,  8, "NTFS    ",             probe_ntfs },
1303   { "jbd",       1,   0x38,  2, "\123\357",             probe_jbd },
1304   { "ext4dev",   1,   0x38,  2, "\123\357",             probe_ext4dev },
1305   { "ext4",      1,   0x38,  2, "\123\357",             probe_ext4 },
1306   { "ext3",      1,   0x38,  2, "\123\357",             probe_ext3 },
1307   { "ext2",      1,   0x38,  2, "\123\357",             probe_ext2 },
1308   { "reiserfs",  8,   0x34,  8, "ReIsErFs",             probe_reiserfs },
1309   { "reiserfs", 64,   0x34,  9, "ReIsEr2Fs",            probe_reiserfs },
1310   { "reiserfs", 64,   0x34,  9, "ReIsEr3Fs",            probe_reiserfs },
1311   { "reiserfs", 64,   0x34,  8, "ReIsErFs",             probe_reiserfs },
1312   { "reiserfs",  8,     20,  8, "ReIsErFs",             probe_reiserfs },
1313   { "reiser4",  64,      0,  7, "ReIsEr4",              probe_reiserfs4 },
1314   { "gfs2",     64,      0,  4, "\x01\x16\x19\x70",     probe_gfs2 },
1315   { "gfs",      64,      0,  4, "\x01\x16\x19\x70",     probe_gfs },
1316   { "vfat",      0,   0x52,  5, "MSWIN",                probe_fat },
1317   { "vfat",      0,   0x52,  8, "FAT32   ",             probe_fat },
1318   { "vfat",      0,   0x36,  5, "MSDOS",                probe_fat },
1319   { "vfat",      0,   0x36,  8, "FAT16   ",             probe_fat },
1320   { "vfat",      0,   0x36,  8, "FAT12   ",             probe_fat },
1321   { "vfat",      0,      0,  1, "\353",                 probe_fat_nomagic },
1322   { "vfat",      0,      0,  1, "\351",                 probe_fat_nomagic },
1323   { "vfat",      0,  0x1fe,  2, "\125\252",             probe_fat_nomagic },
1324   { "minix",     1,   0x10,  2, "\177\023",             0 },
1325   { "minix",     1,   0x10,  2, "\217\023",             0 },
1326   { "minix",     1,   0x10,  2, "\150\044",             0 },
1327   { "minix",     1,   0x10,  2, "\170\044",             0 },
1328   { "vxfs",      1,      0,  4, "\365\374\001\245",     0 },
1329   { "xfs",       0,      0,  4, "XFSB",                 probe_xfs },
1330   { "romfs",     0,      0,  8, "-rom1fs-",             probe_romfs },
1331   { "bfs",       0,      0,  4, "\316\372\173\033",     0 },
1332   { "cramfs",    0,      0,  4, "E=\315\050",           probe_cramfs },
1333   { "qnx4",      0,      4,  6, "QNX4FS",               0 },
1334   { "udf",      32,      1,  5, "BEA01",                probe_udf },
1335   { "udf",      32,      1,  5, "BOOT2",                probe_udf },
1336   { "udf",      32,      1,  5, "CD001",                probe_udf },
1337   { "udf",      32,      1,  5, "CDW02",                probe_udf },
1338   { "udf",      32,      1,  5, "NSR02",                probe_udf },
1339   { "udf",      32,      1,  5, "NSR03",                probe_udf },
1340   { "udf",      32,      1,  5, "TEA01",                probe_udf },
1341   { "iso9660",  32,      1,  5, "CD001",                probe_iso9660 },
1342   { "iso9660",  32,      9,  5, "CDROM",                probe_iso9660 },
1343   { "jfs",      32,      0,  4, "JFS1",                 probe_jfs },
1344   { "zfs",       8,      0,  8, "\0\0\x02\xf5\xb0\x07\xb1\x0c", probe_zfs },
1345   { "zfs",       8,      0,  8, "\x0c\xb1\x07\xb0\xf5\x02\0\0", probe_zfs },
1346   { "zfs",     264,      0,  8, "\0\0\x02\xf5\xb0\x07\xb1\x0c", probe_zfs },
1347   { "zfs",     264,      0,  8, "\x0c\xb1\x07\xb0\xf5\x02\0\0", probe_zfs },
1348   { "hfsplus",   1,      0,  2, "BD",                   probe_hfsplus },
1349   { "hfsplus",   1,      0,  2, "H+",                   probe_hfsplus },
1350   { "hfsplus",   1,      0,  2, "HX",                   probe_hfsplus },
1351   { "hfs",       1,      0,  2, "BD",                   probe_hfs },
1352   { "ufs",       8,  0x55c,  4, "T\031\001\000",        0 },
1353   { "hpfs",      8,      0,  4, "I\350\225\371",        0 },
1354   { "sysv",      0,  0x3f8,  4, "\020~\030\375",        0 },
1355   { "swap",      0,  0xff6, 10, "SWAP-SPACE",           probe_swap0 },
1356   { "swap",      0,  0xff6, 10, "SWAPSPACE2",           probe_swap1 },
1357   { "swsuspend", 0,  0xff6,  9, "S1SUSPEND",            probe_swap1 },
1358   { "swsuspend", 0,  0xff6,  9, "S2SUSPEND",            probe_swap1 },
1359   { "swap",      0, 0x1ff6, 10, "SWAP-SPACE",           probe_swap0 },
1360   { "swap",      0, 0x1ff6, 10, "SWAPSPACE2",           probe_swap1 },
1361   { "swsuspend", 0, 0x1ff6,  9, "S1SUSPEND",            probe_swap1 },
1362   { "swsuspend", 0, 0x1ff6,  9, "S2SUSPEND",            probe_swap1 },
1363   { "swap",      0, 0x3ff6, 10, "SWAP-SPACE",           probe_swap0 },
1364   { "swap",      0, 0x3ff6, 10, "SWAPSPACE2",           probe_swap1 },
1365   { "swsuspend", 0, 0x3ff6,  9, "S1SUSPEND",            probe_swap1 },
1366   { "swsuspend", 0, 0x3ff6,  9, "S2SUSPEND",            probe_swap1 },
1367   { "swap",      0, 0x7ff6, 10, "SWAP-SPACE",           probe_swap0 },
1368   { "swap",      0, 0x7ff6, 10, "SWAPSPACE2",           probe_swap1 },
1369   { "swsuspend", 0, 0x7ff6,  9, "S1SUSPEND",            probe_swap1 },
1370   { "swsuspend", 0, 0x7ff6,  9, "S2SUSPEND",            probe_swap1 },
1371   { "swap",      0, 0xfff6, 10, "SWAP-SPACE",           probe_swap0 },
1372   { "swap",      0, 0xfff6, 10, "SWAPSPACE2",           probe_swap1 },
1373   { "swsuspend", 0, 0xfff6,  9, "S1SUSPEND",            probe_swap1 },
1374   { "swsuspend", 0, 0xfff6,  9, "S2SUSPEND",            probe_swap1 },
1375   { "ocfs",      0,      8,  9, "OracleCFS",            probe_ocfs },
1376   { "ocfs2",     1,      0,  6, "OCFSV2",               probe_ocfs2 },
1377   { "ocfs2",     2,      0,  6, "OCFSV2",               probe_ocfs2 },
1378   { "ocfs2",     4,      0,  6, "OCFSV2",               probe_ocfs2 },
1379   { "ocfs2",     8,      0,  6, "OCFSV2",               probe_ocfs2 },
1380   { "crypt_LUKS", 0,     0,  6, "LUKS\xba\xbe",         probe_luks },
1381   { "squashfs",  0,      0,  4, "sqsh",                 0 },
1382   { "squashfs",  0,      0,  4, "hsqs",                 0 },
1383   { "lvm2pv",    0,  0x218,  8, "LVM2 001",             probe_lvm2 },
1384   { "lvm2pv",    0,  0x018,  8, "LVM2 001",             probe_lvm2 },
1385   { "lvm2pv",    1,  0x018,  8, "LVM2 001",             probe_lvm2 },
1386   { "lvm2pv",    1,  0x218,  8, "LVM2 001",             probe_lvm2 },
1387   {   NULL,      0,      0,  0, NULL,                   NULL }
1388 };
1389
1390 /*
1391  * Verify that the data in dev is consistent with what is on the actual
1392  * block device (using the devname field only).  Normally this will be
1393  * called when finding items in the cache, but for long running processes
1394  * is also desirable to revalidate an item before use.
1395  *
1396  * If we are unable to revalidate the data, we return the old data and
1397  * do not set the BLKID_BID_FL_VERIFIED flag on it.
1398  */
1399 blkid_dev blkid_verify(blkid_cache cache, blkid_dev dev)
1400 {
1401         struct blkid_magic *id;
1402         struct blkid_probe probe;
1403         blkid_tag_iterate iter;
1404         unsigned char *buf;
1405         const char *type, *value;
1406         struct stat st;
1407         time_t diff, now;
1408         int idx;
1409
1410         if (!dev)
1411                 return NULL;
1412
1413         now = time(0);
1414         diff = now - dev->bid_time;
1415
1416         if (stat(dev->bid_name, &st) < 0) {
1417                 DBG(DEBUG_PROBE,
1418                     printf("blkid_verify: error %s (%d) while "
1419                            "trying to stat %s\n", strerror(errno), errno,
1420                            dev->bid_name));
1421         open_err:
1422                 if ((errno == EPERM) || (errno == EACCES) || (errno == ENOENT)) {
1423                         /* We don't have read permission, just return cache data. */
1424                         DBG(DEBUG_PROBE, printf("returning unverified data for %s\n",
1425                                                 dev->bid_name));
1426                         return dev;
1427                 }
1428                 blkid_free_dev(dev);
1429                 return NULL;
1430         }
1431
1432         if ((now >= dev->bid_time) &&
1433             (st.st_mtime <= dev->bid_time) &&
1434             ((diff < BLKID_PROBE_MIN) ||
1435              (dev->bid_flags & BLKID_BID_FL_VERIFIED &&
1436               diff < BLKID_PROBE_INTERVAL)))
1437                 return dev;
1438
1439         DBG(DEBUG_PROBE,
1440             printf("need to revalidate %s (cache time %lu, stat time %lu,\n\t"
1441                    "time since last check %lu)\n",
1442                    dev->bid_name, (unsigned long)dev->bid_time,
1443                    (unsigned long)st.st_mtime, (unsigned long)diff));
1444
1445         if ((probe.fd = open(dev->bid_name, O_RDONLY)) < 0) {
1446                 DBG(DEBUG_PROBE, printf("blkid_verify: error %s (%d) while "
1447                                         "opening %s\n", strerror(errno), errno,
1448                                         dev->bid_name));
1449                 goto open_err;
1450         }
1451
1452         probe.cache = cache;
1453         probe.dev = dev;
1454         probe.sbbuf = 0;
1455         probe.buf = 0;
1456         probe.buf_max = 0;
1457
1458         /*
1459          * Iterate over the type array.  If we already know the type,
1460          * then try that first.  If it doesn't work, then blow away
1461          * the type information, and try again.
1462          *
1463          */
1464 try_again:
1465         type = 0;
1466         if (!dev->bid_type || !strcmp(dev->bid_type, "mdraid")) {
1467                 uuid_t  uuid;
1468
1469                 if (check_mdraid(probe.fd, uuid) == 0) {
1470                         set_uuid(dev, uuid, 0);
1471                         type = "mdraid";
1472                         goto found_type;
1473                 }
1474         }
1475         for (id = type_array; id->bim_type; id++) {
1476                 if (dev->bid_type &&
1477                     strcmp(id->bim_type, dev->bid_type))
1478                         continue;
1479
1480                 idx = id->bim_kboff + (id->bim_sboff >> 10);
1481                 buf = get_buffer(&probe, idx << 10, 1024);
1482                 if (!buf)
1483                         continue;
1484
1485                 if (memcmp(id->bim_magic, buf + (id->bim_sboff & 0x3ff),
1486                            id->bim_len))
1487                         continue;
1488
1489                 if ((id->bim_probe == NULL) ||
1490                     (id->bim_probe(&probe, id, buf) == 0)) {
1491                         type = id->bim_type;
1492                         goto found_type;
1493                 }
1494         }
1495
1496         if (!id->bim_type && dev->bid_type) {
1497                 /*
1498                  * Zap the device filesystem information and try again
1499                  */
1500                 DBG(DEBUG_PROBE,
1501                     printf("previous fs type %s not valid, "
1502                            "trying full probe\n", dev->bid_type));
1503                 iter = blkid_tag_iterate_begin(dev);
1504                 while (blkid_tag_next(iter, &type, &value) == 0)
1505                         blkid_set_tag(dev, type, 0, 0);
1506                 blkid_tag_iterate_end(iter);
1507                 goto try_again;
1508         }
1509
1510         if (!dev->bid_type) {
1511                 blkid_free_dev(dev);
1512                 dev = 0;
1513                 goto found_type;
1514         }
1515
1516 found_type:
1517         if (dev && type) {
1518                 dev->bid_devno = st.st_rdev;
1519                 dev->bid_time = time(0);
1520                 dev->bid_flags |= BLKID_BID_FL_VERIFIED;
1521                 cache->bic_flags |= BLKID_BIC_FL_CHANGED;
1522
1523                 blkid_set_tag(dev, "TYPE", type, 0);
1524
1525                 DBG(DEBUG_PROBE, printf("%s: devno 0x%04llx, type %s\n",
1526                            dev->bid_name, (long long)st.st_rdev, type));
1527         }
1528
1529         if (probe.sbbuf)
1530                 free(probe.sbbuf);
1531         if (probe.buf)
1532                 free(probe.buf);
1533         if (probe.fd >= 0)
1534                 close(probe.fd);
1535
1536         return dev;
1537 }
1538
1539 int blkid_known_fstype(const char *fstype)
1540 {
1541         struct blkid_magic *id;
1542
1543         for (id = type_array; id->bim_type; id++) {
1544                 if (strcmp(fstype, id->bim_type) == 0)
1545                         return 1;
1546         }
1547         return 0;
1548 }
1549
1550 #ifdef TEST_PROGRAM
1551 int main(int argc, char **argv)
1552 {
1553         blkid_dev dev;
1554         blkid_cache cache;
1555         int ret;
1556
1557         if (argc != 2) {
1558                 fprintf(stderr, "Usage: %s device\n"
1559                         "Probe a single device to determine type\n", argv[0]);
1560                 exit(1);
1561         }
1562         if ((ret = blkid_get_cache(&cache, "/dev/null")) != 0) {
1563                 fprintf(stderr, "%s: error creating cache (%d)\n",
1564                         argv[0], ret);
1565                 exit(1);
1566         }
1567         dev = blkid_get_dev(cache, argv[1], BLKID_DEV_NORMAL);
1568         if (!dev) {
1569                 printf("%s: %s has an unsupported type\n", argv[0], argv[1]);
1570                 return (1);
1571         }
1572         printf("TYPE='%s'\n", dev->bid_type ? dev->bid_type : "(null)");
1573         if (dev->bid_label)
1574                 printf("LABEL='%s'\n", dev->bid_label);
1575         if (dev->bid_uuid)
1576                 printf("UUID='%s'\n", dev->bid_uuid);
1577
1578         blkid_free_dev(dev);
1579         return (0);
1580 }
1581 #endif