Rocco Rutte:
[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 "mx.h"
20 #include "mh.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 * safe_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 (!safe_strncmp (buffer + i, "\n\nFrom ", safe_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 (!safe_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   struct stat sb;
139   struct stat tmp_sb;
140   int i = 0;
141
142   if (stat (path, &sb) != 0)
143     return NULL;
144
145   if (!list_empty(Incoming)) {
146     for (i = 0; i < Incoming->length; i++) {
147       if (stat (Incoming->data[i], &tmp_sb) == 0 &&
148           sb.st_dev == tmp_sb.st_dev && sb.st_ino == tmp_sb.st_ino)
149         return ((BUFFY*) Incoming->data[i]);
150     }
151   }
152   return (NULL);
153 }
154
155 void mutt_update_mailbox (BUFFY * b)
156 {
157   struct stat sb;
158
159   if (!b)
160     return;
161
162   if (stat (b->path, &sb) == 0)
163     b->size = (long) sb.st_size;
164   else
165     b->size = 0;
166   return;
167 }
168 #endif
169
170 /* func to free buffy for list_del() */
171 static void buffy_free (void** p) {
172   FREE(&(*((BUFFY**) p))->path);
173   FREE(p);
174 }
175
176 int buffy_lookup (const char* path) {
177   int i = 0;
178   if (list_empty(Incoming) || !path || !*path)
179     return (-1);
180   for (i = 0; i < Incoming->length; i++) {
181     if (safe_strcmp (((BUFFY*) Incoming->data[i])->path, path) == 0)
182       return (i);
183   }
184   return (-1);
185 }
186
187 int mutt_parse_mailboxes (BUFFER * path, BUFFER * s, unsigned long data,
188                           BUFFER * err)
189 {
190   BUFFY* tmp;
191   char buf[_POSIX_PATH_MAX];
192   int i = 0;
193 #ifdef BUFFY_SIZE
194   struct stat sb;
195 #endif /* BUFFY_SIZE */
196
197   while (MoreArgs (s)) {
198     mutt_extract_token (path, s, 0);
199     strfcpy (buf, path->data, sizeof (buf));
200
201     if (data == M_UNMAILBOXES && safe_strcmp (buf, "*") == 0) {
202       list_del (&Incoming, buffy_free);
203       return 0;
204     }
205
206     /* Skip empty tokens. */
207     if (!*buf)
208       continue;
209
210     mutt_expand_path (buf, sizeof (buf));
211     i = buffy_lookup (buf);
212
213     if (data == M_UNMAILBOXES) {
214       if (i >= 0) {
215         tmp = (BUFFY*) list_pop_idx (Incoming, i);
216         buffy_free (&tmp);
217       }
218       continue;
219     }
220
221     if (i < 0) {
222       tmp = safe_calloc (1, sizeof (BUFFY));
223       tmp->path = safe_strdup (buf);
224       tmp->magic = 0;
225       list_push_back (&Incoming, tmp);
226       i = Incoming->length-1;
227     } else
228       tmp = (BUFFY*) Incoming->data[i];
229
230     tmp->new = 0;
231     tmp->notified = 1;
232     tmp->newly_created = 0;
233
234 #ifdef BUFFY_SIZE
235     /* for buffy_size, it is important that if the folder is new (tested by
236      * reading it), the size is set to 0 so that later when we check we see
237      * that it increased .  without buffy_size we probably don't care.
238      */
239     if (stat (tmp->path, &sb) == 0 && !test_new_folder (tmp->path)) {
240       /* some systems out there don't have an off_t type */
241       tmp->size = (long) sb.st_size;
242     }
243     else
244       tmp->size = 0;
245 #endif /* BUFFY_SIZE */
246   }
247   return 0;
248 }
249
250 #ifdef BUFFY_SIZE
251 /* people use buffy_size on systems where modified time attributes are BADLY
252  * broken. Ignore them.
253  */
254 #define STAT_CHECK (sb.st_size > tmp->size)
255 #else
256 #define STAT_CHECK (sb.st_mtime > sb.st_atime || (tmp->newly_created && sb.st_ctime == sb.st_mtime && sb.st_ctime == sb.st_atime))
257 #endif /* BUFFY_SIZE */
258
259 /* values for force:
260  * 0    don't force any checks + update sidebar
261  * 1    force all checks + update sidebar
262  * 2    force all checks + _don't_ update sidebar
263  */
264 int mutt_buffy_check (int force)
265 {
266   BUFFY *tmp;
267   struct stat sb;
268   struct dirent *de;
269   DIR *dirp;
270   char path[_POSIX_PATH_MAX];
271   struct stat contex_sb;
272   time_t now, last1;
273   CONTEXT *ctx;
274   int i = 0;
275 #ifdef USE_IMAP
276   time_t last2;
277
278   /* update postponed count as well, on force */
279   if (force != 0)
280     mutt_update_num_postponed ();
281 #endif
282
283   /* fastest return if there are no mailboxes */
284   if (list_empty(Incoming))
285     return 0;
286   now = time (NULL);
287   if (force == 0 && (now - BuffyTime < BuffyTimeout)
288 #ifdef USE_IMAP
289       && (now - ImapBuffyTime < ImapBuffyTimeout))
290 #else
291     )
292 #endif
293     return BuffyCount;
294
295   last1 = BuffyTime;
296   if (force != 0 || now - BuffyTime >= BuffyTimeout)
297     BuffyTime = now;
298 #ifdef USE_IMAP
299   last2 = ImapBuffyTime;
300   if (force != 0 || now - ImapBuffyTime >= ImapBuffyTimeout)
301     ImapBuffyTime = now;
302 #endif
303   BuffyCount = 0;
304   BuffyNotify = 0;
305
306 #ifdef USE_IMAP
307   if (!Context || Context->magic != M_IMAP)
308 #endif
309 #ifdef USE_POP
310     if (!Context || Context->magic != M_POP)
311 #endif
312 #ifdef USE_NNTP
313       if (!Context || Context->magic != M_NNTP)
314 #endif
315         /* check device ID and serial number instead of comparing paths */
316         if (!Context || !Context->path
317             || stat (Context->path, &contex_sb) != 0) {
318           contex_sb.st_dev = 0;
319           contex_sb.st_ino = 0;
320         }
321
322   for (i = 0; i < Incoming->length; i++) {
323     tmp = (BUFFY*) Incoming->data[i];
324 #ifdef USE_IMAP
325     if (mx_is_imap (tmp->path))
326       tmp->magic = M_IMAP;
327     else
328 #endif
329 #ifdef USE_POP
330     if (mx_is_pop (tmp->path))
331       tmp->magic = M_POP;
332     else
333 #endif
334 #ifdef USE_NNTP
335     if ((tmp->magic == M_NNTP) || mx_is_nntp (tmp->path))
336       tmp->magic = M_NNTP;
337     else
338 #endif
339     if (stat (tmp->path, &sb) != 0 || sb.st_size == 0 ||
340           (!tmp->magic && (tmp->magic = mx_get_magic (tmp->path)) <= 0)) {
341       /* if the mailbox still doesn't exist, set the newly created flag to
342        * be ready for when it does. */
343       tmp->newly_created = 1;
344       tmp->magic = 0;
345 #ifdef BUFFY_SIZE
346       tmp->size = 0;
347 #endif
348       continue;
349     }
350
351     /* check to see if the folder is the currently selected folder
352      * before polling */
353     if (!Context || !Context->path || ((0
354 #ifdef USE_IMAP
355                                         || tmp->magic == M_IMAP
356 #endif
357 #ifdef USE_POP
358                                         || tmp->magic == M_POP
359 #endif
360 #ifdef USE_NNTP
361                                         || tmp->magic == M_NNTP
362 #endif
363                                        )? safe_strcmp (tmp->path,
364                                                        Context->path) : (sb.
365                                                                          st_dev
366                                                                          !=
367                                                                          contex_sb.
368                                                                          st_dev
369                                                                          ||
370                                                                          sb.
371                                                                          st_ino
372                                                                          !=
373                                                                          contex_sb.
374                                                                          st_ino)
375         )
376       ) {
377       switch (tmp->magic) {
378       case M_MBOX:
379       case M_MMDF:
380         /* only check on force or $mail_check reached */
381         if (force != 0 || (now - last1 >= BuffyTimeout)) {
382           if (SidebarWidth == 0 || !option (OPTMBOXPANE)) {
383             if (STAT_CHECK) {
384               BuffyCount++;
385               tmp->new = 1;
386             }
387 #ifdef BUFFY_SIZE
388             else {
389               /* some other program has deleted mail from the folder */
390               tmp->size = (long) sb.st_size;
391             }
392 #endif
393           }
394           else if (SidebarWidth > 0 && option (OPTMBOXPANE) &&
395                    (STAT_CHECK || tmp->msgcount == 0)) {
396             /* sidebar visible */
397             BuffyCount++;
398             if ((ctx =
399                  mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT,
400                                   NULL)) != NULL) {
401               tmp->msgcount = ctx->msgcount;
402               tmp->new = ctx->new;
403               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
404               tmp->msg_flagged = ctx->flagged;
405               mx_close_mailbox (ctx, 0);
406             }
407           }
408           if (tmp->newly_created &&
409               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
410             tmp->newly_created = 0;
411         }
412         else if (tmp->new > 0)
413           BuffyCount++;
414         break;
415
416       case M_MAILDIR:
417         /* only check on force or $mail_check reached */
418         if (force != 0 || (now - last1 >= BuffyTimeout)) {
419           snprintf (path, sizeof (path), "%s/new", tmp->path);
420           if ((dirp = opendir (path)) == NULL) {
421             tmp->magic = 0;
422             break;
423           }
424           tmp->new = 0;
425           tmp->msg_unread = 0;
426           tmp->msgcount = 0;
427           while ((de = readdir (dirp)) != NULL) {
428             char *p;
429
430             if (*de->d_name != '.' &&
431                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T'))) {
432               /* one new and undeleted message is enough */
433               if (tmp->new == 0) {
434                 BuffyCount++;
435                 tmp->new = 1;
436                 if (SidebarWidth == 0 || !option (OPTMBOXPANE))
437                   /* if sidebar invisible -> done */
438                   break;
439               }
440               tmp->msgcount++;
441               tmp->msg_unread++;
442               tmp->new++;
443             }
444           }
445           closedir (dirp);
446
447           if (SidebarWidth > 0 && option (OPTMBOXPANE)) {
448             /* only count total mail if sidebar visible */
449             snprintf (path, sizeof (path), "%s/cur", tmp->path);
450             if ((dirp = opendir (path)) == NULL) {
451               tmp->magic = 0;
452               break;
453             }
454             tmp->msg_flagged = 0;
455             while ((de = readdir (dirp)) != NULL) {
456               char *p;
457
458               if (*de->d_name != '.'
459                   && (p = strstr (de->d_name, ":2,")) != NULL) {
460                 if (!strchr (p + 3, 'T'))
461                   tmp->msgcount++;
462                 if (strchr (p + 3, 'F'))
463                   tmp->msg_flagged++;
464               }
465             }
466             closedir (dirp);
467           }
468         }
469         else if (tmp->new > 0)
470           /* keep current stats if !force and !$mail_check reached */
471           BuffyCount++;
472         break;
473
474       case M_MH:
475         /* only check on force or $mail_check reached */
476         if (force != 0 || (now - last1 >= BuffyTimeout)) {
477           if ((tmp->new = mh_buffy (tmp->path)) > 0)
478             BuffyCount++;
479           if (SidebarWidth > 0 && option (OPTMBOXPANE)) {
480             DIR *dp;
481             struct dirent *de;
482
483             if ((dp = opendir (path)) == NULL)
484               break;
485             tmp->new = 0;
486             tmp->msgcount = 0;
487             tmp->msg_unread = 0;
488             while ((de = readdir (dp))) {
489               if (mh_valid_message (de->d_name)) {
490                 tmp->msgcount++;
491                 tmp->msg_unread++;
492                 tmp->new++;
493               }
494             }
495             closedir (dp);
496           }
497         }
498         else if (tmp->new > 0)
499           /* keep current stats if !force and !$mail_check reached */
500           BuffyCount++;
501         break;
502
503 #ifdef USE_IMAP
504       case M_IMAP:
505         /* only check on force or $imap_mail_check reached */
506         if (force != 0 || (now - last2 >= ImapBuffyTimeout)) {
507           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
508           if ((tmp->new = imap_mailbox_check (tmp->path, 1)) > 0) {
509             BuffyCount++;
510             tmp->msg_unread = tmp->new; /* for sidebar; wtf? */
511           }
512           else {
513             tmp->new = 0;
514             tmp->msg_unread = 0;
515           }
516         }
517         else if (tmp->new > 0)
518           /* keep current stats if !force and !$imap_mail_check reached */
519           BuffyCount++;
520         break;
521 #endif
522
523 #ifdef USE_POP
524       case M_POP:
525         break;
526 #endif
527
528 #ifdef USE_NNTP
529       case M_NNTP:
530         break;
531 #endif
532       }
533     }
534 #ifdef BUFFY_SIZE
535     else if (Context && Context->path)
536       tmp->size = (long) sb.st_size;    /* update the size */
537 #endif
538
539     if (tmp->new <= 0)
540       tmp->notified = 0;
541     else if (!tmp->notified)
542       BuffyNotify++;
543     tmp->has_new = tmp->new > 0;
544   }
545   if (BuffyCount > 0 && force != 2)
546     sidebar_draw (CurrentMenu);
547   return (BuffyCount);
548 }
549
550 int mutt_buffy_list (void)
551 {
552   BUFFY *tmp;
553   char path[_POSIX_PATH_MAX];
554   char buffylist[160];
555   int pos;
556   int first;
557   int have_unnotified = BuffyNotify;
558   int i = 0;
559
560   if (option (OPTFORCEBUFFYCHECK))
561     mutt_buffy_check (1);
562
563   pos = 0;
564   first = 1;
565   buffylist[0] = 0;
566   pos += safe_strlen (strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
567   if (Incoming) {
568     for (i = 0; i < Incoming->length; i++) {
569       tmp = (BUFFY*) Incoming->data[i];
570       /* Is there new mail in this mailbox? */
571       if (tmp->new <= 0 || (have_unnotified && tmp->notified))
572         continue;
573
574       strfcpy (path, tmp->path, sizeof (path));
575       mutt_pretty_mailbox (path);
576
577       if (!first && pos + safe_strlen (path) >= COLS - 7)
578         break;
579
580       if (!first)
581         pos += safe_strlen (strncat (buffylist + pos, ", ", sizeof (buffylist) - 1 - pos));    /* __STRNCAT_CHECKED__ */
582
583       /* Prepend an asterisk to mailboxes not already notified */
584       if (!tmp->notified) {
585         /* pos += safe_strlen (strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
586         tmp->notified = 1;
587         BuffyNotify--;
588       }
589       pos += safe_strlen (strncat (buffylist + pos, path, sizeof (buffylist) - 1 - pos));      /* __STRNCAT_CHECKED__ */
590       first = 0;
591     }
592   }
593   if (!first && i < Incoming->length) {
594     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos);   /* __STRNCAT_CHECKED__ */
595   }
596   if (!first) {
597     /* on new mail: redraw sidebar */
598     sidebar_draw (CurrentMenu);
599     mutt_message ("%s", buffylist);
600     return (1);
601   }
602   /* there were no mailboxes needing to be notified, so clean up since 
603    * BuffyNotify has somehow gotten out of sync
604    */
605   BuffyNotify = 0;
606   return (0);
607 }
608
609 int mutt_buffy_notify (void)
610 {
611   if (mutt_buffy_check (0) && BuffyNotify) {
612     return (mutt_buffy_list ());
613   }
614   return (0);
615 }
616
617 /* 
618  * mutt_buffy() -- incoming folders completion routine
619  *
620  * given a folder name, this routine gives the next incoming folder with new
621  * new mail.
622  */
623 void mutt_buffy (char *s, size_t slen)
624 {
625   int i = 0, c = 0;
626
627   if (list_empty(Incoming))
628     return;
629
630   mutt_expand_path (s, _POSIX_PATH_MAX);
631   if (mutt_buffy_check (0) == 0) {
632     *s = '\0';
633     return;
634   }
635
636   i = buffy_lookup (s);
637   c = i == Incoming->length-1 ? 0 : i+1;
638   while (((BUFFY*) Incoming->data[c])->new <= 0) {
639     c = (c+1) % Incoming->length;
640     if (c == i)
641       break;    /* tried all once */
642   }
643   if (c == i) {
644     *s = '\0';
645     /* something went wrong since we're here when mutt_buffy_check
646      * reported new mail */
647     mutt_buffy_check (0);
648   } else {
649     strfcpy (s, ((BUFFY*) Incoming->data[c])->path, slen);
650     mutt_pretty_mailbox (s);
651   }
652 }