* admin/gitmerge.el (gitmerge-missing):
[emacs.git] / lib-src / pop.c
blobba5ac6eb8252e0b57c46d31d822b9085a08975f5
1 /* pop.c: client routines for talking to a POP3-protocol post-office server
3 Copyright (C) 1991, 1993, 1996-1997, 1999, 2001-2017 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 <https://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 #undef _WIN32_WINNT
32 #define _WIN32_WINNT 0x0501 /* for getaddrinfo stuff */
33 #include <winsock2.h>
34 #include <ws2tcpip.h>
35 #undef getaddrinfo
36 #define getaddrinfo sys_getaddrinfo
37 #undef freeaddrinfo
38 #define freeaddrinfo sys_freeaddrinfo
39 int sys_getaddrinfo (const char * node, const char * service,
40 const struct addrinfo * hints, struct addrinfo ** res);
41 void sys_freeaddrinfo (struct addrinfo * ai);
42 #undef SOCKET_ERROR
43 #define RECV(s,buf,len,flags) recv (s,buf,len,flags)
44 #define SEND(s,buf,len,flags) send (s,buf,len,flags)
45 #define CLOSESOCKET(s) closesocket (s)
46 #else
47 #include <netinet/in.h>
48 #include <sys/socket.h>
49 #define RECV(s,buf,len,flags) read (s,buf,len)
50 #define SEND(s,buf,len,flags) write (s,buf,len)
51 #define CLOSESOCKET(s) close (s)
52 #endif
53 #include <pop.h>
55 #ifdef HESIOD
56 #include <hesiod.h>
58 * It really shouldn't be necessary to put this declaration here, but
59 * the version of hesiod.h that Athena has installed in release 7.2
60 * doesn't declare this function; I don't know if the 7.3 version of
61 * hesiod.h does.
63 extern struct servent *hes_getservbyname (/* char *, char * */);
64 #endif
66 #include <alloca.h>
67 #include <pwd.h>
68 #include <netdb.h>
69 #include <errno.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <unistd.h>
75 #ifdef KERBEROS
76 # ifdef HAVE_KRB5_H
77 # include <krb5.h>
78 # endif
79 # ifdef HAVE_KRB_H
80 # include <krb.h>
81 # else
82 # ifdef HAVE_KERBEROSIV_KRB_H
83 # include <kerberosIV/krb.h>
84 # else
85 # ifdef HAVE_KERBEROS_KRB_H
86 # include <kerberos/krb.h>
87 # endif
88 # endif
89 # endif
90 # ifdef HAVE_COM_ERR_H
91 # include <com_err.h>
92 # endif
93 #endif /* KERBEROS */
95 #include <c-ctype.h>
96 #include <min-max.h>
98 #ifdef KERBEROS
99 #ifndef KERBEROS5
100 extern int krb_sendauth (/* long, int, KTEXT, char *, char *, char *,
101 u_long, MSG_DAT *, CREDENTIALS *, Key_schedule,
102 struct sockaddr_in *, struct sockaddr_in *,
103 char * */);
104 extern char *krb_realmofhost (/* char * */);
105 #endif /* ! KERBEROS5 */
106 #endif /* KERBEROS */
108 static int socket_connection (char *, int);
109 static int pop_getline (popserver, char **);
110 static int sendline (popserver, const char *);
111 static int fullwrite (int, char *, int);
112 static int getok (popserver);
113 #if 0
114 static int gettermination (popserver);
115 #endif
116 static void pop_trash (popserver);
117 static char *find_crlf (char *, int);
119 #define ERROR_MAX 160 /* a pretty arbitrary size, but needs
120 to be bigger than the original
121 value of 80 */
122 #define POP_PORT 110
123 #define POP_SERVICE "pop3" /* we don't want the POP2 port! */
124 #ifdef KERBEROS
125 #define KPOP_PORT 1109
126 #define KPOP_SERVICE "kpop" /* never used: look for 20060515 to see why */
127 #endif
129 char pop_error[ERROR_MAX];
130 bool pop_debug = false;
133 * Function: pop_open (char *host, char *username, char *password,
134 * int flags)
136 * Purpose: Establishes a connection with a post-office server, and
137 * completes the authorization portion of the session.
139 * Arguments:
140 * host The server host with which the connection should be
141 * established. Optional. If omitted, internal
142 * heuristics will be used to determine the server host,
143 * if possible.
144 * username
145 * The username of the mail-drop to access. Optional.
146 * If omitted, internal heuristics will be used to
147 * determine the username, if possible.
148 * password
149 * The password to use for authorization. If omitted,
150 * internal heuristics will be used to determine the
151 * password, if possible.
152 * flags A bit mask containing flags controlling certain
153 * functions of the routine. Valid flags are defined in
154 * the file pop.h
156 * Return value: Upon successful establishment of a connection, a
157 * non-null popserver will be returned. Otherwise, null will be
158 * returned, and the string variable pop_error will contain an
159 * explanation of the error.
161 popserver
162 pop_open (char *host, char *username, char *password, int flags)
164 int sock;
165 popserver server;
167 /* Determine the user name */
168 if (! username)
170 username = getenv ("USER");
171 if (! (username && *username))
173 username = getlogin ();
174 if (! (username && *username))
176 struct passwd *passwd;
177 passwd = getpwuid (getuid ());
178 if (passwd && passwd->pw_name && *passwd->pw_name)
180 username = passwd->pw_name;
182 else
184 strcpy (pop_error, "Could not determine username");
185 return (0);
192 * Determine the mail host.
195 if (! host)
197 host = getenv ("MAILHOST");
200 #ifdef HESIOD
201 if ((! host) && (! (flags & POP_NO_HESIOD)))
203 struct hes_postoffice *office;
204 office = hes_getmailhost (username);
205 if (office && office->po_type && (! strcmp (office->po_type, "POP"))
206 && office->po_name && *office->po_name && office->po_host
207 && *office->po_host)
209 host = office->po_host;
210 username = office->po_name;
213 #endif
215 #ifdef MAILHOST
216 if (! host)
218 host = MAILHOST;
220 #endif
222 if (! host)
224 strcpy (pop_error, "Could not determine POP server");
225 return (0);
228 /* Determine the password */
229 #ifdef KERBEROS
230 #define DONT_NEED_PASSWORD (! (flags & POP_NO_KERBEROS))
231 #else
232 #define DONT_NEED_PASSWORD 0
233 #endif
235 if ((! password) && (! DONT_NEED_PASSWORD))
237 if (! (flags & POP_NO_GETPASS))
239 password = getpass ("Enter POP password:");
241 if (! password)
243 strcpy (pop_error, "Could not determine POP password");
244 return (0);
247 if (password) /* always true, detected 20060515 */
248 flags |= POP_NO_KERBEROS;
249 else
250 password = username; /* dead code, detected 20060515 */
251 /** "kpop" service is never used: look for 20060515 to see why **/
253 sock = socket_connection (host, flags);
254 if (sock == -1)
255 return (0);
257 server = (popserver) malloc (sizeof (struct _popserver));
258 if (! server)
260 strcpy (pop_error, "Out of memory in pop_open");
261 return (0);
263 server->buffer = (char *) malloc (GETLINE_MIN);
264 if (! server->buffer)
266 strcpy (pop_error, "Out of memory in pop_open");
267 free ((char *) server);
268 return (0);
271 server->file = sock;
272 server->data = 0;
273 server->buffer_index = 0;
274 server->buffer_size = GETLINE_MIN;
275 server->in_multi = false;
276 server->trash_started = false;
278 if (getok (server))
279 return (0);
282 * I really shouldn't use the pop_error variable like this, but....
284 if (strlen (username) > ERROR_MAX - 6)
286 pop_close (server);
287 strcpy (pop_error,
288 "Username too long; recompile pop.c with larger ERROR_MAX");
289 return (0);
291 sprintf (pop_error, "USER %s", username);
293 if (sendline (server, pop_error) || getok (server))
295 return (0);
298 if (strlen (password) > ERROR_MAX - 6)
300 pop_close (server);
301 strcpy (pop_error,
302 "Password too long; recompile pop.c with larger ERROR_MAX");
303 return (0);
305 sprintf (pop_error, "PASS %s", password);
307 if (sendline (server, pop_error) || getok (server))
309 return (0);
312 return (server);
316 * Function: pop_stat
318 * Purpose: Issue the STAT command to the server and return (in the
319 * value parameters) the number of messages in the maildrop and
320 * the total size of the maildrop.
322 * Return value: 0 on success, or non-zero with an error in pop_error
323 * in failure.
325 * Side effects: On failure, may make further operations on the
326 * connection impossible.
329 pop_stat (popserver server, int *count, int *size)
331 char *fromserver;
332 char *end_ptr;
334 if (server->in_multi)
336 strcpy (pop_error, "In multi-line query in pop_stat");
337 return (-1);
340 if (sendline (server, "STAT") || (pop_getline (server, &fromserver) < 0))
341 return (-1);
343 if (strncmp (fromserver, "+OK ", 4))
345 if (0 == strncmp (fromserver, "-ERR", 4))
346 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
347 else
349 strcpy (pop_error,
350 "Unexpected response from POP server in pop_stat");
351 pop_trash (server);
353 return (-1);
356 errno = 0;
357 *count = strtol (&fromserver[4], &end_ptr, 10);
358 /* Check validity of string-to-integer conversion. */
359 if (fromserver + 4 == end_ptr || *end_ptr != ' ' || errno)
361 strcpy (pop_error, "Unexpected response from POP server in pop_stat");
362 pop_trash (server);
363 return (-1);
366 fromserver = end_ptr;
368 errno = 0;
369 *size = strtol (fromserver + 1, &end_ptr, 10);
370 if (fromserver + 1 == end_ptr || errno)
372 strcpy (pop_error, "Unexpected response from POP server in pop_stat");
373 pop_trash (server);
374 return (-1);
377 return (0);
381 * Function: pop_list
383 * Purpose: Performs the POP "list" command and returns (in value
384 * parameters) two malloc'd zero-terminated arrays -- one of
385 * message IDs, and a parallel one of sizes.
387 * Arguments:
388 * server The pop connection to talk to.
389 * message The number of the one message about which to get
390 * information, or 0 to get information about all
391 * messages.
393 * Return value: 0 on success, non-zero with error in pop_error on
394 * failure.
396 * Side effects: On failure, may make further operations on the
397 * connection impossible.
400 pop_list (popserver server, int message, int **IDs, int **sizes)
402 int how_many, i;
403 char *fromserver;
405 if (server->in_multi)
407 strcpy (pop_error, "In multi-line query in pop_list");
408 return (-1);
411 if (message)
412 how_many = 1;
413 else
415 int count, size;
416 if (pop_stat (server, &count, &size))
417 return (-1);
418 how_many = count;
421 *IDs = (int *) malloc ((how_many + 1) * sizeof (int));
422 *sizes = (int *) malloc ((how_many + 1) * sizeof (int));
423 if (! (*IDs && *sizes))
425 strcpy (pop_error, "Out of memory in pop_list");
426 return (-1);
429 if (message)
431 sprintf (pop_error, "LIST %d", message);
432 if (sendline (server, pop_error))
434 free ((char *) *IDs);
435 free ((char *) *sizes);
436 return (-1);
438 if (pop_getline (server, &fromserver) < 0)
440 free ((char *) *IDs);
441 free ((char *) *sizes);
442 return (-1);
444 if (strncmp (fromserver, "+OK ", 4))
446 if (! strncmp (fromserver, "-ERR", 4))
447 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
448 else
450 strcpy (pop_error,
451 "Unexpected response from server in pop_list");
452 pop_trash (server);
454 free ((char *) *IDs);
455 free ((char *) *sizes);
456 return (-1);
458 (*IDs)[0] = atoi (&fromserver[4]);
459 fromserver = strchr (&fromserver[4], ' ');
460 if (! fromserver)
462 strcpy (pop_error,
463 "Badly formatted response from server in pop_list");
464 pop_trash (server);
465 free ((char *) *IDs);
466 free ((char *) *sizes);
467 return (-1);
469 (*sizes)[0] = atoi (fromserver);
470 (*IDs)[1] = (*sizes)[1] = 0;
471 return (0);
473 else
475 if (pop_multi_first (server, "LIST", &fromserver))
477 free ((char *) *IDs);
478 free ((char *) *sizes);
479 return (-1);
481 for (i = 0; i < how_many; i++)
483 if (pop_multi_next (server, &fromserver) <= 0)
485 free ((char *) *IDs);
486 free ((char *) *sizes);
487 return (-1);
489 (*IDs)[i] = atoi (fromserver);
490 fromserver = strchr (fromserver, ' ');
491 if (! fromserver)
493 strcpy (pop_error,
494 "Badly formatted response from server in pop_list");
495 free ((char *) *IDs);
496 free ((char *) *sizes);
497 pop_trash (server);
498 return (-1);
500 (*sizes)[i] = atoi (fromserver);
502 if (pop_multi_next (server, &fromserver) < 0)
504 free ((char *) *IDs);
505 free ((char *) *sizes);
506 return (-1);
508 else if (fromserver)
510 strcpy (pop_error,
511 "Too many response lines from server in pop_list");
512 free ((char *) *IDs);
513 free ((char *) *sizes);
514 return (-1);
516 (*IDs)[i] = (*sizes)[i] = 0;
517 return (0);
522 * Function: pop_retrieve
524 * Purpose: Retrieve a specified message from the maildrop.
526 * Arguments:
527 * server The server to retrieve from.
528 * message The message number to retrieve.
529 * markfrom
530 * If true, then mark the string "From " at the beginning
531 * of lines with '>'.
532 * msg_buf Output parameter to which a buffer containing the
533 * message is assigned.
535 * Return value: The number of bytes in msg_buf, which may contain
536 * embedded nulls, not including its final null, or -1 on error
537 * with pop_error set.
539 * Side effects: May kill connection on error.
542 pop_retrieve (popserver server, int message, int markfrom, char **msg_buf)
544 int *IDs, *sizes, bufsize, fromcount = 0, cp = 0;
545 char *ptr, *fromserver;
546 int ret;
548 if (server->in_multi)
550 strcpy (pop_error, "In multi-line query in pop_retrieve");
551 return (-1);
554 if (pop_list (server, message, &IDs, &sizes))
555 return (-1);
557 if (pop_retrieve_first (server, message, &fromserver))
559 return (-1);
563 * The "5" below is an arbitrary constant -- I assume that if
564 * there are "From" lines in the text to be marked, there
565 * probably won't be more than 5 of them. If there are, I
566 * allocate more space for them below.
568 bufsize = sizes[0] + (markfrom ? 5 : 0);
569 ptr = (char *)malloc (bufsize);
570 free ((char *) IDs);
571 free ((char *) sizes);
573 if (! ptr)
575 strcpy (pop_error, "Out of memory in pop_retrieve");
576 pop_retrieve_flush (server);
577 return (-1);
580 while ((ret = pop_retrieve_next (server, &fromserver)) >= 0)
582 if (! fromserver)
584 ptr[cp] = '\0';
585 *msg_buf = ptr;
586 return (cp);
588 if (markfrom && fromserver[0] == 'F' && fromserver[1] == 'r' &&
589 fromserver[2] == 'o' && fromserver[3] == 'm' &&
590 fromserver[4] == ' ')
592 if (++fromcount == 5)
594 bufsize += 5;
595 ptr = (char *)realloc (ptr, bufsize);
596 if (! ptr)
598 strcpy (pop_error, "Out of memory in pop_retrieve");
599 pop_retrieve_flush (server);
600 return (-1);
602 fromcount = 0;
604 ptr[cp++] = '>';
606 memcpy (&ptr[cp], fromserver, ret);
607 cp += ret;
608 ptr[cp++] = '\n';
611 free (ptr);
612 return (-1);
616 pop_retrieve_first (popserver server, int message, char **response)
618 sprintf (pop_error, "RETR %d", message);
619 return (pop_multi_first (server, pop_error, response));
623 Returns a negative number on error, 0 to indicate that the data has
624 all been read (i.e., the server has returned a "." termination
625 line), or a positive number indicating the number of bytes in the
626 returned buffer (which is null-terminated and may contain embedded
627 nulls, but the returned bytecount doesn't include the final null).
631 pop_retrieve_next (popserver server, char **line)
633 return (pop_multi_next (server, line));
637 pop_retrieve_flush (popserver server)
639 return (pop_multi_flush (server));
643 pop_top_first (popserver server, int message, int lines, char **response)
645 sprintf (pop_error, "TOP %d %d", message, lines);
646 return (pop_multi_first (server, pop_error, response));
650 Returns a negative number on error, 0 to indicate that the data has
651 all been read (i.e., the server has returned a "." termination
652 line), or a positive number indicating the number of bytes in the
653 returned buffer (which is null-terminated and may contain embedded
654 nulls, but the returned bytecount doesn't include the final null).
658 pop_top_next (popserver server, char **line)
660 return (pop_multi_next (server, line));
664 pop_top_flush (popserver server)
666 return (pop_multi_flush (server));
670 pop_multi_first (popserver server, const char *command, char **response)
672 if (server->in_multi)
674 strcpy (pop_error,
675 "Already in multi-line query in pop_multi_first");
676 return (-1);
679 if (sendline (server, command) || (pop_getline (server, response) < 0))
681 return (-1);
684 if (0 == strncmp (*response, "-ERR", 4))
686 snprintf (pop_error, ERROR_MAX, "%s", *response);
687 return (-1);
689 else if (0 == strncmp (*response, "+OK", 3))
691 for (*response += 3; **response == ' '; (*response)++) /* empty */;
692 server->in_multi = true;
693 return (0);
695 else
697 strcpy (pop_error,
698 "Unexpected response from server in pop_multi_first");
699 return (-1);
704 Read the next line of data from SERVER and place a pointer to it
705 into LINE. Return -1 on error, 0 if there are no more lines to read
706 (i.e., the server has returned a line containing only "."), or a
707 positive number indicating the number of bytes in the LINE buffer
708 (not including the final null). The data in that buffer may contain
709 embedded nulls, but does not contain the final CRLF. When returning
710 0, LINE is set to null. */
713 pop_multi_next (popserver server, char **line)
715 char *fromserver;
716 int ret;
718 if (! server->in_multi)
720 strcpy (pop_error, "Not in multi-line query in pop_multi_next");
721 return (-1);
724 ret = pop_getline (server, &fromserver);
725 if (ret < 0)
727 return (-1);
730 if (fromserver[0] == '.')
732 if (! fromserver[1])
734 *line = 0;
735 server->in_multi = false;
736 return (0);
738 else
740 *line = fromserver + 1;
741 return (ret - 1);
744 else
746 *line = fromserver;
747 return (ret);
752 pop_multi_flush (popserver server)
754 char *line;
755 int ret;
757 if (! server->in_multi)
759 return (0);
762 while ((ret = pop_multi_next (server, &line)))
764 if (ret < 0)
765 return (-1);
768 return (0);
771 /* Function: pop_delete
773 * Purpose: Delete a specified message.
775 * Arguments:
776 * server Server from which to delete the message.
777 * message Message to delete.
779 * Return value: 0 on success, non-zero with error in pop_error
780 * otherwise.
783 pop_delete (popserver server, int message)
785 if (server->in_multi)
787 strcpy (pop_error, "In multi-line query in pop_delete");
788 return (-1);
791 sprintf (pop_error, "DELE %d", message);
793 if (sendline (server, pop_error) || getok (server))
794 return (-1);
796 return (0);
800 * Function: pop_noop
802 * Purpose: Send a noop command to the server.
804 * Argument:
805 * server The server to send to.
807 * Return value: 0 on success, non-zero with error in pop_error
808 * otherwise.
810 * Side effects: Closes connection on error.
813 pop_noop (popserver server)
815 if (server->in_multi)
817 strcpy (pop_error, "In multi-line query in pop_noop");
818 return (-1);
821 if (sendline (server, "NOOP") || getok (server))
822 return (-1);
824 return (0);
828 * Function: pop_last
830 * Purpose: Find out the highest seen message from the server.
832 * Arguments:
833 * server The server.
835 * Return value: If successful, the highest seen message, which is
836 * greater than or equal to 0. Otherwise, a negative number with
837 * the error explained in pop_error.
839 * Side effects: Closes the connection on error.
842 pop_last (popserver server)
844 char *fromserver;
846 if (server->in_multi)
848 strcpy (pop_error, "In multi-line query in pop_last");
849 return (-1);
852 if (sendline (server, "LAST"))
853 return (-1);
855 if (pop_getline (server, &fromserver) < 0)
856 return (-1);
858 if (! strncmp (fromserver, "-ERR", 4))
860 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
861 return (-1);
863 else if (strncmp (fromserver, "+OK ", 4))
865 strcpy (pop_error, "Unexpected response from server in pop_last");
866 pop_trash (server);
867 return (-1);
869 else
871 char *end_ptr;
872 int count;
873 errno = 0;
874 count = strtol (&fromserver[4], &end_ptr, 10);
875 if (fromserver + 4 == end_ptr || errno)
877 strcpy (pop_error, "Unexpected response from server in pop_last");
878 pop_trash (server);
879 return (-1);
881 return count;
886 * Function: pop_reset
888 * Purpose: Reset the server to its initial connect state
890 * Arguments:
891 * server The server.
893 * Return value: 0 for success, non-0 with error in pop_error
894 * otherwise.
896 * Side effects: Closes the connection on error.
899 pop_reset (popserver server)
901 if (pop_retrieve_flush (server))
903 return (-1);
906 if (sendline (server, "RSET") || getok (server))
907 return (-1);
909 return (0);
913 * Function: pop_quit
915 * Purpose: Quit the connection to the server,
917 * Arguments:
918 * server The server to quit.
920 * Return value: 0 for success, non-zero otherwise with error in
921 * pop_error.
923 * Side Effects: The popserver passed in is unusable after this
924 * function is called, even if an error occurs.
927 pop_quit (popserver server)
929 int ret = 0;
931 if (server->file >= 0)
933 if (pop_retrieve_flush (server))
935 ret = -1;
938 if (sendline (server, "QUIT") || getok (server))
940 ret = -1;
943 close (server->file);
946 free (server->buffer);
947 free ((char *) server);
949 return (ret);
952 #ifdef WINDOWSNT
953 static int have_winsock = 0;
954 #endif
957 * Function: socket_connection
959 * Purpose: Opens the network connection with the mail host, without
960 * doing any sort of I/O with it or anything.
962 * Arguments:
963 * host The host to which to connect.
964 * flags Option flags.
966 * Return value: A file descriptor indicating the connection, or -1
967 * indicating failure, in which case an error has been copied
968 * into pop_error.
970 static int
971 socket_connection (char *host, int flags)
973 struct addrinfo *res, *it;
974 struct addrinfo hints;
975 int ret;
976 struct servent *servent;
977 struct sockaddr_in addr;
978 char found_port = 0;
979 const char *service;
980 int sock;
981 char *realhost;
982 #ifdef KERBEROS
983 #ifdef KERBEROS5
984 krb5_error_code rem;
985 krb5_context kcontext = 0;
986 krb5_auth_context auth_context = 0;
987 krb5_ccache ccdef;
988 krb5_principal client, server;
989 krb5_error *err_ret;
990 register char *cp;
991 #else
992 KTEXT ticket;
993 MSG_DAT msg_data;
994 CREDENTIALS cred;
995 Key_schedule schedule;
996 int rem;
997 #endif /* KERBEROS5 */
998 #endif /* KERBEROS */
1000 int try_count = 0;
1001 int connect_ok;
1003 #ifdef WINDOWSNT
1005 WSADATA winsockData;
1006 if (WSAStartup (0x101, &winsockData) == 0)
1007 have_winsock = 1;
1009 #endif
1011 memset (&addr, 0, sizeof (addr));
1012 addr.sin_family = AF_INET;
1014 /** "kpop" service is never used: look for 20060515 to see why **/
1015 #ifdef KERBEROS
1016 service = (flags & POP_NO_KERBEROS) ? POP_SERVICE : KPOP_SERVICE;
1017 #else
1018 service = POP_SERVICE;
1019 #endif
1021 #ifdef HESIOD
1022 if (! (flags & POP_NO_HESIOD))
1024 servent = hes_getservbyname (service, "tcp");
1025 if (servent)
1027 addr.sin_port = servent->s_port;
1028 found_port = 1;
1031 #endif
1032 if (! found_port)
1034 servent = getservbyname (service, "tcp");
1035 if (servent)
1037 addr.sin_port = servent->s_port;
1039 else
1041 /** "kpop" service is never used: look for 20060515 to see why **/
1042 #ifdef KERBEROS
1043 addr.sin_port = htons ((flags & POP_NO_KERBEROS) ?
1044 POP_PORT : KPOP_PORT);
1045 #else
1046 addr.sin_port = htons (POP_PORT);
1047 #endif
1051 #define POP_SOCKET_ERROR "Could not create socket for POP connection: "
1053 sock = socket (PF_INET, SOCK_STREAM, 0);
1054 if (sock < 0)
1056 snprintf (pop_error, ERROR_MAX, "%s%s",
1057 POP_SOCKET_ERROR, strerror (errno));
1058 return (-1);
1062 memset (&hints, 0, sizeof (hints));
1063 hints.ai_socktype = SOCK_STREAM;
1064 hints.ai_flags = AI_CANONNAME;
1065 hints.ai_family = AF_INET;
1068 ret = getaddrinfo (host, service, &hints, &res);
1069 try_count++;
1070 if (ret != 0 && (ret != EAI_AGAIN || try_count == 5))
1072 strcpy (pop_error, "Could not determine POP server's address");
1073 return (-1);
1075 } while (ret != 0);
1077 for (it = res; it; it = it->ai_next)
1078 if (it->ai_addrlen == sizeof addr)
1080 struct sockaddr_in *in_a = (struct sockaddr_in *) it->ai_addr;
1081 addr.sin_addr = in_a->sin_addr;
1082 if (! connect (sock, (struct sockaddr *) &addr, sizeof addr))
1083 break;
1085 connect_ok = it != NULL;
1086 if (connect_ok)
1088 realhost = alloca (strlen (it->ai_canonname) + 1);
1089 strcpy (realhost, it->ai_canonname);
1091 freeaddrinfo (res);
1093 #define CONNECT_ERROR "Could not connect to POP server: "
1095 if (! connect_ok)
1097 CLOSESOCKET (sock);
1098 snprintf (pop_error, ERROR_MAX, "%s%s", CONNECT_ERROR, strerror (errno));
1099 return (-1);
1103 #ifdef KERBEROS
1105 #define KRB_ERROR "Kerberos error connecting to POP server: "
1106 if (! (flags & POP_NO_KERBEROS))
1108 #ifdef KERBEROS5
1109 rem = krb5_init_context (&kcontext);
1110 if (rem)
1112 krb5error:
1113 if (auth_context)
1114 krb5_auth_con_free (kcontext, auth_context);
1115 if (kcontext)
1116 krb5_free_context (kcontext);
1117 snprintf (pop_error, ERROR_MAX, "%s%s",
1118 KRB_ERROR, error_message (rem));
1119 CLOSESOCKET (sock);
1120 return (-1);
1123 rem = krb5_auth_con_init (kcontext, &auth_context);
1124 if (rem)
1125 goto krb5error;
1127 rem = krb5_cc_default (kcontext, &ccdef);
1128 if (rem)
1129 goto krb5error;
1131 rem = krb5_cc_get_principal (kcontext, ccdef, &client);
1132 if (rem)
1133 goto krb5error;
1135 for (cp = realhost; *cp; cp++)
1136 *cp = c_tolower (*cp);
1138 rem = krb5_sname_to_principal (kcontext, realhost,
1139 POP_SERVICE, FALSE, &server);
1140 if (rem)
1141 goto krb5error;
1143 rem = krb5_sendauth (kcontext, &auth_context,
1144 (krb5_pointer) &sock, (char *) "KPOPV1.0",
1145 client, server,
1146 AP_OPTS_MUTUAL_REQUIRED,
1147 0, /* no checksum */
1148 0, /* no creds, use ccache instead */
1149 ccdef,
1150 &err_ret,
1151 0, /* don't need subsession key */
1152 0); /* don't need reply */
1153 krb5_free_principal (kcontext, server);
1154 if (rem)
1156 int pop_error_len = snprintf (pop_error, ERROR_MAX, "%s%s",
1157 KRB_ERROR, error_message (rem));
1158 #if defined HAVE_KRB5_ERROR_TEXT
1159 if (err_ret && err_ret->text.length)
1161 int errlen = err_ret->text.length;
1162 snprintf (pop_error + pop_error_len, ERROR_MAX - pop_error_len,
1163 " [server says '%.*s']", errlen, err_ret->text.data);
1165 #elif defined HAVE_KRB5_ERROR_E_TEXT
1166 if (err_ret && err_ret->e_text && **err_ret->e_text)
1167 snprintf (pop_error + pop_error_len, ERROR_MAX - pop_error_len,
1168 " [server says '%s']", *err_ret->e_text);
1169 #endif
1170 if (err_ret)
1171 krb5_free_error (kcontext, err_ret);
1172 krb5_auth_con_free (kcontext, auth_context);
1173 krb5_free_context (kcontext);
1175 CLOSESOCKET (sock);
1176 return (-1);
1178 #else /* ! KERBEROS5 */
1179 ticket = (KTEXT) malloc (sizeof (KTEXT_ST));
1180 rem = krb_sendauth (0L, sock, ticket, "pop", realhost,
1181 (char *) krb_realmofhost (realhost),
1182 (unsigned long) 0, &msg_data, &cred, schedule,
1183 (struct sockaddr_in *) 0,
1184 (struct sockaddr_in *) 0,
1185 "KPOPV0.1");
1186 free ((char *) ticket);
1187 if (rem != KSUCCESS)
1189 snprintf (pop_error, ERROR_MAX, "%s%s", KRB_ERROR, krb_err_txt[rem]);
1190 CLOSESOCKET (sock);
1191 return (-1);
1193 #endif /* KERBEROS5 */
1195 #endif /* KERBEROS */
1197 return (sock);
1198 } /* socket_connection */
1201 * Function: pop_getline
1203 * Purpose: Get a line of text from the connection and return a
1204 * pointer to it. The carriage return and linefeed at the end of
1205 * the line are stripped, but periods at the beginnings of lines
1206 * are NOT dealt with in any special way.
1208 * Arguments:
1209 * server The server from which to get the line of text.
1211 * Returns: The number of characters in the line, which is returned in
1212 * LINE, not including the final null. A return value of 0
1213 * indicates a blank line. A negative return value indicates an
1214 * error (in which case the contents of LINE are undefined. In
1215 * case of error, an error message is copied into pop_error.
1217 * Notes: The line returned is overwritten with each call to pop_getline.
1219 * Side effects: Closes the connection on error.
1221 * THE RETURNED LINE MAY CONTAIN EMBEDDED NULLS!
1223 static int
1224 pop_getline (popserver server, char **line)
1226 #define GETLINE_ERROR "Error reading from server: "
1228 int ret;
1229 int search_offset = 0;
1231 if (server->data)
1233 char *cp = find_crlf (server->buffer + server->buffer_index,
1234 server->data);
1235 if (cp)
1237 int found;
1238 int data_used;
1240 found = server->buffer_index;
1241 data_used = (cp + 2) - server->buffer - found;
1243 *cp = '\0'; /* terminate the string to be returned */
1244 server->data -= data_used;
1245 server->buffer_index += data_used;
1247 if (pop_debug)
1248 /* Embedded nulls will truncate this output prematurely,
1249 but that's OK because it's just for debugging anyway. */
1250 fprintf (stderr, "<<< %s\n", server->buffer + found);
1251 *line = server->buffer + found;
1252 return (data_used - 2);
1254 else
1256 memmove (server->buffer, server->buffer + server->buffer_index,
1257 server->data);
1258 /* Record the fact that we've searched the data already in
1259 the buffer for a CRLF, so that when we search below, we
1260 don't have to search the same data twice. There's a "-
1261 1" here to account for the fact that the last character
1262 of the data we have may be the CR of a CRLF pair, of
1263 which we haven't read the second half yet, so we may have
1264 to search it again when we read more data. */
1265 search_offset = server->data - 1;
1266 server->buffer_index = 0;
1269 else
1271 server->buffer_index = 0;
1274 while (1)
1276 /* There's a "- 1" here to leave room for the null that we put
1277 at the end of the read data below. We put the null there so
1278 that find_crlf knows where to stop when we call it. */
1279 if (server->data == server->buffer_size - 1)
1281 server->buffer_size += GETLINE_INCR;
1282 server->buffer = (char *)realloc (server->buffer, server->buffer_size);
1283 if (! server->buffer)
1285 strcpy (pop_error, "Out of memory in pop_getline");
1286 pop_trash (server);
1287 return (-1);
1290 ret = RECV (server->file, server->buffer + server->data,
1291 server->buffer_size - server->data - 1, 0);
1292 if (ret < 0)
1294 snprintf (pop_error, ERROR_MAX, "%s%s",
1295 GETLINE_ERROR, strerror (errno));
1296 pop_trash (server);
1297 return (-1);
1299 else if (ret == 0)
1301 strcpy (pop_error, "Unexpected EOF from server in pop_getline");
1302 pop_trash (server);
1303 return (-1);
1305 else
1307 char *cp;
1308 server->data += ret;
1309 server->buffer[server->data] = '\0';
1311 cp = find_crlf (server->buffer + search_offset,
1312 server->data - search_offset);
1313 if (cp)
1315 int data_used = (cp + 2) - server->buffer;
1316 *cp = '\0';
1317 server->data -= data_used;
1318 server->buffer_index = data_used;
1320 if (pop_debug)
1321 fprintf (stderr, "<<< %s\n", server->buffer);
1322 *line = server->buffer;
1323 return (data_used - 2);
1325 /* As above, the "- 1" here is to account for the fact that
1326 we may have read a CR without its accompanying LF. */
1327 search_offset += ret - 1;
1331 /* NOTREACHED */
1335 * Function: sendline
1337 * Purpose: Sends a line of text to the POP server. The line of text
1338 * passed into this function should NOT have the carriage return
1339 * and linefeed on the end of it. Periods at beginnings of lines
1340 * will NOT be treated specially by this function.
1342 * Arguments:
1343 * server The server to which to send the text.
1344 * line The line of text to send.
1346 * Return value: Upon successful completion, a value of 0 will be
1347 * returned. Otherwise, a non-zero value will be returned, and
1348 * an error will be copied into pop_error.
1350 * Side effects: Closes the connection on error.
1352 static int
1353 sendline (popserver server, const char *line)
1355 #define SENDLINE_ERROR "Error writing to POP server: "
1356 int ret;
1357 char *buf;
1359 /* Combine the string and the CR-LF into one buffer. Otherwise, two
1360 reasonable network stack optimizations, Nagle's algorithm and
1361 delayed acks, combine to delay us a fraction of a second on every
1362 message we send. (Movemail writes line without \r\n, client
1363 kernel sends packet, server kernel delays the ack to see if it
1364 can combine it with data, movemail writes \r\n, client kernel
1365 waits because it has unacked data already in its outgoing queue,
1366 client kernel eventually times out and sends.)
1368 This can be something like 0.2s per command, which can add up
1369 over a few dozen messages, and is a big chunk of the time we
1370 spend fetching mail from a server close by. */
1371 buf = alloca (strlen (line) + 3);
1372 strcpy (stpcpy (buf, line), "\r\n");
1373 ret = fullwrite (server->file, buf, strlen (buf));
1375 if (ret < 0)
1377 pop_trash (server);
1378 snprintf (pop_error, ERROR_MAX, "%s%s", SENDLINE_ERROR, strerror (errno));
1379 return (ret);
1382 if (pop_debug)
1383 fprintf (stderr, ">>> %s\n", line);
1385 return (0);
1389 * Procedure: fullwrite
1391 * Purpose: Just like write, but keeps trying until the entire string
1392 * has been written.
1394 * Return value: Same as write. Pop_error is not set.
1396 static int
1397 fullwrite (int fd, char *buf, int nbytes)
1399 char *cp;
1400 int ret = 0;
1402 cp = buf;
1403 while (nbytes && ((ret = SEND (fd, cp, nbytes, 0)) > 0))
1405 cp += ret;
1406 nbytes -= ret;
1409 return (ret);
1413 * Procedure getok
1415 * Purpose: Reads a line from the server. If the return indicator is
1416 * positive, return with a zero exit status. If not, return with
1417 * a negative exit status.
1419 * Arguments:
1420 * server The server to read from.
1422 * Returns: 0 for success, else for failure and puts error in pop_error.
1424 * Side effects: On failure, may make the connection unusable.
1426 static int
1427 getok (popserver server)
1429 char *fromline;
1431 if (pop_getline (server, &fromline) < 0)
1433 return (-1);
1436 if (! strncmp (fromline, "+OK", 3))
1437 return (0);
1438 else if (! strncmp (fromline, "-ERR", 4))
1440 snprintf (pop_error, ERROR_MAX, "%s", fromline);
1441 return (-1);
1443 else
1445 strcpy (pop_error,
1446 "Unexpected response from server; expecting +OK or -ERR");
1447 pop_trash (server);
1448 return (-1);
1452 #if 0
1454 * Function: gettermination
1456 * Purpose: Gets the next line and verifies that it is a termination
1457 * line (nothing but a dot).
1459 * Return value: 0 on success, non-zero with pop_error set on error.
1461 * Side effects: Closes the connection on error.
1463 static int
1464 gettermination (server)
1465 popserver server;
1467 char *fromserver;
1469 if (pop_getline (server, &fromserver) < 0)
1470 return (-1);
1472 if (strcmp (fromserver, "."))
1474 strcpy (pop_error,
1475 "Unexpected response from server in gettermination");
1476 pop_trash (server);
1477 return (-1);
1480 return (0);
1482 #endif
1485 * Function pop_close
1487 * Purpose: Close a pop connection, sending a "RSET" command to try to
1488 * preserve any changes that were made and a "QUIT" command to
1489 * try to get the server to quit, but ignoring any responses that
1490 * are received.
1492 * Side effects: The server is unusable after this function returns.
1493 * Changes made to the maildrop since the session was started (or
1494 * since the last pop_reset) may be lost.
1496 void
1497 pop_close (popserver server)
1499 pop_trash (server);
1500 free ((char *) server);
1502 return;
1506 * Function: pop_trash
1508 * Purpose: Like pop_close or pop_quit, but doesn't deallocate the
1509 * memory associated with the server. It is valid to call
1510 * pop_close or pop_quit after this function has been called.
1512 static void
1513 pop_trash (popserver server)
1515 if (server->file >= 0)
1517 /* avoid recursion; sendline can call pop_trash */
1518 if (server->trash_started)
1519 return;
1520 server->trash_started = true;
1522 sendline (server, "RSET");
1523 sendline (server, "QUIT");
1525 CLOSESOCKET (server->file);
1526 server->file = -1;
1527 if (server->buffer)
1529 free (server->buffer);
1530 server->buffer = 0;
1534 #ifdef WINDOWSNT
1535 if (have_winsock)
1536 WSACleanup ();
1537 #endif
1540 /* Return a pointer to the first CRLF in IN_STRING, which can contain
1541 embedded nulls and has LEN characters in it not including the final
1542 null, or 0 if it does not contain one. */
1544 static char *
1545 find_crlf (char *in_string, int len)
1547 while (len--)
1549 if (*in_string == '\r')
1551 if (*++in_string == '\n')
1552 return (in_string - 1);
1554 else
1555 in_string++;
1557 return (0);
1560 #ifdef WINDOWSNT
1561 /* The following 2 functions are only available since XP, so we load
1562 them dynamically and provide fallbacks. */
1564 int (WINAPI *pfn_getaddrinfo) (const char *, const char *,
1565 const struct addrinfo *, struct addrinfo **);
1566 void (WINAPI *pfn_freeaddrinfo) (struct addrinfo *);
1568 static int
1569 load_ws2 (void)
1571 static int ws2_loaded = 0;
1573 if (!ws2_loaded)
1575 HANDLE ws2_lib = LoadLibrary ("Ws2_32.dll");
1577 if (ws2_lib != NULL)
1579 ws2_loaded = 1;
1580 pfn_getaddrinfo = (void *) GetProcAddress (ws2_lib, "getaddrinfo");
1581 pfn_freeaddrinfo = (void *) GetProcAddress (ws2_lib, "freeaddrinfo");
1582 /* Paranoia: these two functions should go together, so if
1583 one is absent, we cannot use the other. */
1584 if (pfn_getaddrinfo == NULL)
1585 pfn_freeaddrinfo = NULL;
1586 else if (pfn_freeaddrinfo == NULL)
1587 pfn_getaddrinfo = NULL;
1590 if (!ws2_loaded)
1592 errno = ENETDOWN;
1593 return -1;
1595 return 0;
1600 sys_getaddrinfo (const char *node, const char *service,
1601 const struct addrinfo *hints, struct addrinfo **res)
1603 int rc;
1605 if (load_ws2 () != 0)
1607 errno = ENETDOWN;
1608 return WSANO_RECOVERY;
1611 if (pfn_getaddrinfo)
1612 rc = pfn_getaddrinfo (node, service, hints, res);
1613 else
1615 int port = 0;
1616 struct hostent *host_info;
1617 struct gai_storage {
1618 struct addrinfo addrinfo;
1619 struct sockaddr_in sockaddr_in;
1620 } *gai_storage;
1622 /* We don't support any flags besides AI_CANONNAME. */
1623 if (hints && (hints->ai_flags & ~(AI_CANONNAME)) != 0)
1624 return WSAEINVAL;
1625 /* NODE cannot be NULL, since pop.c has fallbacks for that. */
1626 if (!node)
1627 return WSAHOST_NOT_FOUND;
1629 if (service)
1631 const char *protocol =
1632 (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
1633 struct servent *srv = getservbyname (service, protocol);
1635 if (srv)
1636 port = srv->s_port;
1637 else
1638 return WSAHOST_NOT_FOUND;
1641 gai_storage = calloc (1, sizeof *gai_storage);
1642 gai_storage->sockaddr_in.sin_port = port;
1643 host_info = gethostbyname (node);
1644 if (host_info)
1646 memcpy (&gai_storage->sockaddr_in.sin_addr,
1647 host_info->h_addr, host_info->h_length);
1648 gai_storage->sockaddr_in.sin_family = host_info->h_addrtype;
1650 else
1652 free (gai_storage);
1653 return WSAHOST_NOT_FOUND;
1656 gai_storage->addrinfo.ai_addr =
1657 (struct sockaddr *)&gai_storage->sockaddr_in;
1658 gai_storage->addrinfo.ai_addrlen = sizeof (gai_storage->sockaddr_in);
1659 if (hints && (hints->ai_flags & AI_CANONNAME) != 0)
1661 gai_storage->addrinfo.ai_canonname = strdup (host_info->h_name);
1662 if (!gai_storage->addrinfo.ai_canonname)
1664 free (gai_storage);
1665 return WSA_NOT_ENOUGH_MEMORY;
1668 gai_storage->addrinfo.ai_protocol = (hints) ? hints->ai_protocol : 0;
1669 gai_storage->addrinfo.ai_socktype = (hints) ? hints->ai_socktype : 0;
1670 gai_storage->addrinfo.ai_family = gai_storage->sockaddr_in.sin_family;
1671 gai_storage->addrinfo.ai_next = NULL;
1673 *res = &gai_storage->addrinfo;
1674 rc = 0;
1677 return rc;
1680 void
1681 sys_freeaddrinfo (struct addrinfo *ai)
1683 if (load_ws2 () != 0)
1685 errno = ENETDOWN;
1686 return;
1689 if (pfn_freeaddrinfo)
1690 pfn_freeaddrinfo (ai);
1691 else
1693 if (ai->ai_canonname)
1694 free (ai->ai_canonname);
1695 free (ai);
1698 #endif /* WINDOWSNT */
1699 #endif /* MAIL_USE_POP */