xref: /freebsd/crypto/heimdal/appl/push/push.c (revision 82431678fce5c893ef9c7418ad6d998ad4187de6)
1 /*
2  * Copyright (c) 1997-2004 Kungliga Tekniska H�gskolan
3  * (Royal Institute of Technology, Stockholm, Sweden).
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * 3. Neither the name of the Institute nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #include "push_locl.h"
35 RCSID("$Id: push.c 14850 2005-04-19 18:00:17Z lha $");
36 
37 #ifdef KRB4
38 static int use_v4 = -1;
39 #endif
40 
41 #ifdef KRB5
42 static int use_v5 = -1;
43 static krb5_context context;
44 #endif
45 
46 static char *port_str;
47 static int verbose_level;
48 static int do_fork;
49 static int do_leave;
50 static int do_version;
51 static int do_help;
52 static int do_from;
53 static int do_count;
54 static char *header_str;
55 
56 struct getargs args[] = {
57 #ifdef KRB4
58     { "krb4",	'4', arg_flag,		&use_v4,	"Use Kerberos V4",
59       NULL },
60 #endif
61 #ifdef KRB5
62     { "krb5",	'5', arg_flag,		&use_v5,	"Use Kerberos V5",
63       NULL },
64 #endif
65     { "verbose",'v', arg_counter,	&verbose_level,	"Verbose",
66       NULL },
67     { "fork",	'f', arg_flag,		&do_fork,	"Fork deleting proc",
68       NULL },
69     { "leave",	'l', arg_flag,		&do_leave,	"Leave mail on server",
70       NULL },
71     { "port",	'p', arg_string,	&port_str,	"Use this port",
72       "number-or-service" },
73     { "from",	 0,  arg_flag,		&do_from,	"Behave like from",
74       NULL },
75     { "headers", 0,  arg_string,	&header_str,	"Headers to print", NULL },
76     { "count", 'c',  arg_flag,		&do_count,	"Print number of messages", NULL},
77     { "version", 0,  arg_flag,		&do_version,	"Print version",
78       NULL },
79     { "help",	 0,  arg_flag,		&do_help,	NULL,
80       NULL }
81 
82 };
83 
84 static void
85 usage (int ret)
86 {
87     arg_printusage (args,
88 		    sizeof(args) / sizeof(args[0]),
89 		    NULL,
90 		    "[[{po:username[@hostname] | hostname[:username]}] ...] "
91 		    "filename");
92     exit (ret);
93 }
94 
95 static int
96 do_connect (const char *hostname, int port, int nodelay)
97 {
98     struct addrinfo *ai, *a;
99     struct addrinfo hints;
100     int error;
101     int s = -1;
102     char portstr[NI_MAXSERV];
103 
104     memset (&hints, 0, sizeof(hints));
105     hints.ai_socktype = SOCK_STREAM;
106     hints.ai_protocol = IPPROTO_TCP;
107 
108     snprintf (portstr, sizeof(portstr), "%u", ntohs(port));
109 
110     error = getaddrinfo (hostname, portstr, &hints, &ai);
111     if (error)
112 	errx (1, "getaddrinfo(%s): %s", hostname, gai_strerror(error));
113 
114     for (a = ai; a != NULL; a = a->ai_next) {
115 	s = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
116 	if (s < 0)
117 	    continue;
118 	if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
119 	    warn ("connect(%s)", hostname);
120  	    close (s);
121  	    continue;
122 	}
123 	break;
124     }
125     freeaddrinfo (ai);
126     if (a == NULL) {
127 	warnx ("failed to contact %s", hostname);
128 	return -1;
129     }
130 
131     if(setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
132 		  (void *)&nodelay, sizeof(nodelay)) < 0)
133 	err (1, "setsockopt TCP_NODELAY");
134     return s;
135 }
136 
137 typedef enum { INIT = 0, GREET, USER, PASS, STAT, RETR, TOP,
138 	       DELE, XDELE, QUIT} pop_state;
139 
140 static char *pop_state_string[] = {
141     "INIT", "GREET", "USER", "PASS", "STAT", "RETR", "TOP",
142     "DELE", "XDELE", "QUIT"
143 };
144 
145 #define PUSH_BUFSIZ 65536
146 
147 #define STEP 16
148 
149 struct write_state {
150     struct iovec *iovecs;
151     size_t niovecs, maxiovecs, allociovecs;
152     int fd;
153 };
154 
155 static void
156 write_state_init (struct write_state *w, int fd)
157 {
158 #ifdef UIO_MAXIOV
159     w->maxiovecs = UIO_MAXIOV;
160 #else
161     w->maxiovecs = 16;
162 #endif
163     w->allociovecs = min(STEP, w->maxiovecs);
164     w->niovecs = 0;
165     w->iovecs = emalloc(w->allociovecs * sizeof(*w->iovecs));
166     w->fd = fd;
167 }
168 
169 static void
170 write_state_add (struct write_state *w, void *v, size_t len)
171 {
172     if(w->niovecs == w->allociovecs) {
173 	if(w->niovecs == w->maxiovecs) {
174 	    if(writev (w->fd, w->iovecs, w->niovecs) < 0)
175 		err(1, "writev");
176 	    w->niovecs = 0;
177 	} else {
178 	    w->allociovecs = min(w->allociovecs + STEP, w->maxiovecs);
179 	    w->iovecs = erealloc (w->iovecs,
180 				  w->allociovecs * sizeof(*w->iovecs));
181 	}
182     }
183     w->iovecs[w->niovecs].iov_base = v;
184     w->iovecs[w->niovecs].iov_len  = len;
185     ++w->niovecs;
186 }
187 
188 static void
189 write_state_flush (struct write_state *w)
190 {
191     if (w->niovecs) {
192 	if (writev (w->fd, w->iovecs, w->niovecs) < 0)
193 	    err (1, "writev");
194 	w->niovecs = 0;
195     }
196 }
197 
198 static void
199 write_state_destroy (struct write_state *w)
200 {
201     free (w->iovecs);
202 }
203 
204 static int
205 doit(int s,
206      const char *host,
207      const char *user,
208      const char *outfilename,
209      const char *header_str,
210      int leavep,
211      int verbose,
212      int forkp)
213 {
214     int ret;
215     char out_buf[PUSH_BUFSIZ];
216     int out_len = 0;
217     char *in_buf;
218     size_t in_buf_size;
219     size_t in_len = 0;
220     char *in_ptr;
221     pop_state state = INIT;
222     unsigned count, bytes;
223     unsigned asked_for = 0, retrieved = 0, asked_deleted = 0, deleted = 0;
224     unsigned sent_xdele = 0;
225     int out_fd;
226     char from_line[128];
227     size_t from_line_length;
228     time_t now;
229     struct write_state write_state;
230     int numheaders = 1;
231     char **headers = NULL;
232     int i;
233     char *tmp = NULL;
234 
235     in_buf = emalloc(PUSH_BUFSIZ + 1);
236     in_ptr = in_buf;
237     in_buf_size = PUSH_BUFSIZ;
238 
239     if (do_from) {
240 	char *tmp2;
241 
242 	tmp2 = tmp = estrdup(header_str);
243 
244 	out_fd = -1;
245 	if (verbose)
246 	    fprintf (stderr, "%s@%s\n", user, host);
247 	while (*tmp != '\0') {
248 	    tmp = strchr(tmp, ',');
249 	    if (tmp == NULL)
250 		break;
251 	    tmp++;
252 	    numheaders++;
253 	}
254 
255 	headers = emalloc(sizeof(char *) * (numheaders + 1));
256 	for (i = 0; i < numheaders; i++) {
257 	    headers[i] = strtok_r(tmp2, ",", &tmp2);
258 	}
259 	headers[numheaders] = NULL;
260     } else {
261 	out_fd = open(outfilename, O_WRONLY | O_APPEND | O_CREAT, 0666);
262 	if (out_fd < 0)
263 	    err (1, "open %s", outfilename);
264 	if (verbose)
265 	    fprintf (stderr, "%s@%s -> %s\n", user, host, outfilename);
266     }
267 
268     now = time(NULL);
269     from_line_length = snprintf (from_line, sizeof(from_line),
270 				 "From %s %s", "push", ctime(&now));
271     if (from_line_length < 0 || from_line_length > sizeof(from_line))
272 	errx (1, "snprintf failed");
273 
274     out_len = snprintf (out_buf, sizeof(out_buf),
275 			"USER %s\r\nPASS hej\r\nSTAT\r\n",
276 			user);
277     if (out_len < 0 || out_len > sizeof(out_buf))
278 	errx (1, "snprintf failed");
279     if (net_write (s, out_buf, out_len) != out_len)
280 	err (1, "write");
281     if (verbose > 1)
282 	fprintf (stderr, "%s", out_buf);
283 
284     if (!do_from)
285 	write_state_init (&write_state, out_fd);
286 
287     while(state != QUIT) {
288 	fd_set readset, writeset;
289 
290 	FD_ZERO(&readset);
291 	FD_ZERO(&writeset);
292 	if (s >= FD_SETSIZE)
293 	    errx (1, "fd too large");
294 	FD_SET(s,&readset);
295 
296 	if (verbose > 1)
297 	    fprintf (stderr, "state: %s count: %d asked_for: %d "
298 		     "retrieved: %d asked_deleted: %d\n",
299 		     pop_state_string[state],
300 		     count, asked_for, retrieved, asked_deleted);
301 
302 	if (((state == STAT || state == RETR || state == TOP)
303 	     && asked_for < count)
304 	    || (state == XDELE && !sent_xdele)
305 	    || (state == DELE && asked_deleted < count))
306 	    FD_SET(s,&writeset);
307 	ret = select (s + 1, &readset, &writeset, NULL, NULL);
308 	if (ret < 0) {
309 	    if (errno == EAGAIN)
310 		continue;
311 	    else
312 		err (1, "select");
313 	}
314 
315 	if (FD_ISSET(s, &readset)) {
316 	    char *beg, *p;
317 	    size_t rem;
318 	    int blank_line = 0;
319 
320 	    if(in_len >= in_buf_size) {
321 		char *tmp = erealloc(in_buf, in_buf_size + PUSH_BUFSIZ + 1);
322 		in_ptr = tmp + (in_ptr - in_buf);
323 		in_buf = tmp;
324 		in_buf_size += PUSH_BUFSIZ;
325 	    }
326 
327 	    ret = read (s, in_ptr, in_buf_size - in_len);
328 	    if (ret < 0)
329 		err (1, "read");
330 	    else if (ret == 0)
331 		errx (1, "EOF during read");
332 
333 	    in_len += ret;
334 	    in_ptr += ret;
335 	    *in_ptr = '\0';
336 
337 	    beg = in_buf;
338 	    rem = in_len;
339 	    while(rem > 1
340 		  && (p = strstr(beg, "\r\n")) != NULL) {
341 		if (state == TOP) {
342 		    char *copy = beg;
343 
344 		    for (i = 0; i < numheaders; i++) {
345 			size_t len;
346 
347 			len = min(p - copy + 1, strlen(headers[i]));
348 			if (strncasecmp(copy, headers[i], len) == 0) {
349 			    fprintf (stdout, "%.*s\n", (int)(p - copy), copy);
350 			}
351 		    }
352 		    if (beg[0] == '.' && beg[1] == '\r' && beg[2] == '\n') {
353 			if (numheaders > 1)
354 			    fprintf (stdout, "\n");
355 			state = STAT;
356 			if (++retrieved == count) {
357 			    state = QUIT;
358 			    net_write (s, "QUIT\r\n", 6);
359 			    if (verbose > 1)
360 				fprintf (stderr, "QUIT\r\n");
361 			}
362 		    }
363 		    rem -= p - beg + 2;
364 		    beg = p + 2;
365 		} else if (state == RETR) {
366 		    char *copy = beg;
367 		    if (beg[0] == '.') {
368 			if (beg[1] == '\r' && beg[2] == '\n') {
369 			    if(!blank_line)
370 				write_state_add(&write_state, "\n", 1);
371 			    state = STAT;
372 			    rem -= p - beg + 2;
373 			    beg = p + 2;
374 			    if (++retrieved == count) {
375 				write_state_flush (&write_state);
376 				if (fsync (out_fd) < 0)
377 				    err (1, "fsync");
378 				close(out_fd);
379 				if (leavep) {
380 				    state = QUIT;
381 				    net_write (s, "QUIT\r\n", 6);
382 				    if (verbose > 1)
383 					fprintf (stderr, "QUIT\r\n");
384 				} else {
385 				    if (forkp) {
386 					pid_t pid;
387 
388 					pid = fork();
389 					if (pid < 0)
390 					    warn ("fork");
391 					else if(pid != 0) {
392 					    if(verbose)
393 						fprintf (stderr,
394 							 "(exiting)");
395 					    return 0;
396 					}
397 				    }
398 
399 				    state = XDELE;
400 				    if (verbose)
401 					fprintf (stderr, "deleting... ");
402 				}
403 			    }
404 			    continue;
405 			} else
406 			    ++copy;
407 		    }
408 		    *p = '\n';
409 		    if(blank_line &&
410 		       strncmp(copy, "From ", min(p - copy + 1, 5)) == 0)
411 			write_state_add(&write_state, ">", 1);
412 		    write_state_add(&write_state, copy, p - copy + 1);
413 		    blank_line = (*copy == '\n');
414 		    rem -= p - beg + 2;
415 		    beg = p + 2;
416 		} else if (rem >= 3 && strncmp (beg, "+OK", 3) == 0) {
417 		    if (state == STAT) {
418 			if (!do_from)
419 			    write_state_add(&write_state,
420 					    from_line, from_line_length);
421 			blank_line = 0;
422 			if (do_from)
423 			    state = TOP;
424 			else
425 			    state = RETR;
426 		    } else if (state == XDELE) {
427 			state = QUIT;
428 			net_write (s, "QUIT\r\n", 6);
429 			if (verbose > 1)
430 			    fprintf (stderr, "QUIT\r\n");
431 			break;
432 		    } else if (state == DELE) {
433 			if (++deleted == count) {
434 			    state = QUIT;
435 			    net_write (s, "QUIT\r\n", 6);
436 			    if (verbose > 1)
437 				fprintf (stderr, "QUIT\r\n");
438 			    break;
439 			}
440 		    } else if (++state == STAT) {
441 			if(sscanf (beg + 4, "%u %u", &count, &bytes) != 2)
442 			    errx(1, "Bad STAT-line: %.*s", (int)(p - beg), beg);
443 			if (verbose) {
444 			    fprintf (stderr, "%u message(s) (%u bytes). "
445 				     "fetching... ",
446 				     count, bytes);
447 			    if (do_from)
448 				fprintf (stderr, "\n");
449 			} else if (do_count) {
450 			    fprintf (stderr, "%u message(s) (%u bytes).\n",
451 				     count, bytes);
452 			}
453 			if (count == 0) {
454 			    state = QUIT;
455 			    net_write (s, "QUIT\r\n", 6);
456 			    if (verbose > 1)
457 				fprintf (stderr, "QUIT\r\n");
458 			    break;
459 			}
460 		    }
461 
462 		    rem -= p - beg + 2;
463 		    beg = p + 2;
464 		} else {
465 		    if(state == XDELE) {
466 			state = DELE;
467 			rem -= p - beg + 2;
468 			beg = p + 2;
469 		    } else
470 			errx (1, "Bad response: %.*s", (int)(p - beg), beg);
471 		}
472 	    }
473 	    if (!do_from)
474 		write_state_flush (&write_state);
475 
476 	    memmove (in_buf, beg, rem);
477 	    in_len = rem;
478 	    in_ptr = in_buf + rem;
479 	}
480 	if (FD_ISSET(s, &writeset)) {
481 	    if ((state == STAT && !do_from) || state == RETR)
482 		out_len = snprintf (out_buf, sizeof(out_buf),
483 				    "RETR %u\r\n", ++asked_for);
484 	    else if ((state == STAT && do_from) || state == TOP)
485 		out_len = snprintf (out_buf, sizeof(out_buf),
486 				    "TOP %u 0\r\n", ++asked_for);
487 	    else if(state == XDELE) {
488 		out_len = snprintf(out_buf, sizeof(out_buf),
489 				   "XDELE %u %u\r\n", 1, count);
490 		sent_xdele++;
491 	    }
492 	    else if(state == DELE)
493 		out_len = snprintf (out_buf, sizeof(out_buf),
494 				    "DELE %u\r\n", ++asked_deleted);
495 	    if (out_len < 0 || out_len > sizeof(out_buf))
496 		errx (1, "snprintf failed");
497 	    if (net_write (s, out_buf, out_len) != out_len)
498 		err (1, "write");
499 	    if (verbose > 1)
500 		fprintf (stderr, "%s", out_buf);
501 	}
502     }
503     if (verbose)
504 	fprintf (stderr, "Done\n");
505     if (do_from) {
506 	free (tmp);
507 	free (headers);
508     } else {
509 	write_state_destroy (&write_state);
510     }
511     return 0;
512 }
513 
514 #ifdef KRB5
515 static int
516 do_v5 (const char *host,
517        int port,
518        const char *user,
519        const char *filename,
520        const char *header_str,
521        int leavep,
522        int verbose,
523        int forkp)
524 {
525     krb5_error_code ret;
526     krb5_auth_context auth_context = NULL;
527     krb5_principal server;
528     int s;
529 
530     s = do_connect (host, port, 1);
531     if (s < 0)
532 	return 1;
533 
534     ret = krb5_sname_to_principal (context,
535 				   host,
536 				   "pop",
537 				   KRB5_NT_SRV_HST,
538 				   &server);
539     if (ret) {
540 	warnx ("krb5_sname_to_principal: %s",
541 	       krb5_get_err_text (context, ret));
542 	return 1;
543     }
544 
545     ret = krb5_sendauth (context,
546 			 &auth_context,
547 			 &s,
548 			 "KPOPV1.0",
549 			 NULL,
550 			 server,
551 			 0,
552 			 NULL,
553 			 NULL,
554 			 NULL,
555 			 NULL,
556 			 NULL,
557 			 NULL);
558     krb5_free_principal (context, server);
559     if (ret) {
560 	warnx ("krb5_sendauth: %s",
561 	       krb5_get_err_text (context, ret));
562 	return 1;
563     }
564     return doit (s, host, user, filename, header_str, leavep, verbose, forkp);
565 }
566 #endif
567 
568 #ifdef KRB4
569 static int
570 do_v4 (const char *host,
571        int port,
572        const char *user,
573        const char *filename,
574        const char *header_str,
575        int leavep,
576        int verbose,
577        int forkp)
578 {
579     KTEXT_ST ticket;
580     MSG_DAT msg_data;
581     CREDENTIALS cred;
582     des_key_schedule sched;
583     int s;
584     int ret;
585 
586     s = do_connect (host, port, 1);
587     if (s < 0)
588 	return 1;
589     ret = krb_sendauth(0,
590 		       s,
591 		       &ticket,
592 		       "pop",
593 		       (char *)host,
594 		       krb_realmofhost(host),
595 		       getpid(),
596 		       &msg_data,
597 		       &cred,
598 		       sched,
599 		       NULL,
600 		       NULL,
601 		       "KPOPV0.1");
602     if(ret) {
603 	warnx("krb_sendauth: %s", krb_get_err_text(ret));
604 	return 1;
605     }
606     return doit (s, host, user, filename, header_str, leavep, verbose, forkp);
607 }
608 #endif /* KRB4 */
609 
610 #ifdef HESIOD
611 
612 #ifdef HESIOD_INTERFACES
613 
614 static char *
615 hesiod_get_pobox (const char **user)
616 {
617     void *context;
618     struct hesiod_postoffice *hpo;
619     char *ret = NULL;
620 
621     if(hesiod_init (&context) != 0)
622 	err (1, "hesiod_init");
623 
624     hpo = hesiod_getmailhost (context, *user);
625     if (hpo == NULL) {
626 	warn ("hesiod_getmailhost %s", *user);
627     } else {
628 	if (strcasecmp(hpo->hesiod_po_type, "pop") != 0)
629 	    errx (1, "Unsupported po type %s", hpo->hesiod_po_type);
630 
631 	ret = estrdup(hpo->hesiod_po_host);
632 	*user = estrdup(hpo->hesiod_po_name);
633 	hesiod_free_postoffice (context, hpo);
634     }
635     hesiod_end (context);
636     return ret;
637 }
638 
639 #else /* !HESIOD_INTERFACES */
640 
641 static char *
642 hesiod_get_pobox (const char **user)
643 {
644     char *ret = NULL;
645     struct hes_postoffice *hpo;
646 
647     hpo = hes_getmailhost (*user);
648     if (hpo == NULL) {
649 	warn ("hes_getmailhost %s", *user);
650     } else {
651 	if (strcasecmp(hpo->po_type, "pop") != 0)
652 	    errx (1, "Unsupported po type %s", hpo->po_type);
653 
654 	ret = estrdup(hpo->po_host);
655 	*user = estrdup(hpo->po_name);
656     }
657     return ret;
658 }
659 
660 #endif /* HESIOD_INTERFACES */
661 
662 #endif /* HESIOD */
663 
664 static char *
665 get_pobox (const char **user)
666 {
667     char *ret = NULL;
668 
669 #ifdef HESIOD
670     ret = hesiod_get_pobox (user);
671 #endif
672 
673     if (ret == NULL)
674 	ret = getenv("MAILHOST");
675     if (ret == NULL)
676 	errx (1, "MAILHOST not set");
677     return ret;
678 }
679 
680 static void
681 parse_pobox (char *a0, const char **host, const char **user)
682 {
683     const char *h, *u;
684     char *p;
685     int po = 0;
686 
687     if (a0 == NULL) {
688 
689 	*user = getenv ("USERNAME");
690 	if (*user == NULL) {
691 	    struct passwd *pwd = getpwuid (getuid ());
692 
693 	    if (pwd == NULL)
694 		errx (1, "Who are you?");
695 	    *user = estrdup (pwd->pw_name);
696 	}
697 	*host = get_pobox (user);
698 	return;
699     }
700 
701     /* if the specification starts with po:, remember this information */
702     if(strncmp(a0, "po:", 3) == 0) {
703 	a0 += 3;
704 	po++;
705     }
706     /* if there is an `@', the hostname is after it, otherwise at the
707        beginning of the string */
708     p = strchr(a0, '@');
709     if(p != NULL) {
710 	*p++ = '\0';
711 	h = p;
712     } else {
713 	h = a0;
714     }
715     /* if there is a `:', the username comes before it, otherwise at
716        the beginning of the string */
717     p = strchr(a0, ':');
718     if(p != NULL) {
719 	*p++ = '\0';
720 	u = p;
721     } else {
722 	u = a0;
723     }
724     if(h == u) {
725 	/* some inconsistent compatibility with various mailers */
726 	if(po) {
727 	    h = get_pobox (&u);
728 	} else {
729 	    u = get_default_username ();
730 	    if (u == NULL)
731 		errx (1, "Who are you?");
732 	}
733     }
734     *host = h;
735     *user = u;
736 }
737 
738 int
739 main(int argc, char **argv)
740 {
741     int port = 0;
742     int optind = 0;
743     int ret = 1;
744     const char *host, *user, *filename = NULL;
745     char *pobox = NULL;
746 
747     setprogname (argv[0]);
748 
749 #ifdef KRB5
750     {
751 	krb5_error_code ret;
752 
753 	ret = krb5_init_context (&context);
754 	if (ret)
755 	    errx (1, "krb5_init_context failed: %d", ret);
756     }
757 #endif
758 
759     if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
760 		&optind))
761 	usage (1);
762 
763     argc -= optind;
764     argv += optind;
765 
766 #if defined(KRB4) && defined(KRB5)
767     if(use_v4 == -1 && use_v5 == 1)
768 	use_v4 = 0;
769     if(use_v5 == -1 && use_v4 == 1)
770 	use_v5 = 0;
771 #endif
772 
773     if (do_help)
774 	usage (0);
775 
776     if (do_version) {
777 	print_version(NULL);
778 	return 0;
779     }
780 
781     if (do_from && header_str == NULL)
782 	header_str = "From:";
783     else if (header_str != NULL)
784 	do_from = 1;
785 
786     if (do_from) {
787 	if (argc == 0)
788 	    pobox = NULL;
789 	else if (argc == 1)
790 	    pobox = argv[0];
791 	else
792 	    usage (1);
793     } else {
794 	if (argc == 1) {
795 	    filename = argv[0];
796 	    pobox    = NULL;
797 	} else if (argc == 2) {
798 	    filename = argv[1];
799 	    pobox    = argv[0];
800 	} else
801 	    usage (1);
802     }
803 
804     if (port_str) {
805 	struct servent *s = roken_getservbyname (port_str, "tcp");
806 
807 	if (s)
808 	    port = s->s_port;
809 	else {
810 	    char *ptr;
811 
812 	    port = strtol (port_str, &ptr, 10);
813 	    if (port == 0 && ptr == port_str)
814 		errx (1, "Bad port `%s'", port_str);
815 	    port = htons(port);
816 	}
817     }
818     if (port == 0) {
819 #ifdef KRB5
820 	port = krb5_getportbyname (context, "kpop", "tcp", 1109);
821 #elif defined(KRB4)
822 	port = k_getportbyname ("kpop", "tcp", htons(1109));
823 #else
824 #error must define KRB4 or KRB5
825 #endif
826     }
827 
828     parse_pobox (pobox, &host, &user);
829 
830 #ifdef KRB5
831     if (ret && use_v5) {
832 	ret = do_v5 (host, port, user, filename, header_str,
833 		     do_leave, verbose_level, do_fork);
834     }
835 #endif
836 
837 #ifdef KRB4
838     if (ret && use_v4) {
839 	ret = do_v4 (host, port, user, filename, header_str,
840 		     do_leave, verbose_level, do_fork);
841     }
842 #endif /* KRB4 */
843     return ret;
844 }
845