Develop and Download Open Source Software

Browse Subversion Repository

Contents of /branches/ttcomtester/teraterm/teraterm/commlib.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 2577 - (show annotations) (download) (as text)
Fri Aug 15 14:35:43 2008 UTC (15 years, 7 months ago) by doda
Original Path: teraterm/trunk/teraterm/commlib.c
File MIME type: text/x-csrc
File size: 28176 byte(s)
シリアル接続/ログ再生時の入出力をフックするためのTTXインタフェースを追加。

1 /* Tera Term
2 Copyright(C) 1994-1998 T. Teranishi
3 All rights reserved. */
4 /* IPv6 modification is Copyright (C) 2000, 2001 Jun-ya KATO <kato@win6.jp> */
5
6 /* TERATERM.EXE, Communication routines */
7 #include "teraterm.h"
8 #include "tttypes.h"
9 #include "tt_res.h"
10 #include <process.h>
11
12 #include "ttcommon.h"
13 #include "ttwsk.h"
14 #include "ttlib.h"
15 #include "ttfileio.h"
16 #include "ttplug.h" /* TTPLUG */
17
18 #include "commlib.h"
19 #ifndef NO_INET6
20 #include <winsock2.h>
21 #include <ws2tcpip.h>
22 #include <stdio.h> /* for _snprintf() */
23 #include "WSAAsyncGetAddrInfo.h"
24 #endif /* NO_INET6 */
25 #include <time.h>
26
27 static SOCKET OpenSocket(PComVar);
28 static void AsyncConnect(PComVar);
29 static int CloseSocket(SOCKET);
30
31 /* create socket */
32 static SOCKET OpenSocket(PComVar cv)
33 {
34 cv->s = cv->res->ai_family;
35 cv->s = Psocket(cv->res->ai_family, cv->res->ai_socktype, cv->res->ai_protocol);
36 return cv->s;
37 }
38
39 /* connect with asynchronous mode */
40 static void AsyncConnect(PComVar cv)
41 {
42 int Err;
43 BOOL BBuf;
44 BBuf = TRUE;
45 /* set synchronous mode */
46 PWSAAsyncSelect(cv->s,cv->HWin,0,0);
47 Psetsockopt(cv->s,(int)SOL_SOCKET,SO_OOBINLINE,(char FAR *)&BBuf,sizeof(BBuf));
48 /* set asynchronous mode */
49 PWSAAsyncSelect(cv->s,cv->HWin,WM_USER_COMMOPEN, FD_CONNECT);
50
51 // �z�X�g���������������������������A�����I���\�P�b�g���N���[�Y�����A
52 // �����������L�����Z���������B�l��0�������������������B
53 // (2007.1.11 yutaka)
54 if (*cv->ConnetingTimeout > 0) {
55 SetTimer(cv->HWin, IdCancelConnectTimer, *cv->ConnetingTimeout * 1000, NULL);
56 }
57
58 /* WM_USER_COMMOPEN occurs, CommOpen is called, then CommStart is called */
59 Err = Pconnect(cv->s, cv->res->ai_addr, cv->res->ai_addrlen);
60 if (Err != 0) {
61 Err = PWSAGetLastError();
62 if (Err == WSAEWOULDBLOCK)
63 {
64 /* Do nothing */
65 } else if (Err!=0 ) {
66 PostMessage(cv->HWin, WM_USER_COMMOPEN,0,
67 MAKELONG(FD_CONNECT,Err));
68 }
69 }
70 }
71
72 /* close socket */
73 static int CloseSocket(SOCKET s)
74 {
75 return Pclosesocket(s);
76 }
77
78 #define CommInQueSize 8192
79 #define CommOutQueSize 2048
80 #define CommXonLim 2048
81 #define CommXoffLim 2048
82
83 #define READENDNAME "ReadEnd"
84 #define WRITENAME "Write"
85 #define READNAME "Read"
86 #define PRNWRITENAME "PrnWrite"
87
88 static HANDLE ReadEnd;
89 static OVERLAPPED wol, rol;
90
91 // Winsock async operation handle
92 static HANDLE HAsync=0;
93
94 BOOL TCPIPClosed = TRUE;
95
96 /* Printer port handle for
97 direct pass-thru printing */
98 static HANDLE PrnID = INVALID_HANDLE_VALUE;
99 static BOOL LPTFlag;
100
101 // Initialize ComVar.
102 // This routine is called only once
103 // by the initialization procedure of Tera Term.
104 void CommInit(PComVar cv)
105 {
106 cv->Open = FALSE;
107 cv->Ready = FALSE;
108
109 // log-buffer variables
110 cv->HLogBuf = 0;
111 cv->HBinBuf = 0;
112 cv->LogBuf = NULL;
113 cv->BinBuf = NULL;
114 cv->LogPtr = 0;
115 cv->LStart = 0;
116 cv->LCount = 0;
117 cv->BinPtr = 0;
118 cv->BStart = 0;
119 cv->BCount = 0;
120 cv->DStart = 0;
121 cv->DCount = 0;
122 cv->BinSkip = 0;
123 cv->FilePause = 0;
124 cv->ProtoFlag = FALSE;
125 /* message flag */
126 cv->NoMsg = 0;
127 }
128
129 /* reset a serial port which is already open */
130 void CommResetSerial(PTTSet ts, PComVar cv, BOOL ClearBuff)
131 {
132 DCB dcb;
133 DWORD DErr;
134 COMMTIMEOUTS ctmo;
135
136 if (! cv->Open ||
137 (cv->PortType != IdSerial)) return;
138
139 ClearCommError(cv->ComID,&DErr,NULL);
140 SetupComm(cv->ComID,CommInQueSize,CommOutQueSize);
141 /* flush input and output buffers */
142 if (ClearBuff)
143 PurgeComm(cv->ComID, PURGE_TXABORT | PURGE_RXABORT |
144 PURGE_TXCLEAR | PURGE_RXCLEAR);
145
146 memset(&ctmo,0,sizeof(ctmo));
147 ctmo.ReadIntervalTimeout = MAXDWORD;
148 ctmo.WriteTotalTimeoutConstant = 500;
149 SetCommTimeouts(cv->ComID,&ctmo);
150 cv->InBuffCount = 0;
151 cv->InPtr = 0;
152 cv->OutBuffCount = 0;
153 cv->OutPtr = 0;
154
155 cv->DelayPerChar = ts->DelayPerChar;
156 cv->DelayPerLine = ts->DelayPerLine;
157
158 memset(&dcb,0,sizeof(DCB));
159 dcb.DCBlength = sizeof(DCB);
160 switch (ts->Baud) {
161 case IdBaud110: dcb.BaudRate = 110; break;
162 case IdBaud300: dcb.BaudRate = 300; break;
163 case IdBaud600: dcb.BaudRate = 600; break;
164 case IdBaud1200: dcb.BaudRate = 1200; break;
165 case IdBaud2400: dcb.BaudRate = 2400; break;
166 case IdBaud4800: dcb.BaudRate = 4800; break;
167 case IdBaud9600: dcb.BaudRate = 9600; break;
168 case IdBaud14400: dcb.BaudRate = 14400; break;
169 case IdBaud19200: dcb.BaudRate = 19200; break;
170 case IdBaud38400: dcb.BaudRate = 38400; break;
171 case IdBaud57600: dcb.BaudRate = 57600; break;
172 case IdBaud115200: dcb.BaudRate = 115200; break;
173 // add (2005.11.30 yutaka)
174 case IdBaud230400: dcb.BaudRate = 230400; break;
175 case IdBaud460800: dcb.BaudRate = 460800; break;
176 case IdBaud921600: dcb.BaudRate = 921600; break;
177 }
178 dcb.fBinary = TRUE;
179 switch (ts->Parity) {
180 case IdParityEven:
181 dcb.fParity = TRUE;
182 dcb.Parity = EVENPARITY;
183 break;
184 case IdParityOdd:
185 dcb.fParity = TRUE;
186 dcb.Parity = ODDPARITY;
187 break;
188 case IdParityNone:
189 dcb.Parity = NOPARITY;
190 break;
191 }
192
193 dcb.fDtrControl = DTR_CONTROL_ENABLE;
194 dcb.fRtsControl = RTS_CONTROL_ENABLE;
195 switch (ts->Flow) {
196 case IdFlowX:
197 dcb.fOutX = TRUE;
198 dcb.fInX = TRUE;
199 dcb.XonLim = CommXonLim;
200 dcb.XoffLim = CommXoffLim;
201 dcb.XonChar = XON;
202 dcb.XoffChar = XOFF;
203 break;
204 case IdFlowHard:
205 dcb.fOutxCtsFlow = TRUE;
206 dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
207 break;
208 }
209
210 switch (ts->DataBit) {
211 case IdDataBit7: dcb.ByteSize = 7; break;
212 case IdDataBit8: dcb.ByteSize = 8; break;
213 }
214 switch (ts->StopBit) {
215 case IdStopBit1: dcb.StopBits = ONESTOPBIT; break;
216 case IdStopBit2: dcb.StopBits = TWOSTOPBITS; break;
217 }
218
219 SetCommState(cv->ComID, &dcb);
220
221 /* enable receive request */
222 SetCommMask(cv->ComID,0);
223 SetCommMask(cv->ComID,EV_RXCHAR);
224 }
225
226 void CommOpen(HWND HW, PTTSet ts, PComVar cv)
227 {
228 #ifdef NO_INET6
229 int Err;
230 #endif /* NO_INET6 */
231 char ErrMsg[21];
232 char P[50];
233
234 MSG Msg;
235 #ifndef NO_INET6
236 ADDRINFO hints;
237 char pname[NI_MAXSERV];
238 #else
239 char HEntBuff[MAXGETHOSTSTRUCT];
240 u_long addr;
241 SOCKADDR_IN saddr;
242 #endif /* NO_INET6 */
243
244 BOOL InvalidHost;
245 #ifdef NO_INET6
246 BOOL BBuf;
247 #endif /* NO_INET6 */
248
249 char uimsg[MAX_UIMSG];
250
251 /* initialize ComVar */
252 cv->InBuffCount = 0;
253 cv->InPtr = 0;
254 cv->OutBuffCount = 0;
255 cv->OutPtr = 0;
256 cv->HWin = HW;
257 cv->Ready = FALSE;
258 cv->Open = FALSE;
259 cv->PortType = ts->PortType;
260 cv->ComPort = 0;
261 cv->RetryCount = 0;
262 #ifndef NO_INET6
263 cv->RetryWithOtherProtocol = TRUE;
264 #endif /* NO_INET6 */
265 cv->s = INVALID_SOCKET;
266 cv->ComID = INVALID_HANDLE_VALUE;
267 cv->CanSend = TRUE;
268 cv->RRQ = FALSE;
269 cv->SendKanjiFlag = FALSE;
270 cv->SendCode = IdASCII;
271 cv->EchoKanjiFlag = FALSE;
272 cv->EchoCode = IdASCII;
273 cv->Language = ts->Language;
274 cv->CRSend = ts->CRSend;
275 cv->KanjiCodeEcho = ts->KanjiCode;
276 cv->JIS7KatakanaEcho = ts->JIS7Katakana;
277 cv->KanjiCodeSend = ts->KanjiCodeSend;
278 cv->JIS7KatakanaSend = ts->JIS7KatakanaSend;
279 cv->KanjiIn = ts->KanjiIn;
280 cv->KanjiOut = ts->KanjiOut;
281 cv->RussHost = ts->RussHost;
282 cv->RussClient = ts->RussClient;
283 cv->DelayFlag = TRUE;
284 cv->DelayPerChar = ts->DelayPerChar;
285 cv->DelayPerLine = ts->DelayPerLine;
286 cv->TelBinRecv = FALSE;
287 cv->TelBinSend = FALSE;
288 cv->TelFlag = FALSE;
289 cv->TelMode = FALSE;
290 cv->IACFlag = FALSE;
291 cv->TelCRFlag = FALSE;
292 cv->TelCRSend = FALSE;
293 cv->TelCRSendEcho = FALSE;
294 cv->TelAutoDetect = ts->TelAutoDetect; /* TTPLUG */
295 cv->Locale = ts->Locale;
296 cv->CodePage = &ts->CodePage;
297 cv->ConnetingTimeout = &ts->ConnectingTimeout;
298 cv->LastSendTime = time(NULL);
299
300 if ((ts->PortType!=IdSerial) && (strlen(ts->HostName)==0))
301 {
302 PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_CLOSE);
303 return;
304 }
305
306 switch (ts->PortType) {
307 case IdTCPIP:
308 cv->TelFlag = (ts->Telnet > 0);
309 if (! LoadWinsock())
310 {
311 if (cv->NoMsg==0)
312 {
313 get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile);
314 get_lang_msg("MSG_WINSOCK_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot use winsock", ts->UILanguageFile);
315 MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION);
316 }
317 InvalidHost = TRUE;
318 }
319 else {
320 TTXOpenTCP(); /* TTPLUG */
321 cv->Open = TRUE;
322 #ifndef NO_INET6
323 /* resolving address */
324 memset(&hints, 0, sizeof(hints));
325 hints.ai_family = ts->ProtocolFamily;
326 hints.ai_socktype = SOCK_STREAM;
327 hints.ai_protocol = IPPROTO_TCP;
328 _snprintf_s(pname, sizeof(pname), _TRUNCATE, "%d", ts->TCPPort);
329
330 HAsync = WSAAsyncGetAddrInfo(HW, WM_USER_GETHOST,
331 ts->HostName, pname, &hints, &cv->res0);
332 if (HAsync == 0)
333 InvalidHost = TRUE;
334 else {
335 cv->ComPort = 1; // set "getting host" flag
336 // (see CVTWindow::OnSysCommand())
337 do {
338 if (GetMessage(&Msg,0,0,0))
339 {
340 if ((Msg.hwnd==HW) &&
341 ((Msg.message == WM_SYSCOMMAND) &&
342 ((Msg.wParam & 0xfff0) == SC_CLOSE) ||
343 (Msg.message == WM_COMMAND) &&
344 (LOWORD(Msg.wParam) == ID_FILE_EXIT) ||
345 (Msg.message == WM_CLOSE)))
346 { /* Exit when the user closes Tera Term */
347 PWSACancelAsyncRequest(HAsync);
348 CloseHandle(HAsync);
349 HAsync = 0;
350 cv->ComPort = 0; // clear "getting host" flag
351 PostMessage(HW,Msg.message,Msg.wParam,Msg.lParam);
352 return;
353 }
354 if (Msg.message != WM_USER_GETHOST)
355 { /* Prosess messages */
356 TranslateMessage(&Msg);
357 DispatchMessage(&Msg);
358 }
359 }
360 else {
361 return;
362 }
363 } while (Msg.message!=WM_USER_GETHOST);
364 cv->ComPort = 0; // clear "getting host" flag
365 CloseHandle(HAsync);
366 HAsync = 0;
367 InvalidHost = WSAGETASYNCERROR(Msg.lParam) != 0;
368 }
369 } /* if (!LoadWinsock()) */
370
371 if (InvalidHost)
372 {
373 if (cv->NoMsg==0)
374 {
375 get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile);
376 get_lang_msg("MSG_INVALID_HOST_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Invalid host", ts->UILanguageFile);
377 MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION);
378 }
379 goto BreakSC;
380 }
381 for (cv->res = cv->res0; cv->res; cv->res = cv->res->ai_next) {
382 cv->s = OpenSocket(cv);
383 if (cv->s == INVALID_SOCKET) {
384 CloseSocket(cv->s);
385 continue;
386 }
387 /* start asynchronous connect */
388 AsyncConnect(cv);
389 break; /* break for-loop immediately */
390 }
391 break;
392 #else
393 if ((ts->HostName[0] >= 0x30) && (ts->HostName[0] <= 0x39))
394 {
395 addr = Pinet_addr(ts->HostName);
396 InvalidHost = (addr == 0xffffffff);
397 }
398 else {
399 HAsync = PWSAAsyncGetHostByName(HW,WM_USER_GETHOST,
400 ts->HostName,HEntBuff,sizeof(HEntBuff));
401 if (HAsync == 0)
402 InvalidHost = TRUE;
403 else {
404 cv->ComPort = 1; // set "getting host" flag
405 // (see CVTWindow::OnSysCommand())
406 do {
407 if (GetMessage(&Msg,0,0,0))
408 {
409 if ((Msg.hwnd==HW) &&
410 ((Msg.message == WM_SYSCOMMAND) &&
411 ((Msg.wParam & 0xfff0) == SC_CLOSE) ||
412 (Msg.message == WM_COMMAND) &&
413 (LOWORD(Msg.wParam) == ID_FILE_EXIT) ||
414 (Msg.message == WM_CLOSE)))
415 { /* Exit when the user closes Tera Term */
416 PWSACancelAsyncRequest(HAsync);
417 HAsync = 0;
418 cv->ComPort = 0; // clear "getting host" flag
419 PostMessage(HW,Msg.message,Msg.wParam,Msg.lParam);
420 return;
421 }
422 if (Msg.message != WM_USER_GETHOST)
423 { /* Prosess messages */
424 TranslateMessage(&Msg);
425 DispatchMessage(&Msg);
426 }
427 }
428 else {
429 return;
430 }
431 } while (Msg.message!=WM_USER_GETHOST);
432 cv->ComPort = 0; // clear "getting host" flag
433 HAsync = 0;
434 InvalidHost = WSAGETASYNCERROR(Msg.lParam) != 0;
435 if (! InvalidHost)
436 {
437 if (((PHOSTENT)HEntBuff)->h_addr_list != NULL)
438 memcpy(&addr,
439 ((PHOSTENT)HEntBuff)->h_addr_list[0],sizeof(addr));
440 else
441 InvalidHost = TRUE;
442 }
443 }
444
445 }
446
447 if (InvalidHost)
448 {
449 if (cv->NoMsg==0)
450 MessageBox(cv->HWin,"Invalid host",ErrorCaption,
451 MB_TASKMODAL | MB_ICONEXCLAMATION);
452 }
453 else {
454 cv->s= Psocket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
455 if (cv->s==INVALID_SOCKET)
456 {
457 InvalidHost = TRUE;
458 if (cv->NoMsg==0)
459 MessageBox(cv->HWin,ErrorCantConn,ErrorCaption,
460 MB_TASKMODAL | MB_ICONEXCLAMATION);
461 }
462 else {
463 BBuf = TRUE;
464 Psetsockopt(cv->s,(int)SOL_SOCKET,SO_OOBINLINE,(char FAR *)&BBuf,sizeof(BBuf));
465
466 PWSAAsyncSelect(cv->s,cv->HWin,WM_USER_COMMOPEN, FD_CONNECT);
467 saddr.sin_family = AF_INET;
468 saddr.sin_port = Phtons(ts->TCPPort);
469 saddr.sin_addr.s_addr = addr;
470 memset(saddr.sin_zero,0,8);
471
472 Err = Pconnect(cv->s,(LPSOCKADDR)&saddr,sizeof(saddr));
473 if (Err!=0 ) Err = PWSAGetLastError();
474 if (Err==WSAEWOULDBLOCK )
475 {
476 /* Do nothing */
477 }
478 else if (Err!=0 )
479 PostMessage(cv->HWin, WM_USER_COMMOPEN,0,
480 MAKELONG(FD_CONNECT,Err));
481 }
482 }
483 }
484 break;
485 #endif /* NO_INET6 */
486
487 case IdSerial:
488 InitFileIO(); /* TTPLUG */
489 TTXOpenFile(); /* TTPLUG */
490 _snprintf_s(P, sizeof(P), _TRUNCATE, "COM%d", ts->ComPort);
491 strncpy_s(ErrMsg, sizeof(ErrMsg),P, _TRUNCATE);
492 strncpy_s(P, sizeof(P),"\\\\.\\", _TRUNCATE);
493 strncat_s(P, sizeof(P),ErrMsg, _TRUNCATE);
494 cv->ComID =
495 PCreateFile(P,GENERIC_READ | GENERIC_WRITE,
496 0,NULL,OPEN_EXISTING,
497 FILE_FLAG_OVERLAPPED,NULL);
498 if (cv->ComID == INVALID_HANDLE_VALUE )
499 {
500
501 get_lang_msg("MSG_CANTOEPN_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot open %s", ts->UILanguageFile);
502 _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, ts->UIMsg, &P[4]);
503
504 if (cv->NoMsg==0)
505 {
506 get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile);
507 MessageBox(cv->HWin,ErrMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION);
508 }
509 InvalidHost = TRUE;
510 }
511 else {
512 cv->Open = TRUE;
513 cv->ComPort = ts->ComPort;
514 CommResetSerial(ts, cv, ts->ClearComBuffOnOpen);
515 if (!ts->ClearComBuffOnOpen)
516 cv->RRQ = TRUE;
517
518 /* notify to VT window that Comm Port is open */
519 PostMessage(cv->HWin, WM_USER_COMMOPEN, 0, 0);
520 InvalidHost = FALSE;
521
522 SetCOMFlag(ts->ComPort);
523 }
524 break; /* end of "case IdSerial:" */
525
526 case IdFile:
527 InitFileIO(); /* TTPLUG */
528 TTXOpenFile(); /* TTPLUG */
529 cv->ComID = PCreateFile(ts->HostName,GENERIC_READ,0,NULL,
530 OPEN_EXISTING,0,NULL);
531 InvalidHost = (cv->ComID == INVALID_HANDLE_VALUE);
532 if (InvalidHost)
533 {
534 if (cv->NoMsg==0)
535 {
536 get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile);
537 get_lang_msg("MSG_CANTOEPN_FILE_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot open file", ts->UILanguageFile);
538 MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION);
539 }
540 }
541 else {
542 cv->Open = TRUE;
543 PostMessage(cv->HWin, WM_USER_COMMOPEN, 0, 0);
544 }
545 break;
546 } /* end of "switch" */
547
548 #ifndef NO_INET6
549 BreakSC:
550 #endif /* NO_INET6 */
551 if (InvalidHost)
552 {
553 PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_CLOSE);
554 if ( (ts->PortType==IdTCPIP) && cv->Open )
555 {
556 if ( cv->s!=INVALID_SOCKET ) Pclosesocket(cv->s);
557 FreeWinsock();
558 }
559 return;
560 }
561 }
562
563 void CommThread(void *arg)
564 {
565 DWORD Evt;
566 PComVar cv = (PComVar)arg;
567 DWORD DErr;
568 HANDLE REnd;
569 char Temp[20];
570
571 _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", READENDNAME, cv->ComPort);
572 REnd = OpenEvent(EVENT_ALL_ACCESS,FALSE, Temp);
573 while (TRUE) {
574 if (WaitCommEvent(cv->ComID,&Evt,NULL))
575 {
576 if (! cv->Ready) _endthread();
577 if (! cv->RRQ)
578 PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_READ);
579 WaitForSingleObject(REnd,INFINITE);
580 }
581 else {
582 if (! cv->Ready) _endthread();
583 ClearCommError(cv->ComID,&DErr,NULL);
584 }
585 }
586 }
587
588 void CommStart(PComVar cv, LONG lParam, PTTSet ts)
589 {
590 char ErrMsg[31];
591 char Temp[20];
592 char uimsg[MAX_UIMSG];
593
594 if (! cv->Open ) return;
595 if ( cv->Ready ) return;
596
597 // �L�����Z���^�C�}�����������������B�������A�������_�� WM_TIMER �����������������\���������B
598 if (*cv->ConnetingTimeout > 0) {
599 KillTimer(cv->HWin, IdCancelConnectTimer);
600 }
601
602 switch (cv->PortType) {
603 case IdTCPIP:
604 ErrMsg[0] = 0;
605 switch (HIWORD(lParam)) {
606 case WSAECONNREFUSED:
607 get_lang_msg("MSG_COMM_REFUSE_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Connection refused", ts->UILanguageFile);
608 _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "%s", ts->UIMsg);
609 break;
610 case WSAENETUNREACH:
611 get_lang_msg("MSG_COMM_REACH_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Network cannot be reached", ts->UILanguageFile);
612 _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "%s", ts->UIMsg);
613 break;
614 case WSAETIMEDOUT:
615 get_lang_msg("MSG_COMM_CONNECT_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Connection timed out", ts->UILanguageFile);
616 _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "%s", ts->UIMsg);
617 break;
618 default:
619 get_lang_msg("MSG_COMM_TIMEOUT_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot connect the host", ts->UILanguageFile);
620 _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "%s", ts->UIMsg);
621 }
622 if (HIWORD(lParam)>0)
623 {
624 #ifndef NO_INET6
625 /* connect() failed */
626 if (cv->res->ai_next != NULL) {
627 /* try to connect with other protocol */
628 CloseSocket(cv->s);
629 for (cv->res = cv->res->ai_next; cv->res; cv->res = cv->res->ai_next) {
630 cv->s = OpenSocket(cv);
631 if (cv->s == INVALID_SOCKET) {
632 CloseSocket(cv->s);
633 continue;
634 }
635 AsyncConnect(cv);
636 cv->Ready = FALSE;
637 cv->RetryWithOtherProtocol = TRUE; /* retry with other procotol */
638 return;
639 }
640 } else {
641 /* trying with all protocol family are failed */
642 if (cv->NoMsg==0)
643 {
644 get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile);
645 MessageBox(cv->HWin,ErrMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION);
646 }
647 PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_CLOSE);
648 cv->RetryWithOtherProtocol = FALSE;
649 return;
650 }
651 #else
652 if (cv->NoMsg==0)
653 MessageBox(cv->HWin,ErrMsg,ErrorCaption,
654 MB_TASKMODAL | MB_ICONEXCLAMATION);
655 PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_CLOSE);
656 return;
657 #endif /* NO_INET6 */
658 }
659
660 #ifndef NO_INET6
661 /* here is connection established */
662 cv->RetryWithOtherProtocol = FALSE;
663 #endif /* NO_INET6 */
664 PWSAAsyncSelect(cv->s,cv->HWin,WM_USER_COMMNOTIFY, FD_READ | FD_OOB | FD_CLOSE);
665 TCPIPClosed = FALSE;
666 break;
667
668 case IdSerial:
669 _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", READENDNAME, cv->ComPort);
670 ReadEnd = CreateEvent(NULL,FALSE,FALSE,Temp);
671 _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", WRITENAME, cv->ComPort);
672 memset(&wol,0,sizeof(OVERLAPPED));
673 wol.hEvent = CreateEvent(NULL,TRUE,TRUE,Temp);
674 _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", READNAME, cv->ComPort);
675 memset(&rol,0,sizeof(OVERLAPPED));
676 rol.hEvent = CreateEvent(NULL,TRUE,FALSE,Temp);
677
678 /* create the receiver thread */
679 if (_beginthread(CommThread,0,cv) == -1)
680 {
681 get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile);
682 get_lang_msg("MSG_TT_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Can't create thread", ts->UILanguageFile);
683 MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION);
684 }
685 break;
686 case IdFile: cv->RRQ = TRUE; break;
687 }
688 cv->Ready = TRUE;
689 }
690
691 BOOL CommCanClose(PComVar cv)
692 { // check if data remains in buffer
693 if (! cv->Open) return TRUE;
694 if (cv->InBuffCount>0) return FALSE;
695 if ((cv->HLogBuf!=NULL) &&
696 ((cv->LCount>0) ||
697 (cv->DCount>0))) return FALSE;
698 if ((cv->HBinBuf!=NULL) &&
699 (cv->BCount>0)) return FALSE;
700 return TRUE;
701 }
702
703 void CommClose(PComVar cv)
704 {
705 if ( ! cv->Open ) return;
706 cv->Open = FALSE;
707
708 /* disable event message posting & flush buffer */
709 cv->RRQ = FALSE;
710 cv->Ready = FALSE;
711 cv->InPtr = 0;
712 cv->InBuffCount = 0;
713 cv->OutPtr = 0;
714 cv->OutBuffCount = 0;
715
716 /* close port & release resources */
717 switch (cv->PortType) {
718 case IdTCPIP:
719 if (HAsync!=0)
720 PWSACancelAsyncRequest(HAsync);
721 HAsync = 0;
722 #ifndef NO_INET6
723 freeaddrinfo(cv->res0);
724 #endif /* NO_INET6 */
725 if ( cv->s!=INVALID_SOCKET )
726 Pclosesocket(cv->s);
727 cv->s = INVALID_SOCKET;
728 TTXCloseTCP(); /* TTPLUG */
729 FreeWinsock();
730 break;
731 case IdSerial:
732 if ( cv->ComID != INVALID_HANDLE_VALUE )
733 {
734 CloseHandle(ReadEnd);
735 CloseHandle(wol.hEvent);
736 CloseHandle(rol.hEvent);
737 PurgeComm(cv->ComID,
738 PURGE_TXABORT | PURGE_RXABORT |
739 PURGE_TXCLEAR | PURGE_RXCLEAR);
740 EscapeCommFunction(cv->ComID,CLRDTR);
741 SetCommMask(cv->ComID,0);
742 PCloseFile(cv->ComID);
743 ClearCOMFlag(cv->ComPort);
744 }
745 TTXCloseFile(); /* TTPLUG */
746 break;
747 case IdFile:
748 if (cv->ComID != INVALID_HANDLE_VALUE)
749 PCloseFile(cv->ComID);
750 TTXCloseFile(); /* TTPLUG */
751 break;
752 }
753 cv->ComID = INVALID_HANDLE_VALUE;
754 cv->PortType = 0;
755 }
756
757 void CommProcRRQ(PComVar cv)
758 {
759 if ( ! cv->Ready ) return;
760 /* disable receive request */
761 switch (cv->PortType) {
762 case IdTCPIP:
763 if (! TCPIPClosed)
764 PWSAAsyncSelect(cv->s,cv->HWin,WM_USER_COMMNOTIFY, FD_OOB | FD_CLOSE);
765 break;
766 case IdSerial:
767 break;
768 }
769 cv->RRQ = TRUE;
770 CommReceive(cv);
771 }
772
773 void CommReceive(PComVar cv)
774 {
775 DWORD C;
776 DWORD DErr;
777
778 if (! cv->Ready || ! cv->RRQ ||
779 (cv->InBuffCount>=InBuffSize)) return;
780
781 /* Compact buffer */
782 if ((cv->InBuffCount>0) && (cv->InPtr>0))
783 {
784 memmove(cv->InBuff,&(cv->InBuff[cv->InPtr]),cv->InBuffCount);
785 cv->InPtr = 0;
786 }
787
788 if (cv->InBuffCount<InBuffSize)
789 {
790 switch (cv->PortType) {
791 case IdTCPIP:
792 C = Precv(cv->s, &(cv->InBuff[cv->InBuffCount]),
793 InBuffSize-cv->InBuffCount, 0);
794 if (C == SOCKET_ERROR)
795 {
796 C = 0;
797 PWSAGetLastError();
798 }
799 cv->InBuffCount = cv->InBuffCount + C;
800 break;
801 case IdSerial:
802 do {
803 ClearCommError(cv->ComID,&DErr,NULL);
804 if (! PReadFile(cv->ComID,&(cv->InBuff[cv->InBuffCount]),
805 InBuffSize-cv->InBuffCount,&C,&rol))
806 {
807 if (GetLastError() == ERROR_IO_PENDING)
808 {
809 if (WaitForSingleObject(rol.hEvent, 1000) !=
810 WAIT_OBJECT_0)
811 C = 0;
812 else
813 GetOverlappedResult(cv->ComID,&rol,&C,FALSE);
814 }
815 else
816 C = 0;
817 }
818 cv->InBuffCount = cv->InBuffCount + C;
819 } while ((C!=0) && (cv->InBuffCount<InBuffSize));
820 ClearCommError(cv->ComID,&DErr,NULL);
821 break;
822 case IdFile:
823 PReadFile(cv->ComID,&(cv->InBuff[cv->InBuffCount]),
824 InBuffSize-cv->InBuffCount,&C,NULL);
825 cv->InBuffCount = cv->InBuffCount + C;
826 break;
827 }
828 }
829
830 if (cv->InBuffCount==0)
831 {
832 switch (cv->PortType) {
833 case IdTCPIP:
834 if (! TCPIPClosed)
835 PWSAAsyncSelect(cv->s,cv->HWin,
836 WM_USER_COMMNOTIFY, FD_READ | FD_OOB | FD_CLOSE);
837 break;
838 case IdSerial:
839 cv->RRQ = FALSE;
840 SetEvent(ReadEnd);
841 return;
842 case IdFile:
843 PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_CLOSE);
844 break;
845 }
846 cv->RRQ = FALSE;
847
848 }
849 }
850
851 void CommSend(PComVar cv)
852 {
853 int delay;
854 COMSTAT Stat;
855 BYTE LineEnd;
856 int C, D, Max;
857 DWORD DErr;
858
859 if ((! cv->Open) || (! cv->Ready))
860 {
861 cv->OutBuffCount = 0;
862 return;
863 }
864
865 if ((cv->OutBuffCount == 0) || (! cv->CanSend)) return;
866
867 /* Max num of bytes to be written */
868 switch (cv->PortType) {
869 case IdTCPIP:
870 if (TCPIPClosed) cv->OutBuffCount = 0;
871 Max = cv->OutBuffCount;
872 break;
873 case IdSerial:
874 ClearCommError(cv->ComID,&DErr,&Stat);
875 Max = OutBuffSize - Stat.cbOutQue;
876 break;
877 case IdFile: Max = cv->OutBuffCount;
878 break;
879 }
880
881 if ( Max<=0 ) return;
882 if ( Max > cv->OutBuffCount ) Max = cv->OutBuffCount;
883
884 if (cv->PortType == IdTCPIP && cv->TelFlag) {
885 cv->LastSendTime = time(NULL);
886 }
887
888 C = Max;
889 delay = 0;
890
891 if ( cv->DelayFlag && (cv->PortType==IdSerial) )
892 {
893 if ( cv->DelayPerLine > 0 )
894 {
895 if ( cv->CRSend==IdCR ) LineEnd = 0x0d;
896 else LineEnd = 0x0a;
897 C = 1;
898 if ( cv->DelayPerChar==0 )
899 while ((C<Max) && (cv->OutBuff[cv->OutPtr+C-1]!=LineEnd))
900 C++;
901 if ( cv->OutBuff[cv->OutPtr+C-1]==LineEnd )
902 delay = cv->DelayPerLine;
903 else delay = cv->DelayPerChar;
904 }
905 else if ( cv->DelayPerChar > 0 )
906 {
907 C = 1;
908 delay = cv->DelayPerChar;
909 }
910 }
911
912 /* Write to comm driver/Winsock */
913 switch (cv->PortType) {
914 case IdTCPIP:
915 D = Psend(cv->s, &(cv->OutBuff[cv->OutPtr]), C, 0);
916 if ( D==SOCKET_ERROR ) /* if error occurs */
917 {
918 PWSAGetLastError(); /* Clear error */
919 D = 0;
920 }
921 break;
922
923 case IdSerial:
924 if (! PWriteFile(cv->ComID,&(cv->OutBuff[cv->OutPtr]),C,(LPDWORD)&D,&wol))
925 {
926 if (GetLastError() == ERROR_IO_PENDING)
927 {
928 if (WaitForSingleObject(wol.hEvent,1000) !=
929 WAIT_OBJECT_0)
930 D = C; /* Time out, ignore data */
931 else
932 GetOverlappedResult(cv->ComID,&wol,(LPDWORD)&D,FALSE);
933 }
934 else /* I/O error */
935 D = C; /* ignore error */
936 }
937 ClearCommError(cv->ComID,&DErr,&Stat);
938 break;
939 case IdFile: D = C; break;
940 }
941
942 cv->OutBuffCount = cv->OutBuffCount - D;
943 if ( cv->OutBuffCount==0 )
944 cv->OutPtr = 0;
945 else
946 cv->OutPtr = cv->OutPtr + D;
947
948 if ( (C==D) && (delay>0) )
949 {
950 cv->CanSend = FALSE;
951 SetTimer(cv->HWin, IdDelayTimer, delay, NULL);
952 }
953 }
954
955 void CommSendBreak(PComVar cv)
956 /* for only serial ports */
957 {
958 MSG DummyMsg;
959
960 if ( ! cv->Ready ) return;
961
962 switch (cv->PortType) {
963 case IdSerial:
964 /* Set com port into a break state */
965 SetCommBreak(cv->ComID);
966
967 /* pause for 1 sec */
968 if (SetTimer(cv->HWin, IdBreakTimer, 1000, NULL) != 0)
969 GetMessage(&DummyMsg,cv->HWin,WM_TIMER,WM_TIMER);
970
971 /* Set com port into the nonbreak state */
972 ClearCommBreak(cv->ComID);
973 break;
974 }
975 }
976
977 void CommLock(PTTSet ts, PComVar cv, BOOL Lock)
978 {
979 BYTE b;
980 DWORD Func;
981
982 if (! cv->Ready) return;
983 if ((cv->PortType==IdTCPIP) ||
984 (cv->PortType==IdSerial) &&
985 (ts->Flow!=IdFlowHard))
986 {
987 if (Lock)
988 b = XOFF;
989 else
990 b = XON;
991 CommBinaryOut(cv,&b,1);
992 }
993 else if ((cv->PortType==IdSerial) &&
994 (ts->Flow==IdFlowHard))
995 {
996 if (Lock)
997 Func = CLRRTS;
998 else
999 Func = SETRTS;
1000 EscapeCommFunction(cv->ComID,Func);
1001 }
1002 }
1003
1004 int GetCommSerialBaudRate(int id)
1005 {
1006 switch (id) {
1007 case IdBaud110:
1008 return 110;
1009 case IdBaud300:
1010 case IdBaud600:
1011 case IdBaud1200:
1012 case IdBaud2400:
1013 case IdBaud4800:
1014 case IdBaud9600:
1015 return 300 << (id - IdBaud110 -1);
1016 case IdBaud14400:
1017 return 14400;
1018 case IdBaud19200:
1019 return 19200;
1020 case IdBaud38400:
1021 return 38400;
1022 case IdBaud57600:
1023 case IdBaud115200:
1024 case IdBaud230400:
1025 case IdBaud460800:
1026 case IdBaud921600:
1027 return 57600 << (id - IdBaud38400 -1);
1028 }
1029
1030 return 0;
1031 }
1032
1033 BOOL PrnOpen(PCHAR DevName)
1034 {
1035 char Temp[MAXPATHLEN];
1036 DCB dcb;
1037 DWORD DErr;
1038 COMMTIMEOUTS ctmo;
1039
1040 strncpy_s(Temp, sizeof(Temp),DevName, _TRUNCATE);
1041 Temp[4] = 0; // COMn or LPTn
1042 LPTFlag = (Temp[0]=='L') ||
1043 (Temp[0]=='l');
1044 PrnID =
1045 CreateFile(Temp,GENERIC_WRITE,
1046 0,NULL,OPEN_EXISTING,
1047 0,NULL);
1048 if (PrnID == INVALID_HANDLE_VALUE) return FALSE;
1049
1050 if (GetCommState(PrnID,&dcb))
1051 {
1052 BuildCommDCB(DevName,&dcb);
1053 SetCommState(PrnID,&dcb);
1054 }
1055 ClearCommError(PrnID,&DErr,NULL);
1056 if (! LPTFlag)
1057 SetupComm(PrnID,0,CommOutQueSize);
1058 /* flush output buffer */
1059 PurgeComm(PrnID, PURGE_TXABORT |
1060 PURGE_TXCLEAR);
1061 memset(&ctmo,0,sizeof(ctmo));
1062 ctmo.WriteTotalTimeoutConstant = 1000;
1063 SetCommTimeouts(PrnID,&ctmo);
1064 if (! LPTFlag)
1065 EscapeCommFunction(PrnID,SETDTR);
1066 return TRUE;
1067 }
1068
1069 int PrnWrite(PCHAR b, int c)
1070 {
1071 int d;
1072 DWORD DErr;
1073 COMSTAT Stat;
1074
1075 if (PrnID == INVALID_HANDLE_VALUE )
1076 return c;
1077
1078 ClearCommError(PrnID,&DErr,&Stat);
1079 if (! LPTFlag &&
1080 (OutBuffSize - (int)Stat.cbOutQue < c))
1081 c = OutBuffSize - Stat.cbOutQue;
1082 if (c<=0) return 0;
1083 if (! WriteFile(PrnID,b,c,(LPDWORD)&d,NULL))
1084 d = 0;
1085 ClearCommError(PrnID,&DErr,NULL);
1086 return d;
1087 }
1088
1089 void PrnCancel()
1090 {
1091 PurgeComm(PrnID,
1092 PURGE_TXABORT | PURGE_TXCLEAR);
1093 PrnClose();
1094 }
1095
1096 void PrnClose()
1097 {
1098 if (PrnID != INVALID_HANDLE_VALUE)
1099 {
1100 if (!LPTFlag)
1101 EscapeCommFunction(PrnID,CLRDTR);
1102 CloseHandle(PrnID);
1103 }
1104 PrnID = INVALID_HANDLE_VALUE;
1105 }

Back to OSDN">Back to OSDN
ViewVC Help
Powered by ViewVC 1.1.26