/* accept a UNIX connection */ static int unixlSelectedR(Socket *self, int fd) { SocketUNIX *sock; int newfd, id; unsigned char idbuf[4]; /* accept it */ newfd = accept(fd, NULL, NULL); if (newfd < 0) return 0; /* then make the return */ sock = (SocketUNIX *) newSocket(sizeof(SocketUNIX)); newSocketWritable(sock, newfd); sock->ssuper.vtbl = &unixVTbl; /* register it */ id = registerSocket((Socket *) sock, NULL); /* then tell the other side */ muxCommand(stdoutSocket, 'c', self->id); muxPrepareInt(idbuf, id); stdoutSocket->vtbl->write(stdoutSocket, idbuf, 4); return 0; }
int escucharACPU(t_log * logger) { int retorno; int fdMemoria = newSocket(); asociarSocket(fdMemoria,vg_puerto_escucha); escucharSocket(fdMemoria,1); int fdCPU = aceptarConexionSocket(fdMemoria); // Veo si quien se conecta es CPU (quien deberia conectarse). void * login = malloc(sizeof(char) * 4); recibirPorSocket(fdCPU, login, 4); int coincide = strcmp((char *) login, "CPU"); free(login); if(coincide != 0) { perror("[ERROR] Se espera conexión del proceso CPU\n"); int respuesta = 0; enviarPorSocket(fdCPU,&respuesta,sizeof(int)); cerrarSocket(fdCPU); retorno = 0; } else { printf("[OK] Conexión entre Memoria y CPU establecida mediante el puerto: %d\n",vg_puerto_escucha); log_info(logger,"Conexión Memoria - CPU establecida mediante el puerto: %d\n",vg_puerto_escucha); int respuesta = 1; enviarPorSocket(fdCPU,&respuesta,sizeof(int)); retorno = fdCPU; } return retorno; }
void webserver_loop() { dmd_log(LOG_INFO, "in function %s, starting webserver main loop.\n", __func__); int serverfd = newSocket(); webserver_serverAddr = newAddress(); bindAddress(serverfd, webserver_serverAddr); listenAddress(serverfd); struct epoll_event events[MAX_EPOLL_EVENT]; int epollfd = newEpollSocket(); dmd_log(LOG_DEBUG, "in function %s, begin to work\n", __func__); addSockfd(epollfd, serverfd); while (1) { int ret = epoll_wait(epollfd, events, MAX_EPOLL_EVENT, -1); dmd_log(LOG_DEBUG, "in function %s, after epoll wait\n", __func__); if (ret < 0) { dmd_log(LOG_ERR, "in function %s, epoll failure\n", __func__); } else { handleEvent(epollfd, serverfd, events, ret); } } // while closeSocket(serverfd); releaseAddress(webserver_serverAddr); }
/* create a new named UNIXL */ static Socket *newUNIXL(char **saveptr) { SocketUNIXL *ret; char *path; int fd, tmpi; struct sockaddr_un sun; /* get the path */ path = strtok_r(NULL, "", saveptr); /* make the socket */ SF(fd, socket, -1, (AF_UNIX, SOCK_STREAM, 0)); sun.sun_family = AF_UNIX; strncpy(sun.sun_path, path, sizeof(sun.sun_path)); SF(tmpi, bind, -1, (fd, (struct sockaddr *) &sun, sizeof(sun))); /* and set it up to listen */ SF(tmpi, listen, -1, (fd, 32)); /* then make the return */ ret = (SocketUNIXL *) newSocket(sizeof(SocketUNIXL)); ret->ssuper.vtbl = &unixlVTbl; ret->fd = fd; return (Socket *) ret; }
static int doBind(int clsock,PCStr(clhost),int clport,int tsock,PCStr(arg)){ IStr(respudp,128); IStr(local,128); IStr(remote,128); IStr(opts,128); IStr(host,128); int port; int fd; int rsock; int cpid = -1; sv1log("==SU BIND %s...\n",arg); strcpy(local,"*"); strcpy(remote,"*"); strcpy(opts,"listen=32"); Xsscanf(arg,"%s %s %s %s",AVStr(respudp),AVStr(local), AVStr(remote),AVStr(opts)); if( isWindows() || SENDFD_OVERTCP ){ rsock = clsock; sscanf(respudp,"pid=%d",&cpid); }else{ rsock = UDP_client_open("BIND/sudo","sendfd",respudp,1); sv1log("==SU rsock=%d %s\n",rsock,respudp); if( rsock < 0 ){ return -1; } } port = 0; Xsscanf(local,"%[^:]:%d",AVStr(host),&port); fd = newSocket("BIND/sudo",""); bindSock(fd,"BIND/SUDO",-1,AVStr(host),port,32); sendFd(rsock,fd,cpid); if( isWindows() ){ }else{ close(rsock); } getpairName(fd,AVStr(local),AVStr(remote)); close(fd); sv1log("==SU BOUND %d %s %s\n",fd,local,remote); /* SendTo(clsock,"OK\r\n",4,clhost,clport); */ IGNRETP write(clsock,"OK\r\n",4); sv1log("==SU returned OK\n"); return 0; }
// renyang - 開始接收對方的資料 // renyang - socket代表client端的socket file descriptor // renyang - proto可能是IHU_TCP或IHU_UDP // renyang-TODO - 要加入IHU_SCTP的部分 void Receiver::start(int socket, int proto) { #ifdef REN_DEBUG qWarning(QString("Receiver::start(int %1, int %2)").arg(socket).arg(proto));; #endif s = socket; protocol = proto; // renyang - 連線之後, 可以取得對方的sockaddr_in資料 // renyang - 由socket取得對方的struct sockaddr // renyang - 此s代表client端的socket file descriptor ::getpeername(s, (struct sockaddr *)&ca, &calen); // renyang-modify - 記錄目前的primary primaddr = ::inet_ntoa(ca.sin_addr); // renyang - 設定sync的型態為STREAM_READ_DATA, 並streamPtr回到起始位址(streamBuffer) resetStream(); // renyang - 設定ihu_refuse, ihu_reply, ihu_abort, connected,...為false reset(); // renayng - working=ture, 表示正在響鈴 go(); // renyang - 新增一個QSocketNotifier, 當有資料可以讀時, emit activated() // renyang - 用來判斷對方是否有傳資料進來 notifier = new QSocketNotifier(s, QSocketNotifier::Read, this); // renyang - activated(int)其參數是表示哪一個socket file descriptor被觸發 // renyang - 表示client端有傳送資料過來 // renyang - 每格一段時間接收一次資料 connect(notifier,SIGNAL(activated(int)),this, SLOT(receive())); // renyang - 因為tcp所接收到的第一個資料是connection,所以,不需要 // renyang - 但是, udp所接收到的第一個資料就是資料啦, 所以要比tcp多接收一次 // renyang - 只有waitCalls端才要執行received的程式 if (received) { // renyang - 若是udp的話, 則直接開始接收資料, 因udp只要是有資料送過來就直接接收@@@ switch(protocol) { case IHU_UDP: // renyang - 因為是connection-less的關係, 所以先接收第一筆資料??? receive(); break; } // renyang - 不論是tcp或是udp均會處理目前的函式 // renyang - 把這一個socket, protocol, ca送到Transmitter, 讓Transmitter可以傳送資料, 給peer端 // renyang - 只有當是waitCalls才會建立一個Transmitter的一個socket用來傳送資料 // renyang - ca在IHU_SCTP用不到 emit newSocket(s, protocol, ca); } // renyang - 開始倒數計時, false表示timeout一次, 就呼叫timeout()一次 checkTimer->start(CHECK_TICKTIME, false); }
/* connection function for GenFDC */ static Socket *genfdcConnect(Socket *self) { SocketGenFDC *sockc = (SocketGenFDC *) self; SocketGenFD *ret; int fd, tmpi; /* make the return */ ret = (SocketGenFD *) newSocket(sizeof(SocketGenFD)); ret->ssuper.ssuper.vtbl = &genfdVTbl; newSocketWritable(&ret->ssuper, sockc->outfd); ret->infd = sockc->infd; return (Socket *) ret; }
RequestResult<const std::string> StreamSession::namingLookup(const std::string& name) const { typedef RequestResult<const std::string> ResultType; typedef Message::Answer<const std::string> AnswerType; std::auto_ptr<Socket> newSocket(new Socket(socket_)); const AnswerType answer = namingLookup(*newSocket, name); switch(answer.status) { case Message::OK: return ResultType(answer.value); case Message::EMPTY_ANSWER: case Message::CLOSED_SOCKET: fallSick(); break; default: break; } return ResultType(); }
RequestResult<const FullDestination> StreamSession::destGenerate() const { typedef RequestResult<const FullDestination> ResultType; typedef Message::Answer<const FullDestination> AnswerType; std::auto_ptr<Socket> newSocket(new Socket(socket_)); const AnswerType answer = destGenerate(*newSocket); switch(answer.status) { case Message::OK: return ResultType(answer.value); case Message::EMPTY_ANSWER: case Message::CLOSED_SOCKET: fallSick(); break; default: break; } return ResultType(); }
/* create a new named GenFDC */ static Socket *newGenFDC(char **saveptr) { SocketGenFDC *ret; char *ins, *outs; int infd, outfd; int tmpi; /* get the in and out FDs */ ins = strtok_r(NULL, ":", saveptr); if (ins == NULL) return NULL; outs = strtok_r(NULL, "", saveptr); if (outs == NULL) return NULL; /* make the return */ ret = (SocketGenFDC *) newSocket(sizeof(SocketGenFDC)); ret->ssuper.vtbl = &genfdcVTbl; ret->infd = atoi(ins); ret->outfd = atoi(ins); return (Socket *) ret; }
static int sftpsv(int port,PCStr(host),PVStr(lhost)){ int acsk,svsk,lport,lports; VSAddr vsa; lport = SERVER_PORT() + 1; lports = (lport<<16) | (lport+32); strcpy(lhost,"127.0.0.1"); VSA_atosa(&vsa,0,lhost); acsk = newSocket("sftp",""); if( BindSocket(acsk,&vsa,lports) != 0 ){ BindSocket(acsk,&vsa,0); } lport = sockPort(acsk); listen(acsk,1); svsk = connect_to_sv(MainConn(),"sftp",host,port); sfsv_acsock = acsk; sfsv_svsock = svsk; SftpTid = thread_fork(0x80000,0,"sftpsv1",(IFUNCP)sftpsv1,acsk,svsk); sv1log("-Esf %d/%d %d/%d %X\n",lport,acsk,sockPort(svsk),svsk,SftpTid); return lport; }
/* create a new named UNIXC */ static Socket *newUNIXC(char **saveptr) { SocketUNIXC *ret; char *path; struct sockaddr_un *sun; /* get the path */ path = strtok_r(NULL, "", saveptr); /* make the return */ ret = (SocketUNIXC *) newSocket(sizeof(SocketUNIXC)); ret->ssuper.vtbl = &unixcVTbl; SF(sun, malloc, NULL, (sizeof(struct sockaddr_un))); sun->sun_family = AF_UNIX; strncpy(sun->sun_path, path, sizeof(sun->sun_path)); ret->addr = (struct sockaddr *) sun; ret->addrlen = sizeof(*sun); return (Socket *) ret; }
/* connection function for UNIXC */ static Socket *unixcConnect(Socket *self) { SocketUNIXC *sockc = (SocketUNIXC *) self; SocketUNIX *ret; int fd, tmpi; /* make the socket */ SF(fd, socket, -1, (AF_UNIX, SOCK_STREAM, 0)); tmpi = connect(fd, sockc->addr, sockc->addrlen); if (tmpi < 0) { close(fd); return NULL; } /* then make the return */ ret = (SocketUNIX *) newSocket(sizeof(SocketUNIX)); newSocketWritable(ret, fd); ret->ssuper.vtbl = &unixVTbl; return (Socket *) ret; }
RequestResult<void> StreamSession::forward(const std::string& host, uint16_t port, bool silent) { typedef RequestResult<void> ResultType; std::auto_ptr<Socket> newSocket(new Socket(socket_)); const Message::eStatus status = forward(*newSocket, sessionID_, host, port, silent); switch(status) { case Message::OK: forwardedStreams_.push_back(ForwardedStream(newSocket.get(), host, port, silent)); newSocket.release(); // release after successful push_back only return ResultType(true); case Message::EMPTY_ANSWER: case Message::CLOSED_SOCKET: case Message::INVALID_ID: case Message::I2P_ERROR: fallSick(); break; default: break; } return ResultType(); }
int conectarASwap(t_log * logger){ int retorno; int fdMemoria = newSocket(); conectarSocket(fdMemoria,vg_ip_swap,vg_puerto_swap); char * login = strdup("MEM"); enviarPorSocket(fdMemoria, (char*) login, 4); free(login); void * buffer = malloc(sizeof(int)); recibirPorSocket(fdMemoria, buffer, sizeof(int)); int numeroRecv = *((int *) buffer); if(numeroRecv == 1){ printf("[OK] Conexión entre Swap y Memoria aceptada mediante el puerto %d\n",vg_puerto_swap); log_info(logger,"Conexión Swap - Memoria aceptada mediante el puerto %d\n",vg_puerto_swap); retorno = fdMemoria; } if(numeroRecv == 0){ printf("[ERROR] Se espera conexión del proceso memoria\n"); retorno = 0; } return retorno; }
void NetChannel::reconfigure(const NetConfig& config) { _config = config; newSocket(); }
int TcpManager::SendTcpMsg(int msgType,int socketid, unsigned int ip,unsigned short port,void* data,int dataSize) { unique_lock<mutex> lock(m_socketMapMutex); shared_ptr<TcpSocket> target; auto it = m_socketMap.begin(); if(socketid != -1) { it = m_socketMap.find(socketid); } else { for(; it != m_socketMap.end(); it++) { if(it->second->m_destIp ==ip && it ->second->m_destPort == port) { target = it->second; break; } } } if(msgType == TCPMSG_CONNECT) { if( it != m_socketMap.end() ) { LOG_ERROR<<"TcpManager 申请的连接已存在"; return -1; } shared_ptr<TcpSocket> newSocket(new TcpSocket); if( target->Connect(ip,port) == -1 ) { return -1; } m_socketMap[newSocket->m_socket] = newSocket; epoll_event ev; ev.data.fd =newSocket->m_socket; ev.events=EPOLLIN; if(m_epoll != -1 && epoll_ctl(m_epoll,EPOLL_CTL_ADD,newSocket->m_socket,&ev) <0) { LOG_ERROR<<"TcpManager 无法加入epoll"; return -1 ; } return newSocket->m_socket; } else if(msgType == TCPMSG_DISCONNECT) { if(it == m_socketMap.end()) { return -1; } CloseSocket(it->second->m_socket); return it->second->m_socket; } else if(msgType ==TCPMSG_SEND) { if(it == m_socketMap.end()) { return -1; } int send_count = it->second ->SendData(data,dataSize); if(send_count == 0 ) //发送缓冲区不够用了 { //注册一个发送监听 epoll_event ev; ev.data.fd =it->second->m_socket; ev.events=EPOLLIN |EPOLLOUT; if(epoll_ctl(m_epoll,EPOLL_CTL_MOD,it->second->m_socket,&ev) == -1) { LOG_INFO<<"epoll_ctl error in EPOLL_CTL_MOD"; return -1; } } return it->second->m_socket; } return -1; }
void MprSocket::acceptProc(int isMprPoolThread) { MprSocket *nsp; MprSocketService *ss; #if BLD_FEATURE_IPV6 struct sockaddr_storage addr6; char hbuf[NI_MAXHOST]; char sbuf[NI_MAXSERV]; int rc; #endif struct sockaddr_in addr; struct sockaddr *sa; char callerIpAddr[MPR_MAX_IP_ADDR]; MprSocklen addrlen; int fd, max, numClients; if (acceptCallback == 0) { return; } lock(); #if BLD_FEATURE_IPV6 if (ipv6) { sa = (struct sockaddr*) &addr6; addrlen = sizeof(addr6); } else #endif { sa = (struct sockaddr*) &addr; addrlen = sizeof(addr); } fd = accept(sock, sa, (SocketLenPtr) &addrlen); if (fd < 0) { mprLog(0, log, "%d: acceptProc: accept failed %d\n", sock, getError()); unlock(); return; } #if !WIN && !WINCE && !VXWORKS fcntl(fd, F_SETFD, FD_CLOEXEC); // Prevent children inheriting #endif ss = mprGetMpr()->socketService; max = ss->getMaxClients(); numClients = ss->getNumClients(); if (max > 0 && numClients >= max) { mprLog(3, "Rejecting connection, too many client connections (%d)\n", numClients); #if CYGWIN || LINUX || MACOSX || SOLARIS || VXWORKS || FREEBSD shutdown(fd, MPR_SHUTDOWN_BOTH); #endif ::closesocket(fd); mprGetMpr()->selectService->awaken(0); unlock(); return; } nsp = newSocket(); nsp->lock(); nsp->sock = fd; nsp->ipAddr = mprStrdup(ipAddr); nsp->acceptData = acceptData; nsp->ioData = ioData; nsp->ioData2 = ioData2; nsp->port = port; nsp->acceptCallback = acceptCallback; nsp->flags = flags; nsp->flags &= ~MPR_SOCKET_LISTENER; nsp->setBlockingMode((nsp->flags & MPR_SOCKET_BLOCK) ? 1: 0); if (nsp->flags & MPR_SOCKET_NODELAY) { nsp->setNoDelay(1); } nsp->inUse++; mprLog(6, log, "%d: acceptProc: isMprPoolThread %d, newSock %d\n", sock, isMprPoolThread, fd); nsp->unlock(); // // Call the user accept callback. // #if BLD_FEATURE_IPV6 if (ipv6) { rc = getnameinfo(sa, addrlen, hbuf, sizeof(hbuf), sbuf, sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV); if (rc) { mprError(MPR_L, MPR_LOG, "Exiting acceptProc with failed getnameinfo"); delete nsp; return; } (nsp->acceptCallback)(nsp->acceptData, nsp, hbuf, atoi(sbuf), this, isMprPoolThread); } else #endif { mprInetNtoa(callerIpAddr, sizeof(callerIpAddr), addr.sin_addr); (nsp->acceptCallback)(nsp->acceptData, nsp, callerIpAddr, ntohs(addr.sin_port), this, isMprPoolThread); } nsp->lock(); if (--nsp->inUse == 0 && nsp->flags & MPR_SOCKET_DISPOSED) { mprLog(9, log, "%d: acceptProc: Leaving deleted\n", sock); delete nsp; } else{ nsp->unlock(); } unlock(); }
int sudo_main(int ac,const char *av[],Connection *Conn){ int ai; const char *arg; int sock; int sendfd = 0; int sockfd = fileno(stderr); const char *optpw = 0; IStr(local,128); IStr(remote,128); CStr(opts,128); IStr(host,128); int port = 0; if( ac <= 1 ){ fprintf(stderr,"Usage: %s [host:port] [-a d:u:p] [-b h:p]\n", av[0]); return 0; } sprintf(host,"%s/sudo/sudo/port/P",DELEGATE_DGROOT); port = 1; for( ai = 1; ai < ac; ai++ ){ arg = av[ai]; if( streq(arg,"-a") ){ if( ai+1 < ac ){ arg = av[++ai]; optpw = arg; } }else if( streq(arg,"-b") ){ if( ai+1 < ac ){ arg = av[++ai]; sendfd = 1; sockfd = newSocket("BIND/test",""); strcpy(opts,arg); } }else if( streq(arg,"-d") ){ sendfd = 1; }else{ Xsscanf(arg,"%[^:]:%d",AVStr(host),&port); } } set_realserver(Conn,"sudo",host,port); Conn->from_myself = 1; sock = connect_to_serv(Conn,0,1,0); if( sock < 0 ){ sock = client_open_un("SUDO",host,32); if( sock < 0 ){ fprintf(stderr,"---- cannot open '%s:%d'\n",host,port); return -1; } } if( optpw ){ int wcc,rcc; CStr(msg,128); sprintf(msg,"PAM %s\r\n",optpw); wcc = write(sock,msg,strlen(msg)); PollIn(sock,8*1000); rcc = read(sock,msg,sizeof(msg)); fprintf(stderr,"---- %s\n",msg); } if( sendfd ){ CStr(msg,128); int wcc; double Start = Time(); if( sockfd == fileno(stderr) ) sprintf(msg,"STDERR\r\n"); else sprintf(msg,"BIND %s\r\n",opts); fprintf(stderr,"---- command BIND sockfd=%d ==> %d\n",sockfd,sock); wcc = write(sock,msg,strlen(msg)); /* fprintf(stderr,"---- sending sockfd=%d ==> %d\n",sockfd,usock); wcc = sendFd(usock,sockfd,0); */ PollIn(sock,8*1000); getpairName(sockfd,AVStr(local),AVStr(remote)); fprintf(stderr,"---- SUDO %s SENT=%d [%.3f] sock=%d [%s][%s]\n", msg,wcc,Time()-Start,sockfd,local,remote); } return 0; }