]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
Get rid of our 'ignore' rules
[ext/subsurface.git] / parse-xml.c
1 #include <stdio.h>
2 #include <ctype.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <errno.h>
6 #include <time.h>
7 #include <libxml/parser.h>
8 #include <libxml/tree.h>
9
10 #include "dive.h"
11
12 int verbose;
13
14 struct dive_table dive_table;
15
16 /*
17  * Add a dive into the dive_table array
18  */
19 static void record_dive(struct dive *dive)
20 {
21         int nr = dive_table.nr, allocated = dive_table.allocated;
22         struct dive **dives = dive_table.dives;
23
24         if (nr >= allocated) {
25                 allocated = (nr + 32) * 3 / 2;
26                 dives = realloc(dives, allocated * sizeof(struct dive *));
27                 if (!dives)
28                         exit(1);
29                 dive_table.dives = dives;
30                 dive_table.allocated = allocated;
31         }
32         dives[nr] = dive;
33         dive_table.nr = nr+1;
34 }
35
36 static void start_match(const char *type, const char *name, char *buffer)
37 {
38         if (verbose > 2)
39                 printf("Matching %s '%s' (%s)\n",
40                         type, name, buffer);
41 }
42
43 static void nonmatch(const char *type, const char *name, char *buffer)
44 {
45         if (verbose > 1)
46                 printf("Unable to match %s '%s' (%s)\n",
47                         type, name, buffer);
48         free(buffer);
49 }
50
51 typedef void (*matchfn_t)(char *buffer, void *);
52
53 static int match(const char *pattern, int plen,
54                  const char *name, int nlen,
55                  matchfn_t fn, char *buf, void *data)
56 {
57         if (plen > nlen)
58                 return 0;
59         if (memcmp(pattern, name + nlen - plen, plen))
60                 return 0;
61         fn(buf, data);
62         return 1;
63 }
64
65 /*
66  * Dive info as it is being built up..
67  */
68 static int alloc_samples;
69 static struct dive *dive;
70 static struct sample *sample;
71 static struct tm tm;
72
73 static time_t utc_mktime(struct tm *tm)
74 {
75         static const int mdays[] = {
76             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
77         };
78         int year = tm->tm_year;
79         int month = tm->tm_mon;
80         int day = tm->tm_mday;
81
82         /* First normalize relative to 1900 */
83         if (year < 70)
84                 year += 100;
85         else if (year > 1900)
86                 year -= 1900;
87
88         /* Normalized to Jan 1, 1970: unix time */
89         year -= 70;
90
91         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
92                 return -1;
93         if (month < 0 || month > 11) /* array bounds */
94                 return -1;
95         if (month < 2 || (year + 2) % 4)
96                 day--;
97         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
98                 return -1;
99         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
100                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
101 }
102
103 static void divedate(char *buffer, void *_when)
104 {
105         int d,m,y;
106         time_t *when = _when;
107
108         if (sscanf(buffer, "%d.%d.%d", &d, &m, &y) == 3) {
109                 tm.tm_year = y;
110                 tm.tm_mon = m-1;
111                 tm.tm_mday = d;
112                 if (tm.tm_sec | tm.tm_min | tm.tm_hour)
113                         *when = utc_mktime(&tm);
114         }
115         free(buffer);
116 }
117
118 static void divetime(char *buffer, void *_when)
119 {
120         int h,m,s = 0;
121         time_t *when = _when;
122
123         if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) {
124                 tm.tm_hour = h;
125                 tm.tm_min = m;
126                 tm.tm_sec = s;
127                 if (tm.tm_year)
128                         *when = utc_mktime(&tm);
129         }
130         free(buffer);
131 }
132
133 /* Libdivecomputer: "2011-03-20 10:22:38" */
134 static void divedatetime(char *buffer, void *_when)
135 {
136         int y,m,d;
137         int hr,min,sec;
138         time_t *when = _when;
139
140         if (sscanf(buffer, "%d-%d-%d %d:%d:%d",
141                 &y, &m, &d, &hr, &min, &sec) == 6) {
142                 tm.tm_year = y;
143                 tm.tm_mon = m-1;
144                 tm.tm_mday = d;
145                 tm.tm_hour = hr;
146                 tm.tm_min = min;
147                 tm.tm_sec = sec;
148                 *when = utc_mktime(&tm);
149         }
150         free(buffer);
151 }
152
153 union int_or_float {
154         long i;
155         double fp;
156 };
157
158 enum number_type {
159         NEITHER,
160         INTEGER,
161         FLOAT
162 };
163
164 static enum number_type integer_or_float(char *buffer, union int_or_float *res)
165 {
166         char *end;
167         long val;
168         double fp;
169
170         /* Integer or floating point? */
171         val = strtol(buffer, &end, 10);
172         if (val < 0 || end == buffer)
173                 return NEITHER;
174
175         /* Looks like it might be floating point? */
176         if (*end == '.') {
177                 errno = 0;
178                 fp = strtod(buffer, &end);
179                 if (!errno) {
180                         res->fp = fp;
181                         return FLOAT;
182                 }
183         }
184
185         res->i = val;
186         return INTEGER;
187 }
188
189 static void pressure(char *buffer, void *_press)
190 {
191         pressure_t *pressure = _press;
192         union int_or_float val;
193
194         switch (integer_or_float(buffer, &val)) {
195         case FLOAT:
196                 /* Maybe it's in Bar? */
197                 if (val.fp < 500.0) {
198                         pressure->mbar = val.fp * 1000;
199                         break;
200                 }
201                 printf("Unknown fractional pressure reading %s\n", buffer);
202                 break;
203
204         case INTEGER:
205                 /*
206                  * Random integer? Maybe in PSI? Or millibar already?
207                  *
208                  * We assume that 5 bar is a ridiculous tank pressure,
209                  * so if it's smaller than 5000, it's in PSI..
210                  */
211                 if (val.i < 5000) {
212                         pressure->mbar = val.i * 68.95;
213                         break;
214                 }
215                 pressure->mbar = val.i;
216                 break;
217         default:
218                 printf("Strange pressure reading %s\n", buffer);
219         }
220         free(buffer);
221 }
222
223 static void depth(char *buffer, void *_depth)
224 {
225         depth_t *depth = _depth;
226         union int_or_float val;
227
228         switch (integer_or_float(buffer, &val)) {
229         /* All values are probably in meters */
230         case INTEGER:
231                 val.fp = val.i;
232                 /* fallthrough */
233         case FLOAT:
234                 depth->mm = val.fp * 1000;
235                 break;
236         default:
237                 printf("Strange depth reading %s\n", buffer);
238         }
239         free(buffer);
240 }
241
242 static void temperature(char *buffer, void *_temperature)
243 {
244         temperature_t *temperature = _temperature;
245         union int_or_float val;
246
247         switch (integer_or_float(buffer, &val)) {
248         /* C or F? Who knows? Let's default to Celsius */
249         case INTEGER:
250                 val.fp = val.i;
251                 /* Fallthrough */
252         case FLOAT:
253                 /* Ignore zero. It means "none" */
254                 if (!val.fp)
255                         break;
256                 /* Celsius */
257                 if (val.fp < 50.0) {
258                         temperature->mkelvin = (val.fp + 273.16) * 1000;
259                         break;
260                 }
261                 /* Fahrenheit */
262                 if (val.fp < 212.0) {
263                         temperature->mkelvin = (val.fp + 459.67) * 5000/9;
264                         break;
265                 }
266                 /* Kelvin or already millikelvin */
267                 if (val.fp < 1000.0)
268                         val.fp *= 1000;
269                 temperature->mkelvin = val.fp;
270                 break;
271         default:
272                 printf("Strange temperature reading %s\n", buffer);
273         }
274         free(buffer);
275 }
276
277 static void sampletime(char *buffer, void *_time)
278 {
279         int i;
280         int min, sec;
281         duration_t *time = _time;
282
283         i = sscanf(buffer, "%d:%d", &min, &sec);
284         switch (i) {
285         case 1:
286                 sec = min;
287                 min = 0;
288         /* fallthrough */
289         case 2:
290                 time->seconds = sec + min*60;
291                 break;
292         default:
293                 printf("Strange sample time reading %s\n", buffer);
294         }
295         free(buffer);
296 }
297
298 static void duration(char *buffer, void *_time)
299 {
300         sampletime(buffer, _time);
301 }
302
303 #define MATCH(pattern, fn, dest) \
304         match(pattern, strlen(pattern), name, len, fn, buf, dest)
305
306 /* We're in samples - try to convert the random xml value to something useful */
307 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
308 {
309         int len = strlen(name);
310
311         start_match("sample", name, buf);
312         if (MATCH(".sample.pressure", pressure, &sample->tankpressure))
313                 return;
314         if (MATCH(".sample.cylpress", pressure, &sample->tankpressure))
315                 return;
316         if (MATCH(".sample.depth", depth, &sample->depth))
317                 return;
318         if (MATCH(".sample.temperature", temperature, &sample->temperature))
319                 return;
320         if (MATCH(".sample.sampletime", sampletime, &sample->time))
321                 return;
322         if (MATCH(".sample.time", sampletime, &sample->time))
323                 return;
324
325         nonmatch("sample", name, buf);
326 }
327
328 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
329 static void try_to_fill_dive(struct dive *dive, const char *name, char *buf)
330 {
331         int len = strlen(name);
332
333         start_match("dive", name, buf);
334         if (MATCH(".date", divedate, &dive->when))
335                 return;
336         if (MATCH(".time", divetime, &dive->when))
337                 return;
338         if (MATCH(".datetime", divedatetime, &dive->when))
339                 return;
340         if (MATCH(".maxdepth", depth, &dive->maxdepth))
341                 return;
342         if (MATCH(".meandepth", depth, &dive->meandepth))
343                 return;
344         if (MATCH(".divetime", duration, &dive->duration))
345                 return;
346         if (MATCH(".divetimesec", duration, &dive->duration))
347                 return;
348         if (MATCH(".surfacetime", duration, &dive->surfacetime))
349                 return;
350         if (MATCH(".airtemp", temperature, &dive->airtemp))
351                 return;
352         if (MATCH(".watertemp", temperature, &dive->watertemp))
353                 return;
354         if (MATCH(".cylinderstartpressure", pressure, &dive->beginning_pressure))
355                 return;
356         if (MATCH(".cylinderendpressure", pressure, &dive->end_pressure))
357                 return;
358         nonmatch("dive", name, buf);
359 }
360
361 static unsigned int dive_size(int samples)
362 {
363         return sizeof(struct dive) + samples*sizeof(struct sample);
364 }
365
366 /*
367  * File boundaries are dive boundaries. But sometimes there are
368  * multiple dives per file, so there can be other events too that
369  * trigger a "new dive" marker and you may get some nesting due
370  * to that. Just ignore nesting levels.
371  */
372 static void dive_start(void)
373 {
374         unsigned int size;
375
376         if (dive)
377                 return;
378
379         alloc_samples = 5;
380         size = dive_size(alloc_samples);
381         dive = malloc(size);
382         if (!dive)
383                 exit(1);
384         memset(dive, 0, size);
385         memset(&tm, 0, sizeof(tm));
386 }
387
388 static char *generate_name(struct dive *dive)
389 {
390         int len;
391         struct tm *tm;
392         char buffer[256], *p;
393
394         tm = gmtime(&dive->when);
395
396         len = snprintf(buffer, sizeof(buffer),
397                 "%04d-%02d-%02d "
398                 "%02d:%02d:%02d "
399                 "(%d ft, %d min)",
400                 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
401                 tm->tm_hour, tm->tm_min, tm->tm_sec,
402                 to_feet(dive->maxdepth), dive->duration.seconds / 60);
403         p = malloc(len+1);
404         if (!p)
405                 exit(1);
406         memcpy(p, buffer, len+1);
407         return p;
408 }
409
410 static void dive_end(void)
411 {
412         if (!dive)
413                 return;
414         if (!dive->name)
415                 dive->name = generate_name(dive);
416         record_dive(dive);
417         dive = NULL;
418 }
419
420 static void sample_start(void)
421 {
422         int nr;
423
424         if (!dive)
425                 return;
426         nr = dive->samples;
427         if (nr >= alloc_samples) {
428                 unsigned int size;
429
430                 alloc_samples = (alloc_samples * 3)/2 + 10;
431                 size = dive_size(alloc_samples);
432                 dive = realloc(dive, size);
433                 if (!dive)
434                         return;
435         }
436         sample = dive->sample + nr;
437         memset(sample, 0, sizeof(*sample));
438 }
439
440 static void sample_end(void)
441 {
442         if (!dive)
443                 return;
444
445         if (sample->time.seconds > dive->duration.seconds) {
446                 if (sample->depth.mm)
447                         dive->duration = sample->time;
448         }
449
450         if (sample->depth.mm > dive->maxdepth.mm)
451                 dive->maxdepth.mm = sample->depth.mm;
452
453         sample = NULL;
454         dive->samples++;
455 }
456
457 static void entry(const char *name, int size, const char *raw)
458 {
459         char *buf = malloc(size+1);
460
461         if (!buf)
462                 return;
463         memcpy(buf, raw, size);
464         buf[size] = 0;
465         if (sample) {
466                 try_to_fill_sample(sample, name, buf);
467                 return;
468         }
469         if (dive) {
470                 try_to_fill_dive(dive, name, buf);
471                 return;
472         }
473 }
474
475 static const char *nodename(xmlNode *node, char *buf, int len)
476 {
477         if (!node || !node->name)
478                 return "root";
479
480         buf += len;
481         *--buf = 0;
482         len--;
483
484         for(;;) {
485                 const char *name = node->name;
486                 int i = strlen(name);
487                 while (--i >= 0) {
488                         unsigned char c = name[i];
489                         *--buf = tolower(c);
490                         if (!--len)
491                                 return buf;
492                 }
493                 node = node->parent;
494                 if (!node || !node->name)
495                         return buf;
496                 *--buf = '.';
497                 if (!--len)
498                         return buf;
499         }
500 }
501
502 #define MAXNAME 64
503
504 static void visit_one_node(xmlNode *node)
505 {
506         int len;
507         const unsigned char *content;
508         char buffer[MAXNAME];
509         const char *name;
510
511         content = node->content;
512         if (!content)
513                 return;
514
515         /* Trim whitespace at beginning */
516         while (isspace(*content))
517                 content++;
518
519         /* Trim whitespace at end */
520         len = strlen(content);
521         while (len && isspace(content[len-1]))
522                 len--;
523
524         if (!len)
525                 return;
526
527         /* Don't print out the node name if it is "text" */
528         if (!strcmp(node->name, "text"))
529                 node = node->parent;
530
531         name = nodename(node, buffer, sizeof(buffer));
532
533         entry(name, len, content);
534 }
535
536 static void traverse(xmlNode *root);
537
538 static void traverse_properties(xmlNode *node)
539 {
540         xmlAttr *p;
541
542         for (p = node->properties; p; p = p->next)
543                 traverse(p->children);
544 }
545
546 static void visit(xmlNode *n)
547 {
548         visit_one_node(n);
549         traverse_properties(n);
550         traverse(n->children);
551 }
552
553 static void traverse(xmlNode *root)
554 {
555         xmlNode *n;
556
557         for (n = root; n; n = n->next) {
558                 /* XML from libdivecomputer: 'dive' per new dive */
559                 if (!strcmp(n->name, "dive")) {
560                         dive_start();
561                         visit(n);
562                         dive_end();
563                         continue;
564                 }
565
566                 /*
567                  * At least both libdivecomputer and Suunto
568                  * agree on "sample".
569                  *
570                  * Well - almost. Ignore case.
571                  */
572                 if (!strcasecmp(n->name, "sample")) {
573                         sample_start();
574                         visit(n);
575                         sample_end();
576                         continue;
577                 }
578
579                 /* Anything else - just visit it and recurse */
580                 visit(n);
581         }
582 }
583
584 void parse_xml_file(const char *filename)
585 {
586         xmlDoc *doc;
587
588         doc = xmlReadFile(filename, NULL, 0);
589         if (!doc) {
590                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
591                 return;
592         }
593
594         dive_start();
595         traverse(xmlDocGetRootElement(doc));
596         dive_end();
597         xmlFreeDoc(doc);
598         xmlCleanupParser();
599 }
600
601 void parse_xml_init(void)
602 {
603         LIBXML_TEST_VERSION
604 }