forked from hdczsf/51degrees.go
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path51Degrees.c
5800 lines (5302 loc) · 196 KB
/
51Degrees.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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#include <assert.h>
#include "51Degrees.h"
#include "city.h"
/* *********************************************************************
* This Source Code Form is copyright of 51Degrees Mobile Experts Limited.
* Copyright 2015 51Degrees Mobile Experts Limited, 5 Charlotte Close,
* Caversham, Reading, Berkshire, United Kingdom RG4 7BY
*
* This Source Code Form is the subject of the following patent
* applications, owned by 51Degrees Mobile Experts Limited of 5 Charlotte
* Close, Caversham, Reading, Berkshire, United Kingdom RG4 7BY:
* European Patent Application No. 13192291.6; and
* United States Patent Application Nos. 14/085,223 and 14/085,301.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0.
*
* If a copy of the MPL was not distributed with this file, You can obtain
* one at http://mozilla.org/MPL/2.0/.
*
* This Source Code Form is "Incompatible With Secondary Licenses", as
* defined by the Mozilla Public License, v. 2.0.
********************************************************************** */
/**
* \cond
* PROBLEM METHODS
* \endcond
*/
/* Change snprintf to the Microsoft version */
#ifdef _MSC_VER
#define snprintf _snprintf
#define strdup _strdup
#endif
/* Define INT32_MAX if not defined */
#ifndef INT32_MAX
#define INT32_MAX 2147483647L
#endif
/**
* \cond
* DATA STRUCTURES USED ONLY BY FUNCTIONS IN THIS FILE
* \endcond
*/
/* Used for boolean results */
#define TRUE 1
#define FALSE 0
/* Ranges used when performing a numeric match */
const fiftyoneDegreesRange RANGES[] = {
{ 0, 10 },
{ 10, 100 },
{ 100, 1000 },
{ 1000, 10000 },
{ 10000, SHRT_MAX }
};
#define RANGES_COUNT sizeof(RANGES) / sizeof(fiftyoneDegreesRange)
const int16_t POWERS[] = { 1, 10, 100, 1000, 10000 };
#define POWERS_COUNT sizeof(POWERS) / sizeof(int16_t)
#define MIN_CACHE_SIZE 2
#define HTTP_PREFIX_UPPER "HTTP_"
/**
* Memory allocation functions.
*/
void *(FIFTYONEDEGREES_CALL_CONV *fiftyoneDegreesMalloc)(size_t __size) = malloc;
void *(FIFTYONEDEGREES_CALL_CONV *fiftyoneDegreesCalloc)(size_t __nmemb, size_t __size) = calloc;
void (FIFTYONEDEGREES_CALL_CONV *fiftyoneDegreesFree)(void *__ptr) = free;
/**
* DATASET MEMORY ALLOCATION SIZE MACROS
*/
#define SIZE_OF_ROOT_NODES(h) h.rootNodes.count * sizeof(fiftyoneDegreesNode*)
#define SIZE_OF_REQUIRED_PROPERTIES_ARRAY requiredPropertyCount * sizeof(char*)
#define SIZE_OF_FILE_NAME(fileName) sizeof(char) * (strlen(fileName) + 1)
#define SIZE_OF_COMPONENTS(h) h.components.count * sizeof(fiftyoneDegreesComponent*)
#define SIZE_OF_HTTP_HEADERS(count) count * sizeof(fiftyoneDegreesHttpHeader)
#define SIZE_OF_REQUIRED_PROPERTIES(count) count * sizeof(fiftyoneDegreesProperty*)
#define SIZE_OF_PROFILES_STRUCT_ARRAY(h) h.properties.count * sizeof(fiftyoneDegreesProfilesStructArray)
#define SIZE_OF_PROFILE_INDEXES_STRUCT(count) count * sizeof(fiftyoneDegreesProfileIndexesStruct)
/**
* WORKSET MEMORY ALLOCATION SIZE MACROS
*/
#define SIZE_OF_WORKSET_POOL sizeof(fiftyoneDegreesWorksetPool)
#define SIZE_OF_POOL_WORKSETS(size) size * sizeof(fiftyoneDegreesWorkset*)
#define SIZE_OF_WORKSET sizeof(fiftyoneDegreesWorkset)
#define SIZE_OF_WORKSET_INPUT(h) (h.maxUserAgentLength + 1) * sizeof(char)
#define SIZE_OF_WORKSET_SIGLIST_ITEMS(h) h.maxSignaturesClosest * sizeof(fiftyoneDegreesLinkedSignatureListItem)
#define SIZE_OF_WORKSET_NODES(h) h.maxUserAgentLength * sizeof(const fiftyoneDegreesNode*)
#define SIZE_OF_WORKSET_USED_NODES(h) h.maxUserAgentLength + 1
#define SIZE_OF_WORKSET_SIG_AS_STRING(h) (h.maxUserAgentLength + 1) * sizeof(char)
#define SIZE_OF_WORKSET_VALUES(h) h.maxValues * sizeof(const fiftyoneDegreesValue*)
#define SIZE_OF_WORKSET_IMPORTANT_HEADERS(count) count * sizeof(fiftyoneDegreesHttpHeaderWorkset)
#define SIZE_OF_WORKSET_PROFILES(h) h.components.count * sizeof(const fiftyoneDegreesProfile*)
#define SIZE_OF_WORKSET_TARGET_USERAGENT_ARRAY(h) (h.maxUserAgentLength + 1) * sizeof(byte)
/**
* CACHE MEMORY ALLOCATION SIZE MACROS
*/
#define SIZE_OF_CACHE sizeof(fiftyoneDegreesResultsetCache)
#define SIZE_OF_CACHE_RESULTSETS(c) c * (sizeof(fiftyoneDegreesResultset))
#define SIZE_OF_CACHE_TARGET_USER_AGENTS(c, h) c * SIZE_OF_WORKSET_TARGET_USERAGENT_ARRAY(h)
#define SIZE_OF_CACHE_PROFILES(c, h) c * SIZE_OF_WORKSET_PROFILES(h)
/**
* \cond
* DATA SET FILE AND MEMORY METHODS
* \endcond
*/
/**
* \cond
* Provides a safe way to advance a pointer by the specified amount of bytes.
* Designed for a continuous allocated memory space where pointer is advanced
* consecutively. Requires the maximum number of bytes in the continuous
* memory space to be provided to carry out of bounds check.
*
* If -1 is supplied as the maximum number of bytes in the continuous memory
* space the check is ignored.
*
* Prior to calling this function for the first time make sure the pointer is
* set to the first byte of the allocated continuous memory space.
*
* @param pointer is the pointer to the current byte. Gets incremented by the
number of bytes provided in advanceBy.
* @param lastByte pointer to the last valid byte in the memory space. A
corrupt memory response is return if this is exceeded.
* @param advanceBy number of bytes to advance the pointer by.
* @return fiftyoneDegreesDataSetInitStatus stating the result of the
* current advance operation. Codes other than
* DATA_SET_INIT_STATUS_SUCCESS indicate there is a problem.
* \endcond
*/
static fiftyoneDegreesDataSetInitStatus advancePointer(byte **pointer,
const byte *lastByte,
long advanceBy) {
if (pointer == NULL || *pointer == NULL) {
return DATA_SET_INIT_STATUS_CORRUPT_DATA;
}
*pointer += advanceBy;
if (*pointer > lastByte) {
return DATA_SET_INIT_STATUS_POINTER_OUT_OF_BOUNDS;
}
return DATA_SET_INIT_STATUS_SUCCESS;
}
/**
* \cond
* Returns the total size of signatures in bytes.
* @param dataSet with headers initialised.
* @return the total size of signatures in bytes.
* \endcond
*/
static int32_t getSizeOfSignature(fiftyoneDegreesDataSet *dataSet) {
return (dataSet->header.signatureProfilesCount * sizeof(int32_t)) +
sizeof(byte) +
sizeof(int32_t) +
sizeof(int32_t) +
sizeof(byte);
}
/**
* \cond
* Returns the start offset for the signature structures.
* @param dataSet with headers initialised.
( @return the start offset for the signature structures.
* \endcond
*/
static int32_t getSignatureStartOfStruct(fiftyoneDegreesDataSet *dataSet) {
return (dataSet->header.signatureProfilesCount * sizeof(int32_t));
}
/**
* \cond
* Returns true if the header already exists in the list of headers.
* @param dataSet that already contains headers
* @param headerOffset to the string containing the name of the header
* @return true if the header exists, otherwise false
* \endcond
*/
static byte doesHeaderExist(fiftyoneDegreesDataSet *dataSet, int32_t headerOffset) {
int index;
for (index = 0; index < dataSet->httpHeadersCount; index++) {
if (headerOffset == dataSet->httpHeaders[index].headerNameOffset) {
return TRUE;
}
}
return FALSE;
}
/**
* \cond
* Returns the string offset for the HTTP header index of the component.
* @param component pointer to the compoent whose header is needed
* @param index of the header name needed
* @return the offset in the strings structure to the header namer
* \endcond
*/
static int32_t getComponentHeaderOffset(const fiftyoneDegreesComponent *component, int index) {
int32_t *first = (int32_t*)((byte*)component + sizeof(fiftyoneDegreesComponent));
return first[index];
}
/**
* \cond
* Reads the root nodes into the dataset from memory.
*
* @param current source pointer to continuous memory space containing decompressed
* 51Degrees pattern data file.
* @param dataSet to be initialised with data from the provided pointer to
* memory location.
* return dataset initialisation status.
* \endcond
*/
static fiftyoneDegreesDataSetInitStatus readRootNodesFromMemory(
int32_t *rootNodeOffsets,
fiftyoneDegreesDataSet *dataSet) {
int32_t index;
dataSet->rootNodes = (const fiftyoneDegreesNode**)
fiftyoneDegreesMalloc(SIZE_OF_ROOT_NODES(dataSet->header));
if (dataSet->rootNodes == NULL) {
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
for (index = 0; index < dataSet->header.rootNodes.count; index++) {
dataSet->rootNodes[index] = (fiftyoneDegreesNode*)(dataSet->nodes + rootNodeOffsets[index]);
}
return DATA_SET_INIT_STATUS_SUCCESS;
}
/**
* \cond
* Creates a list of unique HTTP header components. This is necessary because
* each component can have several HTTP headers associated with it that are
* useful for the purposes of device detection.
*
* This function populates the list of unique HTTP headers that are important
* for device detection. Function advances pointer to the current position.
*
* Function is shared between functions that initialise data file from memory
* and function that reds in data from file.
*
* @param current modifiable pointer to the current position within the
* continuous memory space containing decompressed 51Degrees pattern
* data file.
* @param dataSet to store the header list in.
* @param currentPosition of the pointer in bytes.
* @param maxPosition maximum allowed position of the pointer in bytes.
* Corresponds to the size in bytes that the adat file loaded into
* memory occupies.
* @return dataset initialisation status.
* \endcond
*/
static fiftyoneDegreesDataSetInitStatus readComponents(
fiftyoneDegreesDataSet *dataSet) {
byte *current = (byte*)dataSet->componentsData;
int index, httpHeaderIndex, httpHeadersCount = 0;
int32_t httpHeaderOffset;
// Allocate the memory needed for the components array.
dataSet->components = (const fiftyoneDegreesComponent**)fiftyoneDegreesMalloc(
SIZE_OF_COMPONENTS(dataSet->header));
if (dataSet->components == NULL) {
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
// Set pointers to each of the components in the array.
for (index = 0; index < dataSet->header.components.count; index++) {
dataSet->components[index] = (const fiftyoneDegreesComponent*)current;
current += sizeof(fiftyoneDegreesComponent) + (size_t)(dataSet->components[index]->httpHeaderCount * sizeof(int32_t));
httpHeadersCount += dataSet->components[index]->httpHeaderCount;
}
// Now create a list of unique HTTP headers which will be used to identify
// which headers should be checked when an array of multiple headers is
// passed for detection.
dataSet->httpHeaders = (fiftyoneDegreesHttpHeader*)fiftyoneDegreesMalloc(SIZE_OF_HTTP_HEADERS(httpHeadersCount));
if (dataSet->httpHeaders == NULL) {
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
dataSet->httpHeadersCount = 0;
for (index = 0; index < dataSet->header.components.count; index++) {
for (httpHeaderIndex = 0; httpHeaderIndex < dataSet->components[index]->httpHeaderCount; httpHeaderIndex++) {
httpHeaderOffset = getComponentHeaderOffset(dataSet->components[index], httpHeaderIndex);
if (doesHeaderExist(dataSet, httpHeaderOffset) == FALSE) {
(dataSet->httpHeaders + dataSet->httpHeadersCount)->headerNameOffset = httpHeaderOffset;
(dataSet->httpHeaders + dataSet->httpHeadersCount)->headerName =
(char*)&(fiftyoneDegreesGetString(dataSet, httpHeaderOffset)->firstByte);
dataSet->httpHeadersCount++;
}
}
}
return DATA_SET_INIT_STATUS_SUCCESS;
}
/**
* \cond
* Provides a safe way of initialising the new dataset with properties from the
* old dataset. Safeguards against future changes to the data file and
* data file structure.
*
* The new dataset is created with exactly the same set of properties as found
* within the old dataset.
*
* If the new data file does not obtain one or more property(ies) that the old
* dataset was initialised with, then these properties will not be
* initialised in the new dataset.
*
* Similarly, properties that are present in the new data file but are not
* in the old data file will not be initialised.
*
* It is up to the caller to to verify that all of the required properties have
* been initialised.
*
* @param oldDataSet the dataset to retrieve required property names. Not NULL.
* @param newDataSet the dataset to initialise properties in. Not NULL.
* \endcond
*/
static fiftyoneDegreesDataSetInitStatus setPropertiesFromExistingDataset(
const fiftyoneDegreesDataSet *oldDataSet,
fiftyoneDegreesDataSet *newDataSet) {
int32_t index, propertyIndex, count;
int16_t requiredPropertyLength;
const char *requiredPropertyName;
const fiftyoneDegreesAsciiString *propertyName;
const fiftyoneDegreesProperty *requiredProperty;
count = oldDataSet->requiredPropertyCount;
newDataSet->requiredPropertyCount = 0;
newDataSet->requiredProperties =
(const fiftyoneDegreesProperty**)fiftyoneDegreesMalloc(count * sizeof(const fiftyoneDegreesProperty*));
if (newDataSet->requiredProperties == NULL) {
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
// For each property in the old dataset:
for (propertyIndex = 0; propertyIndex < count; propertyIndex++) {
// Get current property, property length and property name.
requiredProperty = oldDataSet->requiredProperties[propertyIndex];
requiredPropertyName = fiftyoneDegreesGetPropertyName(oldDataSet, requiredProperty);
requiredPropertyLength = (int16_t)strlen(requiredPropertyName);
// For each of the available properties in the new dataset:
for (index = 0; index < newDataSet->header.properties.count; index++) {
// Get name of the current property of the new data set.
propertyName =
fiftyoneDegreesGetString(newDataSet, (newDataSet->properties + index)->nameOffset);
// Compare the two properties byte values and lengths.
if (requiredPropertyLength == propertyName->length - 1 &&
memcmp(requiredPropertyName, &propertyName->firstByte, requiredPropertyLength) == 0) {
*(newDataSet->requiredProperties + newDataSet->requiredPropertyCount) =
(newDataSet->properties + index);
newDataSet->requiredPropertyCount++;
break;
}
}
}
return DATA_SET_INIT_STATUS_SUCCESS;
}
/**
* \cond
* Initialises the provider with the provided dataset using the given
* cache and pool sizes.
* @param provider to initialise.
* @param dataSet to create cache and pool from.
* @param poolSize of the new pool.
* @param cacheSize of the new cache.
* @returns fiftyoneDegreesDataSetInitStatus indicates whether the init
* was successful.
* \endcond
*/
fiftyoneDegreesDataSetInitStatus initProvider(
fiftyoneDegreesProvider *provider,
fiftyoneDegreesDataSet *dataSet,
int poolSize,
int cacheSize) {
fiftyoneDegreesWorksetPool *newPool;
fiftyoneDegreesResultsetCache *cache;
// Create a new cache for the pool to use if a value was provided.
if (cacheSize > 0) {
cache = fiftyoneDegreesResultsetCacheCreate(dataSet, cacheSize);
if (cache == NULL) {
fiftyoneDegreesDataSetFree(dataSet);
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
}
else {
cache = NULL;
}
// Create a new active pool for the provider.
newPool = (fiftyoneDegreesWorksetPool*)fiftyoneDegreesWorksetPoolCreate(
dataSet, cache, poolSize);
if (newPool == NULL) {
fiftyoneDegreesResultsetCacheFree(cache);
fiftyoneDegreesDataSetFree(dataSet);
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
// Set a link between the new pool and the provider. Used to check if the
// pool can be freed when the last work set is handed back.
newPool->provider = provider;
#ifndef FIFTYONEDEGREES_NO_THREADING
// Replace the lock and signal pointers with the ones from the provider.
newPool->lockPtr = &provider->lock;
newPool->signalPtr = &provider->signal;
#endif
// Switch the active pool for the provider to the newly created one.
provider->activePool = newPool;
return DATA_SET_INIT_STATUS_SUCCESS;
}
static fiftyoneDegreesDataSetInitStatus reloadCommon(
fiftyoneDegreesProvider *provider,
fiftyoneDegreesDataSet *newDataSet) {
fiftyoneDegreesDataSetInitStatus status;
// Maintain a reference to the current pool in case it can be freed.
const fiftyoneDegreesWorksetPool *oldPool =
(const fiftyoneDegreesWorksetPool*)provider->activePool;
// Initialise the new dataset with the same properties as the old one.
status = setPropertiesFromExistingDataset(oldPool->dataSet, newDataSet);
if (status != DATA_SET_INIT_STATUS_SUCCESS) {
fiftyoneDegreesDataSetFree(newDataSet);
return status;
}
#ifndef FIFTYONEDEGREES_NO_THREADING
FIFTYONEDEGREES_MUTEX_LOCK(&provider->lock);
#endif
// Initialise the new provider with a pool and cache.
status = initProvider(provider, newDataSet,
oldPool->size, oldPool->cache != NULL ? oldPool->cache->total : 0);
if (status != DATA_SET_INIT_STATUS_SUCCESS) {
fiftyoneDegreesDataSetFree(newDataSet);
}
// If the old pool is ready to be freed then do so.
else if (oldPool->available == oldPool->size) {
fiftyoneDegreesWorksetPoolCacheDataSetFree(
(fiftyoneDegreesWorksetPool*)oldPool);
}
#ifndef FIFTYONEDEGREES_NO_THREADING
FIFTYONEDEGREES_MUTEX_UNLOCK(&provider->lock);
#endif
return status;
}
/**
* \cond
* Reads the various entities from the provided continuous memory location into
* the provided dataset.
*
* For most entities within the dataset it is sufficient to set the address
* of the pointer to the first element to the corresponding place within the
* provided memory space. This allows to avoid most of the additional memory
* allocations used in the init from file methods as the space is already
* allocated and contains data in the right format.
*
* @param source pointer to continuous memory space containing decompressed
* 51Degrees pattern data file.
* @param dataSet to be initialised with data from the provided pointer to
* continuous memory space.
* @param length number of bytes that the file occupies in memory.
* Also corresponds to the last byte within the continuous memory
* space.
* @return dataset initialisation status.
* \endcond
*/
static fiftyoneDegreesDataSetInitStatus readDataSetFromMemoryLocation(
const void *source,
fiftyoneDegreesDataSet *dataSet,
long length) {
fiftyoneDegreesDataSetInitStatus status = DATA_SET_INIT_STATUS_SUCCESS;
byte *current = (byte*)source;
const byte *lastByte = (byte*)source + length;
// Copy the bytes that form the header from the start of the file to the
// data set pointer provided.
if (memcpy((void*)(&dataSet->header), current, sizeof(fiftyoneDegreesDataSetHeader)) != dataSet) {
return DATA_SET_INIT_STATUS_CORRUPT_DATA;
}
status = advancePointer(¤t, lastByte, sizeof(fiftyoneDegreesDataSetHeader));
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
/* Check the version of the data file */
if (dataSet->header.versionMajor != 3 ||
dataSet->header.versionMinor != 2) {
return DATA_SET_INIT_STATUS_INCORRECT_VERSION;
}
dataSet->strings = (const byte*)current;
status = advancePointer(¤t, lastByte, dataSet->header.strings.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->componentsData = (const byte*)current;
status = readComponents(dataSet);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
status = advancePointer(¤t, lastByte, dataSet->header.components.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->maps = (const fiftyoneDegreesMap*)current;
status = advancePointer(¤t, lastByte, dataSet->header.maps.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->properties = (const fiftyoneDegreesProperty*)current;
status = advancePointer(¤t, lastByte, dataSet->header.properties.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->values = (const fiftyoneDegreesValue*)current;
status = advancePointer(¤t, lastByte, dataSet->header.values.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->profiles = (const byte*)current;
status = advancePointer(¤t, lastByte, dataSet->header.profiles.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->signatures = (const byte*)current;
status = advancePointer(¤t, lastByte, dataSet->header.signatures.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->signatureNodeOffsets = (const int32_t*)current;
status = advancePointer(¤t, lastByte, dataSet->header.signatureNodeOffsets.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->nodeRankedSignatureIndexes = (const int32_t*)current;
status = advancePointer(¤t, lastByte, dataSet->header.nodeRankedSignatureIndexes.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->rankedSignatureIndexes = (const int32_t*)current;
status = advancePointer(¤t, lastByte, dataSet->header.rankedSignatureIndexes.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->nodes = (const byte*)current;
status = advancePointer(¤t, lastByte, dataSet->header.nodes.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
status = readRootNodesFromMemory((int32_t*)current, dataSet);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
status = advancePointer(¤t, lastByte, dataSet->header.rootNodes.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
dataSet->profileOffsets = (const fiftyoneDegreesProfileOffset*)current;
status = advancePointer(¤t, lastByte, dataSet->header.profileOffsets.length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) return status;
/* Check that the current pointer equals the last byte */
if (current != lastByte) {
return DATA_SET_INIT_STATUS_POINTER_OUT_OF_BOUNDS;
}
/* Set some of the constant fields */
dataSet->sizeOfSignature = getSizeOfSignature(dataSet);
dataSet->signatureStartOfStruct = getSignatureStartOfStruct(dataSet);
return DATA_SET_INIT_STATUS_SUCCESS;
}
/**
* \cond
* Initialises an array with the size equal to the number of properties, each
* one containing a pointer to an empty array with the size equal to the
* number of values for the corresponding property.
* @param dataSet pointer to a 51Degrees data set.
* \endcond
*/
static void ensureValueProfilesSet(fiftyoneDegreesDataSet *dataSet) {
fiftyoneDegreesProperty *property;
int propertyIndex, valuesCount;
// Allocate an array element for each property.
dataSet->valuePointersArray =
(fiftyoneDegreesProfilesStructArray*)fiftyoneDegreesMalloc(SIZE_OF_PROFILES_STRUCT_ARRAY(dataSet->header));
for (propertyIndex = 0; propertyIndex < dataSet->header.properties.count; propertyIndex++) {
property = (fiftyoneDegreesProperty*)(dataSet->properties + (int32_t)propertyIndex);
valuesCount = property->lastValueIndex - property->firstValueIndex + 1;
// Set the initialised flag to 0;
dataSet->valuePointersArray[propertyIndex].initialised = 0;
// Allocate an array element for each value of the current property.
dataSet->valuePointersArray[propertyIndex].profilesStructs =
(fiftyoneDegreesProfileIndexesStruct*)fiftyoneDegreesMalloc(SIZE_OF_PROFILE_INDEXES_STRUCT(valuesCount));
#ifndef FIFTYONEDEGREES_NO_THREADING
FIFTYONEDEGREES_MUTEX_CREATE(dataSet->valuePointersArray[propertyIndex].lock);
#endif
}
}
/**
* \cond
* Initialises the provided dataset with data from the provided pointer to the
* continuous memory space containing decompressed 51Degreees pattern device
* data.
*
* Remember to free dataset if status is not success.
*
* @param dataSet to be initialised with data from the provided pointer to
* memory location.
* @param source pointer to continuous memory space containing decompressed
* 51Degrees pattern data file. Not NULL.
* @param length number of bytes that the file occupies in memory.
* @return dataset initialisation status.
* \endcond
*/
static fiftyoneDegreesDataSetInitStatus initFromMemory(
fiftyoneDegreesDataSet *dataSet,
const void *source,
long length) {
fiftyoneDegreesDataSetInitStatus status;
if (source == NULL) {
return DATA_SET_INIT_STATUS_NULL_POINTER;
}
// Read the data set from the memory source.
status = readDataSetFromMemoryLocation(source, dataSet, length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) {
return status;
}
// For memory resident data files there is no path to file on disk.
dataSet->fileName = NULL;
// Set the prefixed upper headers to NULL as they may not be
// needed. If they are initialised later then the memory can
// be freed when the data set is destroyed.
dataSet->prefixedUpperHttpHeaders = NULL;
// Initialise the memory for the properties and values structures
// which point to profiles structures.
ensureValueProfilesSet(dataSet);
return status;
}
/**
* \cond
* Sets the data set file name by copying the file name string provided into
* newly allocated memory in the data set.
*
* @param dataSet whose file name field needs to be set.
* @param fileName string to use as the file name.
* @return dataset initialisation status.
* \endcond
*/
static fiftyoneDegreesDataSetInitStatus setDataSetFileName(
fiftyoneDegreesDataSet *dataSet,
const char *fileName) {
dataSet->fileName = (const char*)fiftyoneDegreesMalloc(SIZE_OF_FILE_NAME(fileName));
if (dataSet->fileName == NULL) {
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
memcpy((char*)dataSet->fileName, (char*)fileName, strlen(fileName) + 1);
return DATA_SET_INIT_STATUS_SUCCESS;
}
/**
* \cond
* Initialises the provided dataset from the file path supplied. The memory
* required is allocated by the method and is also marked to be released when
* the data set is freed.
*
* @param fileName path to data file that should be used for initialisation.
* @param dataSet pointer to the dataset structure to be initialised.
* @return dataset initialisation status.
* \endcond
*/
static fiftyoneDegreesDataSetInitStatus initFromFile(
fiftyoneDegreesDataSet *dataSet,
const char *fileName) {
FILE *inputFilePtr;
long fileSize;
fiftyoneDegreesDataSetInitStatus status;
// Open the file and hold on to the pointer.
#ifndef _MSC_FULL_VER
inputFilePtr = fopen(fileName, "rb");
#else
/* If using Microsoft use the fopen_s method to avoid warning */
if (fopen_s(&inputFilePtr, fileName, "rb") != 0) {
return DATA_SET_INIT_STATUS_FILE_NOT_FOUND;
}
#endif
// If the file didn't open return not found.
if (inputFilePtr == NULL) {
return DATA_SET_INIT_STATUS_FILE_NOT_FOUND;
}
// Find the length of the file by moving to the end.
if (fseek(inputFilePtr, 0, SEEK_END) != 0) {
return DATA_SET_INIT_STATUS_CORRUPT_DATA;
}
fileSize = ftell(inputFilePtr);
if (fileSize <= 0) {
return DATA_SET_INIT_STATUS_CORRUPT_DATA;
}
// Read the file into memory in a single continuous memory space.
if (fseek(inputFilePtr, 0, SEEK_SET) != 0) {
return DATA_SET_INIT_STATUS_CORRUPT_DATA;
}
dataSet->memoryToFree = (byte*)fiftyoneDegreesMalloc(fileSize);
if (dataSet->memoryToFree == NULL) {
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
if (fread((byte*)dataSet->memoryToFree, fileSize, 1, inputFilePtr) != 1) {
return DATA_SET_INIT_STATUS_CORRUPT_DATA;
}
fclose(inputFilePtr);
// Initialises the data set using the memory just allocated.
status = initFromMemory(dataSet, dataSet->memoryToFree, fileSize);
if (status != DATA_SET_INIT_STATUS_SUCCESS) {
fiftyoneDegreesFree((void*)dataSet->memoryToFree);
return status;
}
// Set the file name of the data set.
return setDataSetFileName(dataSet, fileName);
}
/**
* \cond
* Creates a new dataset, pool and cache using the same configuration options
* as the current data set, pool and cache associated with the provider. The
* data file which the provider was initialised with is used to create the
* new data set. The exisitng data set, pool and cache are marked to be freed
* if worksets are being used by other threads, or if no work sets are in use
* they are freed immediately.
* @param provider pointer to the provider whose data set should be reloaded
* @return fiftyoneDegreesDataSetInitStatus indicating the result of the reload
* operation.
* \endcond
*/
fiftyoneDegreesDataSetInitStatus fiftyoneDegreesProviderReloadFromFile(
fiftyoneDegreesProvider *provider) {
fiftyoneDegreesDataSetInitStatus status = DATA_SET_INIT_STATUS_NOT_SET;
fiftyoneDegreesDataSet *newDataSet;
// Allocate memory for a new data set.
newDataSet = (fiftyoneDegreesDataSet*)fiftyoneDegreesMalloc(sizeof(fiftyoneDegreesDataSet));
if (newDataSet == NULL) {
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
// Initialise the new data set with the properties of the current one.
status = initFromFile(newDataSet, provider->activePool->dataSet->fileName);
if (status != DATA_SET_INIT_STATUS_SUCCESS) {
fiftyoneDegreesFree(newDataSet);
return status;
}
// Reload common components.
status = reloadCommon(provider, newDataSet);
if (status != DATA_SET_INIT_STATUS_SUCCESS) {
fiftyoneDegreesDataSetFree(newDataSet);
}
return status;
}
/**
* \cond
* Creates a new dataset, pool and cache using the same configuration options
* as the current data set, pool and cache associated with the provider. The
* memory located at the source pointer is used to create the new data set.
* The exisitng data set, pool and cache are marked to be freed if worksets are
* being used by other threads, or if no work sets are in use they are freed
* immediately.
* Important: The memory pointed to by source will NOT be freed by 51Degrees
* when the associated data set is freed. The caller is responsible for
* releasing the memory. If 51Degrees should release the memory then the
* caller should set the memoryToFree field of the data set associated with
* the returned pool to source. 51Degrees will then free this memory when the
* pool, data set and cache are freed after the last work set is returned to
* the pool.
* @param provider pointer to the provider whose data set should be reloaded
* @param source pointer to the dataset held in memory.
* @param length number of bytes that the file occupies in memory.
* @return fiftyoneDegreesDataSetInitStatus indicating the result of the reload
* operation.
* \endcond
*/
fiftyoneDegreesDataSetInitStatus fiftyoneDegreesProviderReloadFromMemory(
fiftyoneDegreesProvider *provider,
void *source,
long length) {
fiftyoneDegreesDataSetInitStatus status = DATA_SET_INIT_STATUS_NOT_SET;
fiftyoneDegreesDataSet *newDataSet = NULL;
// Allocate memory for a new data set.
newDataSet = (fiftyoneDegreesDataSet*)fiftyoneDegreesMalloc(sizeof(fiftyoneDegreesDataSet));
if (newDataSet == NULL) {
return DATA_SET_INIT_STATUS_INSUFFICIENT_MEMORY;
}
// Initialise the new data set with the data pointed to by source.
status = initFromMemory(newDataSet, source, length);
if (status != DATA_SET_INIT_STATUS_SUCCESS) {
fiftyoneDegreesFree((void*)newDataSet);
return status;
}
// Set the full data set pointer to NULL to indicate that when this
// new data set is release the memory shouldn't be freed by 51Degrees.
newDataSet->memoryToFree = NULL;
// Reload common components.
status = reloadCommon(provider, newDataSet);
if (status != DATA_SET_INIT_STATUS_SUCCESS) {
fiftyoneDegreesDataSetFree(newDataSet);
}
return status;
}
/**
* \cond
* METHODS TO RETURN ELEMENTS OF THE DATA SET
* \endcond
*/
/**
* \cond
* Returns a pointer to the ascii string at the byte offset provided
* @param dataSet pointer to the data set
* @param offset to the ascii string required
* @return a pointer to the AsciiString at the offset
* \endcond
*/
const fiftyoneDegreesAsciiString* fiftyoneDegreesGetString(const fiftyoneDegreesDataSet *dataSet, int32_t offset) {
return (const fiftyoneDegreesAsciiString*)(dataSet->strings + offset);
}
/**
* \cond
* Returns a pointer to the profile at the index provided
* @param dataSet pointer to the data set
* @param index of the profile required
* @return pointer to the profile at the index
* \endcond
*/
static fiftyoneDegreesProfile* getProfileByIndex(const fiftyoneDegreesDataSet *dataSet, int32_t index) {
return (fiftyoneDegreesProfile*)(dataSet->profiles + (dataSet->profileOffsets + index)->offset);
}
/**
* \cond
* Gets the index of the property provided from the dataset
* @param dataSet pointer to the data set containing the property
* @param property pointer to the property
* @return the index of the property
* \endcond
*/
static int32_t getPropertyIndex(const fiftyoneDegreesDataSet *dataSet, const fiftyoneDegreesProperty *property) {
return (int32_t)(property - dataSet->properties);
}
/**
* \cond
* Gets the http header name at the index provided.
* @param dataset pointer to an initialised dataset
* @param index of the http header required
* @param httpHeader pointer to memory to place the http header name
* @param size of the memory allocated for the name
* @return the number of bytes written for the http header
* \endcond
*/
int32_t fiftyoneDegreesGetHttpHeaderName(const fiftyoneDegreesDataSet *dataSet, int httpHeaderIndex, char *httpHeader, int size) {
const fiftyoneDegreesHttpHeader *uniqueHttpHeader;
const fiftyoneDegreesAsciiString *name;
int written = 0;
if (httpHeaderIndex >= 0 &&
httpHeaderIndex < dataSet->httpHeadersCount) {
uniqueHttpHeader = dataSet->httpHeaders + httpHeaderIndex;
name = fiftyoneDegreesGetString(dataSet, uniqueHttpHeader->headerNameOffset);
if (name->length <= size) {
memcpy(
httpHeader,
(char*)(&name->firstByte),
name->length);
written = name->length;
}
}
return written;
}
/**
* \cond
* Gets the required property name at the index provided.
* @param dataset pointer to an initialised dataset
* @param index of the property required
* @param propertyName pointer to memory to place the property name
* @param size of the memory allocated for the name
* @return the number of bytes written for the property, zero if the property
* does not exist at the index
* \endcond
*/
int32_t fiftyoneDegreesGetRequiredPropertyName(const fiftyoneDegreesDataSet *dataSet, int requiredPropertyIndex, char *propertyName, int size) {
const fiftyoneDegreesProperty *property;
const fiftyoneDegreesAsciiString *name;
int written = 0;
if (requiredPropertyIndex >= 0 &&
requiredPropertyIndex < dataSet->requiredPropertyCount) {
property = dataSet->requiredProperties[requiredPropertyIndex];
name = fiftyoneDegreesGetString(dataSet, property->nameOffset);
if (name->length <= size) {
memcpy(
propertyName,
(char*)(&name->firstByte),
name->length);
written = name->length;
}
}
return written;
}
/**
* \cond
* Gets the required property index of the property provided, or -1 if the
* property is not available in the dataset.
* @param dataset pointer to an initialised dataset
* @param propertyName pointer to the name of the property required
* @return the index of the property, or -1 if the property does not exist
* \endcond
*/
int32_t fiftyoneDegreesGetRequiredPropertyIndex(const fiftyoneDegreesDataSet *dataSet, const char *propertyName) {
int index;
const char *currentPropertyName;
for (index = 0; index < dataSet->requiredPropertyCount; index++) {
currentPropertyName = fiftyoneDegreesGetPropertyName(
dataSet,
dataSet->requiredProperties[index]);
if (strcmp(currentPropertyName, propertyName) == 0) {
return index;
}
}
return -1;
}
/**
* \cond
* Sets the values character array to the values of the required property
* provided. If the values character array is too small then only the values
* that can be fitted in are added.
* @param ws pointer to a workset configured with the match results
* @param requiredPropertyIndex index of the required property
* @param values pointer to allocated memory to store the values
* @param size the size of the values memory
* @return the number of characters written to the values memory
* \endcond
*/
int32_t fiftyoneDegreesGetValues(fiftyoneDegreesWorkset *ws, int32_t requiredPropertyIndex, char *values, int32_t size) {
int valueIndex;
int sizeNeeded = 0;
char *currentPosition = (char*)values;
const fiftyoneDegreesAsciiString *value;
fiftyoneDegreesSetValues(ws, requiredPropertyIndex);
for (valueIndex = 0; valueIndex < ws->valuesCount; valueIndex++) {
value = fiftyoneDegreesGetString(ws->dataSet, ws->values[valueIndex]->nameOffset);
sizeNeeded += value->length;
if (sizeNeeded <= size) {
// Add a value seperator if this isn't the first value in the list.
if (valueIndex > 0) {
*currentPosition = '|';
currentPosition++;
}
// Copy the value string to the values memory at the current position
// appending a seperator or a end of string byte depending on the
// remaining characters. Take one from the length because we don't
// need the 0 string terminator.
memcpy(currentPosition, (char*)&(value->firstByte), value->length - 1);