Develop and Download Open Source Software

Browse Subversion Repository

Diff of /trunk/teraterm/teraterm/commlib.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

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

Legend:
Removed from v.3855  
changed lines
  Added in v.3857

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