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