]> git.notmuchmail.org Git - notmuch/blob - notmuch-restore.c
Makefile.local: make IS_GIT simply expanded
[notmuch] / notmuch-restore.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 https://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22 #include "hex-escape.h"
23 #include "tag-util.h"
24 #include "string-util.h"
25 #include "zlib-extra.h"
26
27 static int
28 process_config_line (notmuch_database_t *notmuch, const char* line)
29 {
30     const char *key_p, *val_p;
31     char *key, *val;
32     size_t key_len,val_len;
33     const char *delim = " \t\n";
34     int ret = EXIT_FAILURE;
35
36     void *local = talloc_new(NULL);
37
38     key_p = strtok_len_c (line, delim, &key_len);
39     val_p = strtok_len_c (key_p+key_len, delim, &val_len);
40
41     key = talloc_strndup (local, key_p, key_len);
42     val = talloc_strndup (local, val_p, val_len);
43     if (hex_decode_inplace (key) != HEX_SUCCESS ||
44         hex_decode_inplace (val) != HEX_SUCCESS ) {
45         fprintf (stderr, "hex decoding failure on line %s\n", line);
46         goto DONE;
47     }
48
49     if (print_status_database ("notmuch restore", notmuch,
50                                notmuch_database_set_config (notmuch, key, val)))
51         goto DONE;
52
53     ret = EXIT_SUCCESS;
54
55  DONE:
56     talloc_free (local);
57     return ret;
58 }
59
60 static regex_t regex;
61
62 /* Non-zero return indicates an error in retrieving the message,
63  * or in applying the tags.  Missing messages are reported, but not
64  * considered errors.
65  */
66 static int
67 tag_message (unused (void *ctx),
68              notmuch_database_t *notmuch,
69              const char *message_id,
70              tag_op_list_t *tag_ops,
71              tag_op_flag_t flags)
72 {
73     notmuch_status_t status;
74     notmuch_message_t *message = NULL;
75     int ret = 0;
76
77     status = notmuch_database_find_message (notmuch, message_id, &message);
78     if (status) {
79         fprintf (stderr, "Error applying tags to message %s: %s\n",
80                  message_id, notmuch_status_to_string (status));
81         return 1;
82     }
83     if (message == NULL) {
84         fprintf (stderr, "Warning: cannot apply tags to missing message: %s\n",
85                  message_id);
86         /* We consider this a non-fatal error. */
87         return 0;
88     }
89
90     /* In order to detect missing messages, this check/optimization is
91      * intentionally done *after* first finding the message. */
92     if ((flags & TAG_FLAG_REMOVE_ALL) || tag_op_list_size (tag_ops))
93         ret = tag_op_list_apply (message, tag_ops, flags);
94
95     notmuch_message_destroy (message);
96
97     return ret;
98 }
99
100 /* Sup dump output is one line per message. We match a sequence of
101  * non-space characters for the message-id, then one or more
102  * spaces, then a list of space-separated tags as a sequence of
103  * characters within literal '(' and ')'. */
104
105 static int
106 parse_sup_line (void *ctx, char *line,
107                 char **query_str, tag_op_list_t *tag_ops)
108 {
109
110     regmatch_t match[3];
111     char *file_tags;
112     int rerr;
113
114     tag_op_list_reset (tag_ops);
115
116     chomp_newline (line);
117
118     /* Silently ignore blank lines */
119     if (line[0] == '\0') {
120         return 1;
121     }
122
123     rerr = xregexec (&regex, line, 3, match, 0);
124     if (rerr == REG_NOMATCH) {
125         fprintf (stderr, "Warning: Ignoring invalid sup format line: %s\n",
126                  line);
127         return 1;
128     }
129
130     *query_str = talloc_strndup_debug (ctx, line + match[1].rm_so,
131                                        match[1].rm_eo - match[1].rm_so);
132
133     file_tags = talloc_strndup_debug (ctx, line + match[2].rm_so,
134                                       match[2].rm_eo - match[2].rm_so);
135
136     char *tok = file_tags;
137     size_t tok_len = 0;
138
139     tag_op_list_reset (tag_ops);
140
141     while ((tok = strtok_len (tok + tok_len, " ", &tok_len)) != NULL) {
142
143         if (*(tok + tok_len) != '\0') {
144             *(tok + tok_len) = '\0';
145             tok_len++;
146         }
147
148         if (tag_op_list_append (tag_ops, tok, FALSE))
149             return -1;
150     }
151
152     return 0;
153
154 }
155
156 int
157 notmuch_restore_command (notmuch_config_t *config, int argc, char *argv[])
158 {
159     notmuch_database_t *notmuch;
160     notmuch_bool_t accumulate = FALSE;
161     tag_op_flag_t flags = 0;
162     tag_op_list_t *tag_ops;
163
164     char *input_file_name = NULL;
165     const char *name_for_error = NULL;
166     gzFile input = NULL;
167     char *line = NULL;
168     void *line_ctx = NULL;
169     ssize_t line_len;
170
171     int ret = 0;
172     int opt_index;
173     int include = 0;
174     int input_format = DUMP_FORMAT_AUTO;
175
176     if (notmuch_database_open (notmuch_config_get_database_path (config),
177                                NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch))
178         return EXIT_FAILURE;
179
180     if (notmuch_config_get_maildir_synchronize_flags (config))
181         flags |= TAG_FLAG_MAILDIR_SYNC;
182
183     notmuch_opt_desc_t options[] = {
184         { NOTMUCH_OPT_KEYWORD, &input_format, "format", 'f',
185           (notmuch_keyword_t []){ { "auto", DUMP_FORMAT_AUTO },
186                                   { "batch-tag", DUMP_FORMAT_BATCH_TAG },
187                                   { "sup", DUMP_FORMAT_SUP },
188                                   { 0, 0 } } },
189         { NOTMUCH_OPT_KEYWORD_FLAGS, &include, "include", 'I',
190           (notmuch_keyword_t []){ { "config", DUMP_INCLUDE_CONFIG },
191                                   { "tags", DUMP_INCLUDE_TAGS} } },
192
193         { NOTMUCH_OPT_STRING, &input_file_name, "input", 'i', 0 },
194         { NOTMUCH_OPT_BOOLEAN,  &accumulate, "accumulate", 'a', 0 },
195         { NOTMUCH_OPT_INHERIT, (void *) &notmuch_shared_options, NULL, 0, 0 },
196         { 0, 0, 0, 0, 0 }
197     };
198
199     opt_index = parse_arguments (argc, argv, options, 1);
200     if (opt_index < 0) {
201         ret = EXIT_FAILURE;
202         goto DONE;
203     }
204
205     notmuch_process_shared_options (argv[0]);
206     notmuch_exit_if_unmatched_db_uuid (notmuch);
207
208     if (include == 0) {
209         include = DUMP_INCLUDE_CONFIG | DUMP_INCLUDE_TAGS;
210     }
211
212     name_for_error = input_file_name ? input_file_name : "stdin";
213
214     if (! accumulate)
215         flags |= TAG_FLAG_REMOVE_ALL;
216
217     errno = 0;
218     if (input_file_name)
219         input = gzopen (input_file_name, "r");
220     else {
221         int infd = dup (STDIN_FILENO);
222         if (infd < 0) {
223             fprintf (stderr, "Error duping stdin: %s\n",
224                      strerror (errno));
225             ret = EXIT_FAILURE;
226             goto DONE;
227         }
228         input = gzdopen (infd, "r");
229         if (! input)
230             close (infd);
231     }
232
233     if (input == NULL) {
234         fprintf (stderr, "Error opening %s for (gzip) reading: %s\n",
235                  name_for_error, strerror (errno));
236         ret = EXIT_FAILURE;
237         goto DONE;
238     }
239
240     if (opt_index < argc) {
241         fprintf (stderr, "Unused positional parameter: %s\n", argv[opt_index]);
242         ret = EXIT_FAILURE;
243         goto DONE;
244     }
245
246     tag_ops = tag_op_list_create (config);
247     if (tag_ops == NULL) {
248         fprintf (stderr, "Out of memory.\n");
249         ret = EXIT_FAILURE;
250         goto DONE;
251     }
252
253     do {
254         util_status_t status;
255
256         status = gz_getline (line_ctx, &line, &line_len, input);
257
258         /* empty input file not considered an error */
259         if (status == UTIL_EOF) {
260             ret = EXIT_SUCCESS;
261             goto DONE;
262         }
263
264         if (status) {
265             fprintf (stderr, "Error reading (gzipped) input: %s\n",
266                      gz_error_string(status, input));
267             ret = EXIT_FAILURE;
268             goto DONE;
269         }
270
271         if ((include & DUMP_INCLUDE_CONFIG) && line_len >= 2 && line[0] == '#' && line[1] == '@') {
272             ret = process_config_line(notmuch, line+2);
273             if (ret)
274                 goto DONE;
275         }
276
277     } while ((line_len == 0) ||
278              (line[0] == '#') ||
279              /* the cast is safe because we checked about for line_len < 0 */
280              (strspn (line, " \t\n") == (unsigned)line_len));
281
282     if (! (include & DUMP_INCLUDE_TAGS)) {
283         ret = EXIT_SUCCESS;
284         goto DONE;
285     }
286
287     char *p;
288     for (p = line; (input_format == DUMP_FORMAT_AUTO) && *p; p++) {
289         if (*p == '(')
290             input_format = DUMP_FORMAT_SUP;
291     }
292
293     if (input_format == DUMP_FORMAT_AUTO)
294         input_format = DUMP_FORMAT_BATCH_TAG;
295
296     if (input_format == DUMP_FORMAT_SUP)
297         if ( xregcomp (&regex,
298                        "^([^ ]+) \\(([^)]*)\\)$",
299                        REG_EXTENDED) )
300             INTERNAL_ERROR ("compile time constant regex failed.");
301
302     do {
303         char *query_string, *prefix, *term;
304
305         if (line_ctx != NULL)
306             talloc_free (line_ctx);
307
308         line_ctx = talloc_new (config);
309         if (input_format == DUMP_FORMAT_SUP) {
310             ret = parse_sup_line (line_ctx, line, &query_string, tag_ops);
311         } else {
312             ret = parse_tag_line (line_ctx, line, TAG_FLAG_BE_GENEROUS,
313                                   &query_string, tag_ops);
314
315             if (ret == 0) {
316                 ret = parse_boolean_term (line_ctx, query_string,
317                                           &prefix, &term);
318                 if (ret && errno == EINVAL) {
319                     fprintf (stderr, "Warning: cannot parse query: %s (skipping)\n", query_string);
320                     continue;
321                 } else if (ret) {
322                     /* This is more fatal (e.g., out of memory) */
323                     fprintf (stderr, "Error parsing query: %s\n",
324                              strerror (errno));
325                     ret = 1;
326                     break;
327                 } else if (strcmp ("id", prefix) != 0) {
328                     fprintf (stderr, "Warning: not an id query: %s (skipping)\n", query_string);
329                     continue;
330                 }
331                 query_string = term;
332             }
333         }
334
335         if (ret > 0)
336             continue;
337
338         if (ret < 0)
339             break;
340
341         ret = tag_message (line_ctx, notmuch, query_string,
342                            tag_ops, flags);
343         if (ret)
344             break;
345
346     }  while (! (ret = gz_getline (line_ctx, &line, &line_len, input)));
347     
348
349     /* EOF is normal loop termination condition, UTIL_SUCCESS is
350      * impossible here */
351     if (ret == UTIL_EOF) {
352         ret = EXIT_SUCCESS;
353     } else {
354         fprintf (stderr, "Error reading (gzipped) input: %s\n",
355                  gz_error_string (ret, input));
356         ret = EXIT_FAILURE;
357     }
358
359     /* currently this should not be after DONE: since we don't 
360      * know if the xregcomp was reached
361      */
362
363     if (input_format == DUMP_FORMAT_SUP)
364         regfree (&regex);
365
366  DONE:
367     if (line_ctx != NULL)
368         talloc_free (line_ctx);
369
370     if (notmuch)
371         notmuch_database_destroy (notmuch);
372
373     if (input && gzclose_r (input)) {
374         fprintf (stderr, "Error closing %s: %s\n",
375                  name_for_error, gzerror (input, NULL));
376         ret = EXIT_FAILURE;
377     }
378
379     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
380 }