comparison libnumdb/readbin.c @ 8:ffd48df829a7

beginning of libnumdb: reading the binary file
author Mychaela Falconia <falcon@freecalypso.org>
date Sun, 26 Jun 2022 13:07:33 -0800
parents
children
comparison
equal deleted inserted replaced
7:7749ae8b6414 8:ffd48df829a7
1 /*
2 * This library module contains the code that reads /var/gsm/number-db.bin,
3 * as well as definitions of global variables into which the booty is read.
4 */
5
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <stdio.h>
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include <syslog.h>
12 #include "../include/number_db_file.h"
13
14 char numdb_pathname[] = "/var/gsm/number-db.bin";
15 struct stat numdb_file_stat;
16 struct numdb_file_hdr numdb_hdr;
17 uint64_t *numdb_owned_numbers;
18 struct short_number_map *numdb_short_numbers;
19
20 read_number_db()
21 {
22 FILE *inf;
23
24 inf = fopen(numdb_pathname, "r");
25 if (!inf) {
26 syslog(LOG_CRIT, "open %s: %m", numdb_pathname);
27 return(-1);
28 }
29 fstat(fileno(inf), &numdb_file_stat);
30 if (!S_ISREG(numdb_file_stat.st_mode)) {
31 syslog(LOG_CRIT, "invalid %s: not a regular file",
32 numdb_pathname);
33 fclose(inf);
34 return(-1);
35 }
36 if (fread(&numdb_hdr, sizeof numdb_hdr, 1, inf) != 1) {
37 read_err: syslog(LOG_CRIT, "error reading from %s: %m", numdb_pathname);
38 fclose(inf);
39 return(-1);
40 }
41 if (numdb_hdr.owned_number_count) {
42 numdb_owned_numbers = malloc(numdb_hdr.owned_number_count *
43 sizeof(uint64_t));
44 if (!numdb_owned_numbers) {
45 syslog(LOG_CRIT, "malloc for owned number db: %m");
46 fclose(inf);
47 return(-1);
48 }
49 if (fread(numdb_owned_numbers, sizeof(uint64_t),
50 numdb_hdr.owned_number_count, inf) !=
51 numdb_hdr.owned_number_count)
52 goto read_err;
53 }
54 if (numdb_hdr.short_number_count) {
55 numdb_short_numbers = malloc(numdb_hdr.short_number_count *
56 sizeof(struct short_number_map));
57 if (!numdb_short_numbers) {
58 syslog(LOG_CRIT, "malloc for short number db: %m");
59 fclose(inf);
60 return(-1);
61 }
62 if (fread(numdb_short_numbers, sizeof(struct short_number_map),
63 numdb_hdr.short_number_count, inf) !=
64 numdb_hdr.short_number_count)
65 goto read_err;
66 }
67 fclose(inf);
68 return(0);
69 }