]> git.tdb.fi Git - ext/subsurface.git/blob - parse-xml.c
Fix up small details in input/output
[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 static int suunto;
73 static int event_index, gasmix_index;
74
75 static time_t utc_mktime(struct tm *tm)
76 {
77         static const int mdays[] = {
78             0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
79         };
80         int year = tm->tm_year;
81         int month = tm->tm_mon;
82         int day = tm->tm_mday;
83
84         /* First normalize relative to 1900 */
85         if (year < 70)
86                 year += 100;
87         else if (year > 1900)
88                 year -= 1900;
89
90         /* Normalized to Jan 1, 1970: unix time */
91         year -= 70;
92
93         if (year < 0 || year > 129) /* algo only works for 1970-2099 */
94                 return -1;
95         if (month < 0 || month > 11) /* array bounds */
96                 return -1;
97         if (month < 2 || (year + 2) % 4)
98                 day--;
99         if (tm->tm_hour < 0 || tm->tm_min < 0 || tm->tm_sec < 0)
100                 return -1;
101         return (year * 365 + (year + 1) / 4 + mdays[month] + day) * 24*60*60UL +
102                 tm->tm_hour * 60*60 + tm->tm_min * 60 + tm->tm_sec;
103 }
104
105 static void divedate(char *buffer, void *_when)
106 {
107         int d,m,y;
108         time_t *when = _when;
109
110         if (sscanf(buffer, "%d.%d.%d", &d, &m, &y) == 3) {
111                 tm.tm_year = y;
112                 tm.tm_mon = m-1;
113                 tm.tm_mday = d;
114                 if (tm.tm_sec | tm.tm_min | tm.tm_hour)
115                         *when = utc_mktime(&tm);
116         }
117         free(buffer);
118 }
119
120 static void divetime(char *buffer, void *_when)
121 {
122         int h,m,s = 0;
123         time_t *when = _when;
124
125         if (sscanf(buffer, "%d:%d:%d", &h, &m, &s) >= 2) {
126                 tm.tm_hour = h;
127                 tm.tm_min = m;
128                 tm.tm_sec = s;
129                 if (tm.tm_year)
130                         *when = utc_mktime(&tm);
131         }
132         free(buffer);
133 }
134
135 /* Libdivecomputer: "2011-03-20 10:22:38" */
136 static void divedatetime(char *buffer, void *_when)
137 {
138         int y,m,d;
139         int hr,min,sec;
140         time_t *when = _when;
141
142         if (sscanf(buffer, "%d-%d-%d %d:%d:%d",
143                 &y, &m, &d, &hr, &min, &sec) == 6) {
144                 tm.tm_year = y;
145                 tm.tm_mon = m-1;
146                 tm.tm_mday = d;
147                 tm.tm_hour = hr;
148                 tm.tm_min = min;
149                 tm.tm_sec = sec;
150                 *when = utc_mktime(&tm);
151         }
152         free(buffer);
153 }
154
155 union int_or_float {
156         long i;
157         double fp;
158 };
159
160 enum number_type {
161         NEITHER,
162         INTEGER,
163         FLOAT
164 };
165
166 static enum number_type integer_or_float(char *buffer, union int_or_float *res)
167 {
168         char *end;
169         long val;
170         double fp;
171
172         /* Integer or floating point? */
173         val = strtol(buffer, &end, 10);
174         if (val < 0 || end == buffer)
175                 return NEITHER;
176
177         /* Looks like it might be floating point? */
178         if (*end == '.') {
179                 errno = 0;
180                 fp = strtod(buffer, &end);
181                 if (!errno) {
182                         res->fp = fp;
183                         return FLOAT;
184                 }
185         }
186
187         res->i = val;
188         return INTEGER;
189 }
190
191 static void pressure(char *buffer, void *_press)
192 {
193         pressure_t *pressure = _press;
194         union int_or_float val;
195
196         switch (integer_or_float(buffer, &val)) {
197         case FLOAT:
198                 /* Maybe it's in Bar? */
199                 if (val.fp < 500.0) {
200                         pressure->mbar = val.fp * 1000 + 0.5;
201                         break;
202                 }
203                 printf("Unknown fractional pressure reading %s\n", buffer);
204                 break;
205
206         case INTEGER:
207                 /*
208                  * Random integer? Maybe in PSI? Or millibar already?
209                  *
210                  * We assume that 5 bar is a ridiculous tank pressure,
211                  * so if it's smaller than 5000, it's in PSI..
212                  */
213                 if (val.i < 5000) {
214                         pressure->mbar = val.i * 68.95;
215                         break;
216                 }
217                 pressure->mbar = val.i;
218                 break;
219         default:
220                 printf("Strange pressure reading %s\n", buffer);
221         }
222         free(buffer);
223 }
224
225 static void depth(char *buffer, void *_depth)
226 {
227         depth_t *depth = _depth;
228         union int_or_float val;
229
230         switch (integer_or_float(buffer, &val)) {
231         /* All values are probably in meters */
232         case INTEGER:
233                 val.fp = val.i;
234                 /* fallthrough */
235         case FLOAT:
236                 depth->mm = val.fp * 1000 + 0.5;
237                 break;
238         default:
239                 printf("Strange depth reading %s\n", buffer);
240         }
241         free(buffer);
242 }
243
244 static void temperature(char *buffer, void *_temperature)
245 {
246         temperature_t *temperature = _temperature;
247         union int_or_float val;
248
249         switch (integer_or_float(buffer, &val)) {
250         /* C or F? Who knows? Let's default to Celsius */
251         case INTEGER:
252                 val.fp = val.i;
253                 /* Fallthrough */
254         case FLOAT:
255                 /* Ignore zero. It means "none" */
256                 if (!val.fp)
257                         break;
258                 /* Celsius */
259                 if (val.fp < 50.0) {
260                         temperature->mkelvin = (val.fp + 273.15) * 1000 + 0.5;
261                         break;
262                 }
263                 /* Fahrenheit */
264                 if (val.fp < 212.0) {
265                         temperature->mkelvin = (val.fp + 459.67) * 5000/9;
266                         break;
267                 }
268                 /* Kelvin or already millikelvin */
269                 if (val.fp < 1000.0)
270                         val.fp *= 1000;
271                 temperature->mkelvin = val.fp;
272                 break;
273         default:
274                 printf("Strange temperature reading %s\n", buffer);
275         }
276         free(buffer);
277 }
278
279 static void sampletime(char *buffer, void *_time)
280 {
281         int i;
282         int min, sec;
283         duration_t *time = _time;
284
285         i = sscanf(buffer, "%d:%d", &min, &sec);
286         switch (i) {
287         case 1:
288                 sec = min;
289                 min = 0;
290         /* fallthrough */
291         case 2:
292                 time->seconds = sec + min*60;
293                 break;
294         default:
295                 printf("Strange sample time reading %s\n", buffer);
296         }
297         free(buffer);
298 }
299
300 static void duration(char *buffer, void *_time)
301 {
302         sampletime(buffer, _time);
303 }
304
305 static void percent(char *buffer, void *_fraction)
306 {
307         fraction_t *fraction = _fraction;
308         union int_or_float val;
309
310         switch (integer_or_float(buffer, &val)) {
311         /* C or F? Who knows? Let's default to Celsius */
312         case INTEGER:
313                 val.fp = val.i;
314                 /* Fallthrough */
315         case FLOAT:
316                 if (val.fp <= 100.0)
317                         fraction->permille = val.fp * 10 + 0.5;
318                 break;
319
320         default:
321                 printf("Strange percentage reading %s\n", buffer);
322                 break;
323         }
324         free(buffer);
325 }
326
327 static void gasmix(char *buffer, void *_fraction)
328 {
329         /* libdivecomputer does negative percentages. */
330         if (*buffer == '-')
331                 return;
332         if (gasmix_index < MAX_MIXES)
333                 percent(buffer, _fraction);
334 }
335
336 static void gasmix_nitrogen(char *buffer, void *_gasmix)
337 {
338         /* Ignore n2 percentages. There's no value in them. */
339 }
340
341 #define MATCH(pattern, fn, dest) \
342         match(pattern, strlen(pattern), name, len, fn, buf, dest)
343
344 /* We're in samples - try to convert the random xml value to something useful */
345 static void try_to_fill_sample(struct sample *sample, const char *name, char *buf)
346 {
347         int len = strlen(name);
348
349         start_match("sample", name, buf);
350         if (MATCH(".sample.pressure", pressure, &sample->tankpressure))
351                 return;
352         if (MATCH(".sample.cylpress", pressure, &sample->tankpressure))
353                 return;
354         if (MATCH(".sample.depth", depth, &sample->depth))
355                 return;
356         if (MATCH(".sample.temp", temperature, &sample->temperature))
357                 return;
358         if (MATCH(".sample.temperature", temperature, &sample->temperature))
359                 return;
360         if (MATCH(".sample.sampletime", sampletime, &sample->time))
361                 return;
362         if (MATCH(".sample.time", sampletime, &sample->time))
363                 return;
364
365         nonmatch("sample", name, buf);
366 }
367
368 /*
369  * Crazy suunto xml. Look at how those o2/he things match up.
370  */
371 static int suunto_dive_match(struct dive *dive, const char *name, int len, char *buf)
372 {
373         return  MATCH(".o2pct", percent, &dive->gasmix[0].o2) ||
374                 MATCH(".hepct_0", percent, &dive->gasmix[0].he) ||
375                 MATCH(".o2pct_2", percent, &dive->gasmix[1].o2) ||
376                 MATCH(".hepct_1", percent, &dive->gasmix[1].he) ||
377                 MATCH(".o2pct_3", percent, &dive->gasmix[2].o2) ||
378                 MATCH(".hepct_2", percent, &dive->gasmix[2].he) ||
379                 MATCH(".o2pct_4", percent, &dive->gasmix[3].o2) ||
380                 MATCH(".hepct_3", percent, &dive->gasmix[3].he);
381 }
382
383 /* We're in the top-level dive xml. Try to convert whatever value to a dive value */
384 static void try_to_fill_dive(struct dive *dive, const char *name, char *buf)
385 {
386         int len = strlen(name);
387
388         start_match("dive", name, buf);
389         if (MATCH(".date", divedate, &dive->when))
390                 return;
391         if (MATCH(".time", divetime, &dive->when))
392                 return;
393         if (MATCH(".datetime", divedatetime, &dive->when))
394                 return;
395         if (MATCH(".maxdepth", depth, &dive->maxdepth))
396                 return;
397         if (MATCH(".meandepth", depth, &dive->meandepth))
398                 return;
399         if (MATCH(".divetime", duration, &dive->duration))
400                 return;
401         if (MATCH(".divetimesec", duration, &dive->duration))
402                 return;
403         if (MATCH(".surfacetime", duration, &dive->surfacetime))
404                 return;
405         if (MATCH(".airtemp", temperature, &dive->airtemp))
406                 return;
407         if (MATCH(".watertemp", temperature, &dive->watertemp))
408                 return;
409         if (MATCH(".cylinderstartpressure", pressure, &dive->beginning_pressure))
410                 return;
411         if (MATCH(".cylinderendpressure", pressure, &dive->end_pressure))
412                 return;
413
414         if (MATCH(".o2", gasmix, &dive->gasmix[gasmix_index].o2))
415                 return;
416         if (MATCH(".n2", gasmix_nitrogen, &dive->gasmix[gasmix_index]))
417                 return;
418         if (MATCH(".he", gasmix, &dive->gasmix[gasmix_index].he))
419                 return;
420
421         /* Suunto XML files are some crazy sh*t. */
422         if (suunto && suunto_dive_match(dive, name, len, buf))
423                 return;
424
425         nonmatch("dive", name, buf);
426 }
427
428 static unsigned int dive_size(int samples)
429 {
430         return sizeof(struct dive) + samples*sizeof(struct sample);
431 }
432
433 /*
434  * File boundaries are dive boundaries. But sometimes there are
435  * multiple dives per file, so there can be other events too that
436  * trigger a "new dive" marker and you may get some nesting due
437  * to that. Just ignore nesting levels.
438  */
439 static void dive_start(void)
440 {
441         unsigned int size;
442
443         if (dive)
444                 return;
445
446         alloc_samples = 5;
447         size = dive_size(alloc_samples);
448         dive = malloc(size);
449         if (!dive)
450                 exit(1);
451         memset(dive, 0, size);
452         memset(&tm, 0, sizeof(tm));
453 }
454
455 static char *generate_name(struct dive *dive)
456 {
457         int len;
458         struct tm *tm;
459         char buffer[256], *p;
460
461         tm = gmtime(&dive->when);
462
463         len = snprintf(buffer, sizeof(buffer),
464                 "%04d-%02d-%02d "
465                 "%02d:%02d:%02d "
466                 "(%d ft, %d min)",
467                 tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,
468                 tm->tm_hour, tm->tm_min, tm->tm_sec,
469                 to_feet(dive->maxdepth), dive->duration.seconds / 60);
470         p = malloc(len+1);
471         if (!p)
472                 exit(1);
473         memcpy(p, buffer, len+1);
474         return p;
475 }
476
477 static void sanitize_gasmix(struct dive *dive)
478 {
479         int i;
480
481         for (i = 0; i < MAX_MIXES; i++) {
482                 gasmix_t *mix = dive->gasmix+i;
483                 unsigned int o2, he;
484
485                 o2 = mix->o2.permille;
486                 he = mix->he.permille;
487
488                 /* Regular air: leave empty */
489                 if (!he) {
490                         if (!o2)
491                                 continue;
492                         /* 20.9% or 21% O2 is just air */
493                         if (o2 >= 209 && o2 <= 210) {
494                                 mix->o2.permille = 0;
495                                 continue;
496                         }
497                 }
498
499                 /* Sane mix? */
500                 if (o2 <= 1000 && he <= 1000 && o2+he <= 1000)
501                         continue;
502                 fprintf(stderr, "Odd gasmix: %d O2 %d He\n", o2, he);
503                 memset(mix, 0, sizeof(*mix));
504         }
505 }
506
507 static void dive_end(void)
508 {
509         if (!dive)
510                 return;
511         if (!dive->name)
512                 dive->name = generate_name(dive);
513         sanitize_gasmix(dive);
514         record_dive(dive);
515         dive = NULL;
516         gasmix_index = 0;
517 }
518
519 static void suunto_start(void)
520 {
521         suunto++;
522 }
523
524 static void suunto_end(void)
525 {
526         suunto--;
527 }
528
529 static void event_start(void)
530 {
531 }
532
533 static void event_end(void)
534 {
535         event_index++;
536 }
537
538 static void gasmix_start(void)
539 {
540 }
541
542 static void gasmix_end(void)
543 {
544         gasmix_index++;
545 }
546
547 static void sample_start(void)
548 {
549         int nr;
550
551         if (!dive)
552                 return;
553         nr = dive->samples;
554         if (nr >= alloc_samples) {
555                 unsigned int size;
556
557                 alloc_samples = (alloc_samples * 3)/2 + 10;
558                 size = dive_size(alloc_samples);
559                 dive = realloc(dive, size);
560                 if (!dive)
561                         return;
562         }
563         sample = dive->sample + nr;
564         memset(sample, 0, sizeof(*sample));
565         event_index = 0;
566 }
567
568 static void sample_end(void)
569 {
570         if (!dive)
571                 return;
572
573         if (sample->time.seconds > dive->duration.seconds) {
574                 if (sample->depth.mm)
575                         dive->duration = sample->time;
576         }
577
578         if (sample->depth.mm > dive->maxdepth.mm)
579                 dive->maxdepth.mm = sample->depth.mm;
580
581         sample = NULL;
582         dive->samples++;
583 }
584
585 static void entry(const char *name, int size, const char *raw)
586 {
587         char *buf = malloc(size+1);
588
589         if (!buf)
590                 return;
591         memcpy(buf, raw, size);
592         buf[size] = 0;
593         if (sample) {
594                 try_to_fill_sample(sample, name, buf);
595                 return;
596         }
597         if (dive) {
598                 try_to_fill_dive(dive, name, buf);
599                 return;
600         }
601 }
602
603 static const char *nodename(xmlNode *node, char *buf, int len)
604 {
605         if (!node || !node->name)
606                 return "root";
607
608         buf += len;
609         *--buf = 0;
610         len--;
611
612         for(;;) {
613                 const char *name = node->name;
614                 int i = strlen(name);
615                 while (--i >= 0) {
616                         unsigned char c = name[i];
617                         *--buf = tolower(c);
618                         if (!--len)
619                                 return buf;
620                 }
621                 node = node->parent;
622                 if (!node || !node->name)
623                         return buf;
624                 *--buf = '.';
625                 if (!--len)
626                         return buf;
627         }
628 }
629
630 #define MAXNAME 64
631
632 static void visit_one_node(xmlNode *node)
633 {
634         int len;
635         const unsigned char *content;
636         char buffer[MAXNAME];
637         const char *name;
638
639         content = node->content;
640         if (!content)
641                 return;
642
643         /* Trim whitespace at beginning */
644         while (isspace(*content))
645                 content++;
646
647         /* Trim whitespace at end */
648         len = strlen(content);
649         while (len && isspace(content[len-1]))
650                 len--;
651
652         if (!len)
653                 return;
654
655         /* Don't print out the node name if it is "text" */
656         if (!strcmp(node->name, "text"))
657                 node = node->parent;
658
659         name = nodename(node, buffer, sizeof(buffer));
660
661         entry(name, len, content);
662 }
663
664 static void traverse(xmlNode *root);
665
666 static void traverse_properties(xmlNode *node)
667 {
668         xmlAttr *p;
669
670         for (p = node->properties; p; p = p->next)
671                 traverse(p->children);
672 }
673
674 static void visit(xmlNode *n)
675 {
676         visit_one_node(n);
677         traverse_properties(n);
678         traverse(n->children);
679 }
680
681 /*
682  * I'm sure this could be done as some fancy DTD rules.
683  * It's just not worth the headache.
684  */
685 static struct nesting {
686         const char *name;
687         void (*start)(void), (*end)(void);
688 } nesting[] = {
689         { "dive", dive_start, dive_end },
690         { "SUUNTO", suunto_start, suunto_end },
691         { "sample", sample_start, sample_end },
692         { "SAMPLE", sample_start, sample_end },
693         { "event", event_start, event_end },
694         { "gasmix", gasmix_start, gasmix_end },
695         { NULL, }
696 };
697
698 static void traverse(xmlNode *root)
699 {
700         xmlNode *n;
701
702         for (n = root; n; n = n->next) {
703                 struct nesting *rule = nesting;
704
705                 do {
706                         if (!strcmp(rule->name, n->name))
707                                 break;
708                         rule++;
709                 } while (rule->name);
710
711                 if (rule->start)
712                         rule->start();
713                 visit(n);
714                 if (rule->end)
715                         rule->end();
716         }
717 }
718
719 void parse_xml_file(const char *filename)
720 {
721         xmlDoc *doc;
722
723         doc = xmlReadFile(filename, NULL, 0);
724         if (!doc) {
725                 fprintf(stderr, "Failed to parse '%s'.\n", filename);
726                 return;
727         }
728
729         dive_start();
730         traverse(xmlDocGetRootElement(doc));
731         dive_end();
732         xmlFreeDoc(doc);
733         xmlCleanupParser();
734 }
735
736 void parse_xml_init(void)
737 {
738         LIBXML_TEST_VERSION
739 }