1 /*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "sqlite3_android"
18
19 #include <ctype.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23
24 #ifdef SQLITE_ENABLE_ICU
25 #include <unicode/ucol.h>
26 #include <unicode/uiter.h>
27 #include <unicode/ustring.h>
28 #include <unicode/utypes.h>
29 #endif //SQLITE_ENABLE_ICU
30 #include <log/log.h>
31
32 #include "sqlite3_android.h"
33 #include "PhoneNumberUtils.h"
34
35 #define ENABLE_ANDROID_LOG 0
36 #define SMALL_BUFFER_SIZE 10
37 #define PHONE_NUMBER_BUFFER_SIZE 40
38
39 #ifdef SQLITE_ENABLE_ICU
collate16(void * p,int n1,const void * v1,int n2,const void * v2)40 static int collate16(void *p, int n1, const void *v1, int n2, const void *v2)
41 {
42 UCollator *coll = (UCollator *) p;
43 UCollationResult result = ucol_strcoll(coll, (const UChar *) v1, n1,
44 (const UChar *) v2, n2);
45
46 if (result == UCOL_LESS) {
47 return -1;
48 } else if (result == UCOL_GREATER) {
49 return 1;
50 } else {
51 return 0;
52 }
53 }
54
collate8(void * p,int n1,const void * v1,int n2,const void * v2)55 static int collate8(void *p, int n1, const void *v1, int n2, const void *v2)
56 {
57 UCollator *coll = (UCollator *) p;
58 UCharIterator i1, i2;
59 UErrorCode status = U_ZERO_ERROR;
60
61 uiter_setUTF8(&i1, (const char *) v1, n1);
62 uiter_setUTF8(&i2, (const char *) v2, n2);
63
64 UCollationResult result = ucol_strcollIter(coll, &i1, &i2, &status);
65
66 if (U_FAILURE(status)) {
67 // ALOGE("Collation iterator error: %d\n", status);
68 }
69
70 if (result == UCOL_LESS) {
71 return -1;
72 } else if (result == UCOL_GREATER) {
73 return 1;
74 } else {
75 return 0;
76 }
77 }
78 #endif // SQLITE_ENABLE_ICU
79
phone_numbers_equal(sqlite3_context * context,int argc,sqlite3_value ** argv)80 static void phone_numbers_equal(sqlite3_context * context, int argc, sqlite3_value ** argv)
81 {
82 if (argc != 2 && argc != 3) {
83 sqlite3_result_int(context, 0);
84 return;
85 }
86
87 char const * num1 = (char const *)sqlite3_value_text(argv[0]);
88 char const * num2 = (char const *)sqlite3_value_text(argv[1]);
89
90 bool use_strict = false;
91 if (argc == 3) {
92 use_strict = (sqlite3_value_int(argv[2]) != 0);
93 }
94
95 if (num1 == NULL || num2 == NULL) {
96 sqlite3_result_null(context);
97 return;
98 }
99
100 bool equal =
101 (use_strict ?
102 android::phone_number_compare_strict(num1, num2) :
103 android::phone_number_compare_loose(num1, num2));
104
105 if (equal) {
106 sqlite3_result_int(context, 1);
107 } else {
108 sqlite3_result_int(context, 0);
109 }
110 }
111
phone_number_stripped_reversed(sqlite3_context * context,int argc,sqlite3_value ** argv)112 static void phone_number_stripped_reversed(sqlite3_context * context, int argc,
113 sqlite3_value ** argv)
114 {
115 if (argc != 1) {
116 sqlite3_result_int(context, 0);
117 return;
118 }
119
120 char const * number = (char const *)sqlite3_value_text(argv[0]);
121 if (number == NULL) {
122 sqlite3_result_null(context);
123 return;
124 }
125
126 char out[PHONE_NUMBER_BUFFER_SIZE];
127 int outlen = 0;
128 android::phone_number_stripped_reversed_inter(number, out, PHONE_NUMBER_BUFFER_SIZE, &outlen);
129 sqlite3_result_text(context, (const char*)out, outlen, SQLITE_TRANSIENT);
130 }
131
132
133 #if ENABLE_ANDROID_LOG
android_log(sqlite3_context * context,int argc,sqlite3_value ** argv)134 static void android_log(sqlite3_context * context, int argc, sqlite3_value ** argv)
135 {
136 char const * tag = "sqlite_trigger";
137 char const * msg = "";
138 int msgIndex = 0;
139
140 switch (argc) {
141 case 2:
142 tag = (char const *)sqlite3_value_text(argv[0]);
143 if (tag == NULL) {
144 tag = "sqlite_trigger";
145 }
146 msgIndex = 1;
147 case 1:
148 msg = (char const *)sqlite3_value_text(argv[msgIndex]);
149 if (msg == NULL) {
150 msg = "";
151 }
152 ALOG(LOG_INFO, tag, "%s", msg);
153 sqlite3_result_int(context, 1);
154 return;
155
156 default:
157 sqlite3_result_int(context, 0);
158 return;
159 }
160 }
161 #endif
162
delete_file(sqlite3_context * context,int argc,sqlite3_value ** argv)163 static void delete_file(sqlite3_context * context, int argc, sqlite3_value ** argv)
164 {
165 if (argc != 1) {
166 sqlite3_result_int(context, 0);
167 return;
168 }
169
170 char const * path = (char const *)sqlite3_value_text(argv[0]);
171 // Don't allow ".." in paths
172 if (path == NULL || strstr(path, "/../") != NULL) {
173 sqlite3_result_null(context);
174 return;
175 }
176
177 // We only allow deleting files in the EXTERNAL_STORAGE path, or one of the
178 // SECONDARY_STORAGE paths
179 bool good_path = false;
180 char const * external_storage = getenv("EXTERNAL_STORAGE");
181 if (external_storage && strncmp(external_storage, path, strlen(external_storage)) == 0) {
182 good_path = true;
183 } else {
184 // check SECONDARY_STORAGE, which should be a colon separated list of paths
185 char const * secondary_paths = getenv("SECONDARY_STORAGE");
186 while (secondary_paths && secondary_paths[0]) {
187 const char* colon = strchr(secondary_paths, ':');
188 int length = (colon ? colon - secondary_paths : strlen(secondary_paths));
189 if (strncmp(secondary_paths, path, length) == 0) {
190 good_path = true;
191 }
192 secondary_paths += length;
193 while (*secondary_paths == ':') secondary_paths++;
194 }
195 }
196
197 if (!good_path) {
198 sqlite3_result_null(context);
199 return;
200 }
201
202 int err = unlink(path);
203 if (err != -1) {
204 // No error occured, return true
205 sqlite3_result_int(context, 1);
206 } else {
207 // An error occured, return false
208 sqlite3_result_int(context, 0);
209 }
210 }
211
212 #ifdef SQLITE_ENABLE_ICU
tokenize_auxdata_delete(void * data)213 static void tokenize_auxdata_delete(void * data)
214 {
215 sqlite3_stmt * statement = (sqlite3_stmt *)data;
216 sqlite3_finalize(statement);
217 }
218
base16Encode(char * dest,const char * src,uint32_t size)219 static void base16Encode(char* dest, const char* src, uint32_t size)
220 {
221 static const char * BASE16_TABLE = "0123456789abcdef";
222 for (uint32_t i = 0; i < size; i++) {
223 char ch = *src++;
224 *dest++ = BASE16_TABLE[ (ch & 0xf0) >> 4 ];
225 *dest++ = BASE16_TABLE[ (ch & 0x0f) ];
226 }
227 }
228
229 struct SqliteUserData {
230 sqlite3 * handle;
231 UCollator* collator;
232 };
233
234 #if 0
235 /**
236 * This function is invoked as:
237 *
238 * _TOKENIZE('<token_table>', <data_row_id>, <data>, <delimiter>,
239 * <use_token_index>, <data_tag>)
240 *
241 * If <use_token_index> is omitted, it is treated as 0.
242 * If <data_tag> is omitted, it is treated as NULL.
243 *
244 * It will split <data> on each instance of <delimiter> and insert each token
245 * into <token_table>. The following columns in <token_table> are used:
246 * token TEXT, source INTEGER, token_index INTEGER, tag (any type)
247 * The token_index column is not required if <use_token_index> is 0.
248 * The tag column is not required if <data_tag> is NULL.
249 *
250 * One row is inserted for each token in <data>.
251 * In each inserted row, 'source' is <data_row_id>.
252 * In the first inserted row, 'token' is the hex collation key of
253 * the entire <data> string, and 'token_index' is 0.
254 * In each row I (where 1 <= I < N, and N is the number of tokens in <data>)
255 * 'token' will be set to the hex collation key of the I:th token (0-based).
256 * If <use_token_index> != 0, 'token_index' is set to I.
257 * If <data_tag> is not NULL, 'tag' is set to <data_tag>.
258 *
259 * In other words, there will be one row for the entire string,
260 * and one row for each token except the first one.
261 *
262 * The function returns the number of tokens generated.
263 */
264 static void tokenize(sqlite3_context * context, int argc, sqlite3_value ** argv)
265 {
266 //ALOGD("enter tokenize");
267 int err;
268 int useTokenIndex = 0;
269 int useDataTag = 0;
270
271 if (!(argc >= 4 || argc <= 6)) {
272 ALOGE("Tokenize requires 4 to 6 arguments");
273 sqlite3_result_null(context);
274 return;
275 }
276
277 if (argc > 4) {
278 useTokenIndex = sqlite3_value_int(argv[4]);
279 }
280
281 if (argc > 5) {
282 useDataTag = (sqlite3_value_type(argv[5]) != SQLITE_NULL);
283 }
284
285 sqlite3 * handle = sqlite3_context_db_handle(context);
286 UCollator* collator = (UCollator*)sqlite3_user_data(context);
287 char const * tokenTable = (char const *)sqlite3_value_text(argv[0]);
288 if (tokenTable == NULL) {
289 ALOGE("tokenTable null");
290 sqlite3_result_null(context);
291 return;
292 }
293
294 // Get or create the prepared statement for the insertions
295 sqlite3_stmt * statement = (sqlite3_stmt *)sqlite3_get_auxdata(context, 0);
296 if (!statement) {
297 char const * tokenIndexCol = useTokenIndex ? ", token_index" : "";
298 char const * tokenIndexParam = useTokenIndex ? ", ?" : "";
299 char const * dataTagCol = useDataTag ? ", tag" : "";
300 char const * dataTagParam = useDataTag ? ", ?" : "";
301 char * sql = sqlite3_mprintf("INSERT INTO %s (token, source%s%s) VALUES (?, ?%s%s);",
302 tokenTable, tokenIndexCol, dataTagCol, tokenIndexParam, dataTagParam);
303 err = sqlite3_prepare_v2(handle, sql, -1, &statement, NULL);
304 sqlite3_free(sql);
305 if (err) {
306 ALOGE("prepare failed");
307 sqlite3_result_null(context);
308 return;
309 }
310 // This binds the statement to the table it was compiled against, which is argv[0].
311 // If this function is ever called with a different table the finalizer will be called
312 // and sqlite3_get_auxdata() will return null above, forcing a recompile for the new table.
313 sqlite3_set_auxdata(context, 0, statement, tokenize_auxdata_delete);
314 } else {
315 // Reset the cached statement so that binding the row ID will work properly
316 sqlite3_reset(statement);
317 }
318
319 // Bind the row ID of the source row
320 int64_t rowID = sqlite3_value_int64(argv[1]);
321 err = sqlite3_bind_int64(statement, 2, rowID);
322 if (err != SQLITE_OK) {
323 ALOGE("bind failed");
324 sqlite3_result_null(context);
325 return;
326 }
327
328 // Bind <data_tag> to the tag column
329 if (useDataTag) {
330 int dataTagParamIndex = useTokenIndex ? 4 : 3;
331 err = sqlite3_bind_value(statement, dataTagParamIndex, argv[5]);
332 if (err != SQLITE_OK) {
333 ALOGE("bind failed");
334 sqlite3_result_null(context);
335 return;
336 }
337 }
338
339 // Get the raw bytes for the string to tokenize
340 // the string will be modified by following code
341 // however, sqlite did not reuse the string, so it is safe to not dup it
342 UChar * origData = (UChar *)sqlite3_value_text16(argv[2]);
343 if (origData == NULL) {
344 sqlite3_result_null(context);
345 return;
346 }
347
348 // Get the raw bytes for the delimiter
349 const UChar * delim = (const UChar *)sqlite3_value_text16(argv[3]);
350 if (delim == NULL) {
351 ALOGE("can't get delimiter");
352 sqlite3_result_null(context);
353 return;
354 }
355
356 UChar * token = NULL;
357 UChar *state;
358 int numTokens = 0;
359
360 do {
361 if (numTokens == 0) {
362 token = origData;
363 }
364
365 // Reset the program so we can use it to perform the insert
366 sqlite3_reset(statement);
367 UErrorCode status = U_ZERO_ERROR;
368 char keybuf[1024];
369 uint32_t result = ucol_getSortKey(collator, token, -1, (uint8_t*)keybuf, sizeof(keybuf)-1);
370 if (result > sizeof(keybuf)) {
371 // TODO allocate memory for this super big string
372 ALOGE("ucol_getSortKey needs bigger buffer %d", result);
373 break;
374 }
375 uint32_t keysize = result-1;
376 uint32_t base16Size = keysize*2;
377 char *base16buf = (char*)malloc(base16Size);
378 base16Encode(base16buf, keybuf, keysize);
379 err = sqlite3_bind_text(statement, 1, base16buf, base16Size, SQLITE_STATIC);
380
381 if (err != SQLITE_OK) {
382 ALOGE(" sqlite3_bind_text16 error %d", err);
383 free(base16buf);
384 break;
385 }
386
387 if (useTokenIndex) {
388 err = sqlite3_bind_int(statement, 3, numTokens);
389 if (err != SQLITE_OK) {
390 ALOGE(" sqlite3_bind_int error %d", err);
391 free(base16buf);
392 break;
393 }
394 }
395
396 err = sqlite3_step(statement);
397 free(base16buf);
398
399 if (err != SQLITE_DONE) {
400 ALOGE(" sqlite3_step error %d", err);
401 break;
402 }
403 numTokens++;
404 if (numTokens == 1) {
405 // first call
406 u_strtok_r(origData, delim, &state);
407 }
408 } while ((token = u_strtok_r(NULL, delim, &state)) != NULL);
409 sqlite3_result_int(context, numTokens);
410 }
411 #endif
412
localized_collator_dtor(UCollator * collator)413 static void localized_collator_dtor(UCollator* collator)
414 {
415 ucol_close(collator);
416 }
417
418 #define LOCALIZED_COLLATOR_NAME "LOCALIZED"
419
420 // This collator may be removed in the near future, so you MUST not use now.
421 #define PHONEBOOK_COLLATOR_NAME "PHONEBOOK"
422
423 #endif // SQLITE_ENABLE_ICU
424
register_localized_collators(sqlite3 * handle __attribute ((unused)),const char * systemLocale __attribute ((unused)),int utf16Storage __attribute ((unused)))425 extern "C" int register_localized_collators(sqlite3* handle __attribute((unused)),
426 const char* systemLocale __attribute((unused)),
427 int utf16Storage __attribute((unused)))
428 {
429 // This function is no-op for the VNDK, but should exist in case when some vendor
430 // module has a reference to this function.
431 #ifdef SQLITE_ENABLE_ICU
432 UErrorCode status = U_ZERO_ERROR;
433 UCollator* collator = ucol_open(systemLocale, &status);
434 if (U_FAILURE(status)) {
435 return -1;
436 }
437
438 ucol_setAttribute(collator, UCOL_STRENGTH, UCOL_PRIMARY, &status);
439 if (U_FAILURE(status)) {
440 return -1;
441 }
442
443 int err;
444 if (utf16Storage) {
445 err = sqlite3_create_collation_v2(handle, LOCALIZED_COLLATOR_NAME, SQLITE_UTF16, collator,
446 collate16, (void(*)(void*))localized_collator_dtor);
447 } else {
448 err = sqlite3_create_collation_v2(handle, LOCALIZED_COLLATOR_NAME, SQLITE_UTF8, collator,
449 collate8, (void(*)(void*))localized_collator_dtor);
450 }
451
452 if (err != SQLITE_OK) {
453 return err;
454 }
455
456 #if 0
457 // Register the _TOKENIZE function
458 err = sqlite3_create_function(handle, "_TOKENIZE", 4, SQLITE_UTF16, collator, tokenize, NULL, NULL);
459 if (err != SQLITE_OK) {
460 return err;
461 }
462 err = sqlite3_create_function(handle, "_TOKENIZE", 5, SQLITE_UTF16, collator, tokenize, NULL, NULL);
463 if (err != SQLITE_OK) {
464 return err;
465 }
466 err = sqlite3_create_function(handle, "_TOKENIZE", 6, SQLITE_UTF16, collator, tokenize, NULL, NULL);
467 if (err != SQLITE_OK) {
468 return err;
469 }
470 #endif
471
472 //// PHONEBOOK_COLLATOR
473 status = U_ZERO_ERROR;
474 collator = ucol_open(systemLocale, &status);
475 if (U_FAILURE(status)) {
476 return -1;
477 }
478
479 status = U_ZERO_ERROR;
480 ucol_setAttribute(collator, UCOL_STRENGTH, UCOL_PRIMARY, &status);
481 if (U_FAILURE(status)) {
482 return -1;
483 }
484
485 if (utf16Storage) {
486 err = sqlite3_create_collation_v2(handle, PHONEBOOK_COLLATOR_NAME, SQLITE_UTF16, collator,
487 collate16, (void(*)(void*))localized_collator_dtor);
488 } else {
489 err = sqlite3_create_collation_v2(handle, PHONEBOOK_COLLATOR_NAME, SQLITE_UTF8, collator,
490 collate8, (void(*)(void*))localized_collator_dtor);
491 }
492
493 if (err != SQLITE_OK) {
494 return err;
495 }
496 //// PHONEBOOK_COLLATOR
497 #endif //SQLITE_ENABLE_ICU
498
499 return SQLITE_OK;
500 }
501
502
register_android_functions(sqlite3 * handle,int utf16Storage __attribute ((unused)))503 extern "C" int register_android_functions(sqlite3 * handle, int utf16Storage __attribute((unused)))
504 {
505 int err;
506 #ifdef SQLITE_ENABLE_ICU
507 UErrorCode status = U_ZERO_ERROR;
508
509 UCollator * collator = ucol_open(NULL, &status);
510 if (U_FAILURE(status)) {
511 return -1;
512 }
513
514 if (utf16Storage) {
515 // Note that text should be stored as UTF-16
516 err = sqlite3_exec(handle, "PRAGMA encoding = 'UTF-16'", 0, 0, 0);
517 if (err != SQLITE_OK) {
518 return err;
519 }
520
521 // Register the UNICODE collation
522 err = sqlite3_create_collation_v2(handle, "UNICODE", SQLITE_UTF16, collator, collate16,
523 (void(*)(void*))localized_collator_dtor);
524 } else {
525 err = sqlite3_create_collation_v2(handle, "UNICODE", SQLITE_UTF8, collator, collate8,
526 (void(*)(void*))localized_collator_dtor);
527 }
528
529 if (err != SQLITE_OK) {
530 return err;
531 }
532 #endif // SQLITE_ENABLE_ICU
533
534 // Register the PHONE_NUM_EQUALS function
535 err = sqlite3_create_function(
536 handle, "PHONE_NUMBERS_EQUAL", 2,
537 SQLITE_UTF8, NULL, phone_numbers_equal, NULL, NULL);
538 if (err != SQLITE_OK) {
539 return err;
540 }
541
542 // Register the PHONE_NUM_EQUALS function with an additional argument "use_strict"
543 err = sqlite3_create_function(
544 handle, "PHONE_NUMBERS_EQUAL", 3,
545 SQLITE_UTF8, NULL, phone_numbers_equal, NULL, NULL);
546 if (err != SQLITE_OK) {
547 return err;
548 }
549
550 // Register the _DELETE_FILE function
551 err = sqlite3_create_function(handle, "_DELETE_FILE", 1, SQLITE_UTF8, NULL, delete_file, NULL, NULL);
552 if (err != SQLITE_OK) {
553 return err;
554 }
555
556 #if ENABLE_ANDROID_LOG
557 // Register the _LOG function
558 err = sqlite3_create_function(handle, "_LOG", 1, SQLITE_UTF8, NULL, android_log, NULL, NULL);
559 if (err != SQLITE_OK) {
560 return err;
561 }
562 #endif
563
564 // Register the _PHONE_NUMBER_STRIPPED_REVERSED function, which imitates
565 // PhoneNumberUtils.getStrippedReversed. This function is used by
566 // packages/providers/ContactsProvider/src/com/android/providers/contacts/LegacyApiSupport.java
567 // to provide compatibility with Android 1.6 and earlier.
568 err = sqlite3_create_function(handle,
569 "_PHONE_NUMBER_STRIPPED_REVERSED",
570 1, SQLITE_UTF8, NULL,
571 phone_number_stripped_reversed,
572 NULL, NULL);
573 if (err != SQLITE_OK) {
574 return err;
575 }
576
577 return SQLITE_OK;
578 }
579