"Fossies" - the Fresh Open Source Software Archive

Member "hylafax-7.0.2/faxd/sslfax.c++" (6 Dec 2019, 27030 Bytes) of package /linux/misc/hylafax-7.0.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 /*
    2  * Although highly modified and altered, the code in this file was originally
    3  * derived from sources taken from (1) GitHub user, "mrwicks", on 9 Oct 2018.
    4  * That source, itself, was derived from work by "Amlendra" published at
    5  * Aticleworld on 21 May 2017 (2).  That work, then, references programs (3)
    6  * Copyright (c) 2000 Sean Walton and Macmillan Publishers (The "Linux Socket
    7  * Programming" book) and are licensed under the GPL.
    8  *
    9  * 1. https://github.com/mrwicks/miscellaneous/tree/master/tls_1.2_example
   10  * 2. https://aticleworld.com/ssl-server-client-using-openssl-in-c/
   11  * 3. http://www.cs.utah.edu/~swalton/listings/sockets/programs/
   12  *
   13  * It is, therefore, presumed that this work is either under the public
   14  * domain or is licensed under the GPL.  A copy of the GPL is as follows...
   15  *
   16  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
   17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
   20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   26  * SUCH DAMAGE.
   27  */
   28 
   29 #include "config.h"
   30 #if defined(HAVE_SSL)
   31 
   32 #include <sys/time.h>
   33 #include "sslfax.h"
   34 #include "Sys.h"
   35 
   36 timeval currentTime() {
   37     timeval curTime;
   38     gettimeofday(&curTime, 0);
   39     return curTime;
   40 }
   41 
   42 const long ONE_SECOND = 1000000;
   43 
   44 timeval operator-(timeval src1, timeval src2) {
   45     timeval delta;
   46     delta.tv_sec = src1.tv_sec - src2.tv_sec;
   47     delta.tv_usec = src1.tv_usec - src2.tv_usec;
   48     if (delta.tv_usec < 0) {
   49     delta.tv_usec += ONE_SECOND;
   50     delta.tv_sec--;
   51     } else if (delta.tv_usec >= ONE_SECOND) {
   52     delta.tv_usec -= ONE_SECOND;
   53     delta.tv_sec++;
   54     }
   55     return delta;
   56 }
   57 
   58 SSL_CTX* InitServerCTX (void)
   59 {
   60     const SSL_METHOD *method;
   61     SSL_CTX *ctx;
   62 
   63     OpenSSL_add_all_algorithms ();     /* load & register all cryptos, etc. */
   64     SSL_load_error_strings ();         /* load all error messages */
   65 #ifdef HAVE_FLEXSSL
   66     method = TLS_server_method (); /* create new server-method instance */
   67 #else
   68     method = TLSv1_2_server_method (); /* create new server-method instance */
   69 #endif
   70     ctx = SSL_CTX_new (method);        /* create new context from method */
   71     return ctx;
   72 }
   73 
   74 fxStr LoadCertificates (SSL_CTX* ctx, const char* CertFile, const char* KeyFile)
   75 {
   76     /* set the local certificate from CertFile */
   77     if (SSL_CTX_use_certificate_file (ctx, CertFile, SSL_FILETYPE_PEM) <= 0) {
   78     return (fxStr::format("There was a problem with the certificate file \"%s\".", (const char*) CertFile));
   79     }
   80 
   81     /* set the private key from KeyFile (may be the same as CertFile) */
   82     if (SSL_CTX_use_PrivateKey_file (ctx, KeyFile, SSL_FILETYPE_PEM) <= 0) {
   83     return (fxStr::format("There was a problem with the private key in the certificate file \"%s\".", (const char*) KeyFile));
   84     }
   85 
   86     /* verify private key */
   87     if (!SSL_CTX_check_private_key (ctx)) {
   88     return (fxStr("Private key does not match the public certificate."));
   89     }
   90     return(fxStr(""));
   91 }
   92 
   93 // Create the SSL socket and intialize the socket address structure
   94 int OpenListener (int port, fxStr& emsg)
   95 {
   96     int sd;
   97     struct sockaddr_in addr;
   98 
   99     sd = socket (PF_INET, SOCK_STREAM, 0);
  100     bzero (&addr, sizeof (addr));
  101     addr.sin_family = AF_INET;
  102     addr.sin_port = htons (port);
  103     addr.sin_addr.s_addr = INADDR_ANY;
  104     if (bind (sd, (struct sockaddr*)&addr, sizeof (addr)) != 0) {
  105     emsg = fxStr::format("Can't bind port %d: %s", port, strerror(errno));
  106     return 0;
  107     }
  108     if (listen (sd, 10) != 0) {
  109     emsg = fxStr::format("Can't configure listening port %d.", port);
  110     return 0;
  111     }
  112     return sd;
  113 }
  114 
  115 fxStr ShowCerts (SSL* ssl)
  116 {
  117     fxStr msg;
  118     X509 *cert;
  119     cert = SSL_get_peer_certificate (ssl); /* get the server's certificate */
  120     if (cert != NULL) {
  121     msg = fxStr::format("Server certificates: Subject: \"%s\", Issuer: \"%s\"",
  122         X509_NAME_oneline (X509_get_subject_name (cert), 0, 0),
  123         X509_NAME_oneline (X509_get_issuer_name (cert), 0, 0));
  124     X509_free (cert);  /* free the malloc'ed certificate copy */
  125     } else {
  126     msg = "Info: No client certificates configured.";
  127     }
  128     return msg;
  129 }
  130 
  131 int OpenConnection(const char *hostname, uint16_t port, timeval start, long ms, fxStr& emsg)
  132 {
  133     int sd;
  134     struct hostent *host;
  135     struct sockaddr_in addr;
  136 
  137     if ((host = gethostbyname(hostname)) == NULL) {
  138     emsg = fxStr::format("Problem with resolving host \"%s\".", hostname);
  139     return 0;
  140     }
  141     sd = socket(PF_INET, SOCK_STREAM, 0);
  142     if (fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) | O_NONBLOCK) == -1) {
  143     emsg = "Unable to set SSL Fax socket to non-blocking.";
  144     return 0;
  145     }
  146     bzero (&addr, sizeof (addr));
  147     addr.sin_family = AF_INET;
  148     addr.sin_port = htons (port);
  149     addr.sin_addr.s_addr = * (long*) (host->h_addr);
  150 
  151     if (connect(sd, (struct sockaddr*)&addr, sizeof (addr)) != 0) {
  152     if (errno == EINPROGRESS) {
  153         /* Now we wait 3 seconds client to finish the connect. */
  154         fd_set sfd;
  155         FD_ZERO(&sfd);
  156         FD_SET(sd, &sfd);
  157         struct timeval tv;
  158         tv.tv_sec = (int) ms / 1000;
  159         tv.tv_usec = (ms % 1000)*1000;
  160         tv = tv - (currentTime() - start);
  161 #if CONFIG_BADSELECTPROTO
  162         if (!select(sd+1, NULL, (int*) &sfd, NULL, &tv)) {
  163 #else
  164         if (!select(sd+1, NULL, &sfd, NULL, &tv)) {
  165 #endif
  166         close (sd);
  167         emsg = "Timeout waiting for SSL Fax connect completion.";
  168         return 0;
  169         } else {
  170         int code;
  171         socklen_t codelen = sizeof(code);
  172         if (!getsockopt(sd, SOL_SOCKET, SO_ERROR, &code, &codelen)) {
  173             if (!code) {
  174             // connect completed
  175             return sd;
  176             } else {
  177             emsg = fxStr::format("SSL Fax connection failed.  Error: %s", strerror(code));
  178             close(sd);
  179             return 0;
  180             }
  181         } else {
  182             close(sd);
  183             emsg = "Unable to query the SSL Fax connection status.";
  184             return 0;
  185         }
  186         }
  187     }
  188     emsg = fxStr::format("Unable to connect to SSL Fax receiver \"%s\" at port %d (%s)", hostname, port, strerror(errno));
  189     close (sd);
  190     return 0;
  191     }
  192     return sd;
  193 }
  194 
  195 SSL_CTX* InitCTX (void)
  196 {
  197     const SSL_METHOD *method;
  198     SSL_CTX *ctx;
  199 
  200     OpenSSL_add_all_algorithms ();     /* Load cryptos, et.al. */
  201     SSL_load_error_strings ();         /* Bring in and register error messages */
  202 #ifdef HAVE_FLEXSSL
  203     method = TLS_client_method (); /* Create new client-method instance */
  204 #else
  205     method = TLSv1_2_client_method (); /* Create new client-method instance */
  206 #endif
  207     ctx = SSL_CTX_new (method);        /* Create new context */
  208     return ctx;
  209 }
  210 
  211 char *ssl_err_string (void)
  212 {
  213     BIO *bio = BIO_new (BIO_s_mem ());
  214     ERR_print_errors (bio);
  215     char *buf = NULL;
  216     size_t len = BIO_get_mem_data (bio, &buf);
  217     char *ret = (char *) calloc (1, 1 + len);
  218     if (ret) memcpy (ret, buf, len);
  219     BIO_free (bio);
  220     return ret;
  221 }
  222 
  223 /*
  224  * About serverAddress and clientAddress...
  225  *
  226  * A port number for the client is meaningless.  However, for the
  227  * server the port number is essential.  IP address notation with
  228  * port numbers is substantially different between IPv4 and IPv6.
  229  * An IPv4 address with port will be given as "192.168.0.1:8081".
  230  * However, that same address with IPv6 will be (per RFC3986)
  231  * "[0:0:0:0:0:ffff:c0a8:1]:8081".
  232  *
  233  * We'll therefore necessarily distinguish between IPv6 and IPv4
  234  * in a serverAddress by the presence of brackets.  However, the
  235  * client address may not have brackets at all and must, therefore,
  236  * be understood to be IPv4 or IPv6 through use of inet_pton.
  237  */
  238 int SSLFax::getAddressFamily(fxStr& address)
  239 {
  240     char buf[16];
  241     u_int pos1 = address.next(0, '[');
  242     if (pos1 < address.length()) {
  243     // This looks like a bracketed IPv6 address (likely followed by the port number).
  244     u_int pos2 = address.next(pos1, ']');
  245     if (pos2 < address.length()) {
  246         address.remove(pos2, address.length()-pos2);
  247         if (address.length() > pos1) address.remove(0, pos1+1);
  248     }
  249     } else {
  250     pos1 = address.next(0, ':');
  251     if (address.length() > pos1) {
  252         u_int pos2 = address.next(pos1+1, ':');
  253         if (pos2 == address.length()) {
  254         // This looks like an IPv4 address with the port number specified.
  255         address.remove(pos1, address.length()-pos1);
  256         }
  257     }
  258     }
  259     if (inet_pton(AF_INET, (const char*) address, buf)) {
  260     return AF_INET;
  261     } else if (inet_pton(AF_INET6, (const char*) address, buf)) {
  262     return AF_INET6;
  263     }
  264     return -1;
  265 }
  266 
  267 int SSLFax::pending(SSLFaxProcess& sfp)
  268 {
  269     return (SSL_pending(sfp.ssl));
  270 }
  271 
  272 int SSLFax::read(SSLFaxProcess& sfp, void *buf, size_t count, int modemFd, long ms)
  273 {
  274     /*
  275      * We cannot just use select() on the socket to see if there is data waiting
  276      * to be read because the SSL encryption and decryption operates somewhat
  277      * independently of the socket activity. Likewise SSL_pending() will not
  278      * help us here as it only tells us about any data already in the buffer.
  279      * There really is no way around just calling SSL_read() and letting it
  280      * work its magic.  That is why we have it set to non-blocking I/O and are
  281      * prepared to then use select() if it returns an error indicating
  282      * SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE.
  283      *
  284      * With non-blocking sockets, SSL_ERROR_WANT_READ means "wait for the socket
  285      * to be readable, then call this function again."; conversely,
  286      * SSL_ERROR_WANT_WRITE means "wait for the socket to be writeable, then
  287      * call this function again.".
  288      *
  289      * We do this same thing with SSL_connect() and SSL_accept(), also.
  290      *
  291      * In the event that we do turn to a select() then here we also monitor the
  292      * modem for activity, since that would indicate failure of the SSL Fax
  293      * communication.
  294      *
  295      * The special modemFd value of "0" tells us to not monitor the modem.
  296      * This is necessary because we can't select() a modem file descriptor if
  297      * it's at an EOF (it will always be readable).  The modem file descriptor
  298      * will be at an EOF if it is in command mode after an "OK" after a command
  299      * completed.  We can only select() it when we're waiting for a response.
  300      */
  301 
  302 
  303     int sslfd = sfp.client ? sfp.client : sfp.server;
  304 
  305     struct timeval start = currentTime();
  306     int cerror;
  307     int ret;
  308     do {
  309     cerror = 0;
  310     ret = SSL_read(sfp.ssl, buf, count);
  311     if (ret <= 0) {
  312         cerror = SSL_get_error(sfp.ssl, ret);
  313         if (cerror == SSL_ERROR_WANT_READ || cerror == SSL_ERROR_WANT_WRITE) {
  314         int selret;
  315         fd_set rfds;
  316         FD_ZERO(&rfds);
  317         if (modemFd) FD_SET(modemFd, &rfds);
  318         struct timeval tv;
  319         tv.tv_sec = (int) ms / 1000;
  320         tv.tv_usec = (ms % 1000)*1000;
  321         tv = tv - (currentTime() - start);
  322         if (cerror == SSL_ERROR_WANT_READ) {    // wait for the socket to be readable
  323             FD_SET(sslfd, &rfds);
  324 #if CONFIG_BADSELECTPROTO
  325             selret = select((modemFd > sslfd) ? modemFd+1 : sslfd+1, (int*) &rfds, NULL, NULL, &tv);
  326 #else
  327             selret = select((modemFd > sslfd) ? modemFd+1 : sslfd+1, &rfds, NULL, NULL, &tv);
  328 #endif
  329         } else {    // SSL_ERROR_WANT_WRITE, wait for the socket to be writable
  330             fd_set wfds;
  331             FD_ZERO(&wfds);
  332             FD_SET(sslfd, &wfds);
  333 #if CONFIG_BADSELECTPROTO
  334             selret = select((modemFd > sslfd) ? modemFd+1 : sslfd+1, (int*) &rfds, (int*) &wfds, NULL, &tv);
  335 #else
  336             selret = select((modemFd > sslfd) ? modemFd+1 : sslfd+1, &rfds, &wfds, NULL, &tv);
  337 #endif
  338         }
  339         if (!selret) {
  340             sfp.emsg = fxStr::format("Timeout waiting for SSL Fax read (wanting to %s).", (cerror == SSL_ERROR_WANT_READ ? "read" : "write"));
  341             cleanup(sfp);
  342             return (0);
  343         } else if (selret < 0) {
  344             sfp.emsg = fxStr::format("Error waiting for SSL Fax read (wanting to %s): %s", (cerror == SSL_ERROR_WANT_READ ? "read" : "write"), strerror(errno));
  345             cleanup(sfp);
  346             return (0);
  347         }
  348         if (modemFd && FD_ISSET(modemFd, &rfds)) {
  349             // The modem got a signal.  This probably means that SSL Fax is not happening.
  350             sfp.emsg = "Modem has data when waiting for SSL Fax read.  Terminating SSL Fax.";
  351             cleanup(sfp);
  352             return (-1);
  353         }
  354         }
  355     }
  356     } while (cerror == SSL_ERROR_WANT_READ || cerror == SSL_ERROR_WANT_WRITE);
  357     if (ret <= 0) {
  358     if (cerror == SSL_ERROR_SYSCALL) {
  359         sfp.emsg = fxStr::format("Unable to read from SSL Fax connection (syscall).  Error %d: %s", ret, strerror(ret));
  360     } else {
  361         sfp.emsg = fxStr::format("Unable to read from SSL Fax connection.  Error %d: %s", cerror, ssl_err_string());
  362     }
  363     cleanup(sfp);
  364     return (-2);
  365     }
  366     return (ret);
  367 }
  368 
  369 int SSLFax::write(SSLFaxProcess& sfp, const u_char *buf, u_int count, const u_char* bitrev, int modemFd, long ms, bool filter)
  370 {
  371     /*
  372      * Similar approach here as with read() above; however...
  373      *
  374      * Because SSL Fax doesn't use carrier loss as a signal it uses
  375      * <DLE><ETX> as an end-of-data signal.  Therefore, we're required
  376      * here to "filter" DLEs (by doubling them) except for the end-of-
  377      * data signal; the receiver will be required to "un-filter" them
  378      * (by removing doubles and watching for the end-of-data signal).
  379      * So, we process buf one byte at a time.
  380      */
  381     u_int pos;
  382     bool isDLE = false;
  383     struct timeval start = currentTime();
  384     int cerror;
  385     int ret = 0;
  386     int sslfd = sfp.client ? sfp.client : sfp.server;
  387     for (pos = 0; pos < count; pos++) {
  388     do {
  389         cerror = 0;
  390         ret = SSL_write(sfp.ssl, &bitrev[buf[pos]], 1);
  391         if (ret <= 0) {
  392         cerror = SSL_get_error(sfp.ssl, ret);
  393         if (cerror == SSL_ERROR_WANT_READ || cerror == SSL_ERROR_WANT_WRITE) {
  394             int selret;
  395             fd_set rfds;
  396             FD_ZERO(&rfds);
  397             if (modemFd) FD_SET(modemFd, &rfds);
  398             struct timeval tv;
  399             tv.tv_sec = (int) ms / 1000;
  400             tv.tv_usec = (ms % 1000)*1000;
  401             tv = tv - (currentTime() - start);
  402             if (cerror == SSL_ERROR_WANT_READ) {    // wait for the socket to be readable
  403             FD_SET(sslfd, &rfds);
  404 #if CONFIG_BADSELECTPROTO
  405             selret = select((modemFd > sslfd) ? modemFd+1 : sslfd+1, (int*) &rfds, NULL, NULL, &tv);
  406 #else
  407             selret = select((modemFd > sslfd) ? modemFd+1 : sslfd+1, &rfds, NULL, NULL, &tv);
  408 #endif
  409             } else {    // SSL_ERROR_WANT_WRITE, wait for the socket to be writable
  410             fd_set wfds;
  411             FD_ZERO(&wfds);
  412             FD_SET(sslfd, &wfds);
  413 #if CONFIG_BADSELECTPROTO
  414             selret = select((modemFd > sslfd) ? modemFd+1 : sslfd+1, (int*) &rfds, (int*) &wfds, NULL, &tv);
  415 #else
  416             selret = select((modemFd > sslfd) ? modemFd+1 : sslfd+1, &rfds, &wfds, NULL, &tv);
  417 #endif
  418             }
  419             if (!selret) {
  420             sfp.emsg = fxStr::format("Timeout waiting for SSL Fax write (wanting to %s).", (cerror == SSL_ERROR_WANT_READ ? "read" : "write"));
  421             cleanup(sfp);
  422             return (0);
  423             } else if (selret < 0) {
  424             sfp.emsg = fxStr::format("Error waiting for SSL Fax write (wanting to %s): %s", (cerror == SSL_ERROR_WANT_READ ? "read" : "write"), strerror(errno));
  425             cleanup(sfp);
  426             return (0);
  427             }
  428             if (modemFd && FD_ISSET(modemFd, &rfds)) {
  429             // The modem got a signal.  This probably means that SSL Fax is not happening.
  430             sfp.emsg = "Modem has data when waiting for SSL Fax write.  Terminating SSL Fax.";
  431             cleanup(sfp);
  432             return (-1);
  433             }
  434         }
  435         }
  436     } while (cerror == SSL_ERROR_WANT_READ || cerror == SSL_ERROR_WANT_WRITE);
  437     if (ret <= 0) {
  438         if (cerror == SSL_ERROR_SYSCALL) {
  439         sfp.emsg = fxStr::format("Unable to write to SSL Fax connection (syscall).  Error %d: %s", ret, strerror(ret));
  440         } else {
  441         sfp.emsg = fxStr::format("Unable to write to SSL Fax connection.  Error %d: %s", cerror, ssl_err_string());
  442         }
  443         cleanup(sfp);
  444         return (-2);
  445     }
  446     if (filter && buf[pos] == bitrev[16] && !isDLE) {
  447         // We need to duplicate this DLE.  We do that by forcing the loop to repeat this byte once.
  448         pos--;
  449         isDLE = true;
  450     } else {
  451         isDLE = false;
  452     }
  453     }
  454     return (ret);
  455 }
  456 
  457 SSLFaxProcess SSLFax::null()
  458 {
  459     SSLFaxProcess sfp;
  460     sfp.ctx = NULL;
  461     sfp.ssl = NULL;
  462     sfp.emsg = "";
  463     sfp.server = 0;
  464     sfp.client = 0;
  465     return(sfp);
  466 }
  467 
  468 SSLFaxProcess SSLFax::startClient(fxStr info, fxStr passcode, const u_char* bitrev, long ms)
  469 {
  470     SSLFaxProcess sfp;
  471     sfp.ctx = NULL;
  472     sfp.ssl = NULL;
  473     sfp.emsg = "";
  474     sfp.server = 0;
  475     sfp.client = 0;
  476 
  477     // Initialize the SSL library
  478     SSL_library_init();
  479 
  480     u_int ppos = info.nextR(info.length(), ':');
  481     fxStr port = info.tail(info.length()-ppos);
  482     int portnum = atoi((const char*) port);
  483 
  484     fxStr host = fxStr(info);   // getAddressFamily will modify
  485     getAddressFamily(host); // host now omits the port, delimiter, and possible brackets
  486 
  487     sfp.ctx = InitCTX();
  488     if (sfp.ctx == NULL) {
  489     sfp.emsg = fxStr::format("Unable to initialize OpenSSL: %s", ssl_err_string());
  490     cleanup(sfp);
  491     return (sfp);
  492     }
  493     timeval start = currentTime();
  494     sfp.server = OpenConnection(host, portnum, start, ms, sfp.emsg);
  495     if (sfp.emsg != "") {
  496     cleanup(sfp);
  497     return(sfp);
  498     }
  499     sfp.ssl = SSL_new(sfp.ctx);     /* get new SSL state with context */
  500     SSL_set_fd(sfp.ssl, sfp.server);    /* attach the socket descriptor */
  501 
  502     int cerror;
  503     int ret;
  504     do {
  505     cerror = 0;
  506     ret = SSL_connect(sfp.ssl); /* perform the connection */
  507     if (ret <= 0) {
  508         cerror = SSL_get_error(sfp.ssl, ret);
  509         /*
  510          * SSL_connect() can fail with SSL_ERROR_WANT_READ or SSL_ERROR_WANT_WRITE
  511          * because we're using a non-blocking socket.  These conditions
  512          * probably mean that the server has an open socket but that it
  513          * hasn't yet started its SSL_accept() - in other words, we may
  514          * just be a bit ahead of the receiver.  So, according to the
  515          * SSL_connect() man page we then will need to use a select()
  516          * on the socket for read or write and then re-run SSL_connect().
  517          * We are under a time constraint, however.  So, we have to
  518          * also watch for that.
  519          */
  520         if (cerror == SSL_ERROR_WANT_READ || cerror == SSL_ERROR_WANT_WRITE) {
  521         fd_set sfd;
  522         FD_ZERO(&sfd);
  523         FD_SET(sfp.server, &sfd);
  524         struct timeval tv;
  525         tv.tv_sec = (int) ms / 1000;
  526         tv.tv_usec = (ms % 1000)*1000;
  527         tv = tv - (currentTime() - start);
  528         if (cerror == SSL_ERROR_WANT_READ) {
  529 #if CONFIG_BADSELECTPROTO
  530             if (!select(sfp.server+1, (int*) &sfd, NULL, NULL, &tv)) {
  531 #else
  532             if (!select(sfp.server+1, &sfd, NULL, NULL, &tv)) {
  533 #endif
  534             sfp.emsg = "Timeout waiting for SSL Fax connection (wanting to read).";
  535             cleanup(sfp);
  536             return (sfp);
  537             }
  538         } else {    // SSL_ERROR_WANT_WRITE
  539 #if CONFIG_BADSELECTPROTO
  540             if (!select(sfp.server+1, NULL, (int*) &sfd, NULL, &tv)) {
  541 #else
  542             if (!select(sfp.server+1, NULL, &sfd, NULL, &tv)) {
  543 #endif
  544             sfp.emsg = "Timeout waiting for SSL Fax connection (wanting to write).";
  545             cleanup(sfp);
  546             return (sfp);
  547             }
  548         }
  549         }
  550     }
  551     } while (cerror == SSL_ERROR_WANT_READ || cerror == SSL_ERROR_WANT_WRITE);
  552     if (ret <= 0) {
  553     sfp.emsg = fxStr::format("Unable to connect to \"%s\".  Error %d: %s", (const char*) info, cerror, ssl_err_string());
  554     cleanup(sfp);
  555     return (sfp);
  556     }
  557     // Now send the passcode.
  558     const char* p = passcode;
  559     if (write(sfp, (const u_char*) p, passcode.length(), bitrev, 0, 1000, false) <= 0) {
  560     sfp.emsg.append(" (passcode)");
  561     cleanup(sfp);
  562     return (sfp);
  563     }
  564     sfp.emsg.append(fxStr::format("SSL Fax connection with %s encryption.  ", SSL_get_cipher(sfp.ssl)));
  565     sfp.emsg.append(ShowCerts(sfp.ssl));    /* get any certificates */
  566     return (sfp);
  567 }
  568 
  569 SSLFaxProcess SSLFax::startServer(fxStr info, fxStr pemFile)
  570 {
  571     SSLFaxProcess sfp;
  572     sfp.ctx = NULL;
  573     sfp.ssl = NULL;
  574     sfp.emsg = "";
  575     sfp.server = 0;
  576     sfp.client = 0;
  577 
  578     u_int ppos = info.nextR(info.length(), ':');
  579     fxStr port = info.tail(info.length()-ppos);
  580     int portnum = atoi((const char*) port);
  581 
  582     if (portnum < 1) {
  583     sfp.emsg = fxStr::format("Could not determine port number from \"%s\", got \"%s\".", (const char*) info, (const char*) port);
  584     return (sfp);
  585     }
  586     SSL_library_init();     /* Initialize the SSL library */
  587     sfp.ctx = InitServerCTX();  /* initialize SSL */
  588     if (sfp.ctx == NULL) {
  589     sfp.emsg = fxStr::format("Unable to initialize OpenSSL: %s", ssl_err_string());
  590     cleanup(sfp);
  591     return (sfp);
  592     }
  593     sfp.emsg = LoadCertificates(sfp.ctx, (const char*) pemFile, (const char*) pemFile); /* load certs */
  594     if (sfp.emsg != "") {
  595     sfp.emsg.append(ssl_err_string());
  596     cleanup(sfp);
  597     return (sfp);
  598     }
  599     sfp.server = OpenListener(portnum, sfp.emsg); /* create server socket */
  600     if (sfp.emsg != "") {
  601     sfp.emsg.append(ssl_err_string());
  602     cleanup(sfp);
  603     return (sfp);
  604     }
  605     if (fcntl(sfp.server, F_SETFL, fcntl(sfp.server, F_GETFL, 0) | O_NONBLOCK) == -1) {
  606     sfp.emsg.append("Unable to set server SSL Fax socket to non-blocking.");
  607     cleanup(sfp);
  608     return (sfp);
  609     }
  610     // All good so far.
  611     return (sfp);
  612 }
  613 
  614 void SSLFax::acceptClient(SSLFaxProcess& sfp, fxStr passcode, int modemFd, long ms)
  615 {
  616     /* Now we wait for the client to connect. */
  617     /* We can use select() here without SSL telling us to because SSL hasn't started yet. */
  618     fd_set sfd;
  619     FD_ZERO(&sfd);
  620     FD_SET(sfp.server, &sfd);
  621     struct timeval tv;
  622     tv.tv_sec = (int) ms / 1000;
  623     tv.tv_usec = (ms % 1000)*1000;
  624 #if CONFIG_BADSELECTPROTO
  625     if (!select(sfp.server+1, (int*) &sfd, NULL, NULL, &tv)) {
  626 #else
  627     if (!select(sfp.server+1, &sfd, NULL, NULL, &tv)) {
  628 #endif
  629     sfp.emsg = "Timeout waiting for SSL Fax client connection.";
  630     cleanup(sfp);
  631     return;
  632     }
  633     /* A client is waiting... */
  634     struct sockaddr_in addr;
  635     socklen_t len = sizeof (addr);
  636     sfp.client = accept(sfp.server, (struct sockaddr*) &addr, &len);  /* accept connection as usual */
  637     if (fcntl(sfp.client, F_SETFL, fcntl(sfp.client, F_GETFL, 0) | O_NONBLOCK) == -1) {
  638     sfp.emsg.append("Unable to set client SSL Fax socket to non-blocking.");
  639     cleanup(sfp);
  640     return;
  641     }
  642     char address[50];
  643     if (inet_ntop(addr.sin_family, &addr.sin_addr, address, 50)) {
  644     if (addr.sin_family == AF_INET6) {
  645         sfp.emsg = fxStr::format("SSL Fax connection: [%s]:%d ", address, ntohs(addr.sin_port));
  646     } else {
  647         sfp.emsg = fxStr::format("SSL Fax connection: %s:%d ", address, ntohs(addr.sin_port));
  648     }
  649     } else {
  650         sfp.emsg = fxStr::format("SSL Fax connection: <unknown address>:%d ", ntohs(addr.sin_port));
  651     }
  652     sfp.ssl = SSL_new(sfp.ctx);     /* get new SSL state with context */
  653     SSL_set_fd(sfp.ssl, sfp.client);    /* set connection socket to SSL state */
  654 
  655     struct timeval start = currentTime();
  656     int cerror;
  657     int ret;
  658     do {
  659     cerror = 0;
  660     ret = SSL_accept(sfp.ssl);  /* do SSL-protocol accept */
  661     if (ret <= 0) {
  662         cerror = SSL_get_error(sfp.ssl, ret);
  663         if (cerror == SSL_ERROR_WANT_READ || cerror == SSL_ERROR_WANT_WRITE) {
  664         int selret;
  665         fd_set rfds;
  666         FD_ZERO(&rfds);
  667         if (modemFd) FD_SET(modemFd, &rfds);
  668         struct timeval tv;
  669         tv.tv_sec = (int) ms / 1000;
  670         tv.tv_usec = (ms % 1000)*1000;
  671         tv = tv - (currentTime() - start);
  672         if (cerror == SSL_ERROR_WANT_READ) {    // wait for the socket to be readable
  673             FD_SET(sfp.client, &rfds);
  674 #if CONFIG_BADSELECTPROTO
  675             selret = select((modemFd > sfp.client) ? modemFd+1 : sfp.client+1, (int*) &rfds, NULL, NULL, &tv);
  676 #else
  677             selret = select((modemFd > sfp.client) ? modemFd+1 : sfp.client+1, &rfds, NULL, NULL, &tv);
  678 #endif
  679         } else {    // SSL_ERROR_WANT_WRITE, wait for the socket to be writable
  680             fd_set wfds;
  681             FD_ZERO(&wfds);
  682             FD_SET(sfp.client, &wfds);
  683 #if CONFIG_BADSELECTPROTO
  684             selret = select((modemFd > sfp.client) ? modemFd+1 : sfp.client+1, (int*) &rfds, (int*) &wfds, NULL, &tv);
  685 #else
  686             selret = select((modemFd > sfp.client) ? modemFd+1 : sfp.client+1, &rfds, &wfds, NULL, &tv);
  687 #endif
  688         }
  689         if (!selret) {
  690             sfp.emsg = fxStr::format("Timeout in waiting for SSL Fax accept (wanting to %s).", (cerror == SSL_ERROR_WANT_READ ? "read" : "write"));
  691             cleanup(sfp);
  692             return;
  693         } else if (selret < 0) {
  694             sfp.emsg = fxStr::format("Error in waiting for SSL Fax accept (wanting to %s): %s", (cerror == SSL_ERROR_WANT_READ ? "read" : "write"), strerror(errno));
  695             cleanup(sfp);
  696             return;
  697         }
  698         if (modemFd && FD_ISSET(modemFd, &rfds)) {
  699             // The modem got a signal.  This probably means that SSL Fax is not happening.
  700             sfp.emsg = "Modem has data when waiting for SSL Fax accept.  Terminating SSL Fax.";
  701             cleanup(sfp);
  702             return;
  703         }
  704         }
  705     }
  706     } while (cerror == SSL_ERROR_WANT_READ || cerror == SSL_ERROR_WANT_WRITE);
  707     if (ret <= 0) {
  708     if (cerror == SSL_ERROR_SYSCALL) {
  709         sfp.emsg = fxStr::format("Unable to accept SSL Fax connection (syscall).  Error %d: %s", ret, strerror(ret));
  710     } else {
  711         sfp.emsg = fxStr::format("Unable to accept SSL Fax connection.  Error %d: %s", cerror, ssl_err_string());
  712     }
  713     cleanup(sfp);
  714     return;
  715     }
  716 
  717     // Now read the passcode.
  718     u_char p[1];
  719     for (u_int i = 0; i < passcode.length(); i++) {
  720     if (read(sfp, p, 1, modemFd, 1000) <= 0) {
  721         sfp.emsg.append(" (passcode)");
  722         cleanup(sfp);
  723         return;
  724     }
  725     if (p[0] != passcode[i]) {
  726         sfp.emsg.append("Invalid Passcode");
  727         cleanup(sfp);
  728         return;
  729     }
  730     }
  731     sfp.emsg.append(ShowCerts(sfp.ssl));    /* get any certificates */
  732     return;
  733 }
  734 
  735 void SSLFax::cleanup(SSLFaxProcess& sfp)
  736 {
  737     if (sfp.ctx) {
  738     ERR_free_strings(); /* free memory from SSL_load_error_strings */
  739     EVP_cleanup();      /* free memory from OpenSSL_add_all_algorithms */
  740     SSL_CTX_free(sfp.ctx);  /* release context */
  741     }
  742     sfp.ctx = NULL;
  743     sfp.ssl = NULL;
  744     if (sfp.server) {
  745     /*
  746      * This is the client.  We want the client-side to shut down
  747      * first so that the server-side is not left with TIME_WAIT.
  748      * We'll get the TIME_WAIT on the client-side, and that's okay.
  749      */
  750     shutdown(sfp.server, SHUT_RDWR);
  751     close(sfp.server);
  752     }
  753     if (sfp.client) {
  754     /*
  755      * This is the server.  We want to avoid TIME_WAIT, and so we
  756      * wait up to 5 seconds for the client to shut down, and if
  757      * they don't, then we'll RST the connection using SO_LINGER.
  758      */
  759     fcntl(sfp.client, F_SETFL, fcntl(sfp.server, F_GETFL, 0) &~ O_NONBLOCK);    // we want the read() below to block.
  760 
  761     char* buf[1];
  762     bool done = false;
  763     fd_set sfd;
  764     FD_ZERO(&sfd);
  765     FD_SET(sfp.client, &sfd);
  766     struct timeval tv;
  767     do {
  768         tv.tv_sec = 5;
  769         tv.tv_usec = 0;
  770 #if CONFIG_BADSELECTPROTO
  771         if (!select(sfp.client+1, (int*) &sfd, NULL, NULL, &tv)) {
  772 #else
  773         if (!select(sfp.client+1, &sfd, NULL, NULL, &tv)) {
  774 #endif
  775         // The client did not shut down first.  RST the connection.
  776         struct linger ling;
  777         ling.l_onoff = 1;
  778         ling.l_linger = 0;
  779         setsockopt(sfp.client, SOL_SOCKET, SO_LINGER, (char*) &ling, sizeof(ling));
  780         done = true;
  781         } else {
  782         done = (::read(sfp.client, buf, 1) <= 0);
  783         }
  784     } while (!done);
  785     close(sfp.client);
  786     }
  787     sfp.server = 0;
  788     sfp.client = 0;
  789     return;
  790 }
  791 
  792 #endif