]> git.notmuchmail.org Git - notmuch/blob - notmuch-insert.c
0c666f8c39460be9acd78bf8d4bd6c1bc123f7b3
[notmuch] / notmuch-insert.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2013 Peter Wang
4  *
5  * Based in part on notmuch-deliver
6  * Copyright © 2010 Ali Polatel
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see http://www.gnu.org/licenses/ .
20  *
21  * Author: Peter Wang <novalazy@gmail.com>
22  */
23
24 #include "notmuch-client.h"
25 #include "tag-util.h"
26
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
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
38     /* This write is "opportunistic", so it's okay to ignore the
39      * result.  It is not required for correctness, and if it does
40      * fail or produce a short write, we want to get out of the signal
41      * handler as quickly as possible, not retry it. */
42     IGNORE_RESULT (write (2, msg, sizeof (msg) - 1));
43     interrupted = 1;
44 }
45
46 /* Like gethostname but guarantees that a null-terminated hostname is
47  * returned, even if it has to make one up. Invalid characters are
48  * substituted such that the hostname can be used within a filename.
49  */
50 static void
51 safe_gethostname (char *hostname, size_t len)
52 {
53     char *p;
54
55     if (gethostname (hostname, len) == -1) {
56         strncpy (hostname, "unknown", len);
57     }
58     hostname[len - 1] = '\0';
59
60     for (p = hostname; *p != '\0'; p++) {
61         if (*p == '/' || *p == ':')
62             *p = '_';
63     }
64 }
65
66 /* Call fsync() on a directory path. */
67 static notmuch_bool_t
68 sync_dir (const char *dir)
69 {
70     notmuch_bool_t ret;
71     int fd;
72
73     fd = open (dir, O_RDONLY);
74     if (fd == -1) {
75         fprintf (stderr, "Error: open() dir failed: %s\n", strerror (errno));
76         return FALSE;
77     }
78     ret = (fsync (fd) == 0);
79     if (! ret) {
80         fprintf (stderr, "Error: fsync() dir failed: %s\n", strerror (errno));
81     }
82     close (fd);
83     return ret;
84 }
85
86 /* Check the specified folder name does not contain a directory
87  * component ".." to prevent writes outside of the Maildir hierarchy. */
88 static notmuch_bool_t
89 check_folder_name (const char *folder)
90 {
91     const char *p = folder;
92
93     for (;;) {
94         if ((p[0] == '.') && (p[1] == '.') && (p[2] == '\0' || p[2] == '/'))
95             return FALSE;
96         p = strchr (p, '/');
97         if (!p)
98             return TRUE;
99         p++;
100     }
101 }
102
103 /* Open a unique file in the 'tmp' sub-directory of dir.
104  * Returns the file descriptor on success, or -1 on failure.
105  * On success, file paths for the message in the 'tmp' and 'new'
106  * directories are returned via tmppath and newpath,
107  * and the path of the 'new' directory itself in newdir. */
108 static int
109 maildir_open_tmp_file (void *ctx, const char *dir,
110                        char **tmppath, char **newpath, char **newdir)
111 {
112     pid_t pid;
113     char hostname[256];
114     struct timeval tv;
115     char *filename;
116     int fd = -1;
117
118     /* We follow the Dovecot file name generation algorithm. */
119     pid = getpid ();
120     safe_gethostname (hostname, sizeof (hostname));
121     do {
122         gettimeofday (&tv, NULL);
123         filename = talloc_asprintf (ctx, "%ld.M%ldP%d.%s",
124                                     tv.tv_sec, tv.tv_usec, pid, hostname);
125         if (! filename) {
126             fprintf (stderr, "Out of memory\n");
127             return -1;
128         }
129
130         *tmppath = talloc_asprintf (ctx, "%s/tmp/%s", dir, filename);
131         if (! *tmppath) {
132             fprintf (stderr, "Out of memory\n");
133             return -1;
134         }
135
136         fd = open (*tmppath, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
137     } while (fd == -1 && errno == EEXIST);
138
139     if (fd == -1) {
140         fprintf (stderr, "Error: opening %s: %s\n", *tmppath, strerror (errno));
141         return -1;
142     }
143
144     *newdir = talloc_asprintf (ctx, "%s/new", dir);
145     *newpath = talloc_asprintf (ctx, "%s/new/%s", dir, filename);
146     if (! *newdir || ! *newpath) {
147         fprintf (stderr, "Out of memory\n");
148         close (fd);
149         unlink (*tmppath);
150         return -1;
151     }
152
153     talloc_free (filename);
154
155     return fd;
156 }
157
158 /* Copy the contents of standard input (fdin) into fdout.
159  * Returns TRUE if a non-empty file was written successfully.
160  * Otherwise, return FALSE. */
161 static notmuch_bool_t
162 copy_stdin (int fdin, int fdout)
163 {
164     notmuch_bool_t empty = TRUE;
165
166     while (! interrupted) {
167         ssize_t remain;
168         char buf[4096];
169         char *p;
170
171         remain = read (fdin, buf, sizeof (buf));
172         if (remain == 0)
173             break;
174         if (remain < 0) {
175             if (errno == EINTR)
176                 continue;
177             fprintf (stderr, "Error: reading from standard input: %s\n",
178                      strerror (errno));
179             return FALSE;
180         }
181
182         p = buf;
183         do {
184             ssize_t written = write (fdout, p, remain);
185             if (written < 0 && errno == EINTR)
186                 continue;
187             if (written <= 0) {
188                 fprintf (stderr, "Error: writing to temporary file: %s",
189                          strerror (errno));
190                 return FALSE;
191             }
192             p += written;
193             remain -= written;
194             empty = FALSE;
195         } while (remain > 0);
196     }
197
198     return (!interrupted && !empty);
199 }
200
201 /* Add the specified message file to the notmuch database, applying tags.
202  * The file is renamed to encode notmuch tags as maildir flags. */
203 static void
204 add_file_to_database (notmuch_database_t *notmuch, const char *path,
205                       tag_op_list_t *tag_ops)
206 {
207     notmuch_message_t *message;
208     notmuch_status_t status;
209
210     status = notmuch_database_add_message (notmuch, path, &message);
211     switch (status) {
212     case NOTMUCH_STATUS_SUCCESS:
213     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
214         break;
215     default:
216     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
217     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
218     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
219     case NOTMUCH_STATUS_OUT_OF_MEMORY:
220     case NOTMUCH_STATUS_FILE_ERROR:
221     case NOTMUCH_STATUS_NULL_POINTER:
222     case NOTMUCH_STATUS_TAG_TOO_LONG:
223     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
224     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
225     case NOTMUCH_STATUS_LAST_STATUS:
226         fprintf (stderr, "Error: failed to add `%s' to notmuch database: %s\n",
227                  path, notmuch_status_to_string (status));
228         return;
229     }
230
231     if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
232         /* Don't change tags of an existing message. */
233         status = notmuch_message_tags_to_maildir_flags (message);
234         if (status != NOTMUCH_STATUS_SUCCESS)
235             fprintf (stderr, "Error: failed to sync tags to maildir flags\n");
236     } else {
237         tag_op_list_apply (message, tag_ops, TAG_FLAG_MAILDIR_SYNC);
238     }
239
240     notmuch_message_destroy (message);
241 }
242
243 static notmuch_bool_t
244 insert_message (void *ctx, notmuch_database_t *notmuch, int fdin,
245                 const char *dir, tag_op_list_t *tag_ops)
246 {
247     char *tmppath;
248     char *newpath;
249     char *newdir;
250     int fdout;
251     char *cleanup_path;
252
253     fdout = maildir_open_tmp_file (ctx, dir, &tmppath, &newpath, &newdir);
254     if (fdout < 0)
255         return FALSE;
256
257     cleanup_path = tmppath;
258
259     if (! copy_stdin (fdin, fdout))
260         goto FAIL;
261
262     if (fsync (fdout) != 0) {
263         fprintf (stderr, "Error: fsync failed: %s\n", strerror (errno));
264         goto FAIL;
265     }
266
267     close (fdout);
268     fdout = -1;
269
270     /* Atomically move the new message file from the Maildir 'tmp' directory
271      * to the 'new' directory.  We follow the Dovecot recommendation to
272      * simply use rename() instead of link() and unlink().
273      * See also: http://wiki.dovecot.org/MailboxFormat/Maildir#Mail_delivery
274      */
275     if (rename (tmppath, newpath) != 0) {
276         fprintf (stderr, "Error: rename() failed: %s\n", strerror (errno));
277         goto FAIL;
278     }
279
280     cleanup_path = newpath;
281
282     if (! sync_dir (newdir))
283         goto FAIL;
284
285     /* Even if adding the message to the notmuch database fails,
286      * the message is on disk and we consider the delivery completed. */
287     add_file_to_database (notmuch, newpath, tag_ops);
288
289     return TRUE;
290
291   FAIL:
292     if (fdout >= 0)
293         close (fdout);
294     unlink (cleanup_path);
295     return FALSE;
296 }
297
298 int
299 notmuch_insert_command (notmuch_config_t *config, int argc, char *argv[])
300 {
301     notmuch_database_t *notmuch;
302     struct sigaction action;
303     const char *db_path;
304     const char **new_tags;
305     size_t new_tags_length;
306     tag_op_list_t *tag_ops;
307     char *query_string = NULL;
308     const char *folder = NULL;
309     const char *maildir;
310     int opt_index;
311     unsigned int i;
312     notmuch_bool_t ret;
313
314     notmuch_opt_desc_t options[] = {
315         { NOTMUCH_OPT_STRING, &folder, "folder", 0, 0 },
316         { NOTMUCH_OPT_END, 0, 0, 0, 0 }
317     };
318
319     opt_index = parse_arguments (argc, argv, options, 1);
320
321     if (opt_index < 0) {
322         /* diagnostics already printed */
323         return 1;
324     }
325
326     db_path = notmuch_config_get_database_path (config);
327     new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
328
329     tag_ops = tag_op_list_create (config);
330     if (tag_ops == NULL) {
331         fprintf (stderr, "Out of memory.\n");
332         return 1;
333     }
334     for (i = 0; i < new_tags_length; i++) {
335         if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
336             return 1;
337     }
338
339     if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
340                                 &query_string, tag_ops))
341         return 1;
342
343     if (*query_string != '\0') {
344         fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
345         return 1;
346     }
347
348     if (folder == NULL) {
349         maildir = db_path;
350     } else {
351         if (! check_folder_name (folder)) {
352             fprintf (stderr, "Error: bad folder name: %s\n", folder);
353             return 1;
354         }
355         maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
356         if (! maildir) {
357             fprintf (stderr, "Out of memory\n");
358             return 1;
359         }
360     }
361
362     /* Setup our handler for SIGINT. We do not set SA_RESTART so that copying
363      * from standard input may be interrupted. */
364     memset (&action, 0, sizeof (struct sigaction));
365     action.sa_handler = handle_sigint;
366     sigemptyset (&action.sa_mask);
367     action.sa_flags = 0;
368     sigaction (SIGINT, &action, NULL);
369
370     if (notmuch_database_open (notmuch_config_get_database_path (config),
371                                NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch))
372         return 1;
373
374     ret = insert_message (config, notmuch, STDIN_FILENO, maildir, tag_ops);
375
376     notmuch_database_destroy (notmuch);
377
378     return (ret) ? 0 : 1;
379 }