bool MgAceStreamHelper::IsConnected() { bool bConnected = true; ACE_SOCK_Stream stream; stream.set_handle( m_handle ); UINT8 dummy; ACE_Time_Value val(0, 0); ssize_t res = stream.recv_n(&dummy, 1, MSG_PEEK | MG_MSG_NOSIGNAL, &val); if ( res < 0 ) { // Error or timeout occured #ifdef _WIN32 int error = ::WSAGetLastError(); // errno doesn't work correctly on Windows bConnected = ( error == WSAEWOULDBLOCK || error == 0 ); #else bConnected = ( errno == EWOULDBLOCK || errno == 0 || errno == ETIME ); #endif } else if (res == 0) { // No longer connected bConnected = false; } return bConnected; }
void JAWS_Synch_IO::receive_file (const char *filename, void *initial_data, int initial_data_length, int entire_length) { ACE_Filecache_Handle handle (ACE_TEXT_CHAR_TO_TCHAR (filename), entire_length); int result = handle.error (); if (result == ACE_Filecache_Handle::ACE_SUCCESS) { ACE_SOCK_Stream stream; stream.set_handle (this->handle_); int bytes_to_memcpy = ACE_MIN (entire_length, initial_data_length); ACE_OS::memcpy (handle.address (), initial_data, bytes_to_memcpy); int bytes_to_read = entire_length - bytes_to_memcpy; int bytes = stream.recv_n ((char *) handle.address () + initial_data_length, bytes_to_read); if (bytes == bytes_to_read) this->handler_->receive_file_complete (); else result = -1; } if (result != ACE_Filecache_Handle::ACE_SUCCESS) this->handler_->receive_file_error (result); }
/////////////////////////////////////////////////////////////////////////// // <summary> // This method writes data from the given buffer to the underlying stream. // It can block or not, depending on the value of the blocking parameter. // </summary> // // <param name = "buffer"> // The buffer that contains the data to be written. // </param> // // <param name = "size"> // The size of the buffer in bytes of the buffer. // </param> // // <param name = "blocking"> // True if the write request should block; false otherwise. // </param> // // <param name = "bytesWritten"> // An out parameter that will contain the number of bytes that have been // written to the stream. // </param> // // <returns> // Returns a MgStreamStatus value indicating the status of the operation. // </returns> MgStreamHelper::MgStreamStatus MgAceStreamHelper::WriteData(void* buffer, size_t size, bool blocking, size_t* bytesWritten) { // Do not attempt writing zero byte to the socket as this could be problematic. if (0 == size) { return MgStreamHelper::mssDone; } ACE_ASSERT( buffer && size > 0 ); MgStreamHelper::MgStreamStatus stat = MgStreamHelper::mssError; // check parameters if ( buffer && size > 0 ) { // init out parameter if ( bytesWritten != NULL ) *bytesWritten = 0; ACE_SOCK_Stream stream; stream.set_handle( m_handle ); ssize_t res = 0; // On Linux, use MSG_NOSIGNAL to request not to send SIGPIPE on // errors on stream oriented sockets when the other end breaks // the connection. The EPIPE error is still returned. // Note that neither trapping the SIGPIPE signal via an // ACE_Event_Handler nor calling ACE_OS::signal(SIGPIPE, SIG_IGN) // seems to work. if ( blocking ) { res = stream.send_n(buffer, size, MG_MSG_NOSIGNAL); } else { res = stream.send(buffer, size, MG_MSG_NOSIGNAL); } // check for failure if ( res >= 0 ) { // update out parameter if ( bytesWritten != NULL ) *bytesWritten = res; if ( res == (ssize_t)size ) { stat = MgStreamHelper::mssDone; } else { stat = blocking ? MgStreamHelper::mssError : MgStreamHelper::mssNotDone; } } } return stat; }
void JAWS_Synch_IO::receive_file (JAWS_IO_Handler *ioh, const char *filename, void *initial_data, unsigned int initial_data_length, unsigned int entire_length) { ACE_Filecache_Handle handle (filename, (int) entire_length); int result = handle.error (); if (result == ACE_Filecache_Handle::ACE_SUCCESS) { ACE_SOCK_Stream stream; stream.set_handle (ioh->handle ()); int bytes_to_memcpy = ACE_MIN (entire_length, initial_data_length); ACE_OS::memcpy (handle.address (), initial_data, bytes_to_memcpy); int bytes_to_read = entire_length - bytes_to_memcpy; int bytes = stream.recv_n ((char *) handle.address () + initial_data_length, bytes_to_read); if (bytes == bytes_to_read) ioh->receive_file_complete (); else result = -1; } if (result != ACE_Filecache_Handle::ACE_SUCCESS) ioh->receive_file_error (result); }
void JAWS_Synch_IO_No_Cache::send_message (const char *buffer, int length) { ACE_SOCK_Stream stream; stream.set_handle (this->handle_); stream.send_n (buffer, length); }
void JAWS_Synch_IO::send_message (JAWS_IO_Handler *ioh, const char *buffer, unsigned int length) { ACE_SOCK_Stream stream; stream.set_handle (ioh->handle ()); stream.send_n (buffer, length); }
void JAWS_Synch_IO::transmit_file (const char *filename, const char *header, int header_size, const char *trailer, int trailer_size) { ACE_Filecache_Handle handle (ACE_TEXT_CHAR_TO_TCHAR (filename)); int result = handle.error (); if (result == ACE_Filecache_Handle::ACE_SUCCESS) { #if defined (ACE_JAWS_BASELINE) || defined (ACE_WIN32) ACE_SOCK_Stream stream; stream.set_handle (this->handle_); if ((stream.send_n (header, header_size) == header_size) && (stream.send_n (handle.address (), handle.size ()) == handle.size ()) && (stream.send_n (trailer, trailer_size) == trailer_size)) this->handler_->transmit_file_complete (); else result = -1; #else // Attempting to use writev // Is this faster? iovec iov[3]; int iovcnt = 0; if (header_size > 0) { iov[iovcnt].iov_base = const_cast<char*> (header); iov[iovcnt].iov_len = header_size; iovcnt++; } if (handle.size () > 0) { iov[iovcnt].iov_base = reinterpret_cast<char*> (handle.address ()); iov[iovcnt].iov_len = handle.size (); iovcnt++; } if (trailer_size > 0) { iov[iovcnt].iov_base = const_cast<char*> (trailer); iov[iovcnt].iov_len = trailer_size; iovcnt++; } if (ACE_OS::writev (this->handle_, iov, iovcnt) < 0) result = -1; else this->handler_->transmit_file_complete (); #endif /* ACE_JAWS_BASELINE */ } if (result != ACE_Filecache_Handle::ACE_SUCCESS) this->handler_->transmit_file_error (result); }
int ACE_SOCK_Acceptor::accept (ACE_SOCK_Stream &new_stream, ACE_Addr *remote_addr, ACE_Time_Value *timeout, int restart, int reset_new_handle) const { ACE_TRACE ("ACE_SOCK_Acceptor::accept"); int in_blocking_mode = 0; if (this->shared_accept_start (timeout, restart, in_blocking_mode) == -1) return -1; else { // On Win32 the third parameter to <accept> must be a NULL // pointer if we want to ignore the client's address. int *len_ptr = 0; sockaddr *addr = 0; int len = 0; if (remote_addr != 0) { len = remote_addr->get_size (); len_ptr = &len; addr = (sockaddr *) remote_addr->get_addr (); } do new_stream.set_handle (ACE_OS::accept (this->get_handle (), addr, len_ptr)); while (new_stream.get_handle () == ACE_INVALID_HANDLE && restart != 0 && errno == EINTR && timeout == 0); // Reset the size of the addr, so the proper UNIX/IPv4/IPv6 family // is known. if (new_stream.get_handle () != ACE_INVALID_HANDLE && remote_addr != 0) { remote_addr->set_size (len); if (addr) remote_addr->set_type (addr->sa_family); } } return this->shared_accept_finish (new_stream, in_blocking_mode, reset_new_handle); }
int ACE_SOCK_Acceptor::accept (ACE_SOCK_Stream &new_stream, ACE_Accept_QoS_Params qos_params, ACE_Addr *remote_addr, ACE_Time_Value *timeout, int restart, int reset_new_handle) const { ACE_TRACE ("ACE_SOCK_Acceptor::accept"); int in_blocking_mode = 0; if (this->shared_accept_start (timeout, restart, in_blocking_mode) == -1) return -1; else { // On Win32 the third parameter to <accept> must be a NULL // pointer if we want to ignore the client's address. int *len_ptr = 0; int len = 0; sockaddr *addr = 0; if (remote_addr != 0) { len = remote_addr->get_size (); len_ptr = &len; addr = (sockaddr *) remote_addr->get_addr (); } do new_stream.set_handle (ACE_OS::accept (this->get_handle (), addr, len_ptr, qos_params)); while (new_stream.get_handle () == ACE_INVALID_HANDLE && restart != 0 && errno == EINTR && timeout == 0); // Reset the size of the addr, which is only necessary for UNIX // domain sockets. if (new_stream.get_handle () != ACE_INVALID_HANDLE && remote_addr != 0) remote_addr->set_size (len); } return this->shared_accept_finish (new_stream, in_blocking_mode, reset_new_handle); }
void JAWS_Synch_IO::transmit_file (JAWS_IO_Handler *ioh, ACE_HANDLE handle, const char *header, unsigned int header_size, const char *trailer, unsigned int trailer_size) { int result = 0; if (handle != ACE_INVALID_HANDLE) { ACE_SOCK_Stream stream; stream.set_handle (ioh->handle ()); if ((unsigned long) stream.send_n (header, header_size) < header_size) { result = -1; } else { int count; char buf[BUFSIZ]; do { count = ACE_OS::read (handle, buf, sizeof (buf)); if (count <= 0) break; if (stream.send_n (buf, count) < count) { result = -1; } } while (result == 0); if ((unsigned long) stream.send_n (trailer, trailer_size) < trailer_size) { result = -1; } } } if (result == 0) ioh->transmit_file_complete (); else ioh->transmit_file_error (result); }
void JAWS_Synch_IO_No_Cache::read (ACE_Message_Block &mb, int size) { ACE_SOCK_Stream stream; stream.set_handle (this->handle_); int result = stream.recv (mb.wr_ptr (), size); if (result <= 0) this->handler_->read_error (); else { mb.wr_ptr (result); this->handler_->read_complete (mb); } }
void JAWS_Synch_IO::read (JAWS_IO_Handler *ioh, ACE_Message_Block *mb, unsigned int size) { JAWS_TRACE ("JAWS_Synch_IO::read"); ACE_SOCK_Stream stream; stream.set_handle (ioh->handle ()); int result = stream.recv (mb->wr_ptr (), size); if (result <= 0) ioh->read_error (); else { JAWS_TRACE ("JAWS_Synch_IO::read success"); mb->wr_ptr (result); ioh->read_complete (mb); } }
void JAWS_Synch_IO_No_Cache::transmit_file (const char *filename, const char *header, int header_size, const char *trailer, int trailer_size) { int result = 0; // Can we access the file? if (ACE_OS::access (filename, R_OK) == -1) { //ugly hack to send in HTTP_Status_Code::STATUS_NOT_FOUND result = ACE_Filecache_Handle::ACE_ACCESS_FAILED; this->handler_->transmit_file_error (result); return; } ACE_stat stat; // Can we stat the file? if (ACE_OS::stat (filename, &stat) == -1) { //ugly hack to send HTTP_Status_Code::STATUS_FORBIDDEN result = ACE_Filecache_Handle::ACE_STAT_FAILED; this->handler_->transmit_file_error (result); return; } ACE_OFF_T size = stat.st_size; // Can we open the file? ACE_HANDLE handle = ACE_OS::open (filename, O_RDONLY); if (handle == ACE_INVALID_HANDLE) { //ugly hack to send HTTP_Status_Code::STATUS_FORBIDDEN result = ACE_Filecache_Handle::ACE_OPEN_FAILED; this->handler_->transmit_file_error (result); return; } char* f = new char[size]; ACE_Auto_Basic_Array_Ptr<char> file (f); ACE_OS::read_n (handle, f, size); ACE_SOCK_Stream stream; stream.set_handle (this->handle_); if ((stream.send_n (header, header_size) == header_size) && (stream.send_n (f, size) == size) && (stream.send_n (trailer, trailer_size) == trailer_size)) { this->handler_->transmit_file_complete (); } else { //ugly hack to default to HTTP_Status_Code::STATUS_INTERNAL_SERVER_ERROR result = -1; this->handler_->transmit_file_error (result); } ACE_OS::close (handle); }
int DC_Service_Request::do_request(KSG_WORK_SVR_HANDLER *handle) { ACE_Message_Block *mblk = handle->mblk_; ACE_SOCK_Stream peer; ACE_Message_Block *resp_buf; unsigned char *msg_begin = (unsigned char*)mblk->rd_ptr(); unsigned char *out_buf; unsigned char crc_code[4]; int data_len = mblk->length(); short pack_len; int len; int ret; peer.set_handle(handle->handle_); ACE_HEX_DUMP((LM_DEBUG,mblk->rd_ptr(),mblk->length())); if(msg_begin[0]!=0xC0 && msg_begin[data_len]!=0xC1) { ACE_DEBUG((LM_ERROR,"收到数据包起始符错误...")); return -1; } BUF_2_SHORT_BE(pack_len,(msg_begin+1)); if(data_len - 3 < pack_len ) { ACE_DEBUG((LM_ERROR,"收到错误数据包长度错误...")); return -1; } // check crc /* pack_len = GenerateCRC16(msg_begin+3,data_len-3-3); SHORT_2_BUF_BE(pack_len,crc_code); if(memcmp(crc_code,msg_begin+data_len-3,2)!=0) { ACE_DEBUG((LM_ERROR,"收到数据包CRC校验错误...")); return 0; } */ if(calc_sum(msg_begin+3,data_len-3-2)!=msg_begin[data_len-2]) { ACE_DEBUG((LM_ERROR,"收到数据包CRC校验错误...")); return 0; } ACE_NEW_RETURN(resp_buf,ACE_Message_Block(128),-1); len = 0; out_buf = (unsigned char*)resp_buf->wr_ptr(); out_buf[0]=0xC2; out_buf[3]=msg_begin[3]; switch(msg_begin[3]) { case 0x70: ret = do_upload_serial(msg_begin,data_len,out_buf+4,len); break; case 0x71: ret = do_download_blkcard(msg_begin,data_len,out_buf+4,len); break; default: ret = -1; break; } if(ret == 1) { if(len > 0) { // 计算CRC out_buf[4+len]=calc_sum(out_buf+3,len+1); len+=5; out_buf[len++] = 0xC3; pack_len = len - 3; SHORT_2_BUF_BE(pack_len,(out_buf+1)); resp_buf->wr_ptr(len); ACE_HEX_DUMP((LM_DEBUG,resp_buf->rd_ptr(),resp_buf->length())); ACE_Time_Value tv(0); if(peer.send_n(resp_buf,&tv) <=0 ) { ACE_DEBUG((LM_ERROR,"发送应答包失败")); ret = -1; } else { ret = 1; } } else ret = 0; } resp_buf->release(); return ret; }
void JAWS_Synch_IO::transmit_file (JAWS_IO_Handler *ioh, const char *filename, const char *header, unsigned int header_size, const char *trailer, unsigned int trailer_size) { int result = 0; if (filename == 0) { ioh->transmit_file_error (-1); return; } JAWS_Cached_FILE cf (filename); if (cf.file ()->get_handle () != ACE_INVALID_HANDLE && cf.mmap () != 0) { #if defined (ACE_JAWS_BASELINE) || defined (ACE_WIN32) ACE_FILE_Info info; cf.file ()->get_info (info); if (cf.file ()->get_info (info) == 0 && info.size_ > 0) { ACE_SOCK_Stream stream; stream.set_handle (ioh->handle ()); if (((u_long) stream.send_n (header, header_size) == header_size) && (stream.send_n (cf.mmap ()->addr (), info.size_) == info.size_) && ((u_long) stream.send_n (trailer, trailer_size) == trailer_size)) { ioh->transmit_file_complete (); return; } else { result = -1; } } else { result = -1; } #else // Attempting to use writev // Is this faster? iovec iov[3]; int iovcnt = 0; if (header_size > 0) { iov[iovcnt].iov_base = const_cast<char*> (header); iov[iovcnt].iov_len = header_size; iovcnt++; } ACE_FILE_Info info; if (cf.file ()->get_info (info) == 0 && info.size_ > 0) { iov[iovcnt].iov_base = (char *) cf.mmap ()->addr (); iov[iovcnt].iov_len = info.size_; iovcnt++; } if (trailer_size > 0) { iov[iovcnt].iov_base = const_cast<char*> (trailer); iov[iovcnt].iov_len = trailer_size; iovcnt++; } if (ACE_OS::writev (ioh->handle (), iov, iovcnt) < 0) { result = -1; } else { ioh->transmit_file_complete (); return; } #endif /* ACE_JAWS_BASELINE */ } else if (cf.file ()->get_handle () != ACE_INVALID_HANDLE && cf.mmap () == 0) { this->transmit_file (ioh, cf.file ()->get_handle (), header, header_size, trailer, trailer_size); return; } else { result = -1; } if (result != 0) { ioh->transmit_file_error (result); } }
/////////////////////////////////////////////////////////////////////////// // <summary> // This method reads data from the stream into the given buffer. The // parameters control whether or not the read blocks, whether or not, // the caller wants to peek at the data, and if the caller wants to // know how many bytes had been read. // </summary> // // <param name = "buffer"> // The buffer that will receive the data read from the stream. // </param> // // <param name = "size"> // The size of the buffer in bytes of the buffer. // </param> // // <param name = "blocking"> // True if the read request should block; false otherwise. // </param> // // <param name = "peeking"> // True if the read request should not consume the data; false // otherwise. // </param> // // <param name = "bytesAvailable"> // An out parameter that will contain the number of bytes that have been // read from the stream. It will contain -1 if there was an error. // </param> // // <returns> // Returns a MgStreamStatus value indicating the status of the operation. // </returns> MgStreamHelper::MgStreamStatus MgAceStreamHelper::GetData(void* buffer, size_t size, bool blocking, bool peeking) { // Do not attempt reading zero byte from the socket as this could be problematic. if (0 == size) { return MgStreamHelper::mssDone; } ACE_ASSERT( size > 0 ); MgStreamHelper::MgStreamStatus stat = MgStreamHelper::mssError; // Is our internal buffer big enough? If not, expand it. if ( m_readBufSize < size ) { m_readBufSize = size; UINT8* temp = new UINT8[m_readBufSize]; memcpy( temp, &m_readBuffer[m_readBufStart], m_readBufEnd - m_readBufStart ); delete[] m_readBuffer; m_readBuffer = temp; m_readBufEnd -= m_readBufStart; m_readBufStart = 0; } // check if requested data is already in buffer stat = UpdateReadBuffers( buffer, size, peeking ); if ( MgStreamHelper::mssDone != stat ) { // We do not have enough data and will need to read. Shift buffer back // and attempt to fill the entire buffer with a non-blocking read first memmove(m_readBuffer, &m_readBuffer[m_readBufStart], m_readBufEnd-m_readBufStart); m_readBufEnd -= m_readBufStart; m_readBufStart = 0; ACE_SOCK_Stream stream; stream.set_handle( m_handle ); // Windows has a timing problem. If trying to receive data too fast, // it will fail. So, use a timeout to let it catch up. // This workaround reduces the number of lockups significantly and // eliminates the hanging problem when it takes so long to write a // request to the socket. const ACE_Time_Value timeout(60); // On Linux, use MSG_NOSIGNAL to turn off raising of SIGPIPE on // stream sockets when the other end disappears. // Note that neither trapping the SIGPIPE signal via an // ACE_Event_Handler nor calling ACE_OS::signal(SIGPIPE, SIG_IGN) // seems to work. ssize_t res = stream.recv(&m_readBuffer[m_readBufEnd], m_readBufSize - m_readBufEnd, MG_MSG_NOSIGNAL, &timeout); if ( res < 0 ) { // Check this return value to determine if the socket is closed or // if there was simply no data. #ifdef _WIN32 int error = ::WSAGetLastError(); // errno doesn't work correctly on Windows bool bConnected = ( error == WSAEWOULDBLOCK || error == 0 ); #else bool bConnected = ( errno == EWOULDBLOCK || errno == 0 || errno == ETIME ); #endif stat = ( bConnected ) ? MgStreamHelper::mssNotDone : MgStreamHelper::mssError; } else if (res == 0) { // No longer connected stat = MgStreamHelper::mssError; } else { m_readBufEnd += res; // Now do we have enough data? stat = UpdateReadBuffers( buffer, size, peeking ); } if (MgStreamHelper::mssNotDone == stat && blocking) { // Still not enough data. Have to block and fill only what was asked for. res = stream.recv_n(&m_readBuffer[m_readBufEnd], size - (m_readBufEnd-m_readBufStart), MG_MSG_NOSIGNAL); if ( res < 0 ) { // Check this return value to determine if the socket is closed or // if there was simply no data. #ifdef _WIN32 int error = ::WSAGetLastError(); // errno doesn't work correctly on Windows bool bConnected = ( error == WSAEWOULDBLOCK || error == 0 ); #else bool bConnected = ( errno == EWOULDBLOCK || errno == 0 || errno == ETIME ); #endif stat = ( bConnected ) ? MgStreamHelper::mssNotDone : MgStreamHelper::mssError; } else if (res == 0) { // No longer connected stat = MgStreamHelper::mssError; } else { m_readBufEnd += res; // Now we better have enough data... stat = UpdateReadBuffers( buffer, size, peeking ); } } } return stat; }
/*the accept function*/ static ACE_THR_FUNC_RETURN accept_step1(void *arg) { /*ACE_INET_Addr addr;*/ ACE_SOCK_Stream stream; ACE_HANDLE handle = (ACE_HANDLE)(intptr_t) arg; stream.set_handle(handle); if(stream.disable(ACE_NONBLOCK) == -1){ ACE_ERROR_RETURN((LM_ERROR, "%p\n","get_remote_addr"),0); } /* ACE_DEBUG ((LM_INFO, "(%P|%t) client %s connected from %d\n", addr.get_host_name (), addr.get_port_number ())); */ char* buf = new char[128]; ACE_CString* str = new ACE_CString(); do{ int bytes= stream.recv(buf,128); ACE_DEBUG((LM_INFO, "(%P|%t:%l) bytes = %d\n",bytes)); if(bytes == -1|| bytes == 0){ break; } for(int i=0 ;i < bytes; i++){ *str += buf[i]; } }while(true); delete[] buf; //the input format is '^^pqr->v1$$'; int pos = str->find("->"); int tail = str->find("$$"); ACE_CString* pqr = new ACE_CString(str->substr(2,pos-2)); ACE_CString* pv1 = new ACE_CString(str->substr(pos+2, tail - pos - 2)); ACE_DEBUG((LM_INFO, "(%P|%t:%l) pqr: %s\n pv1:%s\n",pqr->c_str(),pv1->c_str())); bn* _pqr = from_hex(pqr); bn* _v1 = from_hex(pv1); bn* _pr = from_hex(&pr); bn* _r = npmod( _v1, _pr, _pqr); ACE_CString* result = _r->to_hex(); ACE_DEBUG((LM_INFO, "(%P|%t:%l)pqr:%s step1:%s ", pqr->c_str(), result->c_str())); ACE_CString reply = ACE_CString("ack"); stream.send(reply.c_str() , reply.length()); stream.close(); /*send the step1 result to hub:10007 */ ACE_SOCK_Connector connector; ACE_INET_Addr hub_addr(port,hub.c_str()); ACE_DEBUG((LM_DEBUG, "(%P|%t:%l) port:%d host:%s\n", port, hub.c_str())); if(connector.connect(stream, hub_addr) == -1){ ACE_ERROR_RETURN ((LM_ERROR, "(%P|%t) %p\n", "connection failed"), 0); } else ACE_DEBUG ((LM_DEBUG, "(%P|%t) connected to %s at port %d\n", hub_addr.get_host_name (), hub_addr.get_port_number ())); /* * message layout: ^^pqr->digest->senderid$$ */ ACE_CString input = ACE_CString("^^"); input += *pqr; input += "->"; input += *result; input += "->"; input += id ; input += "$$"; ACE_DEBUG((LM_INFO, "(%P|%t:%l) input of step1:%s\n", input.c_str())); if(stream.send(input.c_str(),input.length()) != input.length()){ ACE_ERROR((LM_ERROR, "%p\n","send")); } stream.close(); delete str; delete pqr; delete pv1; delete _pqr; delete _v1; delete _pr; delete _r; delete result; return 0; }
// receive the heartbeat information, and return back the enquened messages; static ACE_THR_FUNC_RETURN commu(void* arg){ ACE_INET_Addr addr; ACE_SOCK_Stream stream; ACE_HANDLE handle =(ACE_HANDLE)(intptr_t) arg; stream.set_handle(handle); if(stream.disable(ACE_NONBLOCK) == -1){ ACE_ERROR_RETURN((LM_ERROR, "%p\n","disable"),0); } else if(stream.get_remote_addr(addr)== -1){ ACE_ERROR_RETURN((LM_ERROR, "%p\n","get_remote_addr"),0); } ACE_DEBUG((LM_INFO, "(%P|%t) client %s connected from %d\n", addr.get_host_name(),addr.get_port_number())); ACE_CString str ; char* ch = new char[128]; do{ int bytes = stream.recv(ch, 128); if(bytes == -1){ ACE_ERROR((LM_ERROR, "%p\n","recv")); break; } if(bytes == 0){ ACE_DEBUG((LM_INFO, "(%P|%t) reached end of input, connection closed by client\n")); break; } for(int i = 0; i< bytes; i++){ str += ch[i]; } }while(true); delete[] ch; ACE_DEBUG((LM_INFO, "received message:%s\n", str.c_str())); /* the layout of the heartbeat message: ^^hb->senderid$$ */ /*if got a heartbeat message*/ int pos = str.find("^^hb->"); if( pos >= 0 ){ int p2 = str.find("$$"); ACE_CString id= str.substr(6, p2 -6); // delete str; ACE_CString sql = "select pqr, v2,txn_id from step2 where recipient='"+ id +"' and transmitted='false' "; ACE_DEBUG((LM_DEBUG, "%s\n", sql.c_str())); PGconn* con; PGresult* res; con = PQconnectdb("dbname=pq"); if(PQstatus(con)!= CONNECTION_OK){ ACE_DEBUG((LM_INFO, "Connection to database failed:%s\n", PQerrorMessage(con))); reclaim_conn(con); } res = PQexec(con, sql.c_str()); int n = PQntuples(res); if(n == 0){ /*no pending messages at all, exit immediately*/ ACE_DEBUG((LM_INFO, "(%P|%t) no pending messages at all\n")); PQclear(res); reclaim_conn(con); stream.close(); // delete str; return 0; } /*there are pending messages*/ else{ /* the reply message is in format "^^pqr1->v1->txn_id1||pqr2->v2->txn_id2||pqr3->v3->txn_id3||$$"*/ ACE_CString reply = ACE_CString("^^"); for(int i=0; i < n ; i++){ reply += PQgetvalue(res, i, 0); reply += "->"; reply += PQgetvalue(res, i, 1); reply += "->"; reply += PQgetvalue(res, i, 2); reply += "||"; } reply += "$$"; PQclear(res); /* reclaim_conn(con); */ stream.send(reply.c_str(), reply.length()); ACE_DEBUG((LM_INFO, "(%P|%t:%l) %s\n", reply.c_str())); ACE_DEBUG((LM_INFO, "(%P|%t) close the writer\n")); stream.close(); // delete str; return 0; } } /*if got an ack message '^^ack->txn_id2||ack->txn_id2||$$' */ int p = str.find("^^ack->"); if( p >= 0){ PGconn* con; PGresult* res; con = PQconnectdb("dbname=pq"); if(PQstatus(con)!= CONNECTION_OK){ ACE_DEBUG((LM_INFO, "Connection to database failed:%s\n", PQerrorMessage(con))); reclaim_conn(con); } do{ p += 7; int p2 = str.find("||",p); if(p2< 0){ ACE_DEBUG((LM_INFO, "reached the end of the txn_ids\n")); break; } ACE_CString txn_id = str.substr(pos, p2 - p); ACE_CString sql = ACE_CString("update step2 set transmitted=TRUE where txn_id='"); sql += txn_id; sql += "'"; ACE_DEBUG((LM_INFO, "(%P|%t:%l) sql:%s\n" , sql.c_str())); res = PQexec(con, sql.c_str()); PQclear(res); p = p2; }while(true); reclaim_conn(con); stream.close(); // delete str; return 0; } return 0; }
// sets up the dataModeSocket Stream, reads the test header infomation // and launches a thread to handle the requested test. static void run_server (ACE_HANDLE handle) { ACE_INET_Addr cli_addr; // create a new stream and initialized with the handle returned by // accept ACE_SOCK_Stream * dataModeStream = new ACE_SOCK_Stream; dataModeStream->set_handle (handle); // Make sure we're not in non-blocking mode. if (dataModeStream->disable (ACE_NONBLOCK) == -1){ ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("disable"))); return; } else if (dataModeStream->get_remote_addr (cli_addr) == -1){ ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("get_remote_addr"))); return; } // explicity configure Nagling. Default is // Options_Manager::test_enable_nagle=0 so default configurations is // NO NAGLING ACE_CDR::Long nagle; if (Options_Manager::test_enable_nagle) nagle=0; else nagle=1; if (Options_Manager::test_transport_protocol == IPPROTO_SCTP){ // default - sctp case if (-1 == dataModeStream->set_option(IPPROTO_SCTP, SCTP_NODELAY, &nagle, sizeof nagle)){ ACE_ERROR((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("set_option"))); return; } } else { // tcp case if (-1 == dataModeStream->set_option(IPPROTO_TCP, TCP_NODELAY, &nagle, sizeof nagle)){ ACE_ERROR ((LM_ERROR, "%p\n", "set_option")); return; } } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) client %C connected from %d\n"), cli_addr.get_host_name (), cli_addr.get_port_number ())); // hdr bufSize is hardcoded to 8 bytes // (4 for a CDR-encoded boolean and 4 for a CDR-encoded ULong) ACE_CDR::ULong hdrBufSize = 8; // allocate a raw buffer large enough to receive the header and be // properly aligned for the CDR decoding. ACE_CDR::Char * hdrBuf= new ACE_CDR::Char[hdrBufSize+ACE_CDR::MAX_ALIGNMENT]; // align the raw buffer before reading data into it. char * hdrBuf_a = ACE_ptr_align_binary(hdrBuf, ACE_CDR::MAX_ALIGNMENT); size_t bt; // read the header if ((dataModeStream->recv_n(hdrBuf_a, hdrBufSize, 0, &bt)) == -1){ ACE_ERROR ((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("recv_n"))); return; } // pass the CDR encoded data into an ACE_InputCDR class. hdrCDR does // NOT copy this data. Nor does it delete. It assumes the buffer // remains valid while it is in scope. ACE_InputCDR hdrCDR(hdrBuf_a, hdrBufSize); ACE_CDR::Boolean byteOrder; ACE_CDR::ULong numIterations; // extract the data hdrCDR >> ACE_InputCDR::to_boolean (byteOrder); hdrCDR.reset_byte_order(byteOrder); hdrCDR >> numIterations; // make sure the stream is good after the extractions if (!hdrCDR.good_bit()){ ACE_ERROR((LM_ERROR, ACE_TEXT ("%p\n"), ACE_TEXT ("hdrCDR"))); return; } ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) Test for %u iterations\n"), numIterations)); // deallocate the header buffer delete[] hdrBuf; // bundle up the arguments ArgStruct * args = new ArgStruct; args->stream = dataModeStream; args->numIters = numIterations; #if defined (ACE_HAS_THREADS) // Spawn a new thread and run the new connection in that thread of // control using the <server> function as the entry point. if (ACE_Thread_Manager::instance ()->spawn (unmarshalledOctetServer, reinterpret_cast<void *> (args), THR_DETACHED) == -1) ACE_ERROR ((LM_ERROR, ACE_TEXT ("(%P|%t) %p\n"), ACE_TEXT ("spawn"))); #else (*unmarshalledOctetServer) (reinterpret_cast<void *> (args)); #endif /* ACE_HAS_THREADS */ }
static ACE_THR_FUNC_RETURN process(void* arg){ ACE_INET_Addr addr; ACE_SOCK_Stream stream; ACE_HANDLE handle = (ACE_HANDLE) (intptr_t) arg; stream.set_handle(handle); /*make sure we're not in non-blocking mode.*/ if(stream.disable(ACE_NONBLOCK) == -1){ ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "disable"), 0); } else if(stream.get_remote_addr(addr) == -1){ ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "get_remote_addr"), 0); } ACE_DEBUG ((LM_INFO, "(%P|%t:%l) client %s connected from %d\n", addr.get_host_name (), addr.get_port_number ())); int r_bytes = 0; char buf[SIZE]; ACE_CString cs; do{ r_bytes = stream.recv(buf, SIZE); if(r_bytes == 0 || r_bytes == -1){ ACE_DEBUG((LM_INFO, "(%P|%t:%l) r_bytes = %d, exit from the loop\n", r_bytes)); break; } for(int i=0; i< r_bytes; i++){ cs += buf[i]; } }while(true); stream.close_reader(); /* ACE_DEBUG((LM_INFO, "%s\n", cs.c_str())); */ /*the layout of the message would be: * ^^pq||step1$$ * 1st step: get the d by pq * 2nd calculate * 3rd send back the digest */ int p0, p1; int len = cs.length(); p0 = 2; p1 = cs.find("||"); ACE_CString pq = cs.substr(2, p1 - 2); ACE_CString step1 = cs.substr(p1 + 2, len - p1 -4); /* ACE_DEBUG((LM_INFO, "pq = %s\n step1 = %s\n", pq.c_str(), step1.c_str())); */ //get the d ACE_CString sql = "select d,textid from player0 where pq='"; sql += pq; sql += "'"; /* ACE_DEBUG((LM_INFO, "sql = %s\n", sql.c_str())); */ PGconn* con; con = PQconnectdb("host=45.33.3.188 port=5432 dbname=nv user=dec"); PGresult* res; if(PQstatus(con)!= CONNECTION_OK){ ACE_DEBUG((LM_INFO, "Connection to database failed:%s\n", PQerrorMessage(con))); reclaim_conn(con); } res = PQexec(con, sql.c_str()); int n = PQntuples(res); if(n != 1){ ACE_ERROR((LM_ERROR, "there is significant error: %d\n", n)); // return 0; } ACE_CString d = ""; d += PQgetvalue(res, 0, 0); /* ACE_DEBUG((LM_INFO, "d = %s\n", d.c_str())); */ bn* pq_ = from_hex(&pq); bn* d_ = from_hex(&d); bn* step1_ = from_hex(&step1); bn* step2_ = npmod(step1_ , d_ , pq_ ); ACE_CString* step2 = step2_->to_hex(); //check if the pq is taking the ownnership? /* if pq is 'centralbank', bypass the check, otherwise check the payer whether has the ownnership of the note; * select count(*) from ownership0 o, player0 p where o.owner = p.textid and o.note='0x12345678' and p.pq='0x12345678'; */ bn* e_ = new bn(1); e_->addat(0,0x10001); bn* step3_ = npmod(step2_ , e_ , pq_ ); ACE_CString* rawMsg = encode(step3_); ACE_DEBUG((LM_INFO, "%T :%l step3 = %s\n", rawMsg->c_str())); if(verify_ownership(rawMsg, pq)){ //update the ownership; int pos1 = rawMsg->find("->"); ACE_CString note = rawMsg->substr(2, pos1 -2); int rawlen = rawMsg->length(); ACE_CString id = rawMsg->substr(pos1 + 2, rawlen - pos1 - 6); update_ownership(note, id); /*insert the log entry*/ insert_logentry(pq, *step2, *rawMsg, note, id); stream.send( step2->c_str(), step2->length()); /* ACE_DEBUG((LM_INFO, "%T :%l the step2 message is:\n%s\n", step2->c_str())); */ }else{ ACE_DEBUG((LM_INFO, "%T :%l invalid transfer\n")); ACE_CString reply ="invalid transfer\n"; stream.send( reply.c_str(), reply.length()); } delete step2 ; delete pq_; delete d_; delete step1_; delete step2_; delete e_; delete step3_; delete rawMsg; /* stream.close_writer(); */ stream.close(); ACE_DEBUG((LM_INFO, "%T :%l closed the stream\n")); }