-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.c
1690 lines (1533 loc) · 48.5 KB
/
driver.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* driver.c -- generic driver for mail fetch method protocols
*
* Copyright 1997 by Eric S. Raymond
* For license terms, see the file COPYING in this directory.
*/
#include "config.h"
#include "fetchmail.h"
#include <stdio.h>
#include <setjmp.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#if defined(HAVE_SYS_ITIMER_H)
#include <sys/itimer.h>
#endif
#include <signal.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netdb.h>
#ifdef HAVE_PKG_hesiod
#ifdef __cplusplus
extern "C" {
#endif
#include <hesiod.h>
#ifdef __cplusplus
}
#endif
#endif
#include <langinfo.h>
#include "kerberos.h"
#ifdef KERBEROS_V4
#include <netinet/in.h>
#endif /* KERBEROS_V4 */
#include "i18n.h"
#include "socket.h"
#include "tunable.h"
#include "sdump.h"
/* throw types for runtime errors */
#define THROW_TIMEOUT 1 /* server timed out */
/* magic values for the message length array */
#define MSGLEN_UNKNOWN 0 /* length unknown (0 is impossible) */
#define MSGLEN_INVALID -1 /* length passed back is invalid */
#define MSGLEN_TOOLARGE -2 /* message is too large */
#define MSGLEN_OLD -3 /* message is old */
int pass; /* how many times have we re-polled? */
int stage; /* where are we? */
int phase; /* where are we, for error-logging purposes? */
int batchcount; /* count of messages sent in current batch */
flag peek_capable; /* can we peek for better error recovery? */
int mailserver_socket_temp = -1; /* socket to free if connect timeout */
struct addrinfo *ai0, *ai1; /* clean these up after signal */
static volatile int timeoutcount = 0; /* count consecutive timeouts */
static volatile int idletimeout = 0; /* timeout occured in idle stage? */
static sigjmp_buf restart;
int is_idletimeout(void)
/* last timeout occured in idle stage? */
{
return idletimeout;
}
void resetidletimeout(void)
{
idletimeout = 0;
}
void set_timeout(int timeleft)
/* reset the nonresponse-timeout */
{
struct itimerval ntimeout;
if (timeleft == 0)
timeoutcount = 0;
ntimeout.it_interval.tv_sec = ntimeout.it_interval.tv_usec = 0;
ntimeout.it_value.tv_sec = timeleft;
ntimeout.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &ntimeout, (struct itimerval *)NULL);
}
static void timeout_handler (int signal)
/* handle SIGALRM signal indicating a server timeout */
{
(void)signal;
if(stage != STAGE_IDLE) {
timeoutcount++;
/* XXX FIXME: this siglongjmp must die - it's not safe to be
* called from a function handler and breaks, for instance,
* getaddrinfo() */
siglongjmp(restart, THROW_TIMEOUT);
} else
idletimeout = 1;
}
#define CLEANUP_TIMEOUT 60 /* maximum timeout during cleanup */
static int cleanupSockClose (int fd)
/* close sockets in maximum CLEANUP_TIMEOUT seconds during cleanup */
{
int scerror;
SIGHANDLERTYPE alrmsave;
alrmsave = set_signal_handler(SIGALRM, null_signal_handler);
set_timeout(CLEANUP_TIMEOUT);
scerror = SockClose(fd);
set_timeout(0);
set_signal_handler(SIGALRM, alrmsave);
return (scerror);
}
#ifdef KERBEROS_V4
static int kerberos_auth(socket, canonical, principal)
/* authenticate to the server host using Kerberos V4 */
int socket; /* socket to server host */
char *canonical; /* server name */
char *principal;
{
KTEXT ticket;
MSG_DAT msg_data;
CREDENTIALS cred;
Key_schedule schedule;
int rem;
char * prin_copy = (char *) NULL;
char * prin = (char *) NULL;
char * inst = (char *) NULL;
char * realm = (char *) NULL;
if (principal != (char *)NULL && *principal)
{
char *cp;
prin = prin_copy = xstrdup(principal);
for (cp = prin_copy; *cp && *cp != '.'; ++cp)
;
if (*cp)
{
*cp++ = '\0';
inst = cp;
while (*cp && *cp != '@')
++cp;
if (*cp)
{
*cp++ = '\0';
realm = cp;
}
}
}
ticket = xmalloc(sizeof (KTEXT_ST));
rem = (krb_sendauth (0L, socket, ticket,
prin ? prin : "pop",
inst ? inst : canonical,
realm ? realm : ((char *) (krb_realmofhost (canonical))),
((unsigned long) 0),
(&msg_data),
(&cred),
(schedule),
((struct sockaddr_in *) 0),
((struct sockaddr_in *) 0),
"KPOPV0.1"));
free(ticket);
if (prin_copy)
{
free(prin_copy);
}
if (rem != KSUCCESS)
{
report(stderr, GT_("kerberos error %s\n"), (krb_get_err_text (rem)));
return (PS_AUTHFAIL);
}
return (0);
}
#endif /* KERBEROS_V4 */
#ifdef KERBEROS_V5
static int kerberos5_auth(socket, canonical)
/* authenticate to the server host using Kerberos V5 */
int socket; /* socket to server host */
const char *canonical; /* server name */
{
krb5_error_code retval;
krb5_context context;
krb5_ccache ccdef;
krb5_principal client = NULL, server = NULL;
krb5_error *err_ret = NULL;
krb5_auth_context auth_context = NULL;
krb5_init_context(&context);
krb5_auth_con_init(context, &auth_context);
if ((retval = krb5_cc_default(context, &ccdef))) {
report(stderr, "krb5_cc_default: %s\n", error_message(retval));
return(PS_ERROR);
}
if ((retval = krb5_cc_get_principal(context, ccdef, &client))) {
report(stderr, "krb5_cc_get_principal: %s\n", error_message(retval));
return(PS_ERROR);
}
if ((retval = krb5_sname_to_principal(context, canonical, "pop",
KRB5_NT_UNKNOWN,
&server))) {
report(stderr, "krb5_sname_to_principal: %s\n", error_message(retval));
return(PS_ERROR);
}
retval = krb5_sendauth(context, &auth_context, (krb5_pointer) &socket,
"KPOPV1.0", client, server,
AP_OPTS_MUTUAL_REQUIRED,
NULL, /* no data to checksum */
0, /* no creds, use ccache instead */
ccdef,
&err_ret, 0,
NULL); /* don't need reply */
krb5_free_principal(context, server);
krb5_free_principal(context, client);
krb5_auth_con_free(context, auth_context);
if (retval) {
#ifdef HEIMDAL
if (err_ret && err_ret->e_text) {
char *t = err_ret->e_text;
char *tt = sdump(t, strlen(t));
report(stderr, GT_("krb5_sendauth: %s [server says '%s']\n"),
error_message(retval), tt);
free(tt);
#else
if (err_ret && err_ret->text.length) {
char *tt = sdump(err_ret->text.data, err_ret->text.length);
report(stderr, GT_("krb5_sendauth: %s [server says '%s']\n"),
error_message(retval), tt);
free(tt);
#endif
krb5_free_error(context, err_ret);
} else
report(stderr, "krb5_sendauth: %s\n", error_message(retval));
return(PS_ERROR);
}
return 0;
}
#endif /* KERBEROS_V5 */
static void clean_skipped_list(struct idlist **skipped_list)
/* struct "idlist" contains no "prev" ptr; we must remove unused items first */
{
struct idlist *current=NULL, *prev=NULL, *tmp=NULL, *head=NULL;
prev = current = head = *skipped_list;
if (!head)
return;
do
{
/* if item has no reference, remove it */
if (current && current->val.status.mark == 0)
{
if (current == head) /* remove first item (head) */
{
head = current->next;
if (current->id) free(current->id);
free(current);
prev = current = head;
}
else /* remove middle/last item */
{
tmp = current->next;
prev->next = tmp;
if (current->id) free(current->id);
free(current);
current = tmp;
}
}
else /* skip this item */
{
prev = current;
current = current->next;
}
} while(current);
*skipped_list = head;
}
static void send_size_warnings(struct query *ctl)
/* send warning mail with skipped msg; reset msg count when user notified */
{
int size, nbr;
int msg_to_send = FALSE;
struct idlist *head=NULL, *current=NULL;
int max_warning_poll_count;
head = ctl->skipped;
if (!head)
return;
/* don't start a notification message unless we need to */
for (current = head; current; current = current->next)
if (current->val.status.num == 0 && current->val.status.mark)
msg_to_send = TRUE;
if (!msg_to_send)
return;
/*
* There's no good way to recover if we can't send notification mail,
* but it's not a disaster, either, since the skipped mail will not
* be deleted.
*/
if (open_warning_by_mail(ctl))
return;
stuff_warning(iana_charset, ctl, "Subject: ",
GT_("Fetchmail oversized-messages warning"));
stuff_warning(NULL, ctl, "", "%s", "");
if (ctl->limitflush)
stuff_warning(NULL, ctl, "",
GT_("The following oversized messages were deleted on server %s account %s:"),
ctl->server.pollname, ctl->remotename);
else
stuff_warning(NULL, ctl, "",
GT_("The following oversized messages remain on server %s account %s:"),
ctl->server.pollname, ctl->remotename);
stuff_warning(NULL, ctl, "", "%s", "");
if (run.poll_interval == 0)
max_warning_poll_count = 0;
else
max_warning_poll_count = ctl->warnings/run.poll_interval;
/* parse list of skipped msg, adding items to the mail */
for (current = head; current; current = current->next)
{
if (current->val.status.num == 0 && current->val.status.mark)
{
nbr = current->val.status.mark;
size = atoi(current->id);
if (ctl->limitflush)
stuff_warning(NULL, ctl, "",
ngettext(" %d message %d octets long deleted by fetchmail.",
" %d messages %d octets long deleted by fetchmail.", nbr),
nbr, size);
else
stuff_warning(NULL, ctl, "",
ngettext(" %d message %d octets long skipped by fetchmail.",
" %d messages %d octets long skipped by fetchmail.", nbr),
nbr, size);
}
current->val.status.num++;
current->val.status.mark = 0;
if (current->val.status.num >= max_warning_poll_count)
current->val.status.num = 0;
}
stuff_warning(NULL, ctl, "", "%s", "");
close_warning_by_mail(ctl, (struct msgblk *)NULL);
}
static void mark_oversized(struct query *ctl, int size)
/* mark a message oversized */
{
struct idlist *current=NULL, *tmp=NULL;
char sizestr[32];
int cnt;
/* convert size to string */
snprintf(sizestr, sizeof(sizestr), "%d", size);
/* build a list of skipped messages
* val.id = size of msg (string cnvt)
* val.status.num = warning_poll_count
* val.status.mask = nbr of msg this size
*/
current = ctl->skipped;
/* initialise warning_poll_count to the
* current value so that all new msg will
* be included in the next mail
*/
cnt = current ? current->val.status.num : 0;
/* if entry exists, increment the count */
if (current && (tmp = str_in_list(¤t, sizestr, FALSE)))
{
tmp->val.status.mark++;
}
/* otherwise, create a new entry */
/* initialise with current poll count */
else
{
tmp = save_str(&ctl->skipped, sizestr, 1);
tmp->val.status.num = cnt;
}
}
static int eat_trailer(int sock, struct query *ctl)
{
/* we only need this LF if we're printing ticker dots
* AND we are dumping protocol traces. */
if (outlevel >= O_VERBOSE && want_progress()) fputc('\n', stdout);
return (ctl->server.base_protocol->trail)(sock, ctl, tag);
}
static int fetch_messages(int mailserver_socket, struct query *ctl,
int count, int **msgsizes, int maxfetch,
int *fetches, int *dispatches, int *deletions,
int *transient_errors)
/* fetch messages in lockstep mode */
{
flag force_retrieval;
int num, firstnum = 1, lastnum = 0, err, len;
int fetchsizelimit = ctl->fetchsizelimit;
int msgsize;
int initialfetches = *fetches;
if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit))
{
/* for POP3, we can get the size of one mail only! Unfortunately, this
* protocol specific test cannot be done elsewhere as the protocol
* could be "auto". */
switch (ctl->server.protocol)
{
case P_POP3: case P_APOP: case P_RPOP:
fetchsizelimit = 1;
}
/* Time to allocate memory to store the sizes */
xfree(*msgsizes);
*msgsizes = (int *)xmalloc(sizeof(int) * fetchsizelimit);
}
/*
* What forces this code is that in POP2 and
* IMAP2bis you can't fetch a message without
* having it marked `seen'. In POP3 and IMAP4, on the
* other hand, you can (peek_capable is set by
* each driver module to convey this; it's not a
* method constant because of the difference between
* IMAP2bis and IMAP4, and because POP3 doesn't peek
* if fetchall is on).
*
* The result of being unable to peek is that if there's
* any kind of transient error (DNS lookup failure, or
* sendmail refusing delivery due to process-table limits)
* the message will be marked "seen" on the server without
* having been delivered. This is not a big problem if
* fetchmail is running in foreground, because the user
* will see a "skipped" message when it next runs and get
* clued in.
*
* But in daemon mode this leads to the message
* being silently ignored forever. This is not
* acceptable.
*
* We compensate for this by checking the error
* count from the previous pass and forcing all
* messages to be considered new if it's nonzero.
*/
force_retrieval = !peek_capable && (ctl->errcount > 0);
for (num = 1; num <= count; num++)
{
flag suppress_delete = FALSE;
flag suppress_forward = FALSE;
flag suppress_readbody = FALSE;
flag retained = FALSE;
int msgcode = MSGLEN_UNKNOWN;
/* check if the message is old
* Note: the size of the message may not be known here */
if (ctl->fetchall || force_retrieval) {
/* empty */
} else {
if (ctl->server.base_protocol->is_old && (ctl->server.base_protocol->is_old)(mailserver_socket,ctl,num)) {
msgcode = MSGLEN_OLD;
}
}
if (msgcode == MSGLEN_OLD)
{
/*
* To avoid flooding the logs when using --keep, report
* skipping for old messages only when --flush is on.
*/
if (outlevel > O_SILENT && ctl->flush)
{
report_build(stdout,
GT_("skipping message %s@%s:%d"),
ctl->remotename, ctl->server.truename, num);
}
goto flagthemail;
}
if (ctl->server.base_protocol->getpartialsizes && NUM_NONZERO(fetchsizelimit) &&
lastnum < num)
{
/* Instead of getting the sizes of all mails at the start, we get
* the sizes in blocks of fetchsizelimit. This leads to better
* performance when there are too many mails (say, 10000) in
* the mailbox and either we are not getting all the mails at
* one go (--fetchlimit 100) or there is a frequent socket
* error while just getting the sizes of all mails! */
int i;
int oldstage = stage;
firstnum = num;
lastnum = num + fetchsizelimit - 1;
if (lastnum > count)
lastnum = count;
if (*msgsizes)
for (i = 0; i < fetchsizelimit; i++)
(*msgsizes)[i] = 0;
stage = STAGE_GETSIZES;
err = (ctl->server.base_protocol->getpartialsizes)(mailserver_socket, num, lastnum, *msgsizes);
if (err != 0) {
return err;
}
stage = oldstage;
}
msgsize = *msgsizes ? (*msgsizes)[num-firstnum] : 0;
/* check if the message is oversized */
if (NUM_NONZERO(ctl->limit) && (msgsize > ctl->limit))
msgcode = MSGLEN_TOOLARGE;
/* else if (msgsize == 512)
msgcode = MSGLEN_OLD; (hmh) sample code to skip message */
if (msgcode < 0)
{
if (msgcode == MSGLEN_TOOLARGE)
{
mark_oversized(ctl, msgsize);
if (!ctl->limitflush)
suppress_delete = TRUE;
}
if (outlevel > O_SILENT)
{
/* old messages are already handled above */
report_build(stdout,
GT_("skipping message %s@%s:%d (%d octets)"),
ctl->remotename, ctl->server.truename, num,
msgsize);
switch (msgcode)
{
case MSGLEN_INVALID:
/*
* Invalid lengths are produced by Post Office/NT's
* annoying habit of randomly prepending bogus
* LIST items of length -1. Patrick Audley
* <[email protected]> tells us: LIST shows a
* size of -1, RETR and TOP return "-ERR
* System error - couldn't open message", and
* DELE succeeds but doesn't actually delete
* the message.
*/
report_build(stdout, GT_(" (length -1)"));
break;
case MSGLEN_TOOLARGE:
report_build(stdout, GT_(" (oversized)"));
break;
}
}
}
else
{
/* XXX FIXME: make this one variable, wholesize and
separatefetchbody query the same variable just with
inverted logic */
flag wholesize = !ctl->server.base_protocol->fetch_body;
flag separatefetchbody = (ctl->server.base_protocol->fetch_body) ? TRUE : FALSE;
/* request a message */
err = (ctl->server.base_protocol->fetch_headers)(mailserver_socket,ctl,num, &len);
if (err == PS_TRANSIENT) /* server is probably Exchange */
{
report(stdout,
GT_("couldn't fetch headers, message %s@%s:%d (%d octets)\n"),
ctl->remotename, ctl->server.truename, num,
msgsize);
(*transient_errors)++;
continue;
}
else if (err != 0)
return(err);
/* -1 means we didn't see a size in the response */
if (len == -1)
{
len = msgsize;
wholesize = TRUE;
}
if (outlevel > O_SILENT)
{
report_build(stdout, GT_("reading message %s@%s:%d of %d"),
ctl->remotename, ctl->server.truename,
num, count);
if (len > 0)
report_build(stdout, wholesize ? GT_(" (%d octets)")
: GT_(" (%d header octets)"), len);
if (want_progress()) {
/* flush and add a blank to append ticker dots */
report_flush(stdout);
putchar(' ');
}
}
/*
* Read the message headers and ship them to the
* output sink.
*/
err = readheaders(mailserver_socket, len, msgsize,
ctl, num,
/* pass the suppress_readbody flag only if the underlying
* protocol does not fetch the body separately */
separatefetchbody ? 0 : &suppress_readbody);
if (err == PS_RETAINED)
suppress_forward = suppress_delete = retained = TRUE;
else if (err == PS_TRANSIENT)
{
suppress_delete = suppress_forward = TRUE;
(*transient_errors)++;
}
else if (err == PS_REFUSED)
suppress_forward = TRUE;
else if (err)
return(err);
/* tell server we got it OK and resynchronize */
if (separatefetchbody && ctl->server.base_protocol->trail)
{
err = eat_trailer(mailserver_socket, ctl);
if (err) return(err);
}
/* do not read the body which is not being forwarded only if
* the underlying protocol allows the body to be fetched
* separately */
if (separatefetchbody && suppress_forward)
suppress_readbody = TRUE;
/*
* If we're using IMAP4 or something else that
* can fetch headers separately from bodies,
* it's time to request the body now. This
* fetch may be skipped if we got an anti-spam
* or other PS_REFUSED error response during
* readheaders.
*/
if (!suppress_readbody)
{
if (separatefetchbody)
{
len = -1;
if ((err=(ctl->server.base_protocol->fetch_body)(mailserver_socket,ctl,num,&len)))
return(err);
/*
* Work around a bug in Novell's
* broken GroupWise IMAP server;
* its body FETCH response is missing
* the required length for the data
* string. This violates RFC2060.
*/
if (len == -1)
len = msgsize - msgblk.msglen;
if (!wholesize) {
if (outlevel > O_SILENT)
report_build(stdout,
GT_(" (%d body octets)"), len);
if (want_progress()) {
report_flush(stdout);
putchar(' ');
}
}
}
/* process the body now */
err = readbody(mailserver_socket,
ctl,
!suppress_forward,
len);
if (err == PS_TRANSIENT)
{
suppress_delete = suppress_forward = TRUE;
(*transient_errors)++;
}
else if (err)
return(err);
/* tell server we got it OK and resynchronize */
if (ctl->server.base_protocol->trail) {
err = eat_trailer(mailserver_socket, ctl);
if (err) return(err);
}
}
/* count # messages forwarded on this pass */
if (!suppress_forward)
(*dispatches)++;
/*
* Check to see if the numbers matched?
*
* Yes, some servers foo this up horribly.
* All IMAP servers seem to get it right, and
* so does Eudora QPOP at least in 2.xx
* versions.
*
* Microsoft Exchange gets it completely
* wrong, reporting compressed rather than
* actual sizes (so the actual length of
* message is longer than the reported size).
* Another fine example of Microsoft brain death!
*
* Some older POP servers, like the old UCB
* POP server and the pre-QPOP QUALCOMM
* versions, report a longer size in the LIST
* response than actually gets shipped up.
* It's unclear what is going on here, as the
* QUALCOMM server (at least) seems to be
* reporting the on-disk size correctly.
*
* qmail-pop3d also goofs up message sizes and does not
* count the line end characters properly.
*/
if (msgblk.msglen != msgsize)
{
if (outlevel >= O_DEBUG)
report(stdout,
GT_("message %s@%s:%d was not the expected length (%d actual != %d expected)\n"),
ctl->remotename, ctl->server.truename, num,
msgblk.msglen, msgsize);
}
/* end-of-message processing starts here */
if (!close_sink(ctl, &msgblk, !suppress_forward))
{
ctl->errcount++;
suppress_delete = TRUE;
}
if (!retained)
(*fetches)++;
}
flagthemail:
/*
* At this point in flow of control,
* either we've bombed on a protocol error
* or had delivery refused by the SMTP server
* or we've seen `accepted for delivery' and the message is shipped.
* It's safe to mark the message seen and delete it on the server now.
*/
/* in softbounce mode, suppress deletion and marking as seen */
if (suppress_forward)
suppress_delete = suppress_delete || run.softbounce;
/* maybe we delete this message now? */
if (retained)
{
if (outlevel > O_SILENT)
report_complete(stdout, GT_(" retained\n"));
}
else if (ctl->server.base_protocol->delete_msg
&& !suppress_delete
&& ((msgcode >= 0 && !ctl->keep)
|| (msgcode == MSGLEN_OLD && ctl->flush)
|| (msgcode == MSGLEN_TOOLARGE && ctl->limitflush)))
{
(*deletions)++;
if (outlevel > O_SILENT)
report_complete(stdout, GT_(" flushed\n"));
err = (ctl->server.base_protocol->delete_msg)(mailserver_socket, ctl, num);
if (err != 0)
return(err);
}
else
{
/*
* To avoid flooding the logs when using --keep, report
* skipping of new messages only.
*/
if (outlevel > O_SILENT && msgcode != MSGLEN_OLD)
report_complete(stdout, GT_(" not flushed\n"));
/* maybe we mark this message as seen now? */
if (ctl->server.base_protocol->mark_seen
&& !suppress_delete
&& (msgcode >= 0 && ctl->keep))
{
err = (ctl->server.base_protocol->mark_seen)(mailserver_socket, ctl, num);
if (err != 0)
return(err);
}
}
/* perhaps this as many as we're ready to handle */
if (maxfetch && maxfetch <= *fetches && num < count)
{
int remcount = count - (*fetches - initialfetches);
report(stdout,
ngettext("fetchlimit %d reached; %d message left on server %s account %s\n",
"fetchlimit %d reached; %d messages left on server %s account %s\n", remcount),
maxfetch, remcount, ctl->server.truename, ctl->remotename);
return(PS_MAXFETCH);
}
} /* for (num = 1; num <= count; num++) */
return(PS_SUCCESS);
}
/* retrieve messages from server using given protocol method table */
static int do_session(
/* parsed options with merged-in defaults */
struct query *ctl,
/* protocol method table */
const struct method *proto,
/* maximum number of messages to fetch */
const int maxfetch)
{
static int *msgsizes;
volatile int err, mailserver_socket = -1; /* pacifies -Wall */
int tmperr;
int deletions = 0, js;
const char *msg;
SIGHANDLERTYPE alrmsave;
ctl->server.base_protocol = proto;
msgsizes = NULL;
pass = 0;
err = 0;
init_transact(proto);
/* set up the server-nonresponse timeout */
alrmsave = set_signal_handler(SIGALRM, timeout_handler);
mytimeout = ctl->server.timeout;
if ((js = sigsetjmp(restart,1)))
{
/* exception caught */
sigset_t allsigs;
sigfillset(&allsigs);
sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
if (ai0) {
fm_freeaddrinfo(ai0); ai0 = NULL;
}
if (ai1) {
fm_freeaddrinfo(ai1); ai1 = NULL;
}
if (js == THROW_TIMEOUT)
{
if (phase == OPEN_WAIT)
report(stdout,
GT_("timeout after %d seconds waiting to connect to server %s.\n"),
ctl->server.timeout, ctl->server.pollname);
else if (phase == SERVER_WAIT)
report(stdout,
GT_("timeout after %d seconds waiting for server %s.\n"),
ctl->server.timeout, ctl->server.pollname);
else if (phase == FORWARDING_WAIT)
report(stdout,
GT_("timeout after %d seconds waiting for %s.\n"),
ctl->server.timeout,
ctl->mda ? "MDA" : "SMTP");
else if (phase == LISTENER_WAIT)
report(stdout,
GT_("timeout after %d seconds waiting for listener to respond.\n"), ctl->server.timeout);
else
report(stdout,
GT_("timeout after %d seconds.\n"), ctl->server.timeout);
/*
* If we've exceeded our threshold for consecutive timeouts,
* try to notify the user, then mark the connection wedged.
* Don't do this if the connection can idle, though; idle
* timeouts just mean the frequency of mail is low.
*/
if (timeoutcount > MAX_TIMEOUTS
&& !open_warning_by_mail(ctl))
{
stuff_warning(iana_charset, ctl, "Subject: ",
GT_("fetchmail sees repeated timeouts"));
stuff_warning(NULL, ctl, "", "%s", "");
stuff_warning(NULL, ctl, "",
GT_("Fetchmail saw more than %d timeouts while attempting to get mail from %s@%s.\n"),
MAX_TIMEOUTS,
ctl->remotename, ctl->server.truename);
stuff_warning(NULL, ctl, "",
GT_("This could mean that your mailserver is stuck, or that your SMTP\n" \
"server is wedged, or that your mailbox file on the server has been\n" \
"corrupted by a server error. You can run `fetchmail -v -v' to\n" \
"diagnose the problem.\n\n" \
"Fetchmail won't poll this mailbox again until you restart it.\n"));
close_warning_by_mail(ctl, (struct msgblk *)NULL);
ctl->wedged = TRUE;
}
}
err = PS_SOCKET;
goto cleanUp;
}
else
{
/* sigsetjmp returned zero -> normal operation */
char buf[MSGBUFSIZE+1], *realhost;
int count, newm;
int fetches, dispatches, transient_errors, oldphase;
struct idlist *idp;
/* execute pre-initialization command, if any */
if (ctl->preconnect && (err = system(ctl->preconnect)))
{
if (WIFSIGNALED(err))
report(stderr,
GT_("pre-connection command terminated with signal %d\n"), WTERMSIG(err));
else
report(stderr,
GT_("pre-connection command failed with status %d\n"), WEXITSTATUS(err));
err = PS_SYNTAX;
goto closeUp;
}
/* open a socket to the mail server */
oldphase = phase;
phase = OPEN_WAIT;
set_timeout(mytimeout);
#ifdef HAVE_PKG_hesiod
/* If either the pollname or vianame are "hesiod" we want to
lookup the user's hesiod pobox host */
if (!strcasecmp(ctl->server.queryname, "hesiod")) {
struct hes_postoffice *hes_p;
hes_p = hes_getmailhost(ctl->remotename);
if (hes_p != NULL && strcmp(hes_p->po_type, "POP") == 0) {
free(ctl->server.queryname);
ctl->server.queryname = xstrdup(hes_p->po_host);
if (ctl->server.via)
free(ctl->server.via);
ctl->server.via = xstrdup(hes_p->po_host);
} else {
report(stderr,
GT_("couldn't find HESIOD pobox for %s\n"),
ctl->remotename);
}
}
#endif /* HESIOD */
/*
* Canonicalize the server truename for later use. This also
* functions as a probe for whether the mailserver is accessible.
* We try it on each poll cycle until we get a result. This way,
* fetchmail won't fail if started up when the network is inaccessible.
*/
if (ctl->server.dns && !ctl->server.trueaddr)
{
if (ctl->server.lead_server)
{
char *leadname = ctl->server.lead_server->truename;
/* prevent core dump from ill-formed or duplicate entry */
if (!leadname)
{
report(stderr, GT_("Lead server has no name.\n"));
err = PS_DNS;
set_timeout(0);
phase = oldphase;
goto closeUp;
}
xfree(ctl->server.truename);
ctl->server.truename = xstrdup(leadname);