; Merge from origin/emacs-25
[emacs.git] / lib-src / pop.c
blob74a6fc151aa0d1e040ec2ddb636036aaeed6610f
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 #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 <pwd.h>
67 #include <netdb.h>
68 #include <errno.h>
69 #include <stdio.h>
70 #include <string.h>
71 #include <unistd.h>
73 #ifdef KERBEROS
74 # ifdef HAVE_KRB5_H
75 # include <krb5.h>
76 # endif
77 # ifdef HAVE_KRB_H
78 # include <krb.h>
79 # else
80 # ifdef HAVE_KERBEROSIV_KRB_H
81 # include <kerberosIV/krb.h>
82 # else
83 # ifdef HAVE_KERBEROS_KRB_H
84 # include <kerberos/krb.h>
85 # endif
86 # endif
87 # endif
88 # ifdef HAVE_COM_ERR_H
89 # include <com_err.h>
90 # endif
91 #endif /* KERBEROS */
93 #include <min-max.h>
95 #ifdef KERBEROS
96 #ifndef KERBEROS5
97 extern int krb_sendauth (/* long, int, KTEXT, char *, char *, char *,
98 u_long, MSG_DAT *, CREDENTIALS *, Key_schedule,
99 struct sockaddr_in *, struct sockaddr_in *,
100 char * */);
101 extern char *krb_realmofhost (/* char * */);
102 #endif /* ! KERBEROS5 */
103 #endif /* KERBEROS */
105 static int socket_connection (char *, int);
106 static int pop_getline (popserver, char **);
107 static int sendline (popserver, const char *);
108 static int fullwrite (int, char *, int);
109 static int getok (popserver);
110 #if 0
111 static int gettermination (popserver);
112 #endif
113 static void pop_trash (popserver);
114 static char *find_crlf (char *, int);
116 #define ERROR_MAX 160 /* a pretty arbitrary size, but needs
117 to be bigger than the original
118 value of 80 */
119 #define POP_PORT 110
120 #define POP_SERVICE "pop3" /* we don't want the POP2 port! */
121 #ifdef KERBEROS
122 #define KPOP_PORT 1109
123 #define KPOP_SERVICE "kpop" /* never used: look for 20060515 to see why */
124 #endif
126 char pop_error[ERROR_MAX];
127 bool pop_debug = false;
130 * Function: pop_open (char *host, char *username, char *password,
131 * int flags)
133 * Purpose: Establishes a connection with a post-office server, and
134 * completes the authorization portion of the session.
136 * Arguments:
137 * host The server host with which the connection should be
138 * established. Optional. If omitted, internal
139 * heuristics will be used to determine the server host,
140 * if possible.
141 * username
142 * The username of the mail-drop to access. Optional.
143 * If omitted, internal heuristics will be used to
144 * determine the username, if possible.
145 * password
146 * The password to use for authorization. If omitted,
147 * internal heuristics will be used to determine the
148 * password, if possible.
149 * flags A bit mask containing flags controlling certain
150 * functions of the routine. Valid flags are defined in
151 * the file pop.h
153 * Return value: Upon successful establishment of a connection, a
154 * non-null popserver will be returned. Otherwise, null will be
155 * returned, and the string variable pop_error will contain an
156 * explanation of the error.
158 popserver
159 pop_open (char *host, char *username, char *password, int flags)
161 int sock;
162 popserver server;
164 /* Determine the user name */
165 if (! username)
167 username = getenv ("USER");
168 if (! (username && *username))
170 username = getlogin ();
171 if (! (username && *username))
173 struct passwd *passwd;
174 passwd = getpwuid (getuid ());
175 if (passwd && passwd->pw_name && *passwd->pw_name)
177 username = passwd->pw_name;
179 else
181 strcpy (pop_error, "Could not determine username");
182 return (0);
189 * Determine the mail host.
192 if (! host)
194 host = getenv ("MAILHOST");
197 #ifdef HESIOD
198 if ((! host) && (! (flags & POP_NO_HESIOD)))
200 struct hes_postoffice *office;
201 office = hes_getmailhost (username);
202 if (office && office->po_type && (! strcmp (office->po_type, "POP"))
203 && office->po_name && *office->po_name && office->po_host
204 && *office->po_host)
206 host = office->po_host;
207 username = office->po_name;
210 #endif
212 #ifdef MAILHOST
213 if (! host)
215 host = MAILHOST;
217 #endif
219 if (! host)
221 strcpy (pop_error, "Could not determine POP server");
222 return (0);
225 /* Determine the password */
226 #ifdef KERBEROS
227 #define DONT_NEED_PASSWORD (! (flags & POP_NO_KERBEROS))
228 #else
229 #define DONT_NEED_PASSWORD 0
230 #endif
232 if ((! password) && (! DONT_NEED_PASSWORD))
234 if (! (flags & POP_NO_GETPASS))
236 password = getpass ("Enter POP password:");
238 if (! password)
240 strcpy (pop_error, "Could not determine POP password");
241 return (0);
244 if (password) /* always true, detected 20060515 */
245 flags |= POP_NO_KERBEROS;
246 else
247 password = username; /* dead code, detected 20060515 */
248 /** "kpop" service is never used: look for 20060515 to see why **/
250 sock = socket_connection (host, flags);
251 if (sock == -1)
252 return (0);
254 server = (popserver) malloc (sizeof (struct _popserver));
255 if (! server)
257 strcpy (pop_error, "Out of memory in pop_open");
258 return (0);
260 server->buffer = (char *) malloc (GETLINE_MIN);
261 if (! server->buffer)
263 strcpy (pop_error, "Out of memory in pop_open");
264 free ((char *) server);
265 return (0);
268 server->file = sock;
269 server->data = 0;
270 server->buffer_index = 0;
271 server->buffer_size = GETLINE_MIN;
272 server->in_multi = false;
273 server->trash_started = false;
275 if (getok (server))
276 return (0);
279 * I really shouldn't use the pop_error variable like this, but....
281 if (strlen (username) > ERROR_MAX - 6)
283 pop_close (server);
284 strcpy (pop_error,
285 "Username too long; recompile pop.c with larger ERROR_MAX");
286 return (0);
288 sprintf (pop_error, "USER %s", username);
290 if (sendline (server, pop_error) || getok (server))
292 return (0);
295 if (strlen (password) > ERROR_MAX - 6)
297 pop_close (server);
298 strcpy (pop_error,
299 "Password too long; recompile pop.c with larger ERROR_MAX");
300 return (0);
302 sprintf (pop_error, "PASS %s", password);
304 if (sendline (server, pop_error) || getok (server))
306 return (0);
309 return (server);
313 * Function: pop_stat
315 * Purpose: Issue the STAT command to the server and return (in the
316 * value parameters) the number of messages in the maildrop and
317 * the total size of the maildrop.
319 * Return value: 0 on success, or non-zero with an error in pop_error
320 * in failure.
322 * Side effects: On failure, may make further operations on the
323 * connection impossible.
326 pop_stat (popserver server, int *count, int *size)
328 char *fromserver;
329 char *end_ptr;
331 if (server->in_multi)
333 strcpy (pop_error, "In multi-line query in pop_stat");
334 return (-1);
337 if (sendline (server, "STAT") || (pop_getline (server, &fromserver) < 0))
338 return (-1);
340 if (strncmp (fromserver, "+OK ", 4))
342 if (0 == strncmp (fromserver, "-ERR", 4))
343 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
344 else
346 strcpy (pop_error,
347 "Unexpected response from POP server in pop_stat");
348 pop_trash (server);
350 return (-1);
353 errno = 0;
354 *count = strtol (&fromserver[4], &end_ptr, 10);
355 /* Check validity of string-to-integer conversion. */
356 if (fromserver + 4 == end_ptr || *end_ptr != ' ' || errno)
358 strcpy (pop_error, "Unexpected response from POP server in pop_stat");
359 pop_trash (server);
360 return (-1);
363 fromserver = end_ptr;
365 errno = 0;
366 *size = strtol (fromserver + 1, &end_ptr, 10);
367 if (fromserver + 1 == end_ptr || errno)
369 strcpy (pop_error, "Unexpected response from POP server in pop_stat");
370 pop_trash (server);
371 return (-1);
374 return (0);
378 * Function: pop_list
380 * Purpose: Performs the POP "list" command and returns (in value
381 * parameters) two malloc'd zero-terminated arrays -- one of
382 * message IDs, and a parallel one of sizes.
384 * Arguments:
385 * server The pop connection to talk to.
386 * message The number of the one message about which to get
387 * information, or 0 to get information about all
388 * messages.
390 * Return value: 0 on success, non-zero with error in pop_error on
391 * failure.
393 * Side effects: On failure, may make further operations on the
394 * connection impossible.
397 pop_list (popserver server, int message, int **IDs, int **sizes)
399 int how_many, i;
400 char *fromserver;
402 if (server->in_multi)
404 strcpy (pop_error, "In multi-line query in pop_list");
405 return (-1);
408 if (message)
409 how_many = 1;
410 else
412 int count, size;
413 if (pop_stat (server, &count, &size))
414 return (-1);
415 how_many = count;
418 *IDs = (int *) malloc ((how_many + 1) * sizeof (int));
419 *sizes = (int *) malloc ((how_many + 1) * sizeof (int));
420 if (! (*IDs && *sizes))
422 strcpy (pop_error, "Out of memory in pop_list");
423 return (-1);
426 if (message)
428 sprintf (pop_error, "LIST %d", message);
429 if (sendline (server, pop_error))
431 free ((char *) *IDs);
432 free ((char *) *sizes);
433 return (-1);
435 if (pop_getline (server, &fromserver) < 0)
437 free ((char *) *IDs);
438 free ((char *) *sizes);
439 return (-1);
441 if (strncmp (fromserver, "+OK ", 4))
443 if (! strncmp (fromserver, "-ERR", 4))
444 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
445 else
447 strcpy (pop_error,
448 "Unexpected response from server in pop_list");
449 pop_trash (server);
451 free ((char *) *IDs);
452 free ((char *) *sizes);
453 return (-1);
455 (*IDs)[0] = atoi (&fromserver[4]);
456 fromserver = strchr (&fromserver[4], ' ');
457 if (! fromserver)
459 strcpy (pop_error,
460 "Badly formatted response from server in pop_list");
461 pop_trash (server);
462 free ((char *) *IDs);
463 free ((char *) *sizes);
464 return (-1);
466 (*sizes)[0] = atoi (fromserver);
467 (*IDs)[1] = (*sizes)[1] = 0;
468 return (0);
470 else
472 if (pop_multi_first (server, "LIST", &fromserver))
474 free ((char *) *IDs);
475 free ((char *) *sizes);
476 return (-1);
478 for (i = 0; i < how_many; i++)
480 if (pop_multi_next (server, &fromserver) <= 0)
482 free ((char *) *IDs);
483 free ((char *) *sizes);
484 return (-1);
486 (*IDs)[i] = atoi (fromserver);
487 fromserver = strchr (fromserver, ' ');
488 if (! fromserver)
490 strcpy (pop_error,
491 "Badly formatted response from server in pop_list");
492 free ((char *) *IDs);
493 free ((char *) *sizes);
494 pop_trash (server);
495 return (-1);
497 (*sizes)[i] = atoi (fromserver);
499 if (pop_multi_next (server, &fromserver) < 0)
501 free ((char *) *IDs);
502 free ((char *) *sizes);
503 return (-1);
505 else if (fromserver)
507 strcpy (pop_error,
508 "Too many response lines from server in pop_list");
509 free ((char *) *IDs);
510 free ((char *) *sizes);
511 return (-1);
513 (*IDs)[i] = (*sizes)[i] = 0;
514 return (0);
519 * Function: pop_retrieve
521 * Purpose: Retrieve a specified message from the maildrop.
523 * Arguments:
524 * server The server to retrieve from.
525 * message The message number to retrieve.
526 * markfrom
527 * If true, then mark the string "From " at the beginning
528 * of lines with '>'.
529 * msg_buf Output parameter to which a buffer containing the
530 * message is assigned.
532 * Return value: The number of bytes in msg_buf, which may contain
533 * embedded nulls, not including its final null, or -1 on error
534 * with pop_error set.
536 * Side effects: May kill connection on error.
539 pop_retrieve (popserver server, int message, int markfrom, char **msg_buf)
541 int *IDs, *sizes, bufsize, fromcount = 0, cp = 0;
542 char *ptr, *fromserver;
543 int ret;
545 if (server->in_multi)
547 strcpy (pop_error, "In multi-line query in pop_retrieve");
548 return (-1);
551 if (pop_list (server, message, &IDs, &sizes))
552 return (-1);
554 if (pop_retrieve_first (server, message, &fromserver))
556 return (-1);
560 * The "5" below is an arbitrary constant -- I assume that if
561 * there are "From" lines in the text to be marked, there
562 * probably won't be more than 5 of them. If there are, I
563 * allocate more space for them below.
565 bufsize = sizes[0] + (markfrom ? 5 : 0);
566 ptr = (char *)malloc (bufsize);
567 free ((char *) IDs);
568 free ((char *) sizes);
570 if (! ptr)
572 strcpy (pop_error, "Out of memory in pop_retrieve");
573 pop_retrieve_flush (server);
574 return (-1);
577 while ((ret = pop_retrieve_next (server, &fromserver)) >= 0)
579 if (! fromserver)
581 ptr[cp] = '\0';
582 *msg_buf = ptr;
583 return (cp);
585 if (markfrom && fromserver[0] == 'F' && fromserver[1] == 'r' &&
586 fromserver[2] == 'o' && fromserver[3] == 'm' &&
587 fromserver[4] == ' ')
589 if (++fromcount == 5)
591 bufsize += 5;
592 ptr = (char *)realloc (ptr, bufsize);
593 if (! ptr)
595 strcpy (pop_error, "Out of memory in pop_retrieve");
596 pop_retrieve_flush (server);
597 return (-1);
599 fromcount = 0;
601 ptr[cp++] = '>';
603 memcpy (&ptr[cp], fromserver, ret);
604 cp += ret;
605 ptr[cp++] = '\n';
608 free (ptr);
609 return (-1);
613 pop_retrieve_first (popserver server, int message, char **response)
615 sprintf (pop_error, "RETR %d", message);
616 return (pop_multi_first (server, pop_error, response));
620 Returns a negative number on error, 0 to indicate that the data has
621 all been read (i.e., the server has returned a "." termination
622 line), or a positive number indicating the number of bytes in the
623 returned buffer (which is null-terminated and may contain embedded
624 nulls, but the returned bytecount doesn't include the final null).
628 pop_retrieve_next (popserver server, char **line)
630 return (pop_multi_next (server, line));
634 pop_retrieve_flush (popserver server)
636 return (pop_multi_flush (server));
640 pop_top_first (popserver server, int message, int lines, char **response)
642 sprintf (pop_error, "TOP %d %d", message, lines);
643 return (pop_multi_first (server, pop_error, response));
647 Returns a negative number on error, 0 to indicate that the data has
648 all been read (i.e., the server has returned a "." termination
649 line), or a positive number indicating the number of bytes in the
650 returned buffer (which is null-terminated and may contain embedded
651 nulls, but the returned bytecount doesn't include the final null).
655 pop_top_next (popserver server, char **line)
657 return (pop_multi_next (server, line));
661 pop_top_flush (popserver server)
663 return (pop_multi_flush (server));
667 pop_multi_first (popserver server, const char *command, char **response)
669 if (server->in_multi)
671 strcpy (pop_error,
672 "Already in multi-line query in pop_multi_first");
673 return (-1);
676 if (sendline (server, command) || (pop_getline (server, response) < 0))
678 return (-1);
681 if (0 == strncmp (*response, "-ERR", 4))
683 snprintf (pop_error, ERROR_MAX, "%s", *response);
684 return (-1);
686 else if (0 == strncmp (*response, "+OK", 3))
688 for (*response += 3; **response == ' '; (*response)++) /* empty */;
689 server->in_multi = true;
690 return (0);
692 else
694 strcpy (pop_error,
695 "Unexpected response from server in pop_multi_first");
696 return (-1);
701 Read the next line of data from SERVER and place a pointer to it
702 into LINE. Return -1 on error, 0 if there are no more lines to read
703 (i.e., the server has returned a line containing only "."), or a
704 positive number indicating the number of bytes in the LINE buffer
705 (not including the final null). The data in that buffer may contain
706 embedded nulls, but does not contain the final CRLF. When returning
707 0, LINE is set to null. */
710 pop_multi_next (popserver server, char **line)
712 char *fromserver;
713 int ret;
715 if (! server->in_multi)
717 strcpy (pop_error, "Not in multi-line query in pop_multi_next");
718 return (-1);
721 if ((ret = pop_getline (server, &fromserver)) < 0)
723 return (-1);
726 if (fromserver[0] == '.')
728 if (! fromserver[1])
730 *line = 0;
731 server->in_multi = false;
732 return (0);
734 else
736 *line = fromserver + 1;
737 return (ret - 1);
740 else
742 *line = fromserver;
743 return (ret);
748 pop_multi_flush (popserver server)
750 char *line;
751 int ret;
753 if (! server->in_multi)
755 return (0);
758 while ((ret = pop_multi_next (server, &line)))
760 if (ret < 0)
761 return (-1);
764 return (0);
767 /* Function: pop_delete
769 * Purpose: Delete a specified message.
771 * Arguments:
772 * server Server from which to delete the message.
773 * message Message to delete.
775 * Return value: 0 on success, non-zero with error in pop_error
776 * otherwise.
779 pop_delete (popserver server, int message)
781 if (server->in_multi)
783 strcpy (pop_error, "In multi-line query in pop_delete");
784 return (-1);
787 sprintf (pop_error, "DELE %d", message);
789 if (sendline (server, pop_error) || getok (server))
790 return (-1);
792 return (0);
796 * Function: pop_noop
798 * Purpose: Send a noop command to the server.
800 * Argument:
801 * server The server to send to.
803 * Return value: 0 on success, non-zero with error in pop_error
804 * otherwise.
806 * Side effects: Closes connection on error.
809 pop_noop (popserver server)
811 if (server->in_multi)
813 strcpy (pop_error, "In multi-line query in pop_noop");
814 return (-1);
817 if (sendline (server, "NOOP") || getok (server))
818 return (-1);
820 return (0);
824 * Function: pop_last
826 * Purpose: Find out the highest seen message from the server.
828 * Arguments:
829 * server The server.
831 * Return value: If successful, the highest seen message, which is
832 * greater than or equal to 0. Otherwise, a negative number with
833 * the error explained in pop_error.
835 * Side effects: Closes the connection on error.
838 pop_last (popserver server)
840 char *fromserver;
842 if (server->in_multi)
844 strcpy (pop_error, "In multi-line query in pop_last");
845 return (-1);
848 if (sendline (server, "LAST"))
849 return (-1);
851 if (pop_getline (server, &fromserver) < 0)
852 return (-1);
854 if (! strncmp (fromserver, "-ERR", 4))
856 snprintf (pop_error, ERROR_MAX, "%s", fromserver);
857 return (-1);
859 else if (strncmp (fromserver, "+OK ", 4))
861 strcpy (pop_error, "Unexpected response from server in pop_last");
862 pop_trash (server);
863 return (-1);
865 else
867 char *end_ptr;
868 int count;
869 errno = 0;
870 count = strtol (&fromserver[4], &end_ptr, 10);
871 if (fromserver + 4 == end_ptr || errno)
873 strcpy (pop_error, "Unexpected response from server in pop_last");
874 pop_trash (server);
875 return (-1);
877 return count;
882 * Function: pop_reset
884 * Purpose: Reset the server to its initial connect state
886 * Arguments:
887 * server The server.
889 * Return value: 0 for success, non-0 with error in pop_error
890 * otherwise.
892 * Side effects: Closes the connection on error.
895 pop_reset (popserver server)
897 if (pop_retrieve_flush (server))
899 return (-1);
902 if (sendline (server, "RSET") || getok (server))
903 return (-1);
905 return (0);
909 * Function: pop_quit
911 * Purpose: Quit the connection to the server,
913 * Arguments:
914 * server The server to quit.
916 * Return value: 0 for success, non-zero otherwise with error in
917 * pop_error.
919 * Side Effects: The popserver passed in is unusable after this
920 * function is called, even if an error occurs.
923 pop_quit (popserver server)
925 int ret = 0;
927 if (server->file >= 0)
929 if (pop_retrieve_flush (server))
931 ret = -1;
934 if (sendline (server, "QUIT") || getok (server))
936 ret = -1;
939 close (server->file);
942 free (server->buffer);
943 free ((char *) server);
945 return (ret);
948 #ifdef WINDOWSNT
949 static int have_winsock = 0;
950 #endif
953 * Function: socket_connection
955 * Purpose: Opens the network connection with the mail host, without
956 * doing any sort of I/O with it or anything.
958 * Arguments:
959 * host The host to which to connect.
960 * flags Option flags.
962 * Return value: A file descriptor indicating the connection, or -1
963 * indicating failure, in which case an error has been copied
964 * into pop_error.
966 static int
967 socket_connection (char *host, int flags)
969 struct addrinfo *res, *it;
970 struct addrinfo hints;
971 int ret;
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 memset (&hints, 0, sizeof (hints));
1059 hints.ai_socktype = SOCK_STREAM;
1060 hints.ai_flags = AI_CANONNAME;
1061 hints.ai_family = AF_INET;
1064 ret = getaddrinfo (host, service, &hints, &res);
1065 try_count++;
1066 if (ret != 0 && (ret != EAI_AGAIN || try_count == 5))
1068 strcpy (pop_error, "Could not determine POP server's address");
1069 return (-1);
1071 } while (ret != 0);
1073 for (it = res; it; it = it->ai_next)
1074 if (it->ai_addrlen == sizeof addr)
1076 struct sockaddr_in *in_a = (struct sockaddr_in *) it->ai_addr;
1077 addr.sin_addr = in_a->sin_addr;
1078 if (! connect (sock, (struct sockaddr *) &addr, sizeof addr))
1079 break;
1081 connect_ok = it != NULL;
1082 if (connect_ok)
1084 realhost = alloca (strlen (it->ai_canonname) + 1);
1085 strcpy (realhost, it->ai_canonname);
1087 freeaddrinfo (res);
1089 #define CONNECT_ERROR "Could not connect to POP server: "
1091 if (! connect_ok)
1093 CLOSESOCKET (sock);
1094 snprintf (pop_error, ERROR_MAX, "%s%s", CONNECT_ERROR, strerror (errno));
1095 return (-1);
1099 #ifdef KERBEROS
1101 #define KRB_ERROR "Kerberos error connecting to POP server: "
1102 if (! (flags & POP_NO_KERBEROS))
1104 #ifdef KERBEROS5
1105 if ((rem = krb5_init_context (&kcontext)))
1107 krb5error:
1108 if (auth_context)
1109 krb5_auth_con_free (kcontext, auth_context);
1110 if (kcontext)
1111 krb5_free_context (kcontext);
1112 snprintf (pop_error, ERROR_MAX, "%s%s",
1113 KRB_ERROR, error_message (rem));
1114 CLOSESOCKET (sock);
1115 return (-1);
1118 if ((rem = krb5_auth_con_init (kcontext, &auth_context)))
1119 goto krb5error;
1121 if (rem = krb5_cc_default (kcontext, &ccdef))
1122 goto krb5error;
1124 if (rem = krb5_cc_get_principal (kcontext, ccdef, &client))
1125 goto krb5error;
1127 for (cp = realhost; *cp; cp++)
1129 if (isupper (*cp))
1131 *cp = tolower (*cp);
1135 if (rem = krb5_sname_to_principal (kcontext, realhost,
1136 POP_SERVICE, FALSE, &server))
1137 goto krb5error;
1139 rem = krb5_sendauth (kcontext, &auth_context,
1140 (krb5_pointer) &sock, "KPOPV1.0", client, server,
1141 AP_OPTS_MUTUAL_REQUIRED,
1142 0, /* no checksum */
1143 0, /* no creds, use ccache instead */
1144 ccdef,
1145 &err_ret,
1146 0, /* don't need subsession key */
1147 0); /* don't need reply */
1148 krb5_free_principal (kcontext, server);
1149 if (rem)
1151 int pop_error_len = snprintf (pop_error, ERROR_MAX, "%s%s",
1152 KRB_ERROR, error_message (rem));
1153 #if defined HAVE_KRB5_ERROR_TEXT
1154 if (err_ret && err_ret->text.length)
1156 int errlen = err_ret->text.length;
1157 snprintf (pop_error + pop_error_len, ERROR_MAX - pop_error_len,
1158 " [server says '%.*s']", errlen, err_ret->text.data);
1160 #elif defined HAVE_KRB5_ERROR_E_TEXT
1161 if (err_ret && err_ret->e_text && **err_ret->e_text)
1162 snprintf (pop_error + pop_error_len, ERROR_MAX - pop_error_len,
1163 " [server says '%s']", *err_ret->e_text);
1164 #endif
1165 if (err_ret)
1166 krb5_free_error (kcontext, err_ret);
1167 krb5_auth_con_free (kcontext, auth_context);
1168 krb5_free_context (kcontext);
1170 CLOSESOCKET (sock);
1171 return (-1);
1173 #else /* ! KERBEROS5 */
1174 ticket = (KTEXT) malloc (sizeof (KTEXT_ST));
1175 rem = krb_sendauth (0L, sock, ticket, "pop", realhost,
1176 (char *) krb_realmofhost (realhost),
1177 (unsigned long) 0, &msg_data, &cred, schedule,
1178 (struct sockaddr_in *) 0,
1179 (struct sockaddr_in *) 0,
1180 "KPOPV0.1");
1181 free ((char *) ticket);
1182 if (rem != KSUCCESS)
1184 snprintf (pop_error, ERROR_MAX, "%s%s", KRB_ERROR, krb_err_txt[rem]);
1185 CLOSESOCKET (sock);
1186 return (-1);
1188 #endif /* KERBEROS5 */
1190 #endif /* KERBEROS */
1192 return (sock);
1193 } /* socket_connection */
1196 * Function: pop_getline
1198 * Purpose: Get a line of text from the connection and return a
1199 * pointer to it. The carriage return and linefeed at the end of
1200 * the line are stripped, but periods at the beginnings of lines
1201 * are NOT dealt with in any special way.
1203 * Arguments:
1204 * server The server from which to get the line of text.
1206 * Returns: The number of characters in the line, which is returned in
1207 * LINE, not including the final null. A return value of 0
1208 * indicates a blank line. A negative return value indicates an
1209 * error (in which case the contents of LINE are undefined. In
1210 * case of error, an error message is copied into pop_error.
1212 * Notes: The line returned is overwritten with each call to pop_getline.
1214 * Side effects: Closes the connection on error.
1216 * THE RETURNED LINE MAY CONTAIN EMBEDDED NULLS!
1218 static int
1219 pop_getline (popserver server, char **line)
1221 #define GETLINE_ERROR "Error reading from server: "
1223 int ret;
1224 int search_offset = 0;
1226 if (server->data)
1228 char *cp = find_crlf (server->buffer + server->buffer_index,
1229 server->data);
1230 if (cp)
1232 int found;
1233 int data_used;
1235 found = server->buffer_index;
1236 data_used = (cp + 2) - server->buffer - found;
1238 *cp = '\0'; /* terminate the string to be returned */
1239 server->data -= data_used;
1240 server->buffer_index += data_used;
1242 if (pop_debug)
1243 /* Embedded nulls will truncate this output prematurely,
1244 but that's OK because it's just for debugging anyway. */
1245 fprintf (stderr, "<<< %s\n", server->buffer + found);
1246 *line = server->buffer + found;
1247 return (data_used - 2);
1249 else
1251 memmove (server->buffer, server->buffer + server->buffer_index,
1252 server->data);
1253 /* Record the fact that we've searched the data already in
1254 the buffer for a CRLF, so that when we search below, we
1255 don't have to search the same data twice. There's a "-
1256 1" here to account for the fact that the last character
1257 of the data we have may be the CR of a CRLF pair, of
1258 which we haven't read the second half yet, so we may have
1259 to search it again when we read more data. */
1260 search_offset = server->data - 1;
1261 server->buffer_index = 0;
1264 else
1266 server->buffer_index = 0;
1269 while (1)
1271 /* There's a "- 1" here to leave room for the null that we put
1272 at the end of the read data below. We put the null there so
1273 that find_crlf knows where to stop when we call it. */
1274 if (server->data == server->buffer_size - 1)
1276 server->buffer_size += GETLINE_INCR;
1277 server->buffer = (char *)realloc (server->buffer, server->buffer_size);
1278 if (! server->buffer)
1280 strcpy (pop_error, "Out of memory in pop_getline");
1281 pop_trash (server);
1282 return (-1);
1285 ret = RECV (server->file, server->buffer + server->data,
1286 server->buffer_size - server->data - 1, 0);
1287 if (ret < 0)
1289 snprintf (pop_error, ERROR_MAX, "%s%s",
1290 GETLINE_ERROR, strerror (errno));
1291 pop_trash (server);
1292 return (-1);
1294 else if (ret == 0)
1296 strcpy (pop_error, "Unexpected EOF from server in pop_getline");
1297 pop_trash (server);
1298 return (-1);
1300 else
1302 char *cp;
1303 server->data += ret;
1304 server->buffer[server->data] = '\0';
1306 cp = find_crlf (server->buffer + search_offset,
1307 server->data - search_offset);
1308 if (cp)
1310 int data_used = (cp + 2) - server->buffer;
1311 *cp = '\0';
1312 server->data -= data_used;
1313 server->buffer_index = data_used;
1315 if (pop_debug)
1316 fprintf (stderr, "<<< %s\n", server->buffer);
1317 *line = server->buffer;
1318 return (data_used - 2);
1320 /* As above, the "- 1" here is to account for the fact that
1321 we may have read a CR without its accompanying LF. */
1322 search_offset += ret - 1;
1326 /* NOTREACHED */
1330 * Function: sendline
1332 * Purpose: Sends a line of text to the POP server. The line of text
1333 * passed into this function should NOT have the carriage return
1334 * and linefeed on the end of it. Periods at beginnings of lines
1335 * will NOT be treated specially by this function.
1337 * Arguments:
1338 * server The server to which to send the text.
1339 * line The line of text to send.
1341 * Return value: Upon successful completion, a value of 0 will be
1342 * returned. Otherwise, a non-zero value will be returned, and
1343 * an error will be copied into pop_error.
1345 * Side effects: Closes the connection on error.
1347 static int
1348 sendline (popserver server, const char *line)
1350 #define SENDLINE_ERROR "Error writing to POP server: "
1351 int ret;
1352 char *buf;
1354 /* Combine the string and the CR-LF into one buffer. Otherwise, two
1355 reasonable network stack optimizations, Nagle's algorithm and
1356 delayed acks, combine to delay us a fraction of a second on every
1357 message we send. (Movemail writes line without \r\n, client
1358 kernel sends packet, server kernel delays the ack to see if it
1359 can combine it with data, movemail writes \r\n, client kernel
1360 waits because it has unacked data already in its outgoing queue,
1361 client kernel eventually times out and sends.)
1363 This can be something like 0.2s per command, which can add up
1364 over a few dozen messages, and is a big chunk of the time we
1365 spend fetching mail from a server close by. */
1366 buf = alloca (strlen (line) + 3);
1367 strcpy (stpcpy (buf, line), "\r\n");
1368 ret = fullwrite (server->file, buf, strlen (buf));
1370 if (ret < 0)
1372 pop_trash (server);
1373 snprintf (pop_error, ERROR_MAX, "%s%s", SENDLINE_ERROR, strerror (errno));
1374 return (ret);
1377 if (pop_debug)
1378 fprintf (stderr, ">>> %s\n", line);
1380 return (0);
1384 * Procedure: fullwrite
1386 * Purpose: Just like write, but keeps trying until the entire string
1387 * has been written.
1389 * Return value: Same as write. Pop_error is not set.
1391 static int
1392 fullwrite (int fd, char *buf, int nbytes)
1394 char *cp;
1395 int ret = 0;
1397 cp = buf;
1398 while (nbytes && ((ret = SEND (fd, cp, nbytes, 0)) > 0))
1400 cp += ret;
1401 nbytes -= ret;
1404 return (ret);
1408 * Procedure getok
1410 * Purpose: Reads a line from the server. If the return indicator is
1411 * positive, return with a zero exit status. If not, return with
1412 * a negative exit status.
1414 * Arguments:
1415 * server The server to read from.
1417 * Returns: 0 for success, else for failure and puts error in pop_error.
1419 * Side effects: On failure, may make the connection unusable.
1421 static int
1422 getok (popserver server)
1424 char *fromline;
1426 if (pop_getline (server, &fromline) < 0)
1428 return (-1);
1431 if (! strncmp (fromline, "+OK", 3))
1432 return (0);
1433 else if (! strncmp (fromline, "-ERR", 4))
1435 snprintf (pop_error, ERROR_MAX, "%s", fromline);
1436 return (-1);
1438 else
1440 strcpy (pop_error,
1441 "Unexpected response from server; expecting +OK or -ERR");
1442 pop_trash (server);
1443 return (-1);
1447 #if 0
1449 * Function: gettermination
1451 * Purpose: Gets the next line and verifies that it is a termination
1452 * line (nothing but a dot).
1454 * Return value: 0 on success, non-zero with pop_error set on error.
1456 * Side effects: Closes the connection on error.
1458 static int
1459 gettermination (server)
1460 popserver server;
1462 char *fromserver;
1464 if (pop_getline (server, &fromserver) < 0)
1465 return (-1);
1467 if (strcmp (fromserver, "."))
1469 strcpy (pop_error,
1470 "Unexpected response from server in gettermination");
1471 pop_trash (server);
1472 return (-1);
1475 return (0);
1477 #endif
1480 * Function pop_close
1482 * Purpose: Close a pop connection, sending a "RSET" command to try to
1483 * preserve any changes that were made and a "QUIT" command to
1484 * try to get the server to quit, but ignoring any responses that
1485 * are received.
1487 * Side effects: The server is unusable after this function returns.
1488 * Changes made to the maildrop since the session was started (or
1489 * since the last pop_reset) may be lost.
1491 void
1492 pop_close (popserver server)
1494 pop_trash (server);
1495 free ((char *) server);
1497 return;
1501 * Function: pop_trash
1503 * Purpose: Like pop_close or pop_quit, but doesn't deallocate the
1504 * memory associated with the server. It is valid to call
1505 * pop_close or pop_quit after this function has been called.
1507 static void
1508 pop_trash (popserver server)
1510 if (server->file >= 0)
1512 /* avoid recursion; sendline can call pop_trash */
1513 if (server->trash_started)
1514 return;
1515 server->trash_started = true;
1517 sendline (server, "RSET");
1518 sendline (server, "QUIT");
1520 CLOSESOCKET (server->file);
1521 server->file = -1;
1522 if (server->buffer)
1524 free (server->buffer);
1525 server->buffer = 0;
1529 #ifdef WINDOWSNT
1530 if (have_winsock)
1531 WSACleanup ();
1532 #endif
1535 /* Return a pointer to the first CRLF in IN_STRING, which can contain
1536 embedded nulls and has LEN characters in it not including the final
1537 null, or 0 if it does not contain one. */
1539 static char *
1540 find_crlf (char *in_string, int len)
1542 while (len--)
1544 if (*in_string == '\r')
1546 if (*++in_string == '\n')
1547 return (in_string - 1);
1549 else
1550 in_string++;
1552 return (0);
1555 #ifdef WINDOWSNT
1556 /* The following 2 functions are only available since XP, so we load
1557 them dynamically and provide fallbacks. */
1559 int (WINAPI *pfn_getaddrinfo) (const char *, const char *,
1560 const struct addrinfo *, struct addrinfo **);
1561 void (WINAPI *pfn_freeaddrinfo) (struct addrinfo *);
1563 static int
1564 load_ws2 (void)
1566 static int ws2_loaded = 0;
1568 if (!ws2_loaded)
1570 HANDLE ws2_lib = LoadLibrary ("Ws2_32.dll");
1572 if (ws2_lib != NULL)
1574 ws2_loaded = 1;
1575 pfn_getaddrinfo = (void *) GetProcAddress (ws2_lib, "getaddrinfo");
1576 pfn_freeaddrinfo = (void *) GetProcAddress (ws2_lib, "freeaddrinfo");
1577 /* Paranoia: these two functions should go together, so if
1578 one is absent, we cannot use the other. */
1579 if (pfn_getaddrinfo == NULL)
1580 pfn_freeaddrinfo = NULL;
1581 else if (pfn_freeaddrinfo == NULL)
1582 pfn_getaddrinfo = NULL;
1585 if (!ws2_loaded)
1587 errno = ENETDOWN;
1588 return -1;
1590 return 0;
1595 sys_getaddrinfo (const char *node, const char *service,
1596 const struct addrinfo *hints, struct addrinfo **res)
1598 int rc;
1600 if (load_ws2 () != 0)
1602 errno = ENETDOWN;
1603 return WSANO_RECOVERY;
1606 if (pfn_getaddrinfo)
1607 rc = pfn_getaddrinfo (node, service, hints, res);
1608 else
1610 int port = 0;
1611 struct hostent *host_info;
1612 struct gai_storage {
1613 struct addrinfo addrinfo;
1614 struct sockaddr_in sockaddr_in;
1615 } *gai_storage;
1617 /* We don't support any flags besides AI_CANONNAME. */
1618 if (hints && (hints->ai_flags & ~(AI_CANONNAME)) != 0)
1619 return WSAEINVAL;
1620 /* NODE cannot be NULL, since pop.c has fallbacks for that. */
1621 if (!node)
1622 return WSAHOST_NOT_FOUND;
1624 if (service)
1626 const char *protocol =
1627 (hints && hints->ai_socktype == SOCK_DGRAM) ? "udp" : "tcp";
1628 struct servent *srv = getservbyname (service, protocol);
1630 if (srv)
1631 port = srv->s_port;
1632 else
1633 return WSAHOST_NOT_FOUND;
1636 gai_storage = calloc (1, sizeof *gai_storage);
1637 gai_storage->sockaddr_in.sin_port = port;
1638 host_info = gethostbyname (node);
1639 if (host_info)
1641 memcpy (&gai_storage->sockaddr_in.sin_addr,
1642 host_info->h_addr, host_info->h_length);
1643 gai_storage->sockaddr_in.sin_family = host_info->h_addrtype;
1645 else
1647 free (gai_storage);
1648 return WSAHOST_NOT_FOUND;
1651 gai_storage->addrinfo.ai_addr =
1652 (struct sockaddr *)&gai_storage->sockaddr_in;
1653 gai_storage->addrinfo.ai_addrlen = sizeof (gai_storage->sockaddr_in);
1654 if (hints && (hints->ai_flags & AI_CANONNAME) != 0)
1656 gai_storage->addrinfo.ai_canonname = strdup (host_info->h_name);
1657 if (!gai_storage->addrinfo.ai_canonname)
1659 free (gai_storage);
1660 return WSA_NOT_ENOUGH_MEMORY;
1663 gai_storage->addrinfo.ai_protocol = (hints) ? hints->ai_protocol : 0;
1664 gai_storage->addrinfo.ai_socktype = (hints) ? hints->ai_socktype : 0;
1665 gai_storage->addrinfo.ai_family = gai_storage->sockaddr_in.sin_family;
1666 gai_storage->addrinfo.ai_next = NULL;
1668 *res = &gai_storage->addrinfo;
1669 rc = 0;
1672 return rc;
1675 void
1676 sys_freeaddrinfo (struct addrinfo *ai)
1678 if (load_ws2 () != 0)
1680 errno = ENETDOWN;
1681 return;
1684 if (pfn_freeaddrinfo)
1685 pfn_freeaddrinfo (ai);
1686 else
1688 if (ai->ai_canonname)
1689 free (ai->ai_canonname);
1690 free (ai);
1693 #endif /* WINDOWSNT */
1694 #endif /* MAIL_USE_POP */