; Auto-commit of loaddefs files.
[emacs.git] / lib-src / pop.c
blob6e3b6a9a7735591147e417600e6b00f77b8ffd25
1 /* pop.c: client routines for talking to a POP3-protocol post-office server
3 Copyright (C) 1991, 1993, 1996-1997, 1999, 2001-2016 Free Software
4 Foundation, Inc.
6 Author: Jonathan Kamens <jik@security.ov.com>
8 This file is part of GNU Emacs.
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.
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.
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/>. */
24 #include <config.h>
26 #ifdef MAIL_USE_POP
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>
45 #ifdef HESIOD
46 #include <hesiod.h>
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.
53 extern struct servent *hes_getservbyname (/* char *, char * */);
54 #endif
56 #include <pwd.h>
57 #include <netdb.h>
58 #include <errno.h>
59 #include <stdio.h>
60 #include <string.h>
61 #include <unistd.h>
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 */
83 #include <min-max.h>
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 */
95 #ifndef WINDOWSNT
96 #ifndef HAVE_H_ERRNO
97 extern int h_errno;
98 #endif
99 #endif
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);
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
122 char pop_error[ERROR_MAX];
123 bool pop_debug = false;
126 * Function: pop_open (char *host, char *username, char *password,
127 * int flags)
129 * Purpose: Establishes a connection with a post-office server, and
130 * completes the authorization portion of the session.
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
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.
154 popserver
155 pop_open (char *host, char *username, char *password, int flags)
157 int sock;
158 popserver server;
160 /* Determine the user name */
161 if (! username)
163 username = getenv ("USER");
164 if (! (username && *username))
166 username = getlogin ();
167 if (! (username && *username))
169 struct passwd *passwd;
170 passwd = getpwuid (getuid ());
171 if (passwd && passwd->pw_name && *passwd->pw_name)
173 username = passwd->pw_name;
175 else
177 strcpy (pop_error, "Could not determine username");
178 return (0);
185 * Determine the mail host.
188 if (! host)
190 host = getenv ("MAILHOST");
193 #ifdef HESIOD
194 if ((! host) && (! (flags & POP_NO_HESIOD)))
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)
202 host = office->po_host;
203 username = office->po_name;
206 #endif
208 #ifdef MAILHOST
209 if (! host)
211 host = MAILHOST;
213 #endif
215 if (! host)
217 strcpy (pop_error, "Could not determine POP server");
218 return (0);
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
228 if ((! password) && (! DONT_NEED_PASSWORD))
230 if (! (flags & POP_NO_GETPASS))
232 password = getpass ("Enter POP password:");
234 if (! password)
236 strcpy (pop_error, "Could not determine POP password");
237 return (0);
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 **/
246 sock = socket_connection (host, flags);
247 if (sock == -1)
248 return (0);
250 server = (popserver) malloc (sizeof (struct _popserver));
251 if (! server)
253 strcpy (pop_error, "Out of memory in pop_open");
254 return (0);
256 server->buffer = (char *) malloc (GETLINE_MIN);
257 if (! server->buffer)
259 strcpy (pop_error, "Out of memory in pop_open");
260 free ((char *) server);
261 return (0);
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;
271 if (getok (server))
272 return (0);
275 * I really shouldn't use the pop_error variable like this, but....
277 if (strlen (username) > ERROR_MAX - 6)
279 pop_close (server);
280 strcpy (pop_error,
281 "Username too long; recompile pop.c with larger ERROR_MAX");
282 return (0);
284 sprintf (pop_error, "USER %s", username);
286 if (sendline (server, pop_error) || getok (server))
288 return (0);
291 if (strlen (password) > ERROR_MAX - 6)
293 pop_close (server);
294 strcpy (pop_error,
295 "Password too long; recompile pop.c with larger ERROR_MAX");
296 return (0);
298 sprintf (pop_error, "PASS %s", password);
300 if (sendline (server, pop_error) || getok (server))
302 return (0);
305 return (server);
309 * Function: pop_stat
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.
315 * Return value: 0 on success, or non-zero with an error in pop_error
316 * in failure.
318 * Side effects: On failure, may make further operations on the
319 * connection impossible.
322 pop_stat (popserver server, int *count, int *size)
324 char *fromserver;
325 char *end_ptr;
327 if (server->in_multi)
329 strcpy (pop_error, "In multi-line query in pop_stat");
330 return (-1);
333 if (sendline (server, "STAT") || (pop_getline (server, &fromserver) < 0))
334 return (-1);
336 if (strncmp (fromserver, "+OK ", 4))
338 if (0 == strncmp (fromserver, "-ERR", 4))
339 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
340 else
342 strcpy (pop_error,
343 "Unexpected response from POP server in pop_stat");
344 pop_trash (server);
346 return (-1);
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)
354 strcpy (pop_error, "Unexpected response from POP server in pop_stat");
355 pop_trash (server);
356 return (-1);
359 fromserver = end_ptr;
361 errno = 0;
362 *size = strtol (fromserver + 1, &end_ptr, 10);
363 if (fromserver + 1 == end_ptr || errno)
365 strcpy (pop_error, "Unexpected response from POP server in pop_stat");
366 pop_trash (server);
367 return (-1);
370 return (0);
374 * Function: pop_list
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.
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.
386 * Return value: 0 on success, non-zero with error in pop_error on
387 * failure.
389 * Side effects: On failure, may make further operations on the
390 * connection impossible.
393 pop_list (popserver server, int message, int **IDs, int **sizes)
395 int how_many, i;
396 char *fromserver;
398 if (server->in_multi)
400 strcpy (pop_error, "In multi-line query in pop_list");
401 return (-1);
404 if (message)
405 how_many = 1;
406 else
408 int count, size;
409 if (pop_stat (server, &count, &size))
410 return (-1);
411 how_many = count;
414 *IDs = (int *) malloc ((how_many + 1) * sizeof (int));
415 *sizes = (int *) malloc ((how_many + 1) * sizeof (int));
416 if (! (*IDs && *sizes))
418 strcpy (pop_error, "Out of memory in pop_list");
419 return (-1);
422 if (message)
424 sprintf (pop_error, "LIST %d", message);
425 if (sendline (server, pop_error))
427 free ((char *) *IDs);
428 free ((char *) *sizes);
429 return (-1);
431 if (pop_getline (server, &fromserver) < 0)
433 free ((char *) *IDs);
434 free ((char *) *sizes);
435 return (-1);
437 if (strncmp (fromserver, "+OK ", 4))
439 if (! strncmp (fromserver, "-ERR", 4))
440 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
441 else
443 strcpy (pop_error,
444 "Unexpected response from server in pop_list");
445 pop_trash (server);
447 free ((char *) *IDs);
448 free ((char *) *sizes);
449 return (-1);
451 (*IDs)[0] = atoi (&fromserver[4]);
452 fromserver = strchr (&fromserver[4], ' ');
453 if (! fromserver)
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);
462 (*sizes)[0] = atoi (fromserver);
463 (*IDs)[1] = (*sizes)[1] = 0;
464 return (0);
466 else
468 if (pop_multi_first (server, "LIST", &fromserver))
470 free ((char *) *IDs);
471 free ((char *) *sizes);
472 return (-1);
474 for (i = 0; i < how_many; i++)
476 if (pop_multi_next (server, &fromserver) <= 0)
478 free ((char *) *IDs);
479 free ((char *) *sizes);
480 return (-1);
482 (*IDs)[i] = atoi (fromserver);
483 fromserver = strchr (fromserver, ' ');
484 if (! fromserver)
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);
493 (*sizes)[i] = atoi (fromserver);
495 if (pop_multi_next (server, &fromserver) < 0)
497 free ((char *) *IDs);
498 free ((char *) *sizes);
499 return (-1);
501 else if (fromserver)
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);
509 (*IDs)[i] = (*sizes)[i] = 0;
510 return (0);
515 * Function: pop_retrieve
517 * Purpose: Retrieve a specified message from the maildrop.
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.
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.
532 * Side effects: May kill connection on error.
535 pop_retrieve (popserver server, int message, int markfrom, char **msg_buf)
537 int *IDs, *sizes, bufsize, fromcount = 0, cp = 0;
538 char *ptr, *fromserver;
539 int ret;
541 if (server->in_multi)
543 strcpy (pop_error, "In multi-line query in pop_retrieve");
544 return (-1);
547 if (pop_list (server, message, &IDs, &sizes))
548 return (-1);
550 if (pop_retrieve_first (server, message, &fromserver))
552 return (-1);
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.
561 bufsize = sizes[0] + (markfrom ? 5 : 0);
562 ptr = (char *)malloc (bufsize);
563 free ((char *) IDs);
564 free ((char *) sizes);
566 if (! ptr)
568 strcpy (pop_error, "Out of memory in pop_retrieve");
569 pop_retrieve_flush (server);
570 return (-1);
573 while ((ret = pop_retrieve_next (server, &fromserver)) >= 0)
575 if (! fromserver)
577 ptr[cp] = '\0';
578 *msg_buf = ptr;
579 return (cp);
581 if (markfrom && fromserver[0] == 'F' && fromserver[1] == 'r' &&
582 fromserver[2] == 'o' && fromserver[3] == 'm' &&
583 fromserver[4] == ' ')
585 if (++fromcount == 5)
587 bufsize += 5;
588 ptr = (char *)realloc (ptr, bufsize);
589 if (! ptr)
591 strcpy (pop_error, "Out of memory in pop_retrieve");
592 pop_retrieve_flush (server);
593 return (-1);
595 fromcount = 0;
597 ptr[cp++] = '>';
599 memcpy (&ptr[cp], fromserver, ret);
600 cp += ret;
601 ptr[cp++] = '\n';
604 free (ptr);
605 return (-1);
609 pop_retrieve_first (popserver server, int message, char **response)
611 sprintf (pop_error, "RETR %d", message);
612 return (pop_multi_first (server, pop_error, response));
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).
624 pop_retrieve_next (popserver server, char **line)
626 return (pop_multi_next (server, line));
630 pop_retrieve_flush (popserver server)
632 return (pop_multi_flush (server));
636 pop_top_first (popserver server, int message, int lines, char **response)
638 sprintf (pop_error, "TOP %d %d", message, lines);
639 return (pop_multi_first (server, pop_error, response));
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).
651 pop_top_next (popserver server, char **line)
653 return (pop_multi_next (server, line));
657 pop_top_flush (popserver server)
659 return (pop_multi_flush (server));
663 pop_multi_first (popserver server, const char *command, char **response)
665 if (server->in_multi)
667 strcpy (pop_error,
668 "Already in multi-line query in pop_multi_first");
669 return (-1);
672 if (sendline (server, command) || (pop_getline (server, response) < 0))
674 return (-1);
677 if (0 == strncmp (*response, "-ERR", 4))
679 snprintf (pop_error, ERROR_MAX, "%s", *response);
680 return (-1);
682 else if (0 == strncmp (*response, "+OK", 3))
684 for (*response += 3; **response == ' '; (*response)++) /* empty */;
685 server->in_multi = true;
686 return (0);
688 else
690 strcpy (pop_error,
691 "Unexpected response from server in pop_multi_first");
692 return (-1);
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. */
706 pop_multi_next (popserver server, char **line)
708 char *fromserver;
709 int ret;
711 if (! server->in_multi)
713 strcpy (pop_error, "Not in multi-line query in pop_multi_next");
714 return (-1);
717 if ((ret = pop_getline (server, &fromserver)) < 0)
719 return (-1);
722 if (fromserver[0] == '.')
724 if (! fromserver[1])
726 *line = 0;
727 server->in_multi = false;
728 return (0);
730 else
732 *line = fromserver + 1;
733 return (ret - 1);
736 else
738 *line = fromserver;
739 return (ret);
744 pop_multi_flush (popserver server)
746 char *line;
747 int ret;
749 if (! server->in_multi)
751 return (0);
754 while ((ret = pop_multi_next (server, &line)))
756 if (ret < 0)
757 return (-1);
760 return (0);
763 /* Function: pop_delete
765 * Purpose: Delete a specified message.
767 * Arguments:
768 * server Server from which to delete the message.
769 * message Message to delete.
771 * Return value: 0 on success, non-zero with error in pop_error
772 * otherwise.
775 pop_delete (popserver server, int message)
777 if (server->in_multi)
779 strcpy (pop_error, "In multi-line query in pop_delete");
780 return (-1);
783 sprintf (pop_error, "DELE %d", message);
785 if (sendline (server, pop_error) || getok (server))
786 return (-1);
788 return (0);
792 * Function: pop_noop
794 * Purpose: Send a noop command to the server.
796 * Argument:
797 * server The server to send to.
799 * Return value: 0 on success, non-zero with error in pop_error
800 * otherwise.
802 * Side effects: Closes connection on error.
805 pop_noop (popserver server)
807 if (server->in_multi)
809 strcpy (pop_error, "In multi-line query in pop_noop");
810 return (-1);
813 if (sendline (server, "NOOP") || getok (server))
814 return (-1);
816 return (0);
820 * Function: pop_last
822 * Purpose: Find out the highest seen message from the server.
824 * Arguments:
825 * server The server.
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.
831 * Side effects: Closes the connection on error.
834 pop_last (popserver server)
836 char *fromserver;
838 if (server->in_multi)
840 strcpy (pop_error, "In multi-line query in pop_last");
841 return (-1);
844 if (sendline (server, "LAST"))
845 return (-1);
847 if (pop_getline (server, &fromserver) < 0)
848 return (-1);
850 if (! strncmp (fromserver, "-ERR", 4))
852 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
853 return (-1);
855 else if (strncmp (fromserver, "+OK ", 4))
857 strcpy (pop_error, "Unexpected response from server in pop_last");
858 pop_trash (server);
859 return (-1);
861 else
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)
869 strcpy (pop_error, "Unexpected response from server in pop_last");
870 pop_trash (server);
871 return (-1);
873 return count;
878 * Function: pop_reset
880 * Purpose: Reset the server to its initial connect state
882 * Arguments:
883 * server The server.
885 * Return value: 0 for success, non-0 with error in pop_error
886 * otherwise.
888 * Side effects: Closes the connection on error.
891 pop_reset (popserver server)
893 if (pop_retrieve_flush (server))
895 return (-1);
898 if (sendline (server, "RSET") || getok (server))
899 return (-1);
901 return (0);
905 * Function: pop_quit
907 * Purpose: Quit the connection to the server,
909 * Arguments:
910 * server The server to quit.
912 * Return value: 0 for success, non-zero otherwise with error in
913 * pop_error.
915 * Side Effects: The popserver passed in is unusable after this
916 * function is called, even if an error occurs.
919 pop_quit (popserver server)
921 int ret = 0;
923 if (server->file >= 0)
925 if (pop_retrieve_flush (server))
927 ret = -1;
930 if (sendline (server, "QUIT") || getok (server))
932 ret = -1;
935 close (server->file);
938 free (server->buffer);
939 free ((char *) server);
941 return (ret);
944 #ifdef WINDOWSNT
945 static int have_winsock = 0;
946 #endif
949 * Function: socket_connection
951 * Purpose: Opens the network connection with the mail host, without
952 * doing any sort of I/O with it or anything.
954 * Arguments:
955 * host The host to which to connect.
956 * flags Option flags.
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.
962 static int
963 socket_connection (char *host, int flags)
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 */
996 int try_count = 0;
997 int connect_ok;
999 #ifdef WINDOWSNT
1001 WSADATA winsockData;
1002 if (WSAStartup (0x101, &winsockData) == 0)
1003 have_winsock = 1;
1005 #endif
1007 memset (&addr, 0, sizeof (addr));
1008 addr.sin_family = AF_INET;
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
1017 #ifdef HESIOD
1018 if (! (flags & POP_NO_HESIOD))
1020 servent = hes_getservbyname (service, "tcp");
1021 if (servent)
1023 addr.sin_port = servent->s_port;
1024 found_port = 1;
1027 #endif
1028 if (! found_port)
1030 servent = getservbyname (service, "tcp");
1031 if (servent)
1033 addr.sin_port = servent->s_port;
1035 else
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
1047 #define POP_SOCKET_ERROR "Could not create socket for POP connection: "
1049 sock = socket (PF_INET, SOCK_STREAM, 0);
1050 if (sock < 0)
1052 snprintf (pop_error, ERROR_MAX, "%s%s",
1053 POP_SOCKET_ERROR, strerror (errno));
1054 return (-1);
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;
1065 ret = getaddrinfo (host, service, &hints, &res);
1066 try_count++;
1067 if (ret != 0 && (ret != EAI_AGAIN || try_count == 5))
1069 strcpy (pop_error, "Could not determine POP server's address");
1070 return (-1);
1072 } while (ret != 0);
1074 for (it = res; it; it = it->ai_next)
1075 if (it->ai_addrlen == sizeof addr)
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;
1082 connect_ok = it != NULL;
1083 if (connect_ok)
1085 realhost = alloca (strlen (it->ai_canonname) + 1);
1086 strcpy (realhost, it->ai_canonname);
1088 freeaddrinfo (res);
1090 #else /* !HAVE_GETADDRINFO */
1093 hostent = gethostbyname (host);
1094 try_count++;
1095 if ((! hostent) && ((h_errno != TRY_AGAIN) || (try_count == 5)))
1097 strcpy (pop_error, "Could not determine POP server's address");
1098 return (-1);
1100 } while (! hostent);
1102 while (*hostent->h_addr_list)
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++;
1109 connect_ok = *hostent->h_addr_list != NULL;
1110 if (! connect_ok)
1112 realhost = alloca (strlen (hostent->h_name) + 1);
1113 strcpy (realhost, hostent->h_name);
1116 #endif /* !HAVE_GETADDRINFO */
1118 #define CONNECT_ERROR "Could not connect to POP server: "
1120 if (! connect_ok)
1122 CLOSESOCKET (sock);
1123 snprintf (pop_error, ERROR_MAX, "%s%s", CONNECT_ERROR, strerror (errno));
1124 return (-1);
1128 #ifdef KERBEROS
1130 #define KRB_ERROR "Kerberos error connecting to POP server: "
1131 if (! (flags & POP_NO_KERBEROS))
1133 #ifdef KERBEROS5
1134 if ((rem = krb5_init_context (&kcontext)))
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);
1147 if ((rem = krb5_auth_con_init (kcontext, &auth_context)))
1148 goto krb5error;
1150 if (rem = krb5_cc_default (kcontext, &ccdef))
1151 goto krb5error;
1153 if (rem = krb5_cc_get_principal (kcontext, ccdef, &client))
1154 goto krb5error;
1156 for (cp = realhost; *cp; cp++)
1158 if (isupper (*cp))
1160 *cp = tolower (*cp);
1164 if (rem = krb5_sname_to_principal (kcontext, realhost,
1165 POP_SERVICE, FALSE, &server))
1166 goto krb5error;
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)
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)
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);
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);
1199 CLOSESOCKET (sock);
1200 return (-1);
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)
1213 snprintf (pop_error, ERROR_MAX, "%s%s", KRB_ERROR, krb_err_txt[rem]);
1214 CLOSESOCKET (sock);
1215 return (-1);
1217 #endif /* KERBEROS5 */
1219 #endif /* KERBEROS */
1221 return (sock);
1222 } /* socket_connection */
1225 * Function: pop_getline
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.
1232 * Arguments:
1233 * server The server from which to get the line of text.
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.
1241 * Notes: The line returned is overwritten with each call to pop_getline.
1243 * Side effects: Closes the connection on error.
1245 * THE RETURNED LINE MAY CONTAIN EMBEDDED NULLS!
1247 static int
1248 pop_getline (popserver server, char **line)
1250 #define GETLINE_ERROR "Error reading from server: "
1252 int ret;
1253 int search_offset = 0;
1255 if (server->data)
1257 char *cp = find_crlf (server->buffer + server->buffer_index,
1258 server->data);
1259 if (cp)
1261 int found;
1262 int data_used;
1264 found = server->buffer_index;
1265 data_used = (cp + 2) - server->buffer - found;
1267 *cp = '\0'; /* terminate the string to be returned */
1268 server->data -= data_used;
1269 server->buffer_index += data_used;
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);
1278 else
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;
1293 else
1295 server->buffer_index = 0;
1298 while (1)
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)
1305 server->buffer_size += GETLINE_INCR;
1306 server->buffer = (char *)realloc (server->buffer, server->buffer_size);
1307 if (! server->buffer)
1309 strcpy (pop_error, "Out of memory in pop_getline");
1310 pop_trash (server);
1311 return (-1);
1314 ret = RECV (server->file, server->buffer + server->data,
1315 server->buffer_size - server->data - 1, 0);
1316 if (ret < 0)
1318 snprintf (pop_error, ERROR_MAX, "%s%s",
1319 GETLINE_ERROR, strerror (errno));
1320 pop_trash (server);
1321 return (-1);
1323 else if (ret == 0)
1325 strcpy (pop_error, "Unexpected EOF from server in pop_getline");
1326 pop_trash (server);
1327 return (-1);
1329 else
1331 char *cp;
1332 server->data += ret;
1333 server->buffer[server->data] = '\0';
1335 cp = find_crlf (server->buffer + search_offset,
1336 server->data - search_offset);
1337 if (cp)
1339 int data_used = (cp + 2) - server->buffer;
1340 *cp = '\0';
1341 server->data -= data_used;
1342 server->buffer_index = data_used;
1344 if (pop_debug)
1345 fprintf (stderr, "<<< %s\n", server->buffer);
1346 *line = server->buffer;
1347 return (data_used - 2);
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;
1355 /* NOTREACHED */
1359 * Function: sendline
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.
1366 * Arguments:
1367 * server The server to which to send the text.
1368 * line The line of text to send.
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.
1374 * Side effects: Closes the connection on error.
1376 static int
1377 sendline (popserver server, const char *line)
1379 #define SENDLINE_ERROR "Error writing to POP server: "
1380 int ret;
1381 char *buf;
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.)
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));
1399 if (ret < 0)
1401 pop_trash (server);
1402 snprintf (pop_error, ERROR_MAX, "%s%s", SENDLINE_ERROR, strerror (errno));
1403 return (ret);
1406 if (pop_debug)
1407 fprintf (stderr, ">>> %s\n", line);
1409 return (0);
1413 * Procedure: fullwrite
1415 * Purpose: Just like write, but keeps trying until the entire string
1416 * has been written.
1418 * Return value: Same as write. Pop_error is not set.
1420 static int
1421 fullwrite (int fd, char *buf, int nbytes)
1423 char *cp;
1424 int ret = 0;
1426 cp = buf;
1427 while (nbytes && ((ret = SEND (fd, cp, nbytes, 0)) > 0))
1429 cp += ret;
1430 nbytes -= ret;
1433 return (ret);
1437 * Procedure getok
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.
1443 * Arguments:
1444 * server The server to read from.
1446 * Returns: 0 for success, else for failure and puts error in pop_error.
1448 * Side effects: On failure, may make the connection unusable.
1450 static int
1451 getok (popserver server)
1453 char *fromline;
1455 if (pop_getline (server, &fromline) < 0)
1457 return (-1);
1460 if (! strncmp (fromline, "+OK", 3))
1461 return (0);
1462 else if (! strncmp (fromline, "-ERR", 4))
1464 snprintf (pop_error, ERROR_MAX, "%s", fromline);
1465 return (-1);
1467 else
1469 strcpy (pop_error,
1470 "Unexpected response from server; expecting +OK or -ERR");
1471 pop_trash (server);
1472 return (-1);
1476 #if 0
1478 * Function: gettermination
1480 * Purpose: Gets the next line and verifies that it is a termination
1481 * line (nothing but a dot).
1483 * Return value: 0 on success, non-zero with pop_error set on error.
1485 * Side effects: Closes the connection on error.
1487 static int
1488 gettermination (server)
1489 popserver server;
1491 char *fromserver;
1493 if (pop_getline (server, &fromserver) < 0)
1494 return (-1);
1496 if (strcmp (fromserver, "."))
1498 strcpy (pop_error,
1499 "Unexpected response from server in gettermination");
1500 pop_trash (server);
1501 return (-1);
1504 return (0);
1506 #endif
1509 * Function pop_close
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.
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.
1520 void
1521 pop_close (popserver server)
1523 pop_trash (server);
1524 free ((char *) server);
1526 return;
1530 * Function: pop_trash
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.
1536 static void
1537 pop_trash (popserver server)
1539 if (server->file >= 0)
1541 /* avoid recursion; sendline can call pop_trash */
1542 if (server->trash_started)
1543 return;
1544 server->trash_started = true;
1546 sendline (server, "RSET");
1547 sendline (server, "QUIT");
1549 CLOSESOCKET (server->file);
1550 server->file = -1;
1551 if (server->buffer)
1553 free (server->buffer);
1554 server->buffer = 0;
1558 #ifdef WINDOWSNT
1559 if (have_winsock)
1560 WSACleanup ();
1561 #endif
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. */
1568 static char *
1569 find_crlf (char *in_string, int len)
1571 while (len--)
1573 if (*in_string == '\r')
1575 if (*++in_string == '\n')
1576 return (in_string - 1);
1578 else
1579 in_string++;
1581 return (0);
1584 #endif /* MAIL_USE_POP */