int process_tcp (u_char * userdata, const dp_header * header, const u_char * m_packet) { struct dpargs * args = (struct dpargs *) userdata; struct tcphdr * tcp = (struct tcphdr *) m_packet; curtime = header->ts; /* get info from userdata, then call getPacket */ Packet * packet; switch (args->sa_family) { case (AF_INET): packet = new Packet (args->ip_src, ntohs(tcp->source), args->ip_dst, ntohs(tcp->dest), header->len, header->ts); break; case (AF_INET6): packet = new Packet (args->ip6_src, ntohs(tcp->source), args->ip6_dst, ntohs(tcp->dest), header->len, header->ts); break; } Connection * connection = findConnection(packet); if (connection != NULL) { /* add packet to the connection */ connection->add(packet); } else { /* else: unknown connection, create new */ connection = new Connection (packet); getProcess(connection, args->device); } delete packet; /* we're done now. */ return true; }
OsStatus XCpCall::handleDropConnection(const AcDropConnectionMsg& rMsg) { if (m_pSipConnection) { SipDialog sipDialog; rMsg.getSipDialog(sipDialog); UtlBoolean resFound = FALSE; // find connection by sip dialog if call-id is not null OsPtrLock<XSipConnection> ptrLock; if (sipDialog.getCallId().isNull()) { resFound = getConnection(ptrLock); } else { resFound = findConnection(sipDialog, ptrLock); } if (resFound) { return ptrLock->dropConnection(); } } else { // we don't have any connection requestCallDestruction(); return OS_SUCCESS; } return OS_NOT_FOUND; }
void NetInterface::handleDisconnect(const Address &address, BitStream *stream) { NetConnection *conn = findConnection(address); if(!conn) return; ConnectionParameters &theParams = conn->getConnectionParameters(); Nonce nonce, serverNonce; char reason[256]; nonce.read(stream); serverNonce.read(stream); if(nonce != theParams.mNonce || serverNonce != theParams.mServerNonce) return; U32 decryptPos = stream->getBytePosition(); stream->setBytePosition(decryptPos); if(theParams.mUsingCrypto) { SymmetricCipher theCipher(theParams.mSharedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher)) return; } stream->readString(reason); conn->setConnectionState(NetConnection::Disconnected); conn->onConnectionTerminated(NetConnection::ReasonRemoteDisconnectPacket, reason); removeConnection(conn); }
void NetInterface::processPacket(const Address &sourceAddress, BitStream *pStream) { // Determine what to do with this packet: if(pStream->getBuffer()[0] & 0x80) // it's a protocol packet... { // if the LSB of the first byte is set, it's a game data packet // so pass it to the appropriate connection. // lookup the connection in the addressTable // if this packet causes a disconnection, keep the conn around until this function exits RefPtr<NetConnection> conn = findConnection(sourceAddress); if(conn) conn->readRawPacket(pStream); } else { // Otherwise, it's either a game info packet or a // connection handshake packet. U8 packetType; pStream->read(&packetType); if(packetType >= FirstValidInfoPacketId) handleInfoPacket(sourceAddress, packetType, pStream); else { // check if there's a connection already: switch(packetType) { case ConnectChallengeRequest: handleConnectChallengeRequest(sourceAddress, pStream); break; case ConnectChallengeResponse: handleConnectChallengeResponse(sourceAddress, pStream); break; case ConnectRequest: handleConnectRequest(sourceAddress, pStream); break; case ConnectReject: handleConnectReject(sourceAddress, pStream); break; case ConnectAccept: handleConnectAccept(sourceAddress, pStream); break; case Disconnect: handleDisconnect(sourceAddress, pStream); break; case Punch: handlePunch(sourceAddress, pStream); break; case ArrangedConnectRequest: handleArrangedConnectRequest(sourceAddress, pStream); break; } } } }
//*********************************************************************** void ICACHE_FLASH_ATTR easyMesh::handleNodeSync( meshConnectionType *conn, JsonObject& root ) { debugMsg( SYNC, "handleNodeSync(): with %u\n", conn->chipId); meshPackageType type = (meshPackageType)(int)root["type"]; uint32_t remoteChipId = (uint32_t)root["from"]; uint32_t destId = (uint32_t)root["dest"]; bool reSyncAllSubConnections = false; if( (destId == 0) && (findConnection( remoteChipId ) != NULL) ) { // this is the first NODE_SYNC_REQUEST from a station // is we are already connected drop this connection debugMsg( SYNC, "handleNodeSync(): Already connected to node %d. Dropping\n", conn->chipId); closeConnection( conn ); return; } if ( conn->chipId != remoteChipId ) { debugMsg( SYNC, "handleNodeSync(): conn->chipId updated from %d to %d\n", conn->chipId, remoteChipId ); conn->chipId = remoteChipId; } // check to see if subs have changed. String inComingSubs = root["subs"]; if ( !conn->subConnections.equals( inComingSubs ) ) { // change in the network reSyncAllSubConnections = true; conn->subConnections = inComingSubs; } switch ( type ) { case NODE_SYNC_REQUEST: { debugMsg( SYNC, "handleNodeSync(): valid NODE_SYNC_REQUEST %d sending NODE_SYNC_REPLY\n", conn->chipId ); String myOtherSubConnections = subConnectionJson( conn ); sendMessage( conn, _chipId, NODE_SYNC_REPLY, myOtherSubConnections ); break; } case NODE_SYNC_REPLY: debugMsg( SYNC, "handleNodeSync(): valid NODE_SYNC_REPLY from %d\n", conn->chipId ); conn->nodeSyncRequest = 0; //reset nodeSyncRequest Timer ???? if ( conn->lastTimeSync == 0 ) startTimeSync( conn ); break; default: debugMsg( ERROR, "handleNodeSync(): weird type? %d\n", type ); } if ( reSyncAllSubConnections == true ) { SimpleList<meshConnectionType>::iterator connection = _connections.begin(); while ( connection != _connections.end() ) { connection->nodeSyncStatus = NEEDED; connection++; } } conn->nodeSyncStatus = COMPLETE; // mark this connection nodeSync'd }
/* 按连通域分割图像 * image 图像数据 * i 寻找第一个不为0的点时寻找起始点所在行(寻找方向从左向右,从上向下) * j 寻找第一个不为0的点时寻找起始点所在列(寻找方向从左向右,从上向下) * imgSpArr 分离出的连通域数组 */ void splitImage(IplImage* image, int i, int j, ImageSplitArray* imgSpArr) { int ii, ji; for(ii=i; ii<image->height; ii++) { for(ji=j; ji<image->width; ji++) { if(image->imageData[ii*image->widthStep+ji] != 0) break; } j=0; if(ji < image->width && image->imageData[ii*image->widthStep+ji] != 0) break; } if(ii<image->height && ji<image->width) { PointsArray poiArr = {64, 0, (int(*)[2]) malloc (64*sizeof(int[2])), image->height, image->width, 0, 0}; //点(i,j)8邻域中的非零点所在行和列 PointsArray* ijs = &poiArr; ijs->pointArray[ijs->count][0] = ii; ijs->pointArray[ijs->count][1] = ji; image->imageData[ii*image->widthStep+ji] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; ++(ijs->count); findConnection(image, ijs, ii, ji); /*****如果imgSpArr内存不够,则将结构体数组长度+10*****/ if(imgSpArr->count >= imgSpArr->length) { imgSpArr->length += 10; ImageCon* tempImgCons = (ImageCon*)malloc(sizeof(ImageCon) * imgSpArr->length); for(int m=0; m<imgSpArr->count; m++) { ImageCon tempImgCon = {cvCreateImage(cvGetSize(imgSpArr->imgCons[m].img), imgSpArr->imgCons[m].img->depth, imgSpArr->imgCons[m].img->nChannels), imgSpArr->imgCons[m].minI, imgSpArr->imgCons[m].minJ, imgSpArr->imgCons[m].maxI, imgSpArr->imgCons[m].maxJ, imgSpArr->imgCons[m].aspectRatio, 0, 0}; tempImgCons[m] = tempImgCon; cvCopy(imgSpArr->imgCons[m].img, tempImgCons[m].img, NULL); cvReleaseImage(&(imgSpArr->imgCons[m].img)); } free(imgSpArr->imgCons); imgSpArr->imgCons = tempImgCons; } //imagesSplit[imagesSplit->count] = cvCreateImage(cvSize(image->width,image->height), image->depth, image->nChannels); ImageCon imgCon = {cvCreateImage(cvSize(ijs->maxJ-ijs->minJ+1, ijs->maxI-ijs->minI+1), image->depth, image->nChannels), ijs->minI, ijs->minJ, ijs->maxI, ijs->maxJ, 0.0f, 0, 0}; imgSpArr->imgCons[imgSpArr->count] = imgCon; cvZero(imgSpArr->imgCons[imgSpArr->count].img); imgSpArr->imgCons[imgSpArr->count].aspectRatio = (float)(ijs->maxI-ijs->minI+1) / (float)(ijs->maxJ-ijs->minJ+1); for(int m=0; m<ijs->count; m++) imgSpArr->imgCons[imgSpArr->count].img->imageData[(ijs->pointArray[m][0]-ijs->minI)*imgSpArr->imgCons[imgSpArr->count].img->widthStep+(ijs->pointArray[m][1]-ijs->minJ)] = (char)255; (imgSpArr->count)++; free(ijs->pointArray); //(*foregroundCounts)-=ijs->count; splitImage(image, ii, ji, imgSpArr); } }
void RaftConsensus::removeConnection(int id) { Connection::Ptr pConnection; pConnection = findConnection(id); if (!pConnection) { pConnection->shutdown(); OSS::mutex_critic_sec_lock lock(_connectionMutex); _connections.erase(id); } }
void SFtpConnectionCache::closeConnection(const QUrl &url) { QString key(getKey(url)); if (_connectionMap.contains(key)) { freeConnection(findConnection(url)); _connectionMap.remove(key); } }
void NetInterface::addPendingConnection(NetConnection *connection) { // make sure we're not already connected to the host at the // connection's Address findAndRemovePendingConnection(connection->getNetAddress()); NetConnection *temp = findConnection(connection->getNetAddress()); if(temp) disconnect(temp, NetConnection::ReasonSelfDisconnect, "Reconnecting"); // hang on to the connection and add it to the pending connection list connection->incRef(); mPendingConnections.push_back(connection); }
RaftConsensus::Connection::Ptr RaftConsensus::findOrCreateConnection(Node& node) { Connection::Ptr pConnection; pConnection = findConnection(node.getId()); if (!pConnection) { pConnection = createConnection(node); if (pConnection) { storeConnection(node.getId(), pConnection); } } return pConnection; }
static void createConnection(IDnum nodeID, IDnum node2ID, IDnum direct_count, IDnum paired_count, Coordinate distance, double variance) { Connection *connect = findConnection(nodeID, node2ID); if (connect != NULL) readjustConnection(connect, distance, variance, direct_count, paired_count); else createNewConnection(nodeID, node2ID, direct_count, paired_count, distance, variance); }
int process_tcp (u_char * userdata, const dp_header * header, const u_char * m_packet) { std::cout << "Processing TCP packet with len " << header->len << std::endl; struct dpargs * args = (struct dpargs *) userdata; struct tcphdr * tcp = (struct tcphdr *) m_packet; curtime = header->ts; /* TODO get info from userdata, then call getPacket */ Packet * packet; switch (args->sa_family) { case (AF_INET): packet = new Packet (args->ip_src, ntohs(tcp->source), args->ip_dst, ntohs(tcp->dest), header->len, header->ts); break; case (AF_INET6): packet = new Packet (args->ip6_src, ntohs(tcp->source), args->ip6_dst, ntohs(tcp->dest), header->len, header->ts); break; } //if (DEBUG) // std::cout << "Got packet from " << packet->gethashstring() << std::endl; Connection * connection = findConnection(packet); if (connection != NULL) { /* add packet to the connection */ connection->add(packet); } else { /* else: unknown connection, create new */ connection = new Connection (packet); getProcess(connection, currentdevice); } delete packet; if (needrefresh) { do_refresh(); needrefresh = false; } /* we're done now. */ return true; }
void Network::ReceiveThread() { struct sockaddr_in socketAddrOther; memset((char *)&socketAddrOther, 0, sizeof(socketAddrOther)); int socketAddrLength = sizeof(socketAddrOther); char buf[BUFLEN]; receiveTimer.start(); while (threadsRunning) { if (receiveTimer.getCurrentTimeSeconds() >= receive_delay) { memset(buf, '\0', BUFLEN); int dataCountReceived; if ((dataCountReceived = recvfrom(socketThis, buf, BUFLEN, 0, (struct sockaddr *) &socketAddrOther, &socketAddrLength)) == SOCKET_ERROR) { printf("recvfrom() failed with error code : %d\n", WSAGetLastError()); } else{ inDataMutex.lock(); u_short tempPort = ntohs(socketAddrOther.sin_port); std::string portString = std::to_string(tempPort); char *tempIP = inet_ntoa(socketAddrOther.sin_addr); Connection *conn = new Connection(this); conn->socketAddr = socketAddrOther; if (findConnection(ip, portString) == nullptr) { //Do something with received client connections.push_back(conn); newConnections.push_back(conn); } PacketData pdata; pdata.connection = conn; pdata.data = std::string(&buf[0], &buf[dataCountReceived]); inData.push_back(pdata); // std::cout << "Message received: " << buf << std::endl; inDataMutex.unlock(); } receiveTimer.start(); } } }
int process_udp (u_char * userdata, const dp_header * header, const u_char * m_packet) { struct dpargs * args = (struct dpargs *) userdata; struct udphdr * udp = (struct udphdr *) m_packet; curtime = header->ts; Packet * packet; switch (args->sa_family) { case (AF_INET): packet = new Packet (args->ip_src, ntohs(udp->source), args->ip_dst, ntohs(udp->dest), header->len, header->ts); break; case (AF_INET6): packet = new Packet (args->ip6_src, ntohs(udp->source), args->ip6_dst, ntohs(udp->dest), header->len, header->ts); break; } //if (DEBUG) // std::cout << "Got packet from " << packet->gethashstring() << std::endl; Connection * connection = findConnection(packet); if (connection != NULL) { /* add packet to the connection */ connection->add(packet); } else { /* else: unknown connection, create new */ connection = new Connection (packet); getProcess(connection, args->device); } delete packet; /* we're done now. */ return true; }
/* 从点(i,j)开始的连通域查找方法(i行j列的点) * image 图像数据 * ijs 点(i,j)8邻域中的非零点所在行和列的数组 * i 连通域中的点所在行 * j 连通域中的点所在列 */ void findConnection(IplImage* image, PointsArray *ijs, int i, int j) { /*****如果ijs内存不够,则将数组长度+64*****/ if(ijs->count+7 >= ijs->length) { ijs->length += 64; int (*tempIjs)[2]; tempIjs = (int(*)[2])malloc(sizeof(int[2]) * ijs->length); for(int m=0; m<ijs->count; m++){ tempIjs[m][0] = ijs->pointArray[m][0]; tempIjs[m][1] = ijs->pointArray[m][1]; } free(ijs->pointArray); ijs->pointArray = tempIjs; } int k_start = ijs->count; int k_end; if(i>0 && j>0 && image->imageData[(i-1)*image->widthStep+j-1] == (char)255) //左上 { //ijs=(int(*)[2]) realloc (ijs, (*k+1)*sizeof(int[2])); ijs->pointArray[ijs->count][0] = i-1; ijs->pointArray[ijs->count][1] = j-1; image->imageData[(i-1)*image->widthStep+j-1] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; (ijs->count)++; } if(i>0 && image->imageData[(i-1)*image->widthStep+j] == (char)255) //正上 { //ijs=(int(*)[2]) realloc (ijs, (*k+1)*sizeof(int[2])); ijs->pointArray[ijs->count][0] = i-1; ijs->pointArray[ijs->count][1] = j; image->imageData[(i-1)*image->widthStep+j] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; (ijs->count)++; } if(i>0 && j<image->width-1 && image->imageData[(i-1)*image->widthStep+j+1] == (char)255) //右上 { //ijs=(int(*)[2]) realloc (ijs, (*k+1)*sizeof(int[2])); ijs->pointArray[ijs->count][0] = i-1; ijs->pointArray[ijs->count][1] = j+1; image->imageData[(i-1)*image->widthStep+j+1] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; (ijs->count)++; } if(j>0 && image->imageData[i*image->widthStep+j-1] == (char)255) //左 { //ijs=(int(*)[2]) realloc (ijs, (*k+1)*sizeof(int[2])); ijs->pointArray[ijs->count][0] = i; ijs->pointArray[ijs->count][1] = j-1; image->imageData[i*image->widthStep+j-1] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; (ijs->count)++; } if(j<image->width-1 && image->imageData[i*image->widthStep+j+1] == (char)255) //右 { //ijs=(int(*)[2]) realloc (ijs, (*k+1)*sizeof(int[2])); ijs->pointArray[ijs->count][0] = i; ijs->pointArray[ijs->count][1] = j+1; image->imageData[i*image->widthStep+j+1] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; (ijs->count)++; } if(i<image->height-1 && j>0 && image->imageData[(i+1)*image->widthStep+j-1] == (char)255) //左下 { //ijs=(int(*)[2]) realloc (ijs, (*k+1)*sizeof(int[2])); ijs->pointArray[ijs->count][0] = i+1; ijs->pointArray[ijs->count][1] = j-1; image->imageData[(i+1)*image->widthStep+j-1] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; (ijs->count)++; } if(i<image->height-1 && image->imageData[(i+1)*image->widthStep+j] == (char)255) //正下 { //ijs=(int(*)[2]) realloc (ijs, (*k+1)*sizeof(int[2])); ijs->pointArray[ijs->count][0] = i+1; ijs->pointArray[ijs->count][1] = j; image->imageData[(i+1)*image->widthStep+j] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; (ijs->count)++; } if(i<image->height-1 && j<image->width-1 && image->imageData[(i+1)*image->widthStep+j+1] == (char)255) //右下 { //ijs=(int(*)[2]) realloc (ijs, (*k+1)*sizeof(int[2])); ijs->pointArray[ijs->count][0] = i+1; ijs->pointArray[ijs->count][1] = j+1; image->imageData[(i+1)*image->widthStep+j+1] = 0; ijs->minI > ijs->pointArray[ijs->count][0] ? ijs->minI = ijs->pointArray[ijs->count][0] : ijs->minI = ijs->minI; ijs->minJ > ijs->pointArray[ijs->count][1] ? ijs->minJ = ijs->pointArray[ijs->count][1] : ijs->minJ = ijs->minJ; ijs->maxI < ijs->pointArray[ijs->count][0] ? ijs->maxI = ijs->pointArray[ijs->count][0] : ijs->maxI = ijs->maxI; ijs->maxJ < ijs->pointArray[ijs->count][1] ? ijs->maxJ = ijs->pointArray[ijs->count][1] : ijs->maxJ = ijs->maxJ; (ijs->count)++; } k_end = ijs->count; for(int ki=k_start; ki<k_end; ki++) findConnection(image, ijs, ijs->pointArray[ki][0], ijs->pointArray[ki][1]); }
HDDEDATA gcDDEManager::processCallBack(WORD wType, WORD wFmt, HCONV hConv, HSZ hsz1, HSZ hsz2, HDDEDATA hData, DWORD lData1, DWORD lData2) { //printf("\tProcessing msg: %d\n", wType); switch (wType) { case XTYP_CONNECT: { char szTopic[255]; stringFromAtom(hsz1, szTopic, 255); char szServer[255]; stringFromAtom(hsz2, szServer, 255); gcDDEServer *server = findServer(szServer); if (server) return server->acceptConnection(szTopic, hConv); break; } case XTYP_CONNECT_CONFIRM: { if (m_pCurConnecting) { m_pCurConnecting->setConv(hConv); m_pCurConnecting = NULL; return (DDERETURN)(DWORD)true; } break; } case XTYP_DISCONNECT: { gcDDEConnection *connection = findConnection(hConv); if (connection) return connection->disconnect(); break; } case XTYP_POKE: { gcDDEConnection *connection = findConnection(hConv); if (connection) return (DDERETURN)connection->handlePoke(hsz2, hData); else return (DDERETURN)DDE_FNOTPROCESSED; } case XTYP_ADVSTART: case XTYP_ADVSTOP: case XTYP_EXECUTE: case XTYP_REQUEST: case XTYP_ADVREQ: case XTYP_ADVDATA: printf("gcDDE: This method not implemented! [%d]", wType); } return (DDERETURN)0; }
// Point d'entree dans le programme int main(int argc,char** argv) { FILE* transaction_file = fopen(S_LEC,"a+"); fclose(transaction_file); transaction_file = fopen(S_LEC,"r"); if (transaction_file == NULL) { fprintf(stderr,"Impossible d'ouvrir le fichier %s\n",S_LEC); return -1; } char line_buffer[256], message[256]; int i, flags; Connection* connection; PRIM_PACKET p; // Recuperation des references au tuyaux // (respectivement l'ecriture et l'ecoute) transToNet_pipe = atoi(argv[1]); netToTrans_pipe = atoi(argv[2]); // On s'assure que les file descriptors sont en mode 0_NONBLOCK flags = fcntl(transToNet_pipe,F_GETFL,0); fcntl(transToNet_pipe,F_SETFL, flags | O_NONBLOCK); flags = fcntl(netToTrans_pipe,F_GETFL,0); fcntl(netToTrans_pipe,F_SETFL, flags | O_NONBLOCK); if (DEBUG) printf("TRANSPORT\nMes fd sont:\n%i,%i\n",netToTrans_pipe,transToNet_pipe); //ALGO //-------- //TANT QUE FICHIER_NON_VIDE //LIRE S_LEC //REGARDER_TABLE_DE_CONNEXIONS //SI CONNEXION_EXISTE_PAS //ENVOYER_CONNECTION_REQ //ECOUTER_REPONSE //SI REPONSE_POSITIVE //CHANGER_ETAT_CONNEXION_TABLE_CONNEXION //ENVOYER_DATA_REQ //SINON //SUPPRIMER_CONNEXION //FIN SI //SINON //ENVOYER_DATA_REQ //FIN SI //FIN TANT QUE //POUR TOUS LES CONNEXION //SUPPRIMMER_CONNEXION // Lecture du fichier S_LEC, envoie des requetes et ecoute // de la reponse. while(fgets(line_buffer, 256, transaction_file)) { connection = (Connection*) findConnection(line_buffer[0]); // La connexion n'existe pas if (!connection/*==NULL*/) { // Engager une connexion connection = (Connection*) add_connection(line_buffer[0],NULL,NULL); // Creaction d'un paquet contenant la primitive N_CONNECT_req p.prim = N_CONNECT_req; // Genere un seed pour une valeur pseudo-aleatoire // differente par rand() srand(time(NULL)); p.con_prim_packet.src_addr = (unsigned char) rand(); // Adresses aleatoires pour la source p.con_prim_packet.dest_addr = (unsigned char) rand(); // et la destination.. p.con_prim_packet.con_number = connection->tcon.con_number; // Envoie d'un paquet et ecoute de la reponse de ER writePrimPacketToStdOut(&p,I_AM); if(sendPacketToInterface(&p,transToNet_pipe) == -1) return -1; if (getPacketFromInterface(&p,netToTrans_pipe) == -1) return -1; char result[256]; // Action en consequence switch(p.prim) { // CON_PRIM_PACKET reçu => N_CONNECT_conf case N_CONNECT_conf: // Ecriture des resutlats dans S_ECR sprintf(result,"Reception de la primitive N_CONNECT.conf sur la connection %c\n", connection->tcon.con_number); writeResults(result,S_ECR); // Confirmation de la connexion connection->tcon.state = 0x01; // Construction du paquet de DATA p.prim = N_DATA_req; getMessageFromBuffer(line_buffer,message); strcpy(p.data_prim_packet.transaction,message); p.data_prim_packet.con_number = connection->tcon.con_number; // Envoie du paquet a l'ER writePrimPacketToStdOut(&p,I_AM); if(sendPacketToInterface(&p,transToNet_pipe) == -1) return -1; break; // REL_PRIM_PACKET reçu => N_DISCONNECT_ind case N_DISCONNECT_ind: // Ecriture des resultats dans S_ECR sprintf(result,"Reception de la primitive N_DISCONNECT.ind pour la connexion %c\n",connection->tcon.con_number); writeResults(result,S_ECR); // Retrait de la connexion de la table de connexions remove_connection(connection->tcon.con_number); break; } } else { // Construction du paquet de DATA p.prim = N_DATA_req; getMessageFromBuffer(line_buffer,message); strcpy(p.data_prim_packet.transaction,message); p.data_prim_packet.con_number = connection->tcon.con_number; // Envoyer N_DATA.req writePrimPacketToStdOut(&p,I_AM); if(sendPacketToInterface(&p,transToNet_pipe) == -1) return -1; } } // Construction d'un paquet REL_PRIM_PACKET // et vidage de la table de connexions p.prim = N_DISCONNECT_req; connection = first_con_node; while (connection) { p.rel_prim_packet.con_number = connection->tcon.con_number; writePrimPacketToStdOut(&p,I_AM); if(sendPacketToInterface(&p,transToNet_pipe) == -1) return -1; connection = connection->tcon.next; } deleteAllConnections(); // Fermeture du fichier S_LEC fclose(transaction_file); return 0; }
//------------------------------------------------------------------------------ void WriteJeq(std::string& inputString, const std::vector<kjeqConnection>& orderedConnections, const std::vector<connectionLine>& connectionArray, std::vector<std::string>& joinPath, bool add_active_neutral_filter) { std::string andClause = "AND "; connectionLine cL; std::string output; // Step 1 : Add as many 'AND' as needed size_t currentNrCon = 0; for( size_t idx = 0; idx < connectionArray.size(); ++idx ) currentNrCon += connectionArray[idx].tableAndCol1.size(); size_t totalNrCon = 0; for( size_t idx = 0; idx < orderedConnections.size(); ++idx ) { const kjeqConnection& kC = orderedConnections[idx]; cL = findConnection( connectionArray, kC ); totalNrCon += cL.tableAndCol1.size(); } assert( currentNrCon <= totalNrCon ); for( size_t idx = currentNrCon; idx < totalNrCon; ++idx ) output += andClause; // Step 2 : add K_JEQ conditions in the right order output += '\n'; bool table_prc_is_neutral = false; std::string table_src_prec; std::set<std::string> tables; for( size_t idx = 0; idx < orderedConnections.size(); ++idx ) { const kjeqConnection& kC = orderedConnections[idx]; cL = findConnection( connectionArray, kC ); assert(((kC.tableSource == cL.table1) && (kC.tableDestination == cL.table2)) || ((kC.tableSource == cL.table2) && (kC.tableDestination == cL.table1))); bool invert = (kC.tableSource != cL.table2) && ((connectionArray.size() > 1) || (cL.connectionType.size() > 1)); if (invert) { cL = invertConnection(cL); } for( size_t idx2 = 0; idx2 < cL.tableAndCol1.size(); ++idx2 ) { std::string source, destination; if (add_active_neutral_filter) source = table_prc_is_neutral ? "K_NEUTRAL" : "K_ACTIVE"; source += " " + cL.tableAndCol2[idx2]; if (add_active_neutral_filter) { if (tables.find(cL.table1) != tables.end()) { if (cL.table1 == table_src_prec) { destination = "K_NEUTRAL"; table_prc_is_neutral = true; } else { destination = "K_FILTER "; table_prc_is_neutral = false; } } else { destination = "K_ACTIVE"; table_prc_is_neutral = false; } } destination += " "; destination += cL.tableAndCol1[idx2]; std::string tname = cL.table2.substr(2); if (std::find(joinPath.begin(), joinPath.end(), tname) == joinPath.end()) joinPath.push_back(tname); tname = cL.table1.substr(2); if (std::find(joinPath.begin(), joinPath.end(), tname) == joinPath.end()) joinPath.push_back(tname); output += cL.connectionType[idx2] + " " + destination + " " + source + "\n"; } table_src_prec = cL.table2; tables.insert(cL.table1); tables.insert(cL.table2); } assert(!joinPath.empty()); // Step 3 : localize the conditions from the input request and delete them // each one is caught between the 'firstIndex' and the 'lastindex' std::string::size_type firstIndex = std::string::npos, lastIndex; for(;;) { std::string aux; findJoin( inputString, aux, firstIndex ); if( firstIndex == std::string::npos ) break; lastIndex = firstIndex; lastIndex = inputString.find('.', lastIndex)+1; lastIndex = inputString.find('.', lastIndex); lastIndex = inputString.find(' ', lastIndex) + 1; lastIndex = inputString.find(' ', lastIndex) + 1; lastIndex = inputString.find(' ', lastIndex) + 1; if( lastIndex == std::string::npos ) lastIndex = inputString.length(); inputString = inputString.replace(firstIndex, lastIndex-firstIndex, ""); }; firstIndex = inputString.rfind( andClause ); std::string whereClause = "WHERE "; if( firstIndex == std::string::npos ) firstIndex = inputString.find( whereClause ) + whereClause.length(); else firstIndex += andClause.length(); inputString.insert( firstIndex, output ); }
void NetInterface::handleConnectRequest(const Address &address, BitStream *stream) { if(!mAllowConnections) return; ConnectionParameters theParams; theParams.mNonce.read(stream); theParams.mServerNonce.read(stream); stream->read(&theParams.mClientIdentity); if(theParams.mClientIdentity != computeClientIdentityToken(address, theParams.mNonce)) return; stream->read(&theParams.mPuzzleDifficulty); stream->read(&theParams.mPuzzleSolution); // see if the connection is in the main connection table. // If the connection is in the connection table and it has // the same initiatorSequence, we'll just resend the connect // acceptance packet, assuming that the last time we sent it // it was dropped. NetConnection *connect = findConnection(address); if(connect) { ConnectionParameters &cp = connect->getConnectionParameters(); if(cp.mNonce == theParams.mNonce && cp.mServerNonce == theParams.mServerNonce) { sendConnectAccept(connect); return; } } // check the puzzle solution ClientPuzzleManager::ErrorCode result = mPuzzleManager.checkSolution( theParams.mPuzzleSolution, theParams.mNonce, theParams.mServerNonce, theParams.mPuzzleDifficulty, theParams.mClientIdentity); if(result != ClientPuzzleManager::Success) { sendConnectReject(&theParams, address, "Puzzle"); return; } if(stream->readFlag()) { if(mPrivateKey.isNull()) return; theParams.mUsingCrypto = true; theParams.mPublicKey = new AsymmetricKey(stream); theParams.mPrivateKey = mPrivateKey; U32 decryptPos = stream->getBytePosition(); stream->setBytePosition(decryptPos); theParams.mSharedSecret = theParams.mPrivateKey->computeSharedSecretKey(theParams.mPublicKey); //logprintf("shared secret (server) %s", theParams.mSharedSecret->encodeBase64()->getBuffer()); SymmetricCipher theCipher(theParams.mSharedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher)) return; // now read the first part of the connection's symmetric key stream->read(SymmetricCipher::KeySize, theParams.mSymmetricKey); Random::read(theParams.mInitVector, SymmetricCipher::KeySize); } U32 connectSequence; theParams.mDebugObjectSizes = stream->readFlag(); stream->read(&connectSequence); TNLLogMessageV(LogNetInterface, ("Received Connect Request %8x", theParams.mClientIdentity)); if(connect) disconnect(connect, NetConnection::ReasonSelfDisconnect, "NewConnection"); char connectionClass[256]; stream->readString(connectionClass); NetConnection *conn = NetConnectionRep::create(connectionClass); if(!conn) return; RefPtr<NetConnection> theConnection = conn; conn->getConnectionParameters() = theParams; conn->setNetAddress(address); conn->setInitialRecvSequence(connectSequence); conn->setInterface(this); if(theParams.mUsingCrypto) conn->setSymmetricCipher(new SymmetricCipher(theParams.mSymmetricKey, theParams.mInitVector)); const char *errorString = NULL; if(!conn->readConnectRequest(stream, &errorString)) { sendConnectReject(&theParams, address, errorString); return; } addConnection(conn); conn->setConnectionState(NetConnection::Connected); conn->onConnectionEstablished(); sendConnectAccept(conn); }
void TCPServer::handleWrite(SPL::blob & raw, std::string const & ipAddress, uint32_t port) { // std::string connStr = broadcastResponse_ ? "" : createConnectionStr(ipAddress, port); // std::cerr << "writing to: " << connStr << std::endl; // TCPConnectionWeakPtr connWeakPtr; // bool connExist = false; TCPConnectionWeakPtrMap::iterator iter = broadcastResponse_ ? findFirstConnection() : findConnection(createConnectionStr(ipAddress, port)); if(iter == connMap_.end()) { if(!broadcastResponse_) errorHandler_.handleError(streams_boost::system::error_code(streams_boost::asio::error::connection_aborted), ipAddress, port); } else { AsyncDataItemPtr asyncDataItemPtr = streams_boost::make_shared<AsyncDataItem>(errorHandler_); asyncDataItemPtr->setData<Format>(raw); do { TCPConnectionWeakPtr connWeakPtr = iter->second; TCPConnectionPtr connPtr = connWeakPtr.lock(); /// Validate existing connection if (connPtr && connPtr->socket().is_open()) { uint32_t * numOutstandingWritesPtr = connPtr->getNumOutstandingWritesPtr(); /// Check if client consumes data from a socket if (*numOutstandingWritesPtr <= maxUnreadResponseCount_) { __sync_fetch_and_add(numOutstandingWritesPtr, 1); if(Format == mcts::block) { async_write(connPtr->socket(), asyncDataItemPtr->getBuffers(), connPtr->strand().wrap( streams_boost::bind(&AsyncDataItem::handleError, asyncDataItemPtr, streams_boost::asio::placeholders::error, connPtr->remoteIp(), connPtr->remotePort(), connWeakPtr) ) ); } else { async_write(connPtr->socket(), asyncDataItemPtr->getBuffer(), connPtr->strand().wrap( streams_boost::bind(&AsyncDataItem::handleError, asyncDataItemPtr, streams_boost::asio::placeholders::error, connPtr->remoteIp(), connPtr->remotePort(), connWeakPtr) ) ); } iter++; } else { connPtr->shutdown_conn(makeConnReadOnly_); if(makeConnReadOnly_) { iter++; } else { iter = unmapConnection(iter); } errorHandler_.handleError(streams_boost::system::error_code(streams_boost::asio::error::would_block), ipAddress, port, connWeakPtr); } } else { iter = unmapConnection(iter); } } while (broadcastResponse_ && (iter != connMap_.end())); } }
int handle_command(int socket) { char message[MESSAGE]; int result; int code; //receive message if((result = recvall(socket, message, sizeof(message))) == -1){ printf("handle_command recvall failed\n"); return -1; } //if result 0, close connection if(result == CLOSED){ struct peer *closedSocket = findConnection(socket); printf("%s closed the connection\n", closedSocket->hostname); updateSelect(DELETE, socket, &master_set, &fdmax); removeFromConnections(socket); if(localInfo.isServer){ //broadcast new IP list sendIPLIST(); } return 0; } //printf("NEW MESSAGE: %s\n", message); //EXTRACTING MESSAGE char* newptr = message; int nbytes; char hostName[200]; char port[50]; char ipaddr[INET6_ADDRSTRLEN]; //extract header sscanf(newptr, "%d %n", &code, &nbytes); newptr += nbytes; //SERVER IP UPDATE switch(code) { case ADD_IP_LIST : { DESTROY_IPLIST(); printf("\n%s UPDATED SERVER IP LIST:\n", getTime()); while(true){ //parse out the IP LIST sscanf(newptr, "%s %s %s %n", hostName, ipaddr, port, &nbytes); if(strcmp(hostName, "EOF") == 0) {break;} //printf("%s %s %s\n",hostName, ipaddr, port); SAVE_IPLIST(hostName, port, ipaddr); newptr += nbytes; } PRINT_IPLIST(); printf("\n"); break; } case SEND_FILE : { char filename[50]; char file_len[50]; char chunks_num[50]; sscanf(newptr, "%s %s %s", filename, file_len, chunks_num); struct peer *sender = findConnection(socket); printf("DOWNLOADING FILE: %s FROM: %s\n", filename, sender->hostname); if ((result = receiveFile(socket, filename, file_len, chunks_num)) != 0){ return result; } break; } case REQUEST_FILE : { char filename[50]; int connectionID; sscanf(newptr, "%s", filename); if((connectionID = findID(socket)) == -1){ printf("REQUEST_FILE: connection does not exist\n"); return EHOSTUNREACH; } char ID[20]; sprintf(ID, "%d", connectionID); int argCount = 3; char *arguments[] = {"UPLOAD", ID, filename}; if((result = cmd_upload(argCount, arguments)) != 0){ printf("ERROR: Could not upload file.\n"); char message[MESSAGE]; sprintf(message, "%d %s\n",NOTIFICATION, "REQUEST FAILED: COULD NOT UPLOAD FILE!"); sendall(socket, message, sizeof(message)); return EHOSTUNREACH; } break; } case NOTIFICATION : { struct peer *sender = findConnection(socket); printf("\n**** NOTIFICATION FROM: %s ****\n", sender->hostname); printf(">> %s\n", newptr); break; } default : printf("Invalid Message Code, cannot understand\n"); return -1; } return 0; }
void NetInterface::handleArrangedConnectRequest(const Address &theAddress, BitStream *stream) { S32 i, j; NetConnection *conn; Nonce nonce, serverNonce; nonce.read(stream); // see if the connection is in the main connection table. // If the connection is in the connection table and it has // the same initiatorSequence, we'll just resend the connect // acceptance packet, assuming that the last time we sent it // it was dropped. NetConnection *oldConnection = findConnection(theAddress); if(oldConnection) { ConnectionParameters &cp = oldConnection->getConnectionParameters(); if(cp.mNonce == nonce) { sendConnectAccept(oldConnection); return; } } for(i = 0; i < mPendingConnections.size(); i++) { conn = mPendingConnections[i]; ConnectionParameters &theParams = conn->getConnectionParameters(); if(conn->getConnectionState() != NetConnection::SendingPunchPackets || theParams.mIsInitiator) continue; if(nonce != theParams.mNonce) continue; for(j = 0; j < theParams.mPossibleAddresses.size(); j++) if(theAddress.isEqualAddress(theParams.mPossibleAddresses[j])) break; if(j != theParams.mPossibleAddresses.size()) break; } if(i == mPendingConnections.size()) return; ConnectionParameters &theParams = conn->getConnectionParameters(); SymmetricCipher theCipher(theParams.mArrangedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, stream->getBytePosition(), &theCipher)) return; stream->setBytePosition(stream->getBytePosition()); serverNonce.read(stream); if(serverNonce != theParams.mServerNonce) return; if(stream->readFlag()) { if(mPrivateKey.isNull()) return; theParams.mUsingCrypto = true; theParams.mPublicKey = new AsymmetricKey(stream); theParams.mPrivateKey = mPrivateKey; U32 decryptPos = stream->getBytePosition(); stream->setBytePosition(decryptPos); theParams.mSharedSecret = theParams.mPrivateKey->computeSharedSecretKey(theParams.mPublicKey); SymmetricCipher theCipher(theParams.mSharedSecret); if(!stream->decryptAndCheckHash(NetConnection::MessageSignatureBytes, decryptPos, &theCipher)) return; // now read the first part of the connection's session (symmetric) key stream->read(SymmetricCipher::KeySize, theParams.mSymmetricKey); Random::read(theParams.mInitVector, SymmetricCipher::KeySize); } U32 connectSequence; theParams.mDebugObjectSizes = stream->readFlag(); stream->read(&connectSequence); TNLLogMessageV(LogNetInterface, ("Received Arranged Connect Request")); if(oldConnection) disconnect(oldConnection, NetConnection::ReasonSelfDisconnect, ""); conn->setNetAddress(theAddress); conn->setInitialRecvSequence(connectSequence); if(theParams.mUsingCrypto) conn->setSymmetricCipher(new SymmetricCipher(theParams.mSymmetricKey, theParams.mInitVector)); const char *errorString = NULL; if(!conn->readConnectRequest(stream, &errorString)) { sendConnectReject(&theParams, theAddress, errorString); removePendingConnection(conn); return; } addConnection(conn); removePendingConnection(conn); conn->setConnectionState(NetConnection::Connected); conn->onConnectionEstablished(); sendConnectAccept(conn); }