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