]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
notmuch new: Fix regression preventing addition of symlinked mail files.
[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     /* This is not an error since we may have recursed based on a
233      * symlink to a regular file, not a directory, and we don't know
234      * that until this stat. */
235     if (! S_ISDIR (st.st_mode))
236         return NOTMUCH_STATUS_SUCCESS;
237
238     fs_mtime = st.st_mtime;
239
240     directory = notmuch_database_get_directory (notmuch, path);
241     db_mtime = notmuch_directory_get_mtime (directory);
242
243     /* If the database knows about this directory, then we sort based
244      * on strcmp to match the database sorting. Otherwise, we can do
245      * inode-based sorting for faster filesystem operation. */
246     num_fs_entries = scandir (path, &fs_entries, 0,
247                               db_mtime ?
248                               dirent_sort_strcmp_name : dirent_sort_inode);
249
250     if (num_fs_entries == -1) {
251         fprintf (stderr, "Error opening directory %s: %s\n",
252                  path, strerror (errno));
253         ret = NOTMUCH_STATUS_FILE_ERROR;
254         goto DONE;
255     }
256
257     /* Pass 1: Recurse into all sub-directories. */
258     is_maildir = _entries_resemble_maildir (fs_entries, num_fs_entries);
259
260     for (i = 0; i < num_fs_entries; i++) {
261         if (interrupted)
262             break;
263
264         entry = fs_entries[i];
265
266         if (entry->d_type != DT_DIR && entry->d_type != DT_LNK)
267             continue;
268
269         /* Ignore special directories to avoid infinite recursion.
270          * Also ignore the .notmuch directory and any "tmp" directory
271          * that appears within a maildir.
272          */
273         /* XXX: Eventually we'll want more sophistication to let the
274          * user specify files to be ignored. */
275         if (strcmp (entry->d_name, ".") == 0 ||
276             strcmp (entry->d_name, "..") == 0 ||
277             (is_maildir && strcmp (entry->d_name, "tmp") == 0) ||
278             strcmp (entry->d_name, ".notmuch") ==0)
279         {
280             continue;
281         }
282
283         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
284         status = add_files_recursive (notmuch, next, state);
285         if (status && ret == NOTMUCH_STATUS_SUCCESS)
286             ret = status;
287         talloc_free (next);
288         next = NULL;
289     }
290
291     /* If this directory hasn't been modified since the last
292      * "notmuch new", then we can skip the second pass entirely. */
293     if (fs_mtime <= db_mtime)
294         goto DONE;
295
296     /* Pass 2: Scan for new files, removed files, and removed directories. */
297     db_files = notmuch_directory_get_child_files (directory);
298     db_subdirs = notmuch_directory_get_child_directories (directory);
299
300     for (i = 0; i < num_fs_entries; i++)
301     {
302         if (interrupted)
303             break;
304
305         entry = fs_entries[i];
306
307         /* Check if we've walked past any names in db_files or
308          * db_subdirs. If so, these have been deleted. */
309         while (notmuch_filenames_has_more (db_files) &&
310                strcmp (notmuch_filenames_get (db_files), entry->d_name) < 0)
311         {
312             char *absolute = talloc_asprintf (state->removed_files,
313                                               "%s/%s", path,
314                                               notmuch_filenames_get (db_files));
315
316             _filename_list_add (state->removed_files, absolute);
317
318             notmuch_filenames_advance (db_files);
319         }
320
321         while (notmuch_filenames_has_more (db_subdirs) &&
322                strcmp (notmuch_filenames_get (db_subdirs), entry->d_name) <= 0)
323         {
324             const char *filename = notmuch_filenames_get (db_subdirs);
325
326             if (strcmp (filename, entry->d_name) < 0)
327             {
328                 char *absolute = talloc_asprintf (state->removed_directories,
329                                                   "%s/%s", path, filename);
330
331                 _filename_list_add (state->removed_directories, absolute);
332             }
333
334             notmuch_filenames_advance (db_subdirs);
335         }
336
337         /* If we're looking at a symlink, we only want to add it if it
338          * links to a regular file, (and not to a directory, say). */
339         if (entry->d_type == DT_LNK) {
340             int err;
341
342             next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
343             err = stat (next, &st);
344             talloc_free (next);
345             next = NULL;
346
347             /* Don't emit an error for a link pointing nowhere, since
348              * the directory-traversal pass will have already done
349              * that. */
350             if (err)
351                 continue;
352
353             if (! S_ISREG (st.st_mode))
354                 continue;
355         } else if (entry->d_type != DT_REG) {
356             continue;
357         }
358
359         /* Don't add a file that we've added before. */
360         if (notmuch_filenames_has_more (db_files) &&
361             strcmp (notmuch_filenames_get (db_files), entry->d_name) == 0)
362         {
363             notmuch_filenames_advance (db_files);
364             continue;
365         }
366
367         /* We're now looking at a regular file that doesn't yet exist
368          * in the database, so add it. */
369         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
370
371         state->processed_files++;
372
373         if (state->verbose) {
374             if (state->output_is_a_tty)
375                 printf("\r\033[K");
376
377             printf ("%i/%i: %s",
378                     state->processed_files,
379                     state->total_files,
380                     next);
381
382             putchar((state->output_is_a_tty) ? '\r' : '\n');
383             fflush (stdout);
384         }
385
386         status = notmuch_database_add_message (notmuch, next, &message);
387         switch (status) {
388         /* success */
389         case NOTMUCH_STATUS_SUCCESS:
390             state->added_messages++;
391             tag_inbox_and_unread (message);
392             break;
393         /* Non-fatal issues (go on to next file) */
394         case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
395             /* Stay silent on this one. */
396             break;
397         case NOTMUCH_STATUS_FILE_NOT_EMAIL:
398             fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
399                      next);
400             break;
401         /* Fatal issues. Don't process anymore. */
402         case NOTMUCH_STATUS_READONLY_DATABASE:
403         case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
404         case NOTMUCH_STATUS_OUT_OF_MEMORY:
405             fprintf (stderr, "Error: %s. Halting processing.\n",
406                      notmuch_status_to_string (status));
407             ret = status;
408             goto DONE;
409         default:
410         case NOTMUCH_STATUS_FILE_ERROR:
411         case NOTMUCH_STATUS_NULL_POINTER:
412         case NOTMUCH_STATUS_TAG_TOO_LONG:
413         case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
414         case NOTMUCH_STATUS_LAST_STATUS:
415             INTERNAL_ERROR ("add_message returned unexpected value: %d",  status);
416             goto DONE;
417         }
418
419         if (message) {
420             notmuch_message_destroy (message);
421             message = NULL;
422         }
423
424         if (do_add_files_print_progress) {
425             do_add_files_print_progress = 0;
426             add_files_print_progress (state);
427         }
428
429         talloc_free (next);
430         next = NULL;
431     }
432
433     if (! interrupted) {
434         status = notmuch_directory_set_mtime (directory, fs_mtime);
435         if (status && ret == NOTMUCH_STATUS_SUCCESS)
436             ret = status;
437     }
438
439   DONE:
440     if (next)
441         talloc_free (next);
442     if (entry)
443         free (entry);
444     if (dir)
445         closedir (dir);
446     if (fs_entries)
447         free (fs_entries);
448     if (db_subdirs)
449         notmuch_filenames_destroy (db_subdirs);
450     if (db_files)
451         notmuch_filenames_destroy (db_files);
452     if (directory)
453         notmuch_directory_destroy (directory);
454
455     return ret;
456 }
457
458 /* This is the top-level entry point for add_files. It does a couple
459  * of error checks, sets up the progress-printing timer and then calls
460  * into the recursive function. */
461 static notmuch_status_t
462 add_files (notmuch_database_t *notmuch,
463            const char *path,
464            add_files_state_t *state)
465 {
466     notmuch_status_t status;
467     struct sigaction action;
468     struct itimerval timerval;
469     notmuch_bool_t timer_is_active = FALSE;
470     struct stat st;
471
472     if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
473         /* Setup our handler for SIGALRM */
474         memset (&action, 0, sizeof (struct sigaction));
475         action.sa_handler = handle_sigalrm;
476         sigemptyset (&action.sa_mask);
477         action.sa_flags = SA_RESTART;
478         sigaction (SIGALRM, &action, NULL);
479
480         /* Then start a timer to send SIGALRM once per second. */
481         timerval.it_interval.tv_sec = 1;
482         timerval.it_interval.tv_usec = 0;
483         timerval.it_value.tv_sec = 1;
484         timerval.it_value.tv_usec = 0;
485         setitimer (ITIMER_REAL, &timerval, NULL);
486
487         timer_is_active = TRUE;
488     }
489
490     if (stat (path, &st)) {
491         fprintf (stderr, "Error reading directory %s: %s\n",
492                  path, strerror (errno));
493         return NOTMUCH_STATUS_FILE_ERROR;
494     }
495
496     if (! S_ISDIR (st.st_mode)) {
497         fprintf (stderr, "Error: %s is not a directory.\n", path);
498         return NOTMUCH_STATUS_FILE_ERROR;
499     }
500
501     status = add_files_recursive (notmuch, path, state);
502
503     if (timer_is_active) {
504         /* Now stop the timer. */
505         timerval.it_interval.tv_sec = 0;
506         timerval.it_interval.tv_usec = 0;
507         timerval.it_value.tv_sec = 0;
508         timerval.it_value.tv_usec = 0;
509         setitimer (ITIMER_REAL, &timerval, NULL);
510
511         /* And disable the signal handler. */
512         action.sa_handler = SIG_IGN;
513         sigaction (SIGALRM, &action, NULL);
514     }
515
516     return status;
517 }
518
519 /* XXX: This should be merged with the add_files function since it
520  * shares a lot of logic with it. */
521 /* Recursively count all regular files in path and all sub-directories
522  * of path.  The result is added to *count (which should be
523  * initialized to zero by the top-level caller before calling
524  * count_files). */
525 static void
526 count_files (const char *path, int *count)
527 {
528     struct dirent *entry = NULL;
529     char *next;
530     struct stat st;
531     struct dirent **fs_entries = NULL;
532     int num_fs_entries = scandir (path, &fs_entries, 0, dirent_sort_inode);
533     int i = 0;
534
535     if (num_fs_entries == -1) {
536         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
537                  path, strerror (errno));
538         goto DONE;
539     }
540
541     while (!interrupted) {
542         if (i == num_fs_entries)
543             break;
544
545         entry = fs_entries[i++];
546
547         /* Ignore special directories to avoid infinite recursion.
548          * Also ignore the .notmuch directory.
549          */
550         /* XXX: Eventually we'll want more sophistication to let the
551          * user specify files to be ignored. */
552         if (strcmp (entry->d_name, ".") == 0 ||
553             strcmp (entry->d_name, "..") == 0 ||
554             strcmp (entry->d_name, ".notmuch") == 0)
555         {
556             continue;
557         }
558
559         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
560             next = NULL;
561             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
562                      path, entry->d_name);
563             continue;
564         }
565
566         stat (next, &st);
567
568         if (S_ISREG (st.st_mode)) {
569             *count = *count + 1;
570             if (*count % 1000 == 0) {
571                 printf ("Found %d files so far.\r", *count);
572                 fflush (stdout);
573             }
574         } else if (S_ISDIR (st.st_mode)) {
575             count_files (next, count);
576         }
577
578         free (next);
579     }
580
581   DONE:
582     if (entry)
583         free (entry);
584     if (fs_entries)
585         free (fs_entries);
586 }
587
588 int
589 notmuch_new_command (void *ctx, int argc, char *argv[])
590 {
591     notmuch_config_t *config;
592     notmuch_database_t *notmuch;
593     add_files_state_t add_files_state;
594     double elapsed;
595     struct timeval tv_now;
596     int ret = 0;
597     struct stat st;
598     const char *db_path;
599     char *dot_notmuch_path;
600     struct sigaction action;
601     _filename_node_t *f;
602     int renamed_files, removed_files;
603     notmuch_status_t status;
604     int i;
605
606     add_files_state.verbose = 0;
607     add_files_state.output_is_a_tty = isatty (fileno (stdout));
608
609     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
610         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
611             add_files_state.verbose = 1;
612         } else {
613             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
614             return 1;
615         }
616     }
617
618     /* Setup our handler for SIGINT */
619     memset (&action, 0, sizeof (struct sigaction));
620     action.sa_handler = handle_sigint;
621     sigemptyset (&action.sa_mask);
622     action.sa_flags = SA_RESTART;
623     sigaction (SIGINT, &action, NULL);
624
625     config = notmuch_config_open (ctx, NULL, NULL);
626     if (config == NULL)
627         return 1;
628
629     db_path = notmuch_config_get_database_path (config);
630
631     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
632
633     if (stat (dot_notmuch_path, &st)) {
634         int count;
635
636         count = 0;
637         count_files (db_path, &count);
638         if (interrupted)
639             return 1;
640
641         printf ("Found %d total files (that's not much mail).\n", count);
642         notmuch = notmuch_database_create (db_path);
643         add_files_state.total_files = count;
644     } else {
645         notmuch = notmuch_database_open (db_path,
646                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
647         add_files_state.total_files = 0;
648     }
649
650     if (notmuch == NULL)
651         return 1;
652
653     talloc_free (dot_notmuch_path);
654     dot_notmuch_path = NULL;
655
656     add_files_state.processed_files = 0;
657     add_files_state.added_messages = 0;
658     gettimeofday (&add_files_state.tv_start, NULL);
659
660     add_files_state.removed_files = _filename_list_create (ctx);
661     add_files_state.removed_directories = _filename_list_create (ctx);
662
663     ret = add_files (notmuch, db_path, &add_files_state);
664
665     removed_files = 0;
666     renamed_files = 0;
667     for (f = add_files_state.removed_files->head; f; f = f->next) {
668         status = notmuch_database_remove_message (notmuch, f->filename);
669         if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
670             renamed_files++;
671         else
672             removed_files++;
673     }
674
675     for (f = add_files_state.removed_directories->head; f; f = f->next) {
676         notmuch_directory_t *directory;
677         notmuch_filenames_t *files;
678
679         directory = notmuch_database_get_directory (notmuch, f->filename);
680
681         for (files = notmuch_directory_get_child_files (directory);
682              notmuch_filenames_has_more (files);
683              notmuch_filenames_advance (files))
684         {
685             char *absolute;
686
687             absolute = talloc_asprintf (ctx, "%s/%s", f->filename,
688                                         notmuch_filenames_get (files));
689             status = notmuch_database_remove_message (notmuch, absolute);
690             if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
691                 renamed_files++;
692             else
693                 removed_files++;
694             talloc_free (absolute);
695         }
696
697         notmuch_directory_destroy (directory);
698     }
699
700     talloc_free (add_files_state.removed_files);
701     talloc_free (add_files_state.removed_directories);
702
703     gettimeofday (&tv_now, NULL);
704     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
705                                     tv_now);
706
707     if (add_files_state.processed_files) {
708         printf ("Processed %d %s in ", add_files_state.processed_files,
709                 add_files_state.processed_files == 1 ?
710                 "file" : "total files");
711         notmuch_time_print_formatted_seconds (elapsed);
712         if (elapsed > 1) {
713             printf (" (%d files/sec.).                 \n",
714                     (int) (add_files_state.processed_files / elapsed));
715         } else {
716             printf (".                    \n");
717         }
718     }
719
720     if (add_files_state.added_messages) {
721         printf ("Added %d new %s to the database.",
722                 add_files_state.added_messages,
723                 add_files_state.added_messages == 1 ?
724                 "message" : "messages");
725     } else {
726         printf ("No new mail.");
727     }
728
729     if (removed_files) {
730         printf (" Removed %d %s.",
731                 removed_files,
732                 removed_files == 1 ? "message" : "messages");
733     }
734
735     if (renamed_files) {
736         printf (" Detected %d file %s.",
737                 renamed_files,
738                 renamed_files == 1 ? "rename" : "renames");
739     }
740
741     printf ("\n");
742
743     if (ret) {
744         printf ("\nNote: At least one error was encountered: %s\n",
745                 notmuch_status_to_string (ret));
746     }
747
748     notmuch_database_close (notmuch);
749
750     return ret || interrupted;
751 }