forked from antirez/smaz
-
Notifications
You must be signed in to change notification settings - Fork 8
/
recipe.c
1668 lines (1523 loc) · 49.6 KB
/
recipe.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Compress a key value pair file according to a recipe.
The recipe indicates the type of each field.
For certain field types the precision or range of allowed
values can be specified to further aid compression.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <strings.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <math.h>
#include <time.h>
#include <dirent.h>
#include <sys/stat.h>
#include <dirent.h>
#ifdef ANDROID
#include <jni.h>
#include <android/log.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "libsmac", __VA_ARGS__))
#define C LOGI("%s:%d: checkpoint",__FILE__,__LINE__);
#else
#define LOGI(...)
#define C
#endif
#include "charset.h"
#include "visualise.h"
#include "arithmetic.h"
#include "packed_stats.h"
#include "smac.h"
#include "recipe.h"
#include "md5.h"
int encryptAndFragment(char *filename,int mtu,char *outputdir,char *publickeyhex);
int defragmentAndDecrypt(char *inputdir,char *outputdir,char *passphrase);
int recipe_create(char *input);
int xhtml_recipe_create(char *recipe_dir, char *input);
#ifdef ANDROID
time_t timegm(struct tm *tm)
{
time_t ret;
char *tz;
tz = getenv("TZ");
setenv("TZ", "", 1);
tzset();
ret = mktime(tm);
if (tz)
setenv("TZ", tz, 1);
else
unsetenv("TZ");
tzset();
return ret;
}
#endif
int recipe_parse_fieldtype(char *name)
{
if (!strcasecmp(name,"integer")) return FIELDTYPE_INTEGER;
if (!strcasecmp(name,"int")) return FIELDTYPE_INTEGER;
if (!strcasecmp(name,"float")) return FIELDTYPE_FLOAT;
if (!strcasecmp(name,"decimal")) return FIELDTYPE_FIXEDPOINT;
if (!strcasecmp(name,"fixedpoint")) return FIELDTYPE_FIXEDPOINT;
if (!strcasecmp(name,"boolean")) return FIELDTYPE_BOOLEAN;
if (!strcasecmp(name,"bool")) return FIELDTYPE_BOOLEAN;
if (!strcasecmp(name,"timeofday")) return FIELDTYPE_TIMEOFDAY;
if (!strcasecmp(name,"timestamp")) return FIELDTYPE_TIMEDATE;
if (!strcasecmp(name,"datetime")) return FIELDTYPE_TIMEDATE;
if (!strcasecmp(name,"magpitimestamp")) return FIELDTYPE_MAGPITIMEDATE;
if (!strcasecmp(name,"date")) return FIELDTYPE_DATE;
if (!strcasecmp(name,"latlong")) return FIELDTYPE_LATLONG;
if (!strcasecmp(name,"geopoint")) return FIELDTYPE_LATLONG;
if (!strcasecmp(name,"text")) return FIELDTYPE_TEXT;
if (!strcasecmp(name,"string")) return FIELDTYPE_TEXT;
if (!strcasecmp(name,"image")) return FIELDTYPE_TEXT;
if (!strcasecmp(name,"information")) return FIELDTYPE_TEXT;
if (!strcasecmp(name,"uuid")) return FIELDTYPE_UUID;
if (!strcasecmp(name,"magpiuuid")) return FIELDTYPE_MAGPIUUID;
if (!strcasecmp(name,"enum")) return FIELDTYPE_ENUM;
if (!strcasecmp(name,"multi")) return FIELDTYPE_MULTISELECT;
return -1;
}
char *recipe_field_type_name(int f)
{
switch(f) {
case FIELDTYPE_INTEGER: return "integer";
case FIELDTYPE_FLOAT: return "float";
case FIELDTYPE_FIXEDPOINT: return "fixedpoint";
case FIELDTYPE_BOOLEAN: return "boolean";
case FIELDTYPE_TIMEOFDAY: return "timeofday";
case FIELDTYPE_TIMEDATE: return "timestamp";
case FIELDTYPE_MAGPITIMEDATE: return "magpitimestamp";
case FIELDTYPE_DATE: return "date";
case FIELDTYPE_LATLONG: return "latlong";
case FIELDTYPE_TEXT: return "text";
case FIELDTYPE_UUID: return "uuid";
case FIELDTYPE_MAGPIUUID: return "magpiuuid";
default: return "unknown";
}
}
char recipe_error[2048]="No error.\n";
void recipe_free(struct recipe *recipe)
{
int i;
for(i=0;i<recipe->field_count;i++) {
if (recipe->fields[i].name) free(recipe->fields[i].name);
recipe->fields[i].name=NULL;
int e;
for(e=0;e<recipe->fields[i].enum_count;e++) {
if (recipe->fields[i].enum_values[e]) {
free(recipe->fields[i].enum_values[e]);
recipe->fields[i].enum_values[e]=NULL;
}
}
}
free(recipe);
}
int recipe_form_hash(char *recipe_file,unsigned char *formhash,
char *formname)
{
MD5_CTX md5;
unsigned char hash[16];
// Get basename of form for computing hash
char recipe_name[1024];
int start=0;
int end=strlen(recipe_file);
int i;
// Cut path from filename
for(i=0;recipe_file[i];i++) if (recipe_file[i]=='/') start=i+1;
// Cut .recipe from filename
if (end>strlen(".recipe"))
if (!strcasecmp(".recipe",&recipe_file[end-strlen(".recipe")]))
end=end-strlen(".recipe")-1;
int j=0;
for(i=start;i<=end;i++) recipe_name[j++]=recipe_file[i];
recipe_name[j]=0;
MD5_Init(&md5);
LOGI("Calculating recipe file formhash from '%s' (%d chars)\n",
recipe_name,(int)strlen(recipe_name));
MD5_Update(&md5,recipe_name,strlen(recipe_name));
MD5_Final(hash,&md5);
bcopy(hash,formhash,6);
if (formname) strcpy(formname,recipe_name);
return 0;
}
struct recipe *recipe_read(char *formname,char *buffer,int buffer_size)
{
if (buffer_size<1||buffer_size>1048576) {
snprintf(recipe_error,2048,"Recipe file empty or too large (>1MB).\n");
return NULL;
}
struct recipe *recipe=calloc(sizeof(struct recipe),1);
if (!recipe) {
snprintf(recipe_error,2048,"Allocation of recipe structure failed.\n");
return NULL;
}
// Get recipe hash
recipe_form_hash(formname,recipe->formhash,recipe->formname);
LOGI("recipe_read(): Computing formhash based on form name '%s'",formname);
int i;
int l=0;
int line_number=1;
char line[16384];
char name[16384],type[16384];
int min,max,precision;
char enumvalues[16384];
for(i=0;i<=buffer_size;i++) {
if (l>16380) {
snprintf(recipe_error,2048,"line:%d:Line too long.\n",line_number);
recipe_free(recipe); return NULL; }
if ((i==buffer_size)||(buffer[i]=='\n')||(buffer[i]=='\r')) {
if (recipe->field_count>1000) {
snprintf(recipe_error,2048,"line:%d:Too many field definitions (must be <=1000).\n",line_number);
recipe_free(recipe); return NULL;
}
// Process recipe line
line[l]=0;
if ((l>0)&&(line[0]!='#')) {
enumvalues[0]=0;
if (sscanf(line,"%[^:]:%[^:]:%d:%d:%d:%[^\n]",
name,type,&min,&max,&precision,enumvalues)>=5) {
int fieldtype=recipe_parse_fieldtype(type);
if (fieldtype==-1) {
char type1024[1024];
if (strlen(type)>1023) type[1023]=0;
bcopy(type,type1024,1024);
snprintf(recipe_error,2048,"line:%d:Unknown or misspelled field type '%s'.\n",line_number,type1024);
recipe_free(recipe); return NULL;
} else {
// Store parsed field
recipe->fields[recipe->field_count].name=strdup(name);
recipe->fields[recipe->field_count].type=fieldtype;
recipe->fields[recipe->field_count].minimum=min;
recipe->fields[recipe->field_count].maximum=max;
recipe->fields[recipe->field_count].precision=precision;
if (fieldtype==FIELDTYPE_ENUM||fieldtype==FIELDTYPE_MULTISELECT) {
char enum_value[1024];
int e=0;
int en=0;
int i;
for(i=0;i<=strlen(enumvalues);i++) {
if ((enumvalues[i]==',')||(enumvalues[i]==0)) {
// End of field
enum_value[e]=0;
if (en>=MAX_ENUM_VALUES) {
snprintf(recipe_error,2048,"line:%d:enum has too many values (max=32)\n",line_number);
recipe_free(recipe);
return NULL;
}
recipe->fields[recipe->field_count].enum_values[en]
=strdup(enum_value);
en++;
e=0;
} else {
// next character of field
enum_value[e++]=enumvalues[i];
}
}
if (en<1) {
snprintf(recipe_error,2048,"line:%d:Malformed enum field definition: must contain at least one value option.\n",line_number);
recipe_free(recipe); return NULL;
}
recipe->fields[recipe->field_count].enum_count=en;
}
recipe->field_count++;
}
} else {
snprintf(recipe_error,2048,"line:%d:Malformed field definition.\n",line_number);
recipe_free(recipe); return NULL;
}
}
line_number++; l=0;
} else {
line[l++]=buffer[i];
}
}
return recipe;
}
int recipe_load_file(char *filename,char *out,int out_size)
{
unsigned char *buffer;
int fd=open(filename,O_RDONLY);
if (fd==-1) {
snprintf(recipe_error,2048,"Could not open file '%s'\n",filename);
return -1;
}
struct stat stat;
if (fstat(fd, &stat) == -1) {
snprintf(recipe_error,2048,"Could not stat file '%s'\n",filename);
close(fd); return -1;
}
if (stat.st_size>out_size) {
snprintf(recipe_error,2048,"File '%s' is too long (must be <= %d bytes)\n",
filename,out_size);
close(fd); return -1;
}
buffer=mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (buffer==MAP_FAILED) {
snprintf(recipe_error,2048,"Could not memory map file '%s'\n",filename);
close(fd); return -1;
}
bcopy(buffer,out,stat.st_size);
munmap(buffer,stat.st_size);
close(fd);
return stat.st_size;
}
struct recipe *recipe_read_from_specification(char *xmlform_c)
{
int magpi_mode =0;
if (xmlform_c&&(!strncasecmp("<html",xmlform_c,5))) magpi_mode=1;
int r;
printf("start of form: '%c%c%c%c%c%c%c%c%c%c'\n",
xmlform_c[0],xmlform_c[1],xmlform_c[2],xmlform_c[3],xmlform_c[4],
xmlform_c[5],xmlform_c[6],xmlform_c[7],xmlform_c[8],xmlform_c[9]
);
char form_name[1024];
char form_version[1024];
char recipetext[65536];
int recipetextLen=65536;
char templatetext[1048576];
int templatetextLen=1048576;
printf("magpi_mode=%d\n",magpi_mode);
if (magpi_mode)
r=xhtmlToRecipe(xmlform_c,strlen(xmlform_c),
form_name,form_version,
recipetext,&recipetextLen,
templatetext,&templatetextLen);
else
r=xmlToRecipe(xmlform_c,strlen(xmlform_c),
form_name,form_version,
recipetext,&recipetextLen,
templatetext,&templatetextLen);
if (r<0) return NULL;
return recipe_read(form_name,recipetext,recipetextLen);
}
struct recipe *recipe_read_from_file(char *filename)
{
struct recipe *recipe=NULL;
unsigned char *buffer;
int fd=open(filename,O_RDONLY);
if (fd==-1) {
snprintf(recipe_error,2048,"Could not open recipe file '%s'\n",filename);
return NULL;
}
struct stat stat;
if (fstat(fd, &stat) == -1) {
snprintf(recipe_error,2048,"Could not stat recipe file '%s'\n",filename);
close(fd); return NULL;
}
buffer=mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (buffer==MAP_FAILED) {
snprintf(recipe_error,2048,"Could not memory map recipe file '%s'\n",filename);
close(fd); return NULL;
}
recipe=recipe_read(filename,(char *)buffer,stat.st_size);
munmap(buffer,stat.st_size);
close(fd);
if (recipe&&recipe->field_count==0) {
recipe_free(recipe);
snprintf(recipe_error,2048,"Recipe contains no field definitions\n");
return NULL;
}
return recipe;
}
int recipe_parse_boolean(char *b)
{
if (!b) return 0;
switch(b[0]) {
case 'y': case 'Y': case 't': case 'T': case '1':
return 1;
default:
return 0;
}
}
int recipe_decode_field(struct recipe *recipe,stats_handle *stats, range_coder *c,
int fieldnumber,char *value,int value_size)
{
int normalised_value;
int minimum;
int maximum;
int precision;
precision=recipe->fields[fieldnumber].precision;
switch (recipe->fields[fieldnumber].type) {
case FIELDTYPE_INTEGER:
minimum=recipe->fields[fieldnumber].minimum;
maximum=recipe->fields[fieldnumber].maximum;
normalised_value=range_decode_equiprobable(c,maximum-minimum+2);
if (normalised_value==(maximum-minimum+1)) {
// out of range value, so decode it as a string.
fprintf(stderr,"FIELDTYPE_INTEGER: Illegal value - decoding string representation.\n");
stats3_decompress_bits(c,(unsigned char *)value,&value_size,stats,NULL);
} else
sprintf(value,"%d",normalised_value+minimum);
return 0;
case FIELDTYPE_FLOAT:
{
// Sign
int sign = range_decode_equiprobable(c,2);
// Exponent
int exponent = range_decode_equiprobable(c,256)-128;
// Mantissa
int mantissa = 0;
int b;
b=range_decode_equiprobable(c,256); mantissa |= b<<16;
b=range_decode_equiprobable(c,256); mantissa |= b<<8;
b=range_decode_equiprobable(c,256); mantissa |= b<<0;
float f = mantissa*1.0/0xffffff;
if (sign) f=-f;
f = ldexp( f, exponent);
fprintf(stderr,"sign=%d, exp=%d, mantissa=%x, f=%f\n",
sign,exponent,mantissa,f);
sprintf(value,"%f",f);
return 0;
}
case FIELDTYPE_BOOLEAN:
normalised_value=range_decode_equiprobable(c,2);
sprintf(value,"%d",normalised_value);
return 0;
break;
case FIELDTYPE_MULTISELECT:
{
int k;
int vlen=0;
// Get bitmap of enum fields
for(k=0;k<recipe->fields[fieldnumber].enum_count;k++)
{
if (range_decode_equiprobable(c,2)) {
// Field value is present
if (vlen) {
value[vlen++]='|'; value[vlen]=0;
}
sprintf(&value[vlen],"%s",recipe->fields[fieldnumber].enum_values[k]);
vlen=strlen(value);
}
}
return 0;
break;
}
case FIELDTYPE_ENUM:
normalised_value=range_decode_equiprobable(c,recipe->fields[fieldnumber]
.enum_count);
if (normalised_value<0||normalised_value>=recipe->fields[fieldnumber].enum_count) {
printf("enum: range_decode_equiprobable returned illegal value %d for range %d..%d\n",
normalised_value,0,recipe->fields[fieldnumber].enum_count-1);
return -1;
}
sprintf(value,"%s",recipe->fields[fieldnumber].enum_values[normalised_value]);
printf("enum: decoding %s as %d of %d\n",
value,normalised_value,recipe->fields[fieldnumber].enum_count);
return 0;
break;
case FIELDTYPE_TEXT:
stats3_decompress_bits(c,(unsigned char *)value,&value_size,stats,NULL);
return 0;
case FIELDTYPE_TIMEDATE:
// time is 32-bit seconds since 1970.
// Format as yyyy-mm-ddThh:mm:ss+hh:mm
{
// SMAC has a bug with encoding large ranges, so break into smaller pieces
time_t t = 0;
t=range_decode_equiprobable(c,0x8000)<<16;
t|=range_decode_equiprobable(c,0x10000);
printf("TIMEDATE: decoding t=%d\n",(int)t);
struct tm tm;
// gmtime_r(&t,&tm);
localtime_r(&t,&tm);
sprintf(value,"%04d-%02d-%02dT%02d:%02d:%02d+00:00",
tm.tm_year+1900,tm.tm_mon+1,tm.tm_mday,
tm.tm_hour,tm.tm_min,tm.tm_sec);
return 0;
}
case FIELDTYPE_MAGPITIMEDATE:
// time encodes each field precisely, allowing years 0 - 9999
// Format as yyyy-mm-dd hh:mm:ss
{
// time_t t=range_decode_equiprobable(c,0x7fffffff);
struct tm tm;
bzero(&tm,sizeof(tm));
tm.tm_year=range_decode_equiprobable(c,10000);
tm.tm_mon=range_decode_equiprobable(c,12);
tm.tm_mday=range_decode_equiprobable(c,31);
tm.tm_hour=range_decode_equiprobable(c,25);
tm.tm_min=range_decode_equiprobable(c,60);
tm.tm_sec=range_decode_equiprobable(c,62);
sprintf(value,"%04d-%02d-%02d %02d:%02d:%02d",
tm.tm_year,tm.tm_mon+1,tm.tm_mday,
tm.tm_hour,tm.tm_min,tm.tm_sec);
return 0;
}
case FIELDTYPE_DATE:
// Date encoded using:
// normalised_value=y*372+(m-1)*31+(d-1);
// So year = value / 372 ...
{
if (precision==0) precision=22;
int minimum=0;
int maximum=10000*372;
maximum=maximum>> (22-precision);
int normalised_value = range_decode_equiprobable(c,maximum-minimum+1);
int year = normalised_value / 372;
int day_of_year = normalised_value - (year*372);
int month = day_of_year/31+1;
int day_of_month = day_of_year%31+1;
// American date format for Magpi
sprintf(value,"%02d-%02d-%04d",month,day_of_month,year);
return 0;
}
case FIELDTYPE_UUID:
{
int i,j=5;
sprintf(value,"uuid:");
for(i=0;i<16;i++)
{
int b=0;
if ((!recipe->fields[fieldnumber].precision)
||(i<recipe->fields[fieldnumber].precision))
b=range_decode_equiprobable(c,256);
switch(i) {
case 4: case 6: case 8: case 10:
value[j++]='-';
}
sprintf(&value[j],"%02x",b); j+=2;
value[j]=0;
}
return 0;
}
case FIELDTYPE_MAGPIUUID:
// 64bit hex followed by seconds since UNIX epoch?
{
int i,j=0;
value[0]=0;
for(i=0;i<8;i++)
{
int b=0;
b=range_decode_equiprobable(c,256);
sprintf(&value[j],"%02x",b); j+=2;
value[j]=0;
}
// 48 bits of milliseconds since unix epoch
long long timestamp=0;
for(i=0;i<6;i++) {
timestamp=timestamp<<8LL;
int b=range_decode_equiprobable(c,256);
timestamp|=b;
}
sprintf(&value[j],"-%lld",timestamp);
return 0;
}
case FIELDTYPE_LATLONG:
{
int ilat,ilon;
double lat,lon;
switch(recipe->fields[fieldnumber].precision) {
case 0: case 34:
ilat=range_decode_equiprobable(c,182*112000); ilat-=90*112000;
ilon=range_decode_equiprobable(c,361*112000); ilon-=180*112000;
lat=ilat/112000.0; lon=ilon/112000.0;
break;
case 16:
ilat=range_decode_equiprobable(c,182); ilat-=90;
ilon=range_decode_equiprobable(c,361); ilon-=180;
lat=ilat; lon=ilon;
break;
default:
sprintf(recipe_error,"Illegal LATLONG precision of %d bits. Should be 16 or 34.\n",recipe->fields[fieldnumber].precision);
return -1;
}
sprintf(value,"%.5f %.5f",lat,lon);
return 0;
}
default:
snprintf(recipe_error,2048,"Attempting decompression of unsupported field type of '%s'.\n",recipe_field_type_name(recipe->fields[fieldnumber].type));
return -1;
}
return 0;
}
int parseHexDigit(int c)
{
if (c>='0'&&c<='9') return c-'0';
if (c>='A'&&c<='F') return c-'A'+10;
if (c>='a'&&c<='f') return c-'a'+10;
return 0;
}
int parseHexByte(char *hex)
{
return (parseHexDigit(hex[0])<<4)|parseHexDigit(hex[1]);
}
int recipe_encode_field(struct recipe *recipe,stats_handle *stats, range_coder *c,
int fieldnumber,char *value)
{
int normalised_value;
int minimum;
int maximum;
int precision;
int h,m,s,d,y;
float lat,lon;
int ilat,ilon;
precision=recipe->fields[fieldnumber].precision;
switch (recipe->fields[fieldnumber].type) {
case FIELDTYPE_INTEGER:
normalised_value=atoi(value)-recipe->fields[fieldnumber].minimum;
minimum=recipe->fields[fieldnumber].minimum;
maximum=recipe->fields[fieldnumber].maximum;
if (maximum<=minimum) {
fprintf(stderr,"Illegal range: min=%d, max=%d\n",minimum,maximum);
LOGI("Illegal range: min=%d, max=%d\n",minimum,maximum);
return -1;
}
if (normalised_value<0||normalised_value>(maximum-minimum+1)) {
fprintf(stderr,"Illegal value: min=%d, max=%d, value=%d\n",
minimum,maximum,atoi(value));
LOGI("Illegal value: min=%d, max=%d, value=%d\n",
minimum,maximum,atoi(value));
range_encode_equiprobable(c,maximum-minimum+2,maximum-minimum+1);
int r=stats3_compress_append(c,(unsigned char *)value,strlen(value),stats,
NULL);
return r;
}
return range_encode_equiprobable(c,maximum-minimum+2,normalised_value);
case FIELDTYPE_FLOAT:
{
float f = atof(value);
int sign=0;
int exponent=0;
int mantissa=0;
if (f<0) { sign=1; f=-f; } else sign=0;
double m = frexp(f,&exponent);
mantissa = m * 0xffffff;
if (exponent<-127) exponent=-127;
if (exponent>127) exponent=127;
fprintf(stderr,"encoding sign=%d, exp=%d, mantissa=%x, f=%f\n",
sign,exponent,mantissa,atof(value));
// Sign
range_encode_equiprobable(c,2,sign);
// Exponent
range_encode_equiprobable(c,256,exponent+128);
// Mantissa
range_encode_equiprobable(c,256,(mantissa>>16)&0xff);
range_encode_equiprobable(c,256,(mantissa>>8)&0xff);
return range_encode_equiprobable(c,256,(mantissa>>0)&0xff);
}
case FIELDTYPE_FIXEDPOINT:
case FIELDTYPE_BOOLEAN:
normalised_value=recipe_parse_boolean(value);
minimum=0;
maximum=1;
return range_encode_equiprobable(c,maximum-minimum+1,normalised_value);
case FIELDTYPE_TIMEOFDAY:
if (sscanf(value,"%d:%d.%d",&h,&m,&s)<2) return -1;
// XXX - We don't support leap seconds
if (h<0||h>23||m<0||m>59||s<0||s>59) return -1;
normalised_value=h*3600+m*60+s;
minimum=0;
maximum=24*60*60;
if (precision==0) precision=17; // 2^16 < 24*60*60 < 2^17
if (precision<17) {
normalised_value=normalised_value >> (17 - precision);
minimum=minimum >> (17 - precision);
maximum=maximum >> (17 - precision);
maximum+=1; // make sure that normalised_value cannot = maximum
}
return range_encode_equiprobable(c,maximum-minimum+1,normalised_value);
case FIELDTYPE_TIMEDATE:
{
struct tm tm;
int tzh=0,tzm=0;
int r;
bzero(&tm,sizeof(tm));
if ((r=sscanf(value,"%d-%d-%dT%d:%d:%d.%*d+%d:%d",
&tm.tm_year,&tm.tm_mon,&tm.tm_mday,
&tm.tm_hour,&tm.tm_min,&tm.tm_sec,
&tzh,&tzm))<6) {
printf("r=%d\n",r);
return -1;
}
#if defined(__sgi) || defined(__sun)
#else
tm.tm_gmtoff=tzm*60+tzh*3600;
#endif
tm.tm_year-=1900;
tm.tm_mon-=1;
time_t t = mktime(&tm);
minimum=1;
maximum=0x7fffffff;
normalised_value=t;
int b;
b=range_encode_equiprobable(c,0x8000,t>>16);
b=range_encode_equiprobable(c,0x10000,t&0xffff);
printf("TIMEDATE: encoding t=%d\n",(int)t);
return b;
}
case FIELDTYPE_MAGPITIMEDATE:
{
struct tm tm;
// int tzh=0,tzm=0;
int r;
bzero(&tm,sizeof(tm));
if ((r=sscanf(value,"%d-%d-%d %d:%d:%d",
&tm.tm_year,&tm.tm_mon,&tm.tm_mday,
&tm.tm_hour,&tm.tm_min,&tm.tm_sec))<6) {
printf("r=%d\n",r);
return -1;
}
// Validate fields
if (tm.tm_year<0||tm.tm_year>9999) return -1;
if (tm.tm_mon<1||tm.tm_mon>12) return -1;
if (tm.tm_mday<1||tm.tm_mday>31) return -1;
if (tm.tm_hour<0||tm.tm_hour>24) return -1;
if (tm.tm_min<0||tm.tm_min>59) return -1;
if (tm.tm_sec<0||tm.tm_sec>61) return -1;
// Encode each field: requires about 40 bits, but safely encodes all values
// without risk of timezone munging on Android
range_encode_equiprobable(c,10000,tm.tm_year);
range_encode_equiprobable(c,12,tm.tm_mon-1);
range_encode_equiprobable(c,31,tm.tm_mday-1);
range_encode_equiprobable(c,25,tm.tm_hour);
range_encode_equiprobable(c,60,tm.tm_min);
return range_encode_equiprobable(c,62,tm.tm_sec);
}
case FIELDTYPE_DATE:
// ODK does YYYY/MM/DD
// Magpi does DD-MM-YYYY
// The different delimiter allows us to discern between the two
fprintf(stderr,"Parsing FIELDTYPE_DATE value '%s'\n",value);
if (sscanf(value,"%d/%d/%d",&y,&m,&d)==3) { }
else if (sscanf(value,"%d-%d-%d",&d,&m,&y)==3) { }
else return -1;
// XXX Not as efficient as it could be (assumes all months have 31 days)
if (y<1||y>9999||m<1||m>12||d<1||d>31) {
fprintf(stderr,"Invalid field value\n");
return -1;
}
normalised_value=y*372+(m-1)*31+(d-1);
minimum=0;
maximum=10000*372;
if (precision==0) precision=22; // 2^21 < maximum < 2^22
if (precision<22) {
normalised_value=normalised_value >> (22 - precision);
minimum=minimum >> (22 - precision);
maximum=maximum >> (22 - precision);
maximum+=1; // make sure that normalised_value cannot = maximum
}
return range_encode_equiprobable(c,maximum-minimum+1,normalised_value);
case FIELDTYPE_LATLONG:
// Allow space or comma between LAT and LONG
if ((sscanf(value,"%f %f",&lat,&lon)!=2)
&&(sscanf(value,"%f,%f",&lat,&lon)!=2))
return -1;
if (lat<-90||lat>90||lon<-180||lon>180) return -1;
ilat=lroundf(lat);
ilon=lroundf(lon);
ilat+=90; // range now 0..181 (for -90 to +90, inclusive)
ilon+=180; // range now 0..360 (for -180 to +180, inclusive)
if (precision==16) {
// gradicule resolution
range_encode_equiprobable(c,182,ilat);
return range_encode_equiprobable(c,361,ilon);
} else if (precision==0||precision==34) {
// ~1m resolution
ilat=lroundf(lat*112000);
ilon=lroundf(lon*112000);
ilat+=90*112000; // range now 0..181 (for -90 to +90, inclusive)
ilon+=180*112000; // range now 0..359 (for -179 to +180, inclusive)
// encode latitude
range_encode_equiprobable(c,182*112000,ilat);
return range_encode_equiprobable(c,361*112000,ilon);
} else
return -1;
case FIELDTYPE_MULTISELECT:
{
// Multiselect has labels for each item selected, with a pipe
// character in between. We encode each as a boolean using 1 bit.
unsigned long long bits=0;
int o=0;
// Generate bitmask of selected items
while (o<strlen(value)) {
char valuetext[1024];
int vtlen=0;
while (value[o]!='|'&&value[o]) {
if (vtlen<1000) valuetext[vtlen++]=value[o];
o++;
}
valuetext[vtlen]=0;
int v;
for(v=0;v<recipe->fields[fieldnumber].enum_count;v++)
if (!strcasecmp(valuetext,recipe->fields[fieldnumber].enum_values[v]))
break;
if (v<recipe->fields[fieldnumber].enum_count) bits|=(1<<v);
if (value[o]=='|') o++;
}
// Encode each checkbox using a single bit
for(o=0;o<recipe->fields[fieldnumber].enum_count;o++)
{
// Work out whether box is ticked
int n=((bits>>o)&1);
range_encode_equiprobable(c,2,n);
}
return 0;
break;
}
case FIELDTYPE_ENUM:
{
for(normalised_value=0;
normalised_value<recipe->fields[fieldnumber].enum_count;
normalised_value++) {
if (!strcasecmp(value,
recipe->fields[fieldnumber].enum_values[normalised_value]))
break;
}
if (normalised_value>=recipe->fields[fieldnumber].enum_count) {
sprintf(recipe_error,"Value '%s' is not in enum list for '%s'.\n",
value,
recipe->fields[fieldnumber].name);
return -1;
}
maximum=recipe->fields[fieldnumber].enum_count;
printf("enum: encoding %s as %d of %d\n",value,normalised_value,maximum);
return range_encode_equiprobable(c,maximum,normalised_value);
}
case FIELDTYPE_TEXT:
{
int before=c->bits_used;
// Trim to precision specified length if non-zero
if (recipe->fields[fieldnumber].precision>0) {
if (strlen(value)>recipe->fields[fieldnumber].precision)
value[recipe->fields[fieldnumber].precision]=0;
}
int r=stats3_compress_append(c,(unsigned char *)value,strlen(value),stats,
NULL);
printf("'%s' encoded in %d bits\n",value,c->bits_used-before);
if (r) return -1;
return 0;
}
case FIELDTYPE_MAGPIUUID:
// 64bit hex followed by milliseconds since UNIX epoch (48 bits to last us many centuries)
{
int i,j=0;
unsigned char uuid[8];
i=0;
for(i=0;i<16;i+=2) {
uuid[j]=parseHexByte(&value[i]);
range_encode_equiprobable(c,256,uuid[j++]);
}
long long timestamp=strtoll(&value[17],NULL,10);
timestamp&=0xffffffffffffLL;
for(i=0;i<6;i++) {
int b=(timestamp>>40LL)&0xff;
range_encode_equiprobable(c,256,b);
timestamp=timestamp<<8LL;
}
return 0;
}
case FIELDTYPE_UUID:
{
// Parse out the 128 bits (=16 bytes) of UUID, and encode as much as we have been asked.
// XXX Will accept all kinds of rubbish
int i,j=0;
unsigned char uuid[16];
i=0;
if (!strncasecmp(value,"uuid:",5)) i=5;
for(;value[i];i++) {
if (j==16) {j=17; break; }
if (value[i]!='-') {
uuid[j++]=parseHexByte(&value[i]);
i++;
}
}
if (j!=16) {
sprintf(recipe_error,"Malformed UUID field.\n");
return -1;
}
// write appropriate number of bytes
int precision=recipe->fields[fieldnumber].precision;
if (precision<1||precision>16) precision=16;
for(i=0;i<precision;i++) {
range_encode_equiprobable(c,256,uuid[i]);
}
return 0;
}
}
return -1;
}
struct recipe *recipe_find_recipe(char *recipe_dir,unsigned char *formhash)
{
DIR *dir=opendir(recipe_dir);
struct dirent *de;
if (!dir) return NULL;
while((de=readdir(dir))!=NULL)
{
if (strlen(de->d_name)>strlen(".recipe")) {
if (!strcasecmp(&de->d_name[strlen(de->d_name)-strlen(".recipe")],
".recipe"))
{
char recipe_path[1024];
snprintf(recipe_path,1024,"%s/%s",recipe_dir,de->d_name);
struct recipe *r=recipe_read_from_file(recipe_path);
if (0) fprintf(stderr,"Is %s a recipe?\n",recipe_path);
if (r) {
if (1) {
fprintf(stderr,"Considering form %s (formhash %02x%02x%02x%02x%02x%02x)\n",recipe_path,
r->formhash[0],r->formhash[1],r->formhash[2],
r->formhash[3],r->formhash[4],r->formhash[5]);
}
if (!memcmp(formhash,r->formhash,6)) {
return r;
}
recipe_free(r);
}
}
}
}
return NULL;
}
int recipe_decompress(stats_handle *h, char *recipe_dir,
unsigned char *in,int in_len, char *out, int out_size,
char *recipe_name)
{
if (!recipe_dir) {
snprintf(recipe_error,2048,"No recipe directory provided.\n");
LOGI("%s",recipe_error);
return -1;
}
if (!in) {
snprintf(recipe_error,2048,"No input provided.\n");
LOGI("%s",recipe_error);
return -1;
}
if (!out) {
snprintf(recipe_error,2048,"No output buffer provided.\n");
LOGI("%s",recipe_error);
return -1;
}
if (in_len>=1024) {
snprintf(recipe_error,2048,"Input must be <1KB.\n");
LOGI("%s",recipe_error);
return -1;
}
// Make new range coder with 1KB of space
range_coder *c=range_new_coder(1024);
// Point range coder bit stream to input buffer
bcopy(in,c->bit_stream,in_len);
c->bit_stream_length=in_len*8;
range_decode_prefetch(c);
// Read form id hash from the succinct data stream.
unsigned char formhash[6];
int i;
for(i=0;i<6;i++) formhash[i]=range_decode_equiprobable(c,256);
printf("formhash from succinct data message = %02x%02x%02x%02x%02x%02x\n",
formhash[0],formhash[1],formhash[2],
formhash[3],formhash[4],formhash[5]);
struct recipe *recipe=recipe_find_recipe(recipe_dir,formhash);
if (!recipe) {
snprintf(recipe_error,2048,"No recipe provided.\n");
LOGI("%s:%d: %s",__FILE__,__LINE__,recipe_error);
range_coder_free(c);
return -1;
}
snprintf(recipe_name,1024,"%s",recipe->formname);
int written=0;
int field;
for(field=0;field<recipe->field_count;field++)
{
int field_present=range_decode_equiprobable(c,2);
printf("%sdecompressing value for '%s'\n",
field_present?"":"not ",
recipe->fields[field].name);