"Fossies" - the Fresh Open Source Software Archive

Member "hylafax-7.0.2/faxd/Class1Send.c++" (5 Dec 2019, 78122 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 /*  $Id: Class1Send.c++ 1178 2013-07-29 22:14:23Z faxguy $ */
    2 /*
    3  * Copyright (c) 1990-1996 Sam Leffler
    4  * Copyright (c) 1991-1996 Silicon Graphics, Inc.
    5  * HylaFAX is a trademark of Silicon Graphics
    6  *
    7  * Permission to use, copy, modify, distribute, and sell this software and 
    8  * its documentation for any purpose is hereby granted without fee, provided
    9  * that (i) the above copyright notices and this permission notice appear in
   10  * all copies of the software and related documentation, and (ii) the names of
   11  * Sam Leffler and Silicon Graphics may not be used in any advertising or
   12  * publicity relating to the software without the specific, prior written
   13  * permission of Sam Leffler and Silicon Graphics.
   14  * 
   15  * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, 
   16  * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY 
   17  * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.  
   18  * 
   19  * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
   20  * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
   21  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
   22  * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF 
   23  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
   24  * OF THIS SOFTWARE.
   25  */
   26 
   27 /*
   28  * EIA/TIA-578 (Class 1) Modem Driver.
   29  *
   30  * Send protocol.
   31  */
   32 #include "config.h"
   33 #include "Sys.h"
   34 #include "Class1.h"
   35 #include "ModemConfig.h"
   36 #include "HDLCFrame.h"
   37 #include "t.30.h"
   38 #include "itufaxicc.h"
   39 
   40 /*
   41  * Force the tty into a known flow control state.
   42  */
   43 bool
   44 Class1Modem::sendSetup(FaxRequest& req, const Class2Params& dis, fxStr& emsg)
   45 {
   46     if (flowControl == FLOW_XONXOFF)
   47     setXONXOFF(FLOW_NONE, FLOW_NONE, ACT_FLUSH);
   48     if (isSSLFax) {
   49     return (FaxModem::sendSetup(req, dis, emsg));
   50     } else {
   51     return (FaxModem::sendSetup(req, dis, emsg) && FaxModem::setOrigin(req));
   52     }
   53 }
   54 
   55 /*
   56  * Wait-for and process a dial command response.
   57  */
   58 CallStatus
   59 Class1Modem::dialResponse(fxStr& emsg)
   60 {
   61     // This is as good a time as any, perhaps, to reset modemParams.br.
   62     // If the call does V.8 handshaking, then it will be altered.
   63     modemParams.br = nonV34br;
   64 
   65     int ntrys = 0;
   66     ATResponse r;
   67     do {
   68     r = atResponse(rbuf, conf.dialResponseTimeout);
   69     
   70     /*
   71      * Blacklisting is handled internally just like a NOCARRIER.
   72      * emsg is customized to let the user know the problem lies in
   73      * the modem and not in line conditions, cables ...
   74      * The known blacklisting modem responses are:
   75      * 1. "BLACKLISTED"
   76      * 2. "DELAYED HH:MM:SS" (ie: "DELAYED 00:59:02")
   77      * 3. "DIALING DISABLED" (USR)
   78      * User can switch on/off the modem or use appropriate reset commands
   79      * to clear/disable blacklisted numbers, ie:
   80      * ModemResetCmds: AT%TCB  (Some rockwell chipsets)
   81      * ModemResetCmds: AT%D0   (Some topic chipsets)
   82      * ModemResetCmds: ATS40=7 (Some usr chipsets)
   83      */
   84     if (strncmp(rbuf, "BLACKLISTED", 11) == 0
   85         || strncmp(rbuf, "DELAYED", 7) == 0
   86         || strncmp(rbuf, "DIALING DISABLED", 16) == 0) {
   87         emsg = "Blacklisted by modem {E010}";
   88         return (NOCARRIER);
   89     }
   90 
   91     switch (r) {
   92     case AT_ERROR:      return (ERROR); // error in dial command
   93     case AT_BUSY:       return (BUSY);  // busy signal
   94     case AT_NOCARRIER:  return (NOCARRIER); // no carrier detected
   95     case AT_NODIALTONE: return (NODIALTONE);// local phone connection hosed
   96     case AT_NOANSWER:   return (NOANSWER);  // no answer or ring back
   97     case AT_TIMEOUT:    return (FAILURE);   // timed out w/o response
   98     case AT_CONNECT:    return (OK);    // fax connection
   99     case AT_DLEEOT:
  100     case AT_OK:
  101         /*
  102          * Apparently some modems (like the AT&T DataPort) can respond OK
  103          * to indicate NO CARRIER.  Other modems, like the Lucent/Agere Venus
  104          * and Agere/LSI OCM/OCF and CFAX34 can respond OK or DLE+EOT to
  105          * indicate a V.34/V.8 handshake incompatibility.  We need to trigger 
  106          * hasV34Trouble for the latter case.
  107          */
  108         if (conf.class1EnableV34Cmd != "" && serviceType == SERVICE_CLASS10)
  109         return (V34FAIL);
  110         if (r == AT_OK)
  111         return (NOCARRIER);
  112         else
  113         return (FAILURE);
  114     case AT_FCERROR:
  115         /*
  116          * Some modems that support adaptive-answer assert a data
  117          * carrier first and then fall back to answering as a fax
  118          * modem.  For these modems we'll get an initial +FCERROR
  119          * (wrong carrier) result that we ignore.  We actually
  120          * accept three of these in case the modem switches carriers
  121          * several times (haven't yet encountered anyone that does).
  122          */
  123     case AT_DLEETX:             // silly modem
  124         if (++ntrys == 3) {
  125         emsg = "Ringback detected, no answer without CED {E011}"; // XXX
  126         protoTrace(emsg);
  127         return (NOFCON);
  128         }
  129         r = AT_OTHER;
  130         break;
  131     }
  132     } while (r == AT_OTHER && isNoise(rbuf));
  133     return (FAILURE);
  134 }
  135 
  136 void
  137 Class1Modem::sendBegin()
  138 {
  139     FaxModem::sendBegin();
  140     setInputBuffering(false);
  141     // polling accounting?
  142     params.br = (u_int) -1;         // force initial training
  143     dataSent = 0;
  144     dataMissed = 0;
  145 }
  146 
  147 #define BATCH_FIRST 1
  148 #define BATCH_LAST  2
  149 
  150 void
  151 Class1Modem::checkReceiverDIS(Class2Params& params)
  152 {
  153     if (useV34) {
  154     if (params.ec == EC_DISABLE) {
  155         protoTrace("V.34-Fax session, but DIS signal contains no ECM bit; ECM forced.");
  156         params.ec = EC_ENABLE256;
  157     }
  158     if (params.br != BR_33600) {
  159         protoTrace("V.34-Fax session, but DIS signal contains no V.8 bit; compensating.");
  160         params.br = BR_33600;
  161     }
  162     }
  163 }
  164 
  165 /*
  166  * Get the initial DIS command.
  167  */
  168 FaxSendStatus
  169 Class1Modem::getPrologue(Class2Params& params, bool& hasDoc, fxStr& emsg, u_int& batched)
  170 {
  171     u_int t1 = howmany(conf.t1Timer, 1000);     // T1 timer in seconds
  172     time_t start = Sys::now();
  173     HDLCFrame frame(conf.class1FrameOverhead);
  174 
  175     if (!isSSLFax && useV34 && (batched & BATCH_FIRST))
  176     waitForDCEChannel(true);        // expect control channel
  177 
  178     bool framerecvd = false;
  179     if (batched & BATCH_FIRST)          // receive carrier raised
  180     framerecvd = recvFrame(frame, FCF_SNDR, conf.t1Timer, true);    // T1 is used here
  181     else {                  // receive carrier not raised
  182     // We're not really switching directions of communication, but we don't want
  183     // to start listening for prologue frames until we're sure that the receiver 
  184     // has dropped the carrier used to signal MCF.
  185     (void) switchingPause(emsg);
  186     // The receiver will allow T2 to elapse intentionally here.
  187     // To keep recvFrame from timing out we double our wait.
  188     framerecvd = recvFrame(frame, FCF_SNDR, conf.t2Timer * 2);
  189     }
  190 
  191     for (;;) {
  192     if (gotEOT) {
  193         if (!isSSLFax && useV34) hadV34Trouble = true;  // it appears that the connection is too poor for the V.34 carrier
  194         break;
  195     }
  196     if (framerecvd) {
  197         /*
  198          * An HDLC frame was received; process any
  199          * optional frames that precede the DIS.
  200          */
  201         do {
  202         switch (frame.getRawFCF()) {
  203         case FCF_NSF:
  204             {
  205             const u_char* features = recvNSF(NSF(frame.getFrameData(), frame.getFrameDataLength()-1, frameRev));
  206             if (features) dis_caps.features = features[0];
  207             }
  208             break;
  209         case FCF_CSI:
  210             { fxStr csi; recvCSI(decodeTSI(csi, frame)); }
  211             break;
  212         case FCF_DIS:
  213             u_char features = dis_caps.features;
  214             dis_caps = frame.getDIS();
  215             dis_caps.features = features;
  216 
  217             if (dis_caps.isBitEnabled(FaxParams::BITNUM_T37) && dis_caps.isBitEnabled(FaxParams::BITNUM_T38)) {
  218             /*
  219              * DIS bit 1 implies T.37 support, and bit 3 implies T.38 support, but
  220              * these bits really just mean that CIA, TSA, and CSA are supported.
  221              * Unfortunately, many devices that enable them don't really support
  222              * these frames.  So, we have to make distinctions.
  223              */
  224             protoTrace("REMOTE supports internet fax");
  225             } else if (dis_caps.isBitEnabled(FaxParams::BITNUM_T37)) {
  226             protoTrace("REMOTE supports internet fax (T.37)");
  227             } else if (dis_caps.isBitEnabled(FaxParams::BITNUM_T38)) {
  228             protoTrace("REMOTE supports internet fax (T.38)");
  229             }
  230 
  231             params.setFromDIS(dis_caps);
  232             checkReceiverDIS(params);
  233             curcap = NULL;          // force initial setup
  234             break;
  235         }
  236         } while (frame.moreFrames() && recvFrame(frame, FCF_SNDR, conf.t2Timer));
  237         if (frame.isOK()) {
  238         switch (frame.getRawFCF()) {
  239         case FCF_DIS:
  240             hasDoc = dis_caps.isBitEnabled(FaxParams::BITNUM_T4XMTR);// documents to poll?
  241             if (!dis_caps.isBitEnabled(FaxParams::BITNUM_T4RCVR)) {
  242             emsg = "Remote has no T.4 receiver capability {E122}";
  243             protoTrace(emsg);
  244                 if (! hasDoc)   // don't die if we can poll
  245                 return (send_failed);
  246             }
  247             emsg = "";
  248             return (send_ok);
  249         case FCF_DTC:               // NB: don't handle DTC
  250             emsg = "DTC received when expecting DIS (not supported) {E123}";
  251             protoTrace(emsg);
  252             return (send_retry);
  253         case FCF_DCN:
  254             emsg = "COMREC error in transmit Phase B/got DCN {E124}";
  255             protoTrace(emsg);
  256             return (send_retry);
  257         default:
  258             emsg = "COMREC invalid command received/no DIS or DTC {E125}";
  259             protoTrace(emsg);
  260             break;
  261         }
  262         }
  263     }
  264     /*
  265      * Wait up to T1 for a valid DIS.
  266      */
  267     if ((unsigned) Sys::now()-start >= t1)
  268         break;
  269     (void) switchingPause(emsg);
  270     framerecvd = recvFrame(frame, FCF_SNDR, (Sys::now()-start)*1000);   // timer here is T1
  271     }
  272     if (emsg == "") {
  273     emsg = "No receiver protocol (T.30 T1 timeout) {E126}";
  274     protoTrace(emsg);
  275     }
  276     return (send_retry);
  277 }
  278 
  279 /*
  280  * Setup file-independent parameters prior
  281  * to entering Phase B of the send protocol.
  282  */
  283 void
  284 Class1Modem::sendSetupPhaseB(const fxStr& p, const fxStr& s)
  285 {
  286     if (p != fxStr::null && dis_caps.isBitEnabled(FaxParams::BITNUM_PWD))
  287     encodePWD(pwd, p);
  288     else
  289     pwd = fxStr::null;
  290     if (s != fxStr::null && dis_caps.isBitEnabled(FaxParams::BITNUM_SUB))
  291     encodePWD(sub, s);
  292     else
  293     sub = fxStr::null;
  294 }
  295 
  296 const u_int Class1Modem::modemPFMCodes[8] = {
  297     FCF_MPS,        // PPM_MPS
  298     FCF_EOM,        // PPM_EOM
  299     FCF_EOP,        // PPM_EOP
  300     FCF_EOP,        // 3 ??? XXX
  301     FCF_PRI_MPS,    // PPM_PRI_MPS
  302     FCF_PRI_EOM,    // PPM_PRI_EOM
  303     FCF_PRI_EOP,    // PPM_PRI_EOP
  304     FCF_EOP,        // 7 ??? XXX
  305 };
  306 
  307 bool
  308 Class1Modem::decodePPM(const fxStr& pph, u_int& ppm, fxStr& emsg)
  309 {
  310     if (FaxModem::decodePPM(pph, ppm, emsg)) {
  311     ppm = modemPFMCodes[ppm];
  312     return (true);
  313     } else
  314     return (false);
  315 }
  316 
  317 void
  318 Class1Modem::getDataStats(FaxSetup* setupinfo)
  319 {
  320     setupinfo->senderDataSent = dataSent;
  321     setupinfo->senderDataMissed = dataMissed;
  322     return;
  323 }
  324 
  325 /*
  326  * Send the specified document using the supplied
  327  * parameters.  The pph is the post-page-handling
  328  * indicators calculated prior to initiating the call.
  329  */
  330 FaxSendStatus
  331 Class1Modem::sendPhaseB(TIFF* tif, Class2Params& next, FaxMachineInfo& info,
  332     fxStr& pph, fxStr& emsg, u_int& batched)
  333 {
  334     int ntrys = 0;          // # retraining/command repeats
  335     bool morePages = true;      // more pages still to send
  336     HDLCFrame frame(conf.class1FrameOverhead);
  337 
  338     do {
  339         hadV34Trouble = false;      // to monitor failure type
  340         hadV17Trouble = false;      // to monitor failure type
  341     batchingError = false;
  342     signalRcvd = 0;
  343     if (abortRequested())
  344         return (send_failed);
  345     if (repeatPhaseB) {
  346         /*
  347          * We need to repeat protocol from the beginning of Phase B
  348          * due to a non-batched EOM signal (formatting change).
  349          */
  350         params.br = (u_int) -1;     // force retraining
  351         batched = batched & ~BATCH_FIRST;   // must raise V.21 receive carrier
  352         bool hasDoc;
  353         FaxSendStatus status = getPrologue(params, hasDoc, emsg, batched);
  354         if (status != send_ok) return (send_retry);
  355         repeatPhaseB = false;
  356     }
  357     /*
  358      * Check the next page to see if the transfer
  359      * characteristics change.  If so, update the
  360      * T.30 session parameters and do training.
  361      * Note that since the initial parameters are
  362      * setup to be "undefined", training will be
  363      * sent for the first page after receiving the
  364      * DIS frame.
  365      */
  366     if (params != next) {
  367         if (!sendTraining(next, 3, emsg)) {
  368         if (hadV34Trouble) {
  369             protoTrace("The destination appears to have trouble with V.34-Fax.");
  370             return (send_v34fail);
  371         }
  372         if (hadV17Trouble) {
  373             protoTrace("The destination appears to have trouble with V.17.");
  374             return (send_v17fail);
  375         }
  376         if (!(batched & BATCH_FIRST)) {
  377             protoTrace("The destination appears to not support batching.");
  378             return (send_batchfail);
  379         }
  380         return (send_retry);
  381         }
  382         params = next;
  383     }
  384 
  385     if (params.ec == EC_DISABLE || useSSLFax) {     // ECM does it later
  386         /*
  387          * According to T.30 5.3.2.4 we must pause at least 75 ms "after 
  388          * receipt of a signal using the T.30 binary coded modulation" and 
  389          * "before sending any signals using V.27 ter/V.29/V.33/V.17 
  390          * modulation system"
  391          *
  392          * We also do this pause when doing SSL Fax to help the receiver
  393          * in being ready for our connection.
  394          */
  395         if (!switchingPause(emsg)) {
  396         return (send_failed);
  397         }
  398     }
  399 #if defined(HAVE_SSL)
  400     if (!suppressSSLFax && !isSSLFax && useSSLFax && remoteCSAType == 0x40 && remoteCSAinfo.length()) {
  401         protoTrace("Connecting to %s for SSL Fax transmission.", (const char*) remoteCSAinfo);
  402         SSLFax sslfax;
  403         sslFaxProcess = sslfax.startClient(remoteCSAinfo, sslFaxPasscode, rtcRev, conf.class1SSLFaxServerTimeout);
  404         if (sslFaxProcess.emsg != "") protoTrace("SSL Fax: \"%s\"", (const char*) sslFaxProcess.emsg);
  405         if (!sslFaxProcess.server) {
  406         protoTrace("SSL Fax connection failed.");
  407         useSSLFax = false;
  408         } else {
  409         protoTrace("SSL Fax connection was successful.");
  410         isSSLFax = true;
  411         }
  412     }
  413 #endif
  414     /*
  415      * The ECM protocol needs to know PPM, so this must be done beforehand...
  416      */
  417     morePages = !TIFFLastDirectory(tif);
  418     u_int cmd;
  419     if (!decodePPM(pph, cmd, emsg))
  420         return (send_failed);
  421     /*
  422      * If pph tells us that the PPM is going to be EOM it means that the
  423      * next page is formatted differently from the current page.  To handle this
  424      * situation properly, EOM is used.  Following EOM we must repeat the
  425      * entire protocol of Phase B.  This triggers that.  Batching is handled
  426      * also with EOM, but not with the repeatPhaseB flag.
  427      */
  428     repeatPhaseB = (cmd == FCF_EOM);
  429     if (cmd == FCF_EOP && !(batched & BATCH_LAST))
  430         cmd = FCF_EOM;
  431 
  432     /*
  433      * Transmit the facsimile message/Phase C.
  434      */
  435     if (!sendPage(tif, params, decodePageChop(pph, params), cmd, emsg)) {
  436         if (hadV34Trouble) {
  437         protoTrace("The destination appears to have trouble with V.34-Fax.");
  438         return (send_v34fail);
  439         }
  440         if (batchingError && (batched & BATCH_FIRST)) {
  441         protoTrace("The destination appears to not support batching.");
  442         return (send_batchfail);
  443         }
  444         return (send_retry);    // a problem, disconnect
  445     }
  446 
  447     int ncrp = 0;
  448 
  449     if (params.ec == EC_DISABLE) {
  450         /*
  451          * Delay before switching to the low speed carrier to
  452          * send the post-page-message frame according to 
  453          * T.30 chapter 5 note 4.  We provide for a different
  454          * setting following EOP because, empirically, some 
  455          * machines may need more time. Beware that, reportedly, 
  456          * lengthening this delay too much can permit echo 
  457          * suppressors to kick in with bad results.
  458          *
  459          * Historically this delay was done using a software pause
  460          * rather than +FTS because the time between +FTS and the 
  461          * OK response is longer than expected, and this was blamed
  462          * for timing problems.  However, this "longer than expected"
  463          * delay is a result of the time required by the modem's
  464          * firmware to actually release the carrier.  T.30 requires
  465          * a delay (period of silence), and this cannot be guaranteed
  466          * by a simple pause.  +FTS must be used.
  467          */
  468         if (!isSSLFax && !atCmd(cmd == FCF_MPS ? conf.class1PPMWaitCmd : conf.class1EOPWaitCmd, AT_OK)) {
  469         emsg = "Stop and wait failure (modem on hook) {E127}";
  470         protoTrace(emsg);
  471         return (send_retry);
  472         }
  473     }
  474 
  475     u_int ppr;
  476     do {
  477         if (signalRcvd == 0) {
  478         /*
  479          * Send post-page message and get response.
  480          */
  481         dataSent++; // non-ECM pages are whole units instead of per-scanline units giving preference to ECM sessions
  482         if (!sendPPM(cmd, frame, emsg)) {
  483             if (cmd == FCF_EOM && (batched & BATCH_FIRST)) {
  484             protoTrace("The destination appears to not support batching.");
  485             return (send_batchfail);
  486             }
  487             return (send_retry);
  488         }
  489         ppr = frame.getFCF();
  490         traceFCF("SEND recv", ppr);
  491         } else {
  492         // ECM protocol already got post-page response
  493         ppr = signalRcvd;
  494         }
  495         switch (ppr) {
  496         case FCF_RTP:       // ack, continue after retraining
  497         params.br = (u_int) -1; // force retraining above
  498         /* fall thru... */
  499         case FCF_MCF:       // ack confirmation
  500         case FCF_PIP:       // ack, w/ operator intervention
  501         countPage();        // bump page count
  502         notifyPageSent(tif);    // update server
  503         if (pph[4] == 'Z')
  504             pph.remove(0,4+5+1);// discard page-chop+handling info
  505         else
  506             pph.remove(0,5);    // discard page-handling info
  507         if (params.ec == EC_DISABLE) (void) switchingPause(emsg);
  508         ntrys = 0;
  509         if (morePages) {    // meaning, more pages in this file, but there may be other files
  510             if (!TIFFReadDirectory(tif)) {
  511             emsg = "Problem reading document directory {E302}";
  512             protoTrace(emsg);
  513             return (send_failed);
  514             }
  515         }
  516         if (cmd != FCF_EOP) {
  517             if (ppr == FCF_PIP) {
  518             emsg = "Procedure interrupt (operator intervention) {E129}";
  519             protoTrace(emsg);
  520             return (send_failed);
  521             }
  522             if (ppr == FCF_MCF && !repeatPhaseB) {
  523             /*
  524              * The session parameters cannot change except following
  525              * the reception of an RTN or RTP signal or the transmission
  526              * of an EOM signal.
  527              *
  528              * Since we did not receive RTN or RTP, if EOM was not used
  529              * (repeating from the start of Phase B) then we require that
  530              * the next page have the same characteristics as this page.
  531              */
  532             next = params;
  533             }
  534         }
  535         break;
  536         case FCF_DCN:       // disconnect, abort
  537         emsg = "Remote fax disconnected prematurely {E128}";
  538         protoTrace(emsg);
  539         return (send_retry);
  540         case FCF_RTN:       // nak, retry after retraining
  541         /*
  542          * The receiver rejected the quality of the previous Phase C communication.
  543          * This may mean that the image quality was unacceptable or it may mean that
  544          * the receiver picked up on some other demodulation artifact that it didn't
  545          * like.  However, the RTN signal does not indicate with any degree of
  546          * reliability whether or not the receiver printed the page at all or what it
  547          * expects us to do with the previous page (retransmit or not).  So it's very
  548          * vague.  The default we follow is to retransmit two more times and then to
  549          * move on to the next page if the RTN signals persist.
  550          *
  551          * With respect to the handling of dataMissed here, we really don't know how
  552          * much data was missed or received corrupt by the sender because the RTN
  553          * signal doesn't give us any indication.  So we make a nominal effort here
  554          * only in that regard.
  555          */
  556         dataMissed++;   // non-ECM pages are whole units instead of per-scanline units giving preference to ECM sessions
  557                 switch( conf.rtnHandling ){
  558         case RTN_RETRANSMITIGNORE:
  559             if (ntrys < 2) break;
  560                 case RTN_IGNORE:
  561             // ignore error and try to send next page
  562             // after retraining
  563             params.br = (u_int) -1; // force retraining above
  564             countPage();        // bump page count
  565             notifyPageSent(tif);    // update server
  566             if (pph[4] == 'Z')
  567             pph.remove(0,4+5+1);// discard page-chop+handling info
  568             else
  569             pph.remove(0,5);    // discard page-handling info
  570             ntrys = 0;
  571             if (ppr == FCF_PIP) {
  572             emsg = "Procedure interrupt (operator intervention) {E129}";
  573             protoTrace(emsg);
  574             return (send_failed);
  575             }
  576             if (morePages) {
  577             if (!TIFFReadDirectory(tif)) {
  578                 emsg = "Problem reading document directory {E302}";
  579                 protoTrace(emsg);
  580                 return (send_failed);
  581             }
  582             FaxSendStatus status =
  583                 sendSetupParams(tif, next, info, emsg);
  584             if (status != send_ok)
  585                 return (status);
  586             }
  587             continue;
  588                 case RTN_GIVEUP:
  589                     emsg = "Unable to transmit page (giving up after RTN) {E130}";
  590             protoTrace(emsg);
  591                     return (send_failed); // "over and out"
  592                 }
  593                 // case RTN_RETRANSMIT
  594                 if (++ntrys >= 3) {
  595                     emsg = "Unable to transmit page (giving up after 3 attempts) {E131}";
  596             protoTrace(emsg);
  597                     return (send_retry);
  598 
  599                 }
  600         params.br = (u_int) -1; // force training
  601         if (!dropToNextBR(next)) {
  602                     emsg = "Unable to transmit page (NAK at all possible signalling rates) {E132}";
  603             protoTrace(emsg);
  604                     return (send_retry);
  605         }
  606                 morePages = true;   // retransmit page
  607         break;
  608         case FCF_PIN:       // nak, retry w/ operator intervention
  609         emsg = "Unable to transmit page (NAK with operator intervention) {E133}";
  610         protoTrace(emsg);
  611         return (send_failed);
  612         case FCF_CRP:
  613         if (!switchingPause(emsg)) {
  614             return (send_retry);
  615         }
  616         break;
  617         default:            // unexpected abort
  618         emsg = "Fax protocol error (unknown frame received) {E134}";
  619         protoTrace(emsg);
  620         return (send_retry);
  621         }
  622     } while (ppr == FCF_CRP && ++ncrp < 3);
  623     if (ncrp == 3) {
  624         emsg = "Fax protocol error (command repeated 3 times) {E135}";
  625         protoTrace(emsg);
  626         return (send_retry);
  627     }
  628     } while (morePages);
  629     if (hadV17Trouble) return (send_v17fail);
  630     return (send_ok);
  631 }
  632 
  633 /*
  634  * Send ms's worth of zero's at the current signalling rate.
  635  * Note that we send real zero data here as recommended
  636  * by T.31 8.3.3 rather than using the Class 1 modem facility
  637  * to do zero fill.
  638  */
  639 bool
  640 Class1Modem::sendTCF(const Class2Params& params, u_int ms)
  641 {
  642     u_int tcfLen = params.transferSize(ms);
  643     u_char* tcf = new u_char[tcfLen];
  644     memset(tcf, 0, tcfLen);
  645     bool ok = transmitData(curcap->value, tcf, tcfLen, frameRev, true);
  646     delete[] tcf;
  647     return ok;
  648 }
  649 
  650 /*
  651  * Send the training prologue frames:
  652  *     PWD  password (optional)
  653  *     SUB  subaddress (optional)
  654  *     TSI  transmitter subscriber id
  655  *     DCS  digital command signal
  656  */
  657 bool
  658 Class1Modem::sendPrologue(FaxParams& dcs_caps, const fxStr& tsi)
  659 {
  660     /*
  661      * T.31 8.3.5 requires the DCE to respond CONNECT or result OK within
  662      * five seconds or it must result ERROR.  T.30 requires the data of
  663      * the HDLC frame to be tranmsitted in 3 s +/- 15%.  Thus, our
  664      * timeouts here must be at least 7500 ms and no more than 8500 ms.
  665      */
  666     bool frameSent;
  667     if (isSSLFax || useV34) frameSent = true;
  668     else {
  669     fxStr emsg;
  670     if (!switchingPause(emsg)) {
  671         return (false);
  672     }
  673     frameSent = (atCmd(thCmd, AT_NOTHING) && atResponse(rbuf, 7550) == AT_CONNECT);
  674     }
  675     if (!frameSent)
  676     return (false);
  677     if (pwd != fxStr::null) {
  678     startTimeout(7550);
  679     bool frameSent = sendFrame(FCF_PWD|FCF_SNDR, pwd, false);
  680     stopTimeout("sending PWD frame");
  681     if (!frameSent)
  682         return (false);
  683     }
  684     if (sub != fxStr::null) {
  685     startTimeout(7550);
  686     bool frameSent = sendFrame(FCF_SUB|FCF_SNDR, sub, false);
  687     stopTimeout("sending SUB frame");
  688     if (!frameSent)
  689         return (false);
  690     }
  691     startTimeout(7550);
  692     frameSent = sendFrame(FCF_TSI|FCF_SNDR, tsi, false);
  693     stopTimeout("sending TSI frame");
  694     if (!frameSent)
  695     return (false);
  696 #if defined(HAVE_SSL)
  697     if (!suppressSSLFax && !isSSLFax && conf.class1SSLFaxSupport && conf.class1SSLFaxInfo.length() && \
  698     (dis_caps.features & FaxParams::FEATURE_SSLFAX || (dis_caps.isBitEnabled(FaxParams::BITNUM_T37) && dis_caps.isBitEnabled(FaxParams::BITNUM_T38)))) {
  699     // We can't trust T.38 support indications to indicate that the remote device actually supports TSA frames.
  700     useSSLFax = true;
  701     SSLFax sslfax;
  702     sslFaxProcess = sslfax.startServer(conf.class1SSLFaxInfo, conf.class1SSLFaxCert);
  703     if (sslFaxProcess.emsg.length()) protoTrace("SSL Fax: \"%s\"", (const char*) sslFaxProcess.emsg);
  704     if (sslFaxProcess.server == 0 ) {
  705         setSSLFaxFd(0);
  706         useSSLFax = false;
  707     }
  708     if (useSSLFax) {
  709         fxStr tsa;
  710         encodeCSA(tsa, conf.class1SSLFaxInfo);
  711         protoTrace("Sending TSA frame to initiate HylaFAX SSL fax feature.");
  712         startTimeout(7550);
  713         frameSent = sendFrame(FCF_TSA|FCF_SNDR, tsa, false);
  714         stopTimeout("sending TSA frame");
  715         if (!frameSent) return (false);
  716     }
  717     }
  718 #endif
  719     startTimeout(7550);
  720     frameSent = sendFrame(FCF_DCS|FCF_SNDR, dcs_caps);
  721     stopTimeout("sending DCS frame");
  722     return (frameSent);
  723 }
  724 
  725 /*
  726  * Return whether or not the previously received DIS indicates
  727  * the remote side is capable of the T.30 DCS signalling rate.
  728  */
  729 bool
  730 Class1Modem::isCapable(u_int sr, FaxParams& dis)
  731 {
  732     switch (sr) {
  733     case DCSSIGRATE_2400V27:
  734         if (!dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_11) &&
  735             !dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_12) &&
  736             !dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_13) &&
  737             !dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_14))
  738         return (true);
  739     /* fall thru... */
  740     case DCSSIGRATE_4800V27:
  741     return dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_12);
  742     case DCSSIGRATE_9600V29:
  743     case DCSSIGRATE_7200V29:
  744     return dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_11);
  745     case DCSSIGRATE_14400V33:
  746     case DCSSIGRATE_12000V33:
  747     // post-1994 revisions of T.30 indicate that V.33 should
  748     // only be used when it is specifically permitted by DIS
  749     return(dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_11) &&
  750         dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_12) &&
  751         dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_13) &&
  752         !dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_14));
  753     case DCSSIGRATE_14400V17:
  754     case DCSSIGRATE_12000V17:
  755     case DCSSIGRATE_9600V17:
  756     case DCSSIGRATE_7200V17:
  757     return(dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_11) &&
  758         dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_12) &&
  759         !dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_13) &&
  760         dis.isBitEnabled(FaxParams::BITNUM_SIGRATE_14));
  761     }
  762     return (false);
  763 }
  764 
  765 /*
  766  * Send capabilities and do training.
  767  */
  768 bool
  769 Class1Modem::sendTraining(Class2Params& params, int tries, fxStr& emsg)
  770 {
  771     bool again = false;
  772     u_short attempt = 0;
  773     if (tries == 0) {
  774     emsg = "DIS/DTC received 3 times; DCS not recognized {E136}";
  775     protoTrace(emsg);
  776     if (!isSSLFax && useV34) hadV34Trouble = true;  // sadly, some receivers will do this with V.34
  777     return (false);
  778     }
  779     params.update(false);
  780     // we should respect the frame-size preference indication by the remote (DIS_FRAMESIZE)
  781     if (params.ec != EC_DISABLE && 
  782     (params.ec == EC_ENABLE64 || conf.class1ECMFrameSize == 64 || dis_caps.isBitEnabled(FaxParams::BITNUM_FRAMESIZE_DIS))) {
  783     params.setBit(FaxParams::BITNUM_FRAMESIZE_DCS, true); // we don't want to add this bit if not using ECM
  784     frameSize = 64;
  785     } else
  786     frameSize = 256;
  787 
  788     // Tell the receiver that we support CIA, TSA, and CSA frames.
  789     if (conf.class1SSLFaxSupport) {
  790     if (dis_caps.isBitEnabled(FaxParams::BITNUM_T37)) params.setBit(FaxParams::BITNUM_T37, true);
  791     if (dis_caps.isBitEnabled(FaxParams::BITNUM_T38)) params.setBit(FaxParams::BITNUM_T38, true);
  792     }
  793 
  794     if (!isSSLFax && !useV34) {
  795     /*
  796      * Select Class 1 capability: use params.br to hunt
  797      * for the best signalling scheme acceptable to both
  798      * local and remote (based on received DIS and modem
  799      * capabilities gleaned at modem setup time).
  800      */
  801     if (!curcap)
  802         curcap = findBRCapability(params.br, xmitCaps);
  803     curcap++;
  804     /*
  805      * We assume that if the sender requested 9600 or 7200 baud
  806      * and if the modem supports both V.17 and V.29 that the
  807      * desired modulation is V.29.
  808      */
  809     do {
  810         if (!dropToNextBR(params))
  811         goto failed;
  812     } while ((params.br == BR_9600 || params.br == BR_7200) && curcap->mod != V29);
  813     }
  814     do {
  815     attempt++;
  816     if (!isSSLFax && !useV34) {
  817         /*
  818          * Override the Class 2 parameter bit rate
  819          * capability and use the signalling rate
  820          * calculated from the modem's capabilities
  821          * and the received DIS.  This is because
  822          * the Class 2 state does not include the
  823          * modulation technique (v.27, v.29, v.17, v.33).
  824          *
  825          * Technically, according to post-1994 revisions
  826          * of T.30, V.33 should not be used except
  827          * in the case where the remote announces
  828          * specific V.33 support with the 1,1,1,0 rate
  829          * bits set.  However, for the sake of versatility
  830          * we'll not enforce this upon modems that support
  831          * V.33 but not V.17 and will require the user
  832          * to disable V.33 if it becomes problematic.  For
  833          * modems that support both V.17 and V.33 the
  834          * latter is never used.
  835          */
  836         params.br = curcap->br;
  837         params.setBit(FaxParams::BITNUM_SIGRATE_11, curcap->sr&DCSSIGRATE_9600V29);
  838         params.setBit(FaxParams::BITNUM_SIGRATE_12, curcap->sr&DCSSIGRATE_4800V27);
  839         params.setBit(FaxParams::BITNUM_SIGRATE_13, curcap->sr&DCSSIGRATE_14400V33);
  840         params.setBit(FaxParams::BITNUM_SIGRATE_14, curcap->sr&DCSSIGRATE_14400V17);
  841         /*
  842          * Set the number of train attemps on the same
  843          * modulation; having set it to 1 we immediately drop
  844          * the speed if the training has been failed.
  845          * This parameter is not specified by T.30
  846          * (the algorith left implementation defined),
  847          * so we choose the exact value according to our
  848          * common sense.
  849          */
  850     } else {
  851         /*
  852          * T.30 Table 2 Note 33 says that when V.34-fax is used
  853          * DCS bits 11-14 should be set to zero.
  854          */
  855         params.setBit(FaxParams::BITNUM_SIGRATE_11, false);
  856         params.setBit(FaxParams::BITNUM_SIGRATE_12, false);
  857         params.setBit(FaxParams::BITNUM_SIGRATE_13, false);
  858         params.setBit(FaxParams::BITNUM_SIGRATE_14, false);
  859     }
  860     int t = 1;
  861     do {
  862         if (!useV34 && !isSSLFax) protoTrace("SEND training at %s %s",
  863         modulationNames[curcap->mod],
  864         Class2Params::bitRateNames[curcap->br]);
  865         if (!sendPrologue(params, lid)) {
  866         if (abortRequested())
  867             goto done;
  868         protoTrace("Error sending T.30 prologue frames");
  869         continue;
  870         }
  871 
  872         /*
  873          * V.8 handshaking provides training for V.34-fax connections
  874          */
  875         if (!isSSLFax && !useV34) {
  876         /*
  877          * Delay before switching to high speed carrier
  878          * to send the TCF data as required by T.30 chapter
  879          * 5 note 3.
  880          *
  881          * Historically this delay was enforced by a pause,
  882          * however, +FTS must be used.  See the notes preceding
  883          * Class1PPMWaitCmd above.
  884          */
  885         if (!atCmd(conf.class1TCFWaitCmd, AT_OK)) {
  886             emsg = "Stop and wait failure (modem on hook) {E127}";
  887             protoTrace(emsg);
  888             return (send_retry);
  889         }
  890 
  891         setDataTimeout(5, params.br);       // TCF data is only 1.5 s
  892         if (!sendTCF(params, TCF_DURATION)) {
  893             if (abortRequested())
  894             goto done;
  895             protoTrace("Problem sending TCF data");
  896         }
  897 
  898         /*
  899          * Some modems may respond OK following TCF transmission
  900          * so quickly that the carrier signal has not actually 
  901          * dropped.  T.30 requires the receiver to wait 75 +/- 20 
  902          * ms before sending a response.  Here we explicitly look for 
  903          * that silence before looking for the low-speed carrier.  
  904          * Doing this resolves "DIS/DTC received 3 times" errors 
  905          * between USR modems and certain HP OfficeJets, in 
  906          * particular.
  907              */
  908         if (conf.class1ResponseWaitCmd != "") {
  909             atCmd(conf.class1ResponseWaitCmd, AT_OK);
  910         }
  911         }
  912 #if defined(HAVE_SSL)
  913         // This will get recvFrame below to fail if there is an SSL Fax connection.
  914         if (useSSLFax) {
  915         setSSLFaxFd(sslFaxProcess.server);
  916         }
  917 #endif
  918         /*
  919          * Receive response to training.  Acceptable
  920          * responses are: DIS or DTC (DTC not handled),
  921          * FTT, or CFR; and also a premature DCN.
  922          */
  923         HDLCFrame frame(conf.class1FrameOverhead);
  924         bool gf = recvFrame(frame, FCF_SNDR, conf.t4Timer);
  925 #if defined(HAVE_SSL)
  926         if (!isSSLFax && useSSLFax) {
  927         SSLFax sslfax;
  928         if (!getSSLFaxConnection()) {
  929             protoTrace("Traditional fax detected.  Shutting down SSL Fax listener.");
  930             sslfax.cleanup(sslFaxProcess);
  931             useSSLFax = false;
  932             sslWatchModem = false;
  933             setSSLFaxFd(0);
  934         } else {
  935             protoTrace("SSL Fax connection detected.");
  936             sslfax.acceptClient(sslFaxProcess, sslFaxPasscode, getModemFd(), conf.class1SSLFaxClientTimeout);
  937             if (sslFaxProcess.emsg != "") protoTrace("SSL Fax accept client: %s", (const char*) sslFaxProcess.emsg);
  938             if (!sslFaxProcess.server) {
  939             protoTrace("SSL Fax client accept failure.  Proceeding with a traditional fax now.");
  940             sslfax.cleanup(sslFaxProcess);
  941             useSSLFax = false;
  942             sslWatchModem = false;
  943             setSSLFaxFd(0);
  944             } else {
  945             isSSLFax = true;
  946             sslWatchModem = true;
  947             }
  948             // The SSL Fax connection tripped up recvFrame, so we need to repeat it.
  949             if (!isSSLFax) {
  950             gf = (waitFor(AT_CONNECT, conf.t4Timer) && recvFrame(frame, FCF_SNDR, conf.t4Timer, true));
  951             } else {
  952             gf = recvFrame(frame, FCF_SNDR, conf.t4Timer);
  953             }
  954         }
  955         }
  956 #endif
  957         if (gf) {
  958         do {
  959             switch (frame.getFCF()) {
  960             case FCF_CSA:
  961             {
  962                 fxStr s;
  963                 decodeCSA(s, frame);
  964                 protoTrace("REMOTE CSA \"%s\", type 0x%X", (const char*) s, remoteCSAType);
  965                 if (remoteCSAType == 0x40 && s.length() > 6 && strncmp((const char*) s, "ssl://", 6) == 0) {
  966                 // Looks like this is an SSL Fax receiver.
  967                 if (conf.class1SSLFaxSupport) useSSLFax = true;
  968                 u_int atpos = s.next(6, '@');
  969                 if (atpos < s.length()) {
  970                     sslFaxPasscode = s.extract(6, atpos-6);
  971                     remoteCSAinfo = s.tail(s.length() - atpos - 1);
  972                 } else {
  973                     sslFaxPasscode = "";
  974                     remoteCSAinfo = s.tail(s.length() - 6);
  975                 }
  976                 }
  977             }
  978             break;
  979             case FCF_NSF:
  980             recvNSF(NSF(frame.getFrameData(), frame.getFrameDataLength()-1, frameRev));
  981             break;
  982             case FCF_CSI:
  983             { fxStr csi; recvCSI(decodeTSI(csi, frame)); }
  984             break;
  985             }
  986         } while (frame.moreFrames() && recvFrame(frame, FCF_SNDR, conf.t2Timer));
  987         } 
  988         if (frame.isOK()) {
  989         switch (frame.getFCF()) {
  990         case FCF_CFR:       // training confirmed
  991             if (!isSSLFax && !useV34) protoTrace("TRAINING succeeded");
  992             setDataTimeout(60, params.br);
  993             return (true);
  994         case FCF_CRP:       // command repeat
  995         case FCF_FTT:       // failure to train, retry
  996             break;
  997         case FCF_DIS:       // new capabilities, maybe
  998             {
  999             FaxParams newDIS = frame.getDIS();
 1000             if (newDIS != dis_caps) {
 1001                 /*
 1002                    dis_caps = newDIS;
 1003                    params.setFromDIS(dis_caps);
 1004                  *
 1005                  * The above code was commented because to
 1006                  * use the newDIS we need to do more work like
 1007                  *     sendClientCapabilitiesOK()
 1008                  *     sendSetupParams()
 1009                  * So we ignore newDIS.
 1010                  * It will work if old dis 'less' then newDIS.
 1011                  */
 1012                 checkReceiverDIS(params);
 1013                 curcap = NULL;
 1014             }
 1015             }
 1016             return (sendTraining(params, --tries, emsg));
 1017         default:
 1018             if (frame.getFCF() == FCF_DCN) {
 1019             /*
 1020              * The receiver is disconnecting.  This can happen
 1021              * if the receiver is exhaused from retraining, but
 1022              * it also happens in situations where, for example,
 1023              * the receiver determines that there is a modulator
 1024              * incompatibility (i.e. with V.17).  In that case,
 1025              * we must prevent ourselves from redialing and
 1026              * reattempting V.17 training, or we'll never get
 1027              * through.
 1028              */
 1029             if (!isSSLFax && !useV34 && curcap->mod == V17 && attempt == 1 && tries == 3) hadV17Trouble = true;
 1030             emsg = "RSPREC error/got DCN (receiver abort) {E103}";
 1031             } else
 1032             emsg = "RSPREC invalid response received {E104}";
 1033             goto done;
 1034         }
 1035         } else {
 1036         /*
 1037          * Historically we waited "Class1TrainingRecovery" (1500 ms)
 1038          * at this point to try to try to avoid retransmitting while
 1039          * the receiver is also transmitting.  Sometimes it proved to be
 1040          * a faulty approach.  Really what we're trying to do is to
 1041          * not be transmitting at the same time as the other end is.
 1042          * The best way to do that is to make sure that there is
 1043          * silence on the line, and  we do that with Class1SwitchingCmd.
 1044          */
 1045         if (isSSLFax || useV34 || !switchingPause(emsg)) {
 1046             emsg = "RSPREC error/got DCN (receiver abort) {E103}";
 1047             return (false);
 1048         }
 1049         }
 1050     } while (--t > 0);
 1051     /*
 1052      * (t) attempts at the current speed failed, drop
 1053      * the signalling rate to the next lower rate supported
 1054      * by the local & remote sides and try again.
 1055      */
 1056     if (!isSSLFax && !useV34) {
 1057         do {
 1058         /*
 1059          * We don't fallback to V.17 9600 or V.17 7200 because
 1060          * after V.17 14400 and V.17 12000 fail they're not likely
 1061          * to succeed, and some receivers will give up after three
 1062          * failed TCFs.
 1063          */
 1064         again = dropToNextBR(params);
 1065         } while (again && (params.br == BR_9600 || params.br == BR_7200) && curcap->mod != V29);
 1066     }
 1067     } while (!isSSLFax && !useV34 && (again || attempt < 3));
 1068 failed:
 1069     emsg = "Failure to train remote modem at 2400 bps or minimum speed {E137}";
 1070 done:
 1071     if (!isSSLFax && !useV34) protoTrace("TRAINING failed");
 1072     return (false);
 1073 }
 1074 
 1075 /*
 1076  * Select the next lower signalling rate that's
 1077  * acceptable to both local and remote machines.
 1078  */
 1079 bool
 1080 Class1Modem::dropToNextBR(Class2Params& params)
 1081 {
 1082     if (curcap->br == BR_2400)
 1083     return (false);
 1084     const Class1Cap* oldcap = curcap;
 1085     curcap--;
 1086     for (;;) {
 1087     if (curcap) {
 1088         /*
 1089          * Hunt for compatibility with remote at this baud rate.
 1090          * We don't drop from V.29 to V.17 because if the 
 1091          * receiver supports V.17 then we probably tried
 1092          * it already without success.
 1093          */
 1094         while (curcap->br == params.br) {
 1095         if (isCapable(curcap->sr, dis_caps) && !(oldcap->mod == V29 && curcap->mod == V17))
 1096             return (true);
 1097         curcap--;
 1098         }
 1099     }
 1100     if (params.br <= minsp)
 1101         return (false);
 1102     params.br--;
 1103     // get ``best capability'' of modem at this baud rate
 1104     curcap = findBRCapability(params.br, xmitCaps);
 1105     }
 1106     /*NOTREACHED*/
 1107 }
 1108 
 1109 /*
 1110  * Select the next higher signalling rate that's
 1111  * acceptable to both local and remote machines.
 1112  */
 1113 bool
 1114 Class1Modem::raiseToNextBR(Class2Params& params)
 1115 {
 1116     for (;;) {
 1117     if (params.br == BR_14400)  // highest speed
 1118         return (false);
 1119     // get ``best capability'' of modem at this baud rate
 1120     curcap = findBRCapability(++params.br, xmitCaps);
 1121     if (curcap) {
 1122         // hunt for compatibility with remote at this baud rate
 1123         do {
 1124         if (isCapable(curcap->sr, dis_caps))
 1125             return (true);
 1126         curcap--;
 1127         } while (curcap->br == params.br);
 1128     }
 1129     }
 1130     /*NOTREACHED*/
 1131 }
 1132 
 1133 void
 1134 Class1Modem::blockData(u_int byte, bool flag)
 1135 {
 1136     if (!isSSLFax && useV34) {
 1137     // With V.34-fax the DTE makes the stuffing
 1138     byte =  (((byte>>0)&1)<<7)|(((byte>>1)&1)<<6)|
 1139         (((byte>>2)&1)<<5)|(((byte>>3)&1)<<4)|
 1140         (((byte>>4)&1)<<3)|(((byte>>5)&1)<<2)|
 1141         (((byte>>6)&1)<<1)|(((byte>>7)&1)<<0);
 1142     ecmStuffedBlock[ecmStuffedBlockPos++] = byte;
 1143     return;
 1144     }
 1145     for (u_int j = 8; j > 0; j--) {
 1146     u_short bit = (byte & (1 << (j - 1))) != 0 ? 1 : 0;
 1147     ecmByte |= (bit << ecmBitPos);
 1148     ecmBitPos++;
 1149     if (ecmBitPos == 8) {
 1150         ecmStuffedBlock[ecmStuffedBlockPos++] = ecmByte;
 1151         ecmBitPos = 0;
 1152         ecmByte = 0;
 1153     }
 1154     // add transparent zero bits if needed
 1155     if (bit == 1 && !flag) ecmOnes++;
 1156     else ecmOnes = 0;
 1157     if (ecmOnes == 5) {
 1158         ecmBitPos++;
 1159         if (ecmBitPos == 8) {
 1160         ecmStuffedBlock[ecmStuffedBlockPos++] = ecmByte;
 1161         ecmBitPos = 0;
 1162         ecmByte = 0;
 1163         }
 1164         ecmOnes = 0;
 1165     }
 1166     }
 1167 }
 1168 
 1169 /*
 1170  * Buffer ECM HDLC image frames until a full block is received.
 1171  * Perform T.30-A image block transmission protocol.
 1172  */
 1173 bool
 1174 Class1Modem::blockFrame(const u_char* bitrev, bool lastframe, u_int ppmcmd, fxStr& emsg)
 1175 {
 1176     // we have a full image frame
 1177 
 1178     for (u_int i = 0; i < ecmFramePos; i++)
 1179     ecmBlock[ecmBlockPos++] = ecmFrame[i];
 1180     ecmFramePos = 0;
 1181     if (frameNumber == 256 || lastframe) {
 1182     fxAssert(frameNumber <= 256, "Invalid frameNumber value.");
 1183     ecmBlockPos = 0;
 1184     bool lastblock = lastframe;
 1185 
 1186     // We now have a full image block without stuffed zero bits.
 1187     // As the remote can request any frame of the block until
 1188     // MCF we must keep the full image block available.
 1189 
 1190     bool blockgood = false, renegotiate = false, constrain = false, duplicate = false;
 1191     u_short pprcnt = 0;
 1192     char ppr[32];               // 256 bits
 1193     for (u_int i = 0; i < 32; i++) ppr[i] = 0xff;
 1194     u_short badframes = frameNumber, badframesbefore = 0;
 1195     bool dolongtrain = false;
 1196 
 1197     do {
 1198         u_short fcount = 0;
 1199         u_short fcountuniq = 0;
 1200         ecmStuffedBlockPos = 0;
 1201 
 1202         if (isSSLFax || !useV34) {
 1203         // synchronize with 200 ms of 0x7e flags
 1204         for (u_int i = 0; i < params.transferSize(200); i++)
 1205             blockData(0x7e, true);
 1206         }
 1207 
 1208         u_char* firstframe = (u_char*) malloc(frameSize + 6);
 1209         fxAssert(firstframe != NULL, "ECM procedure error (frame duplication).");
 1210         firstframe[0] = 0x1;            // marked as unused
 1211         for (u_short fnum = 0; fnum < frameNumber; fnum++) {
 1212         u_int pprpos, pprval;
 1213             for (pprpos = 0, pprval = fnum; pprval >= 8; pprval -= 8) pprpos++;
 1214             if (ppr[pprpos] & frameRev[1 << pprval]) {
 1215             HDLCFrame ecmframe(5);
 1216             // frame bit marked for transmission
 1217             fcount++;
 1218             for (u_int i = fnum * (frameSize + 4);
 1219             i < (fnum + 1) * (frameSize + 4); i++) {
 1220             ecmframe.put(ecmBlock[i]);
 1221             blockData(ecmBlock[i], false);
 1222             }
 1223             int fcs1 = (ecmframe.getCRC() >> 8) & 0xff; // 1st byte FCS
 1224             int fcs2 = ecmframe.getCRC() & 0xff;    // 2nd byte FCS
 1225             ecmframe.put(fcs1); ecmframe.put(fcs2);
 1226             blockData(fcs1, false);
 1227             blockData(fcs2, false);
 1228             traceHDLCFrame("<--", ecmframe, true);
 1229             protoTrace("SEND send frame number %u", fnum);
 1230 
 1231             if (isSSLFax || !useV34) {
 1232             // separate frames with a 0x7e flag
 1233             blockData(0x7e, true);
 1234             }
 1235 
 1236             if (firstframe[0] == 0x1) {
 1237             for (u_int i = 0; i < (frameSize + 6); i++) {
 1238                 firstframe[i] = ecmframe[i];
 1239             }
 1240             }
 1241         }
 1242         }
 1243         fcountuniq = fcount;
 1244         if (fcount == 1 && pprcnt > 0 && firstframe[3] == 0) {
 1245         /*
 1246          * Some receivers may have a hard time hearing the first frame,
 1247          * However, some receivers do not like frame duplication within a
 1248          * block.  So the first time we get here we merely send a single
 1249          * frame, but we flag duplicate so that if we come back through
 1250          * here we'll repeat it and hopefully catch those that have a
 1251          * hard time hearing the first frame.
 1252          */
 1253         if (duplicate) {
 1254             HDLCFrame ecmframe(5);
 1255             fcount++;
 1256             for (u_int i = 0; i < (frameSize + 6); i++) {
 1257             blockData(firstframe[i], false);
 1258             }
 1259             ecmframe.put(firstframe, (frameSize + 6));
 1260             traceHDLCFrame("<--", ecmframe, true);
 1261             protoTrace("SEND send frame number %u", frameRev[firstframe[3]]);
 1262             if (isSSLFax || !useV34) blockData(0x7e, true);
 1263         } else {
 1264             duplicate = true;
 1265         }
 1266         }
 1267         free(firstframe);
 1268         HDLCFrame rcpframe(5);
 1269         rcpframe.put(0xff); rcpframe.put(0xc0); rcpframe.put(0x61); rcpframe.put(0x96); rcpframe.put(0xd3);
 1270         for (u_short k = 0; k < 3; k++) {       // three RCP frames
 1271         for (u_short j = 0; j < 5; j++)
 1272             blockData(rcpframe[j], false);
 1273         traceHDLCFrame("<--", rcpframe, true);
 1274 
 1275         // separate frames with a 0x7e flag
 1276         if (isSSLFax || !useV34) blockData(0x7e, true);
 1277         }
 1278         // add one more flag to ensure one full flag gets transmitted before DLE+ETX
 1279         if (isSSLFax || !useV34) blockData(0x7e, true);
 1280 
 1281         // start up the high-speed carrier...
 1282         if (flowControl == FLOW_XONXOFF)   
 1283         setXONXOFF(FLOW_XONXOFF, FLOW_NONE, ACT_FLUSH);
 1284         if (!isSSLFax && !useV34) {
 1285         // T.30 5.3.2.4 (03/93) gives this to be a 75ms minimum
 1286         if (!switchingPause(emsg)) {
 1287             return (false);
 1288         }
 1289         /*
 1290          * T.30 Section 5, Note 5 states that we must use long training
 1291          * on the first high-speed data message following CTC.
 1292          */
 1293         fxStr tmCmd;
 1294         if (dolongtrain) tmCmd = fxStr(curcap->value, tmCmdFmt);
 1295         else tmCmd = fxStr(curcap[HasShortTraining(curcap)].value, tmCmdFmt);
 1296         if (!atCmd(tmCmd, AT_CONNECT))
 1297             return (false);
 1298         pause(conf.class1TMConnectDelay);
 1299         }
 1300         dolongtrain = false;
 1301 
 1302         // The block is assembled.  Transmit it, adding transparent DLEs.  End with DLE+ETX.
 1303         u_char buf[2];
 1304         if (!isSSLFax && useV34) {
 1305         // switch to primary channel
 1306         buf[0] = DLE; buf[1] = 0x6B;    // <DLE><pri>
 1307         HDLCFrame rtncframe(conf.class1FrameOverhead);
 1308         u_short limit = 5;
 1309         bool gotprate, gotrtncframe = false;
 1310         // wait for the ready indicator, <DLE><pri><DLE><prate>
 1311         do {
 1312             if (!putModemData(buf, 2)) return (false);
 1313             gotprate = waitForDCEChannel(false);
 1314             if (!gotprate && ctrlFrameRcvd != fxStr::null) {
 1315             /*
 1316              * Maybe we took so long to assemble the block that 
 1317              * the receiver has retransmitted CFR or MCF.
 1318              */
 1319             for (u_int i = 0; i < ctrlFrameRcvd.length(); i++)
 1320                 rtncframe.put(frameRev[ctrlFrameRcvd[i] & 0xFF]);
 1321             traceHDLCFrame("-->", rtncframe);
 1322             gotrtncframe = true;
 1323             }
 1324         } while (!gotprate && gotrtncframe && --limit);
 1325         if (renegotiate) {
 1326             // Although spec says this can be done any time,
 1327             // in practice it must be done at this moment.
 1328             renegotiatePrimary(constrain);
 1329             renegotiate = false;
 1330             constrain = false;
 1331         }
 1332         }
 1333         if (!isSSLFax && useV34) {
 1334         // we intentionally do not send the FCS bytes as the DCE regenerates them
 1335         // send fcount frames separated by <DLE><ETX>
 1336         u_short v34frame;
 1337         for (v34frame = 0; v34frame < fcount; v34frame++) {
 1338             if (!sendClass1Data(ecmStuffedBlock, frameSize + 4, bitrev, true, getDataTimeout()))
 1339             return (false);
 1340             ecmStuffedBlock += (frameSize + 6);
 1341         }
 1342         // send 3 RCP frames separated by <DLE><ETX>
 1343         for (v34frame = 0; v34frame < 3; v34frame++) {
 1344             if (!sendClass1Data(ecmStuffedBlock, 3, bitrev, true, getDataTimeout()))
 1345             return (false);
 1346             ecmStuffedBlock += 5;
 1347         }
 1348         ecmStuffedBlock -= ecmStuffedBlockPos;
 1349         } else {
 1350         if (!sendClass1Data(ecmStuffedBlock, ecmStuffedBlockPos, bitrev, true, getDataTimeout()) && !wasSSLFax)
 1351             return (false);
 1352         }
 1353         if (!isSSLFax && !wasSSLFax && useV34) {
 1354         // switch to control channel
 1355         buf[0] = DLE; buf[1] = 0x6D;    // <DLE><ctrl>
 1356         if (!putModemData(buf, 2)) return (false);
 1357         // wait for the ready indicator, <DLE><ctrl><DLE><crate>
 1358         if (!waitForDCEChannel(true)) {
 1359             emsg = "Failed to properly open control V.34 channel. {E116}";
 1360             protoTrace(emsg);
 1361             return (false);
 1362         }
 1363         } else if (!wasSSLFax && !isSSLFax) {
 1364         // Wait for transmit buffer to empty.
 1365         ATResponse r;
 1366         while ((r = atResponse(rbuf, getDataTimeout())) == AT_OTHER);
 1367             if (!(r == AT_OK)) {
 1368             if (r == AT_NOCARRIER) {
 1369             /*
 1370              * The NO CARRIER result here is not per-spec.  However,
 1371              * some modems capable of detecting hangup conditions will
 1372              * use this to indicate a disconnection.  Because we did
 1373              * not check for modem responses during the entire data
 1374              * transfer we flush the modem input so as to avoid reading
 1375              * any modem responses related to misinterpreted Phase C
 1376              * data that occurred after the hangup.
 1377              */
 1378             flushModemInput();
 1379             }
 1380             return (false);
 1381         }
 1382         }
 1383         if (wasSSLFax) wasSSLFax = false;
 1384 
 1385         if (flowControl == FLOW_XONXOFF)
 1386         setXONXOFF(FLOW_NONE, FLOW_NONE, ACT_DRAIN);
 1387 
 1388         if (!isSSLFax && !useV34 && !atCmd(ppmcmd == FCF_MPS ? conf.class1PPMWaitCmd : conf.class1EOPWaitCmd, AT_OK)) {
 1389         emsg = "Stop and wait failure (modem on hook) {E127}";
 1390         protoTrace(emsg);
 1391         return (false);
 1392         }
 1393         /*
 1394          * Build PPS frame and send it.  We don't use I3 = 0xFF when sending
 1395          * zero-count frames because some receivers will read it as 256.
 1396          * Instead we send I3 = 0x00, which technically indicates one frame,
 1397          * but it should be harmless since any interpretation of I3 will not
 1398          * exceed previous indications, and the receiver has already acknowledged
 1399          * all frames properly received.  I3 indicates the *unique* frame count.
 1400          */
 1401         char pps[4];
 1402         if (!lastblock)
 1403         pps[0] = 0x00;
 1404         else
 1405         pps[0] = ppmcmd | 0x80;
 1406         pps[1] = frameRev[(FaxModem::getPageNumberOfCall() - 1) & 0xFF];    // rolls-over after 256
 1407         pps[2] = frameRev[blockNumber];
 1408         pps[3] = frameRev[(fcountuniq == 0 ? 0 : (fcountuniq - 1))];
 1409         dataSent += fcountuniq;
 1410         u_short ppscnt = 0, crpcnt = 0;
 1411         bool gotppr = false;
 1412         /* get MCF/PPR/RNR */
 1413         HDLCFrame pprframe(conf.class1FrameOverhead);
 1414         do {
 1415         if (!isSSLFax && !useV34 && !atCmd(thCmd, AT_CONNECT))
 1416             break;
 1417         startTimeout(3000);
 1418         sendFrame(FCF_PPS|FCF_SNDR, fxStr(pps, 4));
 1419         stopTimeout("sending PPS frame");
 1420         traceFCF("SEND send", FCF_PPS);
 1421         traceFCF("SEND send", pps[0]);
 1422 
 1423         // Some receivers will almost always miss our first PPS message, and
 1424         // in those cases waiting T2 for a response will cause the remote to
 1425         // hang up.  So, using T4 here is imperative so that our second PPS
 1426         // message happens before the remote decides to hang up. As we're in
 1427         // a "RESPONSE REC" operation, anyway, this is correct behavior.
 1428         //
 1429         // We don't use CRP here, because it isn't well-received.
 1430         do {
 1431             gotppr = recvFrame(pprframe, FCF_SNDR, conf.t4Timer, false, false);
 1432         } while (pprframe.getFCF() == FCF_PPS && crpcnt++ < 3);     // handle echo of our PPS
 1433         if (gotppr) {
 1434             traceFCF("SEND recv", pprframe.getFCF());
 1435             if (pprframe.getFCF() == FCF_CRP) {
 1436             gotppr = false;
 1437             crpcnt++;
 1438             ppscnt = 0;
 1439             if (!switchingPause(emsg)) {
 1440                 return (false);
 1441             }
 1442             }
 1443         }
 1444         } while (!gotppr && (++ppscnt < 3) && (crpcnt < 3) && !(useV34 && gotEOT));
 1445         if (gotppr) {
 1446         if (!switchingPause(emsg)) {
 1447             return (false);
 1448         }
 1449         if (pprframe.getFCF() == FCF_RNR) {
 1450             u_int t1 = howmany(conf.t1Timer, 1000);
 1451             time_t start = Sys::now();
 1452             gotppr = false;
 1453             do {
 1454             if ((unsigned) Sys::now()-start >= t1) {
 1455                 // we use T1 rather than T5 to "minimize transmission inefficiency" (T.30 A.5.4.1)
 1456                 emsg = "Receiver flow control exceeded timer. {E138}";
 1457                 if (ppmcmd == FCF_EOM) batchingError = true;
 1458                 protoTrace(emsg);
 1459                 return (false);
 1460             }
 1461             u_short rrcnt = 0, crpcnt = 0;
 1462             bool gotmsg = false;
 1463             do {
 1464                 if (!isSSLFax && !useV34 && !atCmd(thCmd, AT_CONNECT))
 1465                 break;
 1466                 startTimeout(3000);
 1467                 sendFrame(FCF_RR|FCF_SNDR);
 1468                 stopTimeout("sending RR frame");
 1469                 traceFCF("SEND send", FCF_RR);
 1470                 // T.30 states that we must wait no more than T4 between unanswered RR signals.
 1471                 gotmsg = recvFrame(pprframe, FCF_SNDR, conf.t4Timer, false, false);
 1472                 if (gotmsg) {   // no CRP, stick to RR only
 1473                 traceFCF("SEND recv", pprframe.getFCF());
 1474                 if (pprframe.getFCF() == FCF_CRP) {
 1475                     gotmsg = false;
 1476                     crpcnt++;
 1477                     rrcnt = 0;
 1478                     if (!switchingPause(emsg)) {
 1479                     return (false);
 1480                     }
 1481                 }
 1482                 }
 1483             } while (!gotmsg && (++rrcnt < 3) && (crpcnt < 3) && switchingPause(emsg));
 1484             if (!gotmsg) {
 1485                 emsg = "No response to RR repeated 3 times. {E139}";
 1486                 protoTrace(emsg);
 1487                 return (false);
 1488             }
 1489             switch (pprframe.getFCF()) {
 1490                 case FCF_PPR:
 1491                 case FCF_MCF:
 1492                 gotppr = true;
 1493                 break;
 1494                 case FCF_RNR:
 1495                 if (!switchingPause(emsg)) {
 1496                     return (false);
 1497                 }
 1498                 break;
 1499                 default:
 1500                 emsg = "COMREC invalid response received to RR. {E140}";
 1501                 protoTrace(emsg);
 1502                 return (false);
 1503             }
 1504             } while (!gotppr);      
 1505         }
 1506         bool doctceor;
 1507         switch (pprframe.getFCF()) {
 1508             case FCF_MCF:
 1509             case FCF_PIP:
 1510             hadV34Trouble = false;
 1511             blockgood = true;
 1512             signalRcvd = pprframe.getFCF();
 1513             break;
 1514             case FCF_PPR:
 1515             {
 1516                 pprcnt++;
 1517                 // update ppr
 1518                 for (u_int i = 3; i < (pprframe.getLength() - (conf.class1FrameOverhead - 2)); i++) {
 1519                 ppr[i-3] = pprframe[i];
 1520                 }
 1521                 badframesbefore = badframes;
 1522                 badframes = 0;
 1523                 for (u_int j = 0; j < frameNumber; j++) {
 1524                 u_int pprpos, pprval;
 1525                 for (pprpos = 0, pprval = j; pprval >= 8; pprval -= 8) pprpos++;
 1526                 if (ppr[pprpos] & frameRev[1 << pprval]) {
 1527                     badframes++;
 1528                 }
 1529                 }
 1530                 dataMissed += badframes;
 1531             }
 1532             doctceor = (pprcnt == 4);
 1533             /*
 1534              * T.30 Annex F prohibits CTC in V.34-Fax.  Per the spec our options
 1535              * are to do EOR or DCN.  However, many receivers will allow us to
 1536              * simply continue sending image blocks followed by PPS.  Coupled with
 1537              * primary rate negotiations, this becomes a better-than-CTC solution.
 1538              * Do this up to 12 attempts and only when something has gotten through.
 1539              */
 1540             if (isSSLFax || useV34) {
 1541                 if (!isSSLFax && useV34 && pprcnt >= 4 && badframes) hadV34Trouble = true;  // problematic V.34?
 1542                 if (pprcnt == 8) doctceor = true;
 1543                 if (conf.class1PersistentECM && badframes && badframes != frameNumber) doctceor = false;
 1544                 if (pprcnt == 12) doctceor = true;
 1545                 if (!doctceor && badframes && badframes >= (badframesbefore / 2)) {
 1546                 /*
 1547                  * Request to renegotiate the primary rate.  (T.31-A1 B.8.5)
 1548                  * In practice, if we do not constrain the rate then
 1549                  * we may likely speed up the rate; so we constrain it.
 1550                  */
 1551                 renegotiate = true;
 1552                 constrain = true;
 1553                 }
 1554             }
 1555             if (doctceor) {
 1556                 pprcnt = 0;
 1557                 // Some receivers will ignorantly transmit PPR showing all frames good,
 1558                 // so if that's the case then do EOR instead of CTC.
 1559                 if (badframes == 0) {
 1560                 hadV34Trouble = false;
 1561                 blockgood = true;
 1562                 signalRcvd = FCF_MCF;
 1563                 }
 1564                 if (!isSSLFax && !useV34 && curcap->mod == V17 && badframes == frameNumber && FaxModem::getPageNumberOfCall() == 1) {
 1565                 // looks like a V.17 modulator incompatibility that managed to pass TCF
 1566                 // we set hasV17Trouble to help future calls to this destination
 1567                 protoTrace("The destination appears to have trouble with V.17.");
 1568                 hadV17Trouble = true;
 1569                 }
 1570                 // There is no CTC with V.34-fax (T.30 Annex F.3.4.5 Note 1).
 1571                 if (conf.class1PersistentECM && !isSSLFax && !useV34 && (blockgood == false) && 
 1572                 !((curcap->br == 0) && (badframes >= badframesbefore))) {
 1573                 /*
 1574                  * We send ctc even at 2400 baud if we're getting somewhere, and
 1575                  * often training down to a slower speed only makes matters worse.
 1576                  * So, if we seem to be making adequate progress we don't train down.
 1577                  */
 1578                 if (curcap->br != 0 && (badframes >= badframesbefore/2)) {
 1579                     u_char oldmod = curcap->mod;
 1580                     do {
 1581                     if (!dropToNextBR(params)) {
 1582                         // We have a minimum speed that's not BR_2400,
 1583                         // and we're there now.  Undo curcap change...
 1584                         curcap++;
 1585                     }
 1586                     // drop to the next modulation protocol if we're not getting anywhere
 1587                     } while (curcap->br != 0 && badframes >= badframesbefore && curcap->mod == oldmod);
 1588                 }
 1589                 char ctc[2];
 1590                 ctc[0] = 0;
 1591                 ctc[1] = curcap->sr >> 8;
 1592                 bool gotctr = false;
 1593                 u_short ctccnt = 0, crpcnt = 0;
 1594                 HDLCFrame ctrframe(conf.class1FrameOverhead);
 1595                 do {
 1596                     if (!atCmd(thCmd, AT_CONNECT))
 1597                     break;
 1598                     startTimeout(3000);
 1599                     sendFrame(FCF_CTC|FCF_SNDR, fxStr(ctc, 2));
 1600                     stopTimeout("sending CTC frame");
 1601                     traceFCF("SEND send", FCF_CTC);
 1602                     gotctr = recvFrame(ctrframe, FCF_SNDR, conf.t4Timer);
 1603                     if (gotctr) {
 1604                     traceFCF("SEND recv", ctrframe.getFCF());
 1605                     if (ctrframe.getFCF() == FCF_CRP) {
 1606                         gotctr = false;
 1607                         crpcnt++;
 1608                         ctccnt = 0;
 1609                         if (!switchingPause(emsg)) {
 1610                         return (false);
 1611                         }
 1612                     }
 1613                     }
 1614                 } while (!gotctr && (++ctccnt < 3) && (crpcnt < 3));
 1615                 if (!gotctr) {
 1616                     emsg = "No response to CTC repeated 3 times. {E141}";
 1617                     protoTrace(emsg);
 1618                     return (false);
 1619                 }
 1620                 if (!(ctrframe.getFCF() == FCF_CTR)) {
 1621                     emsg = "COMREC invalid response received to CTC. {E142}";
 1622                     protoTrace(emsg);
 1623                     return (false);
 1624                 }
 1625                 setDataTimeout(60, params.br);  // adjust dataTimeout to new bitrate
 1626                 dolongtrain = true; // T.30 states that we must use long-training next
 1627                 } else {
 1628                 /*
 1629                  * At this point data corruption is inevitable if all data
 1630                  * frames have not been received correctly.  With MH and MR 
 1631                  * data formats this may be tolerable if the bad frames are 
 1632                  * few and not in an unfortunate sequence.  With MMR data the
 1633                  * receiving decoder should truncate the image at the point
 1634                  * of the corruption.  The effect of corruption in JBIG or JPEG
 1635                  * data is quite unpredictable.  So if all frames have not been
 1636                  * received correctly and we're looking at an unacceptable
 1637                  * imaging situation on the receiver's end, then we disconnect,
 1638                  * and hopefully we try again successfully.
 1639                  */
 1640                 if (blockgood == false && (params.df >= DF_2DMMR ||
 1641                     (params.df <= DF_2DMR && badframes > frameNumber/2))) {
 1642                     emsg = "Failure to transmit clean ECM image data. {E143}";
 1643                     protoTrace(emsg);
 1644                     return (false);
 1645                 }
 1646                 bool goterr = false;
 1647                 u_short eorcnt = 0, crpcnt = 0;
 1648                 HDLCFrame errframe(conf.class1FrameOverhead);
 1649                 do {
 1650                     if (!isSSLFax && !useV34 && !atCmd(thCmd, AT_CONNECT))
 1651                     break;
 1652                     startTimeout(3000);
 1653                     sendFrame(FCF_EOR|FCF_SNDR, fxStr(pps, 1));
 1654                     stopTimeout("sending EOR frame");
 1655                     traceFCF("SEND send", FCF_EOR);
 1656                     traceFCF("SEND send", pps[0]);
 1657                     goterr = recvFrame(errframe, FCF_SNDR, conf.t4Timer);
 1658                     if (goterr) {
 1659                     traceFCF("SEND recv", errframe.getFCF());
 1660                     if (errframe.getFCF() == FCF_CRP) {
 1661                         goterr = false;
 1662                         crpcnt++;
 1663                         eorcnt = 0;
 1664                         if (!switchingPause(emsg)) {
 1665                         return (false);
 1666                         }
 1667                     }
 1668                     }
 1669                 } while (!goterr && (++eorcnt < 3) && (crpcnt < 3));
 1670                 if (!goterr) {
 1671                     emsg = "No response to EOR repeated 3 times. {E144}";
 1672                     if (ppmcmd == FCF_EOM) batchingError = true;
 1673                     protoTrace(emsg);
 1674                     return (false);
 1675                 }
 1676                 if (errframe.getFCF() == FCF_RNR) {
 1677                     u_int t1 = howmany(conf.t1Timer, 1000);
 1678                     time_t start = Sys::now();
 1679                     goterr = false;
 1680                     do {
 1681                     if ((unsigned) Sys::now()-start >= t1) {
 1682                         // we use T1 rather than T5 to "minimize transmission inefficiency" (T.30 A.5.4.1)
 1683                         emsg = "Receiver flow control exceeded timer. {E138}";
 1684                         if (ppmcmd == FCF_EOM) batchingError = true;
 1685                         protoTrace(emsg);
 1686                         return (false);
 1687                     }
 1688                     u_short rrcnt = 0, crpcnt = 0;
 1689                     bool gotmsg = false;
 1690                     do {
 1691                         if (!isSSLFax && !useV34 && !atCmd(thCmd, AT_CONNECT))
 1692                         break;
 1693                         startTimeout(3000);
 1694                         sendFrame(FCF_RR|FCF_SNDR);
 1695                         stopTimeout("sending RR frame");
 1696                         traceFCF("SEND send", FCF_RR);
 1697                         // T.30 states that we must wait no more than T4 between unanswered RR signals.
 1698                         gotmsg = recvFrame(errframe, FCF_SNDR, conf.t4Timer, false, false);
 1699                         if (gotmsg) {   // no CRP, stick to RR only
 1700                         traceFCF("SEND recv", errframe.getFCF());
 1701                         if (errframe.getFCF() == FCF_CRP) {
 1702                             gotmsg = false;
 1703                             crpcnt++;
 1704                             rrcnt = 0;
 1705                             if (!switchingPause(emsg)) {
 1706                             return (false);
 1707                             }
 1708                         }
 1709                         }
 1710                     } while (!gotmsg && (++rrcnt < 3) && (crpcnt < 3) && switchingPause(emsg));
 1711                     if (!gotmsg) {
 1712                         emsg = "No response to RR repeated 3 times. {E139}";
 1713                         protoTrace(emsg);
 1714                         return (false);
 1715                     }
 1716                     switch (errframe.getFCF()) {
 1717                         case FCF_ERR:
 1718                         goterr = true;
 1719                         break;
 1720                         case FCF_RNR:
 1721                         if (!switchingPause(emsg)) {
 1722                             return (false);
 1723                         }
 1724                         break;
 1725                         default:
 1726                         emsg = "COMREC invalid response received to RR. {E140}";
 1727                         protoTrace(emsg);
 1728                         return (false);
 1729                     }
 1730                     } while (!goterr);      
 1731                 }
 1732                 if (!(errframe.getFCF() == FCF_ERR)) {
 1733                     emsg = "COMREC invalid response received to EOR. {E145}";
 1734                     protoTrace(emsg);
 1735                     return (false);
 1736                 }
 1737                 blockgood = true;
 1738                 signalRcvd = FCF_MCF;
 1739                 }
 1740             }
 1741             break;
 1742             default:
 1743             emsg = "COMREC invalid response received to PPS. {E146}";
 1744             protoTrace(emsg);
 1745             return(false);
 1746         }
 1747         } else {
 1748         emsg = "No response to PPS repeated 3 times. {E147}";
 1749         if (ppmcmd == FCF_EOM) batchingError = true;
 1750         protoTrace(emsg);
 1751         return (false);
 1752         }
 1753     } while (!blockgood);
 1754     frameNumber = 0;
 1755     if (lastblock) blockNumber = 0;
 1756     else blockNumber++;
 1757     }
 1758     return (true);
 1759 }
 1760 
 1761 /*
 1762  * Send T.30-A framed image data.
 1763  */
 1764 bool
 1765 Class1Modem::sendClass1ECMData(const u_char* data, u_int cc, const u_char* bitrev, bool eod, u_int ppmcmd, fxStr& emsg)
 1766 {
 1767     /*
 1768      * Buffer data into the block.  We buffer the entire block
 1769      * before sending it to prevent any modem buffer underruns.
 1770      * Later we send it to sendClass1Data() which adds the 
 1771      * transparent DLE characters and transmits it.
 1772      */
 1773     for (u_int i = 0; i < cc; i++) {
 1774     if (ecmFramePos == 0) {
 1775         ecmFrame[ecmFramePos++] = 0xff;     // address field
 1776         ecmFrame[ecmFramePos++] = 0xc0; // control field
 1777         ecmFrame[ecmFramePos++] = 0x60; // FCD FCF
 1778         ecmFrame[ecmFramePos++] = frameRev[frameNumber++];  // block frame number
 1779     }
 1780     ecmFrame[ecmFramePos++] = frameRev[data[i]];
 1781     if (ecmFramePos == (frameSize + 4)) {
 1782         bool lastframe = ((i == (cc - 1)) && eod);
 1783         if (!blockFrame(bitrev, lastframe, ppmcmd, emsg))
 1784         return (false);
 1785         if (lastframe)
 1786         return (true);
 1787     }
 1788     }
 1789     if (eod) {
 1790     if (ecmFramePos != 0)   {
 1791         // frame must be filled to end with zero-data
 1792         while (ecmFramePos < (frameSize + 4)) ecmFrame[ecmFramePos++] = 0x00;
 1793     }
 1794     if (!blockFrame(bitrev, true, ppmcmd, emsg))
 1795         return (false);
 1796     }
 1797     return (true);
 1798 }
 1799 
 1800 /*
 1801  * Send data for the current page.
 1802  */
 1803 bool
 1804 Class1Modem::sendPageData(u_char* data, u_int cc, const u_char* bitrev, bool ecm, fxStr& emsg)
 1805 {
 1806     if (imagefd > 0) Sys::write(imagefd, (const char*) data, cc);
 1807     beginTimedTransfer();
 1808     bool rc;
 1809     if (ecm)
 1810     rc = sendClass1ECMData(data, cc, bitrev, false, 0, emsg);
 1811     else {
 1812     rc = sendClass1Data(data, cc, bitrev, false, getDataTimeout());
 1813     protoTrace("SENT %u bytes of data", cc);
 1814     }
 1815     endTimedTransfer();
 1816     if (wasSSLFax) {
 1817     /*
 1818      * A value of false for rc here means that there was an error in writing the data.
 1819      * If there was an error writing to the modem, then this would be fatal.  But, because
 1820      * it was an error writing SSL Fax data, then we need to fall back to the modem
 1821      * rather than turning the SSL Fax write error into a fatal condition.
 1822      */
 1823     rc = true;
 1824     }
 1825     return rc;
 1826 }
 1827 
 1828 /*
 1829  * Send RTC to terminate a page.  Note that we pad the
 1830  * RTC with zero fill to "push it out on the wire".  It
 1831  * seems that some Class 1 modems do not immediately
 1832  * send all the data they are presented.
 1833  */
 1834 bool
 1835 Class1Modem::sendRTC(Class2Params params, u_int ppmcmd, uint32 rows, fxStr& emsg)
 1836 {
 1837     if (params.df > DF_2DMR) {
 1838     /*
 1839      * If we ever needed to send NEWLEN or other JBIG-terminating
 1840      * markers this is where we would do it.
 1841      */
 1842     //u_char newlen[8] = { 0xFF, 0x05, 
 1843     //    (rows>>24)&0xFF, (rows>>16)&0xFF, (rows>>8)&0xFF, rows&0xFF,
 1844     //    0xFF, 0x02 }; // SDNORM is added per spec
 1845     //return sendClass1ECMData(newlen, 8, rtcRev, true, ppmcmd, emsg);
 1846     return sendClass1ECMData(NULL, 0, rtcRev, true, ppmcmd, emsg);
 1847     }
 1848     /*
 1849      * These are intentionally reverse-encoded in order to keep
 1850      * rtcRev and bitrev in sendPage() in agreement.  They are also
 1851      * end-padded with zeros to help "push" them out of the modem.
 1852      * We explicitly set the zeros in the padding so as to prevent
 1853      * the "unset" garbage values from confusing the receiver.
 1854      * We don't send that padding with ECM, as it's unnecessary.
 1855      */
 1856     static const u_char RTC1D[9+20] =
 1857     { 0x00,0x08,0x80,0x00,0x08,0x80,0x00,0x08,0x80,
 1858       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 1859       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
 1860     static const u_char RTC2D[10+20] =
 1861     { 0x00,0x18,0x00,0x03,0x60,0x00,0x0C,0x80,0x01,0x30,
 1862       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
 1863       0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
 1864     if (params.is2D()) {
 1865     protoTrace("SEND 2D RTC");
 1866     if (params.ec != EC_DISABLE)
 1867         return sendClass1ECMData(RTC2D, 10, rtcRev, true, ppmcmd, emsg);
 1868     else
 1869         return sendClass1Data(RTC2D, sizeof (RTC2D), rtcRev, true, getDataTimeout());
 1870     } else {
 1871     protoTrace("SEND 1D RTC");
 1872     if (params.ec != EC_DISABLE)
 1873         return sendClass1ECMData(RTC1D, 9, rtcRev, true, ppmcmd, emsg);
 1874     else
 1875         return sendClass1Data(RTC1D, sizeof (RTC1D), rtcRev, true, getDataTimeout());
 1876     }
 1877 }
 1878 
 1879 #define EOLcheck(w,mask,code) \
 1880     if ((w & mask) == code) { w |= mask; return (true); }
 1881 
 1882 /*
 1883  * Check the last 24 bits of received T.4-encoded
 1884  * data (presumed to be in LSB2MSB bit order) for
 1885  * an EOL code and, if one is found, foul the data
 1886  * to insure future calls do not re-recognize an
 1887  * EOL code.
 1888  */
 1889 static bool
 1890 EOLcode(u_long& w)
 1891 {
 1892     if ((w & 0x00f00f) == 0) {
 1893     EOLcheck(w, 0x00f0ff, 0x000080);
 1894     EOLcheck(w, 0x00f87f, 0x000040);
 1895     EOLcheck(w, 0x00fc3f, 0x000020);
 1896     EOLcheck(w, 0x00fe1f, 0x000010);
 1897     }
 1898     if ((w & 0x00ff00) == 0) {
 1899     EOLcheck(w, 0x00ff0f, 0x000008);
 1900     EOLcheck(w, 0x80ff07, 0x000004);
 1901     EOLcheck(w, 0xc0ff03, 0x000002);
 1902     EOLcheck(w, 0xe0ff01, 0x000001);
 1903     }
 1904     if ((w & 0xf00f00) == 0) {
 1905     EOLcheck(w, 0xf0ff00, 0x008000);
 1906     EOLcheck(w, 0xf87f00, 0x004000);
 1907     EOLcheck(w, 0xfc3f00, 0x002000);
 1908     EOLcheck(w, 0xfe1f00, 0x001000);
 1909     }
 1910     return (false);
 1911 }
 1912 #undef EOLcheck
 1913 
 1914 /*
 1915  * Send a page of data.
 1916  */
 1917 bool
 1918 Class1Modem::sendPage(TIFF* tif, Class2Params& params, u_int pageChop, u_int ppmcmd, fxStr& emsg)
 1919 {
 1920     if (!useSSLFax && params.ec == EC_DISABLE) {    // ECM does it later
 1921     /*
 1922      * Set high speed carrier & start transfer.  If the
 1923      * negotiated modulation technique includes short
 1924      * training, then we use it here (it's used for all
 1925      * high speed carrier traffic other than the TCF).
 1926      */
 1927     fxStr tmCmd(curcap[HasShortTraining(curcap)].value, tmCmdFmt);
 1928     if (!atCmd(tmCmd, AT_CONNECT)) {
 1929         emsg = "Unable to establish message carrier {E148}";
 1930         protoTrace(emsg);
 1931         return (false);
 1932     }
 1933     // As with TCF, T.31 8.3.3 requires the DCE to report CONNECT at the beginning
 1934     // of transmission of the training pattern rather than at the end.  We pause here
 1935     // to allow the remote's +FRM to result in CONNECT.
 1936     pause(conf.class1TMConnectDelay);
 1937     if (flowControl == FLOW_XONXOFF)
 1938         setXONXOFF(FLOW_XONXOFF, FLOW_NONE, ACT_FLUSH);
 1939     }
 1940 
 1941     bool rc = true;
 1942     blockNumber = frameNumber = ecmBlockPos = ecmFramePos = ecmBitPos = ecmOnes = ecmByte = 0;
 1943     protoTrace("SEND begin page");
 1944 
 1945     tstrip_t nstrips = TIFFNumberOfStrips(tif);
 1946     uint32 rowsperstrip = 0;
 1947     if (nstrips > 0) {
 1948 
 1949     /*
 1950      * RTFCC may mislead us here, so we temporarily
 1951      * adjust params.
 1952      */
 1953     Class2Params newparams = params;
 1954     uint16 compression;
 1955     TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression);
 1956     if (!params.jp) {
 1957         if (compression != COMPRESSION_CCITTFAX4) {  
 1958         uint32 g3opts = 0;
 1959         TIFFGetField(tif, TIFFTAG_GROUP3OPTIONS, &g3opts);
 1960         if ((g3opts & GROUP3OPT_2DENCODING) == DF_2DMR)
 1961             params.df = DF_2DMR;
 1962         else
 1963             params.df = DF_1DMH;
 1964         } else
 1965         params.df = DF_2DMMR;
 1966     }
 1967 
 1968     /*
 1969      * Correct bit order of data if not what modem expects.
 1970      */
 1971     uint16 fillorder;
 1972     TIFFGetFieldDefaulted(tif, TIFFTAG_FILLORDER, &fillorder);
 1973     const u_char* bitrev =
 1974         TIFFGetBitRevTable(sendFillOrder != FILLORDER_LSB2MSB);
 1975     /*
 1976      * Setup tag line processing.
 1977      */
 1978     bool doTagLine = setupTagLineSlop(params);
 1979     u_int ts = getTagLineSlop();
 1980     /*
 1981      * Calculate total amount of space needed to read
 1982      * the image into memory (in its encoded format).
 1983      *
 1984      * It is tempting to want to use TIFFStripSize() instead
 1985      * of summing stripbytecounts, but the two are not equal.
 1986      */
 1987     TIFFSTRIPBYTECOUNTS* stripbytecount;
 1988     (void) TIFFGetField(tif, TIFFTAG_STRIPBYTECOUNTS, &stripbytecount);
 1989     tstrip_t strip;
 1990     u_long totdata = 0;
 1991     for (strip = 0; strip < nstrips; strip++)
 1992         totdata += stripbytecount[strip];
 1993     /*
 1994      * Read the image into memory.
 1995      */
 1996     u_char* data = new u_char[totdata+ts];
 1997     u_int off = ts;         // skip tag line slop area
 1998     for (strip = 0; strip < nstrips; strip++) {
 1999         uint32 sbc = stripbytecount[strip];
 2000         if (sbc > 0 && TIFFReadRawStrip(tif, strip, data+off, sbc) >= 0)
 2001         off += (u_int) sbc;
 2002     }
 2003     totdata -= pageChop;        // deduct trailing white space not sent
 2004     TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
 2005     if (rowsperstrip == (uint32) -1)
 2006         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &rowsperstrip);
 2007 
 2008     /*
 2009      * Image the tag line, if intended.
 2010      */
 2011     u_char* dp;
 2012     if (doTagLine) {
 2013         u_long totbytes = totdata;
 2014         dp = imageTagLine(data+ts, fillorder, params, totbytes);
 2015         // Because the whole image is processed with MMR, 
 2016         // totdata is then determined during encoding.
 2017         totdata = (params.df == DF_2DMMR) ? totbytes : totdata+ts - (dp-data);
 2018     } else
 2019         dp = data;
 2020 
 2021     /*
 2022      * After a page chop rowsperstrip is no longer valid, as the strip will
 2023      * be shorter.  Therefore, convertPhaseCData (for the benefit of supporting
 2024      * the sending of JBIG NEWLEN markers) and correctPhaseCData (only in the 
 2025      * case of MMR data) deliberately update rowsperstrip.  Page-chopped and
 2026      * un-converted MH and MR data will not have updated rowsperstrip.
 2027      * However, this only amounts to a allocating more memory than is needed,
 2028      * and this is not consequential.
 2029      */
 2030 
 2031     if (conf.softRTFCC && params.df != newparams.df) {
 2032         switch (params.df) {
 2033         case DF_1DMH:
 2034             protoTrace("Reading MH-compressed image file");
 2035             break;
 2036         case DF_2DMR:
 2037             protoTrace("Reading MR-compressed image file");
 2038             break;
 2039         case DF_2DMMR:
 2040             protoTrace("Reading MMR-compressed image file");
 2041             break;
 2042         }
 2043         dp = convertPhaseCData(dp, totdata, fillorder, params, newparams, rowsperstrip);
 2044         params = newparams;     // revert back
 2045     }
 2046 
 2047     if (params.jp) {
 2048 #if defined(HAVE_JPEG) && ( defined(HAVE_LCMS) || defined(HAVE_LCMS2) )
 2049         /*
 2050          * The image is in raw RGB data.  We now need to compress
 2051          * with JPEG and put into the right colorspace (ITULAB).
 2052          */
 2053         uint32 w, h;
 2054         TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
 2055         TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
 2056 #if HAS_NO_OPEN_MEMSTREAM
 2057         FILE* out = Sys::tmpfile();
 2058 #else
 2059         size_t outsize;
 2060         char *outptr;
 2061         FILE* out = open_memstream(&outptr, &outsize);
 2062 #endif
 2063         if (out) {
 2064         char kk[256];
 2065         bool ok = convertRawRGBtoITULAB(dp, off, w, h, out, kk, 256);
 2066         if (!ok || kk[0] != 0) {
 2067             emsg = fxStr::format("Error converting image to JPEG data: %s", kk);
 2068             protoTrace(emsg);
 2069             return (false);
 2070         }
 2071         // JPEG compression succeeded, redirect pointers
 2072 #if HAS_NO_OPEN_MEMSTREAM
 2073         totdata = ftell(out);
 2074         dp = (u_char*) malloc(totdata);
 2075         rewind(out);
 2076         fread(dp, 1, totdata, out);
 2077 #else
 2078         dp = (u_char*) outptr;
 2079         totdata = outsize;
 2080 #endif
 2081         fclose(out);
 2082         } else {
 2083 #endif
 2084         emsg = "Could not open JPEG conversion output stream.";
 2085         protoTrace(emsg);
 2086         return (false);
 2087 #if defined(HAVE_JPEG) && ( defined(HAVE_LCMS) || defined(HAVE_LCMS2) )
 2088         }
 2089 #endif
 2090     } else {
 2091         /*
 2092          * correct broken Phase C (T.4) data if neccessary 
 2093          */
 2094         if (params.df < DF_2DMMR)
 2095         correctPhaseCData(dp, totdata, fillorder, params, rowsperstrip);
 2096     }
 2097 
 2098     /*
 2099      * Send the page of data.  This is slightly complicated
 2100      * by the fact that we may have to add zero-fill before the
 2101      * EOL codes to bring the transmit time for each scanline
 2102      * up to the negotiated min-scanline time.
 2103      *
 2104      * Note that we blindly force the data to be in LSB2MSB bit
 2105      * order so that the EOL locating code works (if needed).
 2106      * This may result in two extraneous bit reversals if the
 2107      * modem wants the data in MSB2LSB order, but for now we'll
 2108      * avoid the temptation to optimize.
 2109      */
 2110     if (!params.jp && params.df <= DF_2DMMR && fillorder != FILLORDER_LSB2MSB) {
 2111         TIFFReverseBits(dp, totdata);
 2112     }
 2113 
 2114     /* For debugging purposes we may want to write the image-data to file. */
 2115     if (conf.saverawimage) imagefd = Sys::open("/tmp/out.fax", O_RDWR|O_CREAT|O_EXCL);
 2116 
 2117     u_int minLen = params.minScanlineSize();
 2118     if (minLen > 0) {           // only in non-ECM
 2119         /*
 2120          * Client requires a non-zero min-scanline time.  We
 2121          * comply by zero-padding scanlines that have <minLen
 2122          * bytes of data to send.  To minimize underrun we
 2123          * do this padding in a strip-sized buffer.
 2124          */
 2125         u_char* fill = new u_char[minLen*rowsperstrip];
 2126         u_char* eoFill = fill + minLen*rowsperstrip;
 2127         u_char* fp = fill;
 2128 
 2129         u_char* bp = dp;
 2130         u_char* ep = dp+totdata;
 2131         u_long w = 0xffffff;
 2132 
 2133             /*
 2134              * Immediately copy leading EOL into the fill buffer,
 2135              * because it has not to be padded. Note that leading
 2136              * EOL is not byte-aligned, and so we also copy 4 bits
 2137              * if image data. But that's OK, and may only lead to
 2138              * adding one extra zero-fill byte to the first image
 2139              * row.
 2140              */
 2141             *fp++ = *bp++;
 2142             *fp++ = *bp++;
 2143 
 2144         /*
 2145          * The modem buffers data.  We need to keep track of how much
 2146          * data has been sent to the modem and how much time has 
 2147          * elapsed in order to know a proper dataTimeout setting
 2148          * because the modem may have a lot of data buffered to it
 2149          * and we can't always rely on a constrained pipe and limited
 2150          * buffer to the modem to keep our needed wait-time to under
 2151          * the 60-second setting that dataTimeout presently has.
 2152          */
 2153         time_t start = Sys::now();
 2154         long pagedatasent = 0;
 2155 
 2156         do {
 2157         u_char* bol = bp;
 2158                 bool foundEOL;
 2159         do {
 2160             w = (w<<8) | *bp++;
 2161                     foundEOL = EOLcode(w);
 2162                 } while (!foundEOL && bp < ep);
 2163         /*
 2164                  * We're either after an EOL code or at the end of data.
 2165          * If necessary, insert zero-fill before the last byte
 2166          * in the EOL code so that we comply with the
 2167          * negotiated min-scanline time.
 2168          */
 2169         u_int lineLen = bp - bol;
 2170         if ((fp + fxmax(lineLen, minLen) >= eoFill) && (fp-fill != 0)) {
 2171             /*
 2172              * Not enough space for this scanline, flush
 2173              * the current data and reset the pointer into
 2174              * the zero fill buffer.
 2175              */
 2176             pagedatasent += fp-fill;
 2177             setDataTimeout(pagedatasent, Sys::now() - start, params.br);
 2178             rc = sendPageData(fill, fp-fill, bitrev, (params.ec != EC_DISABLE), emsg);
 2179             fp = fill;
 2180             if (!rc)            // error writing data
 2181             break;
 2182         }
 2183         if (lineLen >= minLen*rowsperstrip) {
 2184             /*
 2185              * The fill buffer is smaller than this
 2186              * scanline alone.  Flush this scanline
 2187              * also.  lineLen is greater than minLen.
 2188              */
 2189             pagedatasent += fp-fill;
 2190             setDataTimeout(pagedatasent, Sys::now() - start, params.br);
 2191             rc = sendPageData(bol, lineLen, bitrev, (params.ec != EC_DISABLE), emsg);
 2192             if (!rc)            // error writing
 2193             break;
 2194         } else {
 2195             memcpy(fp, bol, lineLen);   // first part of line
 2196             fp += lineLen;
 2197             if (lineLen < minLen) {     // must zero-fill
 2198             u_int zeroLen = minLen - lineLen;
 2199                     if ( foundEOL ) {
 2200                         memset(fp-1, 0, zeroLen);   // zero padding
 2201                 fp += zeroLen;
 2202                 fp[-1] = bp[-1];        // last byte in EOL
 2203             } else {
 2204                 /*
 2205                  * Last line does not contain EOL
 2206                  */
 2207                 memset(fp, 0, zeroLen); // zero padding
 2208                 fp += zeroLen;
 2209             }
 2210             }
 2211         }
 2212         } while (bp < ep);
 2213         /*
 2214          * Flush anything that was not sent above.
 2215          */
 2216         if (fp > fill && rc) {
 2217         pagedatasent += fp-fill;
 2218         setDataTimeout(pagedatasent, Sys::now() - start, params.br);
 2219         rc = sendPageData(fill, fp-fill, bitrev, (params.ec != EC_DISABLE), emsg);
 2220         }
 2221         delete[] fill;
 2222     } else {
 2223         /*
 2224          * No EOL-padding needed, just jam the bytes.
 2225          * We need to set a timeout appropriate to the data size and bitrate.
 2226          */
 2227         setDataTimeout(totdata, 0, params.br);
 2228         rc = sendPageData(dp, (u_int) totdata, bitrev, (params.ec != EC_DISABLE), emsg);
 2229     }
 2230     delete[] data;
 2231     if (imagefd > 0) {
 2232         Sys::close(imagefd);
 2233         imagefd = 0;
 2234     }
 2235     }
 2236     if (!wasSSLFax && (rc || abortRequested()))
 2237     rc = sendRTC(params, ppmcmd, rowsperstrip, emsg);
 2238     protoTrace("SEND end page");
 2239     if (params.ec == EC_DISABLE) {
 2240     // these were already done by ECM protocol
 2241     if (!wasSSLFax && !isSSLFax && rc) {
 2242         /*
 2243          * Wait for transmit buffer to empty.
 2244          */
 2245         ATResponse r;
 2246         while ((r = atResponse(rbuf, getDataTimeout())) == AT_OTHER)
 2247         ;
 2248         rc = (r == AT_OK);
 2249         if (r == AT_NOCARRIER) {
 2250         /*
 2251          * The NO CARRIER result here is not per-spec.  However,
 2252          * some modems capable of detecting hangup conditions will
 2253          * use this to indicate a disconnection.  Because we did
 2254          * not check for modem responses during the entire data
 2255          * transfer we flush the modem input so as to avoid reading
 2256          * any modem responses related to misinterpreted Phase C
 2257          * data that occurred after the hangup.
 2258          */
 2259         flushModemInput();
 2260         }
 2261     }
 2262     if (flowControl == FLOW_XONXOFF)
 2263         setXONXOFF(FLOW_NONE, FLOW_NONE, ACT_DRAIN);
 2264     }
 2265     if (wasSSLFax) {
 2266     /*
 2267      * Same reasoning here as in sendPageData().
 2268      */
 2269     wasSSLFax = false;
 2270     rc = true;
 2271     suppressSSLFax = true;  // since we're likely to get RTN and go back to Phase B let's avoid restarting SSL Fax
 2272     }
 2273     if (!rc && (emsg == "")) {
 2274     emsg = "Unspecified Transmit Phase C error {E149}"; // XXX
 2275         protoTrace(emsg);
 2276     }
 2277     return (rc);
 2278 }
 2279 
 2280 /*
 2281  * Send the post-page-message and wait for a response.
 2282  */
 2283 bool
 2284 Class1Modem::sendPPM(u_int ppm, HDLCFrame& mcf, fxStr& emsg)
 2285 {
 2286     for (int t = 0; t < 3; t++) {
 2287     traceFCF("SEND send", ppm);
 2288     // don't use CRP here because it isn't well-received
 2289     if (transmitFrame(ppm|FCF_SNDR)) {
 2290         bool ok = recvFrame(mcf, FCF_SNDR, conf.t4Timer, false, false);
 2291         if (ok && mcf.getFCF() == ppm) {
 2292         // We probably heard our own echo.  Listen again...
 2293         ok = recvFrame(mcf, FCF_SNDR, conf.t4Timer, false, false);
 2294         }
 2295         if (ok) return (true);
 2296     }
 2297     if (abortRequested())
 2298         return (false);
 2299     switchingPause(emsg);
 2300     }
 2301     switch (ppm) {
 2302     case FCF_MPS:
 2303         emsg = "No response to MPS repeated 3 tries {E150}";
 2304         break;
 2305     case FCF_EOP:
 2306         emsg = "No response to EOP repeated 3 tries {E151}";
 2307         break;
 2308     case FCF_EOM:
 2309         emsg = "No response to EOM repeated 3 tries {E152}";
 2310         break;
 2311     default:
 2312         emsg = "No response to PPM repeated 3 tries {E153}";
 2313         break;
 2314     }
 2315     protoTrace(emsg);
 2316     return (false);
 2317 }
 2318 
 2319 /*
 2320  * Terminate a send session.
 2321  */
 2322 void
 2323 Class1Modem::sendEnd()
 2324 {
 2325     if (!wasModemError()) {
 2326     fxStr emsg;
 2327     (void) switchingPause(emsg);
 2328     transmitFrame(FCF_DCN|FCF_SNDR);        // disconnect
 2329     setInputBuffering(true);
 2330     }
 2331 }
 2332 
 2333 /*
 2334  * Abort an active send session.
 2335  */
 2336 void
 2337 Class1Modem::sendAbort()
 2338 {
 2339     // nothing to do--DCN gets sent in sendEnd
 2340 }