This commit was manufactured by cvs2svn to create tag
[heimdal.git] / appl / push / push.c
blob43e3b1037f7772b5e61dee45bfab1fbd08a1e685
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 KRB4
38 static int use_v4 = -1;
39 #endif
41 #ifdef KRB5
42 static int use_v5 = -1;
43 static krb5_context context;
44 #endif
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;
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 }
84 static void
85 usage (int ret)
87 arg_printusage (args,
88 sizeof(args) / sizeof(args[0]),
89 NULL,
90 "[[{po:username[@hostname] | hostname[:username]}] ...] "
91 "filename");
92 exit (ret);
95 static int
96 do_connect (const char *hostname, int port, int nodelay)
98 struct addrinfo *ai, *a;
99 struct addrinfo hints;
100 int error;
101 int s = -1;
102 char portstr[NI_MAXSERV];
104 memset (&hints, 0, sizeof(hints));
105 hints.ai_socktype = SOCK_STREAM;
106 hints.ai_protocol = IPPROTO_TCP;
108 snprintf (portstr, sizeof(portstr), "%u", ntohs(port));
110 error = getaddrinfo (hostname, portstr, &hints, &ai);
111 if (error)
112 errx (1, "getaddrinfo(%s): %s", hostname, gai_strerror(error));
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;
123 break;
125 freeaddrinfo (ai);
126 if (a == NULL) {
127 warnx ("failed to contact %s", hostname);
128 return -1;
131 if(setsockopt(s, IPPROTO_TCP, TCP_NODELAY,
132 (void *)&nodelay, sizeof(nodelay)) < 0)
133 err (1, "setsockopt TCP_NODELAY");
134 return s;
137 typedef enum { INIT = 0, GREET, USER, PASS, STAT, RETR, TOP,
138 DELE, XDELE, QUIT} pop_state;
140 static char *pop_state_string[] = {
141 "INIT", "GREET", "USER", "PASS", "STAT", "RETR", "TOP",
142 "DELE", "XDELE", "QUIT"
145 #define PUSH_BUFSIZ 65536
147 #define STEP 16
149 struct write_state {
150 struct iovec *iovecs;
151 size_t niovecs, maxiovecs, allociovecs;
152 int fd;
155 static void
156 write_state_init (struct write_state *w, int fd)
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;
169 static void
170 write_state_add (struct write_state *w, void *v, size_t len)
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));
183 w->iovecs[w->niovecs].iov_base = v;
184 w->iovecs[w->niovecs].iov_len = len;
185 ++w->niovecs;
188 static void
189 write_state_flush (struct write_state *w)
191 if (w->niovecs) {
192 if (writev (w->fd, w->iovecs, w->niovecs) < 0)
193 err (1, "writev");
194 w->niovecs = 0;
198 static void
199 write_state_destroy (struct write_state *w)
201 free (w->iovecs);
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)
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;
235 in_buf = emalloc(PUSH_BUFSIZ + 1);
236 in_ptr = in_buf;
237 in_buf_size = PUSH_BUFSIZ;
239 if (do_from) {
240 char *tmp2;
242 tmp2 = tmp = estrdup(header_str);
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++;
255 headers = emalloc(sizeof(char *) * (numheaders + 1));
256 for (i = 0; i < numheaders; i++) {
257 headers[i] = strtok_r(tmp2, ",", &tmp2);
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);
268 now = time(NULL);
269 from_line_length = snprintf (from_line, sizeof(from_line),
270 "From %s %s", "push", ctime(&now));
272 out_len = snprintf (out_buf, sizeof(out_buf),
273 "USER %s\r\nPASS hej\r\nSTAT\r\n",
274 user);
275 if (out_len < 0)
276 errx (1, "snprintf failed");
277 if (net_write (s, out_buf, out_len) != out_len)
278 err (1, "write");
279 if (verbose > 1)
280 fprintf (stderr, "%s", out_buf);
282 if (!do_from)
283 write_state_init (&write_state, out_fd);
285 while(state != QUIT) {
286 fd_set readset, writeset;
288 FD_ZERO(&readset);
289 FD_ZERO(&writeset);
290 if (s >= FD_SETSIZE)
291 errx (1, "fd too large");
292 FD_SET(s,&readset);
294 if (verbose > 1)
295 fprintf (stderr, "state: %s count: %d asked_for: %d "
296 "retrieved: %d asked_deleted: %d\n",
297 pop_state_string[state],
298 count, asked_for, retrieved, asked_deleted);
300 if (((state == STAT || state == RETR || state == TOP)
301 && asked_for < count)
302 || (state == XDELE && !sent_xdele)
303 || (state == DELE && asked_deleted < count))
304 FD_SET(s,&writeset);
305 ret = select (s + 1, &readset, &writeset, NULL, NULL);
306 if (ret < 0) {
307 if (errno == EAGAIN)
308 continue;
309 else
310 err (1, "select");
313 if (FD_ISSET(s, &readset)) {
314 char *beg, *p;
315 size_t rem;
316 int blank_line = 0;
318 if(in_len >= in_buf_size) {
319 char *tmp = erealloc(in_buf, in_buf_size + PUSH_BUFSIZ + 1);
320 in_ptr = tmp + (in_ptr - in_buf);
321 in_buf = tmp;
322 in_buf_size += PUSH_BUFSIZ;
325 ret = read (s, in_ptr, in_buf_size - in_len);
326 if (ret < 0)
327 err (1, "read");
328 else if (ret == 0)
329 errx (1, "EOF during read");
331 in_len += ret;
332 in_ptr += ret;
333 *in_ptr = '\0';
335 beg = in_buf;
336 rem = in_len;
337 while(rem > 1
338 && (p = strstr(beg, "\r\n")) != NULL) {
339 if (state == TOP) {
340 char *copy = beg;
342 for (i = 0; i < numheaders; i++) {
343 size_t len;
345 len = min(p - copy + 1, strlen(headers[i]));
346 if (strncasecmp(copy, headers[i], len) == 0) {
347 fprintf (stdout, "%.*s\n", (int)(p - copy), copy);
350 if (beg[0] == '.' && beg[1] == '\r' && beg[2] == '\n') {
351 if (numheaders > 1)
352 fprintf (stdout, "\n");
353 state = STAT;
354 if (++retrieved == count) {
355 state = QUIT;
356 net_write (s, "QUIT\r\n", 6);
357 if (verbose > 1)
358 fprintf (stderr, "QUIT\r\n");
361 rem -= p - beg + 2;
362 beg = p + 2;
363 } else if (state == RETR) {
364 char *copy = beg;
365 if (beg[0] == '.') {
366 if (beg[1] == '\r' && beg[2] == '\n') {
367 if(!blank_line)
368 write_state_add(&write_state, "\n", 1);
369 state = STAT;
370 rem -= p - beg + 2;
371 beg = p + 2;
372 if (++retrieved == count) {
373 write_state_flush (&write_state);
374 if (fsync (out_fd) < 0)
375 err (1, "fsync");
376 close(out_fd);
377 if (leavep) {
378 state = QUIT;
379 net_write (s, "QUIT\r\n", 6);
380 if (verbose > 1)
381 fprintf (stderr, "QUIT\r\n");
382 } else {
383 if (forkp) {
384 pid_t pid;
386 pid = fork();
387 if (pid < 0)
388 warn ("fork");
389 else if(pid != 0) {
390 if(verbose)
391 fprintf (stderr,
392 "(exiting)");
393 return 0;
397 state = XDELE;
398 if (verbose)
399 fprintf (stderr, "deleting... ");
402 continue;
403 } else
404 ++copy;
406 *p = '\n';
407 if(blank_line &&
408 strncmp(copy, "From ", min(p - copy + 1, 5)) == 0)
409 write_state_add(&write_state, ">", 1);
410 write_state_add(&write_state, copy, p - copy + 1);
411 blank_line = (*copy == '\n');
412 rem -= p - beg + 2;
413 beg = p + 2;
414 } else if (rem >= 3 && strncmp (beg, "+OK", 3) == 0) {
415 if (state == STAT) {
416 if (!do_from)
417 write_state_add(&write_state,
418 from_line, from_line_length);
419 blank_line = 0;
420 if (do_from)
421 state = TOP;
422 else
423 state = RETR;
424 } else if (state == XDELE) {
425 state = QUIT;
426 net_write (s, "QUIT\r\n", 6);
427 if (verbose > 1)
428 fprintf (stderr, "QUIT\r\n");
429 break;
430 } else if (state == DELE) {
431 if (++deleted == count) {
432 state = QUIT;
433 net_write (s, "QUIT\r\n", 6);
434 if (verbose > 1)
435 fprintf (stderr, "QUIT\r\n");
436 break;
438 } else if (++state == STAT) {
439 if(sscanf (beg + 4, "%u %u", &count, &bytes) != 2)
440 errx(1, "Bad STAT-line: %.*s", (int)(p - beg), beg);
441 if (verbose) {
442 fprintf (stderr, "%u message(s) (%u bytes). "
443 "fetching... ",
444 count, bytes);
445 if (do_from)
446 fprintf (stderr, "\n");
447 } else if (do_count) {
448 fprintf (stderr, "%u message(s) (%u bytes).\n",
449 count, bytes);
451 if (count == 0) {
452 state = QUIT;
453 net_write (s, "QUIT\r\n", 6);
454 if (verbose > 1)
455 fprintf (stderr, "QUIT\r\n");
456 break;
460 rem -= p - beg + 2;
461 beg = p + 2;
462 } else {
463 if(state == XDELE) {
464 state = DELE;
465 rem -= p - beg + 2;
466 beg = p + 2;
467 } else
468 errx (1, "Bad response: %.*s", (int)(p - beg), beg);
471 if (!do_from)
472 write_state_flush (&write_state);
474 memmove (in_buf, beg, rem);
475 in_len = rem;
476 in_ptr = in_buf + rem;
478 if (FD_ISSET(s, &writeset)) {
479 if ((state == STAT && !do_from) || state == RETR)
480 out_len = snprintf (out_buf, sizeof(out_buf),
481 "RETR %u\r\n", ++asked_for);
482 else if ((state == STAT && do_from) || state == TOP)
483 out_len = snprintf (out_buf, sizeof(out_buf),
484 "TOP %u 0\r\n", ++asked_for);
485 else if(state == XDELE) {
486 out_len = snprintf(out_buf, sizeof(out_buf),
487 "XDELE %u %u\r\n", 1, count);
488 sent_xdele++;
490 else if(state == DELE)
491 out_len = snprintf (out_buf, sizeof(out_buf),
492 "DELE %u\r\n", ++asked_deleted);
493 if (out_len < 0)
494 errx (1, "snprintf failed");
495 if (net_write (s, out_buf, out_len) != out_len)
496 err (1, "write");
497 if (verbose > 1)
498 fprintf (stderr, "%s", out_buf);
501 if (verbose)
502 fprintf (stderr, "Done\n");
503 if (do_from) {
504 free (tmp);
505 free (headers);
506 } else {
507 write_state_destroy (&write_state);
509 return 0;
512 #ifdef KRB5
513 static int
514 do_v5 (const char *host,
515 int port,
516 const char *user,
517 const char *filename,
518 const char *header_str,
519 int leavep,
520 int verbose,
521 int forkp)
523 krb5_error_code ret;
524 krb5_auth_context auth_context = NULL;
525 krb5_principal server;
526 int s;
528 s = do_connect (host, port, 1);
529 if (s < 0)
530 return 1;
532 ret = krb5_sname_to_principal (context,
533 host,
534 "pop",
535 KRB5_NT_SRV_HST,
536 &server);
537 if (ret) {
538 warnx ("krb5_sname_to_principal: %s",
539 krb5_get_err_text (context, ret));
540 return 1;
543 ret = krb5_sendauth (context,
544 &auth_context,
546 "KPOPV1.0",
547 NULL,
548 server,
550 NULL,
551 NULL,
552 NULL,
553 NULL,
554 NULL,
555 NULL);
556 krb5_free_principal (context, server);
557 if (ret) {
558 warnx ("krb5_sendauth: %s",
559 krb5_get_err_text (context, ret));
560 return 1;
562 return doit (s, host, user, filename, header_str, leavep, verbose, forkp);
564 #endif
566 #ifdef KRB4
567 static int
568 do_v4 (const char *host,
569 int port,
570 const char *user,
571 const char *filename,
572 const char *header_str,
573 int leavep,
574 int verbose,
575 int forkp)
577 KTEXT_ST ticket;
578 MSG_DAT msg_data;
579 CREDENTIALS cred;
580 des_key_schedule sched;
581 int s;
582 int ret;
584 s = do_connect (host, port, 1);
585 if (s < 0)
586 return 1;
587 ret = krb_sendauth(0,
589 &ticket,
590 "pop",
591 (char *)host,
592 krb_realmofhost(host),
593 getpid(),
594 &msg_data,
595 &cred,
596 sched,
597 NULL,
598 NULL,
599 "KPOPV0.1");
600 if(ret) {
601 warnx("krb_sendauth: %s", krb_get_err_text(ret));
602 return 1;
604 return doit (s, host, user, filename, header_str, leavep, verbose, forkp);
606 #endif /* KRB4 */
608 #ifdef HESIOD
610 #ifdef HESIOD_INTERFACES
612 static char *
613 hesiod_get_pobox (const char **user)
615 void *context;
616 struct hesiod_postoffice *hpo;
617 char *ret = NULL;
619 if(hesiod_init (&context) != 0)
620 err (1, "hesiod_init");
622 hpo = hesiod_getmailhost (context, *user);
623 if (hpo == NULL) {
624 warn ("hesiod_getmailhost %s", *user);
625 } else {
626 if (strcasecmp(hpo->hesiod_po_type, "pop") != 0)
627 errx (1, "Unsupported po type %s", hpo->hesiod_po_type);
629 ret = estrdup(hpo->hesiod_po_host);
630 *user = estrdup(hpo->hesiod_po_name);
631 hesiod_free_postoffice (context, hpo);
633 hesiod_end (context);
634 return ret;
637 #else /* !HESIOD_INTERFACES */
639 static char *
640 hesiod_get_pobox (const char **user)
642 char *ret = NULL;
643 struct hes_postoffice *hpo;
645 hpo = hes_getmailhost (*user);
646 if (hpo == NULL) {
647 warn ("hes_getmailhost %s", *user);
648 } else {
649 if (strcasecmp(hpo->po_type, "pop") != 0)
650 errx (1, "Unsupported po type %s", hpo->po_type);
652 ret = estrdup(hpo->po_host);
653 *user = estrdup(hpo->po_name);
655 return ret;
658 #endif /* HESIOD_INTERFACES */
660 #endif /* HESIOD */
662 static char *
663 get_pobox (const char **user)
665 char *ret = NULL;
667 #ifdef HESIOD
668 ret = hesiod_get_pobox (user);
669 #endif
671 if (ret == NULL)
672 ret = getenv("MAILHOST");
673 if (ret == NULL)
674 errx (1, "MAILHOST not set");
675 return ret;
678 static void
679 parse_pobox (char *a0, const char **host, const char **user)
681 const char *h, *u;
682 char *p;
683 int po = 0;
685 if (a0 == NULL) {
687 *user = getenv ("USERNAME");
688 if (*user == NULL) {
689 struct passwd *pwd = getpwuid (getuid ());
691 if (pwd == NULL)
692 errx (1, "Who are you?");
693 *user = estrdup (pwd->pw_name);
695 *host = get_pobox (user);
696 return;
699 /* if the specification starts with po:, remember this information */
700 if(strncmp(a0, "po:", 3) == 0) {
701 a0 += 3;
702 po++;
704 /* if there is an `@', the hostname is after it, otherwise at the
705 beginning of the string */
706 p = strchr(a0, '@');
707 if(p != NULL) {
708 *p++ = '\0';
709 h = p;
710 } else {
711 h = a0;
713 /* if there is a `:', the username comes before it, otherwise at
714 the beginning of the string */
715 p = strchr(a0, ':');
716 if(p != NULL) {
717 *p++ = '\0';
718 u = p;
719 } else {
720 u = a0;
722 if(h == u) {
723 /* some inconsistent compatibility with various mailers */
724 if(po) {
725 h = get_pobox (&u);
726 } else {
727 u = get_default_username ();
728 if (u == NULL)
729 errx (1, "Who are you?");
732 *host = h;
733 *user = u;
737 main(int argc, char **argv)
739 int port = 0;
740 int optind = 0;
741 int ret = 1;
742 const char *host, *user, *filename = NULL;
743 char *pobox = NULL;
745 setprogname (argv[0]);
747 #ifdef KRB5
749 krb5_error_code ret;
751 ret = krb5_init_context (&context);
752 if (ret)
753 errx (1, "krb5_init_context failed: %d", ret);
755 #endif
757 if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
758 &optind))
759 usage (1);
761 argc -= optind;
762 argv += optind;
764 #if defined(KRB4) && defined(KRB5)
765 if(use_v4 == -1 && use_v5 == 1)
766 use_v4 = 0;
767 if(use_v5 == -1 && use_v4 == 1)
768 use_v5 = 0;
769 #endif
771 if (do_help)
772 usage (0);
774 if (do_version) {
775 print_version(NULL);
776 return 0;
779 if (do_from && header_str == NULL)
780 header_str = "From:";
781 else if (header_str != NULL)
782 do_from = 1;
784 if (do_from) {
785 if (argc == 0)
786 pobox = NULL;
787 else if (argc == 1)
788 pobox = argv[0];
789 else
790 usage (1);
791 } else {
792 if (argc == 1) {
793 filename = argv[0];
794 pobox = NULL;
795 } else if (argc == 2) {
796 filename = argv[1];
797 pobox = argv[0];
798 } else
799 usage (1);
802 if (port_str) {
803 struct servent *s = roken_getservbyname (port_str, "tcp");
805 if (s)
806 port = s->s_port;
807 else {
808 char *ptr;
810 port = strtol (port_str, &ptr, 10);
811 if (port == 0 && ptr == port_str)
812 errx (1, "Bad port `%s'", port_str);
813 port = htons(port);
816 if (port == 0) {
817 #ifdef KRB5
818 port = krb5_getportbyname (context, "kpop", "tcp", 1109);
819 #elif defined(KRB4)
820 port = k_getportbyname ("kpop", "tcp", htons(1109));
821 #else
822 #error must define KRB4 or KRB5
823 #endif
826 parse_pobox (pobox, &host, &user);
828 #ifdef KRB5
829 if (ret && use_v5) {
830 ret = do_v5 (host, port, user, filename, header_str,
831 do_leave, verbose_level, do_fork);
833 #endif
835 #ifdef KRB4
836 if (ret && use_v4) {
837 ret = do_v4 (host, port, user, filename, header_str,
838 do_leave, verbose_level, do_fork);
840 #endif /* KRB4 */
841 return ret;