c1117d12ebde098b5df1c64a5c3d9d65cd5b44b9
[monky] / src / mail.c
1 /* Conky, a system monitor, based on torsmo
2  *
3  * Any original torsmo code is licensed under the BSD license
4  *
5  * All code written since the fork of torsmo is licensed under the GPL
6  *
7  * Please see COPYING for details
8  *
9  * Copyright (c) 2004, Hannu Saransaari and Lauri Hakkarainen
10  * Copyright (c) 2005-2009 Brenden Matthews, Philip Kovacs, et. al.
11  *      (see AUTHORS)
12  * All rights reserved.
13  *
14  * This program is free software: you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation, either version 3 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  * You should have received a copy of the GNU General Public License
24  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
25  *
26  */
27
28 #include "config.h"
29 #include "conky.h"
30 #include "common.h"
31 #include "logging.h"
32 #include "mail.h"
33
34 #include <errno.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <limits.h>
39 #include <netinet/in.h>
40 #include <netdb.h>
41 #include <sys/socket.h>
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 #include <sys/param.h>
45
46 #include <dirent.h>
47 #include <errno.h>
48 #include <termios.h>
49
50 /* MAX() is defined by a header included from conky.h
51  * maybe once this is not true anymore, so have an alternative
52  * waiting to drop in.
53  *
54  * #define MAX(a, b)  ((a > b) ? a : b)
55  */
56
57 char *current_mail_spool;
58
59 void update_mail_count(struct local_mail_s *mail)
60 {
61         struct stat st;
62
63         if (mail == NULL) {
64                 return;
65         }
66
67         /* TODO: use that fine file modification notify on Linux 2.4 */
68
69         /* don't check mail so often (9.5s is minimum interval) */
70         if (current_update_time - mail->last_update < 9.5) {
71                 return;
72         } else {
73                 mail->last_update = current_update_time;
74         }
75
76         if (stat(mail->box, &st)) {
77                 static int rep;
78
79                 if (!rep) {
80                         ERR("can't stat %s: %s", mail->box, strerror(errno));
81                         rep = 1;
82                 }
83                 return;
84         }
85 #if HAVE_DIRENT_H
86         /* maildir format */
87         if (S_ISDIR(st.st_mode)) {
88                 DIR *dir;
89                 char *dirname;
90                 struct dirent *dirent;
91                 char *mailflags;
92
93                 mail->mail_count = mail->new_mail_count = 0;
94                 mail->seen_mail_count = mail->unseen_mail_count = 0;
95                 mail->flagged_mail_count = mail->unflagged_mail_count = 0;
96                 mail->forwarded_mail_count = mail->unforwarded_mail_count = 0;
97                 mail->replied_mail_count = mail->unreplied_mail_count = 0;
98                 mail->draft_mail_count = mail->trashed_mail_count = 0;
99                 dirname = (char *) malloc(sizeof(char) * (strlen(mail->box) + 5));
100                 if (!dirname) {
101                         ERR("malloc");
102                         return;
103                 }
104                 strcpy(dirname, mail->box);
105                 strcat(dirname, "/");
106                 /* checking the cur subdirectory */
107                 strcat(dirname, "cur");
108
109                 dir = opendir(dirname);
110                 if (!dir) {
111                         ERR("cannot open directory");
112                         free(dirname);
113                         return;
114                 }
115                 dirent = readdir(dir);
116                 while (dirent) {
117                         /* . and .. are skipped */
118                         if (dirent->d_name[0] != '.') {
119                                 mail->mail_count++;
120                                 mailflags = (char *) malloc(sizeof(char) * strlen(strrchr(dirent->d_name, ',')));
121                                 if (!mailflags) {
122                                         ERR("malloc");
123                                         free(dirname);
124                                         return;
125                                 }
126                                 strcpy(mailflags, strrchr(dirent->d_name, ','));
127                                 if (!strchr(mailflags, 'T')) { /* The message is not in the trash */
128                                         if (strchr(mailflags, 'S')) { /*The message has been seen */
129                                                 mail->seen_mail_count++;
130                                         } else {
131                                                 mail->unseen_mail_count++;
132                                         }
133                                         if (strchr(mailflags, 'F')) { /*The message was flagged */
134                                                 mail->flagged_mail_count++;
135                                         } else {
136                                                 mail->unflagged_mail_count++;
137                                         }
138                                         if (strchr(mailflags, 'P')) { /*The message was forwarded */
139                                                 mail->forwarded_mail_count++;
140                                         } else {
141                                                 mail->unforwarded_mail_count++;
142                                         }
143                                         if (strchr(mailflags, 'R')) { /*The message was replied */
144                                                 mail->replied_mail_count++;
145                                         } else {
146                                                 mail->unreplied_mail_count++;
147                                         }
148                                         if (strchr(mailflags, 'D')) { /*The message is a draft */
149                                                 mail->draft_mail_count++;
150                                         }
151                                 } else {
152                                         mail->trashed_mail_count++;
153                                 }
154                                 free(mailflags);
155                         }
156                         dirent = readdir(dir);
157                 }
158                 closedir(dir);
159
160                 dirname[strlen(dirname) - 3] = '\0';
161                 strcat(dirname, "new");
162
163                 dir = opendir(dirname);
164                 if (!dir) {
165                         ERR("cannot open directory");
166                         free(dirname);
167                         return;
168                 }
169                 dirent = readdir(dir);
170                 while (dirent) {
171                         /* . and .. are skipped */
172                         if (dirent->d_name[0] != '.') {
173                                 mail->new_mail_count++;
174                                 mail->mail_count++;
175                                 mail->unseen_mail_count++;  /* new messages cannot have been seen */
176                         }
177                         dirent = readdir(dir);
178                 }
179                 closedir(dir);
180
181                 free(dirname);
182                 return;
183         }
184 #endif
185         /* mbox format */
186         if (st.st_mtime != mail->last_mtime) {
187                 /* yippee, modification time has changed, let's read mail count! */
188                 static int rep;
189                 FILE *fp;
190                 int reading_status = 0;
191
192                 /* could lock here but I don't think it's really worth it because
193                  * this isn't going to write mail spool */
194
195                 mail->new_mail_count = mail->mail_count = 0;
196
197                 /* these flags are not supported for mbox */
198                 mail->seen_mail_count = mail->unseen_mail_count = -1;
199                 mail->flagged_mail_count = mail->unflagged_mail_count = -1;
200                 mail->forwarded_mail_count = mail->unforwarded_mail_count = -1;
201                 mail->replied_mail_count = mail->unreplied_mail_count = -1;
202                 mail->draft_mail_count = mail->trashed_mail_count = -1;
203
204                 fp = open_file(mail->box, &rep);
205                 if (!fp) {
206                         return;
207                 }
208
209                 /* NOTE: adds mail as new if there isn't Status-field at all */
210
211                 while (!feof(fp)) {
212                         char buf[128];
213
214                         if (fgets(buf, 128, fp) == NULL) {
215                                 break;
216                         }
217
218                         if (strncmp(buf, "From ", 5) == 0) {
219                                 /* ignore MAILER-DAEMON */
220                                 if (strncmp(buf + 5, "MAILER-DAEMON ", 14) != 0) {
221                                         mail->mail_count++;
222
223                                         if (reading_status) {
224                                                 mail->new_mail_count++;
225                                         } else {
226                                                 reading_status = 1;
227                                         }
228                                 }
229                         } else {
230                                 if (reading_status
231                                                 && strncmp(buf, "X-Mozilla-Status:", 17) == 0) {
232                                         /* check that mail isn't already read */
233                                         if (strchr(buf + 21, '0')) {
234                                                 mail->new_mail_count++;
235                                         }
236
237                                         reading_status = 0;
238                                         continue;
239                                 }
240                                 if (reading_status && strncmp(buf, "Status:", 7) == 0) {
241                                         /* check that mail isn't already read */
242                                         if (strchr(buf + 7, 'R') == NULL) {
243                                                 mail->new_mail_count++;
244                                         }
245
246                                         reading_status = 0;
247                                         continue;
248                                 }
249                         }
250
251                         /* skip until \n */
252                         while (strchr(buf, '\n') == NULL && !feof(fp)) {
253                                 fgets(buf, 128, fp);
254                         }
255                 }
256
257                 fclose(fp);
258
259                 if (reading_status) {
260                         mail->new_mail_count++;
261                 }
262
263                 mail->last_mtime = st.st_mtime;
264         }
265 }
266
267 #define MAXDATASIZE 1000
268
269 struct mail_s *parse_mail_args(char type, const char *arg)
270 {
271         struct mail_s *mail;
272         char *tmp;
273
274         mail = malloc(sizeof(struct mail_s));
275         memset(mail, 0, sizeof(struct mail_s));
276
277         if (sscanf(arg, "%128s %128s %128s", mail->host, mail->user, mail->pass)
278                         != 3) {
279                 if (type == POP3_TYPE) {
280                         ERR("Scanning POP3 args failed");
281                 } else if (type == IMAP_TYPE) {
282                         ERR("Scanning IMAP args failed");
283                 }
284                 return 0;
285         }
286         // see if password needs prompting
287         if (mail->pass[0] == '*' && mail->pass[1] == '\0') {
288                 int fp = fileno(stdin);
289                 struct termios term;
290
291                 tcgetattr(fp, &term);
292                 term.c_lflag &= ~ECHO;
293                 tcsetattr(fp, TCSANOW, &term);
294                 printf("Enter mailbox password (%s@%s): ", mail->user, mail->host);
295                 scanf("%128s", mail->pass);
296                 printf("\n");
297                 term.c_lflag |= ECHO;
298                 tcsetattr(fp, TCSANOW, &term);
299         }
300         // now we check for optional args
301         tmp = strstr(arg, "-r ");
302         if (tmp) {
303                 tmp += 3;
304                 sscanf(tmp, "%u", &mail->retries);
305         } else {
306                 mail->retries = 5;      // 5 retries after failure
307         }
308         tmp = strstr(arg, "-i ");
309         if (tmp) {
310                 tmp += 3;
311                 sscanf(tmp, "%f", &mail->interval);
312         } else {
313                 mail->interval = 300;   // 5 minutes
314         }
315         tmp = strstr(arg, "-p ");
316         if (tmp) {
317                 tmp += 3;
318                 sscanf(tmp, "%lu", &mail->port);
319         } else {
320                 if (type == POP3_TYPE) {
321                         mail->port = 110;       // default pop3 port
322                 } else if (type == IMAP_TYPE) {
323                         mail->port = 143;       // default imap port
324                 }
325         }
326         if (type == IMAP_TYPE) {
327                 tmp = strstr(arg, "-f ");
328                 if (tmp) {
329                         tmp += 3;
330                         sscanf(tmp, "%s", mail->folder);
331                 } else {
332                         strncpy(mail->folder, "INBOX", 128);    // default imap inbox
333                 }
334         }
335         tmp = strstr(arg, "-e ");
336         if (tmp) {
337                 int len = 1024;
338                 tmp += 3;
339
340                 if (tmp[0] == '\'') {
341                         len = strstr(tmp + 1, "'") - tmp - 1;
342                         if (len > 1024) {
343                                 len = 1024;
344                         }
345                 }
346                 strncpy(mail->command, tmp + 1, len);
347         } else {
348                 mail->command[0] = '\0';
349         }
350         mail->p_timed_thread = NULL;
351         return mail;
352 }
353
354 int imap_command(int sockfd, const char *command, char *response, const char *verify)
355 {
356         struct timeval timeout;
357         fd_set fdset;
358         int res, numbytes = 0;
359         if (send(sockfd, command, strlen(command), 0) == -1) {
360                 perror("send");
361                 return -1;
362         }
363         timeout.tv_sec = 60;    // 60 second timeout i guess
364         timeout.tv_usec = 0;
365         FD_ZERO(&fdset);
366         FD_SET(sockfd, &fdset);
367         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
368         if (res > 0) {
369                 if ((numbytes = recv(sockfd, response, MAXDATASIZE - 1, 0)) == -1) {
370                         perror("recv");
371                         return -1;
372                 }
373         }
374         DBGP2("imap_command()  command: %s", command);
375         DBGP2("imap_command() received: %s", response);
376         response[numbytes] = '\0';
377         if (strstr(response, verify) == NULL) {
378                 return -1;
379         }
380         return 0;
381 }
382
383 int imap_check_status(char *recvbuf, struct mail_s *mail)
384 {
385         char *reply;
386         reply = strstr(recvbuf, " (MESSAGES ");
387         if (!reply || strlen(reply) < 2) {
388                 return -1;
389         }
390         reply += 2;
391         *strchr(reply, ')') = '\0';
392         if (reply == NULL) {
393                 ERR("Error parsing IMAP response: %s", recvbuf);
394                 return -1;
395         } else {
396                 timed_thread_lock(mail->p_timed_thread);
397                 sscanf(reply, "MESSAGES %lu UNSEEN %lu", &mail->messages,
398                                 &mail->unseen);
399                 timed_thread_unlock(mail->p_timed_thread);
400         }
401         return 0;
402 }
403
404 void imap_unseen_command(struct mail_s *mail, unsigned long old_unseen, unsigned long old_messages)
405 {
406         if (strlen(mail->command) > 1 && (mail->unseen > old_unseen
407                                 || (mail->messages > old_messages && mail->unseen > 0))) {
408                 // new mail goodie
409                 if (system(mail->command) == -1) {
410                         perror("system()");
411                 }
412         }
413 }
414
415 void *imap_thread(void *arg)
416 {
417         int sockfd, numbytes;
418         char recvbuf[MAXDATASIZE];
419         char sendbuf[MAXDATASIZE];
420         unsigned int fail = 0;
421         unsigned long old_unseen = ULONG_MAX;
422         unsigned long old_messages = ULONG_MAX;
423         struct stat stat_buf;
424         struct hostent he, *he_res = 0;
425         int he_errno;
426         char hostbuff[2048];
427         struct sockaddr_in their_addr;  // connector's address information
428         struct mail_s *mail = (struct mail_s *)arg;
429         int has_idle = 0;
430         int threadfd = timed_thread_readfd(mail->p_timed_thread);
431
432 #ifdef HAVE_GETHOSTBYNAME_R
433         if (gethostbyname_r(mail->host, &he, hostbuff, sizeof(hostbuff), &he_res, &he_errno)) { // get the host info
434                 ERR("IMAP gethostbyname_r: %s", hstrerror(h_errno));
435                 exit(1);
436         }
437 #else /* HAVE_GETHOSTBYNAME_R */
438         if ((he_res = gethostbyname(mail->host)) == NULL) {     // get the host info
439                 herror("gethostbyname");
440                 exit(1);
441         }
442 #endif /* HAVE_GETHOSTBYNAME_R */
443         while (fail < mail->retries) {
444                 struct timeval timeout;
445                 int res;
446                 fd_set fdset;
447
448                 if (fail > 0) {
449                         ERR("Trying IMAP connection again for %s@%s (try %u/%u)",
450                                         mail->user, mail->host, fail + 1, mail->retries);
451                 }
452                 do {
453                         if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
454                                 perror("socket");
455                                 fail++;
456                                 break;
457                         }
458
459                         // host byte order
460                         their_addr.sin_family = AF_INET;
461                         // short, network byte order
462                         their_addr.sin_port = htons(mail->port);
463                         their_addr.sin_addr = *((struct in_addr *) he_res->h_addr);
464                         // zero the rest of the struct
465                         memset(&(their_addr.sin_zero), '\0', 8);
466
467                         if (connect(sockfd, (struct sockaddr *) &their_addr,
468                                                 sizeof(struct sockaddr)) == -1) {
469                                 perror("connect");
470                                 fail++;
471                                 break;
472                         }
473
474                         timeout.tv_sec = 60;    // 60 second timeout i guess
475                         timeout.tv_usec = 0;
476                         FD_ZERO(&fdset);
477                         FD_SET(sockfd, &fdset);
478                         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
479                         if (res > 0) {
480                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
481                                         perror("recv");
482                                         fail++;
483                                         break;
484                                 }
485                         } else {
486                                 ERR("IMAP connection failed: timeout");
487                                 fail++;
488                                 break;
489                         }
490                         recvbuf[numbytes] = '\0';
491                         DBGP2("imap_thread() received: %s", recvbuf);
492                         if (strstr(recvbuf, "* OK") != recvbuf) {
493                                 ERR("IMAP connection failed, probably not an IMAP server");
494                                 fail++;
495                                 break;
496                         }
497                         strncpy(sendbuf, "a1 login ", MAXDATASIZE);
498                         strncat(sendbuf, mail->user, MAXDATASIZE - strlen(sendbuf) - 1);
499                         strncat(sendbuf, " ", MAXDATASIZE - strlen(sendbuf) - 1);
500                         strncat(sendbuf, mail->pass, MAXDATASIZE - strlen(sendbuf) - 1);
501                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
502                         if (imap_command(sockfd, sendbuf, recvbuf, "a1 OK")) {
503                                 fail++;
504                                 break;
505                         }
506                         if (strstr(recvbuf, " IDLE ") != NULL) {
507                                 has_idle = 1;
508                         }
509
510                         strncpy(sendbuf, "a2 STATUS ", MAXDATASIZE);
511                         strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
512                         strncat(sendbuf, " (MESSAGES UNSEEN)\r\n",
513                                         MAXDATASIZE - strlen(sendbuf) - 1);
514                         if (imap_command(sockfd, sendbuf, recvbuf, "a2 OK")) {
515                                 fail++;
516                                 break;
517                         }
518
519                         if (imap_check_status(recvbuf, mail)) {
520                                 fail++;
521                                 break;
522                         }
523                         imap_unseen_command(mail, old_unseen, old_messages);
524                         fail = 0;
525                         old_unseen = mail->unseen;
526                         old_messages = mail->messages;
527
528                         if (has_idle) {
529                                 strncpy(sendbuf, "a4 SELECT ", MAXDATASIZE);
530                                 strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
531                                 strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
532                                 if (imap_command(sockfd, sendbuf, recvbuf, "a4 OK")) {
533                                         fail++;
534                                         break;
535                                 }
536
537                                 strncpy(sendbuf, "a5 IDLE\r\n", MAXDATASIZE);
538                                 if (imap_command(sockfd, sendbuf, recvbuf, "+ idling")) {
539                                         fail++;
540                                         break;
541                                 }
542                                 recvbuf[0] = '\0';
543
544                                 while (1) {
545                                         /*
546                                          * RFC 2177 says we have to re-idle every 29 minutes.
547                                          * We'll do it every 20 minutes to be safe.
548                                          */
549                                         timeout.tv_sec = 1200;
550                                         timeout.tv_usec = 0;
551                                         DBGP2("idling...");
552                                         FD_ZERO(&fdset);
553                                         FD_SET(sockfd, &fdset);
554                                         FD_SET(threadfd, &fdset);
555                                         res = select(MAX(sockfd + 1, threadfd + 1), &fdset, NULL, NULL, NULL);
556                                         if (timed_thread_test(mail->p_timed_thread, 1) || (res == -1 && errno == EINTR) || FD_ISSET(threadfd, &fdset)) {
557                                                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
558                                                         /* if a valid socket, close it */
559                                                         close(sockfd);
560                                                 }
561                                                 timed_thread_exit(mail->p_timed_thread);
562                                         } else if (res > 0) {
563                                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
564                                                         perror("recv idling");
565                                                         fail++;
566                                                         break;
567                                                 }
568                                         } else {
569                                                 fail++;
570                                                 break;
571                                         }
572                                         recvbuf[numbytes] = '\0';
573                                         DBGP2("imap_thread() received: %s", recvbuf);
574                                         if (strlen(recvbuf) > 2) {
575                                                 unsigned long messages, recent;
576                                                 char *buf = recvbuf;
577                                                 char force_check = 0;
578                                                 buf = strstr(buf, "EXISTS");
579                                                 while (buf && strlen(buf) > 1 && strstr(buf + 1, "EXISTS")) {
580                                                         buf = strstr(buf + 1, "EXISTS");
581                                                 }
582                                                 if (buf) {
583                                                         // back up until we reach '*'
584                                                         while (buf >= recvbuf && buf[0] != '*') {
585                                                                 buf--;
586                                                         }
587                                                         if (sscanf(buf, "* %lu EXISTS\r\n", &messages) == 1) {
588                                                                 timed_thread_lock(mail->p_timed_thread);
589                                                                 if (mail->messages != messages) {
590                                                                         force_check = 1;
591                                                                         mail->messages = messages;
592                                                                 }
593                                                                 timed_thread_unlock(mail->p_timed_thread);
594                                                         }
595                                                 }
596                                                 buf = recvbuf;
597                                                 buf = strstr(buf, "RECENT");
598                                                 while (buf && strlen(buf) > 1 && strstr(buf + 1, "RECENT")) {
599                                                         buf = strstr(buf + 1, "RECENT");
600                                                 }
601                                                 if (buf) {
602                                                         // back up until we reach '*'
603                                                         while (buf >= recvbuf && buf[0] != '*') {
604                                                                 buf--;
605                                                         }
606                                                         if (sscanf(buf, "* %lu RECENT\r\n", &recent) != 1) {
607                                                                 recent = 0;
608                                                         }
609                                                 }
610                                                 /*
611                                                  * check if we got a FETCH from server, recent was
612                                                  * something other than 0, or we had a timeout
613                                                  */
614                                                 buf = recvbuf;
615                                                 if (recent > 0 || (buf && strstr(buf, " FETCH ")) || timeout.tv_sec == 0 || force_check) {
616                                                         // re-check messages and unseen
617                                                         if (imap_command(sockfd, "DONE\r\n", recvbuf, "a5 OK")) {
618                                                                 fail++;
619                                                                 break;
620                                                         }
621                                                         strncpy(sendbuf, "a2 STATUS ", MAXDATASIZE);
622                                                         strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
623                                                         strncat(sendbuf, " (MESSAGES UNSEEN)\r\n",
624                                                                         MAXDATASIZE - strlen(sendbuf) - 1);
625                                                         if (imap_command(sockfd, sendbuf, recvbuf, "a2 OK")) {
626                                                                 fail++;
627                                                                 break;
628                                                         }
629                                                         if (imap_check_status(recvbuf, mail)) {
630                                                                 fail++;
631                                                                 break;
632                                                         }
633                                                         strncpy(sendbuf, "a5 IDLE\r\n", MAXDATASIZE);
634                                                         if (imap_command(sockfd, sendbuf, recvbuf, "+ idling")) {
635                                                                 fail++;
636                                                                 break;
637                                                         }
638                                                 }
639                                                 /*
640                                                  * check if we got a BYE from server
641                                                  */
642                                                 buf = recvbuf;
643                                                 if (buf && strstr(buf, "* BYE")) {
644                                                         // need to re-connect
645                                                         break;
646                                                 }
647                                         } else {
648                                                 fail++;
649                                                 break;
650                                         }
651                                         imap_unseen_command(mail, old_unseen, old_messages);
652                                         fail = 0;
653                                         old_unseen = mail->unseen;
654                                         old_messages = mail->messages;
655                                 }
656                                 if (fail) break;
657                         } else {
658                                 strncpy(sendbuf, "a3 logout\r\n", MAXDATASIZE);
659                                 if (send(sockfd, sendbuf, strlen(sendbuf), 0) == -1) {
660                                         perror("send a3");
661                                         fail++;
662                                         break;
663                                 }
664                                 timeout.tv_sec = 60;    // 60 second timeout i guess
665                                 timeout.tv_usec = 0;
666                                 FD_ZERO(&fdset);
667                                 FD_SET(sockfd, &fdset);
668                                 res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
669                                 if (res > 0) {
670                                         if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
671                                                 perror("recv a3");
672                                                 fail++;
673                                                 break;
674                                         }
675                                 }
676                                 recvbuf[numbytes] = '\0';
677                                 DBGP2("imap_thread() received: %s", recvbuf);
678                                 if (strstr(recvbuf, "a3 OK") == NULL) {
679                                         ERR("IMAP logout failed: %s", recvbuf);
680                                         fail++;
681                                         break;
682                                 }
683                         }
684                 } while (0);
685                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
686                         /* if a valid socket, close it */
687                         close(sockfd);
688                 }
689                 if (timed_thread_test(mail->p_timed_thread, 0)) {
690                         timed_thread_exit(mail->p_timed_thread);
691                 }
692         }
693         mail->unseen = 0;
694         mail->messages = 0;
695         return 0;
696 }
697
698 int pop3_command(int sockfd, const char *command, char *response, const char *verify)
699 {
700         struct timeval timeout;
701         fd_set fdset;
702         int res, numbytes = 0;
703         if (send(sockfd, command, strlen(command), 0) == -1) {
704                 perror("send");
705                 return -1;
706         }
707         timeout.tv_sec = 60;    // 60 second timeout i guess
708         timeout.tv_usec = 0;
709         FD_ZERO(&fdset);
710         FD_SET(sockfd, &fdset);
711         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
712         if (res > 0) {
713                 if ((numbytes = recv(sockfd, response, MAXDATASIZE - 1, 0)) == -1) {
714                         perror("recv");
715                         return -1;
716                 }
717         }
718         DBGP2("pop3_command() received: %s", response);
719         response[numbytes] = '\0';
720         if (strstr(response, verify) == NULL) {
721                 return -1;
722         }
723         return 0;
724 }
725
726 void *pop3_thread(void *arg)
727 {
728         int sockfd, numbytes;
729         char recvbuf[MAXDATASIZE];
730         char sendbuf[MAXDATASIZE];
731         char *reply;
732         unsigned int fail = 0;
733         unsigned long old_unseen = ULONG_MAX;
734         struct stat stat_buf;
735         struct hostent he, *he_res = 0;
736         int he_errno;
737         char hostbuff[2048];
738         struct sockaddr_in their_addr;  // connector's address information
739         struct mail_s *mail = (struct mail_s *)arg;
740
741 #ifdef HAVE_GETHOSTBYNAME_R
742         if (gethostbyname_r(mail->host, &he, hostbuff, sizeof(hostbuff), &he_res, &he_errno)) { // get the host info
743                 ERR("POP3 gethostbyname_r: %s", hstrerror(h_errno));
744                 exit(1);
745         }
746 #else /* HAVE_GETHOSTBYNAME_R */
747         if ((he_res = gethostbyname(mail->host)) == NULL) {     // get the host info
748                 herror("gethostbyname");
749                 exit(1);
750         }
751 #endif /* HAVE_GETHOSTBYNAME_R */
752         while (fail < mail->retries) {
753                 struct timeval timeout;
754                 int res;
755                 fd_set fdset;
756
757                 if (fail > 0) {
758                         ERR("Trying POP3 connection again for %s@%s (try %u/%u)",
759                                         mail->user, mail->host, fail + 1, mail->retries);
760                 }
761                 do {
762                         if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
763                                 perror("socket");
764                                 fail++;
765                                 break;
766                         }
767
768                         // host byte order
769                         their_addr.sin_family = AF_INET;
770                         // short, network byte order
771                         their_addr.sin_port = htons(mail->port);
772                         their_addr.sin_addr = *((struct in_addr *) he_res->h_addr);
773                         // zero the rest of the struct
774                         memset(&(their_addr.sin_zero), '\0', 8);
775
776                         if (connect(sockfd, (struct sockaddr *) &their_addr,
777                                                 sizeof(struct sockaddr)) == -1) {
778                                 perror("connect");
779                                 fail++;
780                                 break;
781                         }
782
783                         timeout.tv_sec = 60;    // 60 second timeout i guess
784                         timeout.tv_usec = 0;
785                         FD_ZERO(&fdset);
786                         FD_SET(sockfd, &fdset);
787                         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
788                         if (res > 0) {
789                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
790                                         perror("recv");
791                                         fail++;
792                                         break;
793                                 }
794                         } else {
795                                 ERR("POP3 connection failed: timeout\n");
796                                 fail++;
797                                 break;
798                         }
799                         DBGP2("pop3_thread received: %s", recvbuf);
800                         recvbuf[numbytes] = '\0';
801                         if (strstr(recvbuf, "+OK ") != recvbuf) {
802                                 ERR("POP3 connection failed, probably not a POP3 server");
803                                 fail++;
804                                 break;
805                         }
806                         strncpy(sendbuf, "USER ", MAXDATASIZE);
807                         strncat(sendbuf, mail->user, MAXDATASIZE - strlen(sendbuf) - 1);
808                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
809                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
810                                 fail++;
811                                 break;
812                         }
813
814                         strncpy(sendbuf, "PASS ", MAXDATASIZE);
815                         strncat(sendbuf, mail->pass, MAXDATASIZE - strlen(sendbuf) - 1);
816                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
817                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
818                                 ERR("POP3 server login failed: %s", recvbuf);
819                                 fail++;
820                                 break;
821                         }
822
823                         strncpy(sendbuf, "STAT\r\n", MAXDATASIZE);
824                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
825                                 perror("send STAT");
826                                 fail++;
827                                 break;
828                         }
829
830                         // now we get the data
831                         reply = recvbuf + 4;
832                         if (reply == NULL) {
833                                 ERR("Error parsing POP3 response: %s", recvbuf);
834                                 fail++;
835                                 break;
836                         } else {
837                                 timed_thread_lock(mail->p_timed_thread);
838                                 sscanf(reply, "%lu %lu", &mail->unseen, &mail->used);
839                                 timed_thread_unlock(mail->p_timed_thread);
840                         }
841                         
842                         strncpy(sendbuf, "QUIT\r\n", MAXDATASIZE);
843                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK")) {
844                                 ERR("POP3 logout failed: %s", recvbuf);
845                                 fail++;
846                                 break;
847                         }
848                         
849                         if (strlen(mail->command) > 1 && mail->unseen > old_unseen) {
850                                 // new mail goodie
851                                 if (system(mail->command) == -1) {
852                                         perror("system()");
853                                 }
854                         }
855                         fail = 0;
856                         old_unseen = mail->unseen;
857                 } while (0);
858                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
859                         /* if a valid socket, close it */
860                         close(sockfd);
861                 }
862                 if (timed_thread_test(mail->p_timed_thread, 0)) {
863                         timed_thread_exit(mail->p_timed_thread);
864                 }
865         }
866         mail->unseen = 0;
867         mail->used = 0;
868         return 0;
869 }
870