1 /* pop.c: client routines for talking to a POP3-protocol post-office server
2 Copyright (C) 1991, 1993, 1996, 1997, 1999, 2001, 2002, 2003, 2004,
3 2005, 2006, 2007 Free Software Foundation, Inc.
4 Written by Jonathan Kamens, jik@security.ov.com.
6 This file is part of SXEmacs.
8 SXEmacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 SXEmacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>. */
22 #define NO_SHORTNAMES /* Tell config not to load remap.h */
30 #include <sys/types.h>
31 #include <netinet/in.h>
32 #include <sys/socket.h>
33 #define RECV(s,buf,len,flags) read(s,buf,len)
34 #define SEND(s,buf,len,flags) write(s,buf,len)
35 #define CLOSESOCKET(s) close(s)
45 * It really shouldn't be necessary to put this declaration here, but
46 * the version of hesiod.h that Athena has installed in release 7.2
47 * doesn't declare this function; I don't know if the 7.3 version of
50 extern struct servent *hes_getservbyname (/* char *, char * */);
66 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
67 # if defined HAVE_KRB5_KRB5_H
68 # include <krb/krb5.h>
69 # elif defined HAVE_KRB5_H
71 # elif defined HAVE_KRB_KRB_H
73 # elif defined HAVE_KRB_H
75 # elif defined HAVE_KERBEROS_KRB_H
76 # include <kerberos/krb.h>
77 # elif defined HAVE_KERBEROSIV_KRB_H
78 # include <kerberosIV/krb.h>
80 # error "What are you doing here?"
82 # if !defined HAVE_KERBEROS5 && defined HAVE_KRB_COM_ERR_H
83 # include <krb/com_err.h>
84 # elif !defined HAVE_KERBEROS5 && defined HAVE_KERBEROSIV_KRB_ERR_H
85 # include <kerberosIV/krb_err.h>
86 # elif !defined HAVE_KERBEROS5 && defined COM_ERR_H
91 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
92 #if !defined HAVE_KERBEROS5
93 extern int krb_sendauth (/* long, int, KTEXT, char *, char *, char *,
94 u_long, MSG_DAT *, CREDENTIALS *, Key_schedule,
95 struct sockaddr_in *, struct sockaddr_in *,
97 extern char *krb_realmofhost (/* char * */);
98 #endif /* ! HAVE_KERBEROS5 */
99 #endif /* WITH_KERBEROS && HAVE_KERBEROS */
101 #if !defined(HAVE_H_ERRNO) || !defined(HAVE_CONFIG_H)
110 # endif /* __STDC__ */
113 static int socket_connection __P((char *, int));
114 static int pop_getline __P((popserver, char **));
115 static int sendline __P((popserver, char *));
116 static int fullwrite __P((int, char *, int));
117 static int getok __P((popserver));
119 static int gettermination __P((popserver));
121 static void pop_trash __P((popserver));
122 static char *find_crlf __P((char *, int));
124 #define ERROR_MAX 160 /* a pretty arbitrary size, but needs
125 to be bigger than the original
128 #define KPOP_PORT 1109
129 #define POP_SERVICE "pop3" /* we don't want the POP2 port! */
131 #define KPOP_SERVICE "kpop" /* never used: look for 20060515 to see why */
134 char pop_error[ERROR_MAX];
138 #define min(a,b) (((a) < (b)) ? (a) : (b))
142 * Function: pop_open (char *host, char *username, char *password,
145 * Purpose: Establishes a connection with a post-office server, and
146 * completes the authorization portion of the session.
149 * host The server host with which the connection should be
150 * established. Optional. If omitted, internal
151 * heuristics will be used to determine the server host,
154 * The username of the mail-drop to access. Optional.
155 * If omitted, internal heuristics will be used to
156 * determine the username, if possible.
158 * The password to use for authorization. If omitted,
159 * internal heuristics will be used to determine the
160 * password, if possible.
161 * flags A bit mask containing flags controlling certain
162 * functions of the routine. Valid flags are defined in
165 * Return value: Upon successful establishment of a connection, a
166 * non-null popserver will be returned. Otherwise, null will be
167 * returned, and the string variable pop_error will contain an
168 * explanation of the error.
171 pop_open (host, username, password, flags)
181 /* Determine the user name */
183 username = getenv ("USER");
184 if (! (username && *username)) {
185 username = getlogin ();
186 if (! (username && *username)) {
187 struct passwd *passwd;
188 passwd = getpwuid (getuid ());
189 if (passwd && passwd->pw_name &&
191 username = passwd->pw_name;
194 "Could not determine username");
202 * Determine the mail host.
206 host = getenv ("MAILHOST");
210 if ((! host) && (! (flags & POP_NO_HESIOD))) {
211 struct hes_postoffice *office;
212 office = hes_getmailhost (username);
213 if (office && office->po_type && (! strcmp (office->po_type, "POP"))
214 && office->po_name && *office->po_name && office->po_host
215 && *office->po_host) {
216 host = office->po_host;
217 username = office->po_name;
229 strcpy (pop_error, "Could not determine POP server");
233 /* Determine the password */
234 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
235 #define DONT_NEED_PASSWORD (! (flags & POP_NO_KERBEROS))
237 #define DONT_NEED_PASSWORD 0
240 if ((! password) && (! DONT_NEED_PASSWORD)) {
241 if (! (flags & POP_NO_GETPASS)) {
242 password = getpass ("Enter POP password:");
245 strcpy (pop_error, "Could not determine POP password");
249 if (password) /* always true, detected 20060515 */
250 flags |= POP_NO_KERBEROS;
252 password = username; /* dead code, detected 20060515 */
253 /** "kpop" service is never used: look for 20060515 to see why **/
255 sock = socket_connection (host, flags);
259 server = (popserver) malloc (sizeof (struct _popserver));
261 strcpy (pop_error, "Out of memory in pop_open");
264 server->buffer = (char *) malloc (GETLINE_MIN);
265 if (! server->buffer) {
266 strcpy (pop_error, "Out of memory in pop_open");
267 free ((char *) server);
273 server->buffer_index = 0;
274 server->buffer_size = GETLINE_MIN;
275 server->in_multi = 0;
276 server->trash_started = 0;
282 * I really shouldn't use the pop_error variable like this, but....
284 if (strlen (username) > ERROR_MAX - 6) {
287 "Username too long; "
288 "recompile pop.c with larger ERROR_MAX");
291 sz = snprintf (pop_error, sizeof(pop_error), "USER %s", username);
292 assert(sz>=0 && sz<sizeof(pop_error));
294 if (sendline (server, pop_error) || getok (server)) {
298 if (strlen (password) > ERROR_MAX - 6) {
301 "Password too long; "
302 "recompile pop.c with larger ERROR_MAX");
305 sz = snprintf (pop_error, sizeof(pop_error),
306 "PASS %s", password);
307 assert(sz>=0 && sz<sizeof(pop_error));
309 if (sendline (server, pop_error) || getok (server)) {
319 * Purpose: Issue the STAT command to the server and return (in the
320 * value parameters) the number of messages in the maildrop and
321 * the total size of the maildrop.
323 * Return value: 0 on success, or non-zero with an error in pop_error
326 * Side effects: On failure, may make further operations on the
327 * connection impossible.
330 pop_stat (server, count, size)
337 if (server->in_multi) {
338 strcpy (pop_error, "In multi-line query in pop_stat");
342 if (sendline (server, "STAT") ||
343 (pop_getline (server, &fromserver) < 0))
346 if (strncmp (fromserver, "+OK ", 4)) {
347 if (0 == strncmp (fromserver, "-ERR", 4)) {
348 strncpy (pop_error, fromserver, ERROR_MAX);
351 "Unexpected response from POP "
352 "server in pop_stat");
358 *count = atoi (&fromserver[4]);
360 fromserver = index (&fromserver[4], ' ');
363 "Badly formatted response from server in pop_stat");
368 *size = atoi (fromserver + 1);
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.
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
386 * Return value: 0 on success, non-zero with error in pop_error on
389 * Side effects: On failure, may make further operations on the
390 * connection impossible.
393 pop_list (server, message, IDs, sizes)
402 if (server->in_multi) {
403 strcpy (pop_error, "In multi-line query in pop_list");
411 if (pop_stat (server, &count, &size))
416 *IDs = (int *) malloc ((how_many + 1) * sizeof (int));
417 *sizes = (int *) malloc ((how_many + 1) * sizeof (int));
418 if (! (*IDs && *sizes)) {
419 strcpy (pop_error, "Out of memory in pop_list");
424 sz = snprintf (pop_error, sizeof(pop_error), "LIST %d", message);
425 assert(sz>=0 && sz<sizeof(pop_error));
426 if (sendline (server, pop_error)) {
427 free ((char *) *IDs);
428 free ((char *) *sizes);
431 if (pop_getline (server, &fromserver) < 0) {
432 free ((char *) *IDs);
433 free ((char *) *sizes);
436 if (strncmp (fromserver, "+OK ", 4)) {
437 if (! strncmp (fromserver, "-ERR", 4)) {
438 strncpy (pop_error, fromserver, ERROR_MAX);
441 "Unexpected response from "
442 "server in pop_list");
445 free ((char *) *IDs);
446 free ((char *) *sizes);
449 (*IDs)[0] = atoi (&fromserver[4]);
450 fromserver = index (&fromserver[4], ' ');
453 "Badly formatted response from "
454 "server in pop_list");
456 free ((char *) *IDs);
457 free ((char *) *sizes);
460 (*sizes)[0] = atoi (fromserver);
461 (*IDs)[1] = (*sizes)[1] = 0;
464 if (pop_multi_first (server, "LIST", &fromserver)) {
465 free ((char *) *IDs);
466 free ((char *) *sizes);
469 for (i = 0; i < how_many; i++) {
470 if (pop_multi_next (server, &fromserver) <= 0) {
471 free ((char *) *IDs);
472 free ((char *) *sizes);
475 (*IDs)[i] = atoi (fromserver);
476 fromserver = index (fromserver, ' ');
479 "Badly formatted response from "
480 "server in pop_list");
481 free ((char *) *IDs);
482 free ((char *) *sizes);
486 (*sizes)[i] = atoi (fromserver);
488 if (pop_multi_next (server, &fromserver) < 0) {
489 free ((char *) *IDs);
490 free ((char *) *sizes);
492 } else if (fromserver) {
494 "Too many response lines from "
495 "server in pop_list");
496 free ((char *) *IDs);
497 free ((char *) *sizes);
500 (*IDs)[i] = (*sizes)[i] = 0;
506 * Function: pop_retrieve
508 * Purpose: Retrieve a specified message from the maildrop.
511 * server The server to retrieve from.
512 * message The message number to retrieve.
514 * If true, then mark the string "From " at the beginning
516 * msg_buf Output parameter to which a buffer containing the
517 * message is assigned.
519 * Return value: The number of bytes in msg_buf, which may contain
520 * embedded nulls, not including its final null, or -1 on error
521 * with pop_error set.
523 * Side effects: May kill connection on error.
526 pop_retrieve (server, message, markfrom, msg_buf)
532 int *IDs, *sizes, bufsize, fromcount = 0, cp = 0;
533 char *ptr, *fromserver;
536 if (server->in_multi) {
537 strcpy (pop_error, "In multi-line query in pop_retrieve");
541 if (pop_list (server, message, &IDs, &sizes))
544 if (pop_retrieve_first (server, message, &fromserver)) {
549 * The "5" below is an arbitrary constant -- I assume that if
550 * there are "From" lines in the text to be marked, there
551 * probably won't be more than 5 of them. If there are, I
552 * allocate more space for them below.
554 bufsize = sizes[0] + (markfrom ? 5 : 0);
555 ptr = (char *)malloc (bufsize);
557 free ((char *) sizes);
560 strcpy (pop_error, "Out of memory in pop_retrieve");
561 pop_retrieve_flush (server);
565 while ((ret = pop_retrieve_next (server, &fromserver)) >= 0) {
571 if (markfrom && fromserver[0] == 'F' && fromserver[1] == 'r' &&
572 fromserver[2] == 'o' && fromserver[3] == 'm' &&
573 fromserver[4] == ' ') {
574 if (++fromcount == 5) {
576 ptr = (char *)realloc (ptr, bufsize);
578 strcpy (pop_error, "Out of memory "
580 pop_retrieve_flush (server);
587 bcopy (fromserver, &ptr[cp], ret);
597 pop_retrieve_first (server, message, response)
602 int sz = snprintf (pop_error, sizeof(pop_error), "RETR %d", message);
603 assert(sz>=0 && sz<sizeof(pop_error));
604 return (pop_multi_first (server, pop_error, response));
608 Returns a negative number on error, 0 to indicate that the data has
609 all been read (i.e., the server has returned a "." termination
610 line), or a positive number indicating the number of bytes in the
611 returned buffer (which is null-terminated and may contain embedded
612 nulls, but the returned bytecount doesn't include the final null).
616 pop_retrieve_next (server, line)
620 return (pop_multi_next (server, line));
624 pop_retrieve_flush (server)
627 return (pop_multi_flush (server));
631 pop_top_first (server, message, lines, response)
636 int sz = snprintf (pop_error, sizeof(pop_error),
637 "TOP %d %d", message, lines);
638 assert(sz>=0 && sz<sizeof(pop_error));
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 (server, line)
655 return (pop_multi_next (server, line));
659 pop_top_flush (server)
662 return (pop_multi_flush (server));
666 pop_multi_first (server, command, response)
671 if (server->in_multi) {
673 "Already in multi-line query in pop_multi_first");
677 if (sendline (server, command) ||
678 (pop_getline (server, response) < 0)) {
682 if (0 == strncmp (*response, "-ERR", 4)) {
683 strncpy (pop_error, *response, ERROR_MAX);
685 } else if (0 == strncmp (*response, "+OK", 3)) {
686 for (*response += 3; **response == ' ';
687 (*response)++) /* empty */;
688 server->in_multi = 1;
692 "Unexpected response from "
693 "server in pop_multi_first");
699 Read the next line of data from SERVER and place a pointer to it
700 into LINE. Return -1 on error, 0 if there are no more lines to read
701 (i.e., the server has returned a line containing only "."), or a
702 positive number indicating the number of bytes in the LINE buffer
703 (not including the final null). The data in that buffer may contain
704 embedded nulls, but does not contain the final CRLF. When returning
705 0, LINE is set to null. */
708 pop_multi_next (server, line)
715 if (! server->in_multi) {
716 strcpy (pop_error, "Not in multi-line query in pop_multi_next");
720 if ((ret = pop_getline (server, &fromserver)) < 0) {
724 if (fromserver[0] == '.') {
725 if (! fromserver[1]) {
727 server->in_multi = 0;
730 *line = fromserver + 1;
740 pop_multi_flush (server)
746 if (! server->in_multi) {
750 while ((ret = pop_multi_next (server, &line))) {
758 /* Function: pop_delete
760 * Purpose: Delete a specified message.
763 * server Server from which to delete the message.
764 * message Message to delete.
766 * Return value: 0 on success, non-zero with error in pop_error
770 pop_delete (server, message)
776 if (server->in_multi) {
777 strcpy (pop_error, "In multi-line query in pop_delete");
781 sz = snprintf (pop_error, sizeof(pop_error),
783 assert(sz>=0 && sz<sizeof(pop_error));
785 if (sendline (server, pop_error) || getok (server))
794 * Purpose: Send a noop command to the server.
797 * server The server to send to.
799 * Return value: 0 on success, non-zero with error in pop_error
802 * Side effects: Closes connection on error.
808 if (server->in_multi) {
809 strcpy (pop_error, "In multi-line query in pop_noop");
813 if (sendline (server, "NOOP") || getok (server))
822 * Purpose: Find out the highest seen message from 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.
839 if (server->in_multi) {
840 strcpy (pop_error, "In multi-line query in pop_last");
844 if (sendline (server, "LAST"))
847 if (pop_getline (server, &fromserver) < 0)
850 if (! strncmp (fromserver, "-ERR", 4)) {
851 strncpy (pop_error, fromserver, ERROR_MAX);
853 } else if (strncmp (fromserver, "+OK ", 4)) {
854 strcpy (pop_error, "Unexpected response from server in pop_last");
858 return (atoi (&fromserver[4]));
863 * Function: pop_reset
865 * Purpose: Reset the server to its initial connect state
870 * Return value: 0 for success, non-0 with error in pop_error
873 * Side effects: Closes the connection on error.
879 if (pop_retrieve_flush (server)) {
883 if (sendline (server, "RSET") || getok (server))
892 * Purpose: Quit the connection to the server,
895 * server The server to quit.
897 * Return value: 0 for success, non-zero otherwise with error in
900 * Side Effects: The popserver passed in is unusable after this
901 * function is called, even if an error occurs.
909 if (server->file >= 0) {
910 if (pop_retrieve_flush (server)) {
914 if (sendline (server, "QUIT") || getok (server)) {
918 close (server->file);
922 free (server->buffer);
923 free ((char *) server);
929 * Function: socket_connection
931 * Purpose: Opens the network connection with the mail host, without
932 * doing any sort of I/O with it or anything.
935 * host The host to which to connect.
936 * flags Option flags.
938 * Return value: A file descriptor indicating the connection, or -1
939 * indicating failure, in which case an error has been copied
943 socket_connection (host, flags)
947 struct hostent *hostent;
948 struct servent *servent;
949 struct sockaddr_in addr;
953 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
954 # if defined HAVE_KERBEROS5
956 krb5_context kcontext = 0;
957 krb5_auth_context auth_context = 0;
959 krb5_principal client, server;
962 # else /* !HAVE_KERBEROS5 */
966 Key_schedule schedule;
969 # endif /* HAVE_KERBEROS5 */
970 #endif /* WITH_KERBEROS && HAVE_KERBEROS */
974 bzero ((char *) &addr, sizeof (addr));
975 addr.sin_family = AF_INET;
977 /** "kpop" service is never used: look for 20060515 to see why **/
978 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
979 service = (flags & POP_NO_KERBEROS) ? POP_SERVICE : KPOP_SERVICE;
981 service = POP_SERVICE;
985 if (! (flags & POP_NO_HESIOD)) {
986 servent = hes_getservbyname (service, "tcp");
988 addr.sin_port = servent->s_port;
994 servent = getservbyname (service, "tcp");
996 addr.sin_port = servent->s_port;
998 /** "kpop" service is never used:
999 * look for 20060515 to see why **/
1000 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
1001 addr.sin_port = htons ((flags & POP_NO_KERBEROS) ?
1002 POP_PORT : KPOP_PORT);
1004 addr.sin_port = htons (POP_PORT);
1009 #define POP_SOCKET_ERROR "Could not create socket for POP connection: "
1011 sock = socket (PF_INET, SOCK_STREAM, 0);
1013 strcpy (pop_error, POP_SOCKET_ERROR);
1014 strncat (pop_error, strerror (errno),
1015 ERROR_MAX - sizeof (POP_SOCKET_ERROR));
1021 hostent = gethostbyname (host);
1024 ((h_errno != TRY_AGAIN) || (try_count == 5))) {
1025 strcpy (pop_error, "Could not determine "
1026 "POP server's address");
1029 } while (! hostent);
1031 while (*hostent->h_addr_list) {
1032 bcopy (*hostent->h_addr_list, (char *) &addr.sin_addr,
1034 if (! connect (sock, (struct sockaddr *) &addr, sizeof (addr)))
1036 hostent->h_addr_list++;
1039 #define CONNECT_ERROR "Could not connect to POP server: "
1041 if (! *hostent->h_addr_list) {
1043 strcpy (pop_error, CONNECT_ERROR);
1044 strncat (pop_error, strerror (errno),
1045 ERROR_MAX - sizeof (CONNECT_ERROR));
1049 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
1050 #define KRB_ERROR "Kerberos error connecting to POP server: "
1051 if (! (flags & POP_NO_KERBEROS)) {
1052 # if defined HAVE_KERBEROS5
1053 if ((rem = krb5_init_context (&kcontext))) {
1056 krb5_auth_con_free (kcontext, auth_context);
1058 krb5_free_context (kcontext);
1059 strcpy (pop_error, KRB_ERROR);
1060 strncat (pop_error, error_message (rem),
1061 ERROR_MAX - sizeof(KRB_ERROR));
1066 if ((rem = krb5_auth_con_init (kcontext, &auth_context)))
1069 if (rem = krb5_cc_default (kcontext, &ccdef))
1072 if (rem = krb5_cc_get_principal (kcontext, ccdef, &client))
1075 for (cp = hostent->h_name; *cp; cp++) {
1076 if (isupper (*cp)) {
1077 *cp = tolower (*cp);
1081 if (rem = krb5_sname_to_principal (kcontext, hostent->h_name,
1082 POP_SERVICE, FALSE, &server))
1085 rem = krb5_sendauth (kcontext, &auth_context,
1086 (krb5_pointer) &sock, "KPOPV1.0",
1088 AP_OPTS_MUTUAL_REQUIRED,
1089 0, /* no checksum */
1090 0, /* no creds, use ccache instead */
1093 0, /* don't need subsession key */
1094 0); /* don't need reply */
1095 krb5_free_principal (kcontext, server);
1097 if (err_ret && err_ret->text.length) {
1098 strcpy (pop_error, KRB_ERROR);
1099 strncat (pop_error, error_message (rem),
1100 ERROR_MAX - sizeof (KRB_ERROR));
1101 strncat (pop_error, " [server says '",
1102 ERROR_MAX - strlen (pop_error) - 1);
1103 strncat (pop_error, err_ret->text.data,
1105 strlen (pop_error) - 1,
1106 err_ret->text.length));
1107 strncat (pop_error, "']",
1108 ERROR_MAX - strlen (pop_error) - 1);
1110 strcpy (pop_error, KRB_ERROR);
1111 strncat (pop_error, error_message (rem),
1112 ERROR_MAX - sizeof (KRB_ERROR));
1115 krb5_free_error (kcontext, err_ret);
1116 krb5_auth_con_free (kcontext, auth_context);
1117 krb5_free_context (kcontext);
1122 # else /* ! HAVE_KERBEROS5 */
1123 ticket = (KTEXT) malloc (sizeof (KTEXT_ST));
1124 realhost = strdup (hostent->h_name);
1125 rem = krb_sendauth (0L, sock, ticket, "pop", realhost,
1126 (char *) krb_realmofhost (realhost),
1127 (unsigned long) 0, &msg_data, &cred, schedule,
1128 (struct sockaddr_in *) 0,
1129 (struct sockaddr_in *) 0,
1131 free ((char *) ticket);
1133 if (rem != KSUCCESS) {
1134 strcpy (pop_error, KRB_ERROR);
1135 strncat (pop_error, krb_err_txt[rem],
1136 ERROR_MAX - sizeof (KRB_ERROR));
1140 # endif /* HAVE_KERBEROS5 */
1142 #endif /* WITH_KERBEROS && HAVE_KERBEROS */
1145 } /* socket_connection */
1148 * Function: pop_getline
1150 * Purpose: Get a line of text from the connection and return a
1151 * pointer to it. The carriage return and linefeed at the end of
1152 * the line are stripped, but periods at the beginnings of lines
1153 * are NOT dealt with in any special way.
1156 * server The server from which to get the line of text.
1158 * Returns: The number of characters in the line, which is returned in
1159 * LINE, not including the final null. A return value of 0
1160 * indicates a blank line. A negative return value indicates an
1161 * error (in which case the contents of LINE are undefined. In
1162 * case of error, an error message is copied into pop_error.
1164 * Notes: The line returned is overwritten with each call to pop_getline.
1166 * Side effects: Closes the connection on error.
1168 * THE RETURNED LINE MAY CONTAIN EMBEDDED NULLS!
1171 pop_getline (server, line)
1175 #define GETLINE_ERROR "Error reading from server: "
1178 int search_offset = 0;
1181 char *cp = find_crlf (server->buffer + server->buffer_index,
1187 found = server->buffer_index;
1188 data_used = (cp + 2) - server->buffer - found;
1190 /* terminate the string to be returned */
1192 server->data -= data_used;
1193 server->buffer_index += data_used;
1196 /* Embedded nulls will truncate this output
1197 prematurely, but that's OK because it's just
1198 for debugging anyway. */
1199 fprintf (stderr, "<<< %s\n",
1200 server->buffer + found);
1201 *line = server->buffer + found;
1202 return (data_used - 2);
1204 bcopy (server->buffer + server->buffer_index,
1205 server->buffer, server->data);
1206 /* Record the fact that we've searched the data already
1207 in the buffer for a CRLF, so that when we search
1208 below, we don't have to search the same data twice.
1209 There's a "- 1" here to account for the fact that the
1210 last character of the data we have may be the CR of a
1211 CRLF pair, of which we haven't read the second half
1212 yet, so we may have to search it again when we read
1214 search_offset = server->data - 1;
1215 server->buffer_index = 0;
1218 server->buffer_index = 0;
1222 /* There's a "- 1" here to leave room for the null that we put
1223 at the end of the read data below. We put the null there so
1224 that find_crlf knows where to stop when we call it. */
1225 if (server->data == server->buffer_size - 1) {
1226 server->buffer_size += GETLINE_INCR;
1227 server->buffer = (char *)realloc (
1228 server->buffer, server->buffer_size);
1229 if (! server->buffer) {
1231 "Out of memory in pop_getline");
1236 ret = RECV (server->file, server->buffer + server->data,
1237 server->buffer_size - server->data - 1, 0);
1239 strcpy (pop_error, GETLINE_ERROR);
1240 strncat (pop_error, strerror (errno),
1241 ERROR_MAX - sizeof (GETLINE_ERROR));
1244 } else if (ret == 0) {
1245 strcpy (pop_error, "Unexpected EOF from "
1246 "server in pop_getline");
1251 server->data += ret;
1252 server->buffer[server->data] = '\0';
1254 cp = find_crlf (server->buffer + search_offset,
1255 server->data - search_offset);
1257 int data_used = (cp + 2) - server->buffer;
1259 server->data -= data_used;
1260 server->buffer_index = data_used;
1264 "<<< %s\n", server->buffer);
1265 *line = server->buffer;
1266 return (data_used - 2);
1268 /* As above, the "- 1" here is to account for the fact that
1269 we may have read a CR without its accompanying LF. */
1270 search_offset += ret - 1;
1278 * Function: sendline
1280 * Purpose: Sends a line of text to the POP server. The line of text
1281 * passed into this function should NOT have the carriage return
1282 * and linefeed on the end of it. Periods at beginnings of lines
1283 * will NOT be treated specially by this function.
1286 * server The server to which to send the text.
1287 * line The line of text to send.
1289 * Return value: Upon successful completion, a value of 0 will be
1290 * returned. Otherwise, a non-zero value will be returned, and
1291 * an error will be copied into pop_error.
1293 * Side effects: Closes the connection on error.
1296 sendline (server, line)
1300 #define SENDLINE_ERROR "Error writing to POP server: "
1304 /* Combine the string and the CR-LF into one buffer. Otherwise, two
1305 reasonable network stack optimizations, Nagle's algorithm and
1306 delayed acks, combine to delay us a fraction of a second on every
1307 message we send. (Movemail writes line without \r\n, client
1308 kernel sends packet, server kernel delays the ack to see if it
1309 can combine it with data, movemail writes \r\n, client kernel
1310 waits because it has unacked data already in its outgoing queue,
1311 client kernel eventually times out and sends.)
1313 This can be something like 0.2s per command, which can add up
1314 over a few dozen messages, and is a big chunk of the time we
1315 spend fetching mail from a server close by. */
1316 buf = alloca (strlen (line) + 3);
1318 strcat (buf, "\r\n");
1319 ret = fullwrite (server->file, buf, strlen (buf));
1323 strcpy (pop_error, SENDLINE_ERROR);
1324 strncat (pop_error, strerror (errno),
1325 ERROR_MAX - sizeof (SENDLINE_ERROR));
1330 fprintf (stderr, ">>> %s\n", line);
1336 * Procedure: fullwrite
1338 * Purpose: Just like write, but keeps trying until the entire string
1341 * Return value: Same as write. Pop_error is not set.
1344 fullwrite (fd, buf, nbytes)
1353 while (nbytes && ((ret = SEND (fd, cp, nbytes, 0)) > 0)) {
1364 * Purpose: Reads a line from the server. If the return indicator is
1365 * positive, return with a zero exit status. If not, return with
1366 * a negative exit status.
1369 * server The server to read from.
1371 * Returns: 0 for success, else for failure and puts error in pop_error.
1373 * Side effects: On failure, may make the connection unusable.
1381 if (pop_getline (server, &fromline) < 0) {
1385 if (! strncmp (fromline, "+OK", 3))
1387 else if (! strncmp (fromline, "-ERR", 4)) {
1388 strncpy (pop_error, fromline, ERROR_MAX);
1389 pop_error[ERROR_MAX-1] = '\0';
1393 "Unexpected response from server; "
1394 "expecting +OK or -ERR");
1402 * Function: gettermination
1404 * Purpose: Gets the next line and verifies that it is a termination
1405 * line (nothing but a dot).
1407 * Return value: 0 on success, non-zero with pop_error set on error.
1409 * Side effects: Closes the connection on error.
1412 gettermination (server)
1417 if (pop_getline (server, &fromserver) < 0)
1420 if (strcmp (fromserver, ".")) {
1422 "Unexpected response from server in gettermination");
1432 * Function pop_close
1434 * Purpose: Close a pop connection, sending a "RSET" command to try to
1435 * preserve any changes that were made and a "QUIT" command to
1436 * try to get the server to quit, but ignoring any responses that
1439 * Side effects: The server is unusable after this function returns.
1440 * Changes made to the maildrop since the session was started (or
1441 * since the last pop_reset) may be lost.
1448 free ((char *) server);
1454 * Function: pop_trash
1456 * Purpose: Like pop_close or pop_quit, but doesn't deallocate the
1457 * memory associated with the server. It is legal to call
1458 * pop_close or pop_quit after this function has been called.
1464 if (server->file >= 0) {
1465 /* avoid recursion; sendline can call pop_trash */
1466 if (server->trash_started)
1468 server->trash_started = 1;
1470 sendline (server, "RSET");
1471 sendline (server, "QUIT");
1473 CLOSESOCKET (server->file);
1475 if (server->buffer) {
1476 free (server->buffer);
1482 /* Return a pointer to the first CRLF in IN_STRING, which can contain
1483 embedded nulls and has LEN characters in it not including the final
1484 null, or 0 if it does not contain one. */
1487 find_crlf (in_string, len)
1492 if (*in_string == '\r') {
1493 if (*++in_string == '\n')
1494 return (in_string - 1);
1501 #endif /* MAIL_USE_POP */