OSS::IPAddress SIPWebSocketConnection::getRemoteAddress() const /// Returns the last read source address { if (_lastReadAddress.isValid()) return _lastReadAddress; if (_pServerConnection) { boost::system::error_code ec; EndPoint ep = _pServerConnection->get_raw_socket().remote_endpoint(ec); if (!ec) { boost::asio::ip::address ip = ep.address(); _lastReadAddress = OSS::IPAddress(ip.to_string(), ep.port()); return _lastReadAddress; } else { OSS_LOG_WARNING("SIPWebSocketConnection::getRemoteAddress() Exception " << ec.message()); return _connectAddress; } } return OSS::IPAddress(); }
void run() { GLock<1> lock; std::string msg; lock.lock(); BQueue<std::string>* pBQ = _pMsgHandler->getQueue(); ICommunicator* pComm = _pMsgHandler->getCommunicator(); EndPoint remoteEp = _pMsgHandler->getEndPoint(); lock.unlock(); /////////////////////////////////////////////////////// // insert your server processing here while(true) { sout << locker << "\n receiver processing message: " << (msg = pBQ->deQ()).c_str() << unlocker; lock.lock(); EndPoint remoteEp = _pMsgHandler->getEndPoint(); if(pComm->connect(remoteEp.getIP(), remoteEp.getPort())) { pComm->postMessage(std::string("got message")); pComm->disconnect(); } else sout << "\n failed to connect"; lock.unlock(); if(msg == "quit") break; } // end of your code /////////////////////////////////////////////////////// }
bool NetworkServer::ProcessNewUDPConnectionAttempt(Socket *listenSocket, const EndPoint &endPoint, const char *data, size_t numBytes) { LOG(LogInfo, "New inbound connection attempt from %s with datagram of size %d.", endPoint.ToString().c_str(), (int)numBytes); if (!acceptNewConnections) { LOG(LogError, "Ignored a new connection attempt since server is set not to accept new connections."); return false; } // Pass the datagram contents to a callback that decides whether this connection is allowed. if (networkServerListener) { bool connectionAccepted = networkServerListener->NewConnectionAttempt(endPoint, data, numBytes); if (!connectionAccepted) { LOG(LogError, "Server listener did not accept the new connection."); return false; } } ///\todo Check IP banlist. ///\todo Check that the maximum number of active concurrent connections is not exceeded. std::string remoteHostName = endPoint.IPToString(); // Accept the connection and create a new UDP socket that communicates to that endpoint. Socket *socket = owner->CreateUDPSlaveSocket(listenSocket, endPoint, remoteHostName.c_str()); if (!socket) { LOG(LogError, "Network::ConnectUDP failed! Cannot accept new UDP connection."); return false; } UDPMessageConnection *udpConnection = new UDPMessageConnection(owner, this, socket, ConnectionOK); Ptr(MessageConnection) connection(udpConnection); { PolledTimer timer; Lockable<ConnectionMap>::LockType clientsLock = clients.Acquire(); (*clientsLock)[endPoint] = connection; LOG(LogWaits, "NetworkServer::ProcessNewUDPConnectionAttempt: Accessing the connection list took %f msecs.", timer.MSecsElapsed()); } // Pass the MessageConnection to the main application so it can hook the inbound packet stream. if (networkServerListener) networkServerListener->NewConnectionEstablished(connection); connection->SendPingRequestMessage(false); owner->AssignConnectionToWorkerThread(connection); owner->NewMessageConnectionCreated(connection); LOG(LogInfo, "Accepted new UDP connection."); return true; }
void Socket::BindEndPoint(const EndPoint& endpoint) { if(::bind(_sockfd,Socket::sockaddr_cast(&endpoint.GetInternalAddr()), static_cast<socklen_t>(sizeof(endpoint.GetInternalAddr()))) < 0) { int saveErr = errno; throw exceptions::ApiExecError("bind", saveErr); } }
bool UDPPacketReceiver::processRecv(bool expectingPacket) { Address srcAddr; UDPPacket* pChannelReceiveWindow = CREATE_POOL_OBJECT(UDPPacket); int len = pChannelReceiveWindow->recvFromEndPoint(*m_pEndPoint, &srcAddr); if(len <= 0) { RELEASE_POOL_OBJECT(UDPPacket, pChannelReceiveWindow); PacketReceiver::RecvState rstate = this->checkSocketErrors(len, expectingPacket); return rstate == PacketReceiver::RECV_STATE_CONTINUE; } Channel* pSrcChannel = m_pNetworkInterface->findChannel(srcAddr); if(pSrcChannel == NULL) { EndPoint* pNewEndPoint = CREATE_POOL_OBJECT(EndPoint); pNewEndPoint->addr(srcAddr.m_port, srcAddr.m_ip); pSrcChannel = CREATE_POOL_OBJECT(Channel, m_pNetworkInterface, pNewEndPoint, nullptr, PROTOCOL_UDP); if (!pSrcChannel) { pSrcChannel->destroy(); RELEASE_POOL_OBJECT(Channel, pSrcChannel); RELEASE_POOL_OBJECT(UDPPacket, pChannelReceiveWindow); return false; } if(!m_pNetworkInterface->registerChannel(pSrcChannel)) { RELEASE_POOL_OBJECT(UDPPacket, pChannelReceiveWindow); pSrcChannel->destroy(); RELEASE_POOL_OBJECT(Channel, pSrcChannel); return false; } } SLASSERT(pSrcChannel != NULL, "wtf"); if(pSrcChannel->isCondemn()) { RELEASE_POOL_OBJECT(UDPPacket, pChannelReceiveWindow); m_pNetworkInterface->deregisterChannel(pSrcChannel); pSrcChannel->destroy(); RELEASE_POOL_OBJECT(Channel, pSrcChannel); return false; } Reason ret = this->processPacket(pSrcChannel, pChannelReceiveWindow); if(ret != REASON_SUCCESS) { } return true; }
virtual int operator()(EndPoint &serverep) { count = BUFSIZ; UseCntPtr<Address> peer(serverep.getInternalAddress().create()); assert(serverep.read(buf, count, *peer) >= 0); assert(serverep.write(buf, count, *peer) >= 0); return(0); }
void SocketUdp::Bind(const EndPoint& ep) { SOCKADDR_IN sin; if (!ep.getIp()) WSAHtonl(this->socket_, INADDR_ANY, &sin.sin_addr.s_addr); else sin.sin_addr.s_addr = inet_addr(ep.getIpStr().c_str()); sin.sin_family = AF_INET; WSAHtons(this->socket_, ep.getPort(), &sin.sin_port); if ((bind(this->socket_, reinterpret_cast<SOCKADDR*>(&sin), sizeof sin)) == SOCKET_ERROR) throw ErrorInit("Cannot bind the socket"); }
void NetworkServer::ReadUDPSocketData(Socket *listenSocket) // [worker thread] { using namespace std; assert(listenSocket); OverlappedTransferBuffer *recvData = listenSocket->BeginReceive(); if (!recvData) return; // No datagram available, return. if (recvData->bytesContains == 0) { listenSocket->EndReceive(recvData); LOG(LogError, "Received 0 bytes of data in NetworkServer::ReadUDPSocketData!"); return; } EndPoint endPoint = EndPoint::FromSockAddrIn(recvData->from); // This conversion is quite silly, perhaps it could be removed to gain performance? LOG(LogData, "Received a datagram of size %d to socket %s from endPoint %s.", recvData->bytesContains, listenSocket->ToString().c_str(), endPoint.ToString().c_str()); PolledTimer timer; MessageConnection *receiverConnection = 0; { Lockable<ConnectionMap>::LockType clientsLock = clients.Acquire(); if (timer.MSecsElapsed() > 50.f) { LOG(LogWaits, "NetworkServer::ReadUDPSocketData: Accessing the connection list in UDP server receive code took %f msecs.", timer.MSecsElapsed()); } ConnectionMap::iterator iter = clientsLock->find(endPoint); ///\todo HashTable for performance. if (iter != clientsLock->end()) receiverConnection = iter->second; } if (receiverConnection) { // If the datagram came from a known endpoint, pass it to the connection object that handles that endpoint. UDPMessageConnection *udpConnection = dynamic_cast<UDPMessageConnection *>(receiverConnection); if (udpConnection) udpConnection->QueueInboundDatagram(recvData->buffer.buf, recvData->bytesContains); else LOG(LogError, "Critical! UDP socket data received into a TCP socket!"); } else { // The endpoint for this datagram is not known, deserialize it as a new connection attempt packet. EnqueueNewUDPConnectionAttempt(listenSocket, endPoint, recvData->buffer.buf, recvData->bytesContains); } listenSocket->EndReceive(recvData); }
//------------------------------------------------------------------------------------- Reason NetworkInterface::basicSendSingleTry(Channel * pChannel, Packet * pPacket) { EndPoint * endpoint = pChannel->endpoint(); int len = endpoint->send(pPacket->data(), pPacket->totalSize()); if (len == (int)pPacket->totalSize()) { return REASON_SUCCESS; } else { return NetworkInterface::getSendErrorReason(endpoint, len, pPacket->totalSize()); } }
// Compares EndPoint ep with itself amd returns true, if they match // and false otherwise bool FilterEndPoint::matchesWithEndPoint (const EndPoint & ep, const short & netmask) { EndPoint tmp = ep; // apply the local netmask of the FilterEndPoint only, // if it is smaller than the global netmask // (otherwise, nothing would be changed) if ( nmask < netmask && nmask > 0 && nmask < 32) tmp.applyNetmask(nmask); // compare the members and watch out for wildcards if ( (tmp.getIpAddress() == ipAddr || nmask == 0) && (tmp.getPortNr() == portNr || portNr == -1) && (tmp.getProtocolID() == protocolID || protocolID == -1) ) return true; return false; }
ConnectionBasePtr TransferNode::createConnection(const PacketBasePtr &packet_base, const EndPoint &ep) { PacketHeader::PACKET_ID_TYPE packet_id = packet_base->header.getPacketID(); if (packet_id == OpenConnection_ID) { INFO_LOG("Server: new connection from: " << ep.toString()); Poco::SharedPtr<OpenConnectionPacket> packet = packet_base.cast<OpenConnectionPacket>(); assert(packet.get()); ConnectionBasePtr pConn(new ServerConnection(packet->OpenConnection.Code, ep, this->packet_serializer, *this)); return pConn; } else if (packet_id == OpenConnectionReply_ID) { INFO_LOG("Client: new connection to: " << ep.toString()); Poco::SharedPtr<OpenConnectionReplyPacket> packet = packet_base.cast<OpenConnectionReplyPacket>(); ConnectionBasePtr pConn(new ClientConnection(packet->OpenConnectionReply.Code, ep, this->packet_serializer, *this)); return pConn; } else { throw Poco::ApplicationException("unexpected packet type: ", packet_base->header.getPacketID()); // TODO @@@ ??? } }
virtual int operator()(EndPoint &clientep) { char buf[BUFSIZ+1]; size_t count = BUFSIZ; count = clientep.read(buf, count); if (count > 0) { if (clientep.write(buf, count) > 0) return(0); else return(-1); } else if (count == 0) return(1); else return(-1); }
//------------------------------------------------------------------------------------- int UDPPacket::recvFromEndPoint(EndPoint & ep, Address* pAddr) { int len = ep.recvfrom(data(), PACKET_MAX_SIZE_UDP, (u_int16_t*)&pAddr->port, (u_int32_t*)&pAddr->ip); KBE_ASSERT(rpos() == 0); wpos(len); return len; }
//------------------------------------------------------------------------------------- int TCPPacket::recvFromEndPoint(EndPoint & ep, Address* pAddr) { //KBE_ASSERT(MessageHandlers::pMainMessageHandlers != NULL && "Must set up a MainMessageHandlers!\n"); int len = ep.recv(data(), PACKET_MAX_SIZE_TCP * 4); KBE_ASSERT(rpos() == 0); wpos(len); // DEBUG_MSG("TCPPacket::recvFromEndPoint: datasize=%d, wpos=%d.\n", len, wpos()); return len; }
virtual int operator()(EndPoint &serverep) { count = BUFSIZ; UseCntPtr<Address> peer(serverep.getInternalAddress().create()); count = serverep.read(buf, count, *peer); if (count > 0) { if (serverep.write(buf, count, *peer) > 0) return(0); else return(-1); } else if (count < 0) return(-1); // error else return(1); // EOF -- all done }
virtual int operator()(EndPoint &serverep, Address &peer, void *buf, int count) { int status = serverep.write(buf, count, peer); if (status > 0) return(0); else if (status == 0) return(1); else return(-1); }
void ApiDispatcher::handle(RestRequest& request, RestResponse& response) { RestRequest::Method method = request.getMethod(); if (this->endpoints.count(method) > 0) { EndPoint * ep = this->endpoints[method]; try { ep->handle(request,response); } catch (NoSuchMethodHandlerException const & err) { LOG_INFO << LOGGER_PREFIX << err.what(); response.setStatus(STATUS_403_FORBIDDEN); } catch (ParsingContentException const & err) { response.setStatus(STATUS_400_BAD_REQUEST); } } else { LOG_INFO << LOGGER_PREFIX << "Not Allowed Method on " << request.getUri(); response.setStatus(STATUS_405_METHOD_NOT_ALLOWED); } }
void DNSServer::sendreply(const EndPoint& ep, const dnsreq& response) { StringBuilder sb; create_dns_packet(response, sb); boost::shared_ptr<EndPoint> ep1 = boost::shared_ptr<EndPoint>( EndPoint::CreateNull(ep.AddressFamily)); ep.Clone(*ep1.get()); q.Append( { ep1, sb.ToBuffer() }); q.start(); }
void printChannels() { printf("Channels:\n"); for (Channel::Iterator it = ep.channels(); it.hasNext(); ) { Channel ch = it.next(); printf(" %s", ch.address().toString().c_str()); if (ch.host().isValid()) printf(" - %s", ch.host().keyStr().c_str()); printf("\n"); } }
void printHosts() { printf("Hosts:\n"); for (Host::Iterator it = ep.hosts(); it.hasNext(); ) { Host h = it.next(); printf(" %s", h.keyStr().c_str()); Address addr = h.address(); if (addr.isValid()) printf(" - %s", addr.toString().c_str()); printf("\n"); } }
std::string Socket::ToString() const { sockaddr_in addr; socklen_t namelen = sizeof(addr); int peerRet = getpeername(connectSocket, (sockaddr*)&addr, &namelen); // Note: This works only if family==INETv4 EndPoint peerName = EndPoint::FromSockAddrIn(addr); int sockRet = getsockname(connectSocket, (sockaddr*)&addr, &namelen); // Note: This works only if family==INETv4 EndPoint sockName = EndPoint::FromSockAddrIn(addr); char str[256]; sprintf(str, "%s:%d (%s, connected=%s, readOpen: %s, writeOpen: %s, maxSendSize=%d, sock: %s, peer: %s, socket: %d, this: %p)", DestinationAddress(), (int)DestinationPort(), (transport == SocketOverTCP) ? "TCP" : (IsUDPServerSocket() ? "UDP server" : (IsUDPSlaveSocket() ? "UDP Slave" : "UDP")), Connected() ? "true" : "false", readOpen ? "true" : "false", writeOpen ? "true" : "false", (int)maxSendSize, sockRet == 0 ? sockName.ToString().c_str() : "(-)", peerRet == 0 ? peerName.ToString().c_str() : "(-)", (int)connectSocket, this); return std::string(str); }
Socket *NetworkServer::AcceptConnections(Socket *listenSocket) { if (!listenSocket || !listenSocket->Connected()) return 0; sockaddr_in remoteAddress; memset(&remoteAddress, 0, sizeof(remoteAddress)); socklen_t remoteAddressLen = sizeof(remoteAddress); SOCKET &listenSock = listenSocket->GetSocketHandle(); SOCKET acceptSocket = accept(listenSock, (sockaddr*)&remoteAddress, &remoteAddressLen); if (acceptSocket == KNET_ACCEPT_FAILURE) { int error = Network::GetLastError(); if (error != KNET_EWOULDBLOCK) { LOG(LogError, "NetworkServer::AcceptConnections: accept failed: %s", Network::GetErrorString(error).c_str()); closesocket(listenSock); listenSock = INVALID_SOCKET; } return 0; } EndPoint remoteEndPoint = EndPoint::FromSockAddrIn(remoteAddress); std::string remoteHostName = remoteEndPoint.IPToString(); LOG(LogInfo, "Accepted incoming TCP connection from %s:%d.", remoteHostName.c_str(), (int)remoteEndPoint.port); EndPoint localEndPoint; sockaddr_in localSockAddr; socklen_t namelen = sizeof(localSockAddr); int sockRet = getsockname(acceptSocket, (sockaddr*)&localSockAddr, &namelen); // Note: This works only if family==INETv4 localEndPoint = EndPoint::FromSockAddrIn(localSockAddr); std::string localHostName = owner->LocalAddress(); const size_t maxTcpSendSize = 65536; Socket *socket = owner->StoreSocket(Socket(acceptSocket, localEndPoint, localHostName.c_str(), remoteEndPoint, remoteHostName.c_str(), SocketOverTCP, ServerClientSocket, maxTcpSendSize)); socket->SetBlocking(false); return socket; }
//------------------------------------------------------------------------------------- int UDPPacket::recvFromEndPoint(EndPoint & ep, Address* pAddr) { KBE_ASSERT(maxBufferSize() > wpos()); // 当接收来的大小大于接收缓冲区的时候,recvfrom返回-1 int len = ep.recvfrom(data() + wpos(), size() - wpos(), (u_int16_t*)&pAddr->port, (u_int32_t*)&pAddr->ip); if(len > 0) wpos(wpos() + len); return len; }
OSS::IPAddress SIPWebSocketConnection::getLocalAddress() const /// Returns the local address binding for this transport { if (_localAddress.isValid()) return _localAddress; if (_pServerConnection) { boost::system::error_code ec; EndPoint ep = _pServerConnection->get_raw_socket().local_endpoint(ec); if (!ec) { boost::asio::ip::address ip = ep.address(); _localAddress = OSS::IPAddress(ip.to_string(), ep.port()); return _localAddress; } else { OSS_LOG_WARNING("SIPWebSocketConnection::getLocalAddress() Exception " << ec.message()); } } return OSS::IPAddress(); }
Reason TCPPacketSender::processSendPacket(Channel* pChannel, Packet* pPacket) { if(pChannel->isCondemn()) { return REASON_CHANNEL_CONDEMN; } EndPoint* pEndPoint = pChannel->getEndPoint(); int32 len = pEndPoint->send(pPacket->data() + pPacket->m_sentSize, (int32)(pPacket->length() - pPacket->m_sentSize)); if(len > 0) { pPacket->m_sentSize += len; } bool sentCompleted = pPacket->m_sentSize == pPacket->length(); pChannel->onPacketSent(len, sentCompleted); if(sentCompleted) return REASON_SUCCESS; return checkSocketErrors(pEndPoint); }
//------------------------------------------------------------------------------------- Reason TCPPacketSender::processFilterPacket(Channel* pChannel, Packet * pPacket) { if(pChannel->isCondemn()) { return REASON_CHANNEL_CONDEMN; } EndPoint* pEndpoint = pChannel->pEndPoint(); int len = pEndpoint->send(pPacket->data() + pPacket->sentSize, pPacket->length() - pPacket->sentSize); if(len > 0) { pPacket->sentSize += len; // DEBUG_MSG(fmt::format("TCPPacketSender::processFilterPacket: sent={}, sentTotalSize={}.\n", len, pPacket->sentSize)); } bool sentCompleted = pPacket->sentSize == pPacket->length(); pChannel->onPacketSent(len, sentCompleted); if (sentCompleted) return REASON_SUCCESS; return checkSocketErrors(pEndpoint); }
//------------------------------------------------------------------------------------- int TCPPacket::recvFromEndPoint(EndPoint & ep, Address* pAddr) { //KBE_ASSERT(MessageHandlers::pMainMessageHandlers != NULL && "Must set up a MainMessageHandlers!\n"); KBE_ASSERT(maxBufferSize() > wpos()); int len = ep.recv(data() + wpos(), size() - wpos()); wpos(wpos() + len); /* // 注意:必须在大于0的时候否则DEBUG_MSG将会导致WSAGetLastError返回0从而陷入死循环 if(len > 0) { DEBUG_MSG(boost::format("TCPPacket::recvFromEndPoint: datasize=%1%, wpos=%2%.\n") % len % wpos()); } */ return len; }
//------------------------------------------------------------------------------------- int TCPPacket::recvFromEndPoint(EndPoint & ep, Address* pAddr) { //KBE_ASSERT(MessageHandlers::pMainMessageHandlers != NULL && "Must set up a MainMessageHandlers!\n"); KBE_ASSERT(maxBufferSize() > wpos()); int len = ep.recv(data() + wpos(), (int)(size() - wpos())); if(len > 0) { wpos((int)(wpos() + len)); // 注意:必须在大于0的时候否则DEBUG_MSG将会导致WSAGetLastError返回0从而陷入死循环 // DEBUG_MSG(fmt::format("TCPPacket::recvFromEndPoint: datasize={}, wpos={}.\n", len, wpos())); } return len; }
void NetworkServer::EnqueueNewUDPConnectionAttempt(Socket *listenSocket, const EndPoint &endPoint, const char *data, size_t numBytes) { ConnectionAttemptDescriptor desc; desc.data.size = std::min<int>(cDatagramBufferSize, numBytes); memcpy(&desc.data.data[0], data, desc.data.size); desc.peer = endPoint; desc.listenSocket = listenSocket; ///\todo Check IP banlist. ///\todo Check that the maximum number of active concurrent connections is not exceeded. bool success = udpConnectionAttempts.Insert(desc); if (!success) LOG(LogError, "Too many connection attempts!"); else LOG(LogInfo, "Queued new connection attempt from %s.", endPoint.ToString().c_str()); }
ConnMgr::status_t ConnMgr::insert(EndPoint& ep, const int sock, Conn* conn) { LOG_TRACE( "%s", "enter"); // Make sure there is no old connection for the same socket std::map<int, Conn*>::iterator c = sockConnMap.find(sock); if (c != sockConnMap.end()) { LOG_ERROR( "%s", "connection already inserted"); return ERR_AINSERTED; } sockConnMap.insert(std::pair<int, Conn*>(sock, conn)); // Make a string out of ep.host and ep.port std::string keyStr; ep.toHostPortStr(keyStr); // Verify whether there is a leftover connection for this key EpSockMap::iterator p = epSockMap.find(keyStr); if (p == epSockMap.end()) { std::set<int> emptySet; epSockMap.insert( std::pair<std::string, std::set<int> >(keyStr, emptySet)); } p = epSockMap.find(keyStr); if (p != epSockMap.end()) { std::set<int> &socketSet = (p->second); socketSet.insert(sock); } LOG_INFO( "inserted connection %s:%d to connMgr", keyStr.c_str(), sock); LOG_TRACE("Exit"); return SUCCESS; }