]> git.notmuchmail.org Git - notmuch/blob - lib/database.cc
831b4a16926ded207c00920761fe29e08933679a
[notmuch] / lib / database.cc
1 /* database.cc - The database interfaces of the notmuch mail library
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see http://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "database-private.h"
22
23 #include <iostream>
24
25 #include <sys/time.h>
26 #include <signal.h>
27 #include <xapian.h>
28
29 #include <glib.h> /* g_free, GPtrArray, GHashTable */
30
31 using namespace std;
32
33 #define ARRAY_SIZE(arr) (sizeof (arr) / sizeof (arr[0]))
34
35 typedef struct {
36     const char *name;
37     const char *prefix;
38 } prefix_t;
39
40 #define NOTMUCH_DATABASE_VERSION 1
41
42 #define STRINGIFY(s) _SUB_STRINGIFY(s)
43 #define _SUB_STRINGIFY(s) #s
44
45 /* Here's the current schema for our database (for NOTMUCH_DATABASE_VERSION):
46  *
47  * We currently have two different types of documents: mail and directory.
48  *
49  * Mail document
50  * -------------
51  * A mail document is associated with a particular email message file
52  * on disk. It is indexed with the following prefixed terms which the
53  * database uses to construct threads, etc.:
54  *
55  *    Single terms of given prefix:
56  *
57  *      type:   mail
58  *
59  *      id:     Unique ID of mail, (from Message-ID header or generated
60  *              as "notmuch-sha1-<sha1_sum_of_entire_file>.
61  *
62  *      thread: The ID of the thread to which the mail belongs
63  *
64  *      replyto: The ID from the In-Reply-To header of the mail (if any).
65  *
66  *    Multiple terms of given prefix:
67  *
68  *      reference: All message IDs from In-Reply-To and Re ferences
69  *                 headers in the message.
70  *
71  *      tag:       Any tags associated with this message by the user.
72  *
73  *      file-direntry:  A colon-separated pair of values
74  *                      (INTEGER:STRING), where INTEGER is the
75  *                      document ID of a directory document, and
76  *                      STRING is the name of a file within that
77  *                      directory for this mail message.
78  *
79  *    A mail document also has two values:
80  *
81  *      TIMESTAMP:      The time_t value corresponding to the message's
82  *                      Date header.
83  *
84  *      MESSAGE_ID:     The unique ID of the mail mess (see "id" above)
85  *
86  * In addition, terms from the content of the message are added with
87  * "from", "to", "attachment", and "subject" prefixes for use by the
88  * user in searching. But the database doesn't really care itself
89  * about any of these.
90  *
91  * The data portion of a mail document is empty.
92  *
93  * Directory document
94  * ------------------
95  * A directory document is used by a client of the notmuch library to
96  * maintain data necessary to allow for efficient polling of mail
97  * directories.
98  *
99  * All directory documents contain one term:
100  *
101  *      directory:      The directory path (relative to the database path)
102  *                      Or the SHA1 sum of the directory path (if the
103  *                      path itself is too long to fit in a Xapian
104  *                      term).
105  *
106  * And all directory documents for directories other than top-level
107  * directories also contain the following term:
108  *
109  *      directory-direntry: A colon-separated pair of values
110  *                          (INTEGER:STRING), where INTEGER is the
111  *                          document ID of the parent directory
112  *                          document, and STRING is the name of this
113  *                          directory within that parent.
114  *
115  * All directory documents have a single value:
116  *
117  *      TIMESTAMP:      The mtime of the directory (at last scan)
118  *
119  * The data portion of a directory document contains the path of the
120  * directory (relative to the database path).
121  */
122
123 /* With these prefix values we follow the conventions published here:
124  *
125  * http://xapian.org/docs/omega/termprefixes.html
126  *
127  * as much as makes sense. Note that I took some liberty in matching
128  * the reserved prefix values to notmuch concepts, (for example, 'G'
129  * is documented as "newsGroup (or similar entity - e.g. a web forum
130  * name)", for which I think the thread is the closest analogue in
131  * notmuch. This in spite of the fact that we will eventually be
132  * storing mailing-list messages where 'G' for "mailing list name"
133  * might be even a closer analogue. I'm treating the single-character
134  * prefixes preferentially for core notmuch concepts (which will be
135  * nearly universal to all mail messages).
136  */
137
138 prefix_t BOOLEAN_PREFIX_INTERNAL[] = {
139     { "type",                   "T" },
140     { "reference",              "XREFERENCE" },
141     { "replyto",                "XREPLYTO" },
142     { "directory",              "XDIRECTORY" },
143     { "file-direntry",          "XFDIRENTRY" },
144     { "directory-direntry",     "XDDIRENTRY" },
145 };
146
147 prefix_t BOOLEAN_PREFIX_EXTERNAL[] = {
148     { "thread",                 "G" },
149     { "tag",                    "K" },
150     { "id",                     "Q" }
151 };
152
153 prefix_t PROBABILISTIC_PREFIX[]= {
154     { "from",                   "XFROM" },
155     { "to",                     "XTO" },
156     { "attachment",             "XATTACHMENT" },
157     { "subject",                "XSUBJECT"}
158 };
159
160 int
161 _internal_error (const char *format, ...)
162 {
163     va_list va_args;
164
165     va_start (va_args, format);
166
167     fprintf (stderr, "Internal error: ");
168     vfprintf (stderr, format, va_args);
169
170     exit (1);
171
172     return 1;
173 }
174
175 const char *
176 _find_prefix (const char *name)
177 {
178     unsigned int i;
179
180     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_INTERNAL); i++) {
181         if (strcmp (name, BOOLEAN_PREFIX_INTERNAL[i].name) == 0)
182             return BOOLEAN_PREFIX_INTERNAL[i].prefix;
183     }
184
185     for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
186         if (strcmp (name, BOOLEAN_PREFIX_EXTERNAL[i].name) == 0)
187             return BOOLEAN_PREFIX_EXTERNAL[i].prefix;
188     }
189
190     for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
191         if (strcmp (name, PROBABILISTIC_PREFIX[i].name) == 0)
192             return PROBABILISTIC_PREFIX[i].prefix;
193     }
194
195     INTERNAL_ERROR ("No prefix exists for '%s'\n", name);
196
197     return "";
198 }
199
200 const char *
201 notmuch_status_to_string (notmuch_status_t status)
202 {
203     switch (status) {
204     case NOTMUCH_STATUS_SUCCESS:
205         return "No error occurred";
206     case NOTMUCH_STATUS_OUT_OF_MEMORY:
207         return "Out of memory";
208     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
209         return "Attempt to write to a read-only database";
210     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
211         return "A Xapian exception occurred";
212     case NOTMUCH_STATUS_FILE_ERROR:
213         return "Something went wrong trying to read or write a file";
214     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
215         return "File is not an email";
216     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
217         return "Message ID is identical to a message in database";
218     case NOTMUCH_STATUS_NULL_POINTER:
219         return "Erroneous NULL pointer";
220     case NOTMUCH_STATUS_TAG_TOO_LONG:
221         return "Tag value is too long (exceeds NOTMUCH_TAG_MAX)";
222     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
223         return "Unbalanced number of calls to notmuch_message_freeze/thaw";
224     default:
225     case NOTMUCH_STATUS_LAST_STATUS:
226         return "Unknown error status value";
227     }
228 }
229
230 static void
231 find_doc_ids_for_term (notmuch_database_t *notmuch,
232                        const char *term,
233                        Xapian::PostingIterator *begin,
234                        Xapian::PostingIterator *end)
235 {
236     *begin = notmuch->xapian_db->postlist_begin (term);
237
238     *end = notmuch->xapian_db->postlist_end (term);
239 }
240
241 static void
242 find_doc_ids (notmuch_database_t *notmuch,
243               const char *prefix_name,
244               const char *value,
245               Xapian::PostingIterator *begin,
246               Xapian::PostingIterator *end)
247 {
248     char *term;
249
250     term = talloc_asprintf (notmuch, "%s%s",
251                             _find_prefix (prefix_name), value);
252
253     find_doc_ids_for_term (notmuch, term, begin, end);
254
255     talloc_free (term);
256 }
257
258 notmuch_private_status_t
259 _notmuch_database_find_unique_doc_id (notmuch_database_t *notmuch,
260                                       const char *prefix_name,
261                                       const char *value,
262                                       unsigned int *doc_id)
263 {
264     Xapian::PostingIterator i, end;
265
266     find_doc_ids (notmuch, prefix_name, value, &i, &end);
267
268     if (i == end) {
269         *doc_id = 0;
270         return NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND;
271     }
272
273     *doc_id = *i;
274
275 #if DEBUG_DATABASE_SANITY
276     i++;
277
278     if (i != end)
279         INTERNAL_ERROR ("Term %s:%s is not unique as expected.\n",
280                         prefix_name, value);
281 #endif
282
283     return NOTMUCH_PRIVATE_STATUS_SUCCESS;
284 }
285
286 static Xapian::Document
287 find_document_for_doc_id (notmuch_database_t *notmuch, unsigned doc_id)
288 {
289     return notmuch->xapian_db->get_document (doc_id);
290 }
291
292 notmuch_message_t *
293 notmuch_database_find_message (notmuch_database_t *notmuch,
294                                const char *message_id)
295 {
296     notmuch_private_status_t status;
297     unsigned int doc_id;
298
299     status = _notmuch_database_find_unique_doc_id (notmuch, "id",
300                                                    message_id, &doc_id);
301
302     if (status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND)
303         return NULL;
304
305     return _notmuch_message_create (notmuch, notmuch, doc_id, NULL);
306 }
307
308 /* Advance 'str' past any whitespace or RFC 822 comments. A comment is
309  * a (potentially nested) parenthesized sequence with '\' used to
310  * escape any character (including parentheses).
311  *
312  * If the sequence to be skipped continues to the end of the string,
313  * then 'str' will be left pointing at the final terminating '\0'
314  * character.
315  */
316 static void
317 skip_space_and_comments (const char **str)
318 {
319     const char *s;
320
321     s = *str;
322     while (*s && (isspace (*s) || *s == '(')) {
323         while (*s && isspace (*s))
324             s++;
325         if (*s == '(') {
326             int nesting = 1;
327             s++;
328             while (*s && nesting) {
329                 if (*s == '(') {
330                     nesting++;
331                 } else if (*s == ')') {
332                     nesting--;
333                 } else if (*s == '\\') {
334                     if (*(s+1))
335                         s++;
336                 }
337                 s++;
338             }
339         }
340     }
341
342     *str = s;
343 }
344
345 /* Parse an RFC 822 message-id, discarding whitespace, any RFC 822
346  * comments, and the '<' and '>' delimeters.
347  *
348  * If not NULL, then *next will be made to point to the first character
349  * not parsed, (possibly pointing to the final '\0' terminator.
350  *
351  * Returns a newly talloc'ed string belonging to 'ctx'.
352  *
353  * Returns NULL if there is any error parsing the message-id. */
354 static char *
355 _parse_message_id (void *ctx, const char *message_id, const char **next)
356 {
357     const char *s, *end;
358     char *result;
359
360     if (message_id == NULL || *message_id == '\0')
361         return NULL;
362
363     s = message_id;
364
365     skip_space_and_comments (&s);
366
367     /* Skip any unstructured text as well. */
368     while (*s && *s != '<')
369         s++;
370
371     if (*s == '<') {
372         s++;
373     } else {
374         if (next)
375             *next = s;
376         return NULL;
377     }
378
379     skip_space_and_comments (&s);
380
381     end = s;
382     while (*end && *end != '>')
383         end++;
384     if (next) {
385         if (*end)
386             *next = end + 1;
387         else
388             *next = end;
389     }
390
391     if (end > s && *end == '>')
392         end--;
393     if (end <= s)
394         return NULL;
395
396     result = talloc_strndup (ctx, s, end - s + 1);
397
398     /* Finally, collapse any whitespace that is within the message-id
399      * itself. */
400     {
401         char *r;
402         int len;
403
404         for (r = result, len = strlen (r); *r; r++, len--)
405             if (*r == ' ' || *r == '\t')
406                 memmove (r, r+1, len);
407     }
408
409     return result;
410 }
411
412 /* Parse a References header value, putting a (talloc'ed under 'ctx')
413  * copy of each referenced message-id into 'hash'.
414  *
415  * We explicitly avoid including any reference identical to
416  * 'message_id' in the result (to avoid mass confusion when a single
417  * message references itself cyclically---and yes, mail messages are
418  * not infrequent in the wild that do this---don't ask me why).
419 */
420 static void
421 parse_references (void *ctx,
422                   const char *message_id,
423                   GHashTable *hash,
424                   const char *refs)
425 {
426     char *ref;
427
428     if (refs == NULL || *refs == '\0')
429         return;
430
431     while (*refs) {
432         ref = _parse_message_id (ctx, refs, &refs);
433
434         if (ref && strcmp (ref, message_id))
435             g_hash_table_insert (hash, ref, NULL);
436     }
437 }
438
439 notmuch_database_t *
440 notmuch_database_create (const char *path)
441 {
442     notmuch_database_t *notmuch = NULL;
443     char *notmuch_path = NULL;
444     struct stat st;
445     int err;
446
447     if (path == NULL) {
448         fprintf (stderr, "Error: Cannot create a database for a NULL path.\n");
449         goto DONE;
450     }
451
452     err = stat (path, &st);
453     if (err) {
454         fprintf (stderr, "Error: Cannot create database at %s: %s.\n",
455                  path, strerror (errno));
456         goto DONE;
457     }
458
459     if (! S_ISDIR (st.st_mode)) {
460         fprintf (stderr, "Error: Cannot create database at %s: Not a directory.\n",
461                  path);
462         goto DONE;
463     }
464
465     notmuch_path = talloc_asprintf (NULL, "%s/%s", path, ".notmuch");
466
467     err = mkdir (notmuch_path, 0755);
468
469     if (err) {
470         fprintf (stderr, "Error: Cannot create directory %s: %s.\n",
471                  notmuch_path, strerror (errno));
472         goto DONE;
473     }
474
475     notmuch = notmuch_database_open (path,
476                                      NOTMUCH_DATABASE_MODE_READ_WRITE);
477     notmuch_database_upgrade (notmuch, NULL, NULL);
478
479   DONE:
480     if (notmuch_path)
481         talloc_free (notmuch_path);
482
483     return notmuch;
484 }
485
486 notmuch_status_t
487 _notmuch_database_ensure_writable (notmuch_database_t *notmuch)
488 {
489     if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_ONLY) {
490         fprintf (stderr, "Cannot write to a read-only database.\n");
491         return NOTMUCH_STATUS_READ_ONLY_DATABASE;
492     }
493
494     return NOTMUCH_STATUS_SUCCESS;
495 }
496
497 notmuch_database_t *
498 notmuch_database_open (const char *path,
499                        notmuch_database_mode_t mode)
500 {
501     notmuch_database_t *notmuch = NULL;
502     char *notmuch_path = NULL, *xapian_path = NULL;
503     struct stat st;
504     int err;
505     unsigned int i, version;
506
507     if (asprintf (&notmuch_path, "%s/%s", path, ".notmuch") == -1) {
508         notmuch_path = NULL;
509         fprintf (stderr, "Out of memory\n");
510         goto DONE;
511     }
512
513     err = stat (notmuch_path, &st);
514     if (err) {
515         fprintf (stderr, "Error opening database at %s: %s\n",
516                  notmuch_path, strerror (errno));
517         goto DONE;
518     }
519
520     if (asprintf (&xapian_path, "%s/%s", notmuch_path, "xapian") == -1) {
521         xapian_path = NULL;
522         fprintf (stderr, "Out of memory\n");
523         goto DONE;
524     }
525
526     notmuch = talloc (NULL, notmuch_database_t);
527     notmuch->exception_reported = FALSE;
528     notmuch->path = talloc_strdup (notmuch, path);
529
530     if (notmuch->path[strlen (notmuch->path) - 1] == '/')
531         notmuch->path[strlen (notmuch->path) - 1] = '\0';
532
533     notmuch->needs_upgrade = FALSE;
534     notmuch->mode = mode;
535     try {
536         if (mode == NOTMUCH_DATABASE_MODE_READ_WRITE) {
537             notmuch->xapian_db = new Xapian::WritableDatabase (xapian_path,
538                                                                Xapian::DB_CREATE_OR_OPEN);
539             version = notmuch_database_get_version (notmuch);
540
541             if (version > NOTMUCH_DATABASE_VERSION) {
542                 fprintf (stderr,
543                          "Error: Notmuch database at %s\n"
544                          "       has a newer database format version (%u) than supported by this\n"
545                          "       version of notmuch (%u). Refusing to open this database in\n"
546                          "       read-write mode.\n",
547                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
548                 notmuch->mode = NOTMUCH_DATABASE_MODE_READ_ONLY;
549                 notmuch_database_close (notmuch);
550                 notmuch = NULL;
551                 goto DONE;
552             }
553
554             if (version < NOTMUCH_DATABASE_VERSION)
555                 notmuch->needs_upgrade = TRUE;
556         } else {
557             notmuch->xapian_db = new Xapian::Database (xapian_path);
558             version = notmuch_database_get_version (notmuch);
559             if (version > NOTMUCH_DATABASE_VERSION)
560             {
561                 fprintf (stderr,
562                          "Warning: Notmuch database at %s\n"
563                          "         has a newer database format version (%u) than supported by this\n"
564                          "         version of notmuch (%u). Some operations may behave incorrectly,\n"
565                          "         (but the database will not be harmed since it is being opened\n"
566                          "         in read-only mode).\n",
567                          notmuch_path, version, NOTMUCH_DATABASE_VERSION);
568             }
569         }
570         notmuch->query_parser = new Xapian::QueryParser;
571         notmuch->term_gen = new Xapian::TermGenerator;
572         notmuch->term_gen->set_stemmer (Xapian::Stem ("english"));
573         notmuch->value_range_processor = new Xapian::NumberValueRangeProcessor (NOTMUCH_VALUE_TIMESTAMP);
574
575         notmuch->query_parser->set_default_op (Xapian::Query::OP_AND);
576         notmuch->query_parser->set_database (*notmuch->xapian_db);
577         notmuch->query_parser->set_stemmer (Xapian::Stem ("english"));
578         notmuch->query_parser->set_stemming_strategy (Xapian::QueryParser::STEM_SOME);
579         notmuch->query_parser->add_valuerangeprocessor (notmuch->value_range_processor);
580
581         for (i = 0; i < ARRAY_SIZE (BOOLEAN_PREFIX_EXTERNAL); i++) {
582             prefix_t *prefix = &BOOLEAN_PREFIX_EXTERNAL[i];
583             notmuch->query_parser->add_boolean_prefix (prefix->name,
584                                                        prefix->prefix);
585         }
586
587         for (i = 0; i < ARRAY_SIZE (PROBABILISTIC_PREFIX); i++) {
588             prefix_t *prefix = &PROBABILISTIC_PREFIX[i];
589             notmuch->query_parser->add_prefix (prefix->name, prefix->prefix);
590         }
591     } catch (const Xapian::Error &error) {
592         fprintf (stderr, "A Xapian exception occurred opening database: %s\n",
593                  error.get_msg().c_str());
594         notmuch = NULL;
595     }
596
597   DONE:
598     if (notmuch_path)
599         free (notmuch_path);
600     if (xapian_path)
601         free (xapian_path);
602
603     return notmuch;
604 }
605
606 void
607 notmuch_database_close (notmuch_database_t *notmuch)
608 {
609     try {
610         if (notmuch->mode == NOTMUCH_DATABASE_MODE_READ_WRITE)
611             (static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db))->flush ();
612     } catch (const Xapian::Error &error) {
613         if (! notmuch->exception_reported) {
614             fprintf (stderr, "Error: A Xapian exception occurred flushing database: %s\n",
615                      error.get_msg().c_str());
616         }
617     }
618
619     delete notmuch->term_gen;
620     delete notmuch->query_parser;
621     delete notmuch->xapian_db;
622     delete notmuch->value_range_processor;
623     talloc_free (notmuch);
624 }
625
626 const char *
627 notmuch_database_get_path (notmuch_database_t *notmuch)
628 {
629     return notmuch->path;
630 }
631
632 unsigned int
633 notmuch_database_get_version (notmuch_database_t *notmuch)
634 {
635     unsigned int version;
636     string version_string;
637     const char *str;
638     char *end;
639
640     version_string = notmuch->xapian_db->get_metadata ("version");
641     if (version_string.empty ())
642         return 0;
643
644     str = version_string.c_str ();
645     if (str == NULL || *str == '\0')
646         return 0;
647
648     version = strtoul (str, &end, 10);
649     if (*end != '\0')
650         INTERNAL_ERROR ("Malformed database version: %s", str);
651
652     return version;
653 }
654
655 notmuch_bool_t
656 notmuch_database_needs_upgrade (notmuch_database_t *notmuch)
657 {
658     return notmuch->needs_upgrade;
659 }
660
661 static volatile sig_atomic_t do_progress_notify = 0;
662
663 static void
664 handle_sigalrm (unused (int signal))
665 {
666     do_progress_notify = 1;
667 }
668
669 /* Upgrade the current database.
670  *
671  * After opening a database in read-write mode, the client should
672  * check if an upgrade is needed (notmuch_database_needs_upgrade) and
673  * if so, upgrade with this function before making any modifications.
674  *
675  * The optional progress_notify callback can be used by the caller to
676  * provide progress indication to the user. If non-NULL it will be
677  * called periodically with 'count' as the number of messages upgraded
678  * so far and 'total' the overall number of messages that will be
679  * converted.
680  */
681 notmuch_status_t
682 notmuch_database_upgrade (notmuch_database_t *notmuch,
683                           void (*progress_notify) (void *closure,
684                                                    unsigned int count,
685                                                    unsigned int total),
686                           void *closure)
687 {
688     Xapian::WritableDatabase *db;
689     struct sigaction action;
690     struct itimerval timerval;
691     notmuch_bool_t timer_is_active = FALSE;
692     unsigned int version;
693     notmuch_status_t status;
694
695     status = _notmuch_database_ensure_writable (notmuch);
696     if (status)
697         return status;
698
699     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
700
701     version = notmuch_database_get_version (notmuch);
702
703     if (version >= NOTMUCH_DATABASE_VERSION)
704         return NOTMUCH_STATUS_SUCCESS;
705
706     if (progress_notify) {
707         /* Setup our handler for SIGALRM */
708         memset (&action, 0, sizeof (struct sigaction));
709         action.sa_handler = handle_sigalrm;
710         sigemptyset (&action.sa_mask);
711         action.sa_flags = SA_RESTART;
712         sigaction (SIGALRM, &action, NULL);
713
714         /* Then start a timer to send SIGALRM once per second. */
715         timerval.it_interval.tv_sec = 1;
716         timerval.it_interval.tv_usec = 0;
717         timerval.it_value.tv_sec = 1;
718         timerval.it_value.tv_usec = 0;
719         setitimer (ITIMER_REAL, &timerval, NULL);
720
721         timer_is_active = TRUE;
722     }
723
724     /* Before version 1, each message document had its filename in the
725      * data field. Move that into the new format by calling
726      * notmuch_message_add_filename.
727      */
728     if (version < 1) {
729         unsigned int count = 0, total;
730         notmuch_query_t *query = notmuch_query_create (notmuch, "");
731         notmuch_messages_t *messages;
732         notmuch_message_t *message;
733
734         total = notmuch_query_count_messages (query);
735
736         for (messages = notmuch_query_search_messages (query);
737              notmuch_messages_has_more (messages);
738              notmuch_messages_advance (messages))
739         {
740             if (do_progress_notify) {
741                 progress_notify (closure, count, total);
742                 do_progress_notify = 0;
743             }
744
745             message = notmuch_messages_get (messages);
746
747             _notmuch_message_upgrade_filename_storage (message);
748
749             count++;
750         }
751     }
752
753     /* Also, before version 1 we stored directory timestamps in
754      * XTIMESTAMP documents instead of the current XDIRECTORY
755      * documents. So convert those as well. */
756     if (version < 1) {
757         Xapian::TermIterator t, t_end;
758
759         t_end = notmuch->xapian_db->allterms_end ("XTIMESTAMP");
760
761         for (t = notmuch->xapian_db->allterms_begin ("XTIMESTAMP");
762              t != t_end;
763              t++)
764         {
765             Xapian::PostingIterator p, p_end;
766             std::string term = *t;
767
768             p_end = notmuch->xapian_db->postlist_end (term);
769
770             for (p = notmuch->xapian_db->postlist_begin (term);
771                  p != p_end;
772                  p++)
773             {
774                 Xapian::Document document;
775                 time_t mtime;
776                 notmuch_directory_t *directory;
777
778                 document = find_document_for_doc_id (notmuch, *p);
779                 mtime = Xapian::sortable_unserialise (
780                     document.get_value (NOTMUCH_VALUE_TIMESTAMP));
781
782                 directory = notmuch_database_get_directory (notmuch,
783                                                             term.c_str() + 10);
784                 notmuch_directory_set_mtime (directory, mtime);
785                 notmuch_directory_destroy (directory);
786             }
787         }
788     }
789
790     db->set_metadata ("version", STRINGIFY (NOTMUCH_DATABASE_VERSION));
791     db->flush ();
792
793     if (timer_is_active) {
794         /* Now stop the timer. */
795         timerval.it_interval.tv_sec = 0;
796         timerval.it_interval.tv_usec = 0;
797         timerval.it_value.tv_sec = 0;
798         timerval.it_value.tv_usec = 0;
799         setitimer (ITIMER_REAL, &timerval, NULL);
800
801         /* And disable the signal handler. */
802         action.sa_handler = SIG_IGN;
803         sigaction (SIGALRM, &action, NULL);
804     }
805
806     return NOTMUCH_STATUS_SUCCESS;
807 }
808
809 /* We allow the user to use arbitrarily long paths for directories. But
810  * we have a term-length limit. So if we exceed that, we'll use the
811  * SHA-1 of the path for the database term.
812  *
813  * Note: This function may return the original value of 'path'. If it
814  * does not, then the caller is responsible to free() the returned
815  * value.
816  */
817 const char *
818 _notmuch_database_get_directory_db_path (const char *path)
819 {
820     int term_len = strlen (_find_prefix ("directory")) + strlen (path);
821
822     if (term_len > NOTMUCH_TERM_MAX)
823         return notmuch_sha1_of_string (path);
824     else
825         return path;
826 }
827
828 /* Given a path, split it into two parts: the directory part is all
829  * components except for the last, and the basename is that last
830  * component. Getting the return-value for either part is optional
831  * (the caller can pass NULL).
832  *
833  * The original 'path' can represent either a regular file or a
834  * directory---the splitting will be carried out in the same way in
835  * either case. Trailing slashes on 'path' will be ignored, and any
836  * cases of multiple '/' characters appearing in series will be
837  * treated as a single '/'.
838  *
839  * Allocation (if any) will have 'ctx' as the talloc owner. But
840  * pointers will be returned within the original path string whenever
841  * possible.
842  *
843  * Note: If 'path' is non-empty and contains no non-trailing slash,
844  * (that is, consists of a filename with no parent directory), then
845  * the directory returned will be an empty string. However, if 'path'
846  * is an empty string, then both directory and basename will be
847  * returned as NULL.
848  */
849 notmuch_status_t
850 _notmuch_database_split_path (void *ctx,
851                               const char *path,
852                               const char **directory,
853                               const char **basename)
854 {
855     const char *slash;
856
857     if (path == NULL || *path == '\0') {
858         if (directory)
859             *directory = NULL;
860         if (basename)
861             *basename = NULL;
862         return NOTMUCH_STATUS_SUCCESS;
863     }
864
865     /* Find the last slash (not counting a trailing slash), if any. */
866
867     slash = path + strlen (path) - 1;
868
869     /* First, skip trailing slashes. */
870     while (slash != path) {
871         if (*slash != '/')
872             break;
873
874         --slash;
875     }
876
877     /* Then, find a slash. */
878     while (slash != path) {
879         if (*slash == '/')
880             break;
881
882         if (basename)
883             *basename = slash;
884
885         --slash;
886     }
887
888     /* Finally, skip multiple slashes. */
889     while (slash != path) {
890         if (*slash != '/')
891             break;
892
893         --slash;
894     }
895
896     if (slash == path) {
897         if (directory)
898             *directory = talloc_strdup (ctx, "");
899         if (basename)
900             *basename = path;
901     } else {
902         if (directory)
903             *directory = talloc_strndup (ctx, path, slash - path + 1);
904     }
905
906     return NOTMUCH_STATUS_SUCCESS;
907 }
908
909 notmuch_status_t
910 _notmuch_database_find_directory_id (notmuch_database_t *notmuch,
911                                      const char *path,
912                                      unsigned int *directory_id)
913 {
914     notmuch_directory_t *directory;
915     notmuch_status_t status;
916
917     if (path == NULL) {
918         *directory_id = 0;
919         return NOTMUCH_STATUS_SUCCESS;
920     }
921
922     directory = _notmuch_directory_create (notmuch, path, &status);
923     if (status) {
924         *directory_id = -1;
925         return status;
926     }
927
928     *directory_id = _notmuch_directory_get_document_id (directory);
929
930     notmuch_directory_destroy (directory);
931
932     return NOTMUCH_STATUS_SUCCESS;
933 }
934
935 const char *
936 _notmuch_database_get_directory_path (void *ctx,
937                                       notmuch_database_t *notmuch,
938                                       unsigned int doc_id)
939 {
940     Xapian::Document document;
941
942     document = find_document_for_doc_id (notmuch, doc_id);
943
944     return talloc_strdup (ctx, document.get_data ().c_str ());
945 }
946
947 /* Given a legal 'filename' for the database, (either relative to
948  * database path or absolute with initial components identical to
949  * database path), return a new string (with 'ctx' as the talloc
950  * owner) suitable for use as a direntry term value.
951  *
952  * The necessary directory documents will be created in the database
953  * as needed.
954  */
955 notmuch_status_t
956 _notmuch_database_filename_to_direntry (void *ctx,
957                                         notmuch_database_t *notmuch,
958                                         const char *filename,
959                                         char **direntry)
960 {
961     const char *relative, *directory, *basename;
962     Xapian::docid directory_id;
963     notmuch_status_t status;
964
965     relative = _notmuch_database_relative_path (notmuch, filename);
966
967     status = _notmuch_database_split_path (ctx, relative,
968                                            &directory, &basename);
969     if (status)
970         return status;
971
972     status = _notmuch_database_find_directory_id (notmuch, directory,
973                                                   &directory_id);
974     if (status)
975         return status;
976
977     *direntry = talloc_asprintf (ctx, "%u:%s", directory_id, basename);
978
979     return NOTMUCH_STATUS_SUCCESS;
980 }
981
982 /* Given a legal 'path' for the database, return the relative path.
983  *
984  * The return value will be a pointer to the originl path contents,
985  * and will be either the original string (if 'path' was relative) or
986  * a portion of the string (if path was absolute and begins with the
987  * database path).
988  */
989 const char *
990 _notmuch_database_relative_path (notmuch_database_t *notmuch,
991                                  const char *path)
992 {
993     const char *db_path, *relative;
994     unsigned int db_path_len;
995
996     db_path = notmuch_database_get_path (notmuch);
997     db_path_len = strlen (db_path);
998
999     relative = path;
1000
1001     if (*relative == '/') {
1002         while (*relative == '/' && *(relative+1) == '/')
1003             relative++;
1004
1005         if (strncmp (relative, db_path, db_path_len) == 0)
1006         {
1007             relative += db_path_len;
1008             while (*relative == '/')
1009                 relative++;
1010         }
1011     }
1012
1013     return relative;
1014 }
1015
1016 notmuch_directory_t *
1017 notmuch_database_get_directory (notmuch_database_t *notmuch,
1018                                 const char *path)
1019 {
1020     notmuch_status_t status;
1021
1022     return _notmuch_directory_create (notmuch, path, &status);
1023 }
1024
1025 /* Find the thread ID to which the message with 'message_id' belongs.
1026  *
1027  * Returns NULL if no message with message ID 'message_id' is in the
1028  * database.
1029  *
1030  * Otherwise, returns a newly talloced string belonging to 'ctx'.
1031  */
1032 static const char *
1033 _resolve_message_id_to_thread_id (notmuch_database_t *notmuch,
1034                                   void *ctx,
1035                                   const char *message_id)
1036 {
1037     notmuch_message_t *message;
1038     const char *ret = NULL;
1039
1040     message = notmuch_database_find_message (notmuch, message_id);
1041     if (message == NULL)
1042         goto DONE;
1043
1044     ret = talloc_steal (ctx, notmuch_message_get_thread_id (message));
1045
1046   DONE:
1047     if (message)
1048         notmuch_message_destroy (message);
1049
1050     return ret;
1051 }
1052
1053 static notmuch_status_t
1054 _merge_threads (notmuch_database_t *notmuch,
1055                 const char *winner_thread_id,
1056                 const char *loser_thread_id)
1057 {
1058     Xapian::PostingIterator loser, loser_end;
1059     notmuch_message_t *message = NULL;
1060     notmuch_private_status_t private_status;
1061     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1062
1063     find_doc_ids (notmuch, "thread", loser_thread_id, &loser, &loser_end);
1064
1065     for ( ; loser != loser_end; loser++) {
1066         message = _notmuch_message_create (notmuch, notmuch,
1067                                            *loser, &private_status);
1068         if (message == NULL) {
1069             ret = COERCE_STATUS (private_status,
1070                                  "Cannot find document for doc_id from query");
1071             goto DONE;
1072         }
1073
1074         _notmuch_message_remove_term (message, "thread", loser_thread_id);
1075         _notmuch_message_add_term (message, "thread", winner_thread_id);
1076         _notmuch_message_sync (message);
1077
1078         notmuch_message_destroy (message);
1079         message = NULL;
1080     }
1081
1082   DONE:
1083     if (message)
1084         notmuch_message_destroy (message);
1085
1086     return ret;
1087 }
1088
1089 static void
1090 _my_talloc_free_for_g_hash (void *ptr)
1091 {
1092     talloc_free (ptr);
1093 }
1094
1095 static notmuch_status_t
1096 _notmuch_database_link_message_to_parents (notmuch_database_t *notmuch,
1097                                            notmuch_message_t *message,
1098                                            notmuch_message_file_t *message_file,
1099                                            const char **thread_id)
1100 {
1101     GHashTable *parents = NULL;
1102     const char *refs, *in_reply_to, *in_reply_to_message_id;
1103     GList *l, *keys = NULL;
1104     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1105
1106     parents = g_hash_table_new_full (g_str_hash, g_str_equal,
1107                                      _my_talloc_free_for_g_hash, NULL);
1108
1109     refs = notmuch_message_file_get_header (message_file, "references");
1110     parse_references (message, notmuch_message_get_message_id (message),
1111                       parents, refs);
1112
1113     in_reply_to = notmuch_message_file_get_header (message_file, "in-reply-to");
1114     parse_references (message, notmuch_message_get_message_id (message),
1115                       parents, in_reply_to);
1116
1117     /* Carefully avoid adding any self-referential in-reply-to term. */
1118     in_reply_to_message_id = _parse_message_id (message, in_reply_to, NULL);
1119     if (in_reply_to_message_id &&
1120         strcmp (in_reply_to_message_id,
1121                 notmuch_message_get_message_id (message)))
1122     {
1123         _notmuch_message_add_term (message, "replyto",
1124                              _parse_message_id (message, in_reply_to, NULL));
1125     }
1126
1127     keys = g_hash_table_get_keys (parents);
1128     for (l = keys; l; l = l->next) {
1129         char *parent_message_id;
1130         const char *parent_thread_id;
1131
1132         parent_message_id = (char *) l->data;
1133         parent_thread_id = _resolve_message_id_to_thread_id (notmuch,
1134                                                              message,
1135                                                              parent_message_id);
1136
1137         if (parent_thread_id == NULL) {
1138             _notmuch_message_add_term (message, "reference",
1139                                        parent_message_id);
1140         } else {
1141             if (*thread_id == NULL) {
1142                 *thread_id = talloc_strdup (message, parent_thread_id);
1143                 _notmuch_message_add_term (message, "thread", *thread_id);
1144             } else if (strcmp (*thread_id, parent_thread_id)) {
1145                 ret = _merge_threads (notmuch, *thread_id, parent_thread_id);
1146                 if (ret)
1147                     goto DONE;
1148             }
1149         }
1150     }
1151
1152   DONE:
1153     if (keys)
1154         g_list_free (keys);
1155     if (parents)
1156         g_hash_table_unref (parents);
1157
1158     return ret;
1159 }
1160
1161 static notmuch_status_t
1162 _notmuch_database_link_message_to_children (notmuch_database_t *notmuch,
1163                                             notmuch_message_t *message,
1164                                             const char **thread_id)
1165 {
1166     const char *message_id = notmuch_message_get_message_id (message);
1167     Xapian::PostingIterator child, children_end;
1168     notmuch_message_t *child_message = NULL;
1169     const char *child_thread_id;
1170     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1171     notmuch_private_status_t private_status;
1172
1173     find_doc_ids (notmuch, "reference", message_id, &child, &children_end);
1174
1175     for ( ; child != children_end; child++) {
1176
1177         child_message = _notmuch_message_create (message, notmuch,
1178                                                  *child, &private_status);
1179         if (child_message == NULL) {
1180             ret = COERCE_STATUS (private_status,
1181                                  "Cannot find document for doc_id from query");
1182             goto DONE;
1183         }
1184
1185         child_thread_id = notmuch_message_get_thread_id (child_message);
1186         if (*thread_id == NULL) {
1187             *thread_id = talloc_strdup (message, child_thread_id);
1188             _notmuch_message_add_term (message, "thread", *thread_id);
1189         } else if (strcmp (*thread_id, child_thread_id)) {
1190             _notmuch_message_remove_term (child_message, "reference",
1191                                           message_id);
1192             _notmuch_message_sync (child_message);
1193             ret = _merge_threads (notmuch, *thread_id, child_thread_id);
1194             if (ret)
1195                 goto DONE;
1196         }
1197
1198         notmuch_message_destroy (child_message);
1199         child_message = NULL;
1200     }
1201
1202   DONE:
1203     if (child_message)
1204         notmuch_message_destroy (child_message);
1205
1206     return ret;
1207 }
1208
1209 /* Given a (mostly empty) 'message' and its corresponding
1210  * 'message_file' link it to existing threads in the database.
1211  *
1212  * We first look at 'message_file' and its link-relevant headers
1213  * (References and In-Reply-To) for message IDs. We also look in the
1214  * database for existing message that reference 'message'.
1215  *
1216  * The end result is to call _notmuch_message_ensure_thread_id which
1217  * generates a new thread ID if the message doesn't connect to any
1218  * existing threads.
1219  */
1220 static notmuch_status_t
1221 _notmuch_database_link_message (notmuch_database_t *notmuch,
1222                                 notmuch_message_t *message,
1223                                 notmuch_message_file_t *message_file)
1224 {
1225     notmuch_status_t status;
1226     const char *thread_id = NULL;
1227
1228     status = _notmuch_database_link_message_to_parents (notmuch, message,
1229                                                         message_file,
1230                                                         &thread_id);
1231     if (status)
1232         return status;
1233
1234     status = _notmuch_database_link_message_to_children (notmuch, message,
1235                                                          &thread_id);
1236     if (status)
1237         return status;
1238
1239     if (thread_id == NULL)
1240         _notmuch_message_ensure_thread_id (message);
1241
1242     return NOTMUCH_STATUS_SUCCESS;
1243 }
1244
1245 notmuch_status_t
1246 notmuch_database_add_message (notmuch_database_t *notmuch,
1247                               const char *filename,
1248                               notmuch_message_t **message_ret)
1249 {
1250     notmuch_message_file_t *message_file;
1251     notmuch_message_t *message = NULL;
1252     notmuch_status_t ret = NOTMUCH_STATUS_SUCCESS;
1253     notmuch_private_status_t private_status;
1254
1255     const char *date, *header;
1256     const char *from, *to, *subject;
1257     char *message_id = NULL;
1258
1259     if (message_ret)
1260         *message_ret = NULL;
1261
1262     ret = _notmuch_database_ensure_writable (notmuch);
1263     if (ret)
1264         return ret;
1265
1266     message_file = notmuch_message_file_open (filename);
1267     if (message_file == NULL)
1268         return NOTMUCH_STATUS_FILE_ERROR;
1269
1270     notmuch_message_file_restrict_headers (message_file,
1271                                            "date",
1272                                            "from",
1273                                            "in-reply-to",
1274                                            "message-id",
1275                                            "references",
1276                                            "subject",
1277                                            "to",
1278                                            (char *) NULL);
1279
1280     try {
1281         /* Before we do any real work, (especially before doing a
1282          * potential SHA-1 computation on the entire file's contents),
1283          * let's make sure that what we're looking at looks like an
1284          * actual email message.
1285          */
1286         from = notmuch_message_file_get_header (message_file, "from");
1287         subject = notmuch_message_file_get_header (message_file, "subject");
1288         to = notmuch_message_file_get_header (message_file, "to");
1289
1290         if ((from == NULL || *from == '\0') &&
1291             (subject == NULL || *subject == '\0') &&
1292             (to == NULL || *to == '\0'))
1293         {
1294             ret = NOTMUCH_STATUS_FILE_NOT_EMAIL;
1295             goto DONE;
1296         }
1297
1298         /* Now that we're sure it's mail, the first order of business
1299          * is to find a message ID (or else create one ourselves). */
1300
1301         header = notmuch_message_file_get_header (message_file, "message-id");
1302         if (header && *header != '\0') {
1303             message_id = _parse_message_id (message_file, header, NULL);
1304
1305             /* So the header value isn't RFC-compliant, but it's
1306              * better than no message-id at all. */
1307             if (message_id == NULL)
1308                 message_id = talloc_strdup (message_file, header);
1309
1310             /* Reject a Message ID that's too long. */
1311             if (message_id && strlen (message_id) + 1 > NOTMUCH_TERM_MAX) {
1312                 talloc_free (message_id);
1313                 message_id = NULL;
1314             }
1315         }
1316
1317         if (message_id == NULL ) {
1318             /* No message-id at all, let's generate one by taking a
1319              * hash over the file's contents. */
1320             char *sha1 = notmuch_sha1_of_file (filename);
1321
1322             /* If that failed too, something is really wrong. Give up. */
1323             if (sha1 == NULL) {
1324                 ret = NOTMUCH_STATUS_FILE_ERROR;
1325                 goto DONE;
1326             }
1327
1328             message_id = talloc_asprintf (message_file,
1329                                           "notmuch-sha1-%s", sha1);
1330             free (sha1);
1331         }
1332
1333         /* Now that we have a message ID, we get a message object,
1334          * (which may or may not reference an existing document in the
1335          * database). */
1336
1337         message = _notmuch_message_create_for_message_id (notmuch,
1338                                                           message_id,
1339                                                           &private_status);
1340
1341         talloc_free (message_id);
1342
1343         if (message == NULL) {
1344             ret = COERCE_STATUS (private_status,
1345                                  "Unexpected status value from _notmuch_message_create_for_message_id");
1346             goto DONE;
1347         }
1348
1349         _notmuch_message_add_filename (message, filename);
1350
1351         /* Is this a newly created message object? */
1352         if (private_status == NOTMUCH_PRIVATE_STATUS_NO_DOCUMENT_FOUND) {
1353             _notmuch_message_add_term (message, "type", "mail");
1354
1355             ret = _notmuch_database_link_message (notmuch, message,
1356                                                   message_file);
1357             if (ret)
1358                 goto DONE;
1359
1360             date = notmuch_message_file_get_header (message_file, "date");
1361             _notmuch_message_set_date (message, date);
1362
1363             _notmuch_message_index_file (message, filename);
1364         } else {
1365             ret = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1366         }
1367
1368         _notmuch_message_sync (message);
1369     } catch (const Xapian::Error &error) {
1370         fprintf (stderr, "A Xapian exception occurred adding message: %s.\n",
1371                  error.get_description().c_str());
1372         notmuch->exception_reported = TRUE;
1373         ret = NOTMUCH_STATUS_XAPIAN_EXCEPTION;
1374         goto DONE;
1375     }
1376
1377   DONE:
1378     if (message) {
1379         if (ret == NOTMUCH_STATUS_SUCCESS && message_ret)
1380             *message_ret = message;
1381         else
1382             notmuch_message_destroy (message);
1383     }
1384
1385     if (message_file)
1386         notmuch_message_file_close (message_file);
1387
1388     return ret;
1389 }
1390
1391 notmuch_status_t
1392 notmuch_database_remove_message (notmuch_database_t *notmuch,
1393                                  const char *filename)
1394 {
1395     Xapian::WritableDatabase *db;
1396     void *local = talloc_new (notmuch);
1397     const char *prefix = _find_prefix ("file-direntry");
1398     char *direntry, *term;
1399     Xapian::PostingIterator i, end;
1400     Xapian::Document document;
1401     notmuch_status_t status;
1402
1403     status = _notmuch_database_ensure_writable (notmuch);
1404     if (status)
1405         return status;
1406
1407     db = static_cast <Xapian::WritableDatabase *> (notmuch->xapian_db);
1408
1409     status = _notmuch_database_filename_to_direntry (local, notmuch,
1410                                                      filename, &direntry);
1411     if (status)
1412         return status;
1413
1414     term = talloc_asprintf (notmuch, "%s%s", prefix, direntry);
1415
1416     find_doc_ids_for_term (notmuch, term, &i, &end);
1417
1418     for ( ; i != end; i++) {
1419         Xapian::TermIterator j;
1420
1421         document = find_document_for_doc_id (notmuch, *i);
1422
1423         document.remove_term (term);
1424
1425         j = document.termlist_begin ();
1426         j.skip_to (prefix);
1427
1428         /* Was this the last file-direntry in the message? */
1429         if (j == document.termlist_end () ||
1430             strncmp ((*j).c_str (), prefix, strlen (prefix)))
1431         {
1432             db->delete_document (document.get_docid ());
1433             status = NOTMUCH_STATUS_SUCCESS;
1434         } else {
1435             db->replace_document (document.get_docid (), document);
1436             status = NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID;
1437         }
1438     }
1439
1440     talloc_free (local);
1441
1442     return status;
1443 }
1444
1445 notmuch_tags_t *
1446 _notmuch_convert_tags (void *ctx, Xapian::TermIterator &i,
1447                        Xapian::TermIterator &end)
1448 {
1449     const char *prefix = _find_prefix ("tag");
1450     notmuch_tags_t *tags;
1451     std::string tag;
1452
1453     /* Currently this iteration is written with the assumption that
1454      * "tag" has a single-character prefix. */
1455     assert (strlen (prefix) == 1);
1456
1457     tags = _notmuch_tags_create (ctx);
1458     if (unlikely (tags == NULL))
1459         return NULL;
1460
1461     i.skip_to (prefix);
1462
1463     while (i != end) {
1464         tag = *i;
1465
1466         if (tag.empty () || tag[0] != *prefix)
1467             break;
1468
1469         _notmuch_tags_add_tag (tags, tag.c_str () + 1);
1470
1471         i++;
1472     }
1473
1474     _notmuch_tags_prepare_iterator (tags);
1475
1476     return tags;
1477 }
1478
1479 notmuch_tags_t *
1480 notmuch_database_get_all_tags (notmuch_database_t *db)
1481 {
1482     Xapian::TermIterator i, end;
1483     i = db->xapian_db->allterms_begin();
1484     end = db->xapian_db->allterms_end();
1485     return _notmuch_convert_tags(db, i, end);
1486 }