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