xref: /btstack/platform/posix/btstack_tlv_posix.c (revision 4c7f8b037f54edcb6731cbb277cfc1a3fc03cffd)
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 // testing support
71 static bool btstack_tlv_posix_read_only;
72 
73 static void btstack_tlv_posix_append_tag(btstack_tlv_posix_t * self, uint32_t tag, const uint8_t * data, uint32_t data_size){
74 
75 	if (!self->file) return;
76 
77     if (btstack_tlv_posix_read_only) return;
78 
79 	log_info("append tag %04x, len %u", tag, data_size);
80 
81 	uint8_t header[8];
82 	big_endian_store_32(header, 0, tag);
83 	big_endian_store_32(header, 4, data_size);
84 	size_t written_header = fwrite(header, 1, sizeof(header), self->file);
85 	if (written_header != sizeof(header)) return;
86 	if (data_size > 0) {
87 		size_t written_value = fwrite(data, 1, data_size, self->file);
88 		if (written_value != data_size) return;
89 	}
90 	fflush(self->file);
91 }
92 
93 static tlv_entry_t * btstack_tlv_posix_find_entry(btstack_tlv_posix_t * self, uint32_t tag){
94 	btstack_linked_list_iterator_t it;
95 	btstack_linked_list_iterator_init(&it, &self->entry_list);
96 	while (btstack_linked_list_iterator_has_next(&it)){
97 		tlv_entry_t * entry = (tlv_entry_t*) btstack_linked_list_iterator_next(&it);
98 		if (entry->tag != tag) continue;
99 		return entry;
100 	}
101 	return NULL;
102 }
103 
104 /**
105  * Delete Tag
106  * @param tag
107  */
108 static void btstack_tlv_posix_delete_tag(void * context, uint32_t tag){
109 	btstack_tlv_posix_t * self = (btstack_tlv_posix_t *) context;
110 	btstack_linked_list_iterator_t it;
111 	btstack_linked_list_iterator_init(&it, &self->entry_list);
112 	while (btstack_linked_list_iterator_has_next(&it)){
113 		tlv_entry_t * entry = (tlv_entry_t*) btstack_linked_list_iterator_next(&it);
114 		if (entry->tag != tag) continue;
115 		btstack_linked_list_iterator_remove(&it);
116 		free(entry);
117 		btstack_tlv_posix_append_tag(self, tag, NULL, 0);
118 		return;
119 	}
120 }
121 
122 /**
123  * Get Value for Tag
124  * @param tag
125  * @param buffer
126  * @param buffer_size
127  * @returns size of value
128  */
129 static int btstack_tlv_posix_get_tag(void * context, uint32_t tag, uint8_t * buffer, uint32_t buffer_size){
130 	btstack_tlv_posix_t * self = (btstack_tlv_posix_t *) context;
131 	tlv_entry_t * entry = btstack_tlv_posix_find_entry(self, tag);
132 	// not found
133 	if (!entry) return 0;
134 	// return len if buffer = NULL
135 	if (!buffer) return entry->len;
136 	// otherwise copy data into buffer
137 	uint16_t bytes_to_copy = btstack_min(buffer_size, entry->len);
138 	memcpy(buffer, &entry->value[0], bytes_to_copy);
139 	return bytes_to_copy;
140 }
141 
142 /**
143  * Store Tag
144  * @param tag
145  * @param data
146  * @param data_size
147  */
148 static int btstack_tlv_posix_store_tag(void * context, uint32_t tag, const uint8_t * data, uint32_t data_size){
149 	btstack_tlv_posix_t * self = (btstack_tlv_posix_t *) context;
150 
151 	// enforce arbitrary max value size
152 	btstack_assert(data_size <= MAX_TLV_VALUE_SIZE);
153 
154 	// remove old entry
155 	tlv_entry_t * old_entry = btstack_tlv_posix_find_entry(self, tag);
156 	if (old_entry){
157 		btstack_linked_list_remove(&self->entry_list, (btstack_linked_item_t *) old_entry);
158 		free(old_entry);
159 	}
160 
161 	// create new entry
162 	uint32_t entry_size = sizeof(tlv_entry_t) - DUMMY_SIZE + data_size;
163 	tlv_entry_t * new_entry = (tlv_entry_t *) malloc(entry_size);
164 	if (!new_entry) return 0;
165 	memset(new_entry, 0, entry_size);
166 	new_entry->tag = tag;
167 	new_entry->len = data_size;
168 	memcpy(&new_entry->value[0], data, data_size);
169 
170 	// append new entry
171 	btstack_linked_list_add(&self->entry_list, (btstack_linked_item_t *) new_entry);
172 
173 	// write new tag
174 	btstack_tlv_posix_append_tag(self, tag, data, data_size);
175 
176 	return 0;
177 }
178 
179 // returns 0 on success
180 static int btstack_tlv_posix_read_db(btstack_tlv_posix_t * self){
181 	// open file
182 	log_info("open db %s", self->db_path);
183     self->file = fopen(self->db_path,"r+");
184     uint8_t header[BTSTACK_TLV_HEADER_LEN];
185     if (self->file){
186     	// checker header
187 	    size_t objects_read = fread(header, 1, BTSTACK_TLV_HEADER_LEN, self->file );
188 	    int file_valid = 0;
189 	    if (objects_read == BTSTACK_TLV_HEADER_LEN){
190 	    	if (memcmp(header, btstack_tlv_header_magic, strlen(btstack_tlv_header_magic)) == 0){
191 		    	log_info("BTstack Magic Header found");
192 		    	// read entries
193 		    	while (true){
194 					uint8_t entry[8];
195 					size_t 	entries_read = fread(entry, 1, sizeof(entry), self->file);
196 					if (entries_read == 0){
197 						// EOF, we're good
198 						file_valid = 1;
199 						break;
200 					}
201 					if (entries_read != sizeof(entry)) break;
202 
203                     uint32_t tag = big_endian_read_32(entry, 0);
204                     uint32_t len = big_endian_read_32(entry, 4);
205 
206                     // arbitrary safety check: values <= MAX_TLV_VALUE_SIZE
207                     if (len > MAX_TLV_VALUE_SIZE) break;
208 
209                     // create new entry for regular tag
210                     tlv_entry_t * new_entry = NULL;
211                     if (len > 0) {
212                         new_entry = (tlv_entry_t *) malloc(sizeof(tlv_entry_t) - DUMMY_SIZE + len);
213                         if (!new_entry) return 0;
214                         new_entry->tag = tag;
215                         new_entry->len = len;
216 
217                         // read
218                         size_t value_read = fread(&new_entry->value[0], 1, len, self->file);
219                         if (value_read != len) break;
220                     }
221 
222                     // remove old entry
223                     tlv_entry_t * old_entry = btstack_tlv_posix_find_entry(self, tag);
224                     if (old_entry){
225                         btstack_linked_list_remove(&self->entry_list, (btstack_linked_item_t *) old_entry);
226                         free(old_entry);
227                     }
228 
229                     // append new entry
230                     if (new_entry){
231 	                    btstack_linked_list_add(&self->entry_list, (btstack_linked_item_t *) new_entry);
232                     }
233 		    	}
234 	    	}
235 	    }
236 	    if (!file_valid) {
237 	    	log_info("file invalid, re-create");
238     		fclose(self->file);
239     		self->file = NULL;
240 	    }
241     }
242     if (!self->file){
243     	// create truncate file
244 	    self->file = fopen(self->db_path,"w+");
245         if (!self->file) {
246             log_error("failed to create file");
247             return -1;
248         }
249 	    memset(header, 0, sizeof(header));
250 	    strcpy((char *)header, btstack_tlv_header_magic);
251 	    fwrite(header, 1, sizeof(header), self->file);
252 	    // write out all valid entries (if any)
253 		btstack_linked_list_iterator_t it;
254 		btstack_linked_list_iterator_init(&it, &self->entry_list);
255 		while (btstack_linked_list_iterator_has_next(&it)){
256 			tlv_entry_t * entry = (tlv_entry_t*) btstack_linked_list_iterator_next(&it);
257 			btstack_tlv_posix_append_tag(self, entry->tag, &entry->value[0], entry->len);
258 		}
259     }
260 	return 0;
261 }
262 
263 static const btstack_tlv_t btstack_tlv_posix = {
264 	/* int  (*get_tag)(..);     */ &btstack_tlv_posix_get_tag,
265 	/* int (*store_tag)(..);    */ &btstack_tlv_posix_store_tag,
266 	/* void (*delete_tag)(v..); */ &btstack_tlv_posix_delete_tag,
267 };
268 
269 /**
270  * Init Tag Length Value Store
271  */
272 const btstack_tlv_t * btstack_tlv_posix_init_instance(btstack_tlv_posix_t * self, const char * db_path){
273 	memset(self, 0, sizeof(btstack_tlv_posix_t));
274 	self->db_path = db_path;
275 
276     btstack_tlv_posix_read_only = false;
277 
278 	// read DB
279     if (db_path != NULL){
280         btstack_tlv_posix_read_db(self);
281     }
282 	return &btstack_tlv_posix;
283 }
284 
285 void btstack_tlv_posix_set_read_only(bool read_only){
286     btstack_tlv_posix_read_only = read_only;
287 }
288 
289 /**
290  * Free TLV entries
291  * @param self
292  */
293 void btstack_tlv_posix_deinit(btstack_tlv_posix_t * self){
294     // free all entries
295     btstack_linked_list_iterator_t it;
296     btstack_linked_list_iterator_init(&it, &self->entry_list);
297     while (btstack_linked_list_iterator_has_next(&it)){
298         tlv_entry_t * entry = (tlv_entry_t*) btstack_linked_list_iterator_next(&it);
299 		btstack_linked_list_iterator_remove(&it);
300 		free(entry);
301     }
302 }
303