xref: /btstack/platform/posix/btstack_tlv_posix.c (revision 077fecbb6ed539507f37505ebd8a5b00e01c55e9)
1 /*
2  * Copyright (C) 2017 BlueKitchen GmbH
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BLUEKITCHEN
21  * GMBH OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 #define BTSTACK_FILE__ "btstack_tlv_posix.c"
33 
34 #include "btstack_tlv.h"
35 #include "btstack_tlv_posix.h"
36 #include "btstack_debug.h"
37 #include "btstack_util.h"
38 #include "btstack_debug.h"
39 #include "string.h"
40 
41 #include <stdlib.h>
42 #include <string.h>
43 
44 
45 // Header:
46 // - Magic: 'BTstack'
47 // - Status:
48 //   - bits 765432: reserved
49 //	 - bits 10:     epoch
50 
51 // Entries
52 // - Tag: 32 bit
53 // - Len: 32 bit
54 // - Value: Len in bytes
55 
56 #define BTSTACK_TLV_HEADER_LEN 8
57 
58 #define MAX_TLV_VALUE_SIZE 2048
59 
60 static const char * btstack_tlv_header_magic = "BTstack";
61 
62 #define DUMMY_SIZE 4
63 typedef struct tlv_entry {
64 	void   * next;
65 	uint32_t tag;
66 	uint32_t len;
67 	uint8_t  value[DUMMY_SIZE];	// dummy size
68 } tlv_entry_t;
69 
70 static int btstack_tlv_posix_append_tag(btstack_tlv_posix_t * self, uint32_t tag, const uint8_t * data, uint32_t data_size){
71 
72 	if (!self->file) return 1;
73 
74 	log_info("append tag %04x, len %u", tag, data_size);
75 
76 	uint8_t header[8];
77 	big_endian_store_32(header, 0, tag);
78 	big_endian_store_32(header, 4, data_size);
79 	size_t written_header = fwrite(header, 1, sizeof(header), self->file);
80 	if (written_header != sizeof(header)) return 1;
81 	if (data_size > 0) {
82 		size_t written_value = fwrite(data, 1, data_size, self->file);
83 		if (written_value != data_size) return 1;
84 	}
85 	fflush(self->file);
86 	return 1;
87 }
88 
89 static tlv_entry_t * btstack_tlv_posix_find_entry(btstack_tlv_posix_t * self, uint32_t tag){
90 	btstack_linked_list_iterator_t it;
91 	btstack_linked_list_iterator_init(&it, &self->entry_list);
92 	while (btstack_linked_list_iterator_has_next(&it)){
93 		tlv_entry_t * entry = (tlv_entry_t*) btstack_linked_list_iterator_next(&it);
94 		if (entry->tag != tag) continue;
95 		return entry;
96 	}
97 	return NULL;
98 }
99 
100 /**
101  * Delete Tag
102  * @param tag
103  */
104 static void btstack_tlv_posix_delete_tag(void * context, uint32_t tag){
105 	btstack_tlv_posix_t * self = (btstack_tlv_posix_t *) context;
106 	btstack_linked_list_iterator_t it;
107 	btstack_linked_list_iterator_init(&it, &self->entry_list);
108 	while (btstack_linked_list_iterator_has_next(&it)){
109 		tlv_entry_t * entry = (tlv_entry_t*) btstack_linked_list_iterator_next(&it);
110 		if (entry->tag != tag) continue;
111 		btstack_linked_list_iterator_remove(&it);
112 		free(entry);
113 		btstack_tlv_posix_append_tag(self, tag, NULL, 0);
114 		return;
115 	}
116 }
117 
118 /**
119  * Get Value for Tag
120  * @param tag
121  * @param buffer
122  * @param buffer_size
123  * @returns size of value
124  */
125 static int btstack_tlv_posix_get_tag(void * context, uint32_t tag, uint8_t * buffer, uint32_t buffer_size){
126 	btstack_tlv_posix_t * self = (btstack_tlv_posix_t *) context;
127 	tlv_entry_t * entry = btstack_tlv_posix_find_entry(self, tag);
128 	// not found
129 	if (!entry) return 0;
130 	// return len if buffer = NULL
131 	if (!buffer) return entry->len;
132 	// otherwise copy data into buffer
133 	uint16_t bytes_to_copy = btstack_min(buffer_size, entry->len);
134 	memcpy(buffer, &entry->value[0], bytes_to_copy);
135 	return bytes_to_copy;
136 }
137 
138 /**
139  * Store Tag
140  * @param tag
141  * @param data
142  * @param data_size
143  */
144 static int btstack_tlv_posix_store_tag(void * context, uint32_t tag, const uint8_t * data, uint32_t data_size){
145 	btstack_tlv_posix_t * self = (btstack_tlv_posix_t *) context;
146 
147 	// enforce arbitrary max value size
148 	btstack_assert(data_size <= MAX_TLV_VALUE_SIZE);
149 
150 	// remove old entry
151 	tlv_entry_t * old_entry = btstack_tlv_posix_find_entry(self, tag);
152 	if (old_entry){
153 		btstack_linked_list_remove(&self->entry_list, (btstack_linked_item_t *) old_entry);
154 		free(old_entry);
155 	}
156 
157 	// create new entry
158 	uint32_t entry_size = sizeof(tlv_entry_t) - DUMMY_SIZE + data_size;
159 	tlv_entry_t * new_entry = (tlv_entry_t *) malloc(entry_size);
160 	if (!new_entry) return 0;
161 	memset(new_entry, 0, entry_size);
162 	new_entry->tag = tag;
163 	new_entry->len = data_size;
164 	memcpy(&new_entry->value[0], data, data_size);
165 
166 	// append new entry
167 	btstack_linked_list_add(&self->entry_list, (btstack_linked_item_t *) new_entry);
168 
169 	// write new tag
170 	btstack_tlv_posix_append_tag(self, tag, data, data_size);
171 
172 	return 0;
173 }
174 
175 // returns 0 on success
176 static int btstack_tlv_posix_read_db(btstack_tlv_posix_t * self){
177 	// open file
178 	log_info("open db %s", self->db_path);
179     self->file = fopen(self->db_path,"r+");
180     uint8_t header[BTSTACK_TLV_HEADER_LEN];
181     if (self->file){
182     	// checker header
183 	    size_t objects_read = fread(header, 1, BTSTACK_TLV_HEADER_LEN, self->file );
184 	    int file_valid = 0;
185 	    if (objects_read == BTSTACK_TLV_HEADER_LEN){
186 	    	if (memcmp(header, btstack_tlv_header_magic, strlen(btstack_tlv_header_magic)) == 0){
187 		    	log_info("BTstack Magic Header found");
188 		    	// read entries
189 		    	while (true){
190 					uint8_t entry[8];
191 					size_t 	entries_read = fread(entry, 1, sizeof(entry), self->file);
192 					if (entries_read == 0){
193 						// EOF, we're good
194 						file_valid = 1;
195 						break;
196 					}
197 					if (entries_read != sizeof(entry)) break;
198 
199                     uint32_t tag = big_endian_read_32(entry, 0);
200                     uint32_t len = big_endian_read_32(entry, 4);
201 
202                     // arbitrary safety check: values <= MAX_TLV_VALUE_SIZE
203                     if (len > MAX_TLV_VALUE_SIZE) break;
204 
205                     // create new entry for regular tag
206                     tlv_entry_t * new_entry = NULL;
207                     if (len > 0) {
208                         new_entry = (tlv_entry_t *) malloc(sizeof(tlv_entry_t) - DUMMY_SIZE + len);
209                         if (!new_entry) return 0;
210                         new_entry->tag = tag;
211                         new_entry->len = len;
212 
213                         // read
214                         size_t value_read = fread(&new_entry->value[0], 1, len, self->file);
215                         if (value_read != len) break;
216                     }
217 
218                     // remove old entry
219                     tlv_entry_t * old_entry = btstack_tlv_posix_find_entry(self, tag);
220                     if (old_entry){
221                         btstack_linked_list_remove(&self->entry_list, (btstack_linked_item_t *) old_entry);
222                         free(old_entry);
223                     }
224 
225                     // append new entry
226                     if (new_entry){
227 	                    btstack_linked_list_add(&self->entry_list, (btstack_linked_item_t *) new_entry);
228                     }
229 		    	}
230 	    	}
231 	    }
232 	    if (!file_valid) {
233 	    	log_info("file invalid, re-create");
234     		fclose(self->file);
235     		self->file = NULL;
236 	    }
237     }
238     if (!self->file){
239     	// create truncate file
240 	    self->file = fopen(self->db_path,"w+");
241         if (!self->file) {
242             log_error("failed to create file");
243             return -1;
244         }
245 	    memset(header, 0, sizeof(header));
246 	    strcpy((char *)header, btstack_tlv_header_magic);
247 	    fwrite(header, 1, sizeof(header), self->file);
248 	    // write out all valid entries (if any)
249 		btstack_linked_list_iterator_t it;
250 		btstack_linked_list_iterator_init(&it, &self->entry_list);
251 		while (btstack_linked_list_iterator_has_next(&it)){
252 			tlv_entry_t * entry = (tlv_entry_t*) btstack_linked_list_iterator_next(&it);
253 			btstack_tlv_posix_append_tag(self, entry->tag, &entry->value[0], entry->len);
254 		}
255     }
256 	return 0;
257 }
258 
259 static const btstack_tlv_t btstack_tlv_posix = {
260 	/* int  (*get_tag)(..);     */ &btstack_tlv_posix_get_tag,
261 	/* int (*store_tag)(..);    */ &btstack_tlv_posix_store_tag,
262 	/* void (*delete_tag)(v..); */ &btstack_tlv_posix_delete_tag,
263 };
264 
265 /**
266  * Init Tag Length Value Store
267  */
268 const btstack_tlv_t * btstack_tlv_posix_init_instance(btstack_tlv_posix_t * self, const char * db_path){
269 	memset(self, 0, sizeof(btstack_tlv_posix_t));
270 	self->db_path = db_path;
271 
272 	// read DB
273 	btstack_tlv_posix_read_db(self);
274 	return &btstack_tlv_posix;
275 }
276 
277 /**
278  * Free TLV entries
279  * @param self
280  */
281 void btstack_tlv_posix_deinit(btstack_tlv_posix_t * self){
282     // free all entries
283     btstack_linked_list_iterator_t it;
284     btstack_linked_list_iterator_init(&it, &self->entry_list);
285     while (btstack_linked_list_iterator_has_next(&it)){
286         tlv_entry_t * entry = (tlv_entry_t*) btstack_linked_list_iterator_next(&it);
287 		btstack_linked_list_iterator_remove(&it);
288 		free(entry);
289     }
290 }
291