Class1Send.c++
上传用户:weiyuanprp
上传日期:2020-05-20
资源大小:1169k
文件大小:66k
源码类别:

传真(Fax)编程

开发平台:

C/C++

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