int DNS::getSocket( const LogSink& logInstance ) { #if defined( _WIN32 ) && !defined( __SYMBIAN32__ ) WSADATA wsaData; if( WSAStartup( MAKEWORD( 1, 1 ), &wsaData ) != 0 ) { logInstance.dbg( LogAreaClassDns, "WSAStartup() failed. WSAGetLastError: " + util::int2string( ::WSAGetLastError() ) ); return -ConnDnsError; } #endif int protocol = IPPROTO_TCP; #if !defined( __APPLE__ ) // Sandboxing on Apple doesn't like you to use getprotobyname struct protoent* prot; if( ( prot = getprotobyname( "tcp" ) ) != 0 ) { protocol = prot->p_proto; } else { std::string message = "getprotobyname( \"tcp\" ) failed. " #if defined( _WIN32 ) && !defined( __SYMBIAN32__ ) "WSAGetLastError: " + util::int2string( ::WSAGetLastError() ) #else "errno: " + util::int2string( errno ) + ": " + strerror( errno ); #endif + ". Falling back to IPPROTO_TCP: " + util::int2string( IPPROTO_TCP ); logInstance.dbg( LogAreaClassDns, message ); // Do not return an error. We'll fall back to IPPROTO_TCP. } #endif // !defined( __APPLE__ ) return getSocket( PF_INET, SOCK_STREAM, protocol, logInstance ); }
void check_sockets(void) { socket_internal_t *current_socket; uint8_t i = 1; while (i < MAX_SOCKETS+1) { current_socket = getSocket(i); if(isTCPSocket(i)) { switch (current_socket->socket_values.tcp_control.state) { case ESTABLISHED: { handle_established(current_socket); break; } case SYN_SENT: { handle_synchro_timeout(current_socket); break; } case SYN_RCVD: { handle_synchro_timeout(current_socket); break; } default: { break; } } } i++; } }
void Socket::Close() { uv_close((uv_handle_t*) getSocket(), on_close); }
bool Socket_TCP::connectTo(const char * hostname, uint16_t port, uint32_t timeout) { char servport[32]; int rc; struct in6_addr serveraddr; struct addrinfo hints, *res=NULL; memset(&hints, 0x00, sizeof(hints)); #ifdef _WIN32 hints.ai_flags = 0; #else hints.ai_flags = AI_NUMERICSERV; #endif hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; rc = inet_pton(AF_INET, hostname, &serveraddr); if (rc == 1) { hints.ai_family = AF_INET; hints.ai_flags |= AI_NUMERICHOST; } else { rc = inet_pton(AF_INET6, hostname, &serveraddr); if (rc == 1) { hints.ai_family = AF_INET6; hints.ai_flags |= AI_NUMERICHOST; } } snprintf(servport,32,"%u",port); rc = getaddrinfo(hostname, servport, &hints, &res); if (rc != 0) { // Host not found. lastError = "Error resolving hostname"; return false; } bool connected = false; for (struct addrinfo *resiter=res; resiter && !connected; resiter = resiter->ai_next) { if (getSocket() >=0 ) closeSocket(); setSocket(socket(res->ai_family, res->ai_socktype, res->ai_protocol)); if (!isValidSocket()) { lastError = "socket() failed"; break; } // Set the read timeout here. (to zero) setReadTimeout(0); if (internalConnect(getSocket(),resiter->ai_addr, resiter->ai_addrlen,timeout)) { // now it's connected... if (PostConnectSubInitialization()) { connected = true; } else { // should disconnect here. shutdownSocket(); // drop the socket descriptor. we don't need it anymore. closeSocket(); } break; } else { // drop the current socket... (and free the resource :)) shutdownSocket(); closeSocket(); } } freeaddrinfo(res); if (!connected) { lastError = "connect() failed"; return false; } return true; }
ClientSocket::ClientSocket() { //uv_tcp_init(loop, getSocket()); getSocket()->data = this; }
static int acceptSocketConnection ( int (*getSocket) (void), int (*prepareQueue) (int socket), void (*unbindAddress) (const struct sockaddr *address), const struct sockaddr *localAddress, socklen_t localSize, struct sockaddr *remoteAddress, socklen_t *remoteSize ) { int serverSocket = -1; int queueSocket; if ((queueSocket = getSocket()) != -1) { if (!prepareQueue || prepareQueue(queueSocket)) { if (bind(queueSocket, localAddress, localSize) != -1) { if (listen(queueSocket, 1) != -1) { int attempts = 0; { char *address = formatSocketAddress(localAddress); if (address) { logMessage(LOG_NOTICE, "listening on: %s", address); free(address); } } while (1) { fd_set readMask; struct timeval timeout; FD_ZERO(&readMask); FD_SET(queueSocket, &readMask); memset(&timeout, 0, sizeof(timeout)); timeout.tv_sec = 10; ++attempts; switch (select(queueSocket+1, &readMask, NULL, NULL, &timeout)) { case -1: if (errno == EINTR) continue; LogSocketError("select"); break; case 0: logMessage(LOG_DEBUG, "no connection yet, still waiting (%d).", attempts); continue; default: { if (!FD_ISSET(queueSocket, &readMask)) continue; if ((serverSocket = accept(queueSocket, remoteAddress, remoteSize)) != -1) { char *address = formatSocketAddress(remoteAddress); if (address) { logMessage(LOG_NOTICE, "client is: %s", address); free(address); } } else { LogSocketError("accept"); } } } break; } } else { LogSocketError("listen"); } if (unbindAddress) unbindAddress(localAddress); } else { LogSocketError("bind"); } } close(queueSocket); } else { LogSocketError("socket"); } operations = &socketOperationsEntry; return serverSocket; }
void init_tcp_server(void) { sockaddr6_t stSockAddr; int read_bytes; char buff_msg[MAX_TCP_BUFFER]; memset(buff_msg, 0, MAX_TCP_BUFFER); int SocketFD = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP); if(-1 == SocketFD) { perror("can not create socket"); exit(EXIT_FAILURE); } memset(&stSockAddr, 0, sizeof(stSockAddr)); stSockAddr.sin6_family = AF_INET6; stSockAddr.sin6_port = HTONS(1100); ipv6_init_address(&stSockAddr.sin6_addr, 0xabcd, 0x0, 0x0, 0x0, 0x3612, 0x00ff, 0xfe00, get_radio_address()); ipv6_print_addr(&stSockAddr.sin6_addr); if(-1 == bind(SocketFD, &stSockAddr, sizeof(stSockAddr))) { printf("error bind failed\n"); close(SocketFD); return; } print_internal_socket(getSocket(SocketFD)); if(-1 == listen(SocketFD, 10)) { printf("error listen failed\n"); close(SocketFD); return; } while (1) { read_bytes = 0; printf("INFO: WAITING FOR INC CONNECTIONS!\n"); int ConnectFD = accept(SocketFD, NULL, 0); if(0 > ConnectFD) { printf("error accept failed\n"); close(SocketFD); return; } else { printf("Connection established on socket %u.\n", ConnectFD); if (running_recv_threads == 0) { recv_socket_id1 = ConnectFD; thread_create(recv_from_tcp_thread_stack1, RECV_FROM_TCP_THREAD_STACK_SIZE1, PRIORITY_MAIN, CREATE_STACKTEST, recv_from_tcp_thread1, "recv_from_tcp_thread1"); } else if (running_recv_threads == 1) { recv_socket_id2 = ConnectFD; thread_create(recv_from_tcp_thread_stack2, RECV_FROM_TCP_THREAD_STACK_SIZE2, PRIORITY_MAIN, CREATE_STACKTEST, recv_from_tcp_thread2, "recv_from_tcp_thread2"); } running_recv_threads++; } } }
void UnityConnection::readyRead() { if(!sender()) return; qDebug() << this << " readyRead " << getSocket(); getSocket()->write("haha"); }
void SecureSocket::checkResult(int status, int& retry) { // ssl errors are a little quirky. the "want" errors are normal and // should result in a retry. int errorCode = SSL_get_error(m_ssl->m_ssl, status); switch (errorCode) { case SSL_ERROR_NONE: retry = 0; // operation completed break; case SSL_ERROR_ZERO_RETURN: // connection closed isFatal(true); LOG((CLOG_DEBUG "ssl connection closed")); break; case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_CONNECT: case SSL_ERROR_WANT_ACCEPT: // it seems like these sort of errors are part of openssl's normal behavior, // so we should expect a very high amount of these. sleeping doesn't seem to // help... maybe you just have to swallow the errors (yuck). retry++; LOG((CLOG_DEBUG2 "passive ssl error, error=%d, attempt=%d", errorCode, retry)); break; case SSL_ERROR_SYSCALL: LOG((CLOG_ERR "ssl error occurred (system call failure)")); if (ERR_peek_error() == 0) { if (status == 0) { LOG((CLOG_ERR "eof violates ssl protocol")); } else if (status == -1) { // underlying socket I/O reproted an error try { ARCH->throwErrorOnSocket(getSocket()); } catch (XArchNetwork& e) { LOG((CLOG_ERR "%s", e.what())); } } } isFatal(true); break; case SSL_ERROR_SSL: LOG((CLOG_ERR "ssl error occurred (generic failure)")); isFatal(true); break; default: LOG((CLOG_ERR "ssl error occurred (unknown failure)")); isFatal(true); break; } // If the retry max would exceed the allowed, treat it as a fatal error if (retry > maxRetry()) { LOG((CLOG_ERR "passive ssl error limit exceeded: %d", retry)); isFatal(true); } if (isFatal()) { retry = 0; showError(); disconnect(); } }
void CEchoSrvDataChannel::OnSend(char* buff, int& len) { CDataChannelSocket::OnSend(buff, len); if (len > 0) g_globals.m_logger.WriteFormated("CEchoSrvDataChannel::OnSend sock = %d len = %d", getSocket(), len); }
/*------------------------------------------------------------------------------ * Log in to the IceCast server *----------------------------------------------------------------------------*/ bool IceCast :: sendLogin ( void ) throw ( Exception ) { Sink * sink = getSink(); Source * source = getSocket(); const char * str; char resp[STRBUF_SIZE]; unsigned int len; if ( !source->isOpen() ) { return false; } if ( !sink->isOpen() ) { return false; } /* send the request, a string like: * "SOURCE <password> /<mountpoint>\n" */ str = "SOURCE "; sink->write( str, strlen( str)); str = getPassword(); sink->write( str, strlen( str)); str = " /"; sink->write( str, strlen( str)); str = getMountPoint(); sink->write( str, strlen( str)); /* send the x-audiocast headers */ str = "\nx-audiocast-bitrate: "; sink->write( str, strlen( str)); if ( log10(getBitRate()) >= (STRBUF_SIZE-2) ) { throw Exception( __FILE__, __LINE__, "bitrate does not fit string buffer", getBitRate()); } sprintf( resp, "%d", getBitRate()); sink->write( resp, strlen( resp)); str = "\nx-audiocast-public: "; sink->write( str, strlen( str)); str = getIsPublic() ? "1" : "0"; sink->write( str, strlen( str)); if ( getName() ) { str = "\nx-audiocast-name: "; sink->write( str, strlen( str)); str = getName(); sink->write( str, strlen( str)); } if ( getDescription() ) { str = "\nx-audiocast-description: "; sink->write( str, strlen( str)); str = getDescription(); sink->write( str, strlen( str)); } if ( getUrl() ) { str = "\nx-audiocast-url: "; sink->write( str, strlen( str)); str = getUrl(); sink->write( str, strlen( str)); } if ( getGenre() ) { str = "\nx-audiocast-genre: "; sink->write( str, strlen( str)); str = getGenre(); sink->write( str, strlen( str)); } if ( getRemoteDumpFile() ) { str = "\nx-audiocast-dumpfile: "; sink->write( str, strlen( str)); str = getRemoteDumpFile(); sink->write( str, strlen( str)); } str = "\n\n"; sink->write( str, strlen( str)); sink->flush(); /* read the anticipated response: "OK" */ len = source->read( resp, STRBUF_SIZE); if ( len < 2 || resp[0] != 'O' || resp[1] != 'K' ) { return false; } /* suck anything that the other side has to say */ while ( source->canRead( 0, 0) && (len = source->read( resp, STRBUF_SIZE)) ) { ; } return true; }
void GameState::init() { QAbstractSocket::SocketState state = getSocket()->state(); QObject::connect(getSocket().data(), SIGNAL(readyRead()), this, SLOT(readyReadHandler())); }
void GameState::abort() { getSocket()->disconnectFromHost(); moveIntoState(getStateCollection()->getNoConnectionState()); }
void UnityConnection::error(QAbstractSocket::SocketError socketError) { if(!sender()) return; qDebug() << this << " error " << getSocket() << " error = " << socketError; }
void UnityConnection::stateChanged(QAbstractSocket::SocketState socketState) { if(!sender()) return; qDebug() << this << " socket state " << getSocket() << " state = " << socketState; }
void UnityConnection::bytesWritten(qint64 bytes) { if(!sender()) return; qDebug() << this << " bytes written " << getSocket() << " number of bytes " << bytes; }
int ServerSendMessage( int *msgid, char *server, int op, int *retstatus, int *conid_out, void (*ast)(), void *astparam, void (*before_ast)(), int numargs_in, ...) { static unsigned int addr = 0; short port; int conid; int flags = 0; int status = ServerPATH_DOWN; int jobid; int i; if (StartReceiver(&port) && ((conid = ServerConnect(server)) >= 0)) { char cmd[4096]; unsigned char numargs = max(0,min(numargs_in,8)); unsigned char idx = 0; char dtype; short len; char ndims; int dims[8]; int numbytes; int *dptr; va_list vlist; void *mem=0; struct descrip *arg; if (conid_out) *conid_out = conid; if (addr == 0) { int sock=getSocket(conid); struct sockaddr_in addr_struct; unsigned int len=sizeof(addr_struct); if (getsockname(sock,(struct sockaddr *)&addr_struct,&len) == 0) addr = *(int *)&addr_struct.sin_addr; } if (addr) jobid = RegisterJob(msgid,retstatus,ast,astparam,before_ast,conid); if (before_ast) flags |= SrvJobBEFORE_NOTIFY; sprintf(cmd,"MdsServerShr->ServerQAction(%d,%dwu,%d,%d,%d",addr,port,op,flags,jobid); va_start(vlist,numargs_in); for (i=0;i<numargs;i++) { strcat(cmd,","); arg = va_arg(vlist,struct descrip *); if (op == SrvMonitor && numargs == 8 && i == 5 && arg->dtype == DTYPE_LONG && *(int *)arg->ptr == MonitorCheckin) MonJob = jobid; switch(arg->dtype) { case DTYPE_CSTRING: { int j; int k; char *c = (char *)arg->ptr; int len = strlen(c); strcat(cmd,"\""); for (j=0,k=strlen(cmd);j<len;j++,k++) { if (c[j] == '"' || c[j] == '\\') cmd[k++]='\\'; cmd[k]=c[j]; } cmd[k]=0; strcat(cmd,"\""); break; } case DTYPE_LONG: sprintf(&cmd[strlen(cmd)],"%d",*(int *)arg->ptr); break; case DTYPE_CHAR: sprintf(&cmd[strlen(cmd)],"%d",(int)*(char *)arg->ptr); break; default: printf("shouldn't get here! ServerSendMessage dtype = %d\n",arg->dtype); } } strcat(cmd,")"); SndArgChk(conid, idx++, DTYPE_CSTRING, 1, (short)strlen(cmd), 0, 0, cmd); status = GetAnswerInfoTS(conid, &dtype, &len, &ndims, dims, &numbytes, (void **)&dptr, &mem); if (mem) free(mem); if (!addr) { if (retstatus) *retstatus = status; if (ast) (*ast)(astparam,"Job Done"); } }
void WaitingForPlayerConnectionState::abort() { disconnect(getSocket().data(), SIGNAL(connected()), this, SIGNAL(connectedHandler())); getSocket()->abort(); moveIntoState(getStateCollection()->getNoConnectionState()); }
int HttpGetCommand::execute(int argc, char* argv[]) { int commandStatus = CommandProcessor::COMMAND_FAILED; if(argc == 2) { commandStatus = CommandProcessor::COMMAND_SUCCESS; const char* url = argv[1]; const char* serverBegin = strstr(url, "http://"); if(serverBegin != url) { printf("unsupported protocol in Url: %s\n", url); commandStatus = CommandProcessor::COMMAND_BAD_SYNTAX; } else { serverBegin += 7; UtlString uri(serverBegin); int serverEndIndex = uri.index("/"); if(serverEndIndex < 0) serverEndIndex = uri.length(); if(serverEndIndex > 0) { UtlString server = uri; server.remove(serverEndIndex); int portIndex = server.index(":"); int port = PORT_NONE; if(portIndex > 0) { UtlString portString = server; server.remove(portIndex); portString.remove(0, portIndex + 1); printf("port string: %s\n", portString.data()); port = atoi(portString.data()); } uri.remove(0, serverEndIndex); if(uri.isNull()) uri = "/"; printf("HTTP get of %s from server %s port: %d\n", uri.data(), server.data(), port); if (!portIsValid(port)) { port = 80; printf("defaulting to http port 80\n"); } OsConnectionSocket getSocket(port, server.data()); HttpMessage getRequest; getRequest.setFirstHeaderLine("GET", uri.data(), HTTP_PROTOCOL_VERSION); int wroteBytes = getRequest.write(&getSocket); printf("wrote %d\n", wroteBytes); HttpMessage getResponse; getResponse.read(&getSocket); UtlString responseBytes; int responseLength; getResponse.getBytes(&responseBytes, &responseLength); printf("Got %d bytes\n", responseLength); printf("Response: ++++++++++++++++++++++++++++++++++\n%s\n", responseBytes.data()); } else { printf("invalid server in Url: %s\n", url); commandStatus = CommandProcessor::COMMAND_BAD_SYNTAX; } } } else { UtlString usage; getUsage(argv[0], &usage); printf("%s", usage.data()); commandStatus = CommandProcessor::COMMAND_BAD_SYNTAX; //commandStatus = CommandProcessor::COMMAND_FAILED; } return(commandStatus); }
void UnityConnection::disconnected() { if(!sender()) return; qDebug() << this << " disconnected " << getSocket(); }
/////////////////////////////////////////////////////////////////////////////// // // MAIN // /////////////////////////////////////////////////////////////////////////////// int main(int argc, char *argv[]) { // Обработка сигнала struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = handleSigInt; sigaction(SIGINT, &act, 0); // Проверка количества аргументов if (argc < 4) { fprintf(stderr, "Too few arguments\n"); exit(EXIT_FAILURE); } // Количество потоков - 1й параметр запуска int numberOfWorkers = atoi(argv[1]); // Порт - 2й параметр запуска char port[4]; strcpy(port, argv[2]); // Путь к файлу с паролями - 3й параметр запуска readPasswordsFromFile(argv[3]); // Инициализация connections memset(connections, 0, sizeof(connections)); struct addrinfo* addresses = getAvailableAddresses(port); if (!addresses) exit(EXIT_FAILURE); // Получаем дескриптор сокета int _socketfd = getSocket(addresses); if (_socketfd == -1) { exit(EXIT_FAILURE); } setSocketFd(_socketfd); // Начинаем слушать сокет if (listen(socketfd, SOMAXCONN) == -1) { perror("listen\n"); exit(EXIT_FAILURE); } // Создаём потоки pthread_t workers[numberOfWorkers]; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex, &mutexattr); pthread_mutex_init(&connectionsMutex, &mutexattr); pthread_cond_t condition; pthread_cond_init(&condition, NULL); // Создаём отдельный поток для отслеживания таймаута соединений pthread_t timeoutWatcher; pthread_create(&timeoutWatcher, NULL, watchTimeout, NULL); // Создаём очередь struct Queue queue; initQueue(&queue, sizeof(struct epoll_event)); struct WorkerArgs workerArgs; initWorkerArgs(&workerArgs, &queue, &mutex, &condition); for (int i = 0; i < sizeof(workers) / sizeof(pthread_t); i++) { pthread_create(&workers[i], NULL, worker, (void *) &workerArgs); } // Создаём epoll int _epollfd = epoll_create1(0); if (_epollfd == -1) { perror("epoll_create error\n"); exit(EXIT_FAILURE); } setEpollFd(_epollfd); // Добавляем сокет в epoll if (addToEpoll(epollfd, socketfd, EPOLLET | EPOLLIN) == -1) exit(EXIT_FAILURE); int maxEventNum = numberOfWorkers; struct epoll_event events[maxEventNum]; int timeout = -1; printf("Main thread: %d\n", (int)pthread_self()); while(!done) { int eventsNumber = epoll_wait(epollfd, events, maxEventNum, timeout); if (!eventsNumber) printf("No events\n"); for (int i = 0; i < eventsNumber; i++) { pthread_mutex_lock(&mutex); pushQueue(&queue, &events[i]); pthread_cond_signal(&condition); pthread_mutex_unlock(&mutex); } } // Освобождение ресурсов pthread_mutex_destroy(&connectionsMutex); pthread_mutex_destroy(&mutex); pthread_mutexattr_destroy(&mutexattr); free(passPairs); destroyQueue(&queue); close(socketfd); close(epollfd); printf("DONE!!!"); return 0; }
TcpSocket* TcpSocket::doBind() { if(bind(getSocket(),(sockaddr *)getAddr(),sizeof(sockaddr_in)) == SOCKET_ERROR) throw NetworkException("bind", errno); return this; }
void WaitingForPlayerConnectionState::init() { QObject::connect(getSocket().data(), SIGNAL(connected()), this, SLOT(connectedHandler())); QObject::connect(getSocket().data(), SIGNAL(error(QAbstractSocket::SocketError)), SLOT(errorHandler(QAbstractSocket::SocketError))); }
void DebuggerThriftBuffer::flushImpl(const String& data) { TRACE(7, "DebuggerThriftBuffer::flushImpl\n"); getSocket()->write(data); }
/*------------------------------------------------------------------------------ * Log in to the IceCast2 server *----------------------------------------------------------------------------*/ bool IceCast2 :: sendLogin ( void ) throw ( Exception ) { Sink * sink = getSink(); Source * source = getSocket(); const char * str; char resp[STRBUF_SIZE]; unsigned int len; unsigned int lenExpected; if ( !source->isOpen() ) { return false; } if ( !sink->isOpen() ) { return false; } // send the request, a string like: // "SOURCE <mountpoint> ICE/1.0" str = "SOURCE /"; sink->write( str, strlen( str)); str = getMountPoint(); sink->write( str, strlen( str)); str = " HTTP/1.0"; sink->write( str, strlen( str)); // send the content type, Ogg Vorbis str = "\nContent-type: "; sink->write( str, strlen( str)); switch ( format ) { case mp3: str = "audio/mpeg"; break; case oggVorbis: str = "application/x-ogg"; break; default: throw Exception( __FILE__, __LINE__, "unsupported stream format", format); break; } sink->write( str, strlen( str)); // send the authentication info str = "\nAuthorization: Basic "; sink->write( str, strlen(str)); { // send source:<password> encoded as base64 char * source = "source:"; const char * pwd = getPassword(); char * tmp = new char[Util::strLen(source) + Util::strLen(pwd) + 1]; Util::strCpy( tmp, source); Util::strCat( tmp, pwd); char * base64 = Util::base64Encode( tmp); delete[] tmp; sink->write( base64, strlen(base64)); delete[] base64; } // send user agent info str = "\nUser-Agent: DarkIce/" VERSION " (http://darkice.sourceforge.net/)"; sink->write( str, strlen( str)); // send the ice- headers str = "\nice-bitrate: "; sink->write( str, strlen( str)); if ( log10(getBitRate()) >= (STRBUF_SIZE-2) ) { throw Exception( __FILE__, __LINE__, "bitrate does not fit string buffer", getBitRate()); } sprintf( resp, "%d", getBitRate()); sink->write( resp, strlen( resp)); str = "\nice-public: "; sink->write( str, strlen( str)); str = getIsPublic() ? "1" : "0"; sink->write( str, strlen( str)); if ( getName() ) { str = "\nice-name: "; sink->write( str, strlen( str)); str = getName(); sink->write( str, strlen( str)); } if ( getDescription() ) { str = "\nice-description: "; sink->write( str, strlen( str)); str = getDescription(); sink->write( str, strlen( str)); } if ( getUrl() ) { str = "\nice-url: "; sink->write( str, strlen( str)); str = getUrl(); sink->write( str, strlen( str)); } if ( getGenre() ) { str = "\nice-genre: "; sink->write( str, strlen( str)); str = getGenre(); sink->write( str, strlen( str)); } str = "\n\n"; sink->write( str, strlen( str)); sink->flush(); // read the response, expected response begins with responseOK lenExpected = Util::strLen( responseOK); if ( (len = source->read( resp, STRBUF_SIZE-1)) < lenExpected ) { return false; } resp[lenExpected] = 0; if ( !Util::strEq( resp, responseOK) ) { return false; } // suck anything that the other side has to say while ( source->canRead( 0, 0) && (len = source->read( resp, STRBUF_SIZE-1)) ); return true; }
void SecureSocket::checkResult(int status, int& retry) { // ssl errors are a little quirky. the "want" errors are normal and // should result in a retry. int errorCode = SSL_get_error(m_ssl->m_ssl, status); switch (errorCode) { case SSL_ERROR_NONE: retry = 0; // operation completed break; case SSL_ERROR_ZERO_RETURN: // connection closed isFatal(true); LOG((CLOG_DEBUG "ssl connection closed")); break; case SSL_ERROR_WANT_READ: retry++; LOG((CLOG_DEBUG2 "want to read, error=%d, attempt=%d", errorCode, retry)); break; case SSL_ERROR_WANT_WRITE: // Need to make sure the socket is known to be writable so the impending // select action actually triggers on a write. This isn't necessary for // m_readable because the socket logic is always readable m_writable = true; retry++; LOG((CLOG_DEBUG2 "want to write, error=%d, attempt=%d", errorCode, retry)); break; case SSL_ERROR_WANT_CONNECT: retry++; LOG((CLOG_DEBUG2 "want to connect, error=%d, attempt=%d", errorCode, retry)); break; case SSL_ERROR_WANT_ACCEPT: retry++; LOG((CLOG_DEBUG2 "want to accept, error=%d, attempt=%d", errorCode, retry)); break; case SSL_ERROR_SYSCALL: LOG((CLOG_ERR "ssl error occurred (system call failure)")); if (ERR_peek_error() == 0) { if (status == 0) { LOG((CLOG_ERR "eof violates ssl protocol")); } else if (status == -1) { // underlying socket I/O reproted an error try { ARCH->throwErrorOnSocket(getSocket()); } catch (XArchNetwork& e) { LOG((CLOG_ERR "%s", e.what())); } } } isFatal(true); break; case SSL_ERROR_SSL: LOG((CLOG_ERR "ssl error occurred (generic failure)")); isFatal(true); break; default: LOG((CLOG_ERR "ssl error occurred (unknown failure)")); isFatal(true); break; } if (isFatal()) { retry = 0; showError(); disconnect(); } }
void NoeudThor::traitementDeLaTrame(Trame &t, Client<NoeudThor> *noeudSource) { if (noeudSource == noeudSecureNodeListProvider){ switch (t.getTTL()) { case -2: { cout << "On a recu la liste d'ip:portd'écoute des autres clients" << std::endl; list<pair <string, int> > ipPortEveryBody; std::istringstream iStringStream(t.getCommande()); boost::archive::text_iarchive iTextArchive(iStringStream); iTextArchive >> ipPortEveryBody; bool found; for(pair <string, int> trucl : ipPortEveryBody){ found=false; for (auto it = toutlemonde.begin(); it != toutlemonde.end() && found!=true; it++){ if ((*it)->getIpStr() == trucl.first && (*it)->getPort() == trucl.second){ cout << "nous somme déjà connectés à ce client (" << trucl.first << ":" << trucl.second << ")" << std::endl; found = true; } } if (found == false){ cout << "On était pas connecté donc on se connecte" << std::endl; auto cli = new Client<NoeudThor>(this, io_service); tcp::endpoint endpoint(boost::asio::ip::address::from_string(trucl.first), trucl.second); cli->getSocket().connect(endpoint); cli->startRead(); toutlemonde.push_front(cli); } cout << "IT : " << trucl.first << std::endl; cout << "Port : " << trucl.second << std::endl; } cout << "Enregistrement des différents noeuds effectué" << std::endl; break; } case -3: { cout << "On a recu le nombre de Noeuds du réseau" << std::endl; int nombre; sscanf(t.getCommande().c_str(), "%d", &nombre); cout << "Il y a " << nombre << "noeuds sur le réseau." << std::endl; break; } case -4: { cout << "On a recu nos voisins" << std::endl; list<pair <string, int> > ipPortVoisins; std::istringstream iStringStream(t.getCommande()); boost::archive::text_iarchive iTextArchive(iStringStream); iTextArchive >> ipPortVoisins; bool next=false; for(pair <string, int> trucl : ipPortVoisins){ for (auto it = toutlemonde.begin(); it != toutlemonde.end(); it++){ if ((*it)->getIpStr() == trucl.first && (*it)->getPort() == trucl.second){ if (next == false){ this->previous=(*it); next = true; } else { this->next=(*it); } } } } cout << "Enregistrement des voisins effectué" << std::endl; break; } default: { break; } } } else if(noeudSource == noeudServeurCentral){
void __CFReadStreamClientCallBack(CFReadStreamRef stream, CFStreamEventType eventType, void *clientCallBackInfo) { // Extract the context tnet_transport_t *transport = (tnet_transport_t *) clientCallBackInfo; transport_context_t *context = transport->context; /* lock context */ tsk_safeobj_lock(context); // Extract the native socket CFDataRef data = CFReadStreamCopyProperty(stream, kCFStreamPropertySocketNativeHandle); CFSocketNativeHandle fd; CFDataGetBytes(data, CFRangeMake(0, sizeof(CFSocketNativeHandle)), (UInt8*) &fd); CFRelease(data); transport_socket_t *sock = (transport_socket_t *) getSocket(context, fd); switch(eventType) { case kCFStreamEventOpenCompleted: { TSK_DEBUG_INFO("__CFReadStreamClientCallBack --> kCFStreamEventOpenCompleted"); break; } case kCFStreamEventHasBytesAvailable: { tsk_size_t len = 0; void *buffer = 0; tnet_transport_event_t* e; // Allocate a standard buffer len = TNET_BUFFER_SIZE; if (!(buffer = tsk_calloc(len, sizeof(uint8_t)))) { TSK_DEBUG_ERROR("TSK_CALLOC FAILED."); break; } // Process to read data CFIndex index = CFReadStreamRead(stream, buffer, TNET_BUFFER_SIZE); len = index; TSK_DEBUG_INFO("__CFReadStreamClientCallBack --> %u bytes read", len); e = tnet_transport_event_create(event_data, transport->callback_data, sock->fd); e->data = buffer; e->size = len; TSK_RUNNABLE_ENQUEUE_OBJECT(TSK_RUNNABLE(transport), e); break; } case kCFStreamEventEndEncountered: case kCFStreamEventErrorOccurred: { // Get the error code CFErrorRef error = CFReadStreamCopyError(stream); CFIndex index = CFErrorGetCode(error); CFRelease(error); TSK_DEBUG_INFO("__CFReadStreamClientCallBack --> Error %lu", index); TSK_RUNNABLE_ENQUEUE(transport, event_error, transport->callback_data, sock->fd); removeSocket(sock, context); break; } default: { // Not Implemented assert(42 == 0); break; } } /* unlock context */ tsk_safeobj_unlock(context); }
/** @brief Send ping-request to the specified peer and receive ping-reply from the specified peer. @return 1 - success, 0 - fail because free socket is not found or can't be opened. */ uint8_t ping( uint8_t count, /**< Ping request count. */ uint16_t time, /**< wait ping reply time (unit : ms) */ uint8_t* addr, /**< Peer IP Address string in dotted decimal format */ PING_LOG* log /**< result of ping */ ) { PING_MSG* pPingRequest; // pointer for Ping Request PING_MSG* pPingReply; // pointer for Ping Reply uint32_t peerip; // 32 bit Peer IP Address uint32_t tempip; // IP address received from a destination uint16_t port; // port number received from a destination SOCKET s; // socket variable for pinging uint16_t RandomSeqNum; // Ping-Request ID uint16_t len; uint8_t IsReceived; // Received packet = 1, not received packet = 0 portTickType xInitialTick; /* Initialise PingRequest */ if( !(pPingRequest = (PING_MSG *) pvPortMalloc( sizeof(PING_MSG) ))) return 0; if( !(pPingReply = (PING_MSG *) pvPortMalloc( sizeof(PING_MSG) ))) { vPortFree(pPingRequest); return 0; } RandomSeqNum = htons( (uint16_t)rand()); // set ping-request's sequence number to random integer value pPingRequest->type = 0x08; // Ping-Request - ICMP pPingRequest->code = 0x00; // always 0 pPingRequest->checksum = 0; // value of checksum before calculating checksum of ping-request packet pPingRequest->id = htons(PING_ID); // set ping-request ID for(uint16_t i = 0 ; i < PING_OPT_LEN; i++) pPingRequest->OPT[i] = 'a' + i % 23; // fill 'a'~'w' characters into ping-request's data /* Initialise result of ping */ memset((void*)log,0,sizeof(PING_LOG)); /* Verify arguments */ if(!count) count = 4; // set count to default value (4 pings) if(!time) time = 1000; // set response time to default value (1000ms) /* Create a ping socket */ s = getSocket(SOCK_CLOSED,0); if(s == MAX_SOCK_NUM) // if it isn't exist free socket, Error { vPortFree(pPingRequest); vPortFree(pPingReply); return 0; } setSn_PROTO(s,IP_PROTO_ICMP); // Set upper-protocol of IP protocol if( socket( s, Sn_MR_IPRAW, 3000, 0) == 0) // Open IP_RAW Mode , if fail then Error { vPortFree(pPingRequest); vPortFree(pPingReply); return 0; } peerip = htonl( inet_addr(addr)); // convert address string into 32bit address xSerialPrintf_P(PSTR("\r\nPinging %s with %d bytes of data:\r\n"), addr, (sizeof(PING_MSG) - 8)); /* Ping Service */ while( count-- != 0) { IsReceived = 0; pPingRequest->seqNum = htons( RandomSeqNum++); // Increase Sequence number for next ping-request packet pPingRequest->checksum = 0; pPingRequest->checksum = htons( checksum( (uint8_t*)pPingRequest, sizeof(PING_MSG))); // update checksum field (*log).PingRequest++; // Increase PingRequest's value xInitialTick = xTaskGetTickCount(); if( sendto( s, (const uint8_t *)pPingRequest, sizeof(PING_MSG), (uint8_t*)&peerip, 3000)== 0) // Send Ping-Request to the specified peer. If fail, then it is occurred ARP Error. { (*log).ARPErr++; // Increase ARPErr close(s); // close the pinging socket /* Reopen pinging socket */ setSn_PROTO(s,IP_PROTO_ICMP); if(socket( s, Sn_MR_IPRAW, 3000, 0)==0) { vPortFree(pPingRequest); vPortFree(pPingReply); return 0; } continue; } while( xTaskGetTickCount() < (xInitialTick + ( time / portTICK_RATE_MS )) ) // as long as time is remaining { if((len = getSn_RX_RSR(s)) > 0) // Has pinging socket received a packet? { len = recvfrom( s, (uint8_t*)pPingReply, len, (uint8_t*)&tempip, &port); // receive a packet from unknown peer xSerialPrintf_P(PSTR("\r\nReply from %s"), inet_ntoa( ntohl(tempip))); // convert 32 bit unknown peer IP address into string of IP Address. if( checksum((uint8_t*)pPingReply,len) != 0) // if the packet's checksum value is correct { // not correct (*log).CheckSumErr++; // checksum error if(tempip == peerip) IsReceived = 1; xSerialPrint_P(PSTR(": Checksum Error")); } else if(pPingReply->type == 0) // if the received packet is ping-reply { if((pPingReply->id!=pPingRequest->id) || (pPingReply->seqNum!=pPingRequest->seqNum) || (tempip!=peerip)) // verify id,sequence nubmer, and ip address { xSerialPrint_P(PSTR(": Unmatched ID / SeqNum from peer")); // fail to verify (*log).UnknownMSG++; } else // success { IsReceived = 1; xSerialPrintf_P(PSTR(": bytes=%d, time<=%dms"),len-8,(xTaskGetTickCount()-xInitialTick)*portTICK_RATE_MS ); (*log).PingReply++; } } else if( pPingReply->type == 3) // If the packet is unreachable message { IsReceived = 1; xSerialPrint_P(PSTR(": Destination unreachable")); (*log).UnreachableMSG++; } else if( pPingReply->type == 11) // If the packet is time exceeded message { IsReceived = 1; xSerialPrint_P(PSTR(": TTL expired in transit")); (*log).TimeExceedMSG++; } else if( pPingReply->type == 8) // Send ping reply to a peer { xSerialPrint_P(PSTR(": Ping Request message")); SendPingReply(pPingReply,tempip); } else // if the packet is unknown message { xSerialPrintf_P(PSTR(": Unknown message (type = 0x%02X)"), pPingReply->type); (*log).UnknownMSG++; } } else if(getSn_SR(s)==SOCK_CLOSED) // if it is occurred to fail to send arp packet { (*log).ARPErr++; close(s); // close the pinging socket setSn_PROTO( s, IP_PROTO_ICMP); // reopen the pinging socket if(socket( s, Sn_MR_IPRAW, 3000, 0) == 0 ) { vPortFree(pPingRequest); vPortFree(pPingReply); return 0; } break; } if((xTaskGetTickCount() >= (xInitialTick + ( time / portTICK_RATE_MS ))) && (IsReceived == 0)) // If it is not received packet from the specified peer during waiting ping-reply packet. { (*log).Loss++; xSerialPrint_P(PSTR("Request timed out\r\n")); } } } /* Release pinging socket */ setSn_PROTO(s,0); close(s); vPortFree(pPingRequest); vPortFree(pPingReply); return 1; }
void __CFSocketCallBack(CFSocketRef s, CFSocketCallBackType callbackType, CFDataRef address, const void *data, void *info) { // Extract the context tnet_transport_t *transport = (tnet_transport_t *) info; transport_context_t *context = transport->context; // Extract the native socket int fd = CFSocketGetNative(s); transport_socket_t *sock = (transport_socket_t *) getSocket(context, fd); /* lock context */ tsk_safeobj_lock(context); switch (callbackType) { case kCFSocketReadCallBack: { int ret; tsk_size_t len = 0; void* buffer = 0; tnet_transport_event_t* e; if (tnet_ioctlt(sock->fd, FIONREAD, &len) < 0) { TNET_PRINT_LAST_ERROR("IOCTLT FAILED."); break; } if (!len) { TSK_DEBUG_WARN("IOCTLT returned zero."); TSK_RUNNABLE_ENQUEUE(transport, event_closed, transport->callback_data, sock->fd); removeSocket(sock, context); break; } if (!(buffer = tsk_calloc(len, sizeof(uint8_t)))) { TSK_DEBUG_ERROR("TSK_CALLOC FAILED."); break; } if ((ret = tnet_sockfd_recv(sock->fd, buffer, len, 0)) < 0) { TSK_FREE(buffer); removeSocket(sock, context); TNET_PRINT_LAST_ERROR("recv have failed."); break; } else if ((len != (tsk_size_t)ret) && len) { // useless test ? len = (tsk_size_t)ret; // buffer = tsk_realloc(buffer, len); } TSK_DEBUG_INFO("__CFSocketCallBack -> %u bytes read", len); e = tnet_transport_event_create(event_data, transport->callback_data, sock->fd); e->data = buffer; e->size = len; TSK_RUNNABLE_ENQUEUE_OBJECT(TSK_RUNNABLE(transport), e); break; } case kCFSocketAcceptCallBack: case kCFSocketConnectCallBack: case kCFSocketDataCallBack: case kCFSocketWriteCallBack: default: { // Not Implemented assert(42 == 0); break; } } /* unlock context */ tsk_safeobj_unlock(context); }