dtn::data::Bundle Client::getBundle(const dtn::data::Timeout timeout) throw (ConnectionException) { try { return _inqueue.getnpop(true, timeout * 1000); } catch (const ibrcommon::QueueUnblockedException &ex) { if (ex.reason == ibrcommon::QueueUnblockedException::QUEUE_TIMEOUT) { throw ConnectionTimeoutException(); } else if (ex.reason == ibrcommon::QueueUnblockedException::QUEUE_ABORT) { throw ConnectionAbortedException(ex.what()); } throw ConnectionException(ex.what()); } catch (const std::exception &ex) { throw ConnectionException(ex.what()); } throw ConnectionException(); }
ULXR_API_IMPL(void) TcpIpConnection::ServerSocketData::shutdown(int in_mode) { ULXR_TRACE(ULXR_PCHAR("shutdown") << in_mode); int ret; do ret = ::shutdown(socket_no, in_mode); while(ret < 0 && (errno == EINTR || errno == EAGAIN)); if(ret < 0) throw ConnectionException(TransportError, ULXR_PCHAR("shutdown() failed for TcpIpConnection::ServerSocketData"), 500); }
ULXR_API_IMPL(void) HttpClient::filePUT(const CppString &filename, const CppString &type, const CppString &resource) { ULXR_TRACE(ULXR_PCHAR("filePUT")); if (!protocol->isOpen() ) protocol->open(); FILE *ifs = fopen (getLatin1(filename).c_str(), "rb"); if (ifs == 0) throw Exception(SystemError, ulxr_i18n(ULXR_PCHAR("Cannot open file: "))+filename); struct stat statbuf; if (0 != stat (getLatin1(filename).c_str(), &statbuf) ) throw Exception(SystemError, ulxr_i18n(ULXR_PCHAR("Could not get information about file: "))+filename); sendAuthentication(); protocol->sendRequestHeader(ULXR_PCHAR("PUT"), resource, type, statbuf.st_size); char buffer [ULXR_SEND_BUFFER_SIZE]; long readed; try { while (!feof(ifs)) { readed = fread(buffer, 1, sizeof(buffer), ifs); if (readed < 0) throw Exception(SystemError, ulxr_i18n(ULXR_PCHAR("Could not read from file: "))+filename); protocol->writeBody(buffer, readed); } } catch (...) { fclose(ifs); throw; } // bool eof_reached = feof(ifs); fclose(ifs); BodyProcessor bp; receiveResponse(bp); if (getHttpStatus() != 200) throw ConnectionException(TransportError, getHttpPhrase(), getHttpStatus()); if (!protocol->isPersistent() ) protocol->close(); }
ULXR_API_IMPL0 TcpIpConnection::TcpIpConnection(bool I_am_server, long adr, unsigned prt) : Connection() , pimpl(new PImpl) { ULXR_TRACE(ULXR_PCHAR("TcpIpConnection(bool, long, uint)") << adr << ULXR_PCHAR(" ") << pimpl->port); init(prt); pimpl->hostdata.sin_addr.s_addr = htonl(adr); if (I_am_server) { pimpl->server_data = new ServerSocketData(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); if (getServerHandle() < 0) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not create socket: ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); #ifdef ULXR_REUSE_SOCKET int sockOpt = 1; if (::setsockopt(getServerHandle(), SOL_SOCKET, SO_REUSEADDR, (const char*)&sockOpt, sizeof(sockOpt)) < 0) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not set reuse flag for socket: ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); #endif int iOptVal = getTimeout() * 1000; int iOptLen = sizeof(int); ::setsockopt(getServerHandle(), SOL_SOCKET, SO_RCVTIMEO, (char*)&iOptVal, iOptLen); ::setsockopt(getServerHandle(), SOL_SOCKET, SO_SNDTIMEO, (char*)&iOptVal, iOptLen); if((::bind(getServerHandle(), (sockaddr*) &pimpl->hostdata, sizeof(pimpl->hostdata))) < 0) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not bind adress: ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); ::listen(getServerHandle(), 5); } }
void SessionHandle::query(const char* str) { int res = mysql_real_query(h, str, static_cast<unsigned long>(std::strlen(str))); if (res != 0) { std::string msg; msg += "mysql_real_query('"; msg += str; msg += "') error"; throw ConnectionException(msg, h); } }
Connection::Connection(const std::string &dsn, const std::string &userName, const std::string &password) : Env(new Environment) , ConnHldr(0) { std::auto_ptr<ConnectionHolder> NewConnHldr(new ConnectionHolder(*Env.get())); SQLRETURN Ret = SQLConnect(NewConnHldr->GetHandle(), const_cast<SQLCHAR *>(reinterpret_cast<const SQLTCHAR *>(dsn.c_str())), SQL_NTS, !userName.empty() ? const_cast<SQLCHAR *>(reinterpret_cast<const SQLCHAR *>(userName.c_str())) : 0, SQL_NTS, !password.empty() ? const_cast<SQLCHAR *>(reinterpret_cast<const SQLCHAR *>(password.c_str())) : 0, SQL_NTS); if (Ret != SQL_SUCCESS) throw ConnectionException(GetLastDBError(SQL_HANDLE_DBC, NewConnHldr->GetHandle()), ceErrorConnect); ConnHldr = NewConnHldr.release(); }
ULXR_API_IMPL(void) TcpIpConnection::asciiToInAddr(const char *address, struct in_addr &saddr) { memset (&saddr, 0, sizeof(in_addr)); struct hostent *host; /* First try it as aaa.bbb.ccc.ddd. */ saddr.s_addr = inet_addr(address); if ((int)saddr.s_addr == -1) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not perform inet_addr(): ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); #ifndef ULXR_OMIT_REENTRANT_PROTECTOR Mutex::Locker lock(gethostbynameMutex); #endif host = gethostbyname(address); if (host == 0) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not perform gethostbyname(): ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); memmove((void*)&saddr, host->h_addr_list, sizeof(in_addr)); }
int SessionImpl::maxStatementLength() { SQLUINTEGER info; SQLRETURN rc = 0; if (Utility::isError(rc = Poco::Data::ODBC::SQLGetInfo(_db, SQL_MAXIMUM_STATEMENT_LENGTH, (SQLPOINTER) &info, 0, 0))) { throw ConnectionException(_db, "SQLGetInfo(SQL_MAXIMUM_STATEMENT_LENGTH)"); } return info; }
bool Spammer::sendMail() { if (!smtp.connectToHost()) { throw ConnectionException(); } if (auth) { if (!smtp.login(user, password)) throw AuthenticationException(); } if (!smtp.sendMail(message)) { throw SendMailException(); } else { smtp.quit(); } return true; }
ULXR_API_IMPL(void) TcpIpConnection::ServerSocketData::close() { ULXR_TRACE(ULXR_PCHAR("close")); #ifndef __unix__ ::closesocket(socket_no); #else int ret; do ret = ::close(socket_no); while(ret < 0 && (errno == EINTR || errno == EAGAIN)); if(ret < 0) throw ConnectionException(TransportError, ULXR_PCHAR("close() failed for TcpIpConnection::ServerSocketData"), 500); #endif socket_no = -1; }
ULXR_API_IMPL(void) HttpClient::doDELETE(const CppString &resource) { ULXR_TRACE(ULXR_PCHAR("doDELETE")); if (!protocol->isOpen() ) protocol->open(); sendAuthentication(); protocol->sendRequestHeader(ULXR_PCHAR("DELETE"), resource, ULXR_PCHAR(""), 0); BodyProcessor bp; receiveResponse(bp); if (getHttpStatus() != 200) throw ConnectionException(TransportError, getHttpPhrase(), getHttpStatus()); if (!protocol->isPersistent() ) protocol->close(); }
ULXR_API_IMPL(Cpp8BitString) HttpClient::msgGET(const CppString &resource) { ULXR_TRACE(ULXR_PCHAR("msgGET")); Cpp8BitString ret; if (!protocol->isOpen() ) protocol->open(); sendAuthentication(); protocol->sendRequestHeader(ULXR_PCHAR("GET"), resource, ULXR_PCHAR(""), 0); StringProcessor sp (ret); receiveResponse(sp); if (getHttpStatus() != 200) throw ConnectionException(TransportError, getHttpPhrase(), getHttpStatus()); if (!protocol->isPersistent() ) protocol->close(); return ret; }
/** * Connect to the Mumble server via the ICE protocl and initialize a Meta class * which is then * returned. This meta class can be used to further examine the data on the * server, such as enumerating * servers. */ Murmur::MetaPrx MumbleCollector::connect() { auto props = Ice::createProperties(); props->setProperty("Ice.ImplicitContext", "Shared"); Ice::InitializationData idata; idata.properties = props; this->ice = Ice::initialize(idata); if (this->secret.size() > 0) { this->ice->getImplicitContext()->put("secret", this->secret); } auto obj = this->ice->stringToProxy(this->connectStr()); auto meta = Murmur::MetaPrx::checkedCast(obj); if (!meta) { throw ConnectionException(); } return meta; }
LibeventServer::LibeventServer() { base_ = event_base_new(); // Create our event base if (!base_) { throw ConnectionException("Couldn't open event base"); } // Add hang up signal event ev_stop_ = evsignal_new(base_, SIGHUP, ControlCallback::Signal_Callback, base_); evsignal_add(ev_stop_, NULL); // Add timeout event to check server's start/close flag every one second struct timeval one_seconds = {1, 0}; ev_timeout_ = event_new(base_, -1, EV_TIMEOUT | EV_PERSIST, ControlCallback::ServerControl_Callback, this); event_add(ev_timeout_, &one_seconds); // a master thread is responsible for coordinating worker threads. master_thread_ = std::make_shared<LibeventMasterThread>(CONNECTION_THREAD_COUNT, base_); port_ = FLAGS_port; max_connections_ = FLAGS_max_connections; private_key_file_ = FLAGS_private_key_file; certificate_file_ = FLAGS_certificate_file; // For logging purposes // event_enable_debug_mode(); // event_set_log_callback(LogCallback); // Commented because it's not in the libevent version we're using // When we upgrade this should be uncommented // event_enable_debug_logging(EVENT_DBG_ALL); // Ignore the broken pipe signal // We don't want to exit on write when the client disconnects signal(SIGPIPE, SIG_IGN); }
//---------------------------------------------------------------- bool SelectServer::WaitForClient(ClientVector& waitClientVec) throw(ConnectionException&) { int nReady; bool ret = false; waitClientVec.clear(); mCurSet = mInitSet; for(ClientVectorIter iter = mClientConnVec.begin(); iter!=mClientConnVec.end(); ++iter){ FD_SET(iter->GetSockfd(), &mCurSet); } /*only care read event*/ nReady = select(mMaxSockfd+1, &mCurSet, NULL, NULL, NULL); if(nReady == 0) return false;/*no new client*/ else if(nReady < 0){ throw ConnectionException("Error : select error\n"); } //check for listen socket if(FD_ISSET(mListenConn.GetSockfd(), &mCurSet)){/*new client in*/ ConnectionIPV4 cliConn ; if(mListenConn.AcceptClient(cliConn) == true){/*ignore error in accept*/ AddNewClient(cliConn); waitClientVec.push_back(cliConn); mMaxSockfd = mClientConnVec[mClientConnVec.size() - 1].GetSockfd(); ret = true; } --nReady; } //check for other socket for(ClientVectorIter iter = mClientConnVec.begin(); iter!=mClientConnVec.end() && nReady > 0; ++iter){ if(FD_ISSET(iter->GetSockfd(), &mCurSet)){ waitClientVec.push_back(*iter); --nReady; } } return ret; }
ULXR_API_IMPL(void) HttpClient::fileGET(const CppString &filename, const CppString &resource) { ULXR_TRACE(ULXR_PCHAR("fileGET")); if (!protocol->isOpen() ) protocol->open(); std::ofstream ofs (getLatin1(filename).c_str(), std::ios::out | std::ios::binary); if (!ofs.good() ) throw Exception(SystemError, ulxr_i18n(ULXR_PCHAR("Cannot create file: "))+filename); sendAuthentication(); protocol->sendRequestHeader(ULXR_PCHAR("GET"), resource, ULXR_PCHAR(""), 0); FileProcessor fp(ofs, filename); receiveResponse(fp); if (getHttpStatus() != 200) throw ConnectionException(TransportError, getHttpPhrase(), getHttpStatus()); if (!protocol->isPersistent() ) protocol->close(); }
ULXR_API_IMPL(void) HttpClient::msgPUT(const Cpp8BitString &msg, const CppString &type, const CppString &resource) { ULXR_TRACE(ULXR_PCHAR("msgPUT")); if (!protocol->isOpen() ) protocol->open(); sendAuthentication(); protocol->sendRequestHeader(ULXR_PCHAR("PUT"), resource, type, msg.length()); #ifdef ULXR_USE_WXSTRING protocol->writeBody(msg.data(), msg.length()); #else protocol->writeBody(msg.data(), msg.length()); #endif BodyProcessor bp; receiveResponse(bp); if (getHttpStatus() != 200) throw ConnectionException(TransportError, getHttpPhrase(), getHttpStatus()); if (!protocol->isPersistent() ) protocol->close(); }
Requester::waitForResponse(Protocol *protocol, bool wbxml_mode) { ULXR_TRACE(ULXR_PCHAR("waitForResponse(Protocol, wbxml)")); char buffer[ULXR_RECV_BUFFER_SIZE]; char *buff_ptr; std::auto_ptr<XmlParserBase> parser; MethodResponseParserBase *rpb = 0; if (wbxml_mode) { ULXR_TRACE(ULXR_PCHAR("waitForResponse in WBXML")); MethodResponseParserWb *rp = new MethodResponseParserWb(); rpb = rp; #ifdef _MSC_VER std::auto_ptr<XmlParserBase> temp(rp); parser = temp; #else parser.reset(rp); #endif } else { ULXR_TRACE(ULXR_PCHAR("waitForResponse in XML")); MethodResponseParser *rp = new MethodResponseParser(); rpb = rp; #ifdef _MSC_VER std::auto_ptr<XmlParserBase> temp(rp); parser = temp; #else parser.reset(rp); #endif } bool done = false; long readed; while (!done && protocol->hasBytesToRead() && ((readed = protocol->readRaw(buffer, sizeof(buffer))) > 0) ) { buff_ptr = buffer; while (readed > 0) { Protocol::State state = protocol->connectionMachine(buff_ptr, readed); if (state == Protocol::ConnError) { done = true; throw ConnectionException(TransportError, ulxr_i18n(ULXR_PCHAR("network problem occured")), 400); } else if (state == Protocol::ConnSwitchToBody) { #ifdef ULXR_SHOW_READ Cpp8BitString super_data (buff_ptr, readed); while ((readed = protocol->readRaw(buffer, sizeof(buffer))) > 0) super_data.append(buffer, readed); ULXR_DOUT_READ(ULXR_PCHAR("superdata 3 start:\n")); if (wbxml_mode) { ULXR_DOUT_READ(binaryDebugOutput(super_data)); } else { ULXR_DOUT_READ(ULXR_GET_STRING(super_data)); } ULXR_DOUT_READ(ULXR_PCHAR("superdata 3 end:\n") ); #endif if (!protocol->hasBytesToRead()) { throw ConnectionException(NotConformingError, ulxr_i18n(ULXR_PCHAR("Content-Length of message not available")), 411); } CppString s; if (!protocol->responseStatus(s)) throw ConnectionException(TransportError, s, 500); } else if (state == Protocol::ConnBody) { ULXR_DOUT_XML(ULXR_GET_STRING(std::string(buff_ptr, readed))); if (!parser->parse(buff_ptr, readed, false)) { throw XmlException(parser->mapToFaultCode(parser->getErrorCode()), ulxr_i18n(ULXR_PCHAR("Problem while parsing xml response")), parser->getCurrentLineNumber(), ULXR_GET_STRING(parser->getErrorString(parser->getErrorCode()))); } readed = 0; } } if (!protocol->hasBytesToRead()) // || parser->isComplete()) done = true; } if (protocol->isOpen() && !protocol->isPersistent() ) protocol->close(); return rpb->getMethodResponse(); }
void LibeventServer::StartServer() { if (FLAGS_socket_family == "AF_INET") { struct sockaddr_in sin; PL_MEMSET(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(port_); int listen_fd; listen_fd = socket(AF_INET, SOCK_STREAM, 0); if (listen_fd < 0) { throw ConnectionException("Failed to create listen socket"); } int conn_backlog = 12; int reuse = 1; setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); /* Initialize SSL listener connection */ SSL_load_error_strings(); SSL_library_init(); if ((ssl_context = SSL_CTX_new(TLSv1_server_method())) == nullptr) { throw ConnectionException("Error creating SSL context."); } LOG_INFO("private key file path %s", private_key_file_.c_str()); /* * Temporarily commented to pass tests START // register private key if (SSL_CTX_use_PrivateKey_file(ssl_context, private_key_file_.c_str(), SSL_FILETYPE_PEM) == 0) { SSL_CTX_free(ssl_context); throw ConnectionException("Error associating private key.\n"); } LOG_INFO("certificate file path %s", certificate_file_.c_str()); // register public key (certificate) if (SSL_CTX_use_certificate_file(ssl_context, certificate_file_.c_str(), SSL_FILETYPE_PEM) == 0) { SSL_CTX_free(ssl_context); throw ConnectionException("Error associating certificate.\n"); } * Temporarily commented to pass tests END */ if (bind(listen_fd, (struct sockaddr *) &sin, sizeof(sin)) < 0) { SSL_CTX_free(ssl_context); throw ConnectionException("Failed binding socket."); } if (listen(listen_fd, conn_backlog) < 0) { SSL_CTX_free(ssl_context); throw ConnectionException("Error listening onsocket."); } master_thread_->Start(); LibeventServer::CreateNewConn(listen_fd, EV_READ | EV_PERSIST, master_thread_.get(), CONN_LISTENING); LOG_INFO("Listening on port %llu", (unsigned long long) port_); event_base_dispatch(base_); LibeventServer::GetConn(listen_fd)->CloseSocket(); // Free events and event base event_free(LibeventServer::GetConn(listen_fd)->event); event_free(ev_stop_); event_free(ev_timeout_); event_base_free(base_); master_thread_->Stop(); LOG_INFO("Server Closed"); } // This socket family code is not implemented yet else { throw ConnectionException("Unsupported socket family"); } }
MethodCall Dispatcher::waitForCall(int _timeout) { ULXR_TRACE("waitForCall"); if (!protocol->isOpen()) { if (!protocol->accept(_timeout)) return MethodCall(); // // @todo throw exception? } else protocol->resetConnection(); char buffer[ULXR_RECV_BUFFER_SIZE]; char *buff_ptr; std::auto_ptr<XmlParserBase> parser; MethodCallParserBase *cpb = 0; ULXR_TRACE("waitForCall in XML"); MethodCallParser *cp = new MethodCallParser(); cpb = cp; parser.reset(cp); bool done = false; long myRead; while (!done && ((myRead = protocol->readRaw(buffer, sizeof(buffer))) > 0) ) { buff_ptr = buffer; while (myRead > 0) { Protocol::State state = protocol->connectionMachine(buff_ptr, myRead); if (state == Protocol::ConnError) throw ConnectionException(TransportError, "network problem occured", 500); else if (state == Protocol::ConnSwitchToBody) { if (!protocol->hasBytesToRead()) { #ifdef ULXR_SHOW_READ std::string super_data(buff_ptr, myRead); while ((myRead = protocol->readRaw(buffer, sizeof(buffer))) > 0) super_data.append(buffer, myRead); ULXR_DOUT_READ("superdata 1 start:\n" << super_data << "superdata 1 end:\n"); #endif throw ConnectionException(NotConformingError, "Content-Length of message not available", 411); } } else if (state == Protocol::ConnBody) { ULXR_DOUT_XML(std::string(buff_ptr, myRead)); if (!parser->parse(buff_ptr, myRead, done)) { ULXR_DOUT("errline: " << parser->getCurrentLineNumber()); ULXR_DWRITE(buff_ptr, myRead); ULXR_DOUT("") ; throw XmlException(parser->mapToFaultCode(parser->getErrorCode()), "Problem while parsing xml request", parser->getCurrentLineNumber(), parser->getErrorString(parser->getErrorCode())); } myRead = 0; } } if (!protocol->hasBytesToRead()) // || parser->isComplete()) done = true; } ULXR_TRACE("waitForCall got " << cpb->getMethodCall().getXml()); return cpb->getMethodCall(); }
ULXR_API_IMPL(void) TcpIpConnection::init(unsigned prt) { ULXR_TRACE(ULXR_PCHAR("init")); #if defined(__WIN32__) && !defined (ULXR_NO_WSA_STARTUP) WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD( 2, 0 ); if (WSAStartup( wVersionRequested, &wsaData) != 0) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not initialize Windows sockets: ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); #endif pimpl->server_data = 0; setTcpNoDelay(false); pimpl->serverdomain = ULXR_PCHAR(""); pimpl->remote_name = ULXR_PCHAR(""); setTimeout(10); pimpl->port = prt; pimpl->hostdata_len = sizeof(pimpl->hostdata); pimpl->remotedata_len = sizeof(pimpl->remotedata); memset(&pimpl->hostdata, 0, sizeof(pimpl->hostdata)); memset(&pimpl->remotedata, 0, sizeof(pimpl->remotedata)); pimpl->hostdata.sin_port = htons(pimpl->port); pimpl->hostdata.sin_family = AF_INET; char buffer [1000]; memset(buffer, 0, sizeof(buffer)); int ret = gethostname(buffer, sizeof(buffer)-1); if (ret != 0) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not get host name: ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); pimpl->host_name = ULXR_GET_STRING(buffer); #if defined(__SUN__) long status = sysinfo(SI_SRPC_DOMAIN ,buffer, sizeof(buffer)-1); if (status == -1) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not get domain name: ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); if (buffer[0] != 0) { pimpl->host_name += ULXR_PCHAR("."); pimpl->host_name += ULXR_GET_STRING(buffer); } #elif defined(__unix__) || defined(__CYGWIN__) ret = getdomainname(buffer, sizeof(buffer)-1); if (ret != 0) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not get domain name: ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); if (buffer[0] != 0) { pimpl->host_name += ULXR_PCHAR("."); pimpl->host_name += ULXR_GET_STRING(buffer); } #elif _WIN32 #ifndef ULXR_OMIT_REENTRANT_PROTECTOR Mutex::Locker lock(gethostbynameMutex); #endif struct hostent *hostEntPtr = gethostbyname(getLatin1(pimpl->host_name).c_str()); if (!hostEntPtr) throw ConnectionException(SystemError, ulxr_i18n(ULXR_PCHAR("Could not get host+domain name: ")) + ULXR_GET_STRING(getErrorString(getLastError())), 500); pimpl->host_name = ULXR_GET_STRING(hostEntPtr->h_name); #else # pragma message ("don't know how to determine the domain name") #endif }
ConnectionHolder(Environment &env) { if (SQLAllocHandle(SQL_HANDLE_DBC, env.GetHolder().GetHandle(), &Conn) != SQL_SUCCESS) throw ConnectionException("Error allocate connection", ceErrorAllocConnection); }