]> git.tdb.fi Git - ext/subsurface.git/blob - uemis.c
Fix uemis parser to work with base64 data that isn't a multiple of 3
[ext/subsurface.git] / uemis.c
1 /*
2  * uemis.c
3  *
4  * UEMIS SDA file importer
5  * AUTHOR:  Dirk Hohndel - Copyright 2011
6  *
7  * Licensed under the MIT license.
8  */
9
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #define __USE_XOPEN
16 #include <time.h>
17 #include <regex.h>
18
19 #include "dive.h"
20 #include "uemis.h"
21
22 /*
23  * following code is based on code found in at base64.sourceforge.net/b64.c
24  * AUTHOR:         Bob Trower 08/04/01
25  * COPYRIGHT:      Copyright (c) Trantor Standard Systems Inc., 2001
26  * NOTE:           This source code may be used as you wish, subject to
27  *                 the MIT license.
28  */
29 /*
30  * Translation Table to decode (created by Bob Trower)
31  */
32 static const char cd64[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
33
34 /*
35  * decodeblock -- decode 4 '6-bit' characters into 3 8-bit binary bytes
36  */
37 static void decodeblock( unsigned char in[4], unsigned char out[3] ) {
38         out[ 0 ] = (unsigned char ) (in[0] << 2 | in[1] >> 4);
39         out[ 1 ] = (unsigned char ) (in[1] << 4 | in[2] >> 2);
40         out[ 2 ] = (unsigned char ) (((in[2] << 6) & 0xc0) | in[3]);
41 }
42
43 /*
44  * decode a base64 encoded stream discarding padding, line breaks and noise
45  */
46 static void decode( uint8_t *inbuf, uint8_t *outbuf, int inbuf_len ) {
47         uint8_t in[4], out[3], v;
48         int i,len,indx_in=0,indx_out=0;
49
50         while (indx_in < inbuf_len) {
51                 for (len = 0, i = 0; i < 4 && (indx_in < inbuf_len); i++ ) {
52                         v = 0;
53                         while ((indx_in < inbuf_len) && v == 0) {
54                                 v = inbuf[indx_in++];
55                                 v = ((v < 43 || v > 122) ? 0 : cd64[ v - 43 ]);
56                                 if (v)
57                                         v = ((v == '$') ? 0 : v - 61);
58                         }
59                         if (indx_in < inbuf_len) {
60                                 len++;
61                                 if (v)
62                                         in[i] = (v - 1);
63                         }
64                         else
65                                 in[i] = 0;
66                 }
67                 if( len ) {
68                         decodeblock( in, out );
69                         for( i = 0; i < len - 1; i++ )
70                                 outbuf[indx_out++] = out[i];
71                 }
72         }
73 }
74 /* end code from Bob Trower */
75
76 /* small helper functions */
77 /* simpleregex allocates (and reallocates) the found buffer
78  * don't forget to free it when you are done
79  */
80 static int simpleregex(char *buffer, char *regex, char **found) {
81         int status;
82         regex_t re;
83         regmatch_t match[5];
84
85         if (regcomp(&re, regex, 0) !=0) {
86                 fprintf(stderr,"internal error, regex failed!\n");
87                 exit(1);
88         }
89         status = regexec(&re,buffer,5,match,0);
90         if(status == 0) {
91                 *found = realloc(*found,match[1].rm_eo-match[1].rm_so + 1);
92                 strncpy(*found,buffer+match[1].rm_so,match[1].rm_eo-match[1].rm_so);
93                 (*found)[match[1].rm_eo-match[1].rm_so] = '\0';
94         }
95         return(status == 0);
96 }
97
98 /* read in line of arbitrary length (important for SDA files that can
99  * have lines that are tens of kB long
100  * don't forget to free it when you are done
101  */
102 #define MYGETL_INCR 1024
103 static char * mygetline(FILE * f) {
104         size_t size = 0;
105         size_t len  = 0;
106         char * buf  = NULL;
107
108         do {
109                 size += MYGETL_INCR;
110                 if ((buf = realloc(buf,size)) == NULL)
111                         break;
112                 fgets(buf+len,MYGETL_INCR,f);
113                 len = strlen(buf);
114         } while (!feof(f) && buf[len-1]!='\n');
115         return buf;
116 }
117
118 /* text matching, used to build very poor man's XML parser */
119 int matchit(FILE *infd, char *regex, char *typeregex, char **found) {
120         char *buffer;
121
122         while (!feof(infd)) {
123                 buffer = mygetline(infd);
124                 if (buffer && simpleregex(buffer,regex,found)) {
125                         buffer = mygetline(infd);
126                         if (buffer && simpleregex(buffer,typeregex,found)) {
127                                 return 1;
128                         }
129                 }
130         }
131         return 0;
132 }
133
134 /*
135  * pressure_to_depth: In centibar. And when converting to
136  * depth, I'm just going to always use saltwater, because I
137  * think "true depth" is just stupid. From a diving standpoint,
138  * "true depth" is pretty much completely pointless, unless
139  * you're doing some kind of underwater surveying work.
140  *
141  * So I give water depths in "pressure depth", always assuming
142  * salt water. So one atmosphere per 10m.
143  */
144 static int pressure_to_depth(uint16_t value)
145 {
146         double atm, cm;
147
148         atm = (value / 100.0) / 1.01325;
149         cm = 100 * atm + 0.5;
150         return( (cm > 0) ? 10 * (long)cm : 0);
151 }
152
153 /*
154  * convert the base64 data blog
155  */
156 int uemis_convert_base64(char *base64, uint8_t **data) {
157         int len,datalen;
158
159         len = strlen(base64);
160         datalen = (len/4 + 1)*3;
161         if (datalen < 0x123+0x25) {
162                 /* less than header + 1 sample??? */
163                 fprintf(stderr,"suspiciously short data block\n");
164         }
165         *data = malloc(datalen);
166         if (! *data) {
167                 datalen = 0;
168                 fprintf(stderr,"Out of memory\n");
169                 goto bail;
170         }
171         decode(base64, *data, len);
172
173         if (memcmp(*data,"Dive\01\00\00",7))
174                 fprintf(stderr,"Missing Dive100 header\n");
175
176 bail:
177         return datalen;
178 }
179
180 /*
181  * parse uemis base64 data blob into struct dive
182  */
183 static void parse_divelog_binary(char *base64, struct dive **divep) {
184         int datalen;
185         int i;
186         uint8_t *data;
187         struct sample *sample;
188         struct dive *dive = *divep;
189
190         datalen = uemis_convert_base64(base64, &data);
191
192         /* first byte of divelog data is at offset 0x123 */
193         i = 0x123;
194         while ((i < datalen) && (*(uint16_t *)(data+i))) {
195                 /* it seems that a dive_time of 0 indicates the end of the valid readings */
196                 /* the SDA usually records more samples after the end of the dive --
197                  * we want to discard those, but not cut the dive short; sadly the dive
198                  * duration in the header is a) in minutes and b) up to 3 minutes short */
199                 if (*(uint16_t *)(data+i) > dive->duration.seconds + 180)
200                         break;
201                 sample = prepare_sample(divep);
202                 sample->time.seconds = *(uint16_t *)(data+i);
203                 sample->depth.mm = pressure_to_depth(*(uint16_t *)(data+i+2));
204                 sample->temperature.mkelvin = (*(uint16_t *)(data+i+4) * 100) + 273150;
205                 sample->cylinderpressure.mbar= *(uint16_t *)(data+i+23) * 10;
206                 sample->cylinderindex = *(uint8_t *)(data+i+22);
207                 finish_sample(*divep, sample);
208                 i += 0x25;
209         }
210         dive->duration.seconds = sample->time.seconds - 1;
211         return;
212 }
213
214 /* parse a single file
215  * TODO: we don't report any errors when the parse fails - we simply don't add them to the list
216  */
217 void
218 parse_uemis_file(char *divelogfilename) {
219         char *found=NULL;
220         struct tm tm;
221         struct dive *dive;
222
223         FILE *divelogfile = fopen(divelogfilename,"r");
224
225         dive = alloc_dive();
226
227         if (! matchit(divelogfile,"val key=\"date\"","<ts>\\([^<]*\\)</ts>",&found)) {
228                 /* some error handling */
229                 goto bail;
230         }
231         strptime(found, "%Y-%m-%dT%H:%M:%S", &tm);
232         dive->when = utc_mktime(&tm);
233         if (! matchit(divelogfile,"<val key=\"duration\">",
234                         "<float>\\([0-9.]*\\)</float>", &found)) {
235                 /* some error handling */
236                 goto bail;
237         }
238         dive->duration.seconds = 60.0 * atof(found);
239
240         if (! matchit(divelogfile,"<val key=\"depth\">",
241                         "<int>\\([0-9.]*\\)</int>", &found)) {
242                 /* some error handling */
243                 goto bail;
244         }
245         dive->maxdepth.mm = pressure_to_depth(atoi(found));
246
247         if (! matchit(divelogfile,"<val key=\"file_content\">",
248                         ">\\([a-zA-Z0-9+/=]*\\)<", &found)) {
249                 /* some error handling */
250                 goto bail;
251         }
252         parse_divelog_binary(found,&dive);
253         record_dive(dive);
254 bail:
255         if (found)
256                 free(found);
257 }
258
259 /*
260  * parse the two files extracted from the SDA
261  */
262 void
263 uemis_import() {
264         if (open_import_file_dialog("*.SDA","uemis Zurich SDA files",
265                                         &parse_uemis_file))
266                 report_dives();
267 }