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