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