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