MLE: jump-away safety also for colours (SIGH!!!)
[s-mailx.git] / maildir.c
blobffe9b83344da76fc51f1fb6adba31a6d0bafb609
1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ Maildir folder support. FIXME rewrite - why do we chdir(2)??
3 *@ FIXME Simply truncating paths isn't really it.
5 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
6 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <steffen@sdaoden.eu>.
7 */
8 /*
9 * Copyright (c) 2004
10 * Gunnar Ritter. All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by Gunnar Ritter
23 * and his contributors.
24 * 4. Neither the name of Gunnar Ritter nor the names of his contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY GUNNAR RITTER AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL GUNNAR RITTER OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
40 #undef n_FILE
41 #define n_FILE maildir
43 #ifndef HAVE_AMALGAMATION
44 # include "nail.h"
45 #endif
47 #include <dirent.h>
49 static struct message **a_maildir_table;
50 static ui32_t a_maildir_prime;
51 static sigjmp_buf _maildir_jmp;
53 static void __maildircatch(int s);
54 static void __maildircatch_hold(int s);
56 /* Do some cleanup in the tmp/ subdir */
57 static void _cleantmp(void);
59 static int _maildir_setfile1(char const *name, enum fedit_mode fm,
60 int omsgCount);
62 static int a_maildir_cmp(void const *a, void const *b);
64 static int _maildir_subdir(char const *name, char const *sub,
65 enum fedit_mode fm);
67 static void _maildir_append(char const *name, char const *sub,
68 char const *fn);
70 static void readin(char const *name, struct message *m);
72 static void maildir_update(void);
74 static void _maildir_move(struct n_timespec const *tsp,
75 struct message *m);
77 static char * mkname(struct n_timespec const *tsp, enum mflag f,
78 char const *pref);
80 static enum okay maildir_append1(struct n_timespec const *tsp,
81 char const *name, FILE *fp, off_t off1,
82 long size, enum mflag flag);
84 static enum okay trycreate(char const *name);
86 static enum okay mkmaildir(char const *name);
88 static struct message * mdlook(char const *name, struct message *data);
90 static void mktable(void);
92 static enum okay subdir_remove(char const *name, char const *sub);
94 static void
95 __maildircatch(int s)
97 NYD_X; /* Signal handler */
98 siglongjmp(_maildir_jmp, s);
101 static void
102 __maildircatch_hold(int s)
104 NYD_X; /* Signal handler */
105 n_UNUSED(s);
106 /* TODO no STDIO in signal handler, no _() tr's -- pre-translate interrupt
107 * TODO globally; */
108 n_err_sighdl(_("\nImportant operation in progress: "
109 "interrupt again to forcefully abort\n"));
110 safe_signal(SIGINT, &__maildircatch);
113 static void
114 _cleantmp(void)
116 struct stat st;
117 struct n_string s, *sp;
118 si64_t now;
119 DIR *dirp;
120 struct dirent *dp;
121 NYD_ENTER;
123 if ((dirp = opendir("tmp")) == NULL)
124 goto jleave;
126 now = n_time_now(FAL0)->ts_sec;
127 sp = n_string_creat_auto(&s);
129 while ((dp = readdir(dirp)) != NULL) {
130 if (dp->d_name[0] == '.')
131 continue;
133 sp = n_string_trunc(sp, 0);
134 sp = n_string_push_buf(sp, "tmp/", sizeof("tmp/") -1);
135 sp = n_string_push_cp(sp, dp->d_name);
136 if (stat(n_string_cp(sp), &st) == -1)
137 continue;
138 if (st.st_atime + 36*3600 < now)
139 unlink(sp->s_dat);
141 closedir(dirp);
142 jleave:
143 NYD_LEAVE;
146 static int
147 _maildir_setfile1(char const *name, enum fedit_mode fm, int omsgCount)
149 int i;
150 NYD_ENTER;
152 if (!(fm & FEDIT_NEWMAIL))
153 _cleantmp();
155 mb.mb_perm = ((n_poption & n_PO_R_FLAG) || (fm & FEDIT_RDONLY))
156 ? 0 : MB_DELE;
157 if ((i = _maildir_subdir(name, "cur", fm)) != 0)
158 goto jleave;
159 if ((i = _maildir_subdir(name, "new", fm)) != 0)
160 goto jleave;
161 _maildir_append(name, NULL, NULL);
163 n_autorec_relax_create();
164 for (i = ((fm & FEDIT_NEWMAIL) ? omsgCount : 0); i < msgCount; ++i) {
165 readin(name, message + i);
166 n_autorec_relax_unroll();
168 n_autorec_relax_gut();
170 if (fm & FEDIT_NEWMAIL) {
171 if (msgCount > omsgCount)
172 qsort(&message[omsgCount], msgCount - omsgCount, sizeof *message,
173 &a_maildir_cmp);
174 } else if (msgCount)
175 qsort(message, msgCount, sizeof *message, &a_maildir_cmp);
176 i = msgCount;
177 jleave:
178 NYD_LEAVE;
179 return i;
182 static int
183 a_maildir_cmp(void const *xa, void const *xb){
184 char const *cpa, *cpa_pid, *cpb, *cpb_pid;
185 union {struct message const *mp; char const *cp;} a, b;
186 si64_t at, bt;
187 int rv;
188 NYD2_ENTER;
190 a.mp = xa;
191 b.mp = xb;
193 /* We could have parsed the time somewhen in the past, do a quick shot */
194 at = (si64_t)a.mp->m_time;
195 bt = (si64_t)b.mp->m_time;
196 if(at != 0 && bt != 0 && (at -= bt) != 0)
197 goto jret;
199 /* Otherwise we need to parse the name */
200 a.cp = &a.mp->m_maildir_file[4];
201 b.cp = &b.mp->m_maildir_file[4];
203 /* Interpret time stored in name, and use it for comparison */
204 if(((n_idec_si64_cp(&at, a.cp, 10, &cpa)
205 ) & n_IDEC_STATE_EMASK) != n_IDEC_STATE_EBASE || *cpa != '.' ||
206 a.cp == cpa)
207 goto jm1; /* Fishy */
208 if(((n_idec_si64_cp(&bt, b.cp, 10, &cpb)
209 ) & n_IDEC_STATE_EMASK) != n_IDEC_STATE_EBASE || *cpb != '.' ||
210 b.cp == cpb)
211 goto j1; /* Fishy */
213 if((at -= bt) != 0)
214 goto jret;
216 /* If the seconds part does not work, go deeper.
217 * We use de-facto standard "maildir — E-mail directory" from the Courier
218 * mail server, also used by, e.g., Dovecot: sec.MusecPpid.hostname:2,flags.
219 * However, a different name convention exists which uses
220 * sec.pid_counter.hostname:2,flags.
221 * First go for usec/counter, then pid */
223 /* A: exact "standard"? */
224 cpa_pid = NULL;
225 a.cp = ++cpa;
226 if((rv = *a.cp) == 'M')
228 /* Known compat? */
229 else if(digitchar(rv)){
230 cpa_pid = a.cp++;
231 while((rv = *a.cp) != '\0' && rv != '_')
232 ++a.cp;
233 if(rv == '\0')
234 goto jm1; /* Fishy */
236 /* This is compatible to what dovecot does, it surely does not do so
237 * for nothing, but i have no idea, but am too stupid to ask */
238 else for(;; rv = *++a.cp){
239 if(rv == 'M')
240 break;
241 if(rv == '\0' || rv == '.' || rv == n_MAILDIR_SEPARATOR)
242 goto jm1; /* Fishy */
244 ++a.cp;
245 if(((n_idec_si64_cp(&at, a.cp, 10, &cpa)
246 ) & n_IDEC_STATE_EMASK) != n_IDEC_STATE_EBASE)
247 goto jm1; /* Fishy */
249 /* B: as above */
250 cpb_pid = NULL;
251 b.cp = ++cpb;
252 if((rv = *b.cp) == 'M')
254 else if(digitchar(rv)){
255 cpb_pid = b.cp++;
256 while((rv = *b.cp) != '\0' && rv != '_')
257 ++b.cp;
258 if(rv == '\0')
259 goto j1;
260 }else for(;; rv = *++b.cp){
261 if(rv == 'M')
262 break;
263 if(rv == '\0' || rv == '.' || rv == n_MAILDIR_SEPARATOR)
264 goto jm1;
266 ++b.cp;
267 if(((n_idec_si64_cp(&bt, b.cp, 10, &cpb)
268 ) & n_IDEC_STATE_EMASK) != n_IDEC_STATE_EBASE)
269 goto j1;
271 if((at -= bt) != 0)
272 goto jret;
274 /* So this gets hairy: sort by PID, then hostname */
275 if(cpa_pid != NULL){
276 a.cp = cpa_pid;
277 xa = cpa;
278 }else{
279 a.cp = cpa;
280 if(*a.cp++ != 'P')
281 goto jm1; /* Fishy */
283 if(((n_idec_si64_cp(&at, a.cp, 10, &cpa)
284 ) & n_IDEC_STATE_EMASK) != n_IDEC_STATE_EBASE)
285 goto jm1; /* Fishy */
287 if(cpb_pid != NULL){
288 b.cp = cpb_pid;
289 xb = cpb;
290 }else{
291 b.cp = cpb;
292 if(*b.cp++ != 'P')
293 goto j1; /* Fishy */
295 if(((n_idec_si64_cp(&bt, b.cp, 10, &cpb)
296 ) & n_IDEC_STATE_EMASK) != n_IDEC_STATE_EBASE)
297 goto jm1; /* Fishy */
299 if((at -= bt) != 0)
300 goto jret;
302 /* Hostname */
303 a.cp = (cpa_pid != NULL) ? xa : cpa;
304 b.cp = (cpb_pid != NULL) ? xb : cpb;
305 for(;; ++a.cp, ++b.cp){
306 char ac, bc;
308 ac = *a.cp;
309 at = (ac != '\0' && ac != n_MAILDIR_SEPARATOR);
310 bc = *b.cp;
311 bt = (bc != '\0' && bc != n_MAILDIR_SEPARATOR);
312 if((at -= bt) != 0)
313 break;
314 at = ac;
315 if((at -= bc) != 0)
316 break;
319 jret:
320 rv = (at == 0 ? 0 : (at < 0 ? -1 : 1));
321 jleave:
322 NYD2_LEAVE;
323 return rv;
324 jm1:
325 rv = -1;
326 goto jleave;
328 rv = 1;
329 goto jleave;
332 static int
333 _maildir_subdir(char const *name, char const *sub, enum fedit_mode fm)
335 DIR *dirp;
336 struct dirent *dp;
337 int rv;
338 NYD_ENTER;
340 if ((dirp = opendir(sub)) == NULL) {
341 n_err(_("Cannot open directory %s\n"),
342 n_shexp_quote_cp(savecatsep(name, '/', sub), FAL0));
343 rv = -1;
344 goto jleave;
346 if (access(sub, W_OK) == -1)
347 mb.mb_perm = 0;
348 while ((dp = readdir(dirp)) != NULL) {
349 if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
350 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
351 continue;
352 if (dp->d_name[0] == '.')
353 continue;
354 if (!(fm & FEDIT_NEWMAIL) || mdlook(dp->d_name, NULL) == NULL)
355 _maildir_append(name, sub, dp->d_name);
357 closedir(dirp);
358 rv = 0;
359 jleave:
360 NYD_LEAVE;
361 return rv;
364 static void
365 _maildir_append(char const *name, char const *sub, char const *fn)
367 struct message *m;
368 time_t t = 0;
369 enum mflag f = MUSED | MNOFROM | MNEWEST;
370 char const *cp, *xp;
371 NYD_ENTER;
372 n_UNUSED(name);
374 if (fn != NULL && sub != NULL) {
375 if (!strcmp(sub, "new"))
376 f |= MNEW;
378 /* C99 */{
379 si64_t tib;
381 (void)/*TODO*/n_idec_si64_cp(&tib, fn, 10, &xp);
382 t = (time_t)tib;
385 if ((cp = strrchr(xp, ',')) != NULL && PTRCMP(cp, >, xp + 2) &&
386 cp[-1] == '2' && cp[-2] == n_MAILDIR_SEPARATOR) {
387 while (*++cp != '\0') {
388 switch (*cp) {
389 case 'F':
390 f |= MFLAGGED;
391 break;
392 case 'R':
393 f |= MANSWERED;
394 break;
395 case 'S':
396 f |= MREAD;
397 break;
398 case 'T':
399 f |= MDELETED;
400 break;
401 case 'D':
402 f |= MDRAFT;
403 break;
409 /* Ensure room (and a NULLified last entry) */
410 ++msgCount;
411 message_append(NULL);
412 --msgCount;
414 if (fn == NULL || sub == NULL)
415 goto jleave;
417 m = &message[msgCount++];
418 /* C99 */{
419 char *tmp;
420 size_t sz, i;
422 i = strlen(fn) +1;
423 sz = strlen(sub);
424 m->m_maildir_file = tmp = smalloc(sz + 1 + i);
425 memcpy(tmp, sub, sz);
426 tmp[sz++] = '/';
427 memcpy(&tmp[sz], fn, i);
429 m->m_time = t;
430 m->m_flag = f;
431 m->m_maildir_hash = ~n_torek_hash(fn);
432 jleave:
433 NYD_LEAVE;
434 return;
437 static void
438 readin(char const *name, struct message *m)
440 char *buf;
441 size_t bufsize, buflen, cnt;
442 long size = 0, lines = 0;
443 off_t offset;
444 FILE *fp;
445 int emptyline = 0;
446 NYD_ENTER;
448 if ((fp = Fopen(m->m_maildir_file, "r")) == NULL) {
449 n_err(_("Cannot read %s for message %lu\n"),
450 n_shexp_quote_cp(savecatsep(name, '/', m->m_maildir_file), FAL0),
451 (ul_i)PTR2SIZE(m - message + 1));
452 m->m_flag |= MHIDDEN;
453 goto jleave;
456 cnt = fsize(fp);
457 fseek(mb.mb_otf, 0L, SEEK_END);
458 offset = ftell(mb.mb_otf);
459 buf = smalloc(bufsize = LINESIZE);
460 buflen = 0;
461 while (fgetline(&buf, &bufsize, &cnt, &buflen, fp, 1) != NULL) {
462 /* Since we simply copy over data without doing any transfer
463 * encoding reclassification/adjustment we *have* to perform
464 * RFC 4155 compliant From_ quoting here */
465 if (emptyline && is_head(buf, buflen, FAL0)) {
466 putc('>', mb.mb_otf);
467 ++size;
469 size += fwrite(buf, 1, buflen, mb.mb_otf);/*XXX err hdling*/
470 emptyline = (*buf == '\n');
471 ++lines;
473 free(buf);
474 if (!emptyline) {
475 putc('\n', mb.mb_otf);
476 ++lines;
477 ++size;
480 Fclose(fp);
481 fflush(mb.mb_otf);
482 m->m_size = m->m_xsize = size;
483 m->m_lines = m->m_xlines = lines;
484 m->m_block = mailx_blockof(offset);
485 m->m_offset = mailx_offsetof(offset);
486 substdate(m);
487 jleave:
488 NYD_LEAVE;
491 static void
492 maildir_update(void)
494 struct message *m;
495 struct n_timespec const *tsp;
496 int dodel, c, gotcha = 0, held = 0, modflags = 0;
497 NYD_ENTER;
499 if (mb.mb_perm == 0)
500 goto jfree;
502 if (!(n_pstate & n_PS_EDIT)) {
503 holdbits();
504 for (m = message, c = 0; PTRCMP(m, <, message + msgCount); ++m) {
505 if (m->m_flag & MBOX)
506 c++;
508 if (c > 0)
509 if (makembox() == STOP)
510 goto jbypass;
513 tsp = n_time_now(TRU1); /* TODO FAL0, eventloop update! */
515 n_autorec_relax_create();
516 for (m = message, gotcha = 0, held = 0; PTRCMP(m, <, message + msgCount);
517 ++m) {
518 if (n_pstate & n_PS_EDIT)
519 dodel = m->m_flag & MDELETED;
520 else
521 dodel = !((m->m_flag & MPRESERVE) || !(m->m_flag & MTOUCH));
522 if (dodel) {
523 if (unlink(m->m_maildir_file) < 0)
524 n_err(_("Cannot delete file %s for message %lu\n"),
525 n_shexp_quote_cp(savecatsep(mailname, '/', m->m_maildir_file),
526 FAL0), (ul_i)PTR2SIZE(m - message + 1));
527 else
528 ++gotcha;
529 } else {
530 if ((m->m_flag & (MREAD | MSTATUS)) == (MREAD | MSTATUS) ||
531 (m->m_flag & (MNEW | MBOXED | MSAVED | MSTATUS | MFLAG |
532 MUNFLAG | MANSWER | MUNANSWER | MDRAFT | MUNDRAFT))) {
533 _maildir_move(tsp, m);
534 n_autorec_relax_unroll();
535 ++modflags;
537 ++held;
540 n_autorec_relax_gut();
542 jbypass:
543 if ((gotcha || modflags) && (n_pstate & n_PS_EDIT)) {
544 fprintf(n_stdout, "%s %s\n",
545 n_shexp_quote_cp(displayname, FAL0),
546 ((ok_blook(bsdcompat) || ok_blook(bsdmsgs))
547 ? _("complete") : _("updated.")));
548 } else if (held && !(n_pstate & n_PS_EDIT) && mb.mb_perm != 0) {
549 if (held == 1)
550 fprintf(n_stdout, _("Held 1 message in %s\n"), displayname);
551 else
552 fprintf(n_stdout, _("Held %d messages in %s\n"), held, displayname);
554 fflush(n_stdout);
555 jfree:
556 for (m = message; PTRCMP(m, <, message + msgCount); ++m)
557 free(n_UNCONST(m->m_maildir_file));
558 NYD_LEAVE;
561 static void
562 _maildir_move(struct n_timespec const *tsp, struct message *m)
564 char *fn, *newfn;
565 NYD_ENTER;
567 fn = mkname(tsp, m->m_flag, m->m_maildir_file + 4);
568 newfn = savecat("cur/", fn);
569 if (!strcmp(m->m_maildir_file, newfn))
570 goto jleave;
571 if (link(m->m_maildir_file, newfn) == -1) {
572 n_err(_("Cannot link %s to %s: message %lu not touched\n"),
573 n_shexp_quote_cp(savecatsep(mailname, '/', m->m_maildir_file), FAL0),
574 n_shexp_quote_cp(savecatsep(mailname, '/', newfn), FAL0),
575 (ul_i)PTR2SIZE(m - message + 1));
576 goto jleave;
578 if (unlink(m->m_maildir_file) == -1)
579 n_err(_("Cannot unlink %s\n"),
580 n_shexp_quote_cp(savecatsep(mailname, '/', m->m_maildir_file), FAL0));
581 jleave:
582 NYD_LEAVE;
585 static char *
586 mkname(struct n_timespec const *tsp, enum mflag f, char const *pref)
588 static char *node;
589 static struct n_timespec ts;
591 char *cp;
592 int size, n, i;
593 NYD_ENTER;
595 if (pref == NULL) {
596 si64_t s;
598 if(n_pid == 0)
599 n_pid = getpid();
601 if (node == NULL) {
602 cp = n_nodename(FAL0);
603 n = size = 0;
604 do {
605 if (UICMP(32, n, <, size + 8))
606 node = srealloc(node, size += 20);
607 switch (*cp) {
608 case '/':
609 node[n++] = '\\', node[n++] = '0',
610 node[n++] = '5', node[n++] = '7';
611 break;
612 case ':':
613 node[n++] = '\\', node[n++] = '0',
614 node[n++] = '7', node[n++] = '2';
615 break;
616 default:
617 node[n++] = *cp;
619 } while (*cp++ != '\0');
622 /* Problem: Courier spec uses microseconds, not nanoseconds */
623 if((s = tsp->ts_sec) > ts.ts_sec){
624 ts.ts_sec = s;
625 ts.ts_nsec = tsp->ts_nsec / (n_DATE_NANOSSEC / n_DATE_MICROSSEC);
626 }else{
627 s = tsp->ts_nsec / (n_DATE_NANOSSEC / n_DATE_MICROSSEC);
628 if(s <= ts.ts_nsec)
629 s = ts.ts_nsec + 1;
630 if(s < n_DATE_MICROSSEC)
631 ts.ts_nsec = s;
632 else{
633 ++ts.ts_sec;
634 ts.ts_nsec = 0;
638 /* Create a name according to Courier spec */
639 size = 60 + strlen(node);
640 cp = n_autorec_alloc(size);
641 n = snprintf(cp, size, "%" PRId64 ".M%" PRIdZ "P%ld.%s:2,",
642 ts.ts_sec, ts.ts_nsec, (long)n_pid, node);
643 } else {
644 size = (n = strlen(pref)) + 13;
645 cp = salloc(size);
646 memcpy(cp, pref, n +1);
647 for (i = n; i > 3; --i)
648 if (cp[i - 1] == ',' && cp[i - 2] == '2' &&
649 cp[i - 3] == n_MAILDIR_SEPARATOR) {
650 n = i;
651 break;
653 if (i <= 3) {
654 memcpy(cp + n, ":2,", 3 +1);
655 n += 3;
658 if (n < size - 7) {
659 if (f & MDRAFTED)
660 cp[n++] = 'D';
661 if (f & MFLAGGED)
662 cp[n++] = 'F';
663 if (f & MANSWERED)
664 cp[n++] = 'R';
665 if (f & MREAD)
666 cp[n++] = 'S';
667 if (f & MDELETED)
668 cp[n++] = 'T';
669 cp[n] = '\0';
671 NYD_LEAVE;
672 return cp;
675 static enum okay
676 maildir_append1(struct n_timespec const *tsp, char const *name, FILE *fp,
677 off_t off1, long size, enum mflag flag)
679 char buf[4096], *fn, *tfn, *nfn;
680 struct stat st;
681 FILE *op;
682 size_t nlen, flen, n;
683 enum okay rv = STOP;
684 NYD_ENTER;
686 nlen = strlen(name);
688 /* Create a unique temporary file */
689 for (nfn = (char*)0xA /* XXX no magic */;; n_msleep(500, FAL0)) {
690 flen = strlen(fn = mkname(tsp, flag, NULL));
691 tfn = n_autorec_alloc(n = nlen + flen + 6);
692 snprintf(tfn, n, "%s/tmp/%s", name, fn);
694 /* Use "wx" for O_EXCL XXX stat(2) rather redundant; coverity:TOCTOU */
695 if ((!stat(tfn, &st) || n_err_no == n_ERR_NOENT) &&
696 (op = Fopen(tfn, "wx")) != NULL)
697 break;
699 nfn = (char*)(PTR2SIZE(nfn) - 1);
700 if (nfn == NULL) {
701 n_err(_("Can't create an unique file name in %s\n"),
702 n_shexp_quote_cp(savecat(name, "/tmp"), FAL0));
703 goto jleave;
707 if (fseek(fp, off1, SEEK_SET) == -1)
708 goto jtmperr;
709 while (size > 0) {
710 size_t z = UICMP(z, size, >, sizeof buf) ? sizeof buf : (size_t)size;
712 if (z != (n = fread(buf, 1, z, fp)) || n != fwrite(buf, 1, n, op)) {
713 jtmperr:
714 n_err(_("Error writing to %s\n"), n_shexp_quote_cp(tfn, FAL0));
715 Fclose(op);
716 goto jerr;
718 size -= n;
720 Fclose(op);
722 nfn = n_autorec_alloc(n = nlen + flen + 6);
723 snprintf(nfn, n, "%s/new/%s", name, fn);
724 if (link(tfn, nfn) == -1) {
725 n_err(_("Cannot link %s to %s\n"), n_shexp_quote_cp(tfn, FAL0),
726 n_shexp_quote_cp(nfn, FAL0));
727 goto jerr;
729 rv = OKAY;
730 jerr:
731 if (unlink(tfn) == -1)
732 n_err(_("Cannot unlink %s\n"), n_shexp_quote_cp(tfn, FAL0));
733 jleave:
734 NYD_LEAVE;
735 return rv;
738 static enum okay
739 trycreate(char const *name)
741 struct stat st;
742 enum okay rv = STOP;
743 NYD_ENTER;
745 if (!stat(name, &st)) {
746 if (!S_ISDIR(st.st_mode)) {
747 n_err(_("%s is not a directory\n"), n_shexp_quote_cp(name, FAL0));
748 goto jleave;
750 } else if (!n_path_mkdir(name)) {
751 n_err(_("Cannot create directory %s\n"), n_shexp_quote_cp(name, FAL0));
752 goto jleave;
754 rv = OKAY;
755 jleave:
756 NYD_LEAVE;
757 return rv;
760 static enum okay
761 mkmaildir(char const *name) /* TODO proper cleanup on error; use path[] loop */
763 char *np;
764 size_t sz;
765 enum okay rv = STOP;
766 NYD_ENTER;
768 if (trycreate(name) == OKAY) {
769 np = ac_alloc((sz = strlen(name)) + 4 +1);
770 memcpy(np, name, sz);
771 memcpy(np + sz, "/tmp", 4 +1);
772 if (trycreate(np) == OKAY) {
773 memcpy(np + sz, "/new", 4 +1);
774 if (trycreate(np) == OKAY) {
775 memcpy(np + sz, "/cur", 4 +1);
776 rv = trycreate(np);
779 ac_free(np);
781 NYD_LEAVE;
782 return rv;
785 static struct message *
786 mdlook(char const *name, struct message *data)
788 struct message *mp;
789 ui32_t c, h, n = 0;
790 NYD_ENTER;
792 if (data && data->m_maildir_hash)
793 h = ~data->m_maildir_hash;
794 else
795 h = n_torek_hash(name);
796 h %= a_maildir_prime;
797 c = h;
798 mp = a_maildir_table[c];
800 while (mp != NULL) {
801 if (!strcmp(mp->m_maildir_file + 4, name))
802 break;
803 c += (n & 1) ? -((n+1)/2) * ((n+1)/2) : ((n+1)/2) * ((n+1)/2);
804 n++;
805 while (c >= a_maildir_prime)
806 c -= a_maildir_prime;
807 mp = a_maildir_table[c];
809 if (data != NULL && mp == NULL)
810 mp = data;
811 NYD_LEAVE;
812 return mp;
815 static void
816 mktable(void)
818 struct message *mp;
819 size_t i;
820 NYD_ENTER;
822 a_maildir_prime = n_prime_next(msgCount);
823 a_maildir_table = scalloc(a_maildir_prime, sizeof *a_maildir_table);
824 for (mp = message, i = msgCount; i-- != 0; ++mp)
825 mdlook(mp->m_maildir_file + 4, mp);
826 NYD_LEAVE;
829 static enum okay
830 subdir_remove(char const *name, char const *sub)
832 char *path;
833 int pathsize, pathend, namelen, sublen, n;
834 DIR *dirp;
835 struct dirent *dp;
836 enum okay rv = STOP;
837 NYD_ENTER;
839 namelen = strlen(name);
840 sublen = strlen(sub);
841 path = smalloc(pathsize = namelen + sublen + 30 +1);
842 memcpy(path, name, namelen);
843 path[namelen] = '/';
844 memcpy(path + namelen + 1, sub, sublen);
845 path[namelen + sublen + 1] = '/';
846 path[pathend = namelen + sublen + 2] = '\0';
848 if ((dirp = opendir(path)) == NULL) {
849 n_perr(path, 0);
850 goto jleave;
852 while ((dp = readdir(dirp)) != NULL) {
853 if (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
854 (dp->d_name[1] == '.' && dp->d_name[2] == '\0')))
855 continue;
856 if (dp->d_name[0] == '.')
857 continue;
858 n = strlen(dp->d_name);
859 if (UICMP(32, pathend + n +1, >, pathsize))
860 path = srealloc(path, pathsize = pathend + n + 30);
861 memcpy(path + pathend, dp->d_name, n +1);
862 if (unlink(path) == -1) {
863 n_perr(path, 0);
864 closedir(dirp);
865 goto jleave;
868 closedir(dirp);
870 path[pathend] = '\0';
871 if (rmdir(path) == -1) {
872 n_perr(path, 0);
873 goto jleave;
875 rv = OKAY;
876 jleave:
877 free(path);
878 NYD_LEAVE;
879 return rv;
882 FL int
883 maildir_setfile(char const * volatile name, enum fedit_mode fm)
885 sighandler_type volatile saveint;
886 struct cw cw;
887 char const *emsg;
888 int omsgCount;
889 int volatile i = -1;
890 NYD_ENTER;
892 omsgCount = msgCount;
893 if (cwget(&cw) == STOP) {
894 n_alert(_("Cannot open current directory"));
895 goto jleave;
898 if (!(fm & FEDIT_NEWMAIL) && !quit(FAL0))
899 goto jleave;
901 saveint = safe_signal(SIGINT, SIG_IGN);
903 if (!(fm & FEDIT_NEWMAIL)) {
904 if (fm & FEDIT_SYSBOX)
905 n_pstate &= ~n_PS_EDIT;
906 else
907 n_pstate |= n_PS_EDIT;
908 if (mb.mb_itf) {
909 fclose(mb.mb_itf);
910 mb.mb_itf = NULL;
912 if (mb.mb_otf) {
913 fclose(mb.mb_otf);
914 mb.mb_otf = NULL;
916 initbox(name);
917 mb.mb_type = MB_MAILDIR;
920 if(!n_is_dir(name, FAL0)){
921 emsg = N_("Not a maildir: %s\n");
922 goto jerr;
923 }else if(chdir(name) < 0){
924 emsg = N_("Cannot enter maildir://%s\n");
925 jerr:
926 n_err(V_(emsg), n_shexp_quote_cp(name, FAL0));
927 mb.mb_type = MB_VOID;
928 *mailname = '\0';
929 msgCount = 0;
930 cwrelse(&cw);
931 safe_signal(SIGINT, saveint);
932 goto jleave;
935 a_maildir_table = NULL;
936 if (sigsetjmp(_maildir_jmp, 1) == 0) {
937 if (fm & FEDIT_NEWMAIL)
938 mktable();
939 if (saveint != SIG_IGN)
940 safe_signal(SIGINT, &__maildircatch);
941 i = _maildir_setfile1(name, fm, omsgCount);
943 if ((fm & FEDIT_NEWMAIL) && a_maildir_table != NULL)
944 free(a_maildir_table);
946 safe_signal(SIGINT, saveint);
948 if (i < 0) {
949 mb.mb_type = MB_VOID;
950 *mailname = '\0';
951 msgCount = 0;
954 if (cwret(&cw) == STOP)
955 n_panic(_("Cannot change back to current directory"));
956 cwrelse(&cw);
958 setmsize(msgCount);
959 if ((fm & FEDIT_NEWMAIL) && mb.mb_sorted && msgCount > omsgCount) {
960 mb.mb_threaded = 0;
961 c_sort((void*)-1);
964 if (!(fm & FEDIT_NEWMAIL)) {
965 n_pstate &= ~n_PS_SAW_COMMAND;
966 n_pstate |= n_PS_SETFILE_OPENED;
969 if ((n_poption & n_PO_EXISTONLY) && !(n_poption & n_PO_HEADERLIST)) {
970 i = (msgCount == 0);
971 goto jleave;
974 if (!(fm & FEDIT_NEWMAIL) && (fm & FEDIT_SYSBOX) && msgCount == 0) {
975 if (mb.mb_type == MB_MAILDIR /* XXX ?? */ && !ok_blook(emptystart))
976 n_err(_("No mail at %s\n"), n_shexp_quote_cp(name, FAL0));
977 i = 1;
978 goto jleave;
981 if ((fm & FEDIT_NEWMAIL) && msgCount > omsgCount)
982 newmailinfo(omsgCount);
983 i = 0;
984 jleave:
985 NYD_LEAVE;
986 return i;
989 FL bool_t
990 maildir_quit(bool_t hold_sigs_on)
992 sighandler_type saveint;
993 struct cw cw;
994 bool_t rv;
995 NYD_ENTER;
997 if(hold_sigs_on)
998 rele_sigs();
1000 rv = FAL0;
1002 if (cwget(&cw) == STOP) {
1003 n_alert(_("Cannot open current directory"));
1004 goto jleave;
1007 saveint = safe_signal(SIGINT, SIG_IGN);
1009 if (chdir(mailname) == -1) {
1010 n_err(_("Cannot change directory to %s\n"),
1011 n_shexp_quote_cp(mailname, FAL0));
1012 cwrelse(&cw);
1013 safe_signal(SIGINT, saveint);
1014 goto jleave;
1017 if (sigsetjmp(_maildir_jmp, 1) == 0) {
1018 if (saveint != SIG_IGN)
1019 safe_signal(SIGINT, &__maildircatch_hold);
1020 maildir_update();
1023 safe_signal(SIGINT, saveint);
1025 if (cwret(&cw) == STOP)
1026 n_panic(_("Cannot change back to current directory"));
1027 cwrelse(&cw);
1028 rv = TRU1;
1029 jleave:
1030 if(hold_sigs_on)
1031 hold_sigs();
1032 NYD_LEAVE;
1033 return rv;
1036 FL enum okay
1037 maildir_append(char const *name, FILE *fp, long offset)
1039 struct n_timespec const *tsp;
1040 char *buf, *bp, *lp;
1041 size_t bufsize, buflen, cnt;
1042 off_t off1 = -1, offs;
1043 long size;
1044 int flag;
1045 enum {_NONE = 0, _INHEAD = 1<<0, _NLSEP = 1<<1} state;
1046 enum okay rv;
1047 NYD_ENTER;
1049 if ((rv = mkmaildir(name)) != OKAY)
1050 goto jleave;
1052 buf = smalloc(bufsize = LINESIZE); /* TODO line pool; signals */
1053 buflen = 0;
1054 cnt = fsize(fp);
1055 offs = offset /* BSD will move due to O_APPEND! ftell(fp) */;
1056 size = 0;
1057 tsp = n_time_now(TRU1); /* TODO -> eventloop */
1059 n_autorec_relax_create();
1060 for (flag = MNEW, state = _NLSEP;;) {
1061 bp = fgetline(&buf, &bufsize, &cnt, &buflen, fp, 1);
1063 if (bp == NULL ||
1064 ((state & (_INHEAD | _NLSEP)) == _NLSEP &&
1065 is_head(buf, buflen, FAL0))) {
1066 if (off1 != (off_t)-1) {
1067 if ((rv = maildir_append1(tsp, name, fp, off1, size, flag)) == STOP)
1068 goto jfree;
1069 n_autorec_relax_unroll();
1070 if (fseek(fp, offs + buflen, SEEK_SET) == -1) {
1071 rv = STOP;
1072 goto jfree;
1075 off1 = offs + buflen;
1076 size = 0;
1077 state = _INHEAD;
1078 flag = MNEW;
1080 if (bp == NULL)
1081 break;
1082 } else
1083 size += buflen;
1084 offs += buflen;
1086 state &= ~_NLSEP;
1087 if (buf[0] == '\n') {
1088 state &= ~_INHEAD;
1089 state |= _NLSEP;
1090 } else if (state & _INHEAD) {
1091 if (!ascncasecmp(buf, "status", 6)) {
1092 lp = buf + 6;
1093 while (whitechar(*lp))
1094 ++lp;
1095 if (*lp == ':')
1096 while (*++lp != '\0')
1097 switch (*lp) {
1098 case 'R':
1099 flag |= MREAD;
1100 break;
1101 case 'O':
1102 flag &= ~MNEW;
1103 break;
1105 } else if (!ascncasecmp(buf, "x-status", 8)) {
1106 lp = buf + 8;
1107 while (whitechar(*lp))
1108 ++lp;
1109 if (*lp == ':') {
1110 while (*++lp != '\0')
1111 switch (*lp) {
1112 case 'F':
1113 flag |= MFLAGGED;
1114 break;
1115 case 'A':
1116 flag |= MANSWERED;
1117 break;
1118 case 'T':
1119 flag |= MDRAFTED;
1120 break;
1126 assert(rv == OKAY);
1127 jfree:
1128 n_autorec_relax_gut();
1129 free(buf);
1130 jleave:
1131 NYD_LEAVE;
1132 return rv;
1135 FL enum okay
1136 maildir_remove(char const *name)
1138 enum okay rv = STOP;
1139 NYD_ENTER;
1141 if (subdir_remove(name, "tmp") == STOP ||
1142 subdir_remove(name, "new") == STOP ||
1143 subdir_remove(name, "cur") == STOP)
1144 goto jleave;
1145 if (rmdir(name) == -1) {
1146 n_perr(name, 0);
1147 goto jleave;
1149 rv = OKAY;
1150 jleave:
1151 NYD_LEAVE;
1152 return rv;
1155 /* s-it-mode */