]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
lib: Update documentation of notmuch_database_add_message.
[notmuch] / notmuch-new.c
1 /* notmuch - Not much of an email program, (just index and search)
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 "notmuch-client.h"
22
23 #include <unistd.h>
24
25 typedef struct _filename_node {
26     char *filename;
27     struct _filename_node *next;
28 } _filename_node_t;
29
30 typedef struct _filename_list {
31     _filename_node_t *head;
32     _filename_node_t **tail;
33 } _filename_list_t;
34
35 typedef struct {
36     int output_is_a_tty;
37     int verbose;
38
39     int total_files;
40     int processed_files;
41     int added_messages;
42     struct timeval tv_start;
43
44     _filename_list_t *removed_files;
45     _filename_list_t *removed_directories;
46 } add_files_state_t;
47
48 static volatile sig_atomic_t do_add_files_print_progress = 0;
49
50 static void
51 handle_sigalrm (unused (int signal))
52 {
53     do_add_files_print_progress = 1;
54 }
55
56 static volatile sig_atomic_t interrupted;
57
58 static void
59 handle_sigint (unused (int sig))
60 {
61     ssize_t ignored;
62     static char msg[] = "Stopping...         \n";
63
64     ignored = write(2, msg, sizeof(msg)-1);
65     interrupted = 1;
66 }
67
68 static _filename_list_t *
69 _filename_list_create (const void *ctx)
70 {
71     _filename_list_t *list;
72
73     list = talloc (ctx, _filename_list_t);
74     if (list == NULL)
75         return NULL;
76
77     list->head = NULL;
78     list->tail = &list->head;
79
80     return list;
81 }
82
83 static void
84 _filename_list_add (_filename_list_t *list,
85                     const char *filename)
86 {
87     _filename_node_t *node = talloc (list, _filename_node_t);
88
89     node->filename = talloc_strdup (list, filename);
90     node->next = NULL;
91
92     *(list->tail) = node;
93     list->tail = &node->next;
94 }
95
96 static void
97 tag_inbox_and_unread (notmuch_message_t *message)
98 {
99     notmuch_message_add_tag (message, "inbox");
100     notmuch_message_add_tag (message, "unread");
101 }
102
103 static void
104 add_files_print_progress (add_files_state_t *state)
105 {
106     struct timeval tv_now;
107     double elapsed_overall, rate_overall;
108
109     gettimeofday (&tv_now, NULL);
110
111     elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
112     rate_overall = (state->processed_files) / elapsed_overall;
113
114     printf ("Processed %d", state->processed_files);
115
116     if (state->total_files) {
117         double time_remaining;
118
119         time_remaining = ((state->total_files - state->processed_files) /
120                           rate_overall);
121         printf (" of %d files (", state->total_files);
122         notmuch_time_print_formatted_seconds (time_remaining);
123         printf (" remaining).      \r");
124     } else {
125         printf (" files (%d files/sec.)    \r", (int) rate_overall);
126     }
127
128     fflush (stdout);
129 }
130
131 static int
132 dirent_sort_inode (const struct dirent **a, const struct dirent **b)
133 {
134     return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
135 }
136
137 static int
138 dirent_sort_strcmp_name (const struct dirent **a, const struct dirent **b)
139 {
140     return strcmp ((*a)->d_name, (*b)->d_name);
141 }
142
143 /* Test if the directory looks like a Maildir directory.
144  *
145  * Search through the array of directory entries to see if we can find all
146  * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
147  *
148  * Return 1 if the directory looks like a Maildir and 0 otherwise.
149  */
150 static int
151 _entries_resemble_maildir (struct dirent **entries, int count)
152 {
153     int i, found = 0;
154
155     for (i = 0; i < count; i++) {
156         if (entries[i]->d_type != DT_DIR)
157             continue;
158
159         if (strcmp(entries[i]->d_name, "new") == 0 ||
160             strcmp(entries[i]->d_name, "cur") == 0 ||
161             strcmp(entries[i]->d_name, "tmp") == 0)
162         {
163             found++;
164             if (found == 3)
165                 return 1;
166         }
167     }
168
169     return 0;
170 }
171
172 /* Examine 'path' recursively as follows:
173  *
174  *   o Ask the filesystem for the mtime of 'path' (fs_mtime)
175  *   o Ask the database for its timestamp of 'path' (db_mtime)
176  *
177  *   o Ask the filesystem for files and directories within 'path'
178  *     (via scandir and stored in fs_entries)
179  *   o Ask the database for files and directories within 'path'
180  *     (db_files and db_subdirs)
181  *
182  *   o Pass 1: For each directory in fs_entries, recursively call into
183  *     this same function.
184  *
185  *   o Pass 2: If 'fs_mtime' > 'db_mtime', then walk fs_entries
186  *     simultaneously with db_files and db_subdirs. Look for one of
187  *     three interesting cases:
188  *
189  *         1. Regular file in fs_entries and not in db_files
190  *            This is a new file to add_message into the database.
191  *
192  *         2. Filename in db_files not in fs_entries.
193  *            This is a file that has been removed from the mail store.
194  *
195  *         3. Directory in db_subdirs not in fs_entries
196  *            This is a directory that has been removed from the mail store.
197  *
198  *     Note that the addition of a directory is not interesting here,
199  *     since that will have been taken care of in pass 1. Also, we
200  *     don't immediately act on file/directory removal since we must
201  *     ensure that in the case of a rename that the new filename is
202  *     added before the old filename is removed, (so that no
203  *     information is lost from the database).
204  *
205  *   o Tell the database to update its time of 'path' to 'fs_mtime'
206  */
207 static notmuch_status_t
208 add_files_recursive (notmuch_database_t *notmuch,
209                      const char *path,
210                      add_files_state_t *state)
211 {
212     DIR *dir = NULL;
213     struct dirent *entry = NULL;
214     char *next = NULL;
215     time_t fs_mtime, db_mtime;
216     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
217     notmuch_message_t *message = NULL;
218     struct dirent **fs_entries = NULL;
219     int i, num_fs_entries;
220     notmuch_directory_t *directory;
221     notmuch_filenames_t *db_files = NULL;
222     notmuch_filenames_t *db_subdirs = NULL;
223     struct stat st;
224     notmuch_bool_t is_maildir;
225
226     if (stat (path, &st)) {
227         fprintf (stderr, "Error reading directory %s: %s\n",
228                  path, strerror (errno));
229         return NOTMUCH_STATUS_FILE_ERROR;
230     }
231
232     if (! S_ISDIR (st.st_mode)) {
233         fprintf (stderr, "Error: %s is not a directory.\n", path);
234         return NOTMUCH_STATUS_FILE_ERROR;
235     }
236
237     fs_mtime = st.st_mtime;
238
239     directory = notmuch_database_get_directory (notmuch, path);
240     db_mtime = notmuch_directory_get_mtime (directory);
241
242     /* If the database knows about this directory, then we sort based
243      * on strcmp to match the database sorting. Otherwise, we can do
244      * inode-based sorting for faster filesystem operation. */
245     num_fs_entries = scandir (path, &fs_entries, 0,
246                               db_mtime ?
247                               dirent_sort_strcmp_name : dirent_sort_inode);
248
249     if (num_fs_entries == -1) {
250         fprintf (stderr, "Error opening directory %s: %s\n",
251                  path, strerror (errno));
252         ret = NOTMUCH_STATUS_FILE_ERROR;
253         goto DONE;
254     }
255
256     /* Pass 1: Recurse into all sub-directories. */
257     is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
258
259     for (i = 0; i < num_fs_entries; i++) {
260         if (interrupted)
261             break;
262
263         entry = fs_entries[i];
264
265         if (entry->d_type != DT_DIR)
266             continue;
267
268         /* Ignore special directories to avoid infinite recursion.
269          * Also ignore the .notmuch directory and any "tmp" directory
270          * that appears within a maildir.
271          */
272         /* XXX: Eventually we'll want more sophistication to let the
273          * user specify files to be ignored. */
274         if (strcmp (entry->d_name, ".") == 0 ||
275             strcmp (entry->d_name, "..") == 0 ||
276             (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
277             strcmp (entry->d_name, ".notmuch") ==0)
278         {
279             continue;
280         }
281
282         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
283         status = add_files_recursive (notmuch, next, state);
284         if (status && ret == NOTMUCH_STATUS_SUCCESS)
285             ret = status;
286         talloc_free (next);
287         next = NULL;
288     }
289
290     /* If this directory hasn't been modified since the last
291      * "notmuch new", then we can skip the second pass entirely. */
292     if (fs_mtime <= db_mtime)
293         goto DONE;
294
295     /* Pass 2: Scan for new files, removed files, and removed directories. */
296     db_files = notmuch_directory_get_child_files (directory);
297     db_subdirs = notmuch_directory_get_child_directories (directory);
298
299     for (i = 0; i < num_fs_entries; i++)
300     {
301         if (interrupted)
302             break;
303
304         entry = fs_entries[i];
305
306         /* Check if we've walked past any names in db_files or
307          * db_subdirs. If so, these have been deleted. */
308         while (notmuch_filenames_has_more (db_files) &&
309                strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
310         {
311             char *absolute = talloc_asprintf (state->removed_files,
312                                               "%s/%s", path,
313                                               notmuch_filenames_get (db_files));
314
315             _filename_list_add (state->removed_files, absolute);
316
317             notmuch_filenames_advance (db_files);
318         }
319
320         while (notmuch_filenames_has_more (db_subdirs) &&
321                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
322         {
323             const char *filename = notmuch_filenames_get (db_subdirs);
324
325             if (strcmp (filename, entry->d_name) < 0)
326             {
327                 char *absolute = talloc_asprintf (state->removed_directories,
328                                                   "%s/%s", path, filename);
329
330                 _filename_list_add (state->removed_directories, absolute);
331             }
332
333             notmuch_filenames_advance (db_subdirs);
334         }
335
336         if (entry->d_type != DT_REG)
337             continue;
338
339         /* Don't add a file that we've added before. */
340         if (notmuch_filenames_has_more (db_files) &&
341             strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
342         {
343             notmuch_filenames_advance (db_files);
344             continue;
345         }
346
347         /* We're not looking at a regular file that doesn't yet exist
348          * in the database, so add it. */
349         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
350
351         state->processed_files++;
352
353         if (state->verbose) {
354             if (state->output_is_a_tty)
355                 printf("\r\033[K");
356
357             printf ("%i/%i: %s",
358                     state->processed_files,
359                     state->total_files,
360                     next);
361
362             putchar((state->output_is_a_tty) ? '\r' : '\n');
363             fflush (stdout);
364         }
365
366         status = notmuch_database_add_message (notmuch, next, &message);
367         switch (status) {
368         /* success */
369         case NOTMUCH_STATUS_SUCCESS:
370             state->added_messages++;
371             tag_inbox_and_unread (message);
372             break;
373         /* Non-fatal issues (go on to next file) */
374         case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
375             /* Stay silent on this one. */
376             break;
377         case NOTMUCH_STATUS_FILE_NOT_EMAIL:
378             fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
379                      next);
380             break;
381         /* Fatal issues. Don't process anymore. */
382         case NOTMUCH_STATUS_READONLY_DATABASE:
383         case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
384         case NOTMUCH_STATUS_OUT_OF_MEMORY:
385             fprintf (stderr, "Error: %s. Halting processing.\n",
386                      notmuch_status_to_string (status));
387             ret = status;
388             goto DONE;
389         default:
390         case NOTMUCH_STATUS_FILE_ERROR:
391         case NOTMUCH_STATUS_NULL_POINTER:
392         case NOTMUCH_STATUS_TAG_TOO_LONG:
393         case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
394         case NOTMUCH_STATUS_LAST_STATUS:
395             INTERNAL_ERROR ("add_message returned unexpected value: %d",  status);
396             goto DONE;
397         }
398
399         if (message) {
400             notmuch_message_destroy (message);
401             message = NULL;
402         }
403
404         if (do_add_files_print_progress) {
405             do_add_files_print_progress = 0;
406             add_files_print_progress (state);
407         }
408
409         talloc_free (next);
410         next = NULL;
411     }
412
413     if (! interrupted) {
414         status = notmuch_directory_set_mtime (directory, fs_mtime);
415         if (status && ret == NOTMUCH_STATUS_SUCCESS)
416             ret = status;
417     }
418
419   DONE:
420     if (next)
421         talloc_free (next);
422     if (entry)
423         free (entry);
424     if (dir)
425         closedir (dir);
426     if (fs_entries)
427         free (fs_entries);
428     if (db_subdirs)
429         notmuch_filenames_destroy (db_subdirs);
430     if (db_files)
431         notmuch_filenames_destroy (db_files);
432     if (directory)
433         notmuch_directory_destroy (directory);
434
435     return ret;
436 }
437
438 /* This is the top-level entry point for add_files. It does a couple
439  * of error checks, sets up the progress-printing timer and then calls
440  * into the recursive function. */
441 static notmuch_status_t
442 add_files (notmuch_database_t *notmuch,
443            const char *path,
444            add_files_state_t *state)
445 {
446     notmuch_status_t status;
447     struct sigaction action;
448     struct itimerval timerval;
449     notmuch_bool_t timer_is_active = FALSE;
450
451     if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
452         /* Setup our handler for SIGALRM */
453         memset (&action, 0, sizeof (struct sigaction));
454         action.sa_handler = handle_sigalrm;
455         sigemptyset (&action.sa_mask);
456         action.sa_flags = SA_RESTART;
457         sigaction (SIGALRM, &action, NULL);
458
459         /* Then start a timer to send SIGALRM once per second. */
460         timerval.it_interval.tv_sec = 1;
461         timerval.it_interval.tv_usec = 0;
462         timerval.it_value.tv_sec = 1;
463         timerval.it_value.tv_usec = 0;
464         setitimer (ITIMER_REAL, &timerval, NULL);
465
466         timer_is_active = TRUE;
467     }
468
469     status = add_files_recursive (notmuch, path, state);
470
471     if (timer_is_active) {
472         /* Now stop the timer. */
473         timerval.it_interval.tv_sec = 0;
474         timerval.it_interval.tv_usec = 0;
475         timerval.it_value.tv_sec = 0;
476         timerval.it_value.tv_usec = 0;
477         setitimer (ITIMER_REAL, &timerval, NULL);
478
479         /* And disable the signal handler. */
480         action.sa_handler = SIG_IGN;
481         sigaction (SIGALRM, &action, NULL);
482     }
483
484     return status;
485 }
486
487 /* XXX: This should be merged with the add_files function since it
488  * shares a lot of logic with it. */
489 /* Recursively count all regular files in path and all sub-directories
490  * of path.  The result is added to *count (which should be
491  * initialized to zero by the top-level caller before calling
492  * count_files). */
493 static void
494 count_files (const char *path, int *count)
495 {
496     struct dirent *entry = NULL;
497     char *next;
498     struct stat st;
499     struct dirent **fs_entries = NULL;
500     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
501     int i = 0;
502
503     if (num_fs_entries == -1) {
504         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
505                  path, strerror (errno));
506         goto DONE;
507     }
508
509     while (!interrupted) {
510         if (i == num_fs_entries)
511             break;
512
513         entry = fs_entries[i++];
514
515         /* Ignore special directories to avoid infinite recursion.
516          * Also ignore the .notmuch directory.
517          */
518         /* XXX: Eventually we'll want more sophistication to let the
519          * user specify files to be ignored. */
520         if (strcmp (entry->d_name, ".") == 0 ||
521             strcmp (entry->d_name, "..") == 0 ||
522             strcmp (entry->d_name, ".notmuch") == 0)
523         {
524             continue;
525         }
526
527         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
528             next = NULL;
529             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
530                      path, entry->d_name);
531             continue;
532         }
533
534         stat (next, &st);
535
536         if (S_ISREG (st.st_mode)) {
537             *count = *count + 1;
538             if (*count % 1000 == 0) {
539                 printf ("Found %d files so far.\r", *count);
540                 fflush (stdout);
541             }
542         } else if (S_ISDIR (st.st_mode)) {
543             count_files (next, count);
544         }
545
546         free (next);
547     }
548
549   DONE:
550     if (entry)
551         free (entry);
552     if (fs_entries)
553         free (fs_entries);
554 }
555
556 int
557 notmuch_new_command (void *ctx, int argc, char *argv[])
558 {
559     notmuch_config_t *config;
560     notmuch_database_t *notmuch;
561     add_files_state_t add_files_state;
562     double elapsed;
563     struct timeval tv_now;
564     int ret = 0;
565     struct stat st;
566     const char *db_path;
567     char *dot_notmuch_path;
568     struct sigaction action;
569     _filename_node_t *f;
570     int i;
571
572     add_files_state.verbose = 0;
573     add_files_state.output_is_a_tty = isatty (fileno (stdout));
574
575     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
576         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
577             add_files_state.verbose = 1;
578         } else {
579             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
580             return 1;
581         }
582     }
583
584     /* Setup our handler for SIGINT */
585     memset (&action, 0, sizeof (struct sigaction));
586     action.sa_handler = handle_sigint;
587     sigemptyset (&action.sa_mask);
588     action.sa_flags = SA_RESTART;
589     sigaction (SIGINT, &action, NULL);
590
591     config = notmuch_config_open (ctx, NULL, NULL);
592     if (config == NULL)
593         return 1;
594
595     db_path = notmuch_config_get_database_path (config);
596
597     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
598
599     if (stat (dot_notmuch_path, &st)) {
600         int count;
601
602         count = 0;
603         count_files (db_path, &count);
604         if (interrupted)
605             return 1;
606
607         printf ("Found %d total files (that's not much mail).\n", count);
608         notmuch = notmuch_database_create (db_path);
609         add_files_state.total_files = count;
610     } else {
611         notmuch = notmuch_database_open (db_path,
612                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
613         add_files_state.total_files = 0;
614     }
615
616     if (notmuch == NULL)
617         return 1;
618
619     talloc_free (dot_notmuch_path);
620     dot_notmuch_path = NULL;
621
622     add_files_state.processed_files = 0;
623     add_files_state.added_messages = 0;
624     gettimeofday (&add_files_state.tv_start, NULL);
625
626     add_files_state.removed_files = _filename_list_create (ctx);
627     add_files_state.removed_directories = _filename_list_create (ctx);
628
629     ret = add_files (notmuch, db_path, &add_files_state);
630
631     for (f = add_files_state.removed_files->head; f; f = f->next) {
632         notmuch_database_remove_message (notmuch, f->filename);
633     }
634
635     for (f = add_files_state.removed_directories->head; f; f = f->next) {
636         notmuch_directory_t *directory;
637         notmuch_filenames_t *files;
638
639         directory = notmuch_database_get_directory (notmuch, f->filename);
640
641         for (files = notmuch_directory_get_child_files (directory);
642              notmuch_filenames_has_more (files);
643              notmuch_filenames_advance (files))
644         {
645             char *absolute;
646
647             absolute = talloc_asprintf (ctx, "%s/%s", f->filename,
648                                         notmuch_filenames_get (files));
649             notmuch_database_remove_message (notmuch, absolute);
650             talloc_free (absolute);
651         }
652
653         notmuch_directory_destroy (directory);
654     }
655
656     talloc_free (add_files_state.removed_files);
657     talloc_free (add_files_state.removed_directories);
658
659     gettimeofday (&tv_now, NULL);
660     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
661                                     tv_now);
662     if (add_files_state.processed_files) {
663         printf ("Processed %d %s in ", add_files_state.processed_files,
664                 add_files_state.processed_files == 1 ?
665                 "file" : "total files");
666         notmuch_time_print_formatted_seconds (elapsed);
667         if (elapsed > 1) {
668             printf (" (%d files/sec.).                 \n",
669                     (int) (add_files_state.processed_files / elapsed));
670         } else {
671             printf (".                    \n");
672         }
673     }
674     if (add_files_state.added_messages) {
675         printf ("Added %d new %s to the database.\n",
676                 add_files_state.added_messages,
677                 add_files_state.added_messages == 1 ?
678                 "message" : "messages");
679     } else {
680         printf ("No new mail.\n");
681     }
682
683     if (ret) {
684         printf ("\nNote: At least one error was encountered: %s\n",
685                 notmuch_status_to_string (ret));
686     }
687
688     notmuch_database_close (notmuch);
689
690     return ret || interrupted;
691 }