Index: projects/openssl111/contrib/dma/crypto.c =================================================================== --- projects/openssl111/contrib/dma/crypto.c (revision 338769) +++ projects/openssl111/contrib/dma/crypto.c (revision 338770) @@ -1,312 +1,318 @@ /* * Copyright (c) 2008 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by Matthias Schmidt , University of Marburg, * Germany. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of The DragonFly Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific, prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include +#include #include #include "dma.h" static int init_cert_file(SSL_CTX *ctx, const char *path) { int error; /* Load certificate into ctx */ error = SSL_CTX_use_certificate_chain_file(ctx, path); if (error < 1) { syslog(LOG_ERR, "SSL: Cannot load certificate `%s': %s", path, ssl_errstr()); return (-1); } /* Add private key to ctx */ error = SSL_CTX_use_PrivateKey_file(ctx, path, SSL_FILETYPE_PEM); if (error < 1) { syslog(LOG_ERR, "SSL: Cannot load private key `%s': %s", path, ssl_errstr()); return (-1); } /* * Check the consistency of a private key with the corresponding * certificate */ error = SSL_CTX_check_private_key(ctx); if (error < 1) { syslog(LOG_ERR, "SSL: Cannot check private key: %s", ssl_errstr()); return (-1); } return (0); } int smtp_init_crypto(int fd, int feature) { SSL_CTX *ctx = NULL; #if (OPENSSL_VERSION_NUMBER >= 0x00909000L) const SSL_METHOD *meth = NULL; #else SSL_METHOD *meth = NULL; #endif X509 *cert; int error; /* XXX clean up on error/close */ /* Init SSL library */ SSL_library_init(); SSL_load_error_strings(); - meth = TLSv1_client_method(); + // Allow any possible version +#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) + meth = TLS_client_method(); +#else + meth = SSLv23_client_method(); +#endif ctx = SSL_CTX_new(meth); if (ctx == NULL) { syslog(LOG_WARNING, "remote delivery deferred: SSL init failed: %s", ssl_errstr()); return (1); } /* User supplied a certificate */ if (config.certfile != NULL) { error = init_cert_file(ctx, config.certfile); if (error) { syslog(LOG_WARNING, "remote delivery deferred"); return (1); } } /* * If the user wants STARTTLS, we have to send EHLO here */ if (((feature & SECURETRANS) != 0) && (feature & STARTTLS) != 0) { /* TLS init phase, disable SSL_write */ config.features |= NOSSL; send_remote_command(fd, "EHLO %s", hostname()); if (read_remote(fd, 0, NULL) == 2) { send_remote_command(fd, "STARTTLS"); if (read_remote(fd, 0, NULL) != 2) { if ((feature & TLS_OPP) == 0) { syslog(LOG_ERR, "remote delivery deferred: STARTTLS not available: %s", neterr); return (1); } else { syslog(LOG_INFO, "in opportunistic TLS mode, STARTTLS not available: %s", neterr); return (0); } } } /* End of TLS init phase, enable SSL_write/read */ config.features &= ~NOSSL; } config.ssl = SSL_new(ctx); if (config.ssl == NULL) { syslog(LOG_NOTICE, "remote delivery deferred: SSL struct creation failed: %s", ssl_errstr()); return (1); } /* Set ssl to work in client mode */ SSL_set_connect_state(config.ssl); /* Set fd for SSL in/output */ error = SSL_set_fd(config.ssl, fd); if (error == 0) { syslog(LOG_NOTICE, "remote delivery deferred: SSL set fd failed: %s", ssl_errstr()); return (1); } /* Open SSL connection */ error = SSL_connect(config.ssl); if (error < 0) { syslog(LOG_ERR, "remote delivery deferred: SSL handshake failed fatally: %s", ssl_errstr()); return (1); } /* Get peer certificate */ cert = SSL_get_peer_certificate(config.ssl); if (cert == NULL) { syslog(LOG_WARNING, "remote delivery deferred: Peer did not provide certificate: %s", ssl_errstr()); } X509_free(cert); return (0); } /* * hmac_md5() taken out of RFC 2104. This RFC was written by H. Krawczyk, * M. Bellare and R. Canetti. * * text pointer to data stream * text_len length of data stream * key pointer to authentication key * key_len length of authentication key * digest caller digest to be filled int */ void hmac_md5(unsigned char *text, int text_len, unsigned char *key, int key_len, unsigned char* digest) { MD5_CTX context; unsigned char k_ipad[65]; /* inner padding - * key XORd with ipad */ unsigned char k_opad[65]; /* outer padding - * key XORd with opad */ unsigned char tk[16]; int i; /* if key is longer than 64 bytes reset it to key=MD5(key) */ if (key_len > 64) { MD5_CTX tctx; MD5_Init(&tctx); MD5_Update(&tctx, key, key_len); MD5_Final(tk, &tctx); key = tk; key_len = 16; } /* * the HMAC_MD5 transform looks like: * * MD5(K XOR opad, MD5(K XOR ipad, text)) * * where K is an n byte key * ipad is the byte 0x36 repeated 64 times * * opad is the byte 0x5c repeated 64 times * and text is the data being protected */ /* start out by storing key in pads */ bzero( k_ipad, sizeof k_ipad); bzero( k_opad, sizeof k_opad); bcopy( key, k_ipad, key_len); bcopy( key, k_opad, key_len); /* XOR key with ipad and opad values */ for (i=0; i<64; i++) { k_ipad[i] ^= 0x36; k_opad[i] ^= 0x5c; } /* * perform inner MD5 */ MD5_Init(&context); /* init context for 1st * pass */ MD5_Update(&context, k_ipad, 64); /* start with inner pad */ MD5_Update(&context, text, text_len); /* then text of datagram */ MD5_Final(digest, &context); /* finish up 1st pass */ /* * perform outer MD5 */ MD5_Init(&context); /* init context for 2nd * pass */ MD5_Update(&context, k_opad, 64); /* start with outer pad */ MD5_Update(&context, digest, 16); /* then results of 1st * hash */ MD5_Final(digest, &context); /* finish up 2nd pass */ } /* * CRAM-MD5 authentication */ int smtp_auth_md5(int fd, char *login, char *password) { unsigned char digest[BUF_SIZE]; char buffer[BUF_SIZE], ascii_digest[33]; char *temp; int len, i; static char hextab[] = "0123456789abcdef"; temp = calloc(BUF_SIZE, 1); memset(buffer, 0, sizeof(buffer)); memset(digest, 0, sizeof(digest)); memset(ascii_digest, 0, sizeof(ascii_digest)); /* Send AUTH command according to RFC 2554 */ send_remote_command(fd, "AUTH CRAM-MD5"); if (read_remote(fd, sizeof(buffer), buffer) != 3) { syslog(LOG_DEBUG, "smarthost authentication:" " AUTH cram-md5 not available: %s", neterr); /* if cram-md5 is not available */ free(temp); return (-1); } /* skip 3 char status + 1 char space */ base64_decode(buffer + 4, temp); hmac_md5((unsigned char *)temp, strlen(temp), (unsigned char *)password, strlen(password), digest); free(temp); ascii_digest[32] = 0; for (i = 0; i < 16; i++) { ascii_digest[2*i] = hextab[digest[i] >> 4]; ascii_digest[2*i+1] = hextab[digest[i] & 15]; } /* prepare answer */ snprintf(buffer, BUF_SIZE, "%s %s", login, ascii_digest); /* encode answer */ len = base64_encode(buffer, strlen(buffer), &temp); if (len < 0) { syslog(LOG_ERR, "can not encode auth reply: %m"); return (-1); } /* send answer */ send_remote_command(fd, "%s", temp); free(temp); if (read_remote(fd, 0, NULL) != 2) { syslog(LOG_WARNING, "remote delivery deferred:" " AUTH cram-md5 failed: %s", neterr); return (-2); } return (0); } Index: projects/openssl111/contrib/dma/dma-mbox-create.c =================================================================== --- projects/openssl111/contrib/dma/dma-mbox-create.c (revision 338769) +++ projects/openssl111/contrib/dma/dma-mbox-create.c (revision 338770) @@ -1,191 +1,192 @@ /* * Copyright (c) 2010-2014, Simon Schubert <2@0x2c.org>. * Copyright (c) 2008 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by Simon Schubert <2@0x2c.org>. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of The DragonFly Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific, prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This binary is setuid root. Use extreme caution when touching * user-supplied information. Keep the root window as small as possible. */ #ifdef __FreeBSD__ #define USE_CAPSICUM 1 #endif #include #if USE_CAPSICUM #include #endif #include #include #include #include #include #include #include #include #include +#include #include #include #include "dma.h" static void logfail(int exitcode, const char *fmt, ...) { int oerrno = errno; va_list ap; char outs[1024]; outs[0] = 0; if (fmt != NULL) { va_start(ap, fmt); vsnprintf(outs, sizeof(outs), fmt, ap); va_end(ap); } errno = oerrno; if (*outs != 0) syslog(LOG_ERR, errno ? "%s: %m" : "%s", outs); else syslog(LOG_ERR, errno ? "%m" : "unknown error"); exit(exitcode); } /* * Create a mbox in /var/mail for a given user, or make sure * the permissions are correct for dma. */ int main(int argc, char **argv) { #if USE_CAPSICUM cap_rights_t rights; #endif const char *user; struct passwd *pw; struct group *gr; uid_t user_uid; gid_t mail_gid; int f, maildirfd; /* * Open log fd now for capability sandbox. */ openlog("dma-mbox-create", LOG_NDELAY, LOG_MAIL); errno = 0; gr = getgrnam(DMA_GROUP); if (!gr) logfail(EX_CONFIG, "cannot find dma group `%s'", DMA_GROUP); mail_gid = gr->gr_gid; if (setgid(mail_gid) != 0) logfail(EX_NOPERM, "cannot set gid to %d (%s)", mail_gid, DMA_GROUP); if (getegid() != mail_gid) logfail(EX_NOPERM, "cannot set gid to %d (%s), still at %d", mail_gid, DMA_GROUP, getegid()); /* * We take exactly one argument: the username. */ if (argc != 2) { errno = 0; logfail(EX_USAGE, "no arguments"); } user = argv[1]; syslog(LOG_NOTICE, "creating mbox for `%s'", user); /* the username may not contain a pathname separator */ if (strchr(user, '/')) { errno = 0; logfail(EX_DATAERR, "path separator in username `%s'", user); exit(1); } /* verify the user exists */ errno = 0; pw = getpwnam(user); if (!pw) logfail(EX_NOUSER, "cannot find user `%s'", user); maildirfd = open(_PATH_MAILDIR, O_RDONLY); if (maildirfd < 0) logfail(EX_NOINPUT, "cannot open maildir %s", _PATH_MAILDIR); /* * Cache NLS data, for strerror, for err(3), before entering capability * mode. */ caph_cache_catpages(); /* * Cache local time before entering Capsicum capability sandbox. */ caph_cache_tzdata(); #if USE_CAPSICUM cap_rights_init(&rights, CAP_CREATE, CAP_FCHMOD, CAP_FCHOWN, CAP_LOOKUP, CAP_READ); if (cap_rights_limit(maildirfd, &rights) < 0 && errno != ENOSYS) err(EX_OSERR, "can't limit maildirfd rights"); /* Enter Capsicum capability sandbox */ if (caph_enter() < 0) err(EX_OSERR, "cap_enter"); #endif user_uid = pw->pw_uid; f = openat(maildirfd, user, O_RDONLY|O_CREAT|O_NOFOLLOW, 0600); if (f < 0) logfail(EX_NOINPUT, "cannot open mbox `%s'", user); if (fchown(f, user_uid, mail_gid)) logfail(EX_OSERR, "cannot change owner of mbox `%s'", user); if (fchmod(f, 0620)) logfail(EX_OSERR, "cannot change permissions of mbox `%s'", user); /* file should be present with the right owner and permissions */ syslog(LOG_NOTICE, "successfully created mbox for `%s'", user); return (0); } Index: projects/openssl111/contrib/dma/local.c =================================================================== --- projects/openssl111/contrib/dma/local.c (revision 338769) +++ projects/openssl111/contrib/dma/local.c (revision 338770) @@ -1,254 +1,255 @@ /* * Copyright (c) 2008-2014, Simon Schubert <2@0x2c.org>. * Copyright (c) 2008 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by Simon Schubert <2@0x2c.org>. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of The DragonFly Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific, prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include +#include #include #include #include "dma.h" static int create_mbox(const char *name) { struct sigaction sa, osa; pid_t child, waitchild; int status; int i; long maxfd; int e; int r = -1; /* * We need to enable SIGCHLD temporarily so that waitpid works. */ bzero(&sa, sizeof(sa)); sa.sa_handler = SIG_DFL; sigaction(SIGCHLD, &sa, &osa); do_timeout(100, 0); child = fork(); switch (child) { case 0: /* child */ maxfd = sysconf(_SC_OPEN_MAX); if (maxfd == -1) maxfd = 1024; /* what can we do... */ for (i = 3; i <= maxfd; ++i) close(i); execl(LIBEXEC_PATH "/dma-mbox-create", "dma-mbox-create", name, NULL); syslog(LOG_ERR, "cannot execute "LIBEXEC_PATH"/dma-mbox-create: %m"); exit(EX_SOFTWARE); default: /* parent */ waitchild = waitpid(child, &status, 0); e = errno; do_timeout(0, 0); if (waitchild == -1 && e == EINTR) { syslog(LOG_ERR, "hung child while creating mbox `%s': %m", name); break; } if (waitchild == -1) { syslog(LOG_ERR, "child disappeared while creating mbox `%s': %m", name); break; } if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { syslog(LOG_ERR, "error creating mbox `%s'", name); break; } /* success */ r = 0; break; case -1: /* error */ syslog(LOG_ERR, "error creating mbox"); break; } sigaction(SIGCHLD, &osa, NULL); return (r); } int deliver_local(struct qitem *it) { char fn[PATH_MAX+1]; char line[1000]; const char *sender; const char *newline = "\n"; size_t linelen; int tries = 0; int mbox; int error; int hadnl = 0; off_t mboxlen; time_t now = time(NULL); error = snprintf(fn, sizeof(fn), "%s/%s", _PATH_MAILDIR, it->addr); if (error < 0 || (size_t)error >= sizeof(fn)) { syslog(LOG_NOTICE, "local delivery deferred: %m"); return (1); } retry: /* wait for a maximum of 100s to get the lock to the file */ do_timeout(100, 0); /* don't use O_CREAT here, because we might be running as the wrong user. */ mbox = open_locked(fn, O_WRONLY|O_APPEND); if (mbox < 0) { int e = errno; do_timeout(0, 0); switch (e) { case EACCES: case ENOENT: /* * The file does not exist or we can't access it. * Call dma-mbox-create to create it and fix permissions. */ if (tries > 0 || create_mbox(it->addr) != 0) { syslog(LOG_ERR, "local delivery deferred: can not create `%s'", fn); return (1); } ++tries; goto retry; case EINTR: syslog(LOG_NOTICE, "local delivery deferred: can not lock `%s'", fn); break; default: syslog(LOG_NOTICE, "local delivery deferred: can not open `%s': %m", fn); break; } return (1); } do_timeout(0, 0); mboxlen = lseek(mbox, 0, SEEK_END); /* New mails start with \nFrom ...., unless we're at the beginning of the mbox */ if (mboxlen == 0) newline = ""; /* If we're bouncing a message, claim it comes from MAILER-DAEMON */ sender = it->sender; if (strcmp(sender, "") == 0) sender = "MAILER-DAEMON"; if (fseek(it->mailf, 0, SEEK_SET) != 0) { syslog(LOG_NOTICE, "local delivery deferred: can not seek: %m"); goto out; } error = snprintf(line, sizeof(line), "%sFrom %s %s", newline, sender, ctime(&now)); if (error < 0 || (size_t)error >= sizeof(line)) { syslog(LOG_NOTICE, "local delivery deferred: can not write header: %m"); goto out; } if (write(mbox, line, error) != error) goto wrerror; while (!feof(it->mailf)) { if (fgets(line, sizeof(line), it->mailf) == NULL) break; linelen = strlen(line); if (linelen == 0 || line[linelen - 1] != '\n') { syslog(LOG_CRIT, "local delivery failed: corrupted queue file"); snprintf(errmsg, sizeof(errmsg), "corrupted queue file"); error = -1; goto chop; } /* * mboxro processing: * - escape lines that start with "From " with a > sign. * - be reversable by escaping lines that contain an arbitrary * number of > signs, followed by "From ", i.e. />*From / in regexp. * - strict mbox processing only requires escaping after empty lines, * yet most MUAs seem to relax this requirement and will treat any * line starting with "From " as the beginning of a new mail. */ if ((!MBOX_STRICT || hadnl) && strncmp(&line[strspn(line, ">")], "From ", 5) == 0) { const char *gt = ">"; if (write(mbox, gt, 1) != 1) goto wrerror; hadnl = 0; } else if (strcmp(line, "\n") == 0) { hadnl = 1; } else { hadnl = 0; } if ((size_t)write(mbox, line, linelen) != linelen) goto wrerror; } close(mbox); return (0); wrerror: syslog(LOG_ERR, "local delivery failed: write error: %m"); error = 1; chop: if (ftruncate(mbox, mboxlen) != 0) syslog(LOG_WARNING, "error recovering mbox `%s': %m", fn); out: close(mbox); return (error); } Index: projects/openssl111/contrib/dma/mail.c =================================================================== --- projects/openssl111/contrib/dma/mail.c (revision 338769) +++ projects/openssl111/contrib/dma/mail.c (revision 338770) @@ -1,491 +1,492 @@ /* * Copyright (c) 2008-2014, Simon Schubert <2@0x2c.org>. * Copyright (c) 2008 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by Simon Schubert <2@0x2c.org>. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of The DragonFly Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific, prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include +#include #include #include #include "dma.h" #define MAX_LINE_RFC822 1000 void bounce(struct qitem *it, const char *reason) { struct queue bounceq; char line[1000]; size_t pos; int error; /* Don't bounce bounced mails */ if (it->sender[0] == 0) { syslog(LOG_INFO, "can not bounce a bounce message, discarding"); exit(EX_SOFTWARE); } bzero(&bounceq, sizeof(bounceq)); LIST_INIT(&bounceq.queue); bounceq.sender = ""; if (add_recp(&bounceq, it->sender, EXPAND_WILDCARD) != 0) goto fail; if (newspoolf(&bounceq) != 0) goto fail; syslog(LOG_ERR, "delivery failed, bouncing as %s", bounceq.id); setlogident("%s", bounceq.id); error = fprintf(bounceq.mailf, "Received: from MAILER-DAEMON\n" "\tid %s\n" "\tby %s (%s);\n" "\t%s\n" "X-Original-To: <%s>\n" "From: MAILER-DAEMON <>\n" "To: %s\n" "Subject: Mail delivery failed\n" "Message-Id: <%s@%s>\n" "Date: %s\n" "\n" "This is the %s at %s.\n" "\n" "There was an error delivering your mail to <%s>.\n" "\n" "%s\n" "\n" "%s\n" "\n", bounceq.id, hostname(), VERSION, rfc822date(), it->addr, it->sender, bounceq.id, hostname(), rfc822date(), VERSION, hostname(), it->addr, reason, config.features & FULLBOUNCE ? "Original message follows." : "Message headers follow."); if (error < 0) goto fail; if (fseek(it->mailf, 0, SEEK_SET) != 0) goto fail; if (config.features & FULLBOUNCE) { while ((pos = fread(line, 1, sizeof(line), it->mailf)) > 0) { if (fwrite(line, 1, pos, bounceq.mailf) != pos) goto fail; } } else { while (!feof(it->mailf)) { if (fgets(line, sizeof(line), it->mailf) == NULL) break; if (line[0] == '\n') break; if (fwrite(line, strlen(line), 1, bounceq.mailf) != 1) goto fail; } } if (linkspool(&bounceq) != 0) goto fail; /* bounce is safe */ delqueue(it); run_queue(&bounceq); /* NOTREACHED */ fail: syslog(LOG_CRIT, "error creating bounce: %m"); delqueue(it); exit(EX_IOERR); } struct parse_state { char addr[1000]; int pos; enum { NONE = 0, START, MAIN, EOL, QUIT } state; int comment; int quote; int brackets; int esc; }; /* * Simplified RFC2822 header/address parsing. * We copy escapes and quoted strings directly, since * we have to pass them like this to the mail server anyways. * XXX local addresses will need treatment */ static int parse_addrs(struct parse_state *ps, char *s, struct queue *queue) { char *addr; again: switch (ps->state) { case NONE: return (-1); case START: /* init our data */ bzero(ps, sizeof(*ps)); /* skip over header name */ while (*s != ':') s++; s++; ps->state = MAIN; break; case MAIN: /* all fine */ break; case EOL: switch (*s) { case ' ': case '\t': s++; /* continue */ break; default: ps->state = QUIT; if (ps->pos != 0) goto newaddr; return (0); } case QUIT: return (0); } for (; *s != 0; s++) { if (ps->esc) { ps->esc = 0; switch (*s) { case '\r': case '\n': goto err; default: goto copy; } } if (ps->quote) { switch (*s) { case '"': ps->quote = 0; goto copy; case '\\': ps->esc = 1; goto copy; case '\r': case '\n': goto eol; default: goto copy; } } switch (*s) { case '(': ps->comment++; break; case ')': if (ps->comment) ps->comment--; else goto err; goto skip; case '"': ps->quote = 1; goto copy; case '\\': ps->esc = 1; goto copy; case '\r': case '\n': goto eol; } if (ps->comment) goto skip; switch (*s) { case ' ': case '\t': /* ignore whitespace */ goto skip; case '<': /* this is the real address now */ ps->brackets = 1; ps->pos = 0; goto skip; case '>': if (!ps->brackets) goto err; ps->brackets = 0; s++; goto newaddr; case ':': /* group - ignore */ ps->pos = 0; goto skip; case ',': case ';': /* * Next address, copy previous one. * However, we might be directly after * a
, or have two consecutive * commas. * Skip the comma unless there is * really something to copy. */ if (ps->pos == 0) goto skip; s++; goto newaddr; default: goto copy; } copy: if (ps->comment) goto skip; if (ps->pos + 1 == sizeof(ps->addr)) goto err; ps->addr[ps->pos++] = *s; skip: ; } eol: ps->state = EOL; return (0); err: ps->state = QUIT; return (-1); newaddr: ps->addr[ps->pos] = 0; ps->pos = 0; addr = strdup(ps->addr); if (addr == NULL) errlog(EX_SOFTWARE, "strdup"); if (add_recp(queue, addr, EXPAND_WILDCARD) != 0) errlogx(EX_DATAERR, "invalid recipient `%s'", addr); goto again; } static int writeline(struct queue *queue, const char *line, ssize_t linelen) { ssize_t len; while (linelen > 0) { len = linelen; if (linelen > MAX_LINE_RFC822) { len = MAX_LINE_RFC822 - 10; } if (fwrite(line, len, 1, queue->mailf) != 1) return (-1); if (linelen <= MAX_LINE_RFC822) break; if (fwrite("\n", 1, 1, queue->mailf) != 1) return (-1); line += MAX_LINE_RFC822 - 10; linelen = strlen(line); } return (0); } int readmail(struct queue *queue, int nodot, int recp_from_header) { struct parse_state parse_state; char *line = NULL; ssize_t linelen; size_t linecap = 0; char newline[MAX_LINE_RFC822]; size_t error; int had_headers = 0; int had_from = 0; int had_messagid = 0; int had_date = 0; int nocopy = 0; int ret = -1; parse_state.state = NONE; error = fprintf(queue->mailf, "Received: from %s (uid %d)\n" "\t(envelope-from %s)\n" "\tid %s\n" "\tby %s (%s);\n" "\t%s\n", username, useruid, queue->sender, queue->id, hostname(), VERSION, rfc822date()); if ((ssize_t)error < 0) return (-1); while (!feof(stdin)) { newline[0] = '\0'; if ((linelen = getline(&line, &linecap, stdin)) <= 0) break; if (!had_headers) { if (linelen > MAX_LINE_RFC822) { /* XXX also split headers */ errlogx(EX_DATAERR, "bad mail input format:" " from %s (uid %d) (envelope-from %s)", username, useruid, queue->sender); } /* * Unless this is a continuation, switch of * the Bcc: nocopy flag. */ if (!(line[0] == ' ' || line[0] == '\t')) nocopy = 0; if (strprefixcmp(line, "Date:") == 0) had_date = 1; else if (strprefixcmp(line, "Message-Id:") == 0) had_messagid = 1; else if (strprefixcmp(line, "From:") == 0) had_from = 1; else if (strprefixcmp(line, "Bcc:") == 0) nocopy = 1; if (parse_state.state != NONE) { if (parse_addrs(&parse_state, line, queue) < 0) { errlogx(EX_DATAERR, "invalid address in header\n"); /* NOTREACHED */ } } if (recp_from_header && ( strprefixcmp(line, "To:") == 0 || strprefixcmp(line, "Cc:") == 0 || strprefixcmp(line, "Bcc:") == 0)) { parse_state.state = START; if (parse_addrs(&parse_state, line, queue) < 0) { errlogx(EX_DATAERR, "invalid address in header\n"); /* NOTREACHED */ } } } if (strcmp(line, "\n") == 0 && !had_headers) { had_headers = 1; while (!had_date || !had_messagid || !had_from) { if (!had_date) { had_date = 1; snprintf(newline, sizeof(newline), "Date: %s\n", rfc822date()); } else if (!had_messagid) { /* XXX msgid, assign earlier and log? */ had_messagid = 1; snprintf(newline, sizeof(newline), "Message-Id: <%"PRIxMAX".%s.%"PRIxMAX"@%s>\n", (uintmax_t)time(NULL), queue->id, (uintmax_t)random(), hostname()); } else if (!had_from) { had_from = 1; snprintf(newline, sizeof(newline), "From: <%s>\n", queue->sender); } if (fwrite(newline, strlen(newline), 1, queue->mailf) != 1) goto fail; } strlcpy(newline, "\n", sizeof(newline)); } if (!nodot && linelen == 2 && line[0] == '.') break; if (!nocopy) { if (newline[0]) { if (fwrite(newline, strlen(newline), 1, queue->mailf) != 1) goto fail; } else { if (writeline(queue, line, linelen) != 0) goto fail; } } } ret = 0; fail: free(line); return (ret); } Index: projects/openssl111/contrib/dma/net.c =================================================================== --- projects/openssl111/contrib/dma/net.c (revision 338769) +++ projects/openssl111/contrib/dma/net.c (revision 338770) @@ -1,550 +1,551 @@ /* * Copyright (c) 2008-2014, Simon Schubert <2@0x2c.org>. * Copyright (c) 2008 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by Matthias Schmidt , University of Marburg, * Germany. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of The DragonFly Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific, prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "dfcompat.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include #include #include #include "dma.h" char neterr[ERRMSG_SIZE]; char * ssl_errstr(void) { long oerr, nerr; oerr = 0; while ((nerr = ERR_get_error()) != 0) oerr = nerr; return (ERR_error_string(oerr, NULL)); } ssize_t send_remote_command(int fd, const char* fmt, ...) { va_list va; char cmd[4096]; size_t len, pos; int s; ssize_t n; va_start(va, fmt); s = vsnprintf(cmd, sizeof(cmd) - 2, fmt, va); va_end(va); if (s == sizeof(cmd) - 2 || s < 0) { strcpy(neterr, "Internal error: oversized command string"); return (-1); } /* We *know* there are at least two more bytes available */ strcat(cmd, "\r\n"); len = strlen(cmd); if (((config.features & SECURETRANS) != 0) && ((config.features & NOSSL) == 0)) { while ((s = SSL_write(config.ssl, (const char*)cmd, len)) <= 0) { s = SSL_get_error(config.ssl, s); if (s != SSL_ERROR_WANT_READ && s != SSL_ERROR_WANT_WRITE) { strncpy(neterr, ssl_errstr(), sizeof(neterr)); return (-1); } } } else { pos = 0; while (pos < len) { n = write(fd, cmd + pos, len - pos); if (n < 0) return (-1); pos += n; } } return (len); } int read_remote(int fd, int extbufsize, char *extbuf) { ssize_t rlen = 0; size_t pos, len, copysize; char buff[BUF_SIZE]; int done = 0, status = 0, status_running = 0, extbufpos = 0; enum { parse_status, parse_spacedash, parse_rest } parsestate; if (do_timeout(CON_TIMEOUT, 1) != 0) { snprintf(neterr, sizeof(neterr), "Timeout reached"); return (-1); } /* * Remote reading code from femail.c written by Henning Brauer of * OpenBSD and released under a BSD style license. */ len = 0; pos = 0; parsestate = parse_status; neterr[0] = 0; while (!(done && parsestate == parse_status)) { rlen = 0; if (pos == 0 || (pos > 0 && memchr(buff + pos, '\n', len - pos) == NULL)) { memmove(buff, buff + pos, len - pos); len -= pos; pos = 0; if (((config.features & SECURETRANS) != 0) && (config.features & NOSSL) == 0) { if ((rlen = SSL_read(config.ssl, buff + len, sizeof(buff) - len)) == -1) { strncpy(neterr, ssl_errstr(), sizeof(neterr)); goto error; } } else { if ((rlen = read(fd, buff + len, sizeof(buff) - len)) == -1) { strncpy(neterr, strerror(errno), sizeof(neterr)); goto error; } } len += rlen; copysize = sizeof(neterr) - strlen(neterr) - 1; if (copysize > len) copysize = len; strncat(neterr, buff, copysize); } /* * If there is an external buffer with a size bigger than zero * and as long as there is space in the external buffer and * there are new characters read from the mailserver * copy them to the external buffer */ if (extbufpos <= (extbufsize - 1) && rlen > 0 && extbufsize > 0 && extbuf != NULL) { /* do not write over the bounds of the buffer */ if(extbufpos + rlen > (extbufsize - 1)) { rlen = extbufsize - extbufpos; } memcpy(extbuf + extbufpos, buff + len - rlen, rlen); extbufpos += rlen; } if (pos == len) continue; switch (parsestate) { case parse_status: for (; pos < len; pos++) { if (isdigit(buff[pos])) { status_running = status_running * 10 + (buff[pos] - '0'); } else { status = status_running; status_running = 0; parsestate = parse_spacedash; break; } } continue; case parse_spacedash: switch (buff[pos]) { case ' ': done = 1; break; case '-': /* ignore */ /* XXX read capabilities */ break; default: strcpy(neterr, "invalid syntax in reply from server"); goto error; } pos++; parsestate = parse_rest; continue; case parse_rest: /* skip up to \n */ for (; pos < len; pos++) { if (buff[pos] == '\n') { pos++; parsestate = parse_status; break; } } } } do_timeout(0, 0); /* chop off trailing newlines */ while (neterr[0] != 0 && strchr("\r\n", neterr[strlen(neterr) - 1]) != 0) neterr[strlen(neterr) - 1] = 0; return (status/100); error: do_timeout(0, 0); return (-1); } /* * Handle SMTP authentication */ static int smtp_login(int fd, char *login, char* password) { char *temp; int len, res = 0; res = smtp_auth_md5(fd, login, password); if (res == 0) { return (0); } else if (res == -2) { /* * If the return code is -2, then then the login attempt failed, * do not try other login mechanisms */ return (1); } if ((config.features & INSECURE) != 0 || (config.features & SECURETRANS) != 0) { /* Send AUTH command according to RFC 2554 */ send_remote_command(fd, "AUTH LOGIN"); if (read_remote(fd, 0, NULL) != 3) { syslog(LOG_NOTICE, "remote delivery deferred:" " AUTH login not available: %s", neterr); return (1); } len = base64_encode(login, strlen(login), &temp); if (len < 0) { encerr: syslog(LOG_ERR, "can not encode auth reply: %m"); return (1); } send_remote_command(fd, "%s", temp); free(temp); res = read_remote(fd, 0, NULL); if (res != 3) { syslog(LOG_NOTICE, "remote delivery %s: AUTH login failed: %s", res == 5 ? "failed" : "deferred", neterr); return (res == 5 ? -1 : 1); } len = base64_encode(password, strlen(password), &temp); if (len < 0) goto encerr; send_remote_command(fd, "%s", temp); free(temp); res = read_remote(fd, 0, NULL); if (res != 2) { syslog(LOG_NOTICE, "remote delivery %s: Authentication failed: %s", res == 5 ? "failed" : "deferred", neterr); return (res == 5 ? -1 : 1); } } else { syslog(LOG_WARNING, "non-encrypted SMTP login is disabled in config, so skipping it. "); return (1); } return (0); } static int open_connection(struct mx_hostentry *h) { int fd; syslog(LOG_INFO, "trying remote delivery to %s [%s] pref %d", h->host, h->addr, h->pref); fd = socket(h->ai.ai_family, h->ai.ai_socktype, h->ai.ai_protocol); if (fd < 0) { syslog(LOG_INFO, "socket for %s [%s] failed: %m", h->host, h->addr); return (-1); } if (connect(fd, (struct sockaddr *)&h->sa, h->ai.ai_addrlen) < 0) { syslog(LOG_INFO, "connect to %s [%s] failed: %m", h->host, h->addr); close(fd); return (-1); } return (fd); } static void close_connection(int fd) { if (config.ssl != NULL) { if (((config.features & SECURETRANS) != 0) && ((config.features & NOSSL) == 0)) SSL_shutdown(config.ssl); SSL_free(config.ssl); } close(fd); } static int deliver_to_host(struct qitem *it, struct mx_hostentry *host) { struct authuser *a; char line[1000]; size_t linelen; int fd, error = 0, do_auth = 0, res = 0; if (fseek(it->mailf, 0, SEEK_SET) != 0) { snprintf(errmsg, sizeof(errmsg), "can not seek: %s", strerror(errno)); return (-1); } fd = open_connection(host); if (fd < 0) return (1); #define READ_REMOTE_CHECK(c, exp) \ res = read_remote(fd, 0, NULL); \ if (res == 5) { \ syslog(LOG_ERR, "remote delivery to %s [%s] failed after %s: %s", \ host->host, host->addr, c, neterr); \ snprintf(errmsg, sizeof(errmsg), "%s [%s] did not like our %s:\n%s", \ host->host, host->addr, c, neterr); \ error = -1; \ goto out; \ } else if (res != exp) { \ syslog(LOG_NOTICE, "remote delivery deferred: %s [%s] failed after %s: %s", \ host->host, host->addr, c, neterr); \ error = 1; \ goto out; \ } /* Check first reply from remote host */ if ((config.features & SECURETRANS) == 0 || (config.features & STARTTLS) != 0) { config.features |= NOSSL; READ_REMOTE_CHECK("connect", 2); config.features &= ~NOSSL; } if ((config.features & SECURETRANS) != 0) { error = smtp_init_crypto(fd, config.features); if (error == 0) syslog(LOG_DEBUG, "SSL initialization successful"); else goto out; if ((config.features & STARTTLS) == 0) READ_REMOTE_CHECK("connect", 2); } /* XXX allow HELO fallback */ /* XXX record ESMTP keywords */ send_remote_command(fd, "EHLO %s", hostname()); READ_REMOTE_CHECK("EHLO", 2); /* * Use SMTP authentication if the user defined an entry for the remote * or smarthost */ SLIST_FOREACH(a, &authusers, next) { if (strcmp(a->host, host->host) == 0) { do_auth = 1; break; } } if (do_auth == 1) { /* * Check if the user wants plain text login without using * encryption. */ syslog(LOG_INFO, "using SMTP authentication for user %s", a->login); error = smtp_login(fd, a->login, a->password); if (error < 0) { syslog(LOG_ERR, "remote delivery failed:" " SMTP login failed: %m"); snprintf(errmsg, sizeof(errmsg), "SMTP login to %s failed", host->host); error = -1; goto out; } /* SMTP login is not available, so try without */ else if (error > 0) { syslog(LOG_WARNING, "SMTP login not available. Trying without."); } } /* XXX send ESMTP ENVID, RET (FULL/HDRS) and 8BITMIME */ send_remote_command(fd, "MAIL FROM:<%s>", it->sender); READ_REMOTE_CHECK("MAIL FROM", 2); /* XXX send ESMTP ORCPT */ send_remote_command(fd, "RCPT TO:<%s>", it->addr); READ_REMOTE_CHECK("RCPT TO", 2); send_remote_command(fd, "DATA"); READ_REMOTE_CHECK("DATA", 3); error = 0; while (!feof(it->mailf)) { if (fgets(line, sizeof(line), it->mailf) == NULL) break; linelen = strlen(line); if (linelen == 0 || line[linelen - 1] != '\n') { syslog(LOG_CRIT, "remote delivery failed: corrupted queue file"); snprintf(errmsg, sizeof(errmsg), "corrupted queue file"); error = -1; goto out; } /* Remove trailing \n's and escape leading dots */ trim_line(line); /* * If the first character is a dot, we escape it so the line * length increases */ if (line[0] == '.') linelen++; if (send_remote_command(fd, "%s", line) != (ssize_t)linelen+1) { syslog(LOG_NOTICE, "remote delivery deferred: write error"); error = 1; goto out; } } send_remote_command(fd, "."); READ_REMOTE_CHECK("final DATA", 2); send_remote_command(fd, "QUIT"); if (read_remote(fd, 0, NULL) != 2) syslog(LOG_INFO, "remote delivery succeeded but QUIT failed: %s", neterr); out: close_connection(fd); return (error); } int deliver_remote(struct qitem *it) { struct mx_hostentry *hosts, *h; const char *host; int port; int error = 1, smarthost = 0; port = SMTP_PORT; /* Smarthost support? */ if (config.smarthost != NULL) { host = config.smarthost; port = config.port; syslog(LOG_INFO, "using smarthost (%s:%i)", host, port); smarthost = 1; } else { host = strrchr(it->addr, '@'); /* Should not happen */ if (host == NULL) { snprintf(errmsg, sizeof(errmsg), "Internal error: badly formed address %s", it->addr); return(-1); } else { /* Step over the @ */ host++; } } error = dns_get_mx_list(host, port, &hosts, smarthost); if (error) { snprintf(errmsg, sizeof(errmsg), "DNS lookup failure: host %s not found", host); syslog(LOG_NOTICE, "remote delivery %s: DNS lookup failure: host %s not found", error < 0 ? "failed" : "deferred", host); return (error); } for (h = hosts; *h->host != 0; h++) { switch (deliver_to_host(it, h)) { case 0: /* success */ error = 0; goto out; case 1: /* temp failure */ error = 1; break; default: /* perm failure */ error = -1; goto out; } } out: free(hosts); return (error); } Index: projects/openssl111/contrib/dma/spool.c =================================================================== --- projects/openssl111/contrib/dma/spool.c (revision 338769) +++ projects/openssl111/contrib/dma/spool.c (revision 338770) @@ -1,441 +1,442 @@ /* * Copyright (c) 2008-2014, Simon Schubert <2@0x2c.org>. * Copyright (c) 2008 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by Simon Schubert <2@0x2c.org>. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of The DragonFly Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific, prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "dfcompat.h" #include #include #include #include #include #include #include #include #include +#include #include #include "dma.h" /* * Spool file format: * * 'Q'id files (queue): * Organized like an RFC822 header, field: value. Ignores unknown fields. * ID: id * Sender: envelope-from * Recipient: envelope-to * * 'M'id files (data): * mail data * * Each queue file needs to have a corresponding data file. * One data file might be shared by linking it several times. * * Queue ids are unique, formed from the inode of the data file * and a unique identifier. */ int newspoolf(struct queue *queue) { char fn[PATH_MAX+1]; struct stat st; struct stritem *t; int fd; if (snprintf(fn, sizeof(fn), "%s/%s", config.spooldir, "tmp_XXXXXXXXXX") <= 0) return (-1); fd = mkstemp(fn); if (fd < 0) return (-1); /* XXX group rights */ if (fchmod(fd, 0660) < 0) goto fail; if (flock(fd, LOCK_EX) == -1) goto fail; queue->tmpf = strdup(fn); if (queue->tmpf == NULL) goto fail; /* * Assign queue id */ if (fstat(fd, &st) != 0) goto fail; if (asprintf(&queue->id, "%"PRIxMAX, (uintmax_t)st.st_ino) < 0) goto fail; queue->mailf = fdopen(fd, "r+"); if (queue->mailf == NULL) goto fail; t = malloc(sizeof(*t)); if (t != NULL) { t->str = queue->tmpf; SLIST_INSERT_HEAD(&tmpfs, t, next); } return (0); fail: if (queue->mailf != NULL) fclose(queue->mailf); close(fd); unlink(fn); return (-1); } static int writequeuef(struct qitem *it) { int error; int queuefd; queuefd = open_locked(it->queuefn, O_CREAT|O_EXCL|O_RDWR, 0660); if (queuefd == -1) return (-1); if (fchmod(queuefd, 0660) < 0) return (-1); it->queuef = fdopen(queuefd, "w+"); if (it->queuef == NULL) return (-1); error = fprintf(it->queuef, "ID: %s\n" "Sender: %s\n" "Recipient: %s\n", it->queueid, it->sender, it->addr); if (error <= 0) return (-1); if (fflush(it->queuef) != 0 || fsync(fileno(it->queuef)) != 0) return (-1); return (0); } static struct qitem * readqueuef(struct queue *queue, char *queuefn) { char line[1000]; struct queue itmqueue; FILE *queuef = NULL; char *s; char *queueid = NULL, *sender = NULL, *addr = NULL; struct qitem *it = NULL; bzero(&itmqueue, sizeof(itmqueue)); LIST_INIT(&itmqueue.queue); queuef = fopen(queuefn, "r"); if (queuef == NULL) goto out; while (!feof(queuef)) { if (fgets(line, sizeof(line), queuef) == NULL || line[0] == 0) break; line[strlen(line) - 1] = 0; /* chop newline */ s = strchr(line, ':'); if (s == NULL) goto malformed; *s = 0; s++; while (isspace(*s)) s++; s = strdup(s); if (s == NULL) goto malformed; if (strcmp(line, "ID") == 0) { queueid = s; } else if (strcmp(line, "Sender") == 0) { sender = s; } else if (strcmp(line, "Recipient") == 0) { addr = s; } else { syslog(LOG_DEBUG, "ignoring unknown queue info `%s' in `%s'", line, queuefn); free(s); } } if (queueid == NULL || sender == NULL || addr == NULL || *queueid == 0 || *addr == 0) { malformed: errno = EINVAL; syslog(LOG_ERR, "malformed queue file `%s'", queuefn); goto out; } if (add_recp(&itmqueue, addr, 0) != 0) goto out; it = LIST_FIRST(&itmqueue.queue); it->sender = sender; sender = NULL; it->queueid = queueid; queueid = NULL; it->queuefn = queuefn; queuefn = NULL; LIST_INSERT_HEAD(&queue->queue, it, next); out: if (sender != NULL) free(sender); if (queueid != NULL) free(queueid); if (addr != NULL) free(addr); if (queuef != NULL) fclose(queuef); return (it); } int linkspool(struct queue *queue) { struct stat st; struct qitem *it; if (fflush(queue->mailf) != 0 || fsync(fileno(queue->mailf)) != 0) goto delfiles; syslog(LOG_INFO, "new mail from user=%s uid=%d envelope_from=<%s>", username, getuid(), queue->sender); LIST_FOREACH(it, &queue->queue, next) { if (asprintf(&it->queueid, "%s.%"PRIxPTR, queue->id, (uintptr_t)it) <= 0) goto delfiles; if (asprintf(&it->queuefn, "%s/Q%s", config.spooldir, it->queueid) <= 0) goto delfiles; if (asprintf(&it->mailfn, "%s/M%s", config.spooldir, it->queueid) <= 0) goto delfiles; /* Neither file may not exist yet */ if (stat(it->queuefn, &st) == 0 || stat(it->mailfn, &st) == 0) goto delfiles; if (writequeuef(it) != 0) goto delfiles; if (link(queue->tmpf, it->mailfn) != 0) goto delfiles; } LIST_FOREACH(it, &queue->queue, next) { syslog(LOG_INFO, "mail to=<%s> queued as %s", it->addr, it->queueid); } unlink(queue->tmpf); return (0); delfiles: LIST_FOREACH(it, &queue->queue, next) { unlink(it->mailfn); unlink(it->queuefn); } return (-1); } int load_queue(struct queue *queue) { struct stat sb; struct qitem *it; DIR *spooldir; struct dirent *de; char *queuefn; char *mailfn; bzero(queue, sizeof(*queue)); LIST_INIT(&queue->queue); spooldir = opendir(config.spooldir); if (spooldir == NULL) err(EX_NOINPUT, "reading queue"); while ((de = readdir(spooldir)) != NULL) { queuefn = NULL; mailfn = NULL; /* ignore non-queue files */ if (de->d_name[0] != 'Q') continue; if (asprintf(&queuefn, "%s/Q%s", config.spooldir, de->d_name + 1) < 0) goto fail; if (asprintf(&mailfn, "%s/M%s", config.spooldir, de->d_name + 1) < 0) goto fail; /* * Some file systems don't provide a de->d_type, so we have to * do an explicit stat on the queue file. * Move on if it turns out to be something else than a file. */ if (stat(queuefn, &sb) != 0) goto skip_item; if (!S_ISREG(sb.st_mode)) { errno = EINVAL; goto skip_item; } if (stat(mailfn, &sb) != 0) goto skip_item; it = readqueuef(queue, queuefn); if (it == NULL) goto skip_item; it->mailfn = mailfn; continue; skip_item: syslog(LOG_INFO, "could not pick up queue file: `%s'/`%s': %m", queuefn, mailfn); if (queuefn != NULL) free(queuefn); if (mailfn != NULL) free(mailfn); } closedir(spooldir); return (0); fail: return (-1); } void delqueue(struct qitem *it) { unlink(it->mailfn); unlink(it->queuefn); if (it->queuef != NULL) fclose(it->queuef); if (it->mailf != NULL) fclose(it->mailf); free(it); } int acquirespool(struct qitem *it) { int queuefd; if (it->queuef == NULL) { queuefd = open_locked(it->queuefn, O_RDWR|O_NONBLOCK); if (queuefd < 0) goto fail; it->queuef = fdopen(queuefd, "r+"); if (it->queuef == NULL) goto fail; } if (it->mailf == NULL) { it->mailf = fopen(it->mailfn, "r"); if (it->mailf == NULL) goto fail; } return (0); fail: if (errno == EWOULDBLOCK) return (1); syslog(LOG_INFO, "could not acquire queue file: %m"); return (-1); } void dropspool(struct queue *queue, struct qitem *keep) { struct qitem *it; LIST_FOREACH(it, &queue->queue, next) { if (it == keep) continue; if (it->queuef != NULL) fclose(it->queuef); if (it->mailf != NULL) fclose(it->mailf); } } int flushqueue_since(unsigned int period) { struct stat st; struct timeval now; char *flushfn = NULL; if (asprintf(&flushfn, "%s/%s", config.spooldir, SPOOL_FLUSHFILE) < 0) return (0); if (stat(flushfn, &st) < 0) { free(flushfn); return (0); } free(flushfn); flushfn = NULL; if (gettimeofday(&now, 0) != 0) return (0); /* Did the flush file get touched within the last period seconds? */ if (st.st_mtim.tv_sec + (int)period >= now.tv_sec) return (1); else return (0); } int flushqueue_signal(void) { char *flushfn = NULL; int fd; if (asprintf(&flushfn, "%s/%s", config.spooldir, SPOOL_FLUSHFILE) < 0) return (-1); fd = open(flushfn, O_CREAT|O_WRONLY|O_TRUNC, 0660); free(flushfn); if (fd < 0) { syslog(LOG_ERR, "could not open flush file: %m"); return (-1); } close(fd); return (0); } Index: projects/openssl111/contrib/dma/util.c =================================================================== --- projects/openssl111/contrib/dma/util.c (revision 338769) +++ projects/openssl111/contrib/dma/util.c (revision 338770) @@ -1,346 +1,347 @@ /* * Copyright (c) 2008-2014, Simon Schubert <2@0x2c.org>. * Copyright (c) 2008 The DragonFly Project. All rights reserved. * * This code is derived from software contributed to The DragonFly Project * by Simon Schubert <2@0x2c.org>. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of The DragonFly Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific, prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include #include #include #include #include #include #include #include #include #include +#include #include #include #include "dma.h" const char * hostname(void) { #ifndef HOST_NAME_MAX #define HOST_NAME_MAX 255 #endif static char name[HOST_NAME_MAX+1]; static int initialized = 0; char *s; if (initialized) return (name); if (config.mailname == NULL || !*config.mailname) goto local; if (config.mailname[0] == '/') { /* * If the mailname looks like an absolute path, * treat it as a file. */ FILE *fp; fp = fopen(config.mailname, "r"); if (fp == NULL) goto local; s = fgets(name, sizeof(name), fp); fclose(fp); if (s == NULL) goto local; for (s = name; *s != 0 && (isalnum(*s) || strchr("_.-", *s)); ++s) /* NOTHING */; *s = 0; if (!*name) goto local; initialized = 1; return (name); } else { snprintf(name, sizeof(name), "%s", config.mailname); initialized = 1; return (name); } local: if (gethostname(name, sizeof(name)) != 0) *name = 0; /* * gethostname() is allowed to truncate name without NUL-termination * and at the same time not return an error. */ name[sizeof(name) - 1] = 0; for (s = name; *s != 0 && (isalnum(*s) || strchr("_.-", *s)); ++s) /* NOTHING */; *s = 0; if (!*name) snprintf(name, sizeof(name), "unknown-hostname"); initialized = 1; return (name); } void setlogident(const char *fmt, ...) { static char tag[50]; snprintf(tag, sizeof(tag), "%s", logident_base); if (fmt != NULL) { va_list ap; char sufx[50]; va_start(ap, fmt); vsnprintf(sufx, sizeof(sufx), fmt, ap); va_end(ap); snprintf(tag, sizeof(tag), "%s[%s]", logident_base, sufx); } closelog(); openlog(tag, 0, LOG_MAIL); } void errlog(int exitcode, const char *fmt, ...) { int oerrno = errno; va_list ap; char outs[ERRMSG_SIZE]; outs[0] = 0; if (fmt != NULL) { va_start(ap, fmt); vsnprintf(outs, sizeof(outs), fmt, ap); va_end(ap); } errno = oerrno; if (*outs != 0) { syslog(LOG_ERR, "%s: %m", outs); fprintf(stderr, "%s: %s: %s\n", getprogname(), outs, strerror(oerrno)); } else { syslog(LOG_ERR, "%m"); fprintf(stderr, "%s: %s\n", getprogname(), strerror(oerrno)); } exit(exitcode); } void errlogx(int exitcode, const char *fmt, ...) { va_list ap; char outs[ERRMSG_SIZE]; outs[0] = 0; if (fmt != NULL) { va_start(ap, fmt); vsnprintf(outs, sizeof(outs), fmt, ap); va_end(ap); } if (*outs != 0) { syslog(LOG_ERR, "%s", outs); fprintf(stderr, "%s: %s\n", getprogname(), outs); } else { syslog(LOG_ERR, "Unknown error"); fprintf(stderr, "%s: Unknown error\n", getprogname()); } exit(exitcode); } static int check_username(const char *name, uid_t ckuid) { struct passwd *pwd; if (name == NULL) return (0); pwd = getpwnam(name); if (pwd == NULL || pwd->pw_uid != ckuid) return (0); snprintf(username, sizeof(username), "%s", name); return (1); } void set_username(void) { struct passwd *pwd; useruid = getuid(); if (check_username(getlogin(), useruid)) return; if (check_username(getenv("LOGNAME"), useruid)) return; if (check_username(getenv("USER"), useruid)) return; pwd = getpwuid(useruid); if (pwd != NULL && pwd->pw_name != NULL && pwd->pw_name[0] != '\0') { if (check_username(pwd->pw_name, useruid)) return; } snprintf(username, sizeof(username), "uid=%ld", (long)useruid); } void deltmp(void) { struct stritem *t; SLIST_FOREACH(t, &tmpfs, next) { unlink(t->str); } } static sigjmp_buf sigbuf; static int sigbuf_valid; static void sigalrm_handler(int signo) { (void)signo; /* so that gcc doesn't complain */ if (sigbuf_valid) siglongjmp(sigbuf, 1); } int do_timeout(int timeout, int dojmp) { struct sigaction act; int ret = 0; sigemptyset(&act.sa_mask); act.sa_flags = 0; if (timeout) { act.sa_handler = sigalrm_handler; if (sigaction(SIGALRM, &act, NULL) != 0) syslog(LOG_WARNING, "can not set signal handler: %m"); if (dojmp) { ret = sigsetjmp(sigbuf, 1); if (ret) goto disable; /* else just programmed */ sigbuf_valid = 1; } alarm(timeout); } else { disable: alarm(0); act.sa_handler = SIG_IGN; if (sigaction(SIGALRM, &act, NULL) != 0) syslog(LOG_WARNING, "can not remove signal handler: %m"); sigbuf_valid = 0; } return (ret); } int open_locked(const char *fname, int flags, ...) { int mode = 0; if (flags & O_CREAT) { va_list ap; va_start(ap, flags); mode = va_arg(ap, int); va_end(ap); } #ifndef O_EXLOCK int fd, save_errno; fd = open(fname, flags, mode); if (fd < 0) return(fd); if (flock(fd, LOCK_EX|((flags & O_NONBLOCK)? LOCK_NB: 0)) < 0) { save_errno = errno; close(fd); errno = save_errno; return(-1); } return(fd); #else return(open(fname, flags|O_EXLOCK, mode)); #endif } char * rfc822date(void) { static char str[50]; size_t error; time_t now; now = time(NULL); error = strftime(str, sizeof(str), "%a, %d %b %Y %T %z", localtime(&now)); if (error == 0) strcpy(str, "(date fail)"); return (str); } int strprefixcmp(const char *str, const char *prefix) { return (strncasecmp(str, prefix, strlen(prefix))); } void init_random(void) { unsigned int seed; int rf; rf = open("/dev/urandom", O_RDONLY); if (rf == -1) rf = open("/dev/random", O_RDONLY); if (!(rf != -1 && read(rf, &seed, sizeof(seed)) == sizeof(seed))) seed = (time(NULL) ^ getpid()) + (uintptr_t)&seed; srandom(seed); if (rf != -1) close(rf); }