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