728d1cae33747726cacaf2e5c9f3d12e686a3db2
[chise/xemacs-chise.git.1] / lib-src / pop.c
1 /* pop.c: client routines for talking to a POP3-protocol post-office server
2    Copyright (c) 1991, 1993, 1996 Free Software Foundation, Inc.
3    Written by Jonathan Kamens, jik@security.ov.com.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs; see the file COPYING.  If not, write to
19 the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #ifdef HAVE_CONFIG_H
23 #define NO_SHORTNAMES   /* Tell config not to load remap.h */
24 #include <../src/config.h>
25 #else
26 #define MAIL_USE_POP
27 #endif
28
29 #ifdef MAIL_USE_POP
30
31 #ifdef HAVE_CONFIG_H
32 /* Cancel these substitutions made in config.h */
33 #undef open
34 #undef read
35 #undef write
36 #undef close
37 #endif
38
39 #include <sys/types.h>
40 #ifdef WINDOWSNT
41 #include "ntlib.h"
42 #include <winsock.h>
43 #undef SOCKET_ERROR
44 #define RECV(s,buf,len,flags) recv(s,buf,len,flags)
45 #define SEND(s,buf,len,flags) send(s,buf,len,flags)
46 #define CLOSESOCKET(s) closesocket(s)
47 #else
48 #include <netinet/in.h>
49 #include <sys/socket.h>
50 #define RECV(s,buf,len,flags) read(s,buf,len)
51 #define SEND(s,buf,len,flags) write(s,buf,len)
52 #define CLOSESOCKET(s) close(s)
53 #endif
54 #include "pop.h"
55
56 #ifdef sun
57 #include <malloc.h>
58 #endif /* sun */
59
60 #ifdef HESIOD
61 #include <hesiod.h>
62 /*
63  * It really shouldn't be necessary to put this declaration here, but
64  * the version of hesiod.h that Athena has installed in release 7.2
65  * doesn't declare this function; I don't know if the 7.3 version of
66  * hesiod.h does.
67  */
68 extern struct servent *hes_getservbyname (/* char *, char * */);
69 #endif
70
71 #include <pwd.h>
72 #include <netdb.h>
73 #include <errno.h>
74 #include <stdio.h>
75
76 #include <unistd.h>
77 #include <sys/stat.h>
78 #include <sys/file.h>
79 #include "../src/syswait.h"
80 #include "../src/systime.h"
81 #include <stdlib.h>
82 #include <string.h>
83
84 #ifdef KERBEROS
85 #ifndef KRB5
86 #include <des.h>
87 #include <krb.h>
88 #else /* KRB5 */
89 #include <krb5/krb5.h>
90 #include <krb5/ext-proto.h>
91 #include <ctype.h>
92 #endif /* KRB5 */
93 #endif /* KERBEROS */
94
95 #ifdef KERBEROS
96 #ifndef KRB5
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 /* ! KRB5 */
103 #endif /* KERBEROS */
104
105 #ifndef WINDOWSNT
106 #if !defined(HAVE_H_ERRNO) || !defined(HAVE_CONFIG_H)
107 extern int h_errno;
108 #endif
109 #endif
110
111 static int socket_connection (char *, int);
112 static char *pop_getline (popserver);
113 static int sendline (popserver, char *);
114 static int fullwrite (int, char *, int);
115 static int getok (popserver);
116 #if 0
117 static int gettermination (popserver);
118 #endif
119 static void pop_trash (popserver);
120 static char *find_crlf (char *);
121
122 #define ERROR_MAX 80            /* a pretty arbitrary size */
123 #define POP_PORT 110
124 #define KPOP_PORT 1109
125 #if defined(WINDOWSNT) || defined(__CYGWIN32__)
126 #define POP_SERVICE "pop3"      /* we don't want the POP2 port! */
127 #else
128 #define POP_SERVICE "pop"
129 #endif
130 #ifdef KERBEROS
131 #ifdef KRB5
132 #define KPOP_SERVICE "k5pop";
133 #else
134 #define KPOP_SERVICE "kpop"
135 #endif
136 #endif
137
138 char pop_error[ERROR_MAX];
139 int pop_debug = 0;
140
141 #ifndef min
142 #define min(a,b) (((a) < (b)) ? (a) : (b))
143 #endif
144
145 /*
146  * Function: pop_open (char *host, char *username, char *password,
147  *                     int flags)
148  *
149  * Purpose: Establishes a connection with a post-office server, and
150  *      completes the authorization portion of the session.
151  *
152  * Arguments:
153  *      host    The server host with which the connection should be
154  *              established.  Optional.  If omitted, internal
155  *              heuristics will be used to determine the server host,
156  *              if possible.
157  *      username
158  *              The username of the mail-drop to access.  Optional.
159  *              If omitted, internal heuristics will be used to
160  *              determine the username, if possible.
161  *      password
162  *              The password to use for authorization.  If omitted,
163  *              internal heuristics will be used to determine the
164  *              password, if possible.
165  *      flags   A bit mask containing flags controlling certain
166  *              functions of the routine.  Valid flags are defined in
167  *              the file pop.h
168  *
169  * Return value: Upon successful establishment of a connection, a
170  *      non-null popserver will be returned.  Otherwise, null will be
171  *      returned, and the string variable pop_error will contain an
172  *      explanation of the error.
173  */
174 popserver
175 pop_open (char *host, char *username, char *password, int flags)
176 {
177   int sock;
178   popserver server;
179
180   /* Determine the user name */
181   if (! username)
182     {
183       username = getenv ("USER");
184       if (! (username && *username))
185         {
186           username = getlogin ();
187           if (! (username && *username))
188             {
189               struct passwd *passwd;
190               passwd = getpwuid (getuid ());
191               if (passwd && passwd->pw_name && *passwd->pw_name)
192                 {
193                   username = passwd->pw_name;
194                 }
195               else
196                 {
197                   strcpy (pop_error, "Could not determine username");
198                   return (0);
199                 }
200             }
201         }
202     }
203
204   /*
205    *  Determine the mail host.
206    */
207
208   if (! host)
209     {
210       host = getenv ("MAILHOST");
211     }
212
213 #ifdef HESIOD
214   if ((! host) && (! (flags & POP_NO_HESIOD)))
215     {
216       struct hes_postoffice *office;
217       office = hes_getmailhost (username);
218       if (office && office->po_type && (! strcmp (office->po_type, "POP"))
219           && office->po_name && *office->po_name && office->po_host
220           && *office->po_host)
221         {
222           host = office->po_host;
223           username = office->po_name;
224         }
225     }
226 #endif
227
228 #ifdef MAILHOST
229   if (! host)
230     {
231       host = MAILHOST;
232     }
233 #endif
234
235   if (! host)
236     {
237       strcpy (pop_error, "Could not determine POP server");
238       return (0);
239     }
240
241   /* Determine the password */
242 #ifdef KERBEROS
243 #define DONT_NEED_PASSWORD (! (flags & POP_NO_KERBEROS))
244 #else
245 #define DONT_NEED_PASSWORD 0
246 #endif
247  
248   if ((! password) && (! DONT_NEED_PASSWORD))
249     {
250       if (! (flags & POP_NO_GETPASS))
251         {
252           password = getpass ("Enter POP password:");
253         }
254       if (! password)
255         {
256           strcpy (pop_error, "Could not determine POP password");
257           return (0);
258         }
259     }
260   if (password)
261     flags |= POP_NO_KERBEROS;
262   else
263     password = username;
264
265   sock = socket_connection (host, flags);
266   if (sock == -1)
267     return (0);
268
269   server = (popserver) malloc (sizeof (struct _popserver));
270   if (! server)
271     {
272       strcpy (pop_error, "Out of memory in pop_open");
273       return (0);
274     }
275   server->buffer = (char *) malloc (GETLINE_MIN);
276   if (! server->buffer)
277     {
278       strcpy (pop_error, "Out of memory in pop_open");
279       free ((char *) server);
280       return (0);
281     }
282           
283   server->file = sock;
284   server->data = 0;
285   server->buffer_index = 0;
286   server->buffer_size = GETLINE_MIN;
287   server->in_multi = 0;
288   server->trash_started = 0;
289
290   if (getok (server))
291     return (0);
292
293   /*
294    * I really shouldn't use the pop_error variable like this, but....
295    */
296   if (strlen (username) > ERROR_MAX - 6)
297     {
298       pop_close (server);
299       strcpy (pop_error,
300               "Username too long; recompile pop.c with larger ERROR_MAX");
301       return (0);
302     }
303   sprintf (pop_error, "USER %s", username);
304
305   if (sendline (server, pop_error) || getok (server))
306     {
307       return (0);
308     }
309
310   if (strlen (password) > ERROR_MAX - 6)
311     {
312       pop_close (server);
313       strcpy (pop_error,
314               "Password too long; recompile pop.c with larger ERROR_MAX");
315       return (0);
316     }
317   sprintf (pop_error, "PASS %s", password);
318
319   if (sendline (server, pop_error) || getok (server))
320     {
321       return (0);
322     }
323
324   return (server);
325 }
326
327 /*
328  * Function: pop_stat
329  *
330  * Purpose: Issue the STAT command to the server and return (in the
331  *      value parameters) the number of messages in the maildrop and
332  *      the total size of the maildrop.
333  *
334  * Return value: 0 on success, or non-zero with an error in pop_error
335  *      in failure.
336  *
337  * Side effects: On failure, may make further operations on the
338  *      connection impossible.
339  */
340 int
341 pop_stat (popserver server, int *count, int *size)
342 {
343   char *fromserver;
344
345   if (server->in_multi)
346     {
347       strcpy (pop_error, "In multi-line query in pop_stat");
348       return (-1);
349     }
350      
351   if (sendline (server, "STAT") || (! (fromserver = pop_getline (server))))
352     return (-1);
353
354   if (strncmp (fromserver, "+OK ", 4))
355     {
356       if (0 == strncmp (fromserver, "-ERR", 4))
357         {
358           strncpy (pop_error, fromserver, ERROR_MAX);
359         }
360       else
361         {
362           strcpy (pop_error,
363                   "Unexpected response from POP server in pop_stat");
364           pop_trash (server);
365         }
366       return (-1);
367     }
368
369   *count = atoi (&fromserver[4]);
370      
371   fromserver = strchr (&fromserver[4], ' ');
372   if (! fromserver)
373     {
374       strcpy (pop_error,
375               "Badly formatted response from server in pop_stat");
376       pop_trash (server);
377       return (-1);
378     }
379
380   *size = atoi (fromserver + 1);
381
382   return (0);
383 }
384
385 /*
386  * Function: pop_list
387  *
388  * Purpose: Performs the POP "list" command and returns (in value
389  *      parameters) two malloc'd zero-terminated arrays -- one of
390  *      message IDs, and a parallel one of sizes.
391  *
392  * Arguments:
393  *      server  The pop connection to talk to.
394  *      message The number of the one message about which to get
395  *              information, or 0 to get information about all
396  *              messages.
397  *
398  * Return value: 0 on success, non-zero with error in pop_error on
399  *      failure.
400  *
401  * Side effects: On failure, may make further operations on the
402  *      connection impossible.
403  */
404 int
405 pop_list (popserver server, int message, int **IDs, int **sizes)
406 {
407   int how_many, i;
408   char *fromserver;
409
410   if (server->in_multi)
411     {
412       strcpy (pop_error, "In multi-line query in pop_list");
413       return (-1);
414     }
415
416   if (message)
417     how_many = 1;
418   else
419     {
420       int count, size;
421       if (pop_stat (server, &count, &size))
422         return (-1);
423       how_many = count;
424     }
425
426   *IDs = (int *) malloc ((how_many + 1) * sizeof (int));
427   *sizes = (int *) malloc ((how_many + 1) * sizeof (int));
428   if (! (*IDs && *sizes))
429     {
430       strcpy (pop_error, "Out of memory in pop_list");
431       return (-1);
432     }
433
434   if (message)
435     {
436       sprintf (pop_error, "LIST %d", message);
437       if (sendline (server, pop_error))
438         {
439           free ((char *) *IDs);
440           free ((char *) *sizes);
441           return (-1);
442         }
443       if (! (fromserver = pop_getline (server)))
444         {
445           free ((char *) *IDs);
446           free ((char *) *sizes);
447           return (-1);
448         }
449       if (strncmp (fromserver, "+OK ", 4))
450         {
451           if (! strncmp (fromserver, "-ERR", 4))
452             strncpy (pop_error, fromserver, ERROR_MAX);
453           else
454             {
455               strcpy (pop_error,
456                       "Unexpected response from server in pop_list");
457               pop_trash (server);
458             }
459           free ((char *) *IDs);
460           free ((char *) *sizes);
461           return (-1);
462         }
463       (*IDs)[0] = atoi (&fromserver[4]);
464       fromserver = strchr (&fromserver[4], ' ');
465       if (! fromserver)
466         {
467           strcpy (pop_error,
468                   "Badly formatted response from server in pop_list");
469           pop_trash (server);
470           free ((char *) *IDs);
471           free ((char *) *sizes);
472           return (-1);
473         }
474       (*sizes)[0] = atoi (fromserver);
475       (*IDs)[1] = (*sizes)[1] = 0;
476       return (0);
477     }
478   else
479     {
480       if (pop_multi_first (server, "LIST", &fromserver))
481         {
482           free ((char *) *IDs);
483           free ((char *) *sizes);
484           return (-1);
485         }
486       for (i = 0; i < how_many; i++)
487         {
488           if (pop_multi_next (server, &fromserver))
489             {
490               free ((char *) *IDs);
491               free ((char *) *sizes);
492               return (-1);
493             }
494           (*IDs)[i] = atoi (fromserver);
495           fromserver = strchr (fromserver, ' ');
496           if (! fromserver)
497             {
498               strcpy (pop_error,
499                       "Badly formatted response from server in pop_list");
500               free ((char *) *IDs);
501               free ((char *) *sizes);
502               pop_trash (server);
503               return (-1);
504             }
505           (*sizes)[i] = atoi (fromserver);
506         }
507       if (pop_multi_next (server, &fromserver))
508         {
509           free ((char *) *IDs);
510           free ((char *) *sizes);
511           return (-1);
512         }
513       else if (fromserver)
514         {
515           strcpy (pop_error,
516                   "Too many response lines from server in pop_list");
517           free ((char *) *IDs);
518           free ((char *) *sizes);
519           return (-1);
520         }
521       (*IDs)[i] = (*sizes)[i] = 0;
522       return (0);
523     }
524 }
525
526 /*
527  * Function: pop_retrieve
528  *
529  * Purpose: Retrieve a specified message from the maildrop.
530  *
531  * Arguments:
532  *      server  The server to retrieve from.
533  *      message The message number to retrieve.
534  *      markfrom
535  *              If true, then mark the string "From " at the beginning
536  *              of lines with '>'.
537  * 
538  * Return value: A string pointing to the message, if successful, or
539  *      null with pop_error set if not.
540  *
541  * Side effects: May kill connection on error.
542  */
543 char *
544 pop_retrieve (popserver server, int message, int markfrom)
545 {
546   int *IDs, *sizes, bufsize, fromcount = 0, cp = 0;
547   char *ptr, *fromserver;
548   int ret;
549
550   if (server->in_multi)
551     {
552       strcpy (pop_error, "In multi-line query in pop_retrieve");
553       return (0);
554     }
555
556   if (pop_list (server, message, &IDs, &sizes))
557     return (0);
558
559   if (pop_retrieve_first (server, message, &fromserver))
560     {
561       return (0);
562     }
563
564   /*
565    * The "5" below is an arbitrary constant -- I assume that if
566    * there are "From" lines in the text to be marked, there
567    * probably won't be more than 5 of them.  If there are, I
568    * allocate more space for them below.
569    */
570   bufsize = sizes[0] + (markfrom ? 5 : 0);
571   ptr = (char *)malloc (bufsize);
572   free ((char *) IDs);
573   free ((char *) sizes);
574
575   if (! ptr)
576     {
577       strcpy (pop_error, "Out of memory in pop_retrieve");
578       pop_retrieve_flush (server);
579       return (0);
580     }
581
582   while (! (ret = pop_retrieve_next (server, &fromserver)))
583     {
584       int linesize;
585
586       if (! fromserver)
587         {
588           ptr[cp] = '\0';
589           return (ptr);
590         }
591       if (markfrom && fromserver[0] == 'F' && fromserver[1] == 'r' &&
592           fromserver[2] == 'o' && fromserver[3] == 'm' &&
593           fromserver[4] == ' ')
594         {
595           if (++fromcount == 5)
596             {
597               bufsize += 5;
598               ptr = (char *)realloc (ptr, bufsize);
599               if (! ptr)
600                 {
601                   strcpy (pop_error, "Out of memory in pop_retrieve");
602                   pop_retrieve_flush (server);
603                   return (0);
604                 }
605               fromcount = 0;
606             }
607           ptr[cp++] = '>';
608         }
609       linesize = strlen (fromserver);
610       memcpy (&ptr[cp], fromserver, linesize);
611       cp += linesize;
612       ptr[cp++] = '\n';
613     }
614
615   if (ret)
616     {
617       free (ptr);
618       /* return (0); */
619     }
620   /* This function used to fall off the end, but that doesn't make any sense */
621   return (0);
622 }     
623
624 int
625 pop_retrieve_first (popserver server, int message, char **response)
626 {
627   sprintf (pop_error, "RETR %d", message);
628   return (pop_multi_first (server, pop_error, response));
629 }
630
631 int
632 pop_retrieve_next (popserver server, char **line)
633 {
634   return (pop_multi_next (server, line));
635 }
636
637 int
638 pop_retrieve_flush (popserver server)
639 {
640   return (pop_multi_flush (server));
641 }
642
643 int
644 pop_top_first (popserver server, int message, int lines, char **response)
645 {
646   sprintf (pop_error, "TOP %d %d", message, lines);
647   return (pop_multi_first (server, pop_error, response));
648 }
649
650 int
651 pop_top_next (popserver server, char **line)
652 {
653   return (pop_multi_next (server, line));
654 }
655
656 int
657 pop_top_flush (popserver server)
658 {
659   return (pop_multi_flush (server));
660 }
661
662 int
663 pop_multi_first (popserver server, char *command, char **response)
664 {
665   if (server->in_multi)
666     {
667       strcpy (pop_error,
668               "Already in multi-line query in pop_multi_first");
669       return (-1);
670     }
671
672   if (sendline (server, command) || (! (*response = pop_getline (server))))
673     {
674       return (-1);
675     }
676
677   if (0 == strncmp (*response, "-ERR", 4))
678     {
679       strncpy (pop_error, *response, ERROR_MAX);
680       return (-1);
681     }
682   else if (0 == strncmp (*response, "+OK", 3))
683     {
684       for (*response += 3; **response == ' '; (*response)++) /* empty */;
685       server->in_multi = 1;
686       return (0);
687     }
688   else
689     {
690       strcpy (pop_error,
691               "Unexpected response from server in pop_multi_first");
692       return (-1);
693     }
694 }
695
696 int
697 pop_multi_next (popserver server, char **line)
698 {
699   char *fromserver;
700
701   if (! server->in_multi)
702     {
703       strcpy (pop_error, "Not in multi-line query in pop_multi_next");
704       return (-1);
705     }
706
707   fromserver = pop_getline (server);
708   if (! fromserver)
709     {
710       return (-1);
711     }
712
713   if (fromserver[0] == '.')
714     {
715       if (! fromserver[1])
716         {
717           *line = 0;
718           server->in_multi = 0;
719           return (0);
720         }
721       else
722         {
723           *line = fromserver + 1;
724           return (0);
725         }
726     }
727   else
728     {
729       *line = fromserver;
730       return (0);
731     }
732 }
733
734 int
735 pop_multi_flush (popserver server)
736 {
737   char *line;
738
739   if (! server->in_multi)
740     {
741       return (0);
742     }
743
744   while (! pop_multi_next (server, &line))
745     {
746       if (! line)
747         {
748           return (0);
749         }
750     }
751
752   return (-1);
753 }
754
755 /* Function: pop_delete
756  *
757  * Purpose: Delete a specified message.
758  *
759  * Arguments:
760  *      server  Server from which to delete the message.
761  *      message Message to delete.
762  *
763  * Return value: 0 on success, non-zero with error in pop_error
764  *      otherwise.
765  */
766 int
767 pop_delete (popserver server, int message)
768 {
769   if (server->in_multi)
770     {
771       strcpy (pop_error, "In multi-line query in pop_delete");
772       return (-1);
773     }
774
775   sprintf (pop_error, "DELE %d", message);
776
777   if (sendline (server, pop_error) || getok (server))
778     return (-1);
779
780   return (0);
781 }
782
783 /*
784  * Function: pop_noop
785  *
786  * Purpose: Send a noop command to the server.
787  *
788  * Argument:
789  *      server  The server to send to.
790  *
791  * Return value: 0 on success, non-zero with error in pop_error
792  *      otherwise.
793  *
794  * Side effects: Closes connection on error.
795  */
796 int
797 pop_noop (popserver server)
798 {
799   if (server->in_multi)
800     {
801       strcpy (pop_error, "In multi-line query in pop_noop");
802       return (-1);
803     }
804
805   if (sendline (server, "NOOP") || getok (server))
806     return (-1);
807
808   return (0);
809 }
810
811 /*
812  * Function: pop_last
813  *
814  * Purpose: Find out the highest seen message from the server.
815  *
816  * Arguments:
817  *      server  The server.
818  *
819  * Return value: If successful, the highest seen message, which is
820  *      greater than or equal to 0.  Otherwise, a negative number with
821  *      the error explained in pop_error.
822  *
823  * Side effects: Closes the connection on error.
824  */
825 int
826 pop_last (popserver server)
827 {
828   char *fromserver;
829      
830   if (server->in_multi)
831     {
832       strcpy (pop_error, "In multi-line query in pop_last");
833       return (-1);
834     }
835
836   if (sendline (server, "LAST"))
837     return (-1);
838
839   if (! (fromserver = pop_getline (server)))
840     return (-1);
841
842   if (! strncmp (fromserver, "-ERR", 4))
843     {
844       strncpy (pop_error, fromserver, ERROR_MAX);
845       return (-1);
846     }
847   else if (strncmp (fromserver, "+OK ", 4))
848     {
849       strcpy (pop_error, "Unexpected response from server in pop_last");
850       pop_trash (server);
851       return (-1);
852     }
853   else
854     {
855       return (atoi (&fromserver[4]));
856     }
857 }
858
859 /*
860  * Function: pop_reset
861  *
862  * Purpose: Reset the server to its initial connect state
863  *
864  * Arguments:
865  *      server  The server.
866  *
867  * Return value: 0 for success, non-0 with error in pop_error
868  *      otherwise.
869  *
870  * Side effects: Closes the connection on error.
871  */
872 int
873 pop_reset (popserver server)
874 {
875   if (pop_retrieve_flush (server))
876     {
877       return (-1);
878     }
879
880   if (sendline (server, "RSET") || getok (server))
881     return (-1);
882
883   return (0);
884 }
885
886 /*
887  * Function: pop_quit
888  *
889  * Purpose: Quit the connection to the server,
890  *
891  * Arguments:
892  *      server  The server to quit.
893  *
894  * Return value: 0 for success, non-zero otherwise with error in
895  *      pop_error.
896  *
897  * Side Effects: The popserver passed in is unusable after this
898  *      function is called, even if an error occurs.
899  */
900 int
901 pop_quit (popserver server)
902 {
903   int ret = 0;
904
905   if (server->file >= 0)
906     {
907       if (pop_retrieve_flush (server))
908         {
909           ret = -1;
910         }
911
912       if (sendline (server, "QUIT") || getok (server))
913         {
914           ret = -1;
915         }
916
917       close (server->file);
918     }
919
920   if (server->buffer)
921     free (server->buffer);
922   free ((char *) server);
923
924   return (ret);
925 }
926
927 #ifdef WINDOWSNT
928 static int have_winsock = 0;
929 #endif
930
931 /*
932  * Function: socket_connection
933  *
934  * Purpose: Opens the network connection with the mail host, without
935  *      doing any sort of I/O with it or anything.
936  *
937  * Arguments:
938  *      host    The host to which to connect.
939  *      flags   Option flags.
940  *      
941  * Return value: A file descriptor indicating the connection, or -1
942  *      indicating failure, in which case an error has been copied
943  *      into pop_error.
944  */
945 static int
946 socket_connection (char *host, int flags)
947 {
948   struct hostent *hostent;
949   struct servent *servent;
950   struct sockaddr_in addr;
951   char found_port = 0;
952   char *service;
953   int sock;
954 #ifdef KERBEROS
955 #ifdef KRB5
956   krb5_error_code rem;
957   krb5_ccache ccdef;
958   krb5_principal client, server;
959   krb5_error *err_ret;
960   register char *cp;
961 #else
962   KTEXT ticket;
963   MSG_DAT msg_data;
964   CREDENTIALS cred;
965   Key_schedule schedule;
966   int rem;
967 #endif /* KRB5 */
968 #endif /* KERBEROS */
969
970   int try_count = 0;
971
972 #ifdef WINDOWSNT
973   {
974     WSADATA winsockData;
975     if (WSAStartup (0x101, &winsockData) == 0)
976       have_winsock = 1;
977   }
978 #endif
979
980   do
981     {
982       hostent = gethostbyname (host);
983       try_count++;
984       if ((! hostent) 
985 #ifndef BROKEN_CYGWIN     
986           && ((h_errno != TRY_AGAIN) || (try_count == 5))
987 #endif
988           )
989         {
990           strcpy (pop_error, "Could not determine POP server's address");
991           return (-1);
992         }
993     } while (! hostent);
994
995   memset (&addr, 0, sizeof (addr));
996   addr.sin_family = AF_INET;
997
998 #ifdef KERBEROS
999   service = (flags & POP_NO_KERBEROS) ? POP_SERVICE : KPOP_SERVICE;
1000 #else
1001   service = POP_SERVICE;
1002 #endif
1003
1004 #ifdef HESIOD
1005   if (! (flags & POP_NO_HESIOD))
1006     {
1007       servent = hes_getservbyname (service, "tcp");
1008       if (servent)
1009         {
1010           addr.sin_port = servent->s_port;
1011           found_port = 1;
1012         }
1013     }
1014 #endif
1015   if (! found_port)
1016     {
1017       servent = getservbyname (service, "tcp");
1018       if (servent)
1019         {
1020           addr.sin_port = servent->s_port;
1021         }
1022       else
1023         {
1024 #ifdef KERBEROS
1025           addr.sin_port = htons ((flags & POP_NO_KERBEROS) ?
1026                                 POP_PORT : KPOP_PORT);
1027 #else
1028           addr.sin_port = htons (POP_PORT);
1029 #endif
1030         }
1031     }
1032
1033 #define SOCKET_ERROR "Could not create socket for POP connection: "
1034
1035   sock = socket (PF_INET, SOCK_STREAM, 0);
1036   if (sock < 0)
1037     {
1038       strcpy (pop_error, SOCKET_ERROR);
1039       strncat (pop_error, strerror (errno),
1040                ERROR_MAX - sizeof (SOCKET_ERROR));
1041       return (-1);
1042           
1043     }
1044
1045   while (*hostent->h_addr_list)
1046     {
1047       memcpy (&addr.sin_addr, *hostent->h_addr_list, hostent->h_length);
1048       if (! connect (sock, (struct sockaddr *) &addr, sizeof (addr)))
1049         break;
1050       hostent->h_addr_list++;
1051     }
1052
1053 #define CONNECT_ERROR "Could not connect to POP server: "
1054      
1055   if (! *hostent->h_addr_list)
1056     {
1057       CLOSESOCKET (sock);
1058       strcpy (pop_error, CONNECT_ERROR);
1059       strncat (pop_error, strerror (errno),
1060                ERROR_MAX - sizeof (CONNECT_ERROR));
1061       return (-1);
1062           
1063     }
1064
1065 #ifdef KERBEROS
1066 #define KRB_ERROR "Kerberos error connecting to POP server: "
1067   if (! (flags & POP_NO_KERBEROS))
1068     {
1069 #ifdef KRB5
1070       krb5_init_ets ();
1071
1072       if (rem = krb5_cc_default (&ccdef))
1073         {
1074         krb5error:
1075           strcpy (pop_error, KRB_ERROR);
1076           strncat (pop_error, error_message (rem),
1077                    ERROR_MAX - sizeof(KRB_ERROR));
1078           CLOSESOCKET (sock);
1079           return (-1);
1080         }
1081
1082       if (rem = krb5_cc_get_principal (ccdef, &client))
1083         {
1084           goto krb5error;
1085         }
1086
1087       for (cp = hostent->h_name; *cp; cp++)
1088         {
1089           if (isupper (*cp))
1090             {
1091               *cp = tolower (*cp);
1092             }
1093         }
1094
1095       if (rem = krb5_sname_to_principal (hostent->h_name, POP_SERVICE,
1096                                          FALSE, &server))
1097         {
1098           goto krb5error;
1099         }
1100
1101       rem = krb5_sendauth ((krb5_pointer) &sock, "KPOPV1.0", client, server,
1102                           AP_OPTS_MUTUAL_REQUIRED,
1103                           0,    /* no checksum */
1104                           0,    /* no creds, use ccache instead */
1105                           ccdef,
1106                           0,    /* don't need seq # */
1107                           0,    /* don't need subsession key */
1108                           &err_ret,
1109                           0);   /* don't need reply */
1110       krb5_free_principal (server);
1111       if (rem)
1112         {
1113           if (err_ret && err_ret->text.length)
1114             {
1115               strcpy (pop_error, KRB_ERROR);
1116               strncat (pop_error, error_message (rem),
1117                        ERROR_MAX - sizeof (KRB_ERROR));
1118               strncat (pop_error, " [server says '",
1119                        ERROR_MAX - strlen (pop_error) - 1);
1120               strncat (pop_error, err_ret->text.data,
1121                        min (ERROR_MAX - strlen (pop_error) - 1,
1122                             err_ret->text.length));
1123               strncat (pop_error, "']",
1124                        ERROR_MAX - strlen (pop_error) - 1);
1125             }
1126           else
1127             {
1128               strcpy (pop_error, KRB_ERROR);
1129               strncat (pop_error, error_message (rem),
1130                        ERROR_MAX - sizeof (KRB_ERROR));
1131             }
1132           if (err_ret)
1133             krb5_free_error (err_ret);
1134
1135           CLOSESOCKET (sock);
1136           return (-1);
1137         }
1138 #else  /* ! KRB5 */       
1139       ticket = (KTEXT) malloc (sizeof (KTEXT_ST));
1140       rem = krb_sendauth (0L, sock, ticket, "pop", hostent->h_name,
1141                           (char *) krb_realmofhost (hostent->h_name),
1142                           (unsigned long) 0, &msg_data, &cred, schedule,
1143                           (struct sockaddr_in *) 0,
1144                           (struct sockaddr_in *) 0,
1145                           "KPOPV0.1");
1146       free ((char *) ticket);
1147       if (rem != KSUCCESS)
1148         {
1149           strcpy (pop_error, KRB_ERROR);
1150           strncat (pop_error, krb_err_txt[rem],
1151                    ERROR_MAX - sizeof (KRB_ERROR));
1152           CLOSESOCKET (sock);
1153           return (-1);
1154         }
1155 #endif /* KRB5 */
1156     }
1157 #endif /* KERBEROS */
1158
1159   return (sock);
1160 } /* socket_connection */
1161
1162 /*
1163  * Function: pop_getline
1164  *
1165  * Purpose: Get a line of text from the connection and return a
1166  *      pointer to it.  The carriage return and linefeed at the end of
1167  *      the line are stripped, but periods at the beginnings of lines
1168  *      are NOT dealt with in any special way.
1169  *
1170  * Arguments:
1171  *      server  The server from which to get the line of text.
1172  *
1173  * Returns: A non-null pointer if successful, or a null pointer on any
1174  *      error, with an error message copied into pop_error.
1175  *
1176  * Notes: The line returned is overwritten with each call to pop_getline.
1177  *
1178  * Side effects: Closes the connection on error.
1179  */
1180 static char *
1181 pop_getline (popserver server)
1182 {
1183 #define GETLINE_ERROR "Error reading from server: "
1184
1185   int ret;
1186   int search_offset = 0;
1187
1188   if (server->data)
1189     {
1190       char *cp = find_crlf (server->buffer + server->buffer_index);
1191       if (cp)
1192         {
1193           int found;
1194           int data_used;
1195
1196           found = server->buffer_index;
1197           data_used = (cp + 2) - server->buffer - found;
1198                
1199           *cp = '\0';           /* terminate the string to be returned */
1200           server->data -= data_used;
1201           server->buffer_index += data_used;
1202
1203           if (pop_debug)
1204             fprintf (stderr, "<<< %s\n", server->buffer + found);
1205           return (server->buffer + found);
1206         }
1207       else
1208         {
1209           memcpy (server->buffer,
1210                   server->buffer + server->buffer_index,
1211                   server->data);
1212           /* Record the fact that we've searched the data already in
1213              the buffer for a CRLF, so that when we search below, we
1214              don't have to search the same data twice.  There's a "-
1215              1" here to account for the fact that the last character
1216              of the data we have may be the CR of a CRLF pair, of
1217              which we haven't read the second half yet, so we may have
1218              to search it again when we read more data. */
1219           search_offset = server->data - 1;
1220           server->buffer_index = 0;
1221         }
1222     }
1223   else
1224     {
1225       server->buffer_index = 0;
1226     }
1227
1228   while (1)
1229     {
1230       /* There's a "- 1" here to leave room for the null that we put
1231          at the end of the read data below.  We put the null there so
1232          that find_crlf knows where to stop when we call it. */
1233       if (server->data == server->buffer_size - 1)
1234         {
1235           server->buffer_size += GETLINE_INCR;
1236           server->buffer = (char *)realloc (server->buffer, server->buffer_size);
1237           if (! server->buffer)
1238             {
1239               strcpy (pop_error, "Out of memory in pop_getline");
1240               pop_trash (server);
1241               return (0);
1242             }
1243         }
1244       ret = RECV (server->file, server->buffer + server->data,
1245                   server->buffer_size - server->data - 1, 0);
1246       if (ret < 0)
1247         {
1248           strcpy (pop_error, GETLINE_ERROR);
1249           strncat (pop_error, strerror (errno),
1250                    ERROR_MAX - sizeof (GETLINE_ERROR));
1251           pop_trash (server);
1252           return (0);
1253         }
1254       else if (ret == 0)
1255         {
1256           strcpy (pop_error, "Unexpected EOF from server in pop_getline");
1257           pop_trash (server);
1258           return (0);
1259         }
1260       else
1261         {
1262           char *cp;
1263           server->data += ret;
1264           server->buffer[server->data] = '\0';
1265                
1266           cp = find_crlf (server->buffer + search_offset);
1267           if (cp)
1268             {
1269               int data_used = (cp + 2) - server->buffer;
1270               *cp = '\0';
1271               server->data -= data_used;
1272               server->buffer_index = data_used;
1273
1274               if (pop_debug)
1275                 fprintf (stderr, "<<< %s\n", server->buffer);
1276               return (server->buffer);
1277             }
1278           search_offset += ret;
1279         }
1280     }
1281
1282   /* NOTREACHED */
1283 }
1284
1285 /*
1286  * Function: sendline
1287  *
1288  * Purpose: Sends a line of text to the POP server.  The line of text
1289  *      passed into this function should NOT have the carriage return
1290  *      and linefeed on the end of it.  Periods at beginnings of lines
1291  *      will NOT be treated specially by this function.
1292  *
1293  * Arguments:
1294  *      server  The server to which to send the text.
1295  *      line    The line of text to send.
1296  *
1297  * Return value: Upon successful completion, a value of 0 will be
1298  *      returned.  Otherwise, a non-zero value will be returned, and
1299  *      an error will be copied into pop_error.
1300  *
1301  * Side effects: Closes the connection on error.
1302  */
1303 static int
1304 sendline (popserver server, char *line)
1305 {
1306 #define SENDLINE_ERROR "Error writing to POP server: "
1307   int ret;
1308
1309   ret = fullwrite (server->file, line, strlen (line));
1310   if (ret >= 0)
1311     {                           /* 0 indicates that a blank line was written */
1312       ret = fullwrite (server->file, "\r\n", 2);
1313     }
1314
1315   if (ret < 0)
1316     {
1317       pop_trash (server);
1318       strcpy (pop_error, SENDLINE_ERROR);
1319       strncat (pop_error, strerror (errno),
1320                ERROR_MAX - sizeof (SENDLINE_ERROR));
1321       return (ret);
1322     }
1323
1324   if (pop_debug)
1325     fprintf (stderr, ">>> %s\n", line);
1326
1327   return (0);
1328 }
1329
1330 /*
1331  * Procedure: fullwrite
1332  *
1333  * Purpose: Just like write, but keeps trying until the entire string
1334  *      has been written.
1335  *
1336  * Return value: Same as write.  Pop_error is not set.
1337  */
1338 static int
1339 fullwrite (int fd, char *buf, int nbytes)
1340 {
1341   char *cp;
1342   int ret;
1343
1344   cp = buf;
1345   while ((ret = SEND (fd, cp, nbytes, 0)) > 0)
1346     {
1347       cp += ret;
1348       nbytes -= ret;
1349     }
1350
1351   return (ret);
1352 }
1353
1354 /*
1355  * Procedure getok
1356  *
1357  * Purpose: Reads a line from the server.  If the return indicator is
1358  *      positive, return with a zero exit status.  If not, return with
1359  *      a negative exit status.
1360  *
1361  * Arguments:
1362  *      server  The server to read from.
1363  * 
1364  * Returns: 0 for success, else for failure and puts error in pop_error.
1365  *
1366  * Side effects: On failure, may make the connection unusable.
1367  */
1368 static int
1369 getok (popserver server)
1370 {
1371   char *fromline;
1372
1373   if (! (fromline = pop_getline (server)))
1374     {
1375       return (-1);
1376     }
1377
1378   if (! strncmp (fromline, "+OK", 3))
1379     return (0);
1380   else if (! strncmp (fromline, "-ERR", 4))
1381     {
1382       strncpy (pop_error, fromline, ERROR_MAX);
1383       pop_error[ERROR_MAX-1] = '\0';
1384       return (-1);
1385     }
1386   else
1387     {
1388       strcpy (pop_error,
1389               "Unexpected response from server; expecting +OK or -ERR");
1390       pop_trash (server);
1391       return (-1);
1392     }
1393 }         
1394
1395 #if 0
1396 /*
1397  * Function: gettermination
1398  *
1399  * Purpose: Gets the next line and verifies that it is a termination
1400  *      line (nothing but a dot).
1401  *
1402  * Return value: 0 on success, non-zero with pop_error set on error.
1403  *
1404  * Side effects: Closes the connection on error.
1405  */
1406 static int
1407 gettermination (popserver server)
1408 {
1409   char *fromserver;
1410
1411   fromserver = pop_getline (server);
1412   if (! fromserver)
1413     return (-1);
1414
1415   if (strcmp (fromserver, "."))
1416     {
1417       strcpy (pop_error,
1418               "Unexpected response from server in gettermination");
1419       pop_trash (server);
1420       return (-1);
1421     }
1422
1423   return (0);
1424 }
1425 #endif
1426
1427 /*
1428  * Function pop_close
1429  *
1430  * Purpose: Close a pop connection, sending a "RSET" command to try to
1431  *      preserve any changes that were made and a "QUIT" command to
1432  *      try to get the server to quit, but ignoring any responses that
1433  *      are received.
1434  *
1435  * Side effects: The server is unusable after this function returns.
1436  *      Changes made to the maildrop since the session was started (or
1437  *      since the last pop_reset) may be lost.
1438  */
1439 void 
1440 pop_close (popserver server)
1441 {
1442   pop_trash (server);
1443   free ((char *) server);
1444
1445   return;
1446 }
1447
1448 /*
1449  * Function: pop_trash
1450  *
1451  * Purpose: Like pop_close or pop_quit, but doesn't deallocate the
1452  *      memory associated with the server.  It is legal to call
1453  *      pop_close or pop_quit after this function has been called.
1454  */
1455 static void
1456 pop_trash (popserver server)
1457 {
1458   if (server->file >= 0)
1459     {
1460       /* avoid recursion; sendline can call pop_trash */
1461       if (server->trash_started)
1462         return;
1463       server->trash_started = 1;
1464
1465       sendline (server, "RSET");
1466       sendline (server, "QUIT");
1467
1468       CLOSESOCKET (server->file);
1469       server->file = -1;
1470       if (server->buffer)
1471         {
1472           free (server->buffer);
1473           server->buffer = 0;
1474         }
1475     }
1476
1477 #ifdef WINDOWSNT
1478   if (have_winsock)
1479     WSACleanup ();
1480 #endif
1481 }
1482
1483 /* Return a pointer to the first CRLF in IN_STRING,
1484    or 0 if it does not contain one.  */
1485
1486 static char *
1487 find_crlf (char *in_string)
1488 {
1489   while (1)
1490     {
1491       if (! *in_string)
1492         return (0);
1493       else if (*in_string == '\r')
1494         {
1495           if (*++in_string == '\n')
1496             return (in_string - 1);
1497         }
1498       else
1499         in_string++;
1500     }
1501   /* NOTREACHED */
1502 }
1503
1504 #endif /* MAIL_USE_POP */