Extra includes to fix compiling on FreeBSD
[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-2008 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         }
285         // see if password needs prompting
286         if (mail->pass[0] == '*' && mail->pass[1] == '\0') {
287                 int fp = fileno(stdin);
288                 struct termios term;
289
290                 tcgetattr(fp, &term);
291                 term.c_lflag &= ~ECHO;
292                 tcsetattr(fp, TCSANOW, &term);
293                 printf("Enter mailbox password (%s@%s): ", mail->user, mail->host);
294                 scanf("%128s", mail->pass);
295                 printf("\n");
296                 term.c_lflag |= ECHO;
297                 tcsetattr(fp, TCSANOW, &term);
298         }
299         // now we check for optional args
300         tmp = strstr(arg, "-r ");
301         if (tmp) {
302                 tmp += 3;
303                 sscanf(tmp, "%u", &mail->retries);
304         } else {
305                 mail->retries = 5;      // 5 retries after failure
306         }
307         tmp = strstr(arg, "-i ");
308         if (tmp) {
309                 tmp += 3;
310                 sscanf(tmp, "%f", &mail->interval);
311         } else {
312                 mail->interval = 300;   // 5 minutes
313         }
314         tmp = strstr(arg, "-p ");
315         if (tmp) {
316                 tmp += 3;
317                 sscanf(tmp, "%lu", &mail->port);
318         } else {
319                 if (type == POP3_TYPE) {
320                         mail->port = 110;       // default pop3 port
321                 } else if (type == IMAP_TYPE) {
322                         mail->port = 143;       // default imap port
323                 }
324         }
325         if (type == IMAP_TYPE) {
326                 tmp = strstr(arg, "-f ");
327                 if (tmp) {
328                         tmp += 3;
329                         sscanf(tmp, "%s", mail->folder);
330                 } else {
331                         strncpy(mail->folder, "INBOX", 128);    // default imap inbox
332                 }
333         }
334         tmp = strstr(arg, "-e ");
335         if (tmp) {
336                 int len = 1024;
337                 tmp += 3;
338
339                 if (tmp[0] == '\'') {
340                         len = strstr(tmp + 1, "'") - tmp - 1;
341                         if (len > 1024) {
342                                 len = 1024;
343                         }
344                 }
345                 strncpy(mail->command, tmp + 1, len);
346         } else {
347                 mail->command[0] = '\0';
348         }
349         mail->p_timed_thread = NULL;
350         return mail;
351 }
352
353 int imap_command(int sockfd, const char *command, char *response, const char *verify)
354 {
355         struct timeval timeout;
356         fd_set fdset;
357         int res, numbytes = 0;
358         if (send(sockfd, command, strlen(command), 0) == -1) {
359                 perror("send");
360                 return -1;
361         }
362         timeout.tv_sec = 60;    // 60 second timeout i guess
363         timeout.tv_usec = 0;
364         FD_ZERO(&fdset);
365         FD_SET(sockfd, &fdset);
366         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
367         if (res > 0) {
368                 if ((numbytes = recv(sockfd, response, MAXDATASIZE - 1, 0)) == -1) {
369                         perror("recv");
370                         return -1;
371                 }
372         }
373         DBGP2("imap_command()  command: %s", command);
374         DBGP2("imap_command() received: %s", response);
375         response[numbytes] = '\0';
376         if (strstr(response, verify) == NULL) {
377                 return -1;
378         }
379         return 0;
380 }
381
382 int imap_check_status(char *recvbuf, struct mail_s *mail)
383 {
384         char *reply;
385         reply = strstr(recvbuf, " (MESSAGES ");
386         if (!reply || strlen(reply) < 2) {
387                 return -1;
388         }
389         reply += 2;
390         *strchr(reply, ')') = '\0';
391         if (reply == NULL) {
392                 ERR("Error parsing IMAP response: %s", recvbuf);
393                 return -1;
394         } else {
395                 timed_thread_lock(mail->p_timed_thread);
396                 sscanf(reply, "MESSAGES %lu UNSEEN %lu", &mail->messages,
397                                 &mail->unseen);
398                 timed_thread_unlock(mail->p_timed_thread);
399         }
400         return 0;
401 }
402
403 void imap_unseen_command(struct mail_s *mail, unsigned long old_unseen, unsigned long old_messages)
404 {
405         if (strlen(mail->command) > 1 && (mail->unseen > old_unseen
406                                 || (mail->messages > old_messages && mail->unseen > 0))) {
407                 // new mail goodie
408                 if (system(mail->command) == -1) {
409                         perror("system()");
410                 }
411         }
412 }
413
414 void *imap_thread(void *arg)
415 {
416         int sockfd, numbytes;
417         char recvbuf[MAXDATASIZE];
418         char sendbuf[MAXDATASIZE];
419         unsigned int fail = 0;
420         unsigned long old_unseen = ULONG_MAX;
421         unsigned long old_messages = ULONG_MAX;
422         struct stat stat_buf;
423         struct hostent he, *he_res = 0;
424         int he_errno;
425         char hostbuff[2048];
426         struct sockaddr_in their_addr;  // connector's address information
427         struct mail_s *mail = (struct mail_s *)arg;
428         int has_idle = 0;
429         int threadfd = timed_thread_readfd(mail->p_timed_thread);
430
431 #ifdef HAVE_GETHOSTBYNAME_R
432         if (gethostbyname_r(mail->host, &he, hostbuff, sizeof(hostbuff), &he_res, &he_errno)) { // get the host info
433                 ERR("IMAP gethostbyname_r: %s", hstrerror(h_errno));
434                 exit(1);
435         }
436 #else /* HAVE_GETHOSTBYNAME_R */
437         if ((he_res = gethostbyname(mail->host)) == NULL) {     // get the host info
438                 herror("gethostbyname");
439                 exit(1);
440         }
441 #endif /* HAVE_GETHOSTBYNAME_R */
442         while (fail < mail->retries) {
443                 struct timeval timeout;
444                 int res;
445                 fd_set fdset;
446
447                 if (fail > 0) {
448                         ERR("Trying IMAP connection again for %s@%s (try %u/%u)",
449                                         mail->user, mail->host, fail + 1, mail->retries);
450                 }
451                 do {
452                         if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
453                                 perror("socket");
454                                 fail++;
455                                 break;
456                         }
457
458                         // host byte order
459                         their_addr.sin_family = AF_INET;
460                         // short, network byte order
461                         their_addr.sin_port = htons(mail->port);
462                         their_addr.sin_addr = *((struct in_addr *) he_res->h_addr);
463                         // zero the rest of the struct
464                         memset(&(their_addr.sin_zero), '\0', 8);
465
466                         if (connect(sockfd, (struct sockaddr *) &their_addr,
467                                                 sizeof(struct sockaddr)) == -1) {
468                                 perror("connect");
469                                 fail++;
470                                 break;
471                         }
472
473                         timeout.tv_sec = 60;    // 60 second timeout i guess
474                         timeout.tv_usec = 0;
475                         FD_ZERO(&fdset);
476                         FD_SET(sockfd, &fdset);
477                         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
478                         if (res > 0) {
479                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
480                                         perror("recv");
481                                         fail++;
482                                         break;
483                                 }
484                         } else {
485                                 ERR("IMAP connection failed: timeout");
486                                 fail++;
487                                 break;
488                         }
489                         recvbuf[numbytes] = '\0';
490                         DBGP2("imap_thread() received: %s", recvbuf);
491                         if (strstr(recvbuf, "* OK") != recvbuf) {
492                                 ERR("IMAP connection failed, probably not an IMAP server");
493                                 fail++;
494                                 break;
495                         }
496                         strncpy(sendbuf, "a1 login ", MAXDATASIZE);
497                         strncat(sendbuf, mail->user, MAXDATASIZE - strlen(sendbuf) - 1);
498                         strncat(sendbuf, " ", MAXDATASIZE - strlen(sendbuf) - 1);
499                         strncat(sendbuf, mail->pass, MAXDATASIZE - strlen(sendbuf) - 1);
500                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
501                         if (imap_command(sockfd, sendbuf, recvbuf, "a1 OK")) {
502                                 fail++;
503                                 break;
504                         }
505                         if (strstr(recvbuf, " IDLE ") != NULL) {
506                                 has_idle = 1;
507                         }
508
509                         strncpy(sendbuf, "a2 STATUS ", MAXDATASIZE);
510                         strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
511                         strncat(sendbuf, " (MESSAGES UNSEEN)\r\n",
512                                         MAXDATASIZE - strlen(sendbuf) - 1);
513                         if (imap_command(sockfd, sendbuf, recvbuf, "a2 OK")) {
514                                 fail++;
515                                 break;
516                         }
517
518                         if (imap_check_status(recvbuf, mail)) {
519                                 fail++;
520                                 break;
521                         }
522                         imap_unseen_command(mail, old_unseen, old_messages);
523                         fail = 0;
524                         old_unseen = mail->unseen;
525                         old_messages = mail->messages;
526
527                         if (has_idle) {
528                                 strncpy(sendbuf, "a4 SELECT ", MAXDATASIZE);
529                                 strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
530                                 strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
531                                 if (imap_command(sockfd, sendbuf, recvbuf, "a4 OK")) {
532                                         fail++;
533                                         break;
534                                 }
535
536                                 strncpy(sendbuf, "a5 IDLE\r\n", MAXDATASIZE);
537                                 if (imap_command(sockfd, sendbuf, recvbuf, "+ idling")) {
538                                         fail++;
539                                         break;
540                                 }
541                                 recvbuf[0] = '\0';
542
543                                 while (1) {
544                                         /*
545                                          * RFC 2177 says we have to re-idle every 29 minutes.
546                                          * We'll do it every 20 minutes to be safe.
547                                          */
548                                         timeout.tv_sec = 1200;
549                                         timeout.tv_usec = 0;
550                                         DBGP2("idling...");
551                                         FD_ZERO(&fdset);
552                                         FD_SET(sockfd, &fdset);
553                                         FD_SET(threadfd, &fdset);
554                                         res = select(MAX(sockfd + 1, threadfd + 1), &fdset, NULL, NULL, NULL);
555                                         if (timed_thread_test(mail->p_timed_thread, 1) || (res == -1 && errno == EINTR) || FD_ISSET(threadfd, &fdset)) {
556                                                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
557                                                         /* if a valid socket, close it */
558                                                         close(sockfd);
559                                                 }
560                                                 timed_thread_exit(mail->p_timed_thread);
561                                         } else if (res > 0) {
562                                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
563                                                         perror("recv idling");
564                                                         fail++;
565                                                         break;
566                                                 }
567                                         } else {
568                                                 break;
569                                         }
570                                         recvbuf[numbytes] = '\0';
571                                         DBGP2("imap_thread() received: %s", recvbuf);
572                                         if (strlen(recvbuf) > 2) {
573                                                 unsigned long messages, recent;
574                                                 char *buf = recvbuf;
575                                                 char force_check = 0;
576                                                 buf = strstr(buf, "EXISTS");
577                                                 while (buf && strlen(buf) > 1 && strstr(buf + 1, "EXISTS")) {
578                                                         buf = strstr(buf + 1, "EXISTS");
579                                                 }
580                                                 if (buf) {
581                                                         // back up until we reach '*'
582                                                         while (buf >= recvbuf && buf[0] != '*') {
583                                                                 buf--;
584                                                         }
585                                                         if (sscanf(buf, "* %lu EXISTS\r\n", &messages) == 1) {
586                                                                 timed_thread_lock(mail->p_timed_thread);
587                                                                 if (mail->messages != messages) {
588                                                                         force_check = 1;
589                                                                         mail->messages = messages;
590                                                                 }
591                                                                 timed_thread_unlock(mail->p_timed_thread);
592                                                         }
593                                                 }
594                                                 buf = recvbuf;
595                                                 buf = strstr(buf, "RECENT");
596                                                 while (buf && strlen(buf) > 1 && strstr(buf + 1, "RECENT")) {
597                                                         buf = strstr(buf + 1, "RECENT");
598                                                 }
599                                                 if (buf) {
600                                                         // back up until we reach '*'
601                                                         while (buf >= recvbuf && buf[0] != '*') {
602                                                                 buf--;
603                                                         }
604                                                         if (sscanf(buf, "* %lu RECENT\r\n", &recent) != 1) {
605                                                                 recent = 0;
606                                                         }
607                                                 }
608                                                 /*
609                                                  * check if we got a FETCH from server, recent was
610                                                  * something other than 0, or we had a timeout
611                                                  */
612                                                 buf = recvbuf;
613                                                 if (recent > 0 || (buf && strstr(buf, " FETCH ")) || timeout.tv_sec == 0 || force_check) {
614                                                         // re-check messages and unseen
615                                                         if (imap_command(sockfd, "DONE\r\n", recvbuf, "a5 OK")) {
616                                                                 fail++;
617                                                                 break;
618                                                         }
619                                                         strncpy(sendbuf, "a2 STATUS ", MAXDATASIZE);
620                                                         strncat(sendbuf, mail->folder, MAXDATASIZE - strlen(sendbuf) - 1);
621                                                         strncat(sendbuf, " (MESSAGES UNSEEN)\r\n",
622                                                                         MAXDATASIZE - strlen(sendbuf) - 1);
623                                                         if (imap_command(sockfd, sendbuf, recvbuf, "a2 OK")) {
624                                                                 fail++;
625                                                                 break;
626                                                         }
627                                                         if (imap_check_status(recvbuf, mail)) {
628                                                                 fail++;
629                                                                 break;
630                                                         }
631                                                         strncpy(sendbuf, "a5 IDLE\r\n", MAXDATASIZE);
632                                                         if (imap_command(sockfd, sendbuf, recvbuf, "+ idling")) {
633                                                                 fail++;
634                                                                 break;
635                                                         }
636                                                 }
637                                                 /*
638                                                  * check if we got a BYE from server
639                                                  */
640                                                 buf = recvbuf;
641                                                 if (buf && strstr(buf, "* BYE")) {
642                                                         // need to re-connect
643                                                         break;
644                                                 }
645                                         }
646                                         imap_unseen_command(mail, old_unseen, old_messages);
647                                         fail = 0;
648                                         old_unseen = mail->unseen;
649                                         old_messages = mail->messages;
650                                 }
651                         } else {
652                                 strncpy(sendbuf, "a3 logout\r\n", MAXDATASIZE);
653                                 if (send(sockfd, sendbuf, strlen(sendbuf), 0) == -1) {
654                                         perror("send a3");
655                                         fail++;
656                                         break;
657                                 }
658                                 timeout.tv_sec = 60;    // 60 second timeout i guess
659                                 timeout.tv_usec = 0;
660                                 FD_ZERO(&fdset);
661                                 FD_SET(sockfd, &fdset);
662                                 res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
663                                 if (res > 0) {
664                                         if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
665                                                 perror("recv a3");
666                                                 fail++;
667                                                 break;
668                                         }
669                                 }
670                                 recvbuf[numbytes] = '\0';
671                                 DBGP2("imap_thread() received: %s", recvbuf);
672                                 if (strstr(recvbuf, "a3 OK") == NULL) {
673                                         ERR("IMAP logout failed: %s", recvbuf);
674                                         fail++;
675                                         break;
676                                 }
677                         }
678                 } while (0);
679                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
680                         /* if a valid socket, close it */
681                         close(sockfd);
682                 }
683                 if (timed_thread_test(mail->p_timed_thread, 0)) {
684                         timed_thread_exit(mail->p_timed_thread);
685                 }
686         }
687         mail->unseen = 0;
688         mail->messages = 0;
689         return 0;
690 }
691
692 int pop3_command(int sockfd, const char *command, char *response, const char *verify)
693 {
694         struct timeval timeout;
695         fd_set fdset;
696         int res, numbytes = 0;
697         if (send(sockfd, command, strlen(command), 0) == -1) {
698                 perror("send");
699                 return -1;
700         }
701         timeout.tv_sec = 60;    // 60 second timeout i guess
702         timeout.tv_usec = 0;
703         FD_ZERO(&fdset);
704         FD_SET(sockfd, &fdset);
705         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
706         if (res > 0) {
707                 if ((numbytes = recv(sockfd, response, MAXDATASIZE - 1, 0)) == -1) {
708                         perror("recv");
709                         return -1;
710                 }
711         }
712         DBGP2("pop3_command() received: %s", response);
713         response[numbytes] = '\0';
714         if (strstr(response, verify) == NULL) {
715                 return -1;
716         }
717         return 0;
718 }
719
720 void *pop3_thread(void *arg)
721 {
722         int sockfd, numbytes;
723         char recvbuf[MAXDATASIZE];
724         char sendbuf[MAXDATASIZE];
725         char *reply;
726         unsigned int fail = 0;
727         unsigned long old_unseen = ULONG_MAX;
728         struct stat stat_buf;
729         struct hostent he, *he_res = 0;
730         int he_errno;
731         char hostbuff[2048];
732         struct sockaddr_in their_addr;  // connector's address information
733         struct mail_s *mail = (struct mail_s *)arg;
734
735 #ifdef HAVE_GETHOSTBYNAME_R
736         if (gethostbyname_r(mail->host, &he, hostbuff, sizeof(hostbuff), &he_res, &he_errno)) { // get the host info
737                 ERR("POP3 gethostbyname_r: %s", hstrerror(h_errno));
738                 exit(1);
739         }
740 #else /* HAVE_GETHOSTBYNAME_R */
741         if ((he_res = gethostbyname(mail->host)) == NULL) {     // get the host info
742                 herror("gethostbyname");
743                 exit(1);
744         }
745 #endif /* HAVE_GETHOSTBYNAME_R */
746         while (fail < mail->retries) {
747                 struct timeval timeout;
748                 int res;
749                 fd_set fdset;
750
751                 if (fail > 0) {
752                         ERR("Trying POP3 connection again for %s@%s (try %u/%u)",
753                                         mail->user, mail->host, fail + 1, mail->retries);
754                 }
755                 do {
756                         if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
757                                 perror("socket");
758                                 fail++;
759                                 break;
760                         }
761
762                         // host byte order
763                         their_addr.sin_family = AF_INET;
764                         // short, network byte order
765                         their_addr.sin_port = htons(mail->port);
766                         their_addr.sin_addr = *((struct in_addr *) he_res->h_addr);
767                         // zero the rest of the struct
768                         memset(&(their_addr.sin_zero), '\0', 8);
769
770                         if (connect(sockfd, (struct sockaddr *) &their_addr,
771                                                 sizeof(struct sockaddr)) == -1) {
772                                 perror("connect");
773                                 fail++;
774                                 break;
775                         }
776
777                         timeout.tv_sec = 60;    // 60 second timeout i guess
778                         timeout.tv_usec = 0;
779                         FD_ZERO(&fdset);
780                         FD_SET(sockfd, &fdset);
781                         res = select(sockfd + 1, &fdset, NULL, NULL, &timeout);
782                         if (res > 0) {
783                                 if ((numbytes = recv(sockfd, recvbuf, MAXDATASIZE - 1, 0)) == -1) {
784                                         perror("recv");
785                                         fail++;
786                                         break;
787                                 }
788                         } else {
789                                 ERR("POP3 connection failed: timeout\n");
790                                 fail++;
791                                 break;
792                         }
793                         DBGP2("pop3_thread received: %s", recvbuf);
794                         recvbuf[numbytes] = '\0';
795                         if (strstr(recvbuf, "+OK ") != recvbuf) {
796                                 ERR("POP3 connection failed, probably not a POP3 server");
797                                 fail++;
798                                 break;
799                         }
800                         strncpy(sendbuf, "USER ", MAXDATASIZE);
801                         strncat(sendbuf, mail->user, MAXDATASIZE - strlen(sendbuf) - 1);
802                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
803                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
804                                 fail++;
805                                 break;
806                         }
807
808                         strncpy(sendbuf, "PASS ", MAXDATASIZE);
809                         strncat(sendbuf, mail->pass, MAXDATASIZE - strlen(sendbuf) - 1);
810                         strncat(sendbuf, "\r\n", MAXDATASIZE - strlen(sendbuf) - 1);
811                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
812                                 ERR("POP3 server login failed: %s", recvbuf);
813                                 fail++;
814                                 break;
815                         }
816
817                         strncpy(sendbuf, "STAT\r\n", MAXDATASIZE);
818                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK ")) {
819                                 perror("send STAT");
820                                 fail++;
821                                 break;
822                         }
823
824                         // now we get the data
825                         reply = recvbuf + 4;
826                         if (reply == NULL) {
827                                 ERR("Error parsing POP3 response: %s", recvbuf);
828                                 fail++;
829                                 break;
830                         } else {
831                                 timed_thread_lock(mail->p_timed_thread);
832                                 sscanf(reply, "%lu %lu", &mail->unseen, &mail->used);
833                                 timed_thread_unlock(mail->p_timed_thread);
834                         }
835                         
836                         strncpy(sendbuf, "QUIT\r\n", MAXDATASIZE);
837                         if (pop3_command(sockfd, sendbuf, recvbuf, "+OK")) {
838                                 ERR("POP3 logout failed: %s", recvbuf);
839                                 fail++;
840                                 break;
841                         }
842                         
843                         if (strlen(mail->command) > 1 && mail->unseen > old_unseen) {
844                                 // new mail goodie
845                                 if (system(mail->command) == -1) {
846                                         perror("system()");
847                                 }
848                         }
849                         fail = 0;
850                         old_unseen = mail->unseen;
851                 } while (0);
852                 if ((fstat(sockfd, &stat_buf) == 0) && S_ISSOCK(stat_buf.st_mode)) {
853                         /* if a valid socket, close it */
854                         close(sockfd);
855                 }
856                 if (timed_thread_test(mail->p_timed_thread, 0)) {
857                         timed_thread_exit(mail->p_timed_thread);
858                 }
859         }
860         mail->unseen = 0;
861         mail->used = 0;
862         return 0;
863 }
864