Minor for for mail args parsing.
[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 IMAP args failed");
281                 } else if (type == IMAP_TYPE) {
282                         ERR("Scanning POP3 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                                                 break;
570                                         }
571                                         recvbuf[numbytes] = '\0';
572                                         DBGP2("imap_thread() received: %s", recvbuf);
573                                         if (strlen(recvbuf) > 2) {
574                                                 unsigned long messages, recent;
575                                                 char *buf = recvbuf;
576                                                 char force_check = 0;
577                                                 buf = strstr(buf, "EXISTS");
578                                                 while (buf && strlen(buf) > 1 && strstr(buf + 1, "EXISTS")) {
579                                                         buf = strstr(buf + 1, "EXISTS");
580                                                 }
581                                                 if (buf) {
582                                                         // back up until we reach '*'
583                                                         while (buf >= recvbuf && buf[0] != '*') {
584                                                                 buf--;
585                                                         }
586                                                         if (sscanf(buf, "* %lu EXISTS\r\n", &messages) == 1) {
587                                                                 timed_thread_lock(mail->p_timed_thread);
588                                                                 if (mail->messages != messages) {
589                                                                         force_check = 1;
590                                                                         mail->messages = messages;
591                                                                 }
592                                                                 timed_thread_unlock(mail->p_timed_thread);
593                                                         }
594                                                 }
595                                                 buf = recvbuf;
596                                                 buf = strstr(buf, "RECENT");
597                                                 while (buf && strlen(buf) > 1 && strstr(buf + 1, "RECENT")) {
598                                                         buf = strstr(buf + 1, "RECENT");
599                                                 }
600                                                 if (buf) {
601                                                         // back up until we reach '*'
602                                                         while (buf >= recvbuf && buf[0] != '*') {
603                                                                 buf--;
604                                                         }
605                                                         if (sscanf(buf, "* %lu RECENT\r\n", &recent) != 1) {
606                                                                 recent = 0;
607                                                         }
608                                                 }
609                                                 /*
610                                                  * check if we got a FETCH from server, recent was
611                                                  * something other than 0, or we had a timeout
612                                                  */
613                                                 buf = recvbuf;
614                                                 if (recent > 0 || (buf && strstr(buf, " FETCH ")) || timeout.tv_sec == 0 || force_check) {
615                                                         // re-check messages and unseen
616                                                         if (imap_command(sockfd, "DONE\r\n", recvbuf, "a5 OK")) {
617                                                                 fail++;
618                                                                 break;
619                                                         }
620                                                         strncpy(sendbuf, "a2 STATUS ", MAXDATASIZE);
621                                                         strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
622                                                         strncat(sendbuf, " (MESSAGES UNSEEN)\r\n",
623                                                                         MAXDATASIZE - strlen(sendbuf) - 1);
624                                                         if (imap_command(sockfd, sendbuf, recvbuf, "a2 OK")) {
625                                                                 fail++;
626                                                                 break;
627                                                         }
628                                                         if (imap_check_status(recvbuf, mail)) {
629                                                                 fail++;
630                                                                 break;
631                                                         }
632                                                         strncpy(sendbuf, "a5 IDLE\r\n", MAXDATASIZE);
633                                                         if (imap_command(sockfd, sendbuf, recvbuf, "+ idling")) {
634                                                                 fail++;
635                                                                 break;
636                                                         }
637                                                 }
638                                                 /*
639                                                  * check if we got a BYE from server
640                                                  */
641                                                 buf = recvbuf;
642                                                 if (buf && strstr(buf, "* BYE")) {
643                                                         // need to re-connect
644                                                         break;
645                                                 }
646                                         }
647                                         imap_unseen_command(mail, old_unseen, old_messages);
648                                         fail = 0;
649                                         old_unseen = mail->unseen;
650                                         old_messages = mail->messages;
651                                 }
652                         } else {
653                                 strncpy(sendbuf, "a3 logout\r\n", MAXDATASIZE);
654                                 if (send(sockfd, sendbuf, strlen(sendbuf), 0) == -1) {
655                                         perror("send a3");
656                                         fail++;
657                                         break;
658                                 }
659                                 timeout.tv_sec = 60;    // 60 second timeout i guess
660                                 timeout.tv_usec = 0;
661                                 FD_ZERO(&fdset);
662                                 FD_SET(sockfd, &fdset);
663                                 res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
664                                 if (res > 0) {
665                                         if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
666                                                 perror("recv a3");
667                                                 fail++;
668                                                 break;
669                                         }
670                                 }
671                                 recvbuf[numbytes] = '\0';
672                                 DBGP2("imap_thread() received: %s", recvbuf);
673                                 if (strstr(recvbuf, "a3 OK") == NULL) {
674                                         ERR("IMAP logout failed: %s", recvbuf);
675                                         fail++;
676                                         break;
677                                 }
678                         }
679                 } while (0);
680                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
681                         /* if a valid socket, close it */
682                         close(sockfd);
683                 }
684                 if (timed_thread_test(mail->p_timed_thread, 0)) {
685                         timed_thread_exit(mail->p_timed_thread);
686                 }
687         }
688         mail->unseen = 0;
689         mail->messages = 0;
690         return 0;
691 }
692
693 int pop3_command(int sockfd, const char *command, char *response, const char *verify)
694 {
695         struct timeval timeout;
696         fd_set fdset;
697         int res, numbytes = 0;
698         if (send(sockfd, command, strlen(command), 0) == -1) {
699                 perror("send");
700                 return -1;
701         }
702         timeout.tv_sec = 60;    // 60 second timeout i guess
703         timeout.tv_usec = 0;
704         FD_ZERO(&fdset);
705         FD_SET(sockfd, &fdset);
706         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
707         if (res > 0) {
708                 if ((numbytes = recv(sockfd, response, MAXDATASIZE - 1, 0)) == -1) {
709                         perror("recv");
710                         return -1;
711                 }
712         }
713         DBGP2("pop3_command() received: %s", response);
714         response[numbytes] = '\0';
715         if (strstr(response, verify) == NULL) {
716                 return -1;
717         }
718         return 0;
719 }
720
721 void *pop3_thread(void *arg)
722 {
723         int sockfd, numbytes;
724         char recvbuf[MAXDATASIZE];
725         char sendbuf[MAXDATASIZE];
726         char *reply;
727         unsigned int fail = 0;
728         unsigned long old_unseen = ULONG_MAX;
729         struct stat stat_buf;
730         struct hostent he, *he_res = 0;
731         int he_errno;
732         char hostbuff[2048];
733         struct sockaddr_in their_addr;  // connector's address information
734         struct mail_s *mail = (struct mail_s *)arg;
735
736 #ifdef HAVE_GETHOSTBYNAME_R
737         if (gethostbyname_r(mail->host, &he, hostbuff, sizeof(hostbuff), &he_res, &he_errno)) { // get the host info
738                 ERR("POP3 gethostbyname_r: %s", hstrerror(h_errno));
739                 exit(1);
740         }
741 #else /* HAVE_GETHOSTBYNAME_R */
742         if ((he_res = gethostbyname(mail->host)) == NULL) {     // get the host info
743                 herror("gethostbyname");
744                 exit(1);
745         }
746 #endif /* HAVE_GETHOSTBYNAME_R */
747         while (fail < mail->retries) {
748                 struct timeval timeout;
749                 int res;
750                 fd_set fdset;
751
752                 if (fail > 0) {
753                         ERR("Trying POP3 connection again for %s@%s (try %u/%u)",
754                                         mail->user, mail->host, fail + 1, mail->retries);
755                 }
756                 do {
757                         if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
758                                 perror("socket");
759                                 fail++;
760                                 break;
761                         }
762
763                         // host byte order
764                         their_addr.sin_family = AF_INET;
765                         // short, network byte order
766                         their_addr.sin_port = htons(mail->port);
767                         their_addr.sin_addr = *((struct in_addr *) he_res->h_addr);
768                         // zero the rest of the struct
769                         memset(&(their_addr.sin_zero), '\0', 8);
770
771                         if (connect(sockfd, (struct sockaddr *) &their_addr,
772                                                 sizeof(struct sockaddr)) == -1) {
773                                 perror("connect");
774                                 fail++;
775                                 break;
776                         }
777
778                         timeout.tv_sec = 60;    // 60 second timeout i guess
779                         timeout.tv_usec = 0;
780                         FD_ZERO(&fdset);
781                         FD_SET(sockfd, &fdset);
782                         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
783                         if (res > 0) {
784                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
785                                         perror("recv");
786                                         fail++;
787                                         break;
788                                 }
789                         } else {
790                                 ERR("POP3 connection failed: timeout\n");
791                                 fail++;
792                                 break;
793                         }
794                         DBGP2("pop3_thread received: %s", recvbuf);
795                         recvbuf[numbytes] = '\0';
796                         if (strstr(recvbuf, "+OK ") != recvbuf) {
797                                 ERR("POP3 connection failed, probably not a POP3 server");
798                                 fail++;
799                                 break;
800                         }
801                         strncpy(sendbuf, "USER ", MAXDATASIZE);
802                         strncat(sendbuf, mail->user, MAXDATASIZE - strlen(sendbuf) - 1);
803                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
804                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
805                                 fail++;
806                                 break;
807                         }
808
809                         strncpy(sendbuf, "PASS ", MAXDATASIZE);
810                         strncat(sendbuf, mail->pass, MAXDATASIZE - strlen(sendbuf) - 1);
811                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
812                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
813                                 ERR("POP3 server login failed: %s", recvbuf);
814                                 fail++;
815                                 break;
816                         }
817
818                         strncpy(sendbuf, "STAT\r\n", MAXDATASIZE);
819                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
820                                 perror("send STAT");
821                                 fail++;
822                                 break;
823                         }
824
825                         // now we get the data
826                         reply = recvbuf + 4;
827                         if (reply == NULL) {
828                                 ERR("Error parsing POP3 response: %s", recvbuf);
829                                 fail++;
830                                 break;
831                         } else {
832                                 timed_thread_lock(mail->p_timed_thread);
833                                 sscanf(reply, "%lu %lu", &mail->unseen, &mail->used);
834                                 timed_thread_unlock(mail->p_timed_thread);
835                         }
836                         
837                         strncpy(sendbuf, "QUIT\r\n", MAXDATASIZE);
838                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK")) {
839                                 ERR("POP3 logout failed: %s", recvbuf);
840                                 fail++;
841                                 break;
842                         }
843                         
844                         if (strlen(mail->command) > 1 && mail->unseen > old_unseen) {
845                                 // new mail goodie
846                                 if (system(mail->command) == -1) {
847                                         perror("system()");
848                                 }
849                         }
850                         fail = 0;
851                         old_unseen = mail->unseen;
852                 } while (0);
853                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
854                         /* if a valid socket, close it */
855                         close(sockfd);
856                 }
857                 if (timed_thread_test(mail->p_timed_thread, 0)) {
858                         timed_thread_exit(mail->p_timed_thread);
859                 }
860         }
861         mail->unseen = 0;
862         mail->used = 0;
863         return 0;
864 }
865