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))
141 #define xstrncpy(d_,s_,l_) \
145 strncat((dst_),(s_),(l_)-1); \
149 * Function: pop_open (char *host, char *username, char *password,
152 * Purpose: Establishes a connection with a post-office server, and
153 * completes the authorization portion of the session.
156 * host The server host with which the connection should be
157 * established. Optional. If omitted, internal
158 * heuristics will be used to determine the server host,
161 * The username of the mail-drop to access. Optional.
162 * If omitted, internal heuristics will be used to
163 * determine the username, if possible.
165 * The password to use for authorization. If omitted,
166 * internal heuristics will be used to determine the
167 * password, if possible.
168 * flags A bit mask containing flags controlling certain
169 * functions of the routine. Valid flags are defined in
172 * Return value: Upon successful establishment of a connection, a
173 * non-null popserver will be returned. Otherwise, null will be
174 * returned, and the string variable pop_error will contain an
175 * explanation of the error.
178 pop_open (host, username, password, flags)
188 /* Determine the user name */
190 username = getenv ("USER");
191 if (! (username && *username)) {
192 username = getlogin ();
193 if (! (username && *username)) {
194 struct passwd *passwd;
195 passwd = getpwuid (getuid ());
196 if (passwd && passwd->pw_name &&
198 username = passwd->pw_name;
201 "Could not determine username");
209 * Determine the mail host.
213 host = getenv ("MAILHOST");
217 if ((! host) && (! (flags & POP_NO_HESIOD))) {
218 struct hes_postoffice *office;
219 office = hes_getmailhost (username);
220 if (office && office->po_type && (! strcmp (office->po_type, "POP"))
221 && office->po_name && *office->po_name && office->po_host
222 && *office->po_host) {
223 host = office->po_host;
224 username = office->po_name;
236 strcpy (pop_error, "Could not determine POP server");
240 /* Determine the password */
241 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
242 #define DONT_NEED_PASSWORD (! (flags & POP_NO_KERBEROS))
244 #define DONT_NEED_PASSWORD 0
247 if ((! password) && (! DONT_NEED_PASSWORD)) {
248 if (! (flags & POP_NO_GETPASS)) {
249 password = getpass ("Enter POP password:");
252 strcpy (pop_error, "Could not determine POP password");
256 if (password) /* always true, detected 20060515 */
257 flags |= POP_NO_KERBEROS;
259 password = username; /* dead code, detected 20060515 */
260 /** "kpop" service is never used: look for 20060515 to see why **/
262 sock = socket_connection (host, flags);
266 server = (popserver) malloc (sizeof (struct _popserver));
268 strcpy (pop_error, "Out of memory in pop_open");
271 server->buffer = (char *) malloc (GETLINE_MIN);
272 if (! server->buffer) {
273 strcpy (pop_error, "Out of memory in pop_open");
274 free ((char *) server);
280 server->buffer_index = 0;
281 server->buffer_size = GETLINE_MIN;
282 server->in_multi = 0;
283 server->trash_started = 0;
289 * I really shouldn't use the pop_error variable like this, but....
291 if (strlen (username) > ERROR_MAX - 6) {
294 "Username too long; "
295 "recompile pop.c with larger ERROR_MAX");
298 sz = snprintf (pop_error, sizeof(pop_error), "USER %s", username);
299 assert(sz>=0 && sz<sizeof(pop_error));
301 if (sendline (server, pop_error) || getok (server)) {
305 if (strlen (password) > ERROR_MAX - 6) {
308 "Password too long; "
309 "recompile pop.c with larger ERROR_MAX");
312 sz = snprintf (pop_error, sizeof(pop_error),
313 "PASS %s", password);
314 assert(sz>=0 && sz<sizeof(pop_error));
316 if (sendline (server, pop_error) || getok (server)) {
326 * Purpose: Issue the STAT command to the server and return (in the
327 * value parameters) the number of messages in the maildrop and
328 * the total size of the maildrop.
330 * Return value: 0 on success, or non-zero with an error in pop_error
333 * Side effects: On failure, may make further operations on the
334 * connection impossible.
337 pop_stat (server, count, size)
344 if (server->in_multi) {
345 strcpy (pop_error, "In multi-line query in pop_stat");
349 if (sendline (server, "STAT") ||
350 (pop_getline (server, &fromserver) < 0))
353 if (strncmp (fromserver, "+OK ", 4)) {
354 if (0 == strncmp (fromserver, "-ERR", 4)) {
355 xstrncpy (pop_error, fromserver, ERROR_MAX);
358 "Unexpected response from POP "
359 "server in pop_stat", ERROR_MAX);
365 *count = atoi (&fromserver[4]);
367 fromserver = index (&fromserver[4], ' ');
370 "Badly formatted response from server in pop_stat");
375 *size = atoi (fromserver + 1);
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.
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
393 * Return value: 0 on success, non-zero with error in pop_error on
396 * Side effects: On failure, may make further operations on the
397 * connection impossible.
400 pop_list (server, message, IDs, sizes)
409 if (server->in_multi) {
410 strcpy (pop_error, "In multi-line query in pop_list");
418 if (pop_stat (server, &count, &size))
423 *IDs = (int *) malloc ((how_many + 1) * sizeof (int));
424 *sizes = (int *) malloc ((how_many + 1) * sizeof (int));
425 if (! (*IDs && *sizes)) {
426 strcpy (pop_error, "Out of memory in pop_list");
431 sz = snprintf (pop_error, sizeof(pop_error), "LIST %d", message);
432 assert(sz>=0 && sz<sizeof(pop_error));
433 if (sendline (server, pop_error)) {
434 free ((char *) *IDs);
435 free ((char *) *sizes);
438 if (pop_getline (server, &fromserver) < 0) {
439 free ((char *) *IDs);
440 free ((char *) *sizes);
443 if (strncmp (fromserver, "+OK ", 4)) {
444 if (! strncmp (fromserver, "-ERR", 4)) {
445 xstrncpy (pop_error, fromserver, ERROR_MAX);
448 "Unexpected response from "
449 "server in pop_list");
452 free ((char *) *IDs);
453 free ((char *) *sizes);
456 (*IDs)[0] = atoi (&fromserver[4]);
457 fromserver = index (&fromserver[4], ' ');
460 "Badly formatted response from "
461 "server in pop_list");
463 free ((char *) *IDs);
464 free ((char *) *sizes);
467 (*sizes)[0] = atoi (fromserver);
468 (*IDs)[1] = (*sizes)[1] = 0;
471 if (pop_multi_first (server, "LIST", &fromserver)) {
472 free ((char *) *IDs);
473 free ((char *) *sizes);
476 for (i = 0; i < how_many; i++) {
477 if (pop_multi_next (server, &fromserver) <= 0) {
478 free ((char *) *IDs);
479 free ((char *) *sizes);
482 (*IDs)[i] = atoi (fromserver);
483 fromserver = index (fromserver, ' ');
486 "Badly formatted response from "
487 "server in pop_list");
488 free ((char *) *IDs);
489 free ((char *) *sizes);
493 (*sizes)[i] = atoi (fromserver);
495 if (pop_multi_next (server, &fromserver) < 0) {
496 free ((char *) *IDs);
497 free ((char *) *sizes);
499 } else if (fromserver) {
501 "Too many response lines from "
502 "server in pop_list");
503 free ((char *) *IDs);
504 free ((char *) *sizes);
507 (*IDs)[i] = (*sizes)[i] = 0;
513 * Function: pop_retrieve
515 * Purpose: Retrieve a specified message from the maildrop.
518 * server The server to retrieve from.
519 * message The message number to retrieve.
521 * If true, then mark the string "From " at the beginning
523 * msg_buf Output parameter to which a buffer containing the
524 * message is assigned.
526 * Return value: The number of bytes in msg_buf, which may contain
527 * embedded nulls, not including its final null, or -1 on error
528 * with pop_error set.
530 * Side effects: May kill connection on error.
533 pop_retrieve (server, message, markfrom, msg_buf)
539 int *IDs, *sizes, bufsize, fromcount = 0, cp = 0;
540 char *ptr, *fromserver;
543 if (server->in_multi) {
544 strcpy (pop_error, "In multi-line query in pop_retrieve");
548 if (pop_list (server, message, &IDs, &sizes))
551 if (pop_retrieve_first (server, message, &fromserver)) {
556 * The "5" below is an arbitrary constant -- I assume that if
557 * there are "From" lines in the text to be marked, there
558 * probably won't be more than 5 of them. If there are, I
559 * allocate more space for them below.
561 bufsize = sizes[0] + (markfrom ? 5 : 0);
562 ptr = (char *)malloc (bufsize);
564 free ((char *) sizes);
567 strcpy (pop_error, "Out of memory in pop_retrieve");
568 pop_retrieve_flush (server);
572 while ((ret = pop_retrieve_next (server, &fromserver)) >= 0) {
578 if (markfrom && fromserver[0] == 'F' && fromserver[1] == 'r' &&
579 fromserver[2] == 'o' && fromserver[3] == 'm' &&
580 fromserver[4] == ' ') {
581 if (++fromcount == 5) {
583 ptr = (char *)realloc (ptr, bufsize);
585 strcpy (pop_error, "Out of memory "
587 pop_retrieve_flush (server);
594 bcopy (fromserver, &ptr[cp], ret);
604 pop_retrieve_first (server, message, response)
609 int sz = snprintf (pop_error, sizeof(pop_error), "RETR %d", message);
610 assert(sz>=0 && sz<sizeof(pop_error));
611 return (pop_multi_first (server, pop_error, response));
615 Returns a negative number on error, 0 to indicate that the data has
616 all been read (i.e., the server has returned a "." termination
617 line), or a positive number indicating the number of bytes in the
618 returned buffer (which is null-terminated and may contain embedded
619 nulls, but the returned bytecount doesn't include the final null).
623 pop_retrieve_next (server, line)
627 return (pop_multi_next (server, line));
631 pop_retrieve_flush (server)
634 return (pop_multi_flush (server));
638 pop_top_first (server, message, lines, response)
643 int sz = snprintf (pop_error, sizeof(pop_error),
644 "TOP %d %d", message, lines);
645 assert(sz>=0 && sz<sizeof(pop_error));
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 (server, line)
662 return (pop_multi_next (server, line));
666 pop_top_flush (server)
669 return (pop_multi_flush (server));
673 pop_multi_first (server, command, response)
678 if (server->in_multi) {
680 "Already in multi-line query in pop_multi_first");
684 if (sendline (server, command) ||
685 (pop_getline (server, response) < 0)) {
689 if (0 == strncmp (*response, "-ERR", 4)) {
690 xstrncpy (pop_error, *response, ERROR_MAX);
692 } else if (0 == strncmp (*response, "+OK", 3)) {
693 for (*response += 3; **response == ' ';
694 (*response)++) /* empty */;
695 server->in_multi = 1;
699 "Unexpected response from "
700 "server in pop_multi_first");
706 Read the next line of data from SERVER and place a pointer to it
707 into LINE. Return -1 on error, 0 if there are no more lines to read
708 (i.e., the server has returned a line containing only "."), or a
709 positive number indicating the number of bytes in the LINE buffer
710 (not including the final null). The data in that buffer may contain
711 embedded nulls, but does not contain the final CRLF. When returning
712 0, LINE is set to null. */
715 pop_multi_next (server, line)
722 if (! server->in_multi) {
723 strcpy (pop_error, "Not in multi-line query in pop_multi_next");
727 if ((ret = pop_getline (server, &fromserver)) < 0) {
731 if (fromserver[0] == '.') {
732 if (! fromserver[1]) {
734 server->in_multi = 0;
737 *line = fromserver + 1;
747 pop_multi_flush (server)
753 if (! server->in_multi) {
757 while ((ret = pop_multi_next (server, &line))) {
765 /* Function: pop_delete
767 * Purpose: Delete a specified message.
770 * server Server from which to delete the message.
771 * message Message to delete.
773 * Return value: 0 on success, non-zero with error in pop_error
777 pop_delete (server, message)
783 if (server->in_multi) {
784 strcpy (pop_error, "In multi-line query in pop_delete");
788 sz = snprintf (pop_error, sizeof(pop_error),
790 assert(sz>=0 && sz<sizeof(pop_error));
792 if (sendline (server, pop_error) || getok (server))
801 * Purpose: Send a noop command to the server.
804 * server The server to send to.
806 * Return value: 0 on success, non-zero with error in pop_error
809 * Side effects: Closes connection on error.
815 if (server->in_multi) {
816 strcpy (pop_error, "In multi-line query in pop_noop");
820 if (sendline (server, "NOOP") || getok (server))
829 * Purpose: Find out the highest seen message from the server.
834 * Return value: If successful, the highest seen message, which is
835 * greater than or equal to 0. Otherwise, a negative number with
836 * the error explained in pop_error.
838 * Side effects: Closes the connection on error.
846 if (server->in_multi) {
847 strcpy (pop_error, "In multi-line query in pop_last");
851 if (sendline (server, "LAST"))
854 if (pop_getline (server, &fromserver) < 0)
857 if (! strncmp (fromserver, "-ERR", 4)) {
858 xstrncpy (pop_error, fromserver, ERROR_MAX);
860 } else if (strncmp (fromserver, "+OK ", 4)) {
861 strcpy (pop_error, "Unexpected response from server in pop_last");
865 return (atoi (&fromserver[4]));
870 * Function: pop_reset
872 * Purpose: Reset the server to its initial connect state
877 * Return value: 0 for success, non-0 with error in pop_error
880 * Side effects: Closes the connection on error.
886 if (pop_retrieve_flush (server)) {
890 if (sendline (server, "RSET") || getok (server))
899 * Purpose: Quit the connection to the server,
902 * server The server to quit.
904 * Return value: 0 for success, non-zero otherwise with error in
907 * Side Effects: The popserver passed in is unusable after this
908 * function is called, even if an error occurs.
916 if (server->file >= 0) {
917 if (pop_retrieve_flush (server)) {
921 if (sendline (server, "QUIT") || getok (server)) {
925 close (server->file);
929 free (server->buffer);
930 free ((char *) server);
936 * Function: socket_connection
938 * Purpose: Opens the network connection with the mail host, without
939 * doing any sort of I/O with it or anything.
942 * host The host to which to connect.
943 * flags Option flags.
945 * Return value: A file descriptor indicating the connection, or -1
946 * indicating failure, in which case an error has been copied
950 socket_connection (host, flags)
954 struct hostent *hostent;
955 struct servent *servent;
956 struct sockaddr_in addr;
960 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
961 # if defined HAVE_KERBEROS5
963 krb5_context kcontext = 0;
964 krb5_auth_context auth_context = 0;
966 krb5_principal client, server;
969 # else /* !HAVE_KERBEROS5 */
973 Key_schedule schedule;
976 # endif /* HAVE_KERBEROS5 */
977 #endif /* WITH_KERBEROS && HAVE_KERBEROS */
981 bzero ((char *) &addr, sizeof (addr));
982 addr.sin_family = AF_INET;
984 /** "kpop" service is never used: look for 20060515 to see why **/
985 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
986 service = (flags & POP_NO_KERBEROS) ? POP_SERVICE : KPOP_SERVICE;
988 service = POP_SERVICE;
992 if (! (flags & POP_NO_HESIOD)) {
993 servent = hes_getservbyname (service, "tcp");
995 addr.sin_port = servent->s_port;
1001 servent = getservbyname (service, "tcp");
1003 addr.sin_port = servent->s_port;
1005 /** "kpop" service is never used:
1006 * look for 20060515 to see why **/
1007 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
1008 addr.sin_port = htons ((flags & POP_NO_KERBEROS) ?
1009 POP_PORT : KPOP_PORT);
1011 addr.sin_port = htons (POP_PORT);
1016 #define POP_SOCKET_ERROR "Could not create socket for POP connection: "
1018 sock = socket (PF_INET, SOCK_STREAM, 0);
1020 strcpy (pop_error, POP_SOCKET_ERROR);
1021 strncat (pop_error, strerror (errno),
1022 ERROR_MAX - sizeof (POP_SOCKET_ERROR));
1028 hostent = gethostbyname (host);
1031 ((h_errno != TRY_AGAIN) || (try_count == 5))) {
1032 strcpy (pop_error, "Could not determine "
1033 "POP server's address");
1036 } while (! hostent);
1038 while (*hostent->h_addr_list) {
1039 bcopy (*hostent->h_addr_list, (char *) &addr.sin_addr,
1041 if (! connect (sock, (struct sockaddr *) &addr, sizeof (addr)))
1043 hostent->h_addr_list++;
1046 #define CONNECT_ERROR "Could not connect to POP server: "
1048 if (! *hostent->h_addr_list) {
1050 strcpy (pop_error, CONNECT_ERROR);
1051 strncat (pop_error, strerror (errno),
1052 ERROR_MAX - sizeof (CONNECT_ERROR));
1056 #if defined WITH_KERBEROS && defined HAVE_KERBEROS
1057 #define KRB_ERROR "Kerberos error connecting to POP server: "
1058 if (! (flags & POP_NO_KERBEROS)) {
1059 # if defined HAVE_KERBEROS5
1060 if ((rem = krb5_init_context (&kcontext))) {
1063 krb5_auth_con_free (kcontext, auth_context);
1065 krb5_free_context (kcontext);
1066 strcpy (pop_error, KRB_ERROR);
1067 strncat (pop_error, error_message (rem),
1068 ERROR_MAX - sizeof(KRB_ERROR));
1073 if ((rem = krb5_auth_con_init (kcontext, &auth_context)))
1076 if (rem = krb5_cc_default (kcontext, &ccdef))
1079 if (rem = krb5_cc_get_principal (kcontext, ccdef, &client))
1082 for (cp = hostent->h_name; *cp; cp++) {
1083 if (isupper (*cp)) {
1084 *cp = tolower (*cp);
1088 if (rem = krb5_sname_to_principal (kcontext, hostent->h_name,
1089 POP_SERVICE, FALSE, &server))
1092 rem = krb5_sendauth (kcontext, &auth_context,
1093 (krb5_pointer) &sock, "KPOPV1.0",
1095 AP_OPTS_MUTUAL_REQUIRED,
1096 0, /* no checksum */
1097 0, /* no creds, use ccache instead */
1100 0, /* don't need subsession key */
1101 0); /* don't need reply */
1102 krb5_free_principal (kcontext, server);
1104 if (err_ret && err_ret->text.length) {
1105 strcpy (pop_error, KRB_ERROR);
1106 strncat (pop_error, error_message (rem),
1107 ERROR_MAX - sizeof (KRB_ERROR));
1108 strncat (pop_error, " [server says '",
1109 ERROR_MAX - strlen (pop_error) - 1);
1110 strncat (pop_error, err_ret->text.data,
1112 strlen (pop_error) - 1,
1113 err_ret->text.length));
1114 strncat (pop_error, "']",
1115 ERROR_MAX - strlen (pop_error) - 1);
1117 strcpy (pop_error, KRB_ERROR);
1118 strncat (pop_error, error_message (rem),
1119 ERROR_MAX - sizeof (KRB_ERROR));
1122 krb5_free_error (kcontext, err_ret);
1123 krb5_auth_con_free (kcontext, auth_context);
1124 krb5_free_context (kcontext);
1129 # else /* ! HAVE_KERBEROS5 */
1130 ticket = (KTEXT) malloc (sizeof (KTEXT_ST));
1131 realhost = strdup (hostent->h_name);
1132 rem = krb_sendauth (0L, sock, ticket, "pop", realhost,
1133 (char *) krb_realmofhost (realhost),
1134 (unsigned long) 0, &msg_data, &cred, schedule,
1135 (struct sockaddr_in *) 0,
1136 (struct sockaddr_in *) 0,
1138 free ((char *) ticket);
1140 if (rem != KSUCCESS) {
1141 strcpy (pop_error, KRB_ERROR);
1142 strncat (pop_error, krb_err_txt[rem],
1143 ERROR_MAX - sizeof (KRB_ERROR));
1147 # endif /* HAVE_KERBEROS5 */
1149 #endif /* WITH_KERBEROS && HAVE_KERBEROS */
1152 } /* socket_connection */
1155 * Function: pop_getline
1157 * Purpose: Get a line of text from the connection and return a
1158 * pointer to it. The carriage return and linefeed at the end of
1159 * the line are stripped, but periods at the beginnings of lines
1160 * are NOT dealt with in any special way.
1163 * server The server from which to get the line of text.
1165 * Returns: The number of characters in the line, which is returned in
1166 * LINE, not including the final null. A return value of 0
1167 * indicates a blank line. A negative return value indicates an
1168 * error (in which case the contents of LINE are undefined. In
1169 * case of error, an error message is copied into pop_error.
1171 * Notes: The line returned is overwritten with each call to pop_getline.
1173 * Side effects: Closes the connection on error.
1175 * THE RETURNED LINE MAY CONTAIN EMBEDDED NULLS!
1178 pop_getline (server, line)
1182 #define GETLINE_ERROR "Error reading from server: "
1185 int search_offset = 0;
1188 char *cp = find_crlf (server->buffer + server->buffer_index,
1194 found = server->buffer_index;
1195 data_used = (cp + 2) - server->buffer - found;
1197 /* terminate the string to be returned */
1199 server->data -= data_used;
1200 server->buffer_index += data_used;
1203 /* Embedded nulls will truncate this output
1204 prematurely, but that's OK because it's just
1205 for debugging anyway. */
1206 fprintf (stderr, "<<< %s\n",
1207 server->buffer + found);
1208 *line = server->buffer + found;
1209 return (data_used - 2);
1211 bcopy (server->buffer + server->buffer_index,
1212 server->buffer, server->data);
1213 /* Record the fact that we've searched the data already
1214 in the buffer for a CRLF, so that when we search
1215 below, we don't have to search the same data twice.
1216 There's a "- 1" here to account for the fact that the
1217 last character of the data we have may be the CR of a
1218 CRLF pair, of which we haven't read the second half
1219 yet, so we may have to search it again when we read
1221 search_offset = server->data - 1;
1222 server->buffer_index = 0;
1225 server->buffer_index = 0;
1229 /* There's a "- 1" here to leave room for the null that we put
1230 at the end of the read data below. We put the null there so
1231 that find_crlf knows where to stop when we call it. */
1232 if (server->data == server->buffer_size - 1) {
1233 server->buffer_size += GETLINE_INCR;
1234 server->buffer = (char *)realloc (
1235 server->buffer, server->buffer_size);
1236 if (! server->buffer) {
1238 "Out of memory in pop_getline");
1243 ret = RECV (server->file, server->buffer + server->data,
1244 server->buffer_size - server->data - 1, 0);
1246 strcpy (pop_error, GETLINE_ERROR);
1247 strncat (pop_error, strerror (errno),
1248 ERROR_MAX - sizeof (GETLINE_ERROR));
1251 } else if (ret == 0) {
1252 strcpy (pop_error, "Unexpected EOF from "
1253 "server in pop_getline");
1258 server->data += ret;
1259 server->buffer[server->data] = '\0';
1261 cp = find_crlf (server->buffer + search_offset,
1262 server->data - search_offset);
1264 int data_used = (cp + 2) - server->buffer;
1266 server->data -= data_used;
1267 server->buffer_index = data_used;
1271 "<<< %s\n", server->buffer);
1272 *line = server->buffer;
1273 return (data_used - 2);
1275 /* As above, the "- 1" here is to account for the fact that
1276 we may have read a CR without its accompanying LF. */
1277 search_offset += ret - 1;
1285 * Function: sendline
1287 * Purpose: Sends a line of text to the POP server. The line of text
1288 * passed into this function should NOT have the carriage return
1289 * and linefeed on the end of it. Periods at beginnings of lines
1290 * will NOT be treated specially by this function.
1293 * server The server to which to send the text.
1294 * line The line of text to send.
1296 * Return value: Upon successful completion, a value of 0 will be
1297 * returned. Otherwise, a non-zero value will be returned, and
1298 * an error will be copied into pop_error.
1300 * Side effects: Closes the connection on error.
1303 sendline (server, line)
1307 #define SENDLINE_ERROR "Error writing to POP server: "
1311 /* Combine the string and the CR-LF into one buffer. Otherwise, two
1312 reasonable network stack optimizations, Nagle's algorithm and
1313 delayed acks, combine to delay us a fraction of a second on every
1314 message we send. (Movemail writes line without \r\n, client
1315 kernel sends packet, server kernel delays the ack to see if it
1316 can combine it with data, movemail writes \r\n, client kernel
1317 waits because it has unacked data already in its outgoing queue,
1318 client kernel eventually times out and sends.)
1320 This can be something like 0.2s per command, which can add up
1321 over a few dozen messages, and is a big chunk of the time we
1322 spend fetching mail from a server close by. */
1323 buf = alloca (strlen (line) + 3);
1325 strcat (buf, "\r\n");
1326 ret = fullwrite (server->file, buf, strlen (buf));
1330 strcpy (pop_error, SENDLINE_ERROR);
1331 strncat (pop_error, strerror (errno),
1332 ERROR_MAX - sizeof (SENDLINE_ERROR));
1337 fprintf (stderr, ">>> %s\n", line);
1343 * Procedure: fullwrite
1345 * Purpose: Just like write, but keeps trying until the entire string
1348 * Return value: Same as write. Pop_error is not set.
1351 fullwrite (fd, buf, nbytes)
1360 while (nbytes && ((ret = SEND (fd, cp, nbytes, 0)) > 0)) {
1371 * Purpose: Reads a line from the server. If the return indicator is
1372 * positive, return with a zero exit status. If not, return with
1373 * a negative exit status.
1376 * server The server to read from.
1378 * Returns: 0 for success, else for failure and puts error in pop_error.
1380 * Side effects: On failure, may make the connection unusable.
1388 if (pop_getline (server, &fromline) < 0) {
1392 if (! strncmp (fromline, "+OK", 3))
1394 else if (! strncmp (fromline, "-ERR", 4)) {
1395 xstrncpy (pop_error, fromline, ERROR_MAX);
1396 pop_error[ERROR_MAX-1] = '\0';
1400 "Unexpected response from server; "
1401 "expecting +OK or -ERR");
1409 * Function: gettermination
1411 * Purpose: Gets the next line and verifies that it is a termination
1412 * line (nothing but a dot).
1414 * Return value: 0 on success, non-zero with pop_error set on error.
1416 * Side effects: Closes the connection on error.
1419 gettermination (server)
1424 if (pop_getline (server, &fromserver) < 0)
1427 if (strcmp (fromserver, ".")) {
1429 "Unexpected response from server in gettermination");
1439 * Function pop_close
1441 * Purpose: Close a pop connection, sending a "RSET" command to try to
1442 * preserve any changes that were made and a "QUIT" command to
1443 * try to get the server to quit, but ignoring any responses that
1446 * Side effects: The server is unusable after this function returns.
1447 * Changes made to the maildrop since the session was started (or
1448 * since the last pop_reset) may be lost.
1455 free ((char *) server);
1461 * Function: pop_trash
1463 * Purpose: Like pop_close or pop_quit, but doesn't deallocate the
1464 * memory associated with the server. It is legal to call
1465 * pop_close or pop_quit after this function has been called.
1471 if (server->file >= 0) {
1472 /* avoid recursion; sendline can call pop_trash */
1473 if (server->trash_started)
1475 server->trash_started = 1;
1477 sendline (server, "RSET");
1478 sendline (server, "QUIT");
1480 CLOSESOCKET (server->file);
1482 if (server->buffer) {
1483 free (server->buffer);
1489 /* Return a pointer to the first CRLF in IN_STRING, which can contain
1490 embedded nulls and has LEN characters in it not including the final
1491 null, or 0 if it does not contain one. */
1494 find_crlf (in_string, len)
1499 if (*in_string == '\r') {
1500 if (*++in_string == '\n')
1501 return (in_string - 1);
1508 #endif /* MAIL_USE_POP */