]> git.notmuchmail.org Git - notmuch/blob - notmuch-new.c
72c6c58799a3a96b92e452592826b61d87b63db7
[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 static volatile sig_atomic_t do_add_files_print_progress = 0;
26
27 static void
28 handle_sigalrm (unused (int signal))
29 {
30     do_add_files_print_progress = 1;
31 }
32
33 static volatile sig_atomic_t interrupted;
34
35 static void
36 handle_sigint (unused (int sig))
37 {
38     static char msg[] = "Stopping...         \n";
39     write(2, msg, sizeof(msg)-1);
40     interrupted = 1;
41 }
42
43 static void
44 tag_inbox_and_unread (notmuch_message_t *message)
45 {
46     notmuch_message_add_tag (message, "inbox");
47     notmuch_message_add_tag (message, "unread");
48 }
49
50 static void
51 add_files_print_progress (add_files_state_t *state)
52 {
53     struct timeval tv_now;
54     double elapsed_overall, rate_overall;
55
56     gettimeofday (&tv_now, NULL);
57
58     elapsed_overall = notmuch_time_elapsed (state->tv_start, tv_now);
59     rate_overall = (state->processed_files) / elapsed_overall;
60
61     printf ("Processed %d", state->processed_files);
62
63     if (state->total_files) {
64         double time_remaining;
65
66         time_remaining = ((state->total_files - state->processed_files) /
67                           rate_overall);
68         printf (" of %d files (", state->total_files);
69         notmuch_time_print_formatted_seconds (time_remaining);
70         printf (" remaining).      \r");
71     } else {
72         printf (" files (%d files/sec.)    \r", (int) rate_overall);
73     }
74
75     fflush (stdout);
76 }
77
78 static int ino_cmp(const struct dirent **a, const struct dirent **b)
79 {
80     return ((*a)->d_ino < (*b)->d_ino) ? -1 : 1;
81 }
82
83 /* Test if the directory looks like a Maildir directory.
84  *
85  * Search through the array of directory entries to see if we can find all
86  * three subdirectories typical for Maildir, that is "new", "cur", and "tmp".
87  *
88  * Return 1 if the directory looks like a Maildir and 0 otherwise.
89  */
90 static int is_maildir (struct dirent **entries, int count)
91 {
92     int i, found = 0;
93
94     for (i = 0; i < count; i++) {
95         if (entries[i]->d_type != DT_DIR) continue;
96         if (strcmp(entries[i]->d_name, "new") == 0 ||
97             strcmp(entries[i]->d_name, "cur") == 0 ||
98             strcmp(entries[i]->d_name, "tmp") == 0)
99         {
100             found++;
101             if (found == 3) return 1;
102         }
103     }
104
105     return 0;
106 }
107
108 /* Examine 'path' recursively as follows:
109  *
110  *   o Ask the filesystem for the mtime of 'path' (path_mtime)
111  *
112  *   o Ask the database for its timestamp of 'path' (path_dbtime)
113  *
114  *   o If 'path_mtime' > 'path_dbtime'
115  *
116  *       o For each regular file in 'path' with mtime newer than the
117  *         'path_dbtime' call add_message to add the file to the
118  *         database.
119  *
120  *       o For each sub-directory of path, recursively call into this
121  *         same function.
122  *
123  *   o Tell the database to update its time of 'path' to 'path_mtime'
124  *
125  * The 'struct stat *st' must point to a structure that has already
126  * been initialized for 'path' by calling stat().
127  */
128 static notmuch_status_t
129 add_files_recursive (notmuch_database_t *notmuch,
130                      const char *path,
131                      struct stat *st,
132                      add_files_state_t *state)
133 {
134     DIR *dir = NULL;
135     struct dirent *entry = NULL;
136     char *next = NULL;
137     time_t path_mtime, path_dbtime;
138     notmuch_status_t status, ret = NOTMUCH_STATUS_SUCCESS;
139     notmuch_message_t *message = NULL;
140     struct dirent **namelist = NULL;
141     int num_entries;
142
143     /* If we're told to, we bail out on encountering a read-only
144      * directory, (with this being a clear clue from the user to
145      * Notmuch that new mail won't be arriving there and we need not
146      * look. */
147     if (state->ignore_read_only_directories &&
148         (st->st_mode & S_IWUSR) == 0)
149     {
150         state->saw_read_only_directory = TRUE;
151         goto DONE;
152     }
153
154     path_mtime = st->st_mtime;
155
156     path_dbtime = notmuch_database_get_timestamp (notmuch, path);
157     num_entries = scandir (path, &namelist, 0, ino_cmp);
158
159     if (num_entries == -1) {
160         fprintf (stderr, "Error opening directory %s: %s\n",
161                  path, strerror (errno));
162         ret = NOTMUCH_STATUS_FILE_ERROR;
163         goto DONE;
164     }
165
166     int i=0;
167
168     while (!interrupted) {
169         if (i == num_entries)
170             break;
171
172         entry= namelist[i++];
173
174         /* If this directory hasn't been modified since the last
175          * add_files, then we only need to look further for
176          * sub-directories. */
177         if (path_mtime <= path_dbtime && entry->d_type == DT_REG)
178             continue;
179
180         /* Ignore special directories to avoid infinite recursion.
181          * Also ignore the .notmuch directory.
182          */
183         /* XXX: Eventually we'll want more sophistication to let the
184          * user specify files to be ignored. */
185         if (strcmp (entry->d_name, ".") == 0 ||
186             strcmp (entry->d_name, "..") == 0 ||
187             (entry->d_type == DT_DIR &&
188              (strcmp (entry->d_name, "tmp") == 0) &&
189              is_maildir (namelist, num_entries)) ||
190             strcmp (entry->d_name, ".notmuch") ==0)
191         {
192             continue;
193         }
194
195         next = talloc_asprintf (notmuch, "%s/%s", path, entry->d_name);
196
197         if (stat (next, st)) {
198             fprintf (stderr, "Error reading %s: %s\n",
199                      next, strerror (errno));
200             ret = NOTMUCH_STATUS_FILE_ERROR;
201             continue;
202         }
203
204         if (S_ISREG (st->st_mode)) {
205             /* If the file hasn't been modified since the last
206              * add_files, then we need not look at it. */
207             if (path_dbtime == 0 || st->st_mtime > path_dbtime) {
208                 state->processed_files++;
209
210                 if (state->verbose) {
211                     if (state->output_is_a_tty)
212                         printf("\r\033[K");
213
214                     printf ("%i/%i: %s",
215                             state->processed_files,
216                             state->total_files,
217                             next);
218
219                     putchar((state->output_is_a_tty) ? '\r' : '\n');
220                     fflush (stdout);
221                 }
222
223                 status = notmuch_database_add_message (notmuch, next, &message);
224                 switch (status) {
225                     /* success */
226                     case NOTMUCH_STATUS_SUCCESS:
227                         state->added_messages++;
228                         tag_inbox_and_unread (message);
229                         break;
230                     /* Non-fatal issues (go on to next file) */
231                     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
232                         /* Stay silent on this one. */
233                         break;
234                     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
235                         fprintf (stderr, "Note: Ignoring non-mail file: %s\n",
236                                  next);
237                         break;
238                     /* Fatal issues. Don't process anymore. */
239                     case NOTMUCH_STATUS_READONLY_DATABASE:
240                     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
241                     case NOTMUCH_STATUS_OUT_OF_MEMORY:
242                         fprintf (stderr, "Error: %s. Halting processing.\n",
243                                  notmuch_status_to_string (status));
244                         ret = status;
245                         goto DONE;
246                     default:
247                     case NOTMUCH_STATUS_FILE_ERROR:
248                     case NOTMUCH_STATUS_NULL_POINTER:
249                     case NOTMUCH_STATUS_TAG_TOO_LONG:
250                     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
251                     case NOTMUCH_STATUS_LAST_STATUS:
252                         INTERNAL_ERROR ("add_message returned unexpected value: %d",  status);
253                         goto DONE;
254                 }
255
256                 if (message) {
257                     notmuch_message_destroy (message);
258                     message = NULL;
259                 }
260
261                 if (do_add_files_print_progress) {
262                     do_add_files_print_progress = 0;
263                     add_files_print_progress (state);
264                 }
265             }
266         } else if (S_ISDIR (st->st_mode)) {
267             status = add_files_recursive (notmuch, next, st, state);
268             if (status && ret == NOTMUCH_STATUS_SUCCESS)
269                 ret = status;
270         }
271
272         talloc_free (next);
273         next = NULL;
274     }
275
276     status = notmuch_database_set_timestamp (notmuch, path, path_mtime);
277     if (status && ret == NOTMUCH_STATUS_SUCCESS)
278         ret = status;
279
280   DONE:
281     if (next)
282         talloc_free (next);
283     if (entry)
284         free (entry);
285     if (dir)
286         closedir (dir);
287     if (namelist)
288         free (namelist);
289
290     return ret;
291 }
292
293 /* This is the top-level entry point for add_files. It does a couple
294  * of error checks, sets up the progress-printing timer and then calls
295  * into the recursive function. */
296 notmuch_status_t
297 add_files (notmuch_database_t *notmuch,
298            const char *path,
299            add_files_state_t *state)
300 {
301     struct stat st;
302     notmuch_status_t status;
303     struct sigaction action;
304     struct itimerval timerval;
305     notmuch_bool_t timer_is_active = FALSE;
306
307     if (stat (path, &st)) {
308         fprintf (stderr, "Error reading directory %s: %s\n",
309                  path, strerror (errno));
310         return NOTMUCH_STATUS_FILE_ERROR;
311     }
312
313     if (! S_ISDIR (st.st_mode)) {
314         fprintf (stderr, "Error: %s is not a directory.\n", path);
315         return NOTMUCH_STATUS_FILE_ERROR;
316     }
317
318     if (state->output_is_a_tty && ! debugger_is_active () && ! state->verbose) {
319         /* Setup our handler for SIGALRM */
320         memset (&action, 0, sizeof (struct sigaction));
321         action.sa_handler = handle_sigalrm;
322         sigemptyset (&action.sa_mask);
323         action.sa_flags = SA_RESTART;
324         sigaction (SIGALRM, &action, NULL);
325
326         /* Then start a timer to send SIGALRM once per second. */
327         timerval.it_interval.tv_sec = 1;
328         timerval.it_interval.tv_usec = 0;
329         timerval.it_value.tv_sec = 1;
330         timerval.it_value.tv_usec = 0;
331         setitimer (ITIMER_REAL, &timerval, NULL);
332
333         timer_is_active = TRUE;
334     }
335
336     status = add_files_recursive (notmuch, path, &st, state);
337
338     if (timer_is_active) {
339         /* Now stop the timer. */
340         timerval.it_interval.tv_sec = 0;
341         timerval.it_interval.tv_usec = 0;
342         timerval.it_value.tv_sec = 0;
343         timerval.it_value.tv_usec = 0;
344         setitimer (ITIMER_REAL, &timerval, NULL);
345
346         /* And disable the signal handler. */
347         action.sa_handler = SIG_IGN;
348         sigaction (SIGALRM, &action, NULL);
349     }
350
351     return status;
352 }
353
354 /* XXX: This should be merged with the add_files function since it
355  * shares a lot of logic with it. */
356 /* Recursively count all regular files in path and all sub-directories
357  * of path.  The result is added to *count (which should be
358  * initialized to zero by the top-level caller before calling
359  * count_files). */
360 static void
361 count_files (const char *path, int *count)
362 {
363     struct dirent *entry = NULL;
364     char *next;
365     struct stat st;
366     struct dirent **namelist = NULL;
367     int n_entries = scandir (path, &namelist, 0, ino_cmp);
368     int i = 0;
369
370     if (n_entries == -1) {
371         fprintf (stderr, "Warning: failed to open directory %s: %s\n",
372                  path, strerror (errno));
373         goto DONE;
374     }
375
376     while (!interrupted) {
377         if (i == n_entries)
378             break;
379
380         entry= namelist[i++];
381
382         /* Ignore special directories to avoid infinite recursion.
383          * Also ignore the .notmuch directory.
384          */
385         /* XXX: Eventually we'll want more sophistication to let the
386          * user specify files to be ignored. */
387         if (strcmp (entry->d_name, ".") == 0 ||
388             strcmp (entry->d_name, "..") == 0 ||
389             strcmp (entry->d_name, ".notmuch") == 0)
390         {
391             continue;
392         }
393
394         if (asprintf (&next, "%s/%s", path, entry->d_name) == -1) {
395             next = NULL;
396             fprintf (stderr, "Error descending from %s to %s: Out of memory\n",
397                      path, entry->d_name);
398             continue;
399         }
400
401         stat (next, &st);
402
403         if (S_ISREG (st.st_mode)) {
404             *count = *count + 1;
405             if (*count % 1000 == 0) {
406                 printf ("Found %d files so far.\r", *count);
407                 fflush (stdout);
408             }
409         } else if (S_ISDIR (st.st_mode)) {
410             count_files (next, count);
411         }
412
413         free (next);
414     }
415
416   DONE:
417     if (entry)
418         free (entry);
419     if (namelist)
420         free (namelist);
421 }
422
423 int
424 notmuch_new_command (void *ctx, int argc, char *argv[])
425 {
426     notmuch_config_t *config;
427     notmuch_database_t *notmuch;
428     add_files_state_t add_files_state;
429     double elapsed;
430     struct timeval tv_now;
431     int ret = 0;
432     struct stat st;
433     const char *db_path;
434     char *dot_notmuch_path;
435     struct sigaction action;
436     int i;
437
438     add_files_state.verbose = 0;
439     add_files_state.output_is_a_tty = isatty (fileno (stdout));
440
441     for (i = 0; i < argc && argv[i][0] == '-'; i++) {
442         if (STRNCMP_LITERAL (argv[i], "--verbose") == 0) {
443             add_files_state.verbose = 1;
444         } else {
445             fprintf (stderr, "Unrecognized option: %s\n", argv[i]);
446             return 1;
447         }
448     }
449
450     /* Setup our handler for SIGINT */
451     memset (&action, 0, sizeof (struct sigaction));
452     action.sa_handler = handle_sigint;
453     sigemptyset (&action.sa_mask);
454     action.sa_flags = SA_RESTART;
455     sigaction (SIGINT, &action, NULL);
456
457     config = notmuch_config_open (ctx, NULL, NULL);
458     if (config == NULL)
459         return 1;
460
461     db_path = notmuch_config_get_database_path (config);
462
463     dot_notmuch_path = talloc_asprintf (ctx, "%s/%s", db_path, ".notmuch");
464
465     if (stat (dot_notmuch_path, &st)) {
466         int count;
467
468         count = 0;
469         count_files (db_path, &count);
470         if (interrupted)
471             return 1;
472
473         printf ("Found %d total files.     \n", count);
474         notmuch = notmuch_database_create (db_path);
475         add_files_state.ignore_read_only_directories = FALSE;
476         add_files_state.total_files = count;
477     } else {
478         notmuch = notmuch_database_open (db_path,
479                                          NOTMUCH_DATABASE_MODE_READ_WRITE);
480         add_files_state.ignore_read_only_directories = TRUE;
481         add_files_state.total_files = 0;
482     }
483
484     if (notmuch == NULL)
485         return 1;
486
487     talloc_free (dot_notmuch_path);
488     dot_notmuch_path = NULL;
489
490     add_files_state.saw_read_only_directory = FALSE;
491     add_files_state.processed_files = 0;
492     add_files_state.added_messages = 0;
493     gettimeofday (&add_files_state.tv_start, NULL);
494
495     ret = add_files (notmuch, db_path, &add_files_state);
496
497     gettimeofday (&tv_now, NULL);
498     elapsed = notmuch_time_elapsed (add_files_state.tv_start,
499                                     tv_now);
500     if (add_files_state.processed_files) {
501         printf ("Processed %d %s in ", add_files_state.processed_files,
502                 add_files_state.processed_files == 1 ?
503                 "file" : "total files");
504         notmuch_time_print_formatted_seconds (elapsed);
505         if (elapsed > 1) {
506             printf (" (%d files/sec.).                 \n",
507                     (int) (add_files_state.processed_files / elapsed));
508         } else {
509             printf (".                    \n");
510         }
511     }
512     if (add_files_state.added_messages) {
513         printf ("Added %d new %s to the database (not much, really).\n",
514                 add_files_state.added_messages,
515                 add_files_state.added_messages == 1 ?
516                 "message" : "messages");
517     } else {
518         printf ("No new mail---and that's not much.\n");
519     }
520
521     if (elapsed > 1 && ! add_files_state.saw_read_only_directory) {
522         printf ("\nTip: If you have any sub-directories that are archives (that is,\n"
523                 "they will never receive new mail), marking these directories as\n"
524                 "read-only (chmod u-w /path/to/dir) will make \"notmuch new\"\n"
525                 "much more efficient (it won't even look in those directories).\n");
526     }
527
528     if (ret) {
529         printf ("\nNote: At least one error was encountered: %s\n",
530                 notmuch_status_to_string (ret));
531     }
532
533     notmuch_database_close (notmuch);
534
535     return ret || interrupted;
536 }