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 4849 - (show annotations) (download) (as text)
Thu Mar 1 09:14:41 2012 UTC (12 years, 1 month ago) by doda
Original Path: trunk/teraterm/teraterm/commlib.c
File MIME type: text/x-csrc
File size: 30306 byte(s)
シリアル接続で、マークパリティ, スペースバリティ, 1.5ストップビットをサポートした。

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

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