remove unused variable
[heimdal.git] / appl / push / push.c
blobd65276c7c78b6884c697b022594347e02e1d5212
1 /*
2 * Copyright (c) 1997-2004 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
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.
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.
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.
34 #include "push_locl.h"
35 RCSID("$Id$");
37 #ifdef KRB5
38 static int use_v5 = -1;
39 static krb5_context context;
40 #endif
42 static char *port_str;
43 static int verbose_level;
44 static int do_fork;
45 static int do_leave;
46 static int do_version;
47 static int do_help;
48 static int do_from;
49 static int do_count;
50 static char *header_str;
52 struct getargs args[] = {
53 #ifdef KRB5
54 { "krb5", '5', arg_flag, &use_v5, "Use Kerberos V5",
55 NULL },
56 #endif
57 { "verbose",'v', arg_counter, &verbose_level, "Verbose",
58 NULL },
59 { "fork", 'f', arg_flag, &do_fork, "Fork deleting proc",
60 NULL },
61 { "leave", 'l', arg_flag, &do_leave, "Leave mail on server",
62 NULL },
63 { "port", 'p', arg_string, &port_str, "Use this port",
64 "number-or-service" },
65 { "from", 0, arg_flag, &do_from, "Behave like from",
66 NULL },
67 { "headers", 0, arg_string, &header_str, "Headers to print", NULL },
68 { "count", 'c', arg_flag, &do_count, "Print number of messages", NULL},
69 { "version", 0, arg_flag, &do_version, "Print version",
70 NULL },
71 { "help", 0, arg_flag, &do_help, NULL,
72 NULL }
76 static void
77 usage (int ret)
79 arg_printusage (args,
80 sizeof(args) / sizeof(args[0]),
81 NULL,
82 "[[{po:username[@hostname] | hostname[:username]}] ...] "
83 "filename");
84 exit (ret);
87 static int
88 do_connect (const char *hostname, int port, int nodelay)
90 struct addrinfo *ai, *a;
91 struct addrinfo hints;
92 int error;
93 int s = -1;
94 char portstr[NI_MAXSERV];
96 memset (&hints, 0, sizeof(hints));
97 hints.ai_socktype = SOCK_STREAM;
98 hints.ai_protocol = IPPROTO_TCP;
100 snprintf (portstr, sizeof(portstr), "%u", ntohs(port));
102 error = getaddrinfo (hostname, portstr, &hints, &ai);
103 if (error)
104 errx (1, "getaddrinfo(%s): %s", hostname, gai_strerror(error));
106 for (a = ai; a != NULL; a = a->ai_next) {
107 s = socket (a->ai_family, a->ai_socktype, a->ai_protocol);
108 if (s < 0)
109 continue;
110 if (connect (s, a->ai_addr, a->ai_addrlen) < 0) {
111 warn ("connect(%s)", hostname);
112 close (s);
113 continue;
115 break;
117 freeaddrinfo (ai);
118 if (a == NULL) {
119 warnx ("failed to contact %s", hostname);
120 return -1;
123 if(setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
124 (void *)&nodelay, sizeof(nodelay)) < 0)
125 err (1, "setsockopt TCP_NODELAY");
126 return s;
129 typedef enum { INIT = 0, GREET, USER, PASS, STAT, RETR, TOP,
130 DELE, XDELE, QUIT} pop_state;
132 static char *pop_state_string[] = {
133 "INIT", "GREET", "USER", "PASS", "STAT", "RETR", "TOP",
134 "DELE", "XDELE", "QUIT"
137 #define PUSH_BUFSIZ 65536
139 #define STEP 16
141 struct write_state {
142 struct iovec *iovecs;
143 size_t niovecs, maxiovecs, allociovecs;
144 int fd;
147 static void
148 write_state_init (struct write_state *w, int fd)
150 #ifdef UIO_MAXIOV
151 w->maxiovecs = UIO_MAXIOV;
152 #else
153 w->maxiovecs = 16;
154 #endif
155 w->allociovecs = min(STEP, w->maxiovecs);
156 w->niovecs = 0;
157 w->iovecs = emalloc(w->allociovecs * sizeof(*w->iovecs));
158 w->fd = fd;
161 static void
162 write_state_add (struct write_state *w, void *v, size_t len)
164 if(w->niovecs == w->allociovecs) {
165 if(w->niovecs == w->maxiovecs) {
166 if(writev (w->fd, w->iovecs, w->niovecs) < 0)
167 err(1, "writev");
168 w->niovecs = 0;
169 } else {
170 w->allociovecs = min(w->allociovecs + STEP, w->maxiovecs);
171 w->iovecs = erealloc (w->iovecs,
172 w->allociovecs * sizeof(*w->iovecs));
175 w->iovecs[w->niovecs].iov_base = v;
176 w->iovecs[w->niovecs].iov_len = len;
177 ++w->niovecs;
180 static void
181 write_state_flush (struct write_state *w)
183 if (w->niovecs) {
184 if (writev (w->fd, w->iovecs, w->niovecs) < 0)
185 err (1, "writev");
186 w->niovecs = 0;
190 static void
191 write_state_destroy (struct write_state *w)
193 free (w->iovecs);
196 static int
197 doit(int s,
198 const char *host,
199 const char *user,
200 const char *outfilename,
201 const char *header_str,
202 int leavep,
203 int verbose,
204 int forkp)
206 int ret;
207 char out_buf[PUSH_BUFSIZ];
208 int out_len = 0;
209 char *in_buf;
210 size_t in_buf_size;
211 size_t in_len = 0;
212 char *in_ptr;
213 pop_state state = INIT;
214 unsigned count = 0, bytes;
215 unsigned asked_for = 0, retrieved = 0, asked_deleted = 0, deleted = 0;
216 unsigned sent_xdele = 0;
217 int out_fd;
218 char from_line[128];
219 size_t from_line_length;
220 time_t now;
221 struct write_state write_state;
222 unsigned int numheaders = 1;
223 char **headers = NULL;
224 int i;
225 char *tmp = NULL;
227 in_buf = emalloc(PUSH_BUFSIZ + 1);
228 in_ptr = in_buf;
229 in_buf_size = PUSH_BUFSIZ;
231 if (do_from) {
232 char *tmp2;
234 tmp2 = tmp = estrdup(header_str);
236 out_fd = -1;
237 if (verbose)
238 fprintf (stderr, "%s@%s\n", user, host);
239 while (*tmp != '\0') {
240 tmp = strchr(tmp, ',');
241 if (tmp == NULL)
242 break;
243 tmp++;
244 numheaders++;
247 headers = emalloc(sizeof(char *) * (numheaders + 1));
248 for (i = 0; i < numheaders; i++) {
249 headers[i] = strtok_r(tmp2, ",", &tmp2);
251 headers[numheaders] = NULL;
252 } else {
253 out_fd = open(outfilename, O_WRONLY | O_APPEND | O_CREAT, 0666);
254 if (out_fd < 0)
255 err (1, "open %s", outfilename);
256 if (verbose)
257 fprintf (stderr, "%s@%s -> %s\n", user, host, outfilename);
260 now = time(NULL);
261 from_line_length = snprintf (from_line, sizeof(from_line),
262 "From %s %s", "push", ctime(&now));
263 if (from_line_length < 0 || from_line_length > sizeof(from_line))
264 errx (1, "snprintf failed");
266 out_len = snprintf (out_buf, sizeof(out_buf),
267 "USER %s\r\nPASS hej\r\nSTAT\r\n",
268 user);
269 if (out_len < 0 || out_len > sizeof(out_buf))
270 errx (1, "snprintf failed");
271 if (net_write (s, out_buf, out_len) != out_len)
272 err (1, "write");
273 if (verbose > 1)
274 fprintf (stderr, "%s", out_buf);
276 if (!do_from)
277 write_state_init (&write_state, out_fd);
279 while(state != QUIT) {
280 fd_set readset, writeset;
282 FD_ZERO(&readset);
283 FD_ZERO(&writeset);
284 if (s >= FD_SETSIZE)
285 errx (1, "fd too large");
286 FD_SET(s,&readset);
288 if (verbose > 1)
289 fprintf (stderr, "state: %s count: %d asked_for: %d "
290 "retrieved: %d asked_deleted: %d\n",
291 pop_state_string[state],
292 count, asked_for, retrieved, asked_deleted);
294 if (((state == STAT || state == RETR || state == TOP)
295 && asked_for < count)
296 || (state == XDELE && !sent_xdele)
297 || (state == DELE && asked_deleted < count))
298 FD_SET(s,&writeset);
299 ret = select (s + 1, &readset, &writeset, NULL, NULL);
300 if (ret < 0) {
301 if (errno == EAGAIN)
302 continue;
303 else
304 err (1, "select");
307 if (FD_ISSET(s, &readset)) {
308 char *beg, *p;
309 size_t rem;
310 int blank_line = 0;
312 if(in_len >= in_buf_size) {
313 char *tmp = erealloc(in_buf, in_buf_size + PUSH_BUFSIZ + 1);
314 in_ptr = tmp + (in_ptr - in_buf);
315 in_buf = tmp;
316 in_buf_size += PUSH_BUFSIZ;
319 ret = read (s, in_ptr, in_buf_size - in_len);
320 if (ret < 0)
321 err (1, "read");
322 else if (ret == 0)
323 errx (1, "EOF during read");
325 in_len += ret;
326 in_ptr += ret;
327 *in_ptr = '\0';
329 beg = in_buf;
330 rem = in_len;
331 while(rem > 1
332 && (p = strstr(beg, "\r\n")) != NULL) {
333 if (state == TOP) {
334 char *copy = beg;
336 for (i = 0; i < numheaders; i++) {
337 size_t len;
339 len = min(p - copy + 1, strlen(headers[i]));
340 if (strncasecmp(copy, headers[i], len) == 0) {
341 fprintf (stdout, "%.*s\n", (int)(p - copy), copy);
344 if (beg[0] == '.' && beg[1] == '\r' && beg[2] == '\n') {
345 if (numheaders > 1)
346 fprintf (stdout, "\n");
347 state = STAT;
348 if (++retrieved == count) {
349 state = QUIT;
350 net_write (s, "QUIT\r\n", 6);
351 if (verbose > 1)
352 fprintf (stderr, "QUIT\r\n");
355 rem -= p - beg + 2;
356 beg = p + 2;
357 } else if (state == RETR) {
358 char *copy = beg;
359 if (beg[0] == '.') {
360 if (beg[1] == '\r' && beg[2] == '\n') {
361 if(!blank_line)
362 write_state_add(&write_state, "\n", 1);
363 state = STAT;
364 rem -= p - beg + 2;
365 beg = p + 2;
366 if (++retrieved == count) {
367 write_state_flush (&write_state);
368 if (fsync (out_fd) < 0)
369 err (1, "fsync");
370 close(out_fd);
371 if (leavep) {
372 state = QUIT;
373 net_write (s, "QUIT\r\n", 6);
374 if (verbose > 1)
375 fprintf (stderr, "QUIT\r\n");
376 } else {
377 if (forkp) {
378 pid_t pid;
380 pid = fork();
381 if (pid < 0)
382 warn ("fork");
383 else if(pid != 0) {
384 if(verbose)
385 fprintf (stderr,
386 "(exiting)");
387 return 0;
391 state = XDELE;
392 if (verbose)
393 fprintf (stderr, "deleting... ");
396 continue;
397 } else
398 ++copy;
400 *p = '\n';
401 if(blank_line &&
402 strncmp(copy, "From ", min(p - copy + 1, 5)) == 0)
403 write_state_add(&write_state, ">", 1);
404 write_state_add(&write_state, copy, p - copy + 1);
405 blank_line = (*copy == '\n');
406 rem -= p - beg + 2;
407 beg = p + 2;
408 } else if (rem >= 3 && strncmp (beg, "+OK", 3) == 0) {
409 if (state == STAT) {
410 if (!do_from)
411 write_state_add(&write_state,
412 from_line, from_line_length);
413 blank_line = 0;
414 if (do_from)
415 state = TOP;
416 else
417 state = RETR;
418 } else if (state == XDELE) {
419 state = QUIT;
420 net_write (s, "QUIT\r\n", 6);
421 if (verbose > 1)
422 fprintf (stderr, "QUIT\r\n");
423 break;
424 } else if (state == DELE) {
425 if (++deleted == count) {
426 state = QUIT;
427 net_write (s, "QUIT\r\n", 6);
428 if (verbose > 1)
429 fprintf (stderr, "QUIT\r\n");
430 break;
432 } else if (++state == STAT) {
433 if(sscanf (beg + 4, "%u %u", &count, &bytes) != 2)
434 errx(1, "Bad STAT-line: %.*s", (int)(p - beg), beg);
435 if (verbose) {
436 fprintf (stderr, "%u message(s) (%u bytes). "
437 "fetching... ",
438 count, bytes);
439 if (do_from)
440 fprintf (stderr, "\n");
441 } else if (do_count) {
442 fprintf (stderr, "%u message(s) (%u bytes).\n",
443 count, bytes);
445 if (count == 0) {
446 state = QUIT;
447 net_write (s, "QUIT\r\n", 6);
448 if (verbose > 1)
449 fprintf (stderr, "QUIT\r\n");
450 break;
454 rem -= p - beg + 2;
455 beg = p + 2;
456 } else {
457 if(state == XDELE) {
458 state = DELE;
459 rem -= p - beg + 2;
460 beg = p + 2;
461 } else
462 errx (1, "Bad response: %.*s", (int)(p - beg), beg);
465 if (!do_from)
466 write_state_flush (&write_state);
468 memmove (in_buf, beg, rem);
469 in_len = rem;
470 in_ptr = in_buf + rem;
472 if (FD_ISSET(s, &writeset)) {
473 if ((state == STAT && !do_from) || state == RETR)
474 out_len = snprintf (out_buf, sizeof(out_buf),
475 "RETR %u\r\n", ++asked_for);
476 else if ((state == STAT && do_from) || state == TOP)
477 out_len = snprintf (out_buf, sizeof(out_buf),
478 "TOP %u 0\r\n", ++asked_for);
479 else if(state == XDELE) {
480 out_len = snprintf(out_buf, sizeof(out_buf),
481 "XDELE %u %u\r\n", 1, count);
482 sent_xdele++;
484 else if(state == DELE)
485 out_len = snprintf (out_buf, sizeof(out_buf),
486 "DELE %u\r\n", ++asked_deleted);
487 if (out_len < 0 || out_len > sizeof(out_buf))
488 errx (1, "snprintf failed");
489 if (net_write (s, out_buf, out_len) != out_len)
490 err (1, "write");
491 if (verbose > 1)
492 fprintf (stderr, "%s", out_buf);
495 if (verbose)
496 fprintf (stderr, "Done\n");
497 if (do_from) {
498 free (tmp);
499 free (headers);
500 } else {
501 write_state_destroy (&write_state);
503 return 0;
506 #ifdef KRB5
507 static int
508 do_v5 (const char *host,
509 int port,
510 const char *user,
511 const char *filename,
512 const char *header_str,
513 int leavep,
514 int verbose,
515 int forkp)
517 krb5_error_code ret;
518 krb5_auth_context auth_context = NULL;
519 krb5_principal server;
520 int s;
522 s = do_connect (host, port, 1);
523 if (s < 0)
524 return 1;
526 ret = krb5_sname_to_principal (context,
527 host,
528 "pop",
529 KRB5_NT_SRV_HST,
530 &server);
531 if (ret) {
532 warnx ("krb5_sname_to_principal: %s",
533 krb5_get_err_text (context, ret));
534 return 1;
537 ret = krb5_sendauth (context,
538 &auth_context,
540 "KPOPV1.0",
541 NULL,
542 server,
544 NULL,
545 NULL,
546 NULL,
547 NULL,
548 NULL,
549 NULL);
550 krb5_free_principal (context, server);
551 if (ret) {
552 warnx ("krb5_sendauth: %s",
553 krb5_get_err_text (context, ret));
554 return 1;
556 return doit (s, host, user, filename, header_str, leavep, verbose, forkp);
558 #endif
560 #ifdef HESIOD
562 #ifdef HESIOD_INTERFACES
564 static char *
565 hesiod_get_pobox (const char **user)
567 void *context;
568 struct hesiod_postoffice *hpo;
569 char *ret = NULL;
571 if(hesiod_init (&context) != 0)
572 err (1, "hesiod_init");
574 hpo = hesiod_getmailhost (context, *user);
575 if (hpo == NULL) {
576 warn ("hesiod_getmailhost %s", *user);
577 } else {
578 if (strcasecmp(hpo->hesiod_po_type, "pop") != 0)
579 errx (1, "Unsupported po type %s", hpo->hesiod_po_type);
581 ret = estrdup(hpo->hesiod_po_host);
582 *user = estrdup(hpo->hesiod_po_name);
583 hesiod_free_postoffice (context, hpo);
585 hesiod_end (context);
586 return ret;
589 #else /* !HESIOD_INTERFACES */
591 static char *
592 hesiod_get_pobox (const char **user)
594 char *ret = NULL;
595 struct hes_postoffice *hpo;
597 hpo = hes_getmailhost (*user);
598 if (hpo == NULL) {
599 warn ("hes_getmailhost %s", *user);
600 } else {
601 if (strcasecmp(hpo->po_type, "pop") != 0)
602 errx (1, "Unsupported po type %s", hpo->po_type);
604 ret = estrdup(hpo->po_host);
605 *user = estrdup(hpo->po_name);
607 return ret;
610 #endif /* HESIOD_INTERFACES */
612 #endif /* HESIOD */
614 static char *
615 get_pobox (const char **user)
617 char *ret = NULL;
619 #ifdef HESIOD
620 ret = hesiod_get_pobox (user);
621 #endif
623 if (ret == NULL)
624 ret = getenv("MAILHOST");
625 if (ret == NULL)
626 errx (1, "MAILHOST not set");
627 return ret;
630 static void
631 parse_pobox (char *a0, const char **host, const char **user)
633 const char *h, *u;
634 char *p;
635 int po = 0;
637 if (a0 == NULL) {
639 *user = getenv ("USERNAME");
640 if (*user == NULL) {
641 struct passwd *pwd = getpwuid (getuid ());
643 if (pwd == NULL)
644 errx (1, "Who are you?");
645 *user = estrdup (pwd->pw_name);
647 *host = get_pobox (user);
648 return;
651 /* if the specification starts with po:, remember this information */
652 if(strncmp(a0, "po:", 3) == 0) {
653 a0 += 3;
654 po++;
656 /* if there is an `@', the hostname is after it, otherwise at the
657 beginning of the string */
658 p = strchr(a0, '@');
659 if(p != NULL) {
660 *p++ = '\0';
661 h = p;
662 } else {
663 h = a0;
665 /* if there is a `:', the username comes before it, otherwise at
666 the beginning of the string */
667 p = strchr(a0, ':');
668 if(p != NULL) {
669 *p++ = '\0';
670 u = p;
671 } else {
672 u = a0;
674 if(h == u) {
675 /* some inconsistent compatibility with various mailers */
676 if(po) {
677 h = get_pobox (&u);
678 } else {
679 u = get_default_username ();
680 if (u == NULL)
681 errx (1, "Who are you?");
684 *host = h;
685 *user = u;
689 main(int argc, char **argv)
691 int port = 0;
692 int optind = 0;
693 int ret = 1;
694 const char *host, *user, *filename = NULL;
695 char *pobox = NULL;
697 setprogname (argv[0]);
699 #ifdef KRB5
701 krb5_error_code ret;
703 ret = krb5_init_context (&context);
704 if (ret)
705 errx (1, "krb5_init_context failed: %d", ret);
707 #endif
709 if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
710 &optind))
711 usage (1);
713 argc -= optind;
714 argv += optind;
716 if (do_help)
717 usage (0);
719 if (do_version) {
720 print_version(NULL);
721 return 0;
724 if (do_from && header_str == NULL)
725 header_str = "From:";
726 else if (header_str != NULL)
727 do_from = 1;
729 if (do_from) {
730 if (argc == 0)
731 pobox = NULL;
732 else if (argc == 1)
733 pobox = argv[0];
734 else
735 usage (1);
736 } else {
737 if (argc == 1) {
738 filename = argv[0];
739 pobox = NULL;
740 } else if (argc == 2) {
741 filename = argv[1];
742 pobox = argv[0];
743 } else
744 usage (1);
747 if (port_str) {
748 struct servent *s = roken_getservbyname (port_str, "tcp");
750 if (s)
751 port = s->s_port;
752 else {
753 char *ptr;
755 port = strtol (port_str, &ptr, 10);
756 if (port == 0 && ptr == port_str)
757 errx (1, "Bad port `%s'", port_str);
758 port = htons(port);
761 if (port == 0) {
762 #ifdef KRB5
763 port = krb5_getportbyname (context, "kpop", "tcp", 1109);
764 #else
765 #error must define KRB5
766 #endif
769 parse_pobox (pobox, &host, &user);
771 #ifdef KRB5
772 if (ret && use_v5) {
773 ret = do_v5 (host, port, user, filename, header_str,
774 do_leave, verbose_level, do_fork);
776 #endif
777 return ret;