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

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