fix regressions
[apps/madmutt.git] / buffy.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  *
5  * Parts were written/modified by:
6  * Rocco Rutte <pdmef@cs.tu-berlin.de>
7  *
8  * This file is part of mutt-ng, see http://www.muttng.org/.
9  * It's licensed under the GNU General Public License,
10  * please see the file GPL in the top level source directory.
11  */
12
13 #if HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #include <lib-lib/mem.h>
18
19 #include "mutt.h"
20 #include "buffy.h"
21 #include "buffer.h"
22 #include "mx.h"
23 #include "mh.h"
24 #include "sidebar.h"
25
26 #include "mutt_curses.h"
27
28 #ifdef USE_IMAP
29 #include "imap.h"
30 #endif
31
32 #include "lib/mem.h"
33 #include "lib/intl.h"
34
35 #include <string.h>
36 #include <sys/stat.h>
37 #include <dirent.h>
38 #include <utime.h>
39 #include <ctype.h>
40 #include <unistd.h>
41
42 #include <stdio.h>
43
44 static time_t BuffyTime = 0;    /* last time we started checking for mail */
45
46 #ifdef USE_IMAP
47 static time_t ImapBuffyTime = 0;        /* last time we started checking for mail */
48 #endif
49 static short BuffyCount = 0;    /* how many boxes with new mail */
50 static short BuffyNotify = 0;   /* # of unnotified new boxes */
51
52 #ifdef BUFFY_SIZE
53
54 /* Find the last message in the file. 
55  * upon success return 0. If no message found - return -1 */
56
57 static int fseeko_last_message (FILE * f)
58 {
59   LOFF_T pos;
60   char buffer[BUFSIZ + 9];      /* 7 for "\n\nFrom " */
61   int bytes_read;
62   int i;                        /* Index into `buffer' for scanning.  */
63
64   memset (buffer, 0, sizeof (buffer));
65   fseeko (f, 0, SEEK_END);
66   pos = ftello (f);
67
68   /* Set `bytes_read' to the size of the last, probably partial, buffer; 0 <
69    * `bytes_read' <= `BUFSIZ'.  */
70   bytes_read = pos % BUFSIZ;
71   if (bytes_read == 0)
72     bytes_read = BUFSIZ;
73   /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
74    * reads will be on block boundaries, which might increase efficiency.  */
75   while ((pos -= bytes_read) >= 0) {
76     /* we save in the buffer at the end the first 7 chars from the last read */
77     strncpy (buffer + BUFSIZ, buffer, 5 + 2);   /* 2 == 2 * str_len(CRLF) */
78     fseeko (f, pos, SEEK_SET);
79     bytes_read = fread (buffer, sizeof (char), bytes_read, f);
80     if (bytes_read == -1)
81       return -1;
82     for (i = bytes_read; --i >= 0;)
83       if (!str_ncmp (buffer + i, "\n\nFrom ", str_len ("\n\nFrom "))) { /* found it - go to the beginning of the From */
84         fseeko (f, pos + i + 2, SEEK_SET);
85         return 0;
86       }
87     bytes_read = BUFSIZ;
88   }
89
90   /* here we are at the beginning of the file */
91   if (!str_ncmp ("From ", buffer, 5)) {
92     fseeko (f, 0, 0);
93     return (0);
94   }
95
96   return (-1);
97 }
98
99 /* Return 1 if the last message is new */
100 static int test_last_status_new (FILE * f)
101 {
102   HEADER *hdr;
103   ENVELOPE *tmp_envelope;
104   int result = 0;
105
106   if (fseeko_last_message (f) == -1)
107     return (0);
108
109   hdr = mutt_new_header ();
110   tmp_envelope = mutt_read_rfc822_header (f, hdr, 0, 0);
111   if (!(hdr->read || hdr->old))
112     result = 1;
113
114   mutt_free_envelope (&tmp_envelope);
115   mutt_free_header (&hdr);
116
117   return result;
118 }
119
120 static int test_new_folder (const char *path)
121 {
122   FILE *f;
123   int rc = 0;
124   int typ;
125
126   typ = mx_get_magic (path);
127
128   if (typ != M_MBOX && typ != M_MMDF)
129     return 0;
130
131   if ((f = fopen (path, "rb"))) {
132     rc = test_last_status_new (f);
133     fclose (f);
134   }
135
136   return rc;
137 }
138
139 BUFFY *buffy_find_mailbox (const char *path)
140 {
141   struct stat sb;
142   struct stat tmp_sb;
143   int i = 0;
144
145   if (stat (path, &sb) != 0)
146     return NULL;
147
148   if (!list_empty(Incoming)) {
149     for (i = 0; i < Incoming->length; i++) {
150       if (stat (Incoming->data[i], &tmp_sb) == 0 &&
151           sb.st_dev == tmp_sb.st_dev && sb.st_ino == tmp_sb.st_ino)
152         return ((BUFFY*) Incoming->data[i]);
153     }
154   }
155   return (NULL);
156 }
157
158 void buffy_update_mailbox (BUFFY * b)
159 {
160   struct stat sb;
161
162   if (!b)
163     return;
164
165   if (stat (b->path, &sb) == 0)
166     b->size = (long) sb.st_size;
167   else
168     b->size = 0;
169   return;
170 }
171 #endif
172
173 /* func to free buffy for list_del() */
174 static void buffy_free (BUFFY** p) {
175   p_delete(&(*p)->path);
176   p_delete(p);
177 }
178
179 int buffy_lookup (const char* path) {
180   int i = 0;
181   if (list_empty(Incoming) || !path || !*path)
182     return (-1);
183   for (i = 0; i < Incoming->length; i++) {
184     if (str_eq (((BUFFY*) Incoming->data[i])->path, path) )
185       return (i);
186   }
187   return (-1);
188 }
189
190 int buffy_parse_mailboxes (BUFFER * path, BUFFER * s, unsigned long data,
191                           BUFFER * err)
192 {
193   BUFFY* tmp;
194   char buf[_POSIX_PATH_MAX];
195   int i = 0;
196 #ifdef BUFFY_SIZE
197   struct stat sb;
198 #endif /* BUFFY_SIZE */
199
200   while (MoreArgs (s)) {
201     mutt_extract_token (path, s, 0);
202     strfcpy (buf, path->data, sizeof (buf));
203
204     if (data == M_UNMAILBOXES && str_eq (buf, "*")) {
205       list_del (&Incoming, (list_del_t*) buffy_free);
206       return 0;
207     }
208
209     /* Skip empty tokens. */
210     if (!*buf)
211       continue;
212
213     mutt_expand_path (buf, sizeof (buf));
214     i = buffy_lookup (buf);
215
216     if (data == M_UNMAILBOXES) {
217       if (i >= 0) {
218         tmp = (BUFFY*) list_pop_idx (Incoming, i);
219         buffy_free (&tmp);
220       }
221       continue;
222     }
223
224     if (i < 0) {
225       tmp = p_new(BUFFY, 1);
226       tmp->path = str_dup (buf);
227       tmp->magic = 0;
228       list_push_back (&Incoming, tmp);
229       i = Incoming->length-1;
230     } else
231       tmp = (BUFFY*) Incoming->data[i];
232
233     tmp->new = 0;
234     tmp->notified = 1;
235     tmp->newly_created = 0;
236
237 #ifdef BUFFY_SIZE
238     /* for buffy_size, it is important that if the folder is new (tested by
239      * reading it), the size is set to 0 so that later when we check we see
240      * that it increased .  without buffy_size we probably don't care.
241      */
242     if (stat (tmp->path, &sb) == 0 && !test_new_folder (tmp->path)) {
243       /* some systems out there don't have an off_t type */
244       tmp->size = (long) sb.st_size;
245     }
246     else
247       tmp->size = 0;
248 #endif /* BUFFY_SIZE */
249   }
250   return 0;
251 }
252
253 #ifdef BUFFY_SIZE
254 /* people use buffy_size on systems where modified time attributes are BADLY
255  * broken. Ignore them.
256  */
257 #define STAT_CHECK (sb.st_size > tmp->size)
258 #else
259 #define STAT_CHECK (sb.st_mtime > sb.st_atime || (tmp->newly_created && sb.st_ctime == sb.st_mtime && sb.st_ctime == sb.st_atime))
260 #endif /* BUFFY_SIZE */
261
262 /* values for force:
263  * 0    don't force any checks + update sidebar
264  * 1    force all checks + update sidebar
265  * 2    don't force any checks + _don't_ update sidebar
266  */
267 int buffy_check (int force)
268 {
269   BUFFY *tmp;
270   struct stat sb;
271   struct dirent *de;
272   DIR *dirp;
273   char path[_POSIX_PATH_MAX];
274   struct stat contex_sb;
275   time_t now, last1;
276   CONTEXT *ctx;
277   int i = 0, local = 0, count = 0;
278 #ifdef USE_IMAP
279   time_t last2;
280
281   /* update postponed count as well, on force */
282   if (force == 1)
283     mutt_update_num_postponed ();
284 #endif
285
286   /* fastest return if there are no mailboxes */
287   if (list_empty(Incoming))
288     return 0;
289   now = time (NULL);
290   if (force == 0 && (now - BuffyTime < BuffyTimeout)
291 #ifdef USE_IMAP
292       && (now - ImapBuffyTime < ImapBuffyTimeout))
293 #else
294     )
295 #endif
296     return BuffyCount;
297
298   last1 = BuffyTime;
299   if (force == 1 || now - BuffyTime >= BuffyTimeout)
300     BuffyTime = now;
301 #ifdef USE_IMAP
302   last2 = ImapBuffyTime;
303   if (force == 1 || now - ImapBuffyTime >= ImapBuffyTimeout)
304     ImapBuffyTime = now;
305 #endif
306   BuffyCount = 0;
307   BuffyNotify = 0;
308
309   count = sidebar_need_count ();
310
311   if (!Context || !Context->path || 
312       (mx_is_local (Context->magic-1) && stat (Context->path, &contex_sb) != 0)) {
313     /* check device ID and serial number instead of comparing paths */
314     contex_sb.st_dev = 0;
315     contex_sb.st_ino = 0;
316   }
317
318   for (i = 0; i < Incoming->length; i++) {
319     tmp = (BUFFY*) Incoming->data[i];
320     tmp->magic = mx_get_magic (tmp->path);
321     local = mx_is_local (tmp->magic-1);
322     if ((tmp->magic <= 0 || local) && (stat (tmp->path, &sb) != 0 || sb.st_size == 0)) {
323       /* if the mailbox still doesn't exist, set the newly created flag to
324        * be ready for when it does. */
325       tmp->newly_created = 1;
326       tmp->magic = -1;
327 #ifdef BUFFY_SIZE
328       tmp->size = 0;
329 #endif
330       continue;
331     }
332
333     /* check to see if the folder is the currently selected folder
334      * before polling */
335     if (!Context || !Context->path || (local ? (sb.st_dev != contex_sb.st_dev ||
336                                                 sb.st_ino != contex_sb.st_ino) : 
337                                        !str_eq (tmp->path, Context->path))) {
338       switch (tmp->magic) {
339       case M_MBOX:
340       case M_MMDF:
341         /* only check on force or $mail_check reached */
342         if (force == 1 || (now - last1 >= BuffyTimeout)) {
343           if (!count) {
344             if (STAT_CHECK) {
345               BuffyCount++;
346               tmp->new = 1;
347             }
348 #ifdef BUFFY_SIZE
349             else {
350               /* some other program has deleted mail from the folder */
351               tmp->size = (long) sb.st_size;
352             }
353 #endif
354           }
355           else if (STAT_CHECK || tmp->msgcount == 0) {
356             /* sidebar visible */
357             BuffyCount++;
358             if ((ctx =
359                  mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT | M_COUNT,
360                                   NULL)) != NULL) {
361               tmp->msgcount = ctx->msgcount;
362               tmp->new = ctx->new;
363               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
364               tmp->msg_flagged = ctx->flagged;
365               mx_close_mailbox (ctx, 0);
366             }
367           }
368           if (tmp->newly_created &&
369               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
370             tmp->newly_created = 0;
371         }
372         else if (tmp->new > 0)
373           BuffyCount++;
374         break;
375
376       case M_MAILDIR:
377         /* only check on force or $mail_check reached */
378         if (force == 1 || (now - last1 >= BuffyTimeout)) {
379           snprintf (path, sizeof (path), "%s/new", tmp->path);
380           if ((dirp = opendir (path)) == NULL) {
381             tmp->magic = 0;
382             break;
383           }
384           tmp->new = 0;
385           tmp->msg_unread = 0;
386           tmp->msgcount = 0;
387           while ((de = readdir (dirp)) != NULL) {
388             char *p;
389
390             if (*de->d_name != '.' &&
391                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T'))) {
392               /* one new and undeleted message is enough */
393               if (tmp->new == 0) {
394                 BuffyCount++;
395                 if (!count) {
396                   /* if sidebar invisible -> done */
397                   tmp->new = 1;
398                   break;
399                 }
400               }
401               tmp->msgcount++;
402               tmp->msg_unread++;
403               tmp->new++;
404             }
405           }
406           closedir (dirp);
407
408           if (count) {
409             /* only count total mail if sidebar visible */
410             snprintf (path, sizeof (path), "%s/cur", tmp->path);
411             if ((dirp = opendir (path)) == NULL) {
412               tmp->magic = 0;
413               break;
414             }
415             tmp->msg_flagged = 0;
416             while ((de = readdir (dirp)) != NULL) {
417               char *p;
418
419               if (*de->d_name != '.'
420                   && (p = strstr (de->d_name, ":2,")) != NULL) {
421                 if (!strchr (p + 3, 'T'))
422                   tmp->msgcount++;
423                 if (strchr (p + 3, 'F'))
424                   tmp->msg_flagged++;
425               }
426             }
427             closedir (dirp);
428           }
429         }
430         else if (tmp->new > 0)
431           /* keep current stats if !force and !$mail_check reached */
432           BuffyCount++;
433         break;
434
435       case M_MH:
436         /* only check on force or $mail_check reached */
437         if (force == 1 || (now - last1 >= BuffyTimeout)) {
438           if ((tmp->new = mh_buffy (tmp->path)) > 0)
439             BuffyCount++;
440           if (count) {
441             DIR *dp;
442             struct dirent *de;
443
444             if ((dp = opendir (path)) == NULL)
445               break;
446             tmp->new = 0;
447             tmp->msgcount = 0;
448             tmp->msg_unread = 0;
449             while ((de = readdir (dp))) {
450               if (mh_valid_message (de->d_name)) {
451                 tmp->msgcount++;
452                 tmp->msg_unread++;
453                 tmp->new++;
454               }
455             }
456             closedir (dp);
457           }
458         }
459         else if (tmp->new > 0)
460           /* keep current stats if !force and !$mail_check reached */
461           BuffyCount++;
462         break;
463
464 #ifdef USE_IMAP
465       case M_IMAP:
466         /* only check on force or $imap_mail_check reached */
467         if (force == 1 || (now - last2 >= ImapBuffyTimeout)) {
468           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
469           tmp->new = imap_mailbox_check (tmp->path, 1);
470           tmp->msg_unread = imap_mailbox_check (tmp->path, 2);
471           if (tmp->new > 0)
472             BuffyCount++;
473           else
474             tmp->new = 0;
475           if (tmp->msg_unread < 0)
476             tmp->msg_unread = 0;
477         }
478         else if (tmp->new > 0)
479           /* keep current stats if !force and !$imap_mail_check reached */
480           BuffyCount++;
481         break;
482 #endif
483
484       }
485     }
486 #ifdef BUFFY_SIZE
487     else if (Context && Context->path)
488       tmp->size = (long) sb.st_size;    /* update the size */
489 #endif
490
491     if (tmp->new <= 0)
492       tmp->notified = 0;
493     else if (!tmp->notified)
494       BuffyNotify++;
495     tmp->has_new = tmp->new > 0;
496   }
497   if (BuffyCount > 0 && force != 2)
498     sidebar_draw (CurrentMenu);
499   return (BuffyCount);
500 }
501
502 int buffy_list (void)
503 {
504   BUFFY *tmp;
505   char path[_POSIX_PATH_MAX];
506   char buffylist[160];
507   int pos;
508   int first;
509   int have_unnotified = BuffyNotify;
510   int i = 0;
511
512   pos = 0;
513   first = 1;
514   buffylist[0] = 0;
515   pos += str_len (strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
516   if (Incoming) {
517     for (i = 0; i < Incoming->length; i++) {
518       tmp = (BUFFY*) Incoming->data[i];
519       /* Is there new mail in this mailbox? */
520       if (tmp->new <= 0 || (have_unnotified && tmp->notified))
521         continue;
522
523       strfcpy (path, tmp->path, sizeof (path));
524       mutt_pretty_mailbox (path);
525
526       if (!first && pos + str_len (path) >= COLS - 7)
527         break;
528
529       if (!first)
530         pos += str_len (strncat (buffylist + pos, ", ", sizeof (buffylist) - 1 - pos));    /* __STRNCAT_CHECKED__ */
531
532       /* Prepend an asterisk to mailboxes not already notified */
533       if (!tmp->notified) {
534         /* pos += str_len (strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
535         tmp->notified = 1;
536         BuffyNotify--;
537       }
538       pos += str_len (strncat (buffylist + pos, path, sizeof (buffylist) - 1 - pos));      /* __STRNCAT_CHECKED__ */
539       first = 0;
540     }
541   }
542   if (!first && i < Incoming->length) {
543     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos);   /* __STRNCAT_CHECKED__ */
544   }
545   if (!first) {
546     /* on new mail: redraw sidebar */
547     sidebar_draw (CurrentMenu);
548     mutt_message ("%s", buffylist);
549     return (1);
550   }
551   /* there were no mailboxes needing to be notified, so clean up since 
552    * BuffyNotify has somehow gotten out of sync
553    */
554   BuffyNotify = 0;
555   return (0);
556 }
557
558 int buffy_notify (void)
559 {
560   if (buffy_check (0) && BuffyNotify) {
561     return (buffy_list ());
562   }
563   return (0);
564 }
565
566 /* 
567  * mutt_buffy() -- incoming folders completion routine
568  *
569  * given a folder name, this routine gives the next incoming folder with new
570  * new mail.
571  */
572 void buffy_next (char *s, size_t slen)
573 {
574   int i = 0, c = 0, l = 0;
575
576   if (list_empty(Incoming))
577     return;
578
579   mutt_expand_path (s, _POSIX_PATH_MAX);
580   if (buffy_check (0) == 0) {
581     *s = '\0';
582     return;
583   }
584
585   /*
586    * If buffy_lookup returns the index,
587    * or -1 if not found (-1..Incoming->length-1);
588    * plus one --> (0..Incoming->length).
589    * Modulo mapps it into the correct range.
590    */
591   i = 1 + buffy_lookup (s);
592   for (l=0; l < Incoming->length; l++) {
593     c = (l+i) % Incoming->length;
594     if ((!Context || !Context->path || !str_eq (((BUFFY*) Incoming->data[c])->path, Context->path)) &&
595         ((BUFFY*) Incoming->data[c])->new > 0)
596       break;
597   }
598   if (l >= Incoming->length) {
599     *s = '\0';
600     /* something went wrong since we're here when buffy_check
601      * reported new mail */
602     buffy_check (0);
603   } else {
604     strfcpy (s, ((BUFFY*) Incoming->data[c])->path, slen);
605     mutt_pretty_mailbox (s);
606   }
607 }