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