]> code.delx.au - gnu-emacs/blob - lib-src/pop.c
Rework C source files to avoid ^(
[gnu-emacs] / lib-src / pop.c
1 /* pop.c: client routines for talking to a POP3-protocol post-office server
2
3 Copyright (C) 1991, 1993, 1996-1997, 1999, 2001-2016 Free Software
4 Foundation, Inc.
5
6 Author: Jonathan Kamens <jik@security.ov.com>
7
8 This file is part of GNU Emacs.
9
10 GNU Emacs is free software: you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or (at
13 your option) any later version.
14
15 GNU Emacs is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
22
23
24 #include <config.h>
25
26 #ifdef MAIL_USE_POP
27
28 #include <sys/types.h>
29 #ifdef WINDOWSNT
30 #include "ntlib.h"
31 #include <winsock.h>
32 #undef SOCKET_ERROR
33 #define RECV(s,buf,len,flags) recv (s,buf,len,flags)
34 #define SEND(s,buf,len,flags) send (s,buf,len,flags)
35 #define CLOSESOCKET(s) closesocket (s)
36 #else
37 #include <netinet/in.h>
38 #include <sys/socket.h>
39 #define RECV(s,buf,len,flags) read (s,buf,len)
40 #define SEND(s,buf,len,flags) write (s,buf,len)
41 #define CLOSESOCKET(s) close (s)
42 #endif
43 #include <pop.h>
44
45 #ifdef HESIOD
46 #include <hesiod.h>
47 /*
48 * It really shouldn't be necessary to put this declaration here, but
49 * the version of hesiod.h that Athena has installed in release 7.2
50 * doesn't declare this function; I don't know if the 7.3 version of
51 * hesiod.h does.
52 */
53 extern struct servent *hes_getservbyname (/* char *, char * */);
54 #endif
55
56 #include <pwd.h>
57 #include <netdb.h>
58 #include <errno.h>
59 #include <stdio.h>
60 #include <string.h>
61 #include <unistd.h>
62
63 #ifdef KERBEROS
64 # ifdef HAVE_KRB5_H
65 # include <krb5.h>
66 # endif
67 # ifdef HAVE_KRB_H
68 # include <krb.h>
69 # else
70 # ifdef HAVE_KERBEROSIV_KRB_H
71 # include <kerberosIV/krb.h>
72 # else
73 # ifdef HAVE_KERBEROS_KRB_H
74 # include <kerberos/krb.h>
75 # endif
76 # endif
77 # endif
78 # ifdef HAVE_COM_ERR_H
79 # include <com_err.h>
80 # endif
81 #endif /* KERBEROS */
82
83 #include <min-max.h>
84
85 #ifdef KERBEROS
86 #ifndef KERBEROS5
87 extern int krb_sendauth (/* long, int, KTEXT, char *, char *, char *,
88 u_long, MSG_DAT *, CREDENTIALS *, Key_schedule,
89 struct sockaddr_in *, struct sockaddr_in *,
90 char * */);
91 extern char *krb_realmofhost (/* char * */);
92 #endif /* ! KERBEROS5 */
93 #endif /* KERBEROS */
94
95 #ifndef WINDOWSNT
96 #ifndef HAVE_H_ERRNO
97 extern int h_errno;
98 #endif
99 #endif
100
101 static int socket_connection (char *, int);
102 static int pop_getline (popserver, char **);
103 static int sendline (popserver, const char *);
104 static int fullwrite (int, char *, int);
105 static int getok (popserver);
106 #if 0
107 static int gettermination (popserver);
108 #endif
109 static void pop_trash (popserver);
110 static char *find_crlf (char *, int);
111
112 #define ERROR_MAX 160 /* a pretty arbitrary size, but needs
113 to be bigger than the original
114 value of 80 */
115 #define POP_PORT 110
116 #define POP_SERVICE "pop3" /* we don't want the POP2 port! */
117 #ifdef KERBEROS
118 #define KPOP_PORT 1109
119 #define KPOP_SERVICE "kpop" /* never used: look for 20060515 to see why */
120 #endif
121
122 char pop_error[ERROR_MAX];
123 bool pop_debug = false;
124
125 /*
126 * Function: pop_open (char *host, char *username, char *password,
127 * int flags)
128 *
129 * Purpose: Establishes a connection with a post-office server, and
130 * completes the authorization portion of the session.
131 *
132 * Arguments:
133 * host The server host with which the connection should be
134 * established. Optional. If omitted, internal
135 * heuristics will be used to determine the server host,
136 * if possible.
137 * username
138 * The username of the mail-drop to access. Optional.
139 * If omitted, internal heuristics will be used to
140 * determine the username, if possible.
141 * password
142 * The password to use for authorization. If omitted,
143 * internal heuristics will be used to determine the
144 * password, if possible.
145 * flags A bit mask containing flags controlling certain
146 * functions of the routine. Valid flags are defined in
147 * the file pop.h
148 *
149 * Return value: Upon successful establishment of a connection, a
150 * non-null popserver will be returned. Otherwise, null will be
151 * returned, and the string variable pop_error will contain an
152 * explanation of the error.
153 */
154 popserver
155 pop_open (char *host, char *username, char *password, int flags)
156 {
157 int sock;
158 popserver server;
159
160 /* Determine the user name */
161 if (! username)
162 {
163 username = getenv ("USER");
164 if (! (username && *username))
165 {
166 username = getlogin ();
167 if (! (username && *username))
168 {
169 struct passwd *passwd;
170 passwd = getpwuid (getuid ());
171 if (passwd && passwd->pw_name && *passwd->pw_name)
172 {
173 username = passwd->pw_name;
174 }
175 else
176 {
177 strcpy (pop_error, "Could not determine username");
178 return (0);
179 }
180 }
181 }
182 }
183
184 /*
185 * Determine the mail host.
186 */
187
188 if (! host)
189 {
190 host = getenv ("MAILHOST");
191 }
192
193 #ifdef HESIOD
194 if ((! host) && (! (flags & POP_NO_HESIOD)))
195 {
196 struct hes_postoffice *office;
197 office = hes_getmailhost (username);
198 if (office && office->po_type && (! strcmp (office->po_type, "POP"))
199 && office->po_name && *office->po_name && office->po_host
200 && *office->po_host)
201 {
202 host = office->po_host;
203 username = office->po_name;
204 }
205 }
206 #endif
207
208 #ifdef MAILHOST
209 if (! host)
210 {
211 host = MAILHOST;
212 }
213 #endif
214
215 if (! host)
216 {
217 strcpy (pop_error, "Could not determine POP server");
218 return (0);
219 }
220
221 /* Determine the password */
222 #ifdef KERBEROS
223 #define DONT_NEED_PASSWORD (! (flags & POP_NO_KERBEROS))
224 #else
225 #define DONT_NEED_PASSWORD 0
226 #endif
227
228 if ((! password) && (! DONT_NEED_PASSWORD))
229 {
230 if (! (flags & POP_NO_GETPASS))
231 {
232 password = getpass ("Enter POP password:");
233 }
234 if (! password)
235 {
236 strcpy (pop_error, "Could not determine POP password");
237 return (0);
238 }
239 }
240 if (password) /* always true, detected 20060515 */
241 flags |= POP_NO_KERBEROS;
242 else
243 password = username; /* dead code, detected 20060515 */
244 /** "kpop" service is never used: look for 20060515 to see why **/
245
246 sock = socket_connection (host, flags);
247 if (sock == -1)
248 return (0);
249
250 server = (popserver) malloc (sizeof (struct _popserver));
251 if (! server)
252 {
253 strcpy (pop_error, "Out of memory in pop_open");
254 return (0);
255 }
256 server->buffer = (char *) malloc (GETLINE_MIN);
257 if (! server->buffer)
258 {
259 strcpy (pop_error, "Out of memory in pop_open");
260 free ((char *) server);
261 return (0);
262 }
263
264 server->file = sock;
265 server->data = 0;
266 server->buffer_index = 0;
267 server->buffer_size = GETLINE_MIN;
268 server->in_multi = false;
269 server->trash_started = false;
270
271 if (getok (server))
272 return (0);
273
274 /*
275 * I really shouldn't use the pop_error variable like this, but....
276 */
277 if (strlen (username) > ERROR_MAX - 6)
278 {
279 pop_close (server);
280 strcpy (pop_error,
281 "Username too long; recompile pop.c with larger ERROR_MAX");
282 return (0);
283 }
284 sprintf (pop_error, "USER %s", username);
285
286 if (sendline (server, pop_error) || getok (server))
287 {
288 return (0);
289 }
290
291 if (strlen (password) > ERROR_MAX - 6)
292 {
293 pop_close (server);
294 strcpy (pop_error,
295 "Password too long; recompile pop.c with larger ERROR_MAX");
296 return (0);
297 }
298 sprintf (pop_error, "PASS %s", password);
299
300 if (sendline (server, pop_error) || getok (server))
301 {
302 return (0);
303 }
304
305 return (server);
306 }
307
308 /*
309 * Function: pop_stat
310 *
311 * Purpose: Issue the STAT command to the server and return (in the
312 * value parameters) the number of messages in the maildrop and
313 * the total size of the maildrop.
314 *
315 * Return value: 0 on success, or non-zero with an error in pop_error
316 * in failure.
317 *
318 * Side effects: On failure, may make further operations on the
319 * connection impossible.
320 */
321 int
322 pop_stat (popserver server, int *count, int *size)
323 {
324 char *fromserver;
325 char *end_ptr;
326
327 if (server->in_multi)
328 {
329 strcpy (pop_error, "In multi-line query in pop_stat");
330 return (-1);
331 }
332
333 if (sendline (server, "STAT") || (pop_getline (server, &fromserver) < 0))
334 return (-1);
335
336 if (strncmp (fromserver, "+OK ", 4))
337 {
338 if (0 == strncmp (fromserver, "-ERR", 4))
339 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
340 else
341 {
342 strcpy (pop_error,
343 "Unexpected response from POP server in pop_stat");
344 pop_trash (server);
345 }
346 return (-1);
347 }
348
349 errno = 0;
350 *count = strtol (&fromserver[4], &end_ptr, 10);
351 /* Check validity of string-to-integer conversion. */
352 if (fromserver + 4 == end_ptr || *end_ptr != ' ' || errno)
353 {
354 strcpy (pop_error, "Unexpected response from POP server in pop_stat");
355 pop_trash (server);
356 return (-1);
357 }
358
359 fromserver = end_ptr;
360
361 errno = 0;
362 *size = strtol (fromserver + 1, &end_ptr, 10);
363 if (fromserver + 1 == end_ptr || errno)
364 {
365 strcpy (pop_error, "Unexpected response from POP server in pop_stat");
366 pop_trash (server);
367 return (-1);
368 }
369
370 return (0);
371 }
372
373 /*
374 * Function: pop_list
375 *
376 * Purpose: Performs the POP "list" command and returns (in value
377 * parameters) two malloc'd zero-terminated arrays -- one of
378 * message IDs, and a parallel one of sizes.
379 *
380 * Arguments:
381 * server The pop connection to talk to.
382 * message The number of the one message about which to get
383 * information, or 0 to get information about all
384 * messages.
385 *
386 * Return value: 0 on success, non-zero with error in pop_error on
387 * failure.
388 *
389 * Side effects: On failure, may make further operations on the
390 * connection impossible.
391 */
392 int
393 pop_list (popserver server, int message, int **IDs, int **sizes)
394 {
395 int how_many, i;
396 char *fromserver;
397
398 if (server->in_multi)
399 {
400 strcpy (pop_error, "In multi-line query in pop_list");
401 return (-1);
402 }
403
404 if (message)
405 how_many = 1;
406 else
407 {
408 int count, size;
409 if (pop_stat (server, &count, &size))
410 return (-1);
411 how_many = count;
412 }
413
414 *IDs = (int *) malloc ((how_many + 1) * sizeof (int));
415 *sizes = (int *) malloc ((how_many + 1) * sizeof (int));
416 if (! (*IDs && *sizes))
417 {
418 strcpy (pop_error, "Out of memory in pop_list");
419 return (-1);
420 }
421
422 if (message)
423 {
424 sprintf (pop_error, "LIST %d", message);
425 if (sendline (server, pop_error))
426 {
427 free ((char *) *IDs);
428 free ((char *) *sizes);
429 return (-1);
430 }
431 if (pop_getline (server, &fromserver) < 0)
432 {
433 free ((char *) *IDs);
434 free ((char *) *sizes);
435 return (-1);
436 }
437 if (strncmp (fromserver, "+OK ", 4))
438 {
439 if (! strncmp (fromserver, "-ERR", 4))
440 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
441 else
442 {
443 strcpy (pop_error,
444 "Unexpected response from server in pop_list");
445 pop_trash (server);
446 }
447 free ((char *) *IDs);
448 free ((char *) *sizes);
449 return (-1);
450 }
451 (*IDs)[0] = atoi (&fromserver[4]);
452 fromserver = strchr (&fromserver[4], ' ');
453 if (! fromserver)
454 {
455 strcpy (pop_error,
456 "Badly formatted response from server in pop_list");
457 pop_trash (server);
458 free ((char *) *IDs);
459 free ((char *) *sizes);
460 return (-1);
461 }
462 (*sizes)[0] = atoi (fromserver);
463 (*IDs)[1] = (*sizes)[1] = 0;
464 return (0);
465 }
466 else
467 {
468 if (pop_multi_first (server, "LIST", &fromserver))
469 {
470 free ((char *) *IDs);
471 free ((char *) *sizes);
472 return (-1);
473 }
474 for (i = 0; i < how_many; i++)
475 {
476 if (pop_multi_next (server, &fromserver) <= 0)
477 {
478 free ((char *) *IDs);
479 free ((char *) *sizes);
480 return (-1);
481 }
482 (*IDs)[i] = atoi (fromserver);
483 fromserver = strchr (fromserver, ' ');
484 if (! fromserver)
485 {
486 strcpy (pop_error,
487 "Badly formatted response from server in pop_list");
488 free ((char *) *IDs);
489 free ((char *) *sizes);
490 pop_trash (server);
491 return (-1);
492 }
493 (*sizes)[i] = atoi (fromserver);
494 }
495 if (pop_multi_next (server, &fromserver) < 0)
496 {
497 free ((char *) *IDs);
498 free ((char *) *sizes);
499 return (-1);
500 }
501 else if (fromserver)
502 {
503 strcpy (pop_error,
504 "Too many response lines from server in pop_list");
505 free ((char *) *IDs);
506 free ((char *) *sizes);
507 return (-1);
508 }
509 (*IDs)[i] = (*sizes)[i] = 0;
510 return (0);
511 }
512 }
513
514 /*
515 * Function: pop_retrieve
516 *
517 * Purpose: Retrieve a specified message from the maildrop.
518 *
519 * Arguments:
520 * server The server to retrieve from.
521 * message The message number to retrieve.
522 * markfrom
523 * If true, then mark the string "From " at the beginning
524 * of lines with '>'.
525 * msg_buf Output parameter to which a buffer containing the
526 * message is assigned.
527 *
528 * Return value: The number of bytes in msg_buf, which may contain
529 * embedded nulls, not including its final null, or -1 on error
530 * with pop_error set.
531 *
532 * Side effects: May kill connection on error.
533 */
534 int
535 pop_retrieve (popserver server, int message, int markfrom, char **msg_buf)
536 {
537 int *IDs, *sizes, bufsize, fromcount = 0, cp = 0;
538 char *ptr, *fromserver;
539 int ret;
540
541 if (server->in_multi)
542 {
543 strcpy (pop_error, "In multi-line query in pop_retrieve");
544 return (-1);
545 }
546
547 if (pop_list (server, message, &IDs, &sizes))
548 return (-1);
549
550 if (pop_retrieve_first (server, message, &fromserver))
551 {
552 return (-1);
553 }
554
555 /*
556 * The "5" below is an arbitrary constant -- I assume that if
557 * there are "From" lines in the text to be marked, there
558 * probably won't be more than 5 of them. If there are, I
559 * allocate more space for them below.
560 */
561 bufsize = sizes[0] + (markfrom ? 5 : 0);
562 ptr = (char *)malloc (bufsize);
563 free ((char *) IDs);
564 free ((char *) sizes);
565
566 if (! ptr)
567 {
568 strcpy (pop_error, "Out of memory in pop_retrieve");
569 pop_retrieve_flush (server);
570 return (-1);
571 }
572
573 while ((ret = pop_retrieve_next (server, &fromserver)) >= 0)
574 {
575 if (! fromserver)
576 {
577 ptr[cp] = '\0';
578 *msg_buf = ptr;
579 return (cp);
580 }
581 if (markfrom && fromserver[0] == 'F' && fromserver[1] == 'r' &&
582 fromserver[2] == 'o' && fromserver[3] == 'm' &&
583 fromserver[4] == ' ')
584 {
585 if (++fromcount == 5)
586 {
587 bufsize += 5;
588 ptr = (char *)realloc (ptr, bufsize);
589 if (! ptr)
590 {
591 strcpy (pop_error, "Out of memory in pop_retrieve");
592 pop_retrieve_flush (server);
593 return (-1);
594 }
595 fromcount = 0;
596 }
597 ptr[cp++] = '>';
598 }
599 memcpy (&ptr[cp], fromserver, ret);
600 cp += ret;
601 ptr[cp++] = '\n';
602 }
603
604 free (ptr);
605 return (-1);
606 }
607
608 int
609 pop_retrieve_first (popserver server, int message, char **response)
610 {
611 sprintf (pop_error, "RETR %d", message);
612 return (pop_multi_first (server, pop_error, response));
613 }
614
615 /*
616 Returns a negative number on error, 0 to indicate that the data has
617 all been read (i.e., the server has returned a "." termination
618 line), or a positive number indicating the number of bytes in the
619 returned buffer (which is null-terminated and may contain embedded
620 nulls, but the returned bytecount doesn't include the final null).
621 */
622
623 int
624 pop_retrieve_next (popserver server, char **line)
625 {
626 return (pop_multi_next (server, line));
627 }
628
629 int
630 pop_retrieve_flush (popserver server)
631 {
632 return (pop_multi_flush (server));
633 }
634
635 int
636 pop_top_first (popserver server, int message, int lines, char **response)
637 {
638 sprintf (pop_error, "TOP %d %d", message, lines);
639 return (pop_multi_first (server, pop_error, response));
640 }
641
642 /*
643 Returns a negative number on error, 0 to indicate that the data has
644 all been read (i.e., the server has returned a "." termination
645 line), or a positive number indicating the number of bytes in the
646 returned buffer (which is null-terminated and may contain embedded
647 nulls, but the returned bytecount doesn't include the final null).
648 */
649
650 int
651 pop_top_next (popserver server, char **line)
652 {
653 return (pop_multi_next (server, line));
654 }
655
656 int
657 pop_top_flush (popserver server)
658 {
659 return (pop_multi_flush (server));
660 }
661
662 int
663 pop_multi_first (popserver server, const char *command, char **response)
664 {
665 if (server->in_multi)
666 {
667 strcpy (pop_error,
668 "Already in multi-line query in pop_multi_first");
669 return (-1);
670 }
671
672 if (sendline (server, command) || (pop_getline (server, response) < 0))
673 {
674 return (-1);
675 }
676
677 if (0 == strncmp (*response, "-ERR", 4))
678 {
679 snprintf (pop_error, ERROR_MAX, "%s", *response);
680 return (-1);
681 }
682 else if (0 == strncmp (*response, "+OK", 3))
683 {
684 for (*response += 3; **response == ' '; (*response)++) /* empty */;
685 server->in_multi = true;
686 return (0);
687 }
688 else
689 {
690 strcpy (pop_error,
691 "Unexpected response from server in pop_multi_first");
692 return (-1);
693 }
694 }
695
696 /*
697 Read the next line of data from SERVER and place a pointer to it
698 into LINE. Return -1 on error, 0 if there are no more lines to read
699 (i.e., the server has returned a line containing only "."), or a
700 positive number indicating the number of bytes in the LINE buffer
701 (not including the final null). The data in that buffer may contain
702 embedded nulls, but does not contain the final CRLF. When returning
703 0, LINE is set to null. */
704
705 int
706 pop_multi_next (popserver server, char **line)
707 {
708 char *fromserver;
709 int ret;
710
711 if (! server->in_multi)
712 {
713 strcpy (pop_error, "Not in multi-line query in pop_multi_next");
714 return (-1);
715 }
716
717 if ((ret = pop_getline (server, &fromserver)) < 0)
718 {
719 return (-1);
720 }
721
722 if (fromserver[0] == '.')
723 {
724 if (! fromserver[1])
725 {
726 *line = 0;
727 server->in_multi = false;
728 return (0);
729 }
730 else
731 {
732 *line = fromserver + 1;
733 return (ret - 1);
734 }
735 }
736 else
737 {
738 *line = fromserver;
739 return (ret);
740 }
741 }
742
743 int
744 pop_multi_flush (popserver server)
745 {
746 char *line;
747 int ret;
748
749 if (! server->in_multi)
750 {
751 return (0);
752 }
753
754 while ((ret = pop_multi_next (server, &line)))
755 {
756 if (ret < 0)
757 return (-1);
758 }
759
760 return (0);
761 }
762
763 /* Function: pop_delete
764 *
765 * Purpose: Delete a specified message.
766 *
767 * Arguments:
768 * server Server from which to delete the message.
769 * message Message to delete.
770 *
771 * Return value: 0 on success, non-zero with error in pop_error
772 * otherwise.
773 */
774 int
775 pop_delete (popserver server, int message)
776 {
777 if (server->in_multi)
778 {
779 strcpy (pop_error, "In multi-line query in pop_delete");
780 return (-1);
781 }
782
783 sprintf (pop_error, "DELE %d", message);
784
785 if (sendline (server, pop_error) || getok (server))
786 return (-1);
787
788 return (0);
789 }
790
791 /*
792 * Function: pop_noop
793 *
794 * Purpose: Send a noop command to the server.
795 *
796 * Argument:
797 * server The server to send to.
798 *
799 * Return value: 0 on success, non-zero with error in pop_error
800 * otherwise.
801 *
802 * Side effects: Closes connection on error.
803 */
804 int
805 pop_noop (popserver server)
806 {
807 if (server->in_multi)
808 {
809 strcpy (pop_error, "In multi-line query in pop_noop");
810 return (-1);
811 }
812
813 if (sendline (server, "NOOP") || getok (server))
814 return (-1);
815
816 return (0);
817 }
818
819 /*
820 * Function: pop_last
821 *
822 * Purpose: Find out the highest seen message from the server.
823 *
824 * Arguments:
825 * server The server.
826 *
827 * Return value: If successful, the highest seen message, which is
828 * greater than or equal to 0. Otherwise, a negative number with
829 * the error explained in pop_error.
830 *
831 * Side effects: Closes the connection on error.
832 */
833 int
834 pop_last (popserver server)
835 {
836 char *fromserver;
837
838 if (server->in_multi)
839 {
840 strcpy (pop_error, "In multi-line query in pop_last");
841 return (-1);
842 }
843
844 if (sendline (server, "LAST"))
845 return (-1);
846
847 if (pop_getline (server, &fromserver) < 0)
848 return (-1);
849
850 if (! strncmp (fromserver, "-ERR", 4))
851 {
852 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
853 return (-1);
854 }
855 else if (strncmp (fromserver, "+OK ", 4))
856 {
857 strcpy (pop_error, "Unexpected response from server in pop_last");
858 pop_trash (server);
859 return (-1);
860 }
861 else
862 {
863 char *end_ptr;
864 int count;
865 errno = 0;
866 count = strtol (&fromserver[4], &end_ptr, 10);
867 if (fromserver + 4 == end_ptr || errno)
868 {
869 strcpy (pop_error, "Unexpected response from server in pop_last");
870 pop_trash (server);
871 return (-1);
872 }
873 return count;
874 }
875 }
876
877 /*
878 * Function: pop_reset
879 *
880 * Purpose: Reset the server to its initial connect state
881 *
882 * Arguments:
883 * server The server.
884 *
885 * Return value: 0 for success, non-0 with error in pop_error
886 * otherwise.
887 *
888 * Side effects: Closes the connection on error.
889 */
890 int
891 pop_reset (popserver server)
892 {
893 if (pop_retrieve_flush (server))
894 {
895 return (-1);
896 }
897
898 if (sendline (server, "RSET") || getok (server))
899 return (-1);
900
901 return (0);
902 }
903
904 /*
905 * Function: pop_quit
906 *
907 * Purpose: Quit the connection to the server,
908 *
909 * Arguments:
910 * server The server to quit.
911 *
912 * Return value: 0 for success, non-zero otherwise with error in
913 * pop_error.
914 *
915 * Side Effects: The popserver passed in is unusable after this
916 * function is called, even if an error occurs.
917 */
918 int
919 pop_quit (popserver server)
920 {
921 int ret = 0;
922
923 if (server->file >= 0)
924 {
925 if (pop_retrieve_flush (server))
926 {
927 ret = -1;
928 }
929
930 if (sendline (server, "QUIT") || getok (server))
931 {
932 ret = -1;
933 }
934
935 close (server->file);
936 }
937
938 free (server->buffer);
939 free ((char *) server);
940
941 return (ret);
942 }
943
944 #ifdef WINDOWSNT
945 static int have_winsock = 0;
946 #endif
947
948 /*
949 * Function: socket_connection
950 *
951 * Purpose: Opens the network connection with the mail host, without
952 * doing any sort of I/O with it or anything.
953 *
954 * Arguments:
955 * host The host to which to connect.
956 * flags Option flags.
957 *
958 * Return value: A file descriptor indicating the connection, or -1
959 * indicating failure, in which case an error has been copied
960 * into pop_error.
961 */
962 static int
963 socket_connection (char *host, int flags)
964 {
965 #ifdef HAVE_GETADDRINFO
966 struct addrinfo *res, *it;
967 struct addrinfo hints;
968 int ret;
969 #else /* !HAVE_GETADDRINFO */
970 struct hostent *hostent;
971 #endif
972 struct servent *servent;
973 struct sockaddr_in addr;
974 char found_port = 0;
975 const char *service;
976 int sock;
977 char *realhost;
978 #ifdef KERBEROS
979 #ifdef KERBEROS5
980 krb5_error_code rem;
981 krb5_context kcontext = 0;
982 krb5_auth_context auth_context = 0;
983 krb5_ccache ccdef;
984 krb5_principal client, server;
985 krb5_error *err_ret;
986 register char *cp;
987 #else
988 KTEXT ticket;
989 MSG_DAT msg_data;
990 CREDENTIALS cred;
991 Key_schedule schedule;
992 int rem;
993 #endif /* KERBEROS5 */
994 #endif /* KERBEROS */
995
996 int try_count = 0;
997 int connect_ok;
998
999 #ifdef WINDOWSNT
1000 {
1001 WSADATA winsockData;
1002 if (WSAStartup (0x101, &winsockData) == 0)
1003 have_winsock = 1;
1004 }
1005 #endif
1006
1007 memset (&addr, 0, sizeof (addr));
1008 addr.sin_family = AF_INET;
1009
1010 /** "kpop" service is never used: look for 20060515 to see why **/
1011 #ifdef KERBEROS
1012 service = (flags & POP_NO_KERBEROS) ? POP_SERVICE : KPOP_SERVICE;
1013 #else
1014 service = POP_SERVICE;
1015 #endif
1016
1017 #ifdef HESIOD
1018 if (! (flags & POP_NO_HESIOD))
1019 {
1020 servent = hes_getservbyname (service, "tcp");
1021 if (servent)
1022 {
1023 addr.sin_port = servent->s_port;
1024 found_port = 1;
1025 }
1026 }
1027 #endif
1028 if (! found_port)
1029 {
1030 servent = getservbyname (service, "tcp");
1031 if (servent)
1032 {
1033 addr.sin_port = servent->s_port;
1034 }
1035 else
1036 {
1037 /** "kpop" service is never used: look for 20060515 to see why **/
1038 #ifdef KERBEROS
1039 addr.sin_port = htons ((flags & POP_NO_KERBEROS) ?
1040 POP_PORT : KPOP_PORT);
1041 #else
1042 addr.sin_port = htons (POP_PORT);
1043 #endif
1044 }
1045 }
1046
1047 #define POP_SOCKET_ERROR "Could not create socket for POP connection: "
1048
1049 sock = socket (PF_INET, SOCK_STREAM, 0);
1050 if (sock < 0)
1051 {
1052 snprintf (pop_error, ERROR_MAX, "%s%s",
1053 POP_SOCKET_ERROR, strerror (errno));
1054 return (-1);
1055
1056 }
1057
1058 #ifdef HAVE_GETADDRINFO
1059 memset (&hints, 0, sizeof (hints));
1060 hints.ai_socktype = SOCK_STREAM;
1061 hints.ai_flags = AI_CANONNAME;
1062 hints.ai_family = AF_INET;
1063 do
1064 {
1065 ret = getaddrinfo (host, service, &hints, &res);
1066 try_count++;
1067 if (ret != 0 && (ret != EAI_AGAIN || try_count == 5))
1068 {
1069 strcpy (pop_error, "Could not determine POP server's address");
1070 return (-1);
1071 }
1072 } while (ret != 0);
1073
1074 for (it = res; it; it = it->ai_next)
1075 if (it->ai_addrlen == sizeof addr)
1076 {
1077 struct sockaddr_in *in_a = (struct sockaddr_in *) it->ai_addr;
1078 addr.sin_addr = in_a->sin_addr;
1079 if (! connect (sock, (struct sockaddr *) &addr, sizeof addr))
1080 break;
1081 }
1082 connect_ok = it != NULL;
1083 if (connect_ok)
1084 {
1085 realhost = alloca (strlen (it->ai_canonname) + 1);
1086 strcpy (realhost, it->ai_canonname);
1087 }
1088 freeaddrinfo (res);
1089
1090 #else /* !HAVE_GETADDRINFO */
1091 do
1092 {
1093 hostent = gethostbyname (host);
1094 try_count++;
1095 if ((! hostent) && ((h_errno != TRY_AGAIN) || (try_count == 5)))
1096 {
1097 strcpy (pop_error, "Could not determine POP server's address");
1098 return (-1);
1099 }
1100 } while (! hostent);
1101
1102 while (*hostent->h_addr_list)
1103 {
1104 memcpy (&addr.sin_addr, *hostent->h_addr_list, hostent->h_length);
1105 if (! connect (sock, (struct sockaddr *) &addr, sizeof (addr)))
1106 break;
1107 hostent->h_addr_list++;
1108 }
1109 connect_ok = *hostent->h_addr_list != NULL;
1110 if (! connect_ok)
1111 {
1112 realhost = alloca (strlen (hostent->h_name) + 1);
1113 strcpy (realhost, hostent->h_name);
1114 }
1115
1116 #endif /* !HAVE_GETADDRINFO */
1117
1118 #define CONNECT_ERROR "Could not connect to POP server: "
1119
1120 if (! connect_ok)
1121 {
1122 CLOSESOCKET (sock);
1123 snprintf (pop_error, ERROR_MAX, "%s%s", CONNECT_ERROR, strerror (errno));
1124 return (-1);
1125
1126 }
1127
1128 #ifdef KERBEROS
1129
1130 #define KRB_ERROR "Kerberos error connecting to POP server: "
1131 if (! (flags & POP_NO_KERBEROS))
1132 {
1133 #ifdef KERBEROS5
1134 if ((rem = krb5_init_context (&kcontext)))
1135 {
1136 krb5error:
1137 if (auth_context)
1138 krb5_auth_con_free (kcontext, auth_context);
1139 if (kcontext)
1140 krb5_free_context (kcontext);
1141 snprintf (pop_error, ERROR_MAX, "%s%s",
1142 KRB_ERROR, error_message (rem));
1143 CLOSESOCKET (sock);
1144 return (-1);
1145 }
1146
1147 if ((rem = krb5_auth_con_init (kcontext, &auth_context)))
1148 goto krb5error;
1149
1150 if (rem = krb5_cc_default (kcontext, &ccdef))
1151 goto krb5error;
1152
1153 if (rem = krb5_cc_get_principal (kcontext, ccdef, &client))
1154 goto krb5error;
1155
1156 for (cp = realhost; *cp; cp++)
1157 {
1158 if (isupper (*cp))
1159 {
1160 *cp = tolower (*cp);
1161 }
1162 }
1163
1164 if (rem = krb5_sname_to_principal (kcontext, realhost,
1165 POP_SERVICE, FALSE, &server))
1166 goto krb5error;
1167
1168 rem = krb5_sendauth (kcontext, &auth_context,
1169 (krb5_pointer) &sock, "KPOPV1.0", client, server,
1170 AP_OPTS_MUTUAL_REQUIRED,
1171 0, /* no checksum */
1172 0, /* no creds, use ccache instead */
1173 ccdef,
1174 &err_ret,
1175 0, /* don't need subsession key */
1176 0); /* don't need reply */
1177 krb5_free_principal (kcontext, server);
1178 if (rem)
1179 {
1180 int pop_error_len = snprintf (pop_error, ERROR_MAX, "%s%s",
1181 KRB_ERROR, error_message (rem));
1182 #if defined HAVE_KRB5_ERROR_TEXT
1183 if (err_ret && err_ret->text.length)
1184 {
1185 int errlen = err_ret->text.length;
1186 snprintf (pop_error + pop_error_len, ERROR_MAX - pop_error_len,
1187 " [server says '%.*s']", errlen, err_ret->text.data);
1188 }
1189 #elif defined HAVE_KRB5_ERROR_E_TEXT
1190 if (err_ret && err_ret->e_text && **err_ret->e_text)
1191 snprintf (pop_error + pop_error_len, ERROR_MAX - pop_error_len,
1192 " [server says '%s']", *err_ret->e_text);
1193 #endif
1194 if (err_ret)
1195 krb5_free_error (kcontext, err_ret);
1196 krb5_auth_con_free (kcontext, auth_context);
1197 krb5_free_context (kcontext);
1198
1199 CLOSESOCKET (sock);
1200 return (-1);
1201 }
1202 #else /* ! KERBEROS5 */
1203 ticket = (KTEXT) malloc (sizeof (KTEXT_ST));
1204 rem = krb_sendauth (0L, sock, ticket, "pop", realhost,
1205 (char *) krb_realmofhost (realhost),
1206 (unsigned long) 0, &msg_data, &cred, schedule,
1207 (struct sockaddr_in *) 0,
1208 (struct sockaddr_in *) 0,
1209 "KPOPV0.1");
1210 free ((char *) ticket);
1211 if (rem != KSUCCESS)
1212 {
1213 snprintf (pop_error, ERROR_MAX, "%s%s", KRB_ERROR, krb_err_txt[rem]);
1214 CLOSESOCKET (sock);
1215 return (-1);
1216 }
1217 #endif /* KERBEROS5 */
1218 }
1219 #endif /* KERBEROS */
1220
1221 return (sock);
1222 } /* socket_connection */
1223
1224 /*
1225 * Function: pop_getline
1226 *
1227 * Purpose: Get a line of text from the connection and return a
1228 * pointer to it. The carriage return and linefeed at the end of
1229 * the line are stripped, but periods at the beginnings of lines
1230 * are NOT dealt with in any special way.
1231 *
1232 * Arguments:
1233 * server The server from which to get the line of text.
1234 *
1235 * Returns: The number of characters in the line, which is returned in
1236 * LINE, not including the final null. A return value of 0
1237 * indicates a blank line. A negative return value indicates an
1238 * error (in which case the contents of LINE are undefined. In
1239 * case of error, an error message is copied into pop_error.
1240 *
1241 * Notes: The line returned is overwritten with each call to pop_getline.
1242 *
1243 * Side effects: Closes the connection on error.
1244 *
1245 * THE RETURNED LINE MAY CONTAIN EMBEDDED NULLS!
1246 */
1247 static int
1248 pop_getline (popserver server, char **line)
1249 {
1250 #define GETLINE_ERROR "Error reading from server: "
1251
1252 int ret;
1253 int search_offset = 0;
1254
1255 if (server->data)
1256 {
1257 char *cp = find_crlf (server->buffer + server->buffer_index,
1258 server->data);
1259 if (cp)
1260 {
1261 int found;
1262 int data_used;
1263
1264 found = server->buffer_index;
1265 data_used = (cp + 2) - server->buffer - found;
1266
1267 *cp = '\0'; /* terminate the string to be returned */
1268 server->data -= data_used;
1269 server->buffer_index += data_used;
1270
1271 if (pop_debug)
1272 /* Embedded nulls will truncate this output prematurely,
1273 but that's OK because it's just for debugging anyway. */
1274 fprintf (stderr, "<<< %s\n", server->buffer + found);
1275 *line = server->buffer + found;
1276 return (data_used - 2);
1277 }
1278 else
1279 {
1280 memmove (server->buffer, server->buffer + server->buffer_index,
1281 server->data);
1282 /* Record the fact that we've searched the data already in
1283 the buffer for a CRLF, so that when we search below, we
1284 don't have to search the same data twice. There's a "-
1285 1" here to account for the fact that the last character
1286 of the data we have may be the CR of a CRLF pair, of
1287 which we haven't read the second half yet, so we may have
1288 to search it again when we read more data. */
1289 search_offset = server->data - 1;
1290 server->buffer_index = 0;
1291 }
1292 }
1293 else
1294 {
1295 server->buffer_index = 0;
1296 }
1297
1298 while (1)
1299 {
1300 /* There's a "- 1" here to leave room for the null that we put
1301 at the end of the read data below. We put the null there so
1302 that find_crlf knows where to stop when we call it. */
1303 if (server->data == server->buffer_size - 1)
1304 {
1305 server->buffer_size += GETLINE_INCR;
1306 server->buffer = (char *)realloc (server->buffer, server->buffer_size);
1307 if (! server->buffer)
1308 {
1309 strcpy (pop_error, "Out of memory in pop_getline");
1310 pop_trash (server);
1311 return (-1);
1312 }
1313 }
1314 ret = RECV (server->file, server->buffer + server->data,
1315 server->buffer_size - server->data - 1, 0);
1316 if (ret < 0)
1317 {
1318 snprintf (pop_error, ERROR_MAX, "%s%s",
1319 GETLINE_ERROR, strerror (errno));
1320 pop_trash (server);
1321 return (-1);
1322 }
1323 else if (ret == 0)
1324 {
1325 strcpy (pop_error, "Unexpected EOF from server in pop_getline");
1326 pop_trash (server);
1327 return (-1);
1328 }
1329 else
1330 {
1331 char *cp;
1332 server->data += ret;
1333 server->buffer[server->data] = '\0';
1334
1335 cp = find_crlf (server->buffer + search_offset,
1336 server->data - search_offset);
1337 if (cp)
1338 {
1339 int data_used = (cp + 2) - server->buffer;
1340 *cp = '\0';
1341 server->data -= data_used;
1342 server->buffer_index = data_used;
1343
1344 if (pop_debug)
1345 fprintf (stderr, "<<< %s\n", server->buffer);
1346 *line = server->buffer;
1347 return (data_used - 2);
1348 }
1349 /* As above, the "- 1" here is to account for the fact that
1350 we may have read a CR without its accompanying LF. */
1351 search_offset += ret - 1;
1352 }
1353 }
1354
1355 /* NOTREACHED */
1356 }
1357
1358 /*
1359 * Function: sendline
1360 *
1361 * Purpose: Sends a line of text to the POP server. The line of text
1362 * passed into this function should NOT have the carriage return
1363 * and linefeed on the end of it. Periods at beginnings of lines
1364 * will NOT be treated specially by this function.
1365 *
1366 * Arguments:
1367 * server The server to which to send the text.
1368 * line The line of text to send.
1369 *
1370 * Return value: Upon successful completion, a value of 0 will be
1371 * returned. Otherwise, a non-zero value will be returned, and
1372 * an error will be copied into pop_error.
1373 *
1374 * Side effects: Closes the connection on error.
1375 */
1376 static int
1377 sendline (popserver server, const char *line)
1378 {
1379 #define SENDLINE_ERROR "Error writing to POP server: "
1380 int ret;
1381 char *buf;
1382
1383 /* Combine the string and the CR-LF into one buffer. Otherwise, two
1384 reasonable network stack optimizations, Nagle's algorithm and
1385 delayed acks, combine to delay us a fraction of a second on every
1386 message we send. (Movemail writes line without \r\n, client
1387 kernel sends packet, server kernel delays the ack to see if it
1388 can combine it with data, movemail writes \r\n, client kernel
1389 waits because it has unacked data already in its outgoing queue,
1390 client kernel eventually times out and sends.)
1391
1392 This can be something like 0.2s per command, which can add up
1393 over a few dozen messages, and is a big chunk of the time we
1394 spend fetching mail from a server close by. */
1395 buf = alloca (strlen (line) + 3);
1396 strcpy (stpcpy (buf, line), "\r\n");
1397 ret = fullwrite (server->file, buf, strlen (buf));
1398
1399 if (ret < 0)
1400 {
1401 pop_trash (server);
1402 snprintf (pop_error, ERROR_MAX, "%s%s", SENDLINE_ERROR, strerror (errno));
1403 return (ret);
1404 }
1405
1406 if (pop_debug)
1407 fprintf (stderr, ">>> %s\n", line);
1408
1409 return (0);
1410 }
1411
1412 /*
1413 * Procedure: fullwrite
1414 *
1415 * Purpose: Just like write, but keeps trying until the entire string
1416 * has been written.
1417 *
1418 * Return value: Same as write. Pop_error is not set.
1419 */
1420 static int
1421 fullwrite (int fd, char *buf, int nbytes)
1422 {
1423 char *cp;
1424 int ret = 0;
1425
1426 cp = buf;
1427 while (nbytes && ((ret = SEND (fd, cp, nbytes, 0)) > 0))
1428 {
1429 cp += ret;
1430 nbytes -= ret;
1431 }
1432
1433 return (ret);
1434 }
1435
1436 /*
1437 * Procedure getok
1438 *
1439 * Purpose: Reads a line from the server. If the return indicator is
1440 * positive, return with a zero exit status. If not, return with
1441 * a negative exit status.
1442 *
1443 * Arguments:
1444 * server The server to read from.
1445 *
1446 * Returns: 0 for success, else for failure and puts error in pop_error.
1447 *
1448 * Side effects: On failure, may make the connection unusable.
1449 */
1450 static int
1451 getok (popserver server)
1452 {
1453 char *fromline;
1454
1455 if (pop_getline (server, &fromline) < 0)
1456 {
1457 return (-1);
1458 }
1459
1460 if (! strncmp (fromline, "+OK", 3))
1461 return (0);
1462 else if (! strncmp (fromline, "-ERR", 4))
1463 {
1464 snprintf (pop_error, ERROR_MAX, "%s", fromline);
1465 return (-1);
1466 }
1467 else
1468 {
1469 strcpy (pop_error,
1470 "Unexpected response from server; expecting +OK or -ERR");
1471 pop_trash (server);
1472 return (-1);
1473 }
1474 }
1475
1476 #if 0
1477 /*
1478 * Function: gettermination
1479 *
1480 * Purpose: Gets the next line and verifies that it is a termination
1481 * line (nothing but a dot).
1482 *
1483 * Return value: 0 on success, non-zero with pop_error set on error.
1484 *
1485 * Side effects: Closes the connection on error.
1486 */
1487 static int
1488 gettermination (server)
1489 popserver server;
1490 {
1491 char *fromserver;
1492
1493 if (pop_getline (server, &fromserver) < 0)
1494 return (-1);
1495
1496 if (strcmp (fromserver, "."))
1497 {
1498 strcpy (pop_error,
1499 "Unexpected response from server in gettermination");
1500 pop_trash (server);
1501 return (-1);
1502 }
1503
1504 return (0);
1505 }
1506 #endif
1507
1508 /*
1509 * Function pop_close
1510 *
1511 * Purpose: Close a pop connection, sending a "RSET" command to try to
1512 * preserve any changes that were made and a "QUIT" command to
1513 * try to get the server to quit, but ignoring any responses that
1514 * are received.
1515 *
1516 * Side effects: The server is unusable after this function returns.
1517 * Changes made to the maildrop since the session was started (or
1518 * since the last pop_reset) may be lost.
1519 */
1520 void
1521 pop_close (popserver server)
1522 {
1523 pop_trash (server);
1524 free ((char *) server);
1525
1526 return;
1527 }
1528
1529 /*
1530 * Function: pop_trash
1531 *
1532 * Purpose: Like pop_close or pop_quit, but doesn't deallocate the
1533 * memory associated with the server. It is valid to call
1534 * pop_close or pop_quit after this function has been called.
1535 */
1536 static void
1537 pop_trash (popserver server)
1538 {
1539 if (server->file >= 0)
1540 {
1541 /* avoid recursion; sendline can call pop_trash */
1542 if (server->trash_started)
1543 return;
1544 server->trash_started = true;
1545
1546 sendline (server, "RSET");
1547 sendline (server, "QUIT");
1548
1549 CLOSESOCKET (server->file);
1550 server->file = -1;
1551 if (server->buffer)
1552 {
1553 free (server->buffer);
1554 server->buffer = 0;
1555 }
1556 }
1557
1558 #ifdef WINDOWSNT
1559 if (have_winsock)
1560 WSACleanup ();
1561 #endif
1562 }
1563
1564 /* Return a pointer to the first CRLF in IN_STRING, which can contain
1565 embedded nulls and has LEN characters in it not including the final
1566 null, or 0 if it does not contain one. */
1567
1568 static char *
1569 find_crlf (char *in_string, int len)
1570 {
1571 while (len--)
1572 {
1573 if (*in_string == '\r')
1574 {
1575 if (*++in_string == '\n')
1576 return (in_string - 1);
1577 }
1578 else
1579 in_string++;
1580 }
1581 return (0);
1582 }
1583
1584 #endif /* MAIL_USE_POP */