void *SpeedFanNodePlugin::ListenerThread::Entry() { if (!OpenSocket()) { // Failed to open socket return NULL; } // Use a 2048 byte buffer, Ethernet frame size is 1500 const int bufferSize = 2048; char *buffer = new char[bufferSize]; while (!TestDestroy()) { // Reset the socket after recieving a packet int ret = m_Socket.RecvFrom(buffer, bufferSize); if (ret > 0) { buffer[ret] = 0; ProcessBuffer(buffer); } else { // Reopen socket if (TestDestroy() || !OpenSocket()) { // We need to exit or we failed to re-open the socket break; } } Sleep(0); } delete [] buffer; return NULL; }
BOOL CIServer::Start(HWND hWnd, UINT uMsg, DWORD dwPort, DWORD dwMax) { Destroy(); // Open the socket if ( !OpenSocket() || // Bind to TCP port !Bind( dwPort ) || // Listen for connections !Listen( dwMax ) || // Async operation !SetMessageTarget( hWnd, uMsg ) || // Start callback thread !StartCallbacks() ) { Destroy(); return FALSE; } // end if return TRUE; }
SOCK Tcp_Connect(const char *ip,uint16_t port,struct sockaddr_in *servaddr,int32_t retry) { if(!ip) return INVALID_SOCK; memset((void*)servaddr,0,sizeof(*servaddr)); servaddr->sin_family = INET; servaddr->sin_port = htons(port); #ifdef _WIN servaddr->sin_addr.s_addr = inet_addr(ip); #else if(inet_pton(INET,ip,&servaddr->sin_addr) < 0) { printf("%s\n",strerror(errno)); return INVALID_SOCK; } #endif SOCK sock = OpenSocket(INET,STREAM,TCP); if(sock) { while(1) { if(0 == Connect(sock,(struct sockaddr*)servaddr,sizeof(*servaddr))) return sock; if(!retry) break; } CloseSocket(sock); } return INVALID_SOCK; }
BOOL CPort::Open(const char* pszFileName, BOOL fIsSocket) { RIL_LOG_VERBOSE("CPort::Open() - Enter fIsSocket=[%d]\r\n", fIsSocket); BOOL fRet = FALSE; if (NULL == pszFileName) { RIL_LOG_CRITICAL("CPort::Open() - pszFileName is NULL!\r\n"); return FALSE; } if (!m_fIsPortOpen) { if (NULL == m_pFile) { m_pFile = new CFile(); } if (fIsSocket) { fRet = OpenSocket(pszFileName); } else { fRet = OpenPort(pszFileName); } } else { RIL_LOG_CRITICAL("CPort::Open() - Port is already open!\r\n"); } RIL_LOG_VERBOSE("CPort::Open() - Exit\r\n"); return fRet; }
int32_t Tcp_Connect(const char *ip,uint16_t port,struct sockaddr_in *servaddr,int32_t retry) { if(!ip) return -1; bzero(servaddr,sizeof(*servaddr)); servaddr->sin_family = INET; servaddr->sin_port = htons(port); if(inet_pton(INET,ip,&servaddr->sin_addr) < 0) { printf("%s\n",strerror(errno)); return -1; } HANDLE sock = OpenSocket(INET,STREAM,TCP); if(sock) { while(1) { if(0 == Connect(sock,(struct sockaddr*)servaddr,sizeof(*servaddr))) return sock; if(!retry) break; } CloseSocket(sock); } return -1; }
int main(int argc, char *argv[]){ //ARGS: IP PORT FILENAME char* IP = ""; int port = 0; if(argc != 3){ printf("please provide two parameters! (IP, port)\n"); return 0; }else{ IP = argv[1]; port = atoi(argv[2]); } //OpenFile(filename); OpenSocket(IP,port); getCommands(); //printf("Clientapp\n"); return 0; }
void MemoryWatcherUnix::Create() { if (!LoadAddresses(File::GetUserPath(F_MEMORYWATCHERLOCATIONS_IDX))) return; if (!OpenSocket(File::GetUserPath(F_MEMORYWATCHERSOCKET_IDX))) return; m_running = true; m_watcher_thread = std::thread(&MemoryWatcherUnix::WatcherThread, this); }
MemoryWatcher::MemoryWatcher() { m_running = false; if (!LoadAddresses(File::GetUserPath(F_MEMORYWATCHERLOCATIONS_IDX))) return; if (!OpenSocket(File::GetUserPath(F_MEMORYWATCHERSOCKET_IDX))) return; m_running = true; }
Client::Client(const char *host, int portNum) { OpenSocket(); ConnectToHost(host, portNum); SendMsg(NetMsg(Ok, 23)); GetResponse(); Disconnect(); }
MemoryWatcher::MemoryWatcher() : m_context(1) { if (!LoadAddresses(File::GetUserPath(F_MEMORYWATCHERLOCATIONS_IDX))) { std::cout << "Failed to load MemoryWatcher addresses. Not watching memory." << std::endl; return; } if (!OpenSocket(File::GetUserPath(F_MEMORYWATCHERSOCKET_IDX))) return; m_running = true; }
void nsGopherContentStream::OnCallbackPending() { nsresult rv; // We have a callback, so failure means we should close the stream. if (!mSocket) { rv = OpenSocket(CallbackTarget()); } else if (mSocketInput) { rv = mSocketInput->AsyncWait(this, 0, 0, CallbackTarget()); } if (NS_FAILED(rv)) CloseWithStatus(rv); }
void main(int argc, char **argv) { if (OpenSocket()) { printf("OpenSocket error\n"); exit(-1); } DWORD mode = PROMISC_MODE_ON; if (SetPromiscMode(&mode)) { printf("SetPromiscMode error\n"); exit(-1); } fstream file; file.open("C:\\Users\\tausvo\\Desktop\\byvitya\\SocketSniffer\\Debug\\packets.log", ios::out); while(1) { IPHeader *packet = SniffPacket(); printf("writing packet...\n"); /*TCPHeader *tcpPacket = (TCPHeader*)malloc(packet->iph_len); memcpy(tcpPacket, &packet->iph_data, packet->iph_len); byte *tcpData = (byte*)malloc(packet->iph_len); memcpy(tcpData, &tcpPacket->tcph_data, packet->iph_len); char *tcpStrData = (char*)malloc(packet->iph_len); memcpy(tcpStrData, &tcpData[128], packet->iph_len); printf(tcpStrData); free(tcpStrData); error, rewrite this components free(tcpData); free(tcpPacket); //vector<string> splitedCoockies;*/ char *str = IPPacket2Str(packet); file.write(str,strlen(str)); free(str); free(packet); } file.close(); }
int32_t connector_connect(connector_t c,const char *ip,uint32_t port,on_connect call_back,void *ud,uint32_t ms) { struct sockaddr_in remote; HANDLE sock; struct pending_connect *pc; sock = OpenSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sock < 0) return -1; remote.sin_family = AF_INET; remote.sin_port = htons(port); if(inet_pton(INET,ip,&remote.sin_addr) < 0) { printf("%s\n",strerror(errno)); return -1; } if(ms>0) { if(setNonblock(sock)!=0) return -1; } if(Connect(sock, (struct sockaddr *)&remote, sizeof(remote)) == 0) { //连接成功,无需要后续处理了,直接调用回调函数 call_back(sock,ip,port,ud); return 0; } socket_t s = GetSocketByHandle(sock); pc = malloc(sizeof(*pc)); pc->lnode.next = NULL; pc->sock = sock; pc->ip = ip; pc->port = port; pc->call_back = call_back; pc->timeout = GetSystemMs() + ms; pc->ud = ud; pc->real_fd = s->fd; mutex_lock(c->lock); LINK_LIST_PUSH_BACK(c->extern_pending_connect,pc); mutex_unlock(c->lock); return 0; }
SOCK Tcp_Listen(const char *ip,uint16_t port,int32_t backlog) { struct sockaddr_in servaddr; SOCK sock; sock = OpenSocket(INET,STREAM,TCP); if(sock == INVALID_SOCK) return INVALID_SOCK; memset((void*)&servaddr,0,sizeof(servaddr)); servaddr.sin_family = INET; if(ip) { if(inet_pton(INET,ip,&servaddr.sin_addr) < 0) { printf("%s\n",strerror(errno)); return INVALID_SOCK; } } else servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(port); if (set_reuseaddr(sock) != 0){ CloseSocket(sock); return INVALID_SOCK; } if(Bind(sock,(struct sockaddr*)&servaddr,sizeof(servaddr)) == INVALID_SOCK) { CloseSocket(sock); return INVALID_SOCK; } if(Listen(sock,backlog) != INVALID_SOCK) return sock; else { CloseSocket(sock); return INVALID_SOCK; } }
SOCK Tcp_Listen(const char *ip,uint16_t port,struct sockaddr_in *servaddr,int32_t backlog) { SOCK sock; sock = OpenSocket(INET,STREAM,TCP); if(sock < 0) return INVALID_SOCK; memset((void*)servaddr,0,sizeof(*servaddr)); servaddr->sin_family = INET; if(ip) { #ifdef _WIN servaddr->sin_addr.s_addr = inet_addr(ip); #else if(inet_pton(INET,ip,&servaddr->sin_addr) < 0) { printf("%s\n",strerror(errno)); return INVALID_SOCK; } #endif } else servaddr->sin_addr.s_addr = htonl(INADDR_ANY); servaddr->sin_port = htons(port); if(Bind(sock,(struct sockaddr*)servaddr,sizeof(*servaddr)) < 0) { CloseSocket(sock); return INVALID_SOCK; } if(Listen(sock,backlog) == 0) return sock; else { CloseSocket(sock); return INVALID_SOCK; } }
SOCK Tcp_Connect(const char *ip,uint16_t port) { if(!ip) return INVALID_SOCK; struct sockaddr_in servaddr; memset((void*)&servaddr,0,sizeof(servaddr)); servaddr.sin_family = INET; servaddr.sin_port = htons(port); if(inet_pton(INET,ip,&servaddr.sin_addr) < 0) { printf("%s\n",strerror(errno)); return INVALID_SOCK; } SOCK sock = OpenSocket(INET,STREAM,TCP); if(sock != INVALID_SOCK) { if(INVALID_SOCK != Connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr))) return sock; CloseSocket(sock); } return INVALID_SOCK; }
HANDLE Tcp_Listen(const char *ip,unsigned short port,struct sockaddr_in *servaddr,int backlog) { HANDLE sock; sock = OpenSocket(INET,STREAM,TCP); if(sock < 0) return -1; bzero(servaddr,sizeof(*servaddr)); servaddr->sin_family = INET; if(ip) { if(inet_pton(INET,ip,&servaddr->sin_addr) < 0) { printf("%s\n",strerror(errno)); return -1; } } else servaddr->sin_addr.s_addr = htonl(INADDR_ANY); servaddr->sin_port = htons(port); if(Bind(sock,(struct sockaddr*)servaddr,sizeof(*servaddr)) < 0) { CloseSocket(sock); return -1; } if(Listen(sock,backlog) == 0) return sock; else { CloseSocket(sock); return -1; } }
WinSocket_UDP::WinSocket_UDP (long *plOk, unsigned short usLocalPort, char *pchLocalAdress, bool bEnableBroadcasts) { long lError, lBindError; sockaddr_in RecvAddr; *plOk = FALSE; m_bInitOK = false; m_pcLocalVars = NULL; m_pcLocalVars = new t_WinSocket_UDP_LocalVars; memset (m_pcLocalVars, 0, sizeof(t_WinSocket_UDP_LocalVars)); m_pcLocalVars->bIsServer = false; m_pcLocalVars->bBroadcastsEnabled = bEnableBroadcasts; m_pcLocalVars->usPort = usLocalPort; strncpy (m_pcLocalVars->achAdress, pchLocalAdress, 256); m_pcLocalVars->achAdress[255] = 0; if ((lError = OpenSocket()) <= 0) { *plOk = lError; return; } RecvAddr.sin_family = AF_INET; RecvAddr.sin_addr.s_addr = (pchLocalAdress) ? inet_addr(pchLocalAdress) : htonl(INADDR_ANY); RecvAddr.sin_port = htons(usLocalPort); if (usLocalPort != 0) { lBindError = bind(m_pcLocalVars->Socket, (SOCKADDR *) &RecvAddr, sizeof(RecvAddr)); if (lBindError == SOCKET_ERROR) { printf("ERROR: bind() failed: %ld\n", WSAGetLastError()); *plOk = ERRSOCK_PORT_BIND; return; } m_pcLocalVars->bIsServer = true; } m_bInitOK = true; *plOk = TRUE; }
int main(int argc,char **argv) { SSLStateMachine *pMachine; int nPort; int nFD; const char *szCertificateFile; const char *szKeyFile; char rbuf[1]; int nrbuf=0; if(argc != 4) { fprintf(stderr,"%s <port> <certificate file> <key file>\n",argv[0]); exit(6); } nPort=atoi(argv[1]); szCertificateFile=argv[2]; szKeyFile=argv[3]; SSL_library_init(); OpenSSL_add_ssl_algorithms(); SSL_load_error_strings(); ERR_load_crypto_strings(); nFD=OpenSocket(nPort); pMachine=SSLStateMachine_new(szCertificateFile,szKeyFile); for( ; ; ) { fd_set rfds,wfds; unsigned char buf[1024]; int n; FD_ZERO(&rfds); FD_ZERO(&wfds); /* Select socket for input */ FD_SET(nFD,&rfds); /* check whether there's decrypted data */ if(!nrbuf) nrbuf=SSLStateMachine_read_extract(pMachine,rbuf,1); /* if there's decrypted data, check whether we can write it */ if(nrbuf) FD_SET(1,&wfds); /* Select socket for output */ if(SSLStateMachine_write_can_extract(pMachine)) FD_SET(nFD,&wfds); /* Select stdin for input */ FD_SET(0,&rfds); /* Wait for something to do something */ n=select(nFD+1,&rfds,&wfds,NULL,NULL); assert(n > 0); /* Socket is ready for input */ if(FD_ISSET(nFD,&rfds)) { n=read(nFD,buf,sizeof buf); if(n == 0) { fprintf(stderr,"Got EOF on socket\n"); exit(0); } assert(n > 0); SSLStateMachine_read_inject(pMachine,buf,n); } /* stdout is ready for output (and hence we have some to send it) */ if(FD_ISSET(1,&wfds)) { assert(nrbuf == 1); buf[0]=rbuf[0]; nrbuf=0; n=SSLStateMachine_read_extract(pMachine,buf+1,sizeof buf-1); if(n < 0) { SSLStateMachine_print_error(pMachine,"read extract failed"); break; } assert(n >= 0); ++n; if(n > 0) /* FIXME: has to be true now */ { int w; w=write(1,buf,n); /* FIXME: we should push back any unwritten data */ assert(w == n); } } /* Socket is ready for output (and therefore we have output to send) */ if(FD_ISSET(nFD,&wfds)) { int w; n=SSLStateMachine_write_extract(pMachine,buf,sizeof buf); assert(n > 0); w=write(nFD,buf,n); /* FIXME: we should push back any unwritten data */ assert(w == n); } /* Stdin is ready for input */ if(FD_ISSET(0,&rfds)) { n=read(0,buf,sizeof buf); if(n == 0) { fprintf(stderr,"Got EOF on stdin\n"); exit(0); } assert(n > 0); SSLStateMachine_write_inject(pMachine,buf,n); } } /* not reached */ return 0; }
int main( int argc, char *argv[] ) { self = argv[0]; srand( getpid() * time( 0 ) ); int id = -1; static struct option long_options[] = { {"monitor", 1, 0, 'm'}, {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {0, 0, 0, 0} }; while (1) { int option_index = 0; int c = getopt_long (argc, argv, "m:h:v", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'm': id = atoi(optarg); break; case 'h': case '?': Usage(); break; case 'v': std::cout << ZM_VERSION << "\n"; exit(0); default: //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c ); break; } } if (optind < argc) { fprintf( stderr, "Extraneous options, " ); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); Usage(); } if ( id < 0 ) { fprintf( stderr, "Bogus monitor %d\n", id ); Usage(); exit( 0 ); } char log_id_string[16]; snprintf( log_id_string, sizeof(log_id_string), "m%d", id ); zmLoadConfig(); logInit( "zmf" ); ssedetect(); Monitor *monitor = Monitor::Load( id, false, Monitor::QUERY ); if ( !monitor ) { fprintf( stderr, "Can't find monitor with id of %d\n", id ); exit( -1 ); } char capt_path[PATH_MAX]; char anal_path[PATH_MAX]; snprintf( capt_path, sizeof(capt_path), "%s/%d/%%s/%%0%dd-capture.jpg", config.dir_events, monitor->Id(), config.event_image_digits ); snprintf( anal_path, sizeof(anal_path), "%s/%d/%%s/%%0%dd-analyse.jpg", config.dir_events, monitor->Id(), config.event_image_digits ); zmSetDefaultTermHandler(); zmSetDefaultDieHandler(); sigset_t block_set; sigemptyset( &block_set ); int sd = OpenSocket( monitor->Id() ); FrameHeader frame_header = { 0, 0, false, 0 }; //unsigned char *image_data = 0; fd_set rfds; struct timeval timeout; timeout.tv_sec = 1; timeout.tv_usec = 0; while( 1 ) { struct timeval temp_timeout = timeout; FD_ZERO(&rfds); FD_SET(sd, &rfds); int n_found = select( sd+1, &rfds, NULL, NULL, &temp_timeout ); if( n_found == 0 ) { Debug( 1, "Select timed out" ); continue; } else if ( n_found < 0) { Error( "Select error: %s", strerror(errno) ); ReopenSocket( sd, monitor->Id() ); continue; } sigprocmask( SIG_BLOCK, &block_set, 0 ); int n_bytes = read( sd, &frame_header, sizeof(frame_header) ); if ( n_bytes != sizeof(frame_header) ) { if ( n_bytes < 0 ) { Error( "Can't read frame header: %s", strerror(errno) ); } else if ( n_bytes > 0 ) { Error( "Incomplete read of frame header, %d bytes only", n_bytes ); } else { Warning( "Socket closed at remote end" ); } ReopenSocket( sd, monitor->Id() ); continue; } Debug( 1, "Read frame header, expecting %ld bytes of image", frame_header.image_length ); static unsigned char image_data[ZM_MAX_IMAGE_SIZE]; // Read for pipe and loop until bytes expected have been read or an error occurs int bytes_read = 0; do { n_bytes = read( sd, image_data+bytes_read, frame_header.image_length-bytes_read ); if (n_bytes < 0) break; // break on error if (n_bytes < (int)frame_header.image_length) { // print some informational messages if (bytes_read == 0) { Debug(4,"Image read : Short read %d bytes of %d expected bytes",n_bytes,frame_header.image_length); } else if (bytes_read+n_bytes == (int)frame_header.image_length) { Debug(5,"Image read : Read rest of short read: %d bytes read total of %d bytes",n_bytes,frame_header.image_length); } else { Debug(6,"Image read : continuing, read %d bytes (%d so far)", n_bytes, bytes_read+n_bytes); } } bytes_read+= n_bytes; } while (n_bytes>0 && (bytes_read < (ssize_t)frame_header.image_length) ); // Print errors if there was a problem if ( n_bytes < 1 ) { Error( "Only read %d bytes of %d\n", bytes_read, frame_header.image_length); if ( n_bytes < 0 ) { Error( "Can't read frame image data: %s", strerror(errno) ); } else { Warning( "Socket closed at remote end" ); } ReopenSocket( sd, monitor->Id() ); continue; } static char subpath[PATH_MAX] = ""; if ( config.use_deep_storage ) { struct tm *time = localtime( &frame_header.event_time ); snprintf( subpath, sizeof(subpath), "%02d/%02d/%02d/%02d/%02d/%02d", time->tm_year-100, time->tm_mon+1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec ); } else { snprintf( subpath, sizeof(subpath), "%ld", frame_header.event_id ); } static char path[PATH_MAX] = ""; snprintf( path, sizeof(path), frame_header.alarm_frame?anal_path:capt_path, subpath, frame_header.frame_id ); Debug( 1, "Got image, writing to %s", path ); FILE *fd = 0; if ( (fd = fopen( path, "w" )) < 0 ) { Error( "Can't fopen '%s': %s", path, strerror(errno) ); exit( -1 ); } if ( 0 == fwrite( image_data, frame_header.image_length, 1, fd ) ) { Error( "Can't fwrite image data: %s", strerror(errno) ); exit( -1 ); } fclose( fd ); sigprocmask( SIG_UNBLOCK, &block_set, 0 ); } logTerm(); zmDbClose(); }
void CommStart(PComVar cv, LONG lParam, PTTSet ts) { char ErrMsg[31]; char Temp[20]; char uimsg[MAX_UIMSG]; if (! cv->Open ) { return; } if ( cv->Ready ) { return; } // キャンセルタイマがあれば取り消す。ただし、この時点で WM_TIMER が送られている可能性はある。 if (*cv->ConnetingTimeout > 0) { KillTimer(cv->HWin, IdCancelConnectTimer); } switch (cv->PortType) { case IdTCPIP: ErrMsg[0] = 0; switch (HIWORD(lParam)) { case WSAECONNREFUSED: get_lang_msg("MSG_COMM_REFUSE_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Connection refused", ts->UILanguageFile); _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "%s", ts->UIMsg); break; case WSAENETUNREACH: get_lang_msg("MSG_COMM_REACH_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Network cannot be reached", ts->UILanguageFile); _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "%s", ts->UIMsg); break; case WSAETIMEDOUT: get_lang_msg("MSG_COMM_CONNECT_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Connection timed out", ts->UILanguageFile); _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "%s", ts->UIMsg); break; default: get_lang_msg("MSG_COMM_TIMEOUT_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot connect the host", ts->UILanguageFile); _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "%s", ts->UIMsg); } if (HIWORD(lParam)>0) { #ifndef NO_INET6 /* connect() failed */ if (cv->res->ai_next != NULL) { /* try to connect with other protocol */ CloseSocket(cv->s); for (cv->res = cv->res->ai_next; cv->res; cv->res = cv->res->ai_next) { cv->s = OpenSocket(cv); if (cv->s == INVALID_SOCKET) { CloseSocket(cv->s); continue; } AsyncConnect(cv); cv->Ready = FALSE; cv->RetryWithOtherProtocol = TRUE; /* retry with other procotol */ return; } } else { /* trying with all protocol family are failed */ if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); MessageBox(cv->HWin,ErrMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); } PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_CLOSE); cv->RetryWithOtherProtocol = FALSE; return; } #else if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); MessageBox(cv->HWin, ErrMsg, uimsg, MB_TASKMODAL | MB_ICONEXCLAMATION); } PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_CLOSE); return; #endif /* NO_INET6 */ } #ifndef NO_INET6 /* here is connection established */ cv->RetryWithOtherProtocol = FALSE; #endif /* NO_INET6 */ PWSAAsyncSelect(cv->s,cv->HWin,WM_USER_COMMNOTIFY, FD_READ | FD_OOB | FD_CLOSE); TCPIPClosed = FALSE; break; case IdSerial: _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", READENDNAME, cv->ComPort); ReadEnd = CreateEvent(NULL,FALSE,FALSE,Temp); _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", WRITENAME, cv->ComPort); memset(&wol,0,sizeof(OVERLAPPED)); wol.hEvent = CreateEvent(NULL,TRUE,TRUE,Temp); _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", READNAME, cv->ComPort); memset(&rol,0,sizeof(OVERLAPPED)); rol.hEvent = CreateEvent(NULL,TRUE,FALSE,Temp); /* create the receiver thread */ if (_beginthread(CommThread,0,cv) == -1) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); get_lang_msg("MSG_TT_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Can't create thread", ts->UILanguageFile); MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); } break; case IdFile: cv->RRQ = TRUE; break; case IdNamedPipe: cv->ComPort = 0; _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", READENDNAME, cv->ComPort); ReadEnd = CreateEvent(NULL,FALSE,FALSE,Temp); _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", WRITENAME, cv->ComPort); memset(&wol,0,sizeof(OVERLAPPED)); wol.hEvent = CreateEvent(NULL,TRUE,TRUE,Temp); _snprintf_s(Temp, sizeof(Temp), _TRUNCATE, "%s%d", READNAME, cv->ComPort); memset(&rol,0,sizeof(OVERLAPPED)); rol.hEvent = CreateEvent(NULL,TRUE,FALSE,Temp); /* create the receiver thread */ if (_beginthread(NamedPipeThread,0,cv) == -1) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); get_lang_msg("MSG_TT_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Can't create thread", ts->UILanguageFile); MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); } break; } cv->Ready = TRUE; }
/* * NET_IP_OpenSocket */ static qboolean NET_IP_OpenSocket( socket_t *sock, const netadr_t *address, socket_type_t socktype, qboolean server ) { int newsocket; const char *proto, *stype; assert( sock && !sock->open ); assert( address ); if( address->type == NA_IP ) proto = "IP"; else if( address->type == NA_IP6 ) proto = "IPv6"; else { NET_SetErrorString( "Invalid address type" ); return qfalse; } if( socktype == SOCKET_UDP ) stype = "UDP"; #ifdef TCP_SUPPORT else if( socktype == SOCKET_TCP ) stype = "TCP"; #endif else { NET_SetErrorString( "Invalid socket type" ); return qfalse; } if( NET_IsAnyAddress( address ) ) { Com_Printf( "Opening %s/%s socket: *:%hu\n", stype, proto, NET_GetAddressPort( address ) ); } else { Com_Printf( "Opening %s/%s socket: %s\n", stype, proto, NET_AddressToString( address ) ); } if( ( newsocket = OpenSocket( socktype, ( address->type == NA_IP6 ? qtrue : qfalse ) ) ) == INVALID_SOCKET ) return qfalse; // make it non-blocking if( !NET_SocketMakeNonBlocking( newsocket ) ) { Sys_NET_SocketClose( newsocket ); return qfalse; } if( socktype == SOCKET_UDP ) { // make it broadcast capable if( !NET_SocketMakeBroadcastCapable( newsocket ) ) { Sys_NET_SocketClose( newsocket ); return qfalse; } } // wsw : pb : make it reusable (fast release of port when quit) /*if( setsockopt(newsocket, SOL_SOCKET, SO_REUSEADDR, (char *)&i, sizeof(i)) == -1 ) { SetErrorStringFromErrno( "setsockopt" ); return 0; }*/ if( !BindSocket( newsocket, address ) ) { Sys_NET_SocketClose( newsocket ); return qfalse; } sock->open = qtrue; sock->type = socktype; sock->address = *address; sock->server = server; sock->handle = newsocket; return qtrue; }
int ReopenSocket( int &sd, int monitor_id ) { close( sd ); return( sd = OpenSocket( monitor_id ) ); }
int main( int argc, char *argv[] ) { srand( getpid() * time( 0 ) ); int id = -1; static struct option long_options[] = { {"monitor", 1, 0, 'm'}, {"help", 0, 0, 'h'}, {0, 0, 0, 0} }; while (1) { int option_index = 0; int c = getopt_long (argc, argv, "m:h", long_options, &option_index); if (c == -1) { break; } switch (c) { case 'm': id = atoi(optarg); break; case 'h': case '?': Usage(); break; default: //fprintf( stderr, "?? getopt returned character code 0%o ??\n", c ); break; } } if (optind < argc) { fprintf( stderr, "Extraneous options, " ); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); Usage(); } if ( id < 0 ) { fprintf( stderr, "Bogus monitor %d\n", id ); Usage(); exit( 0 ); } char dbg_id_string[16]; snprintf( dbg_id_string, sizeof(dbg_id_string), "m%d", id ); zmDbgInit( "zmf", dbg_id_string, 0 ); zmLoadConfig(); Monitor *monitor = Monitor::Load( id, false, Monitor::QUERY ); if ( !monitor ) { fprintf( stderr, "Can't find monitor with id of %d\n", id ); exit( -1 ); } char capt_path[PATH_MAX]; char anal_path[PATH_MAX]; snprintf( capt_path, sizeof(capt_path), "%s/%d/%%s/%%0%dd-capture.jpg", config.dir_events, monitor->Id(), config.event_image_digits ); snprintf( anal_path, sizeof(anal_path), "%s/%d/%%s/%%0%dd-analyse.jpg", config.dir_events, monitor->Id(), config.event_image_digits ); zmSetDefaultTermHandler(); zmSetDefaultDieHandler(); sigset_t block_set; sigemptyset( &block_set ); int sd = OpenSocket( monitor->Id() ); FrameHeader frame_header = { 0, 0, false, 0 }; //unsigned char *image_data = 0; fd_set rfds; struct timeval timeout; timeout.tv_sec = 1; timeout.tv_usec = 0; while( 1 ) { struct timeval temp_timeout = timeout; FD_ZERO(&rfds); FD_SET(sd, &rfds); int n_found = select( sd+1, &rfds, NULL, NULL, &temp_timeout ); if( n_found == 0 ) { Debug( 1, "Select timed out" ); continue; } else if ( n_found < 0) { Error( "Select error: %s", strerror(errno) ); ReopenSocket( sd, monitor->Id() ); continue; } sigprocmask( SIG_BLOCK, &block_set, 0 ); int n_bytes = read( sd, &frame_header, sizeof(frame_header) ); if ( n_bytes != sizeof(frame_header) ) { if ( n_bytes < 0 ) { Error( "Can't read frame header: %s", strerror(errno) ); } else if ( n_bytes > 0 ) { Error( "Incomplete read of frame header, %d bytes only", n_bytes ); } else { Warning( "Socket closed at remote end" ); } ReopenSocket( sd, monitor->Id() ); continue; } Debug( 1, "Read frame header, expecting %ld bytes of image", frame_header.image_length ); static unsigned char image_data[ZM_MAX_IMAGE_SIZE]; n_bytes = read( sd, image_data, frame_header.image_length ); if ( n_bytes != (ssize_t)frame_header.image_length ) { if ( n_bytes < 0 ) { Error( "Can't read frame image data: %s", strerror(errno) ); } else if ( n_bytes > 0 ) { Error( "Incomplete read of frame image data, %d bytes only", n_bytes ); } else { Warning( "Socket closed at remote end" ); } ReopenSocket( sd, monitor->Id() ); continue; } static char subpath[PATH_MAX] = ""; if ( config.use_deep_storage ) { struct tm *time = localtime( &frame_header.event_time ); snprintf( subpath, sizeof(subpath), "%02d/%02d/%02d/%02d/%02d/%02d", time->tm_year-100, time->tm_mon+1, time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec ); } else { snprintf( subpath, sizeof(subpath), "%ld", frame_header.event_id ); } static char path[PATH_MAX] = ""; snprintf( path, sizeof(path), frame_header.alarm_frame?anal_path:capt_path, subpath, frame_header.frame_id ); Debug( 1, "Got image, writing to %s", path ); FILE *fd = 0; if ( (fd = fopen( path, "w" )) < 0 ) { Error( "Can't fopen '%s': %s", path, strerror(errno) ); exit( -1 ); } if ( 0 == fwrite( image_data, frame_header.image_length, 1, fd ) ) { Error( "Can't fwrite image data: %s", strerror(errno) ); exit( -1 ); } fclose( fd ); sigprocmask( SIG_UNBLOCK, &block_set, 0 ); } }
int testserver(void) { unsigned int sockaddr; unsigned char mysocket; unsigned int rsize; mysocket = 0; // magic number! declare the socket number we will use (0-3) sockaddr = 0x400;//W5100_SKT_BASE(mysocket); // calc address of W5100 register set for this socket /* * The main loop. Control stays in this loop forever, processing any received packets * and sending any requested data. */ while (1) { LATAbits.LATA0 ^= 1; int x = w5100_read(sockaddr + W5100_SR_OFFSET); switch (x) // based on current status of socket... { case W5100_SKT_SR_CLOSED: // if socket is closed... LATBbits.LATB8 = 0; if (OpenSocket(mysocket, W5100_SKT_MR_TCP, HTTP_PORT) == mysocket) // if successful opening a socket... { Listen(mysocket); __delay_ms(1); } break; case W5100_SKT_SR_ESTABLISHED: // if socket connection is established... LATBbits.LATB8 = 1; rsize = ReceivedSize(mysocket); // find out how many bytes if (rsize > 0) { if (Receive(mysocket, buf, rsize) != W5100_OK) break; // if we had problems, all done /* * Add code here to process the payload from the packet. * * For now, we just ignore the payload and send a canned HTML page so the client at least * knows we are alive. */ strcpy((char *) buf, "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nPragma: no-cache\r\n\r\n"); strcat((char *) buf, "<html>\r\n<body>\r\n"); strcat((char *) buf, "<title>Phil's W5100 web server (ATmega644p)</title>\r\n"); strcat((char *) buf, "<h2>Phil's ATmega644p web server using Wiznet W5100 chip</h2>\r\n"); strcat((char *) buf, "<br /><hr>\r\n"); if (Send(mysocket, buf, strlen((char *) buf)) == W5100_FAIL) break; // just throw out the packet for now strcpy((char *) buf, "This is part 2 of the page."); strcat((char *) buf, "</body>\r\n</html>\r\n"); if (Send(mysocket, buf, strlen((char *) buf)) == W5100_FAIL) break; // just throw out the packet for now DisconnectSocket(mysocket); } else // no data yet... { __delay_us(10); } break; case W5100_SKT_SR_FIN_WAIT: case W5100_SKT_SR_CLOSING: case W5100_SKT_SR_TIME_WAIT: case W5100_SKT_SR_CLOSE_WAIT: case W5100_SKT_SR_LAST_ACK: CloseSocket(mysocket); break; } } return 0; }
int main(void) { unsigned int sockaddr; unsigned char mysocket; unsigned int rsize; /* Initialize the UART for ATmega168 96008N1 */ uart_init(); stdout = &uart_stdout; //Required for printf init mysocket = 0; // magic number! declare the socket number we will us sockaddr = W5100_SKT_BASE(mysocket); // calc address of W5100 register set for this socket puts("AVR Ethernet\r\n"); /* * Initialize the ATmega168 SPI subsystem */ CS_PORT |= (1 << CS_BIT); // pull CS pin high CS_DDR |= (1 << CS_BIT); // now make it an output SPI_PORT = SPI_PORT | (1 << PORTB2); // make sure SS is high SPI_DDR = (1 << PORTB3) | (1 << PORTB5) | (1 << PORTB2); // set MOSI, SCK and SS as output, others as input SPCR = (1 << SPE) | (1 << MSTR); // enable SPI, master mode 0 SPSR |= (1 << SPI2X); // set the clock rate fck/2 /* * Load up the callback block, then initialize the Wiznet W5100 */ my_callbacks._select = &my_select; // callback for selecting the W5100 my_callbacks._xchg = &my_xchg; // callback for exchanging data my_callbacks._deselect = &my_deselect; // callback for deselecting the W5100 my_callbacks._reset = &my_reset; // callback for hardware-reset of the W5100 W51_register(&my_callbacks); // register our target-specific W5100 routines with the W5100 library W51_init(); // now initialize the W5100 /* * Configure the W5100 device to handle PING requests. * This requires configuring the chip, not a specific socket. */ W51_config(&my_cfg); // config the W5100 (MAC, TCP address, subnet, etc puts("Debug: AVR Ethernet after W5100 config\r\n"); /* * The main loop. Control stays in this loop forever, processing any received packets * and sending any requested data. */ while (1) { switch (W51_read(sockaddr + W5100_SR_OFFSET)) // based on current status of socket... { case W5100_SKT_SR_CLOSED: // if socket is closed... if (OpenSocket(mysocket, W5100_SKT_MR_TCP, HTTP_PORT) == mysocket) // if successful opening a socket... { Listen(mysocket); _delay_ms(1); } break; case W5100_SKT_SR_ESTABLISHED: // if socket connection is established... rsize = ReceivedSize(mysocket); // find out how many bytes if (rsize > 0) { if (Receive(mysocket, buf, rsize) != W5100_OK) break; // if we had problems, all done /* * Add code here to process the payload from the packet. * * For now, we just ignore the payload and send a canned HTML page so the client at least * knows we are alive. */ strcpy_P((char *)buf,PSTR("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nPragma: no-cache\r\n\r\n")); strcat_P((char *)buf,PSTR("<html>\r\n<body>\r\n")); strcat_P((char *)buf,PSTR("<title>Title</title>\r\n")); strcat_P((char *)buf,PSTR("<p>Hello world</p>\r\n")); strcat_P((char *)buf,PSTR("</body>\r\n</html>\r\n")); if (Send(mysocket, buf, strlen((char *)buf)) == W5100_FAIL) break; // just throw out the packet for now DisconnectSocket(mysocket); } else // no data yet... { _delay_us(10); } break; case W5100_SKT_SR_FIN_WAIT: case W5100_SKT_SR_CLOSING: case W5100_SKT_SR_TIME_WAIT: case W5100_SKT_SR_CLOSE_WAIT: case W5100_SKT_SR_LAST_ACK: CloseSocket(mysocket); break; } } return 0; }
I2Addr CreateListenSocket(I2Addr addr, char* serv, int options, int buf_size) { int fd = -1; socklen_t optlen; int set_size; if (addr && (I2AddrFD(addr) > -1)) { log_println(1, "Invalid I2Addr record - fd already specified."); goto error; } if ((!addr) && !(addr = I2AddrByWildcard(get_errhandle(), SOCK_STREAM, serv))) { log_println(1, "Unable to create I2Addr record by wildcard."); goto error; } if (!I2AddrSetPassive(addr,True)) { log_println(1, "Unable to set passive mode in I2Addr record."); goto error; } fd = OpenSocket(addr, serv, options); if (fd < 0) { log_println(1, "Unable to open socket."); goto error; } /* Set sock opt code from Marion Nakanson <[email protected] * OHSU Advanced Computing Center * email on 2/19/09 correctly notes that setsockops must be made before open() * or listen() calls are made */ optlen = sizeof(set_size); getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &set_size, &optlen); log_print(5, "\nSend buffer initialized to %d, ", set_size); getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &set_size, &optlen); log_println(5, "Receive buffer initialized to %d", set_size); if (buf_size > 0) { setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buf_size, sizeof(buf_size)); setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buf_size, sizeof(buf_size)); getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &set_size, &optlen); log_print(5, "Changed buffer sizes: Send buffer set to %d(%d), ", set_size, buf_size); getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &set_size, &optlen); log_println(5, "Receive buffer set to %d(%d)", set_size, buf_size); } if (listen(fd, NDT_BACKLOG) < 0) { log_println(1, "listen(%d,%d):%s", fd, NDT_BACKLOG, strerror(errno)); goto error; } return addr; error: I2AddrFree(addr); return NULL; }
void CommOpen(HWND HW, PTTSet ts, PComVar cv) { #ifdef NO_INET6 int Err; #endif /* NO_INET6 */ char ErrMsg[21+256]; char P[50+256]; MSG Msg; #ifndef NO_INET6 ADDRINFO hints; char pname[NI_MAXSERV]; #else char HEntBuff[MAXGETHOSTSTRUCT]; u_long addr; SOCKADDR_IN saddr; #endif /* NO_INET6 */ BOOL InvalidHost; #ifdef NO_INET6 BOOL BBuf; #endif /* NO_INET6 */ char uimsg[MAX_UIMSG]; // ホスト名が名前付きパイプかどうかを調べる。 if (ts->PortType == IdTCPIP) { if (CheckNamedPipeFormat(ts->HostName, strlen(ts->HostName)) == 0) { ts->PortType = IdNamedPipe; } } /* initialize ComVar */ cv->InBuffCount = 0; cv->InPtr = 0; cv->OutBuffCount = 0; cv->OutPtr = 0; cv->HWin = HW; cv->Ready = FALSE; cv->Open = FALSE; cv->PortType = ts->PortType; cv->ComPort = 0; cv->RetryCount = 0; #ifndef NO_INET6 cv->RetryWithOtherProtocol = TRUE; #endif /* NO_INET6 */ cv->s = INVALID_SOCKET; cv->ComID = INVALID_HANDLE_VALUE; cv->CanSend = TRUE; cv->RRQ = FALSE; cv->SendKanjiFlag = FALSE; cv->SendCode = IdASCII; cv->EchoKanjiFlag = FALSE; cv->EchoCode = IdASCII; cv->Language = ts->Language; cv->CRSend = ts->CRSend; cv->KanjiCodeEcho = ts->KanjiCode; cv->JIS7KatakanaEcho = ts->JIS7Katakana; cv->KanjiCodeSend = ts->KanjiCodeSend; cv->JIS7KatakanaSend = ts->JIS7KatakanaSend; cv->KanjiIn = ts->KanjiIn; cv->KanjiOut = ts->KanjiOut; cv->RussHost = ts->RussHost; cv->RussClient = ts->RussClient; cv->DelayFlag = TRUE; cv->DelayPerChar = ts->DelayPerChar; cv->DelayPerLine = ts->DelayPerLine; cv->TelBinRecv = FALSE; cv->TelBinSend = FALSE; cv->TelFlag = FALSE; cv->TelMode = FALSE; cv->IACFlag = FALSE; cv->TelCRFlag = FALSE; cv->TelCRSend = FALSE; cv->TelCRSendEcho = FALSE; cv->TelAutoDetect = ts->TelAutoDetect; /* TTPLUG */ cv->Locale = ts->Locale; cv->locale = _create_locale(LC_ALL, cv->Locale); cv->CodePage = &ts->CodePage; cv->ConnetingTimeout = &ts->ConnectingTimeout; cv->LastSendTime = time(NULL); cv->LineModeBuffCount = 0; cv->Flush = FALSE; cv->FlushLen = 0; cv->TelLineMode = FALSE; if ((ts->PortType!=IdSerial) && (strlen(ts->HostName)==0)) { PostMessage(cv->HWin, WM_USER_COMMNOTIFY, 0, FD_CLOSE); return; } switch (ts->PortType) { case IdTCPIP: cv->TelFlag = (ts->Telnet > 0); if (ts->EnableLineMode) { cv->TelLineMode = TRUE; } if (! LoadWinsock()) { if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); get_lang_msg("MSG_WINSOCK_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot use winsock", ts->UILanguageFile); MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); } InvalidHost = TRUE; } else { TTXOpenTCP(); /* TTPLUG */ cv->Open = TRUE; #ifndef NO_INET6 /* resolving address */ memset(&hints, 0, sizeof(hints)); hints.ai_family = ts->ProtocolFamily; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; _snprintf_s(pname, sizeof(pname), _TRUNCATE, "%d", ts->TCPPort); HAsync = PWSAAsyncGetAddrInfo(HW, WM_USER_GETHOST, ts->HostName, pname, &hints, &cv->res0); if (HAsync == 0) InvalidHost = TRUE; else { cv->ComPort = 1; // set "getting host" flag // (see CVTWindow::OnSysCommand()) do { if (GetMessage(&Msg,0,0,0)) { if ((Msg.hwnd==HW) && ((Msg.message == WM_SYSCOMMAND) && ((Msg.wParam & 0xfff0) == SC_CLOSE) || (Msg.message == WM_COMMAND) && (LOWORD(Msg.wParam) == ID_FILE_EXIT) || (Msg.message == WM_CLOSE))) { /* Exit when the user closes Tera Term */ PWSACancelAsyncRequest(HAsync); CloseHandle(HAsync); HAsync = 0; cv->ComPort = 0; // clear "getting host" flag PostMessage(HW,Msg.message,Msg.wParam,Msg.lParam); return; } if (Msg.message != WM_USER_GETHOST) { /* Prosess messages */ TranslateMessage(&Msg); DispatchMessage(&Msg); } } else { return; } } while (Msg.message!=WM_USER_GETHOST); cv->ComPort = 0; // clear "getting host" flag CloseHandle(HAsync); HAsync = 0; InvalidHost = WSAGETASYNCERROR(Msg.lParam) != 0; } } /* if (!LoadWinsock()) */ if (InvalidHost) { if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); get_lang_msg("MSG_INVALID_HOST_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Invalid host", ts->UILanguageFile); MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); } goto BreakSC; } for (cv->res = cv->res0; cv->res; cv->res = cv->res->ai_next) { cv->s = OpenSocket(cv); if (cv->s == INVALID_SOCKET) { CloseSocket(cv->s); continue; } /* start asynchronous connect */ AsyncConnect(cv); break; /* break for-loop immediately */ } break; #else if ((ts->HostName[0] >= 0x30) && (ts->HostName[0] <= 0x39)) { addr = Pinet_addr(ts->HostName); InvalidHost = (addr == 0xffffffff); } else { HAsync = PWSAAsyncGetHostByName(HW,WM_USER_GETHOST, ts->HostName,HEntBuff,sizeof(HEntBuff)); if (HAsync == 0) InvalidHost = TRUE; else { cv->ComPort = 1; // set "getting host" flag // (see CVTWindow::OnSysCommand()) do { if (GetMessage(&Msg,0,0,0)) { if ((Msg.hwnd==HW) && ((Msg.message == WM_SYSCOMMAND) && ((Msg.wParam & 0xfff0) == SC_CLOSE) || (Msg.message == WM_COMMAND) && (LOWORD(Msg.wParam) == ID_FILE_EXIT) || (Msg.message == WM_CLOSE))) { /* Exit when the user closes Tera Term */ PWSACancelAsyncRequest(HAsync); HAsync = 0; cv->ComPort = 0; // clear "getting host" flag PostMessage(HW,Msg.message,Msg.wParam,Msg.lParam); return; } if (Msg.message != WM_USER_GETHOST) { /* Prosess messages */ TranslateMessage(&Msg); DispatchMessage(&Msg); } } else { return; } } while (Msg.message!=WM_USER_GETHOST); cv->ComPort = 0; // clear "getting host" flag HAsync = 0; InvalidHost = WSAGETASYNCERROR(Msg.lParam) != 0; if (! InvalidHost) { if (((PHOSTENT)HEntBuff)->h_addr_list != NULL) memcpy(&addr, ((PHOSTENT)HEntBuff)->h_addr_list[0],sizeof(addr)); else InvalidHost = TRUE; } } } if (InvalidHost) { if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); get_lang_msg("MSG_INVALID_HOST_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Invalid host", ts->UILanguageFile); MessageBox(cv->HWin, ts->UIMsg, uimsg, MB_TASKMODAL | MB_ICONEXCLAMATION); } } else { cv->s= Psocket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (cv->s==INVALID_SOCKET) { InvalidHost = TRUE; if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); get_lang_msg("MSG_COMM_TIMEOUT_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot connect the host", ts->UILanguageFile); MessageBox(cv->HWin, ts->UIMsg, uimsg, MB_TASKMODAL | MB_ICONEXCLAMATION); } } else { BBuf = TRUE; Psetsockopt(cv->s,(int)SOL_SOCKET,SO_OOBINLINE,(char FAR *)&BBuf,sizeof(BBuf)); PWSAAsyncSelect(cv->s,cv->HWin,WM_USER_COMMOPEN, FD_CONNECT); saddr.sin_family = AF_INET; saddr.sin_port = Phtons(ts->TCPPort); saddr.sin_addr.s_addr = addr; memset(saddr.sin_zero,0,8); Err = Pconnect(cv->s,(LPSOCKADDR)&saddr,sizeof(saddr)); if (Err!=0 ) Err = PWSAGetLastError(); if (Err==WSAEWOULDBLOCK ) { /* Do nothing */ } else if (Err!=0 ) PostMessage(cv->HWin, WM_USER_COMMOPEN,0, MAKELONG(FD_CONNECT,Err)); } } } break; #endif /* NO_INET6 */ case IdSerial: InitFileIO(IdSerial); /* TTPLUG */ TTXOpenFile(); /* TTPLUG */ _snprintf_s(P, sizeof(P), _TRUNCATE, "COM%d", ts->ComPort); strncpy_s(ErrMsg, sizeof(ErrMsg),P, _TRUNCATE); strncpy_s(P, sizeof(P),"\\\\.\\", _TRUNCATE); strncat_s(P, sizeof(P),ErrMsg, _TRUNCATE); cv->ComID = PCreateFile(P,GENERIC_READ | GENERIC_WRITE, 0,NULL,OPEN_EXISTING, FILE_FLAG_OVERLAPPED,NULL); if (cv->ComID == INVALID_HANDLE_VALUE ) { get_lang_msg("MSG_CANTOEPN_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot open %s", ts->UILanguageFile); _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, ts->UIMsg, &P[4]); if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); MessageBox(cv->HWin,ErrMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); } InvalidHost = TRUE; } else { cv->Open = TRUE; cv->ComPort = ts->ComPort; CommResetSerial(ts, cv, ts->ClearComBuffOnOpen); if (!ts->ClearComBuffOnOpen) { cv->RRQ = TRUE; } /* notify to VT window that Comm Port is open */ PostMessage(cv->HWin, WM_USER_COMMOPEN, 0, 0); InvalidHost = FALSE; SetCOMFlag(ts->ComPort); } break; /* end of "case IdSerial:" */ case IdFile: InitFileIO(IdFile); /* TTPLUG */ TTXOpenFile(); /* TTPLUG */ cv->ComID = PCreateFile(ts->HostName,GENERIC_READ,0,NULL, OPEN_EXISTING,0,NULL); InvalidHost = (cv->ComID == INVALID_HANDLE_VALUE); if (InvalidHost) { if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); get_lang_msg("MSG_CANTOEPN_FILE_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot open file", ts->UILanguageFile); MessageBox(cv->HWin,ts->UIMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); } } else { cv->Open = TRUE; PostMessage(cv->HWin, WM_USER_COMMOPEN, 0, 0); } break; case IdNamedPipe: InitFileIO(IdNamedPipe); /* TTPLUG */ TTXOpenFile(); /* TTPLUG */ memset(P, 0, sizeof(P)); strncpy_s(P, sizeof(P), ts->HostName, _TRUNCATE); // 名前付きパイプが正しい書式かをチェックする。 if (CheckNamedPipeFormat(P, strlen(P)) < 0) { InvalidHost = TRUE; _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, "Invalid pipe name\n\n" "A valid pipe name has the form\n" "\"\\\\<ServerName>\\pipe\\<PipeName>\"", GetLastError()); get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); MessageBox(cv->HWin,ErrMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); break; } cv->ComID = PCreateFile(P,GENERIC_READ | GENERIC_WRITE, 0,NULL,OPEN_EXISTING, 0, // ブロッキングモードにする(FILE_FLAG_OVERLAPPED は指定しない) NULL); if (cv->ComID == INVALID_HANDLE_VALUE ) { get_lang_msg("MSG_CANTOEPN_ERROR", ts->UIMsg, sizeof(ts->UIMsg), "Cannot open %s", ts->UILanguageFile); _snprintf_s(ErrMsg, sizeof(ErrMsg), _TRUNCATE, ts->UIMsg, &P[4]); if (cv->NoMsg==0) { get_lang_msg("MSG_TT_ERROR", uimsg, sizeof(uimsg), "Tera Term: Error", ts->UILanguageFile); MessageBox(cv->HWin,ErrMsg,uimsg,MB_TASKMODAL | MB_ICONEXCLAMATION); } InvalidHost = TRUE; } else { cv->Open = TRUE; PostMessage(cv->HWin, WM_USER_COMMOPEN, 0, 0); InvalidHost = FALSE; } break; /* end of "case IdNamedPipe:" */ } /* end of "switch" */
I2Addr CreateListenSocket(I2Addr addr, char* serv, int options, int buf_size) { int fd = -1; socklen_t optlen; int set_size; if (addr && (I2AddrFD(addr) > -1)) { log_println(1, "Invalid I2Addr record - fd already specified."); goto error; } if ((!addr) && !(addr = I2AddrByWildcard(get_errhandle(), SOCK_STREAM, serv))) { log_println(1, "Unable to create I2Addr record by wildcard."); goto error; } if (!I2AddrSetPassive(addr, True)) { log_println(1, "Unable to set passive mode in I2Addr record."); goto error; } // create and bind socket using arguments, prefering v6 (since v6 addresses // can be both v4 and v6). #ifdef AF_INET6 if ((options & OPT_IPV4_ONLY) == 0) fd = OpenSocket(addr, serv, AF_INET6, options); #endif if (fd < 0) if ((options & OPT_IPV6_ONLY) == 0) fd = OpenSocket(addr, serv, AF_INET, options); if (fd < 0) { log_println(1, "Unable to open socket."); goto error; } /* Set sock opt code from Marion Nakanson <[email protected] * OHSU Advanced Computing Center * email on 2/19/09 correctly notes that setsockops must be made before open() * or listen() calls are made */ optlen = sizeof(set_size); // get send buffer size getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &set_size, &optlen); log_print(5, "\nSend buffer initialized to %d, ", set_size); // get receive buffer size getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &set_size, &optlen); log_println(5, "Receive buffer initialized to %d", set_size); // now assign buffer sizes passed as arguments if (buf_size > 0) { setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buf_size, sizeof(buf_size)); setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buf_size, sizeof(buf_size)); // print values set to help user verify getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &set_size, &optlen); log_print(5, "Changed buffer sizes: Send buffer set to %d(%d), ", set_size, buf_size); getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &set_size, &optlen); log_println(5, "Receive buffer set to %d(%d)", set_size, buf_size); } // listen on socket for connections, with backlog queue length = NDT_BACKLOG if (listen(fd, NDT_BACKLOG) < 0) { // if listen returns value <0, then error log_println(1, "listen(%d,%d):%s", fd, NDT_BACKLOG, strerror(errno)); goto error; } return addr; // If error, try freeing memory error: I2AddrFree(addr); return NULL; }
void CTcpSymbianEngine::OpenSocketL() { User::LeaveIfError(OpenSocket()); }