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