int16_t VariantImpl::asInt16() const { switch(type) { case VAR_INT8: return value.i8; case VAR_INT16: return value.i16; case VAR_STRING: return convertFromString<int16_t>(); default: throw InvalidConversion(QPID_MSG("Cannot convert from " << getTypeName(type) << " to " << getTypeName(VAR_INT16))); } }
void QueueEvents::registerListener(const std::string& id, const EventListener& listener) { qpid::sys::Mutex::ScopedLock l(lock); if (listeners.find(id) == listeners.end()) { listeners[id] = listener; } else { throw Exception(QPID_MSG("Event listener already registered for '" << id << "'")); } }
double VariantImpl::asDouble() const { switch(type) { case VAR_FLOAT: return value.f; case VAR_DOUBLE: return value.d; case VAR_STRING: return convertFromString<double>(); default: throw InvalidConversion(QPID_MSG("Cannot convert from " << getTypeName(type) << " to " << getTypeName(VAR_DOUBLE))); } }
template<class T> T convertFromString() const { std::string* s = reinterpret_cast<std::string*>(value.v); try { return boost::lexical_cast<T>(*s); } catch(const boost::bad_lexical_cast&) { throw InvalidConversion(QPID_MSG("Cannot convert " << *s)); } }
void Connection::open(const ConnectionSettings& settings) { if (isOpen()) throw Exception(QPID_MSG("Connection::open() was already called")); impl = ConnectionImpl::create(version, settings); impl->open(); if ( failureCallback ) impl->registerFailureCallback ( failureCallback ); }
std::string MemoryMappedFile::open(const std::string& name, const std::string& directory) { std::string path = getFileName(name, directory); int flags = O_CREAT | O_TRUNC | O_RDWR; int fd = ::open(path.c_str(), flags, S_IRUSR | S_IWUSR); if (fd == -1) throw qpid::Exception(QPID_MSG("Failed to open memory mapped file " << path << ": " << qpid::sys::strError(errno) << " [flags=" << flags << "]")); state->fd = fd; return path; }
uint32_t VariantImpl::asUint32() const { switch(type) { case VAR_UINT8: return value.ui8; case VAR_UINT16: return value.ui16; case VAR_UINT32: return value.ui32; case VAR_STRING: return convertFromString<uint32_t>(); default: throw InvalidConversion(QPID_MSG("Cannot convert from " << getTypeName(type) << " to " << getTypeName(VAR_UINT32))); } }
char* MemoryMappedFile::map(size_t offset, size_t size) { int protection = PROT_READ | PROT_WRITE; char* region = (char*) ::mmap(0, size, protection, MAP_SHARED, state->fd, offset); if (region == MAP_FAILED) { throw qpid::Exception(QPID_MSG("Failed to map page into memory: " << qpid::sys::strError(errno))); } return region; }
void MapReader::onSymbol(const CharSequence& v, const Descriptor* d) { if (!level) throw qpid::Exception(QPID_MSG("Expecting map as top level datum")); if (key) { onSymbolValue(key, v, d); key.data = 0; key.size = 0; } else { key = v; } }
uint16_t SocketAddress::getPort(::sockaddr const * const addr) { switch (addr->sa_family) { case AF_INET: return ntohs(((::sockaddr_in*)addr)->sin_port); case AF_INET6: return ntohs(((::sockaddr_in6*)addr)->sin6_port); default: throw Exception(QPID_MSG("Unexpected socket type")); } }
CyrusSecurityLayer::CyrusSecurityLayer(sasl_conn_t* c, uint16_t maxFrameSize) : conn(c), decrypted(0), decryptedSize(0), encrypted(0), encryptedSize(0), codec(0), maxInputSize(0), decodeBuffer(maxFrameSize), encodeBuffer(maxFrameSize), encoded(0) { const void* value(0); int result = sasl_getprop(conn, SASL_MAXOUTBUF, &value); if (result != SASL_OK) { throw framing::InternalErrorException(QPID_MSG("SASL encode error: " << sasl_errdetail(conn))); } maxInputSize = *(reinterpret_cast<const unsigned*>(value)); }
void SequenceSet::decode(Buffer& buffer) { clear(); uint16_t size = buffer.getShort(); uint16_t count = size / RANGE_SIZE;//number of ranges if (size % RANGE_SIZE) throw IllegalArgumentException(QPID_MSG("Invalid size for sequence set: " << size)); for (uint16_t i = 0; i < count; i++) { add(SequenceNumber(buffer.getLong()), SequenceNumber(buffer.getLong())); } }
void Cluster::processFrame(const EventFrame& e, Lock& l) { if (e.isCluster()) { QPID_LOG_IF(trace, loggable(e.frame), *this << " DLVR: " << e); ClusterDispatcher dispatch(*this, e.connectionId.getMember(), l); if (!framing::invoke(dispatch, *e.frame.getBody()).wasHandled()) throw Exception(QPID_MSG("Invalid cluster control")); } else if (state >= CATCHUP) { map.incrementFrameSeq(); ConnectionPtr connection = getConnection(e, l); if (connection) { QPID_LOG_IF(trace, loggable(e.frame), *this << " DLVR " << map.getFrameSeq() << ": " << e); connection->deliveredFrame(e); } else throw Exception(QPID_MSG("Unknown connection: " << e)); } else // Drop connection frames while state < CATCHUP QPID_LOG_IF(trace, loggable(e.frame), *this << " DROP (joining): " << e); }
void SslSocket::connect(const std::string& host, uint16_t port) const { std::stringstream namestream; namestream << host << ":" << port; connectname = namestream.str(); void* arg = SslOptions::global.certName.empty() ? 0 : const_cast<char*>(SslOptions::global.certName.c_str()); NSS_CHECK(SSL_GetClientAuthDataHook(socket, NSS_GetClientAuthData, arg)); NSS_CHECK(SSL_SetURL(socket, host.data())); char hostBuffer[PR_NETDB_BUF_SIZE]; PRHostEnt hostEntry; PR_CHECK(PR_GetHostByName(host.data(), hostBuffer, PR_NETDB_BUF_SIZE, &hostEntry)); PRNetAddr address; int value = PR_EnumerateHostEnt(0, &hostEntry, port, &address); if (value < 0) { throw Exception(QPID_MSG("Error getting address for host: " << ErrorString())); } else if (value == 0) { throw Exception(QPID_MSG("Could not resolve address for host.")); } PR_CHECK(PR_Connect(socket, &address, PR_INTERVAL_NO_TIMEOUT)); }
bool MapReader::onStartMap(uint32_t count, const CharSequence&, const Descriptor* d) { if (level++) { if (key) { bool step = onStartMapValue(key, count, d); key.data = 0; key.size = 0; return step; } else { throw qpid::Exception(QPID_MSG("Expecting symbol as key")); } } return true; }
void SCM::stop(const string& serviceName) { // Ensure a handle to the SCM database. openSvcManager(); // Get a handle to the service. AutoServiceHandle svc(::OpenService(scmHandle, serviceName.c_str(), SERVICE_STOP | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS)); QPID_WINDOWS_CHECK_NULL(svc); // Make sure the service is not already stopped; if it's stop-pending, // wait for it to finalize. DWORD state = waitForStateChangeFrom(svc, SERVICE_STOP_PENDING); if (state == SERVICE_STOPPED) { QPID_LOG(info, "Service is already stopped"); return; } // If the service is running, dependencies must be stopped first. std::auto_ptr<ENUM_SERVICE_STATUS> deps; DWORD numDeps = getDependentServices(svc, deps); for (DWORD i = 0; i < numDeps; i++) stop(deps.get()[i].lpServiceName); // Dependents stopped; send a stop code to the service. SERVICE_STATUS_PROCESS ssp; if (!::ControlService(svc, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&ssp)) throw qpid::Exception(QPID_MSG("Stopping " << serviceName << ": " << qpid::sys::strError(::GetLastError()))); // Wait for the service to stop. state = waitForStateChangeFrom(svc, SERVICE_STOP_PENDING); if (state == SERVICE_STOPPED) QPID_LOG(info, QPID_MSG("Service " << serviceName << " stopped successfully.")); }
bool Interconnects::createObject(Broker& broker, const std::string& type, const std::string& name, const qpid::types::Variant::Map& properties, const std::string& /*userId*/, const std::string& /*connectionId*/) { if (type == DOMAIN_TYPE) { qpid::sys::ScopedLock<qpid::sys::Mutex> l(lock); DomainMap::iterator i = domains.find(name); if (i == domains.end()) { boost::shared_ptr<Domain> domain(new Domain(name, properties, broker)); domains[name] = domain; if (domain->isDurable()) broker.getStore().create(*domain); return true; } else { return false; } } else if (type == INCOMING_TYPE || type == OUTGOING_TYPE) { QPID_LOG(notice, "Creating interconnect " << name << ", " << properties); boost::shared_ptr<Domain> domain; { qpid::sys::ScopedLock<qpid::sys::Mutex> l(lock); qpid::types::Variant::Map::const_iterator p = properties.find(DOMAIN_TYPE); if (p != properties.end()) { std::string domainName = p->second; DomainMap::iterator i = domains.find(domainName); if (i != domains.end()) { domain = i->second; } else { throw qpid::Exception(QPID_MSG("No such domain: " << domainName)); } } else { throw qpid::Exception(QPID_MSG("Domain must be specified")); } } domain->connect(type == INCOMING_TYPE, name, properties, *context); return true; } else { return false; } }
void Socket::connect(const SocketAddress& addr) const { peername = addr.asString(false); createSocket(addr); const SOCKET& socket = impl->fd; int err; WSASetLastError(0); if ((::connect(socket, getAddrInfo(addr).ai_addr, getAddrInfo(addr).ai_addrlen) != 0) && ((err = ::WSAGetLastError()) != WSAEWOULDBLOCK)) throw qpid::Exception(QPID_MSG(strError(err) << ": " << peername)); }
/** Return true if the message should be procesed, false if it should be ignored. */ bool track(Message& message) { if (!(opts.verifySequence || opts.ignoreDuplicates)) return true; // Not checking sequence numbers. uint sn = message.getProperties()[SN]; bool duplicate = (sn <= lastSn); bool dropped = (sn > lastSn+1); if (opts.verifySequence && dropped) throw Exception(QPID_MSG("Gap in sequence numbers " << lastSn << "-" << sn)); bool ignore = duplicate && opts.ignoreDuplicates; if (ignore && opts.checkRedelivered && !message.getRedelivered()) throw qpid::Exception("duplicate sequence number received, message not marked as redelivered!"); if (!duplicate) lastSn = sn; return !ignore; }
void enqueue(TransactionContext* , const boost::intrusive_ptr<PersistableMessage>& pmsg, const PersistableQueue& ) { qpid::broker::amqp_0_10::MessageTransfer* msg = dynamic_cast<qpid::broker::amqp_0_10::MessageTransfer*>(pmsg.get()); assert(msg); // Dump the message if there is a dump file. if (dump.get()) { msg->getFrames().getMethod()->print(*dump); *dump << endl << " "; msg->getFrames().getHeaders()->print(*dump); *dump << endl << " "; *dump << msg->getFrames().getContentSize() << endl; } // Check the message for special instructions. string data = msg->getFrames().getContent(); size_t i = string::npos; size_t j = string::npos; if (strncmp(data.c_str(), TEST_STORE_DO.c_str(), strlen(TEST_STORE_DO.c_str())) == 0 && (i = data.find(name+"[")) != string::npos && (j = data.find("]", i)) != string::npos) { size_t start = i+name.size()+1; string action = data.substr(start, j-start); if (action == EXCEPTION) { throw Exception(QPID_MSG("TestStore " << name << " throwing exception for: " << data)); } else if (action == EXIT_PROCESS) { // FIXME aconway 2009-04-10: this is a dubious way to // close the process at best, it can cause assertions or seg faults // rather than clean exit. QPID_LOG(critical, "TestStore " << name << " forcing process exit for: " << data); exit(0); } else if (strncmp(action.c_str(), ASYNC.c_str(), strlen(ASYNC.c_str())) == 0) { std::string delayStr(action.substr(ASYNC.size())); int delay = boost::lexical_cast<int>(delayStr); threads.push_back(Thread(*new Completer(msg, delay))); } else { QPID_LOG(error, "TestStore " << name << " unknown action " << action); msg->enqueueComplete(); } } else msg->enqueueComplete(); }
int SslSocket::listen(uint16_t port, int backlog, const std::string& certName, bool clientAuth) const { //configure prototype socket: prototype = SSL_ImportFD(0, PR_NewTCPSocket()); if (clientAuth) { NSS_CHECK(SSL_OptionSet(prototype, SSL_REQUEST_CERTIFICATE, PR_TRUE)); NSS_CHECK(SSL_OptionSet(prototype, SSL_REQUIRE_CERTIFICATE, PR_TRUE)); } //get certificate and key (is this the correct way?) CERTCertificate *cert = PK11_FindCertFromNickname(const_cast<char*>(certName.c_str()), 0); if (!cert) throw Exception(QPID_MSG("Failed to load certificate '" << certName << "'")); SECKEYPrivateKey *key = PK11_FindKeyByAnyCert(cert, 0); if (!key) throw Exception(QPID_MSG("Failed to retrieve private key from certificate")); NSS_CHECK(SSL_ConfigSecureServer(prototype, cert, key, NSS_FindCertKEAType(cert))); SECKEY_DestroyPrivateKey(key); CERT_DestroyCertificate(cert); //bind and listen const int& socket = impl->fd; int yes=1; QPID_POSIX_CHECK(setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes))); struct sockaddr_in name; name.sin_family = AF_INET; name.sin_port = htons(port); name.sin_addr.s_addr = 0; if (::bind(socket, (struct sockaddr*)&name, sizeof(name)) < 0) throw Exception(QPID_MSG("Can't bind to port " << port << ": " << strError(errno))); if (::listen(socket, backlog) < 0) throw Exception(QPID_MSG("Can't listen on port " << port << ": " << strError(errno))); socklen_t namelen = sizeof(name); if (::getsockname(socket, (struct sockaddr*)&name, &namelen) < 0) throw QPID_POSIX_ERROR(errno); return ntohs(name.sin_port); }
/** * this represents the low address of an ACL address range. * Given rangeHi that represents the high address, * return a string showing the numeric comparisons that the * inRange checks will do for address pair. */ std::string SocketAddress::comparisonDetails(const SocketAddress& rangeHi) const { std::ostringstream os; SocketAddress thisSa(*this); SocketAddress rangeHiSa(rangeHi); (void) getAddrInfo(thisSa); (void) getAddrInfo(rangeHiSa); os << "(" << thisSa.asString(true, true, false) << "," << rangeHiSa.asString(true, true, false) << ")"; while (thisSa.nextAddress()) { if (!rangeHiSa.nextAddress()) { throw(Exception(QPID_MSG("Comparison iteration fails: " + (*this).asString() + rangeHi.asString()))); } os << ",(" << thisSa.asString(true, true, false) << "," << rangeHiSa.asString(true, true, false) << ")"; } if (rangeHiSa.nextAddress()) { throw(Exception(QPID_MSG("Comparison iteration fails: " + (*this).asString() + rangeHi.asString()))); } std::string result = os.str(); return result; }
void SocketAddress::setAddrInfoPort(uint16_t port) { if (!currentAddrInfo) return; ::addrinfo& ai = *currentAddrInfo; switch (ai.ai_family) { case AF_INET: ((::sockaddr_in*)ai.ai_addr)->sin_port = htons(port); return; case AF_INET6: ((::sockaddr_in6*)ai.ai_addr)->sin6_port = htons(port); return; default: throw Exception(QPID_MSG("Unexpected socket type")); } }
void StoreStatus::load() { if (dataDir.empty()) { throw Exception(QPID_MSG("No data-dir: When a store is loaded together with clustering, --data-dir must be specified.")); } try { fs::path dir = fs::path(dataDir, fs::native)/SUBDIR; create_directory(dir); fs::path file = dir/STORE_STATUS; if (fs::exists(file)) { string data = readFile(file); istringstream is(data); is.exceptions(std::ios::badbit | std::ios::failbit); is >> ws >> clusterId >> ws >> shutdownId; if (!clusterId) throw Exception(QPID_MSG("Invalid cluster store state, no cluster-id")); if (shutdownId) state = STORE_STATE_CLEAN_STORE; else state = STORE_STATE_DIRTY_STORE; } else { // Starting from empty store clusterId = Uuid(true); save(); state = STORE_STATE_EMPTY_STORE; } }
bool VariantImpl::asBool() const { switch(type) { case VAR_VOID: return false; case VAR_BOOL: return value.b; case VAR_UINT8: return value.ui8; case VAR_UINT16: return value.ui16; case VAR_UINT32: return value.ui32; case VAR_UINT64: return value.ui64; case VAR_INT8: return value.i8; case VAR_INT16: return value.i16; case VAR_INT32: return value.i32; case VAR_INT64: return value.i64; case VAR_STRING: return toBool(*reinterpret_cast<std::string*>(value.v)); default: throw InvalidConversion(QPID_MSG("Cannot convert from " << getTypeName(type) << " to " << getTypeName(VAR_BOOL))); } }
void FieldTable::decode(Buffer& buffer){ clear(); uint32_t len = buffer.getLong(); if (len) { uint32_t available = buffer.available(); if (available < len) throw IllegalArgumentException(QPID_MSG("Not enough data for field table.")); uint32_t count = buffer.getLong(); uint32_t leftover = available - len; while(buffer.available() > leftover && count--){ std::string name; ValuePtr value(new FieldValue); buffer.getShortString(name); value->decode(buffer); values[name] = ValuePtr(value); } } }
void Connection::open(const Url& url, const ConnectionSettings& settings) { if (url.empty()) throw Exception(QPID_MSG("Attempt to open URL with no addresses.")); Url::const_iterator i = url.begin(); do { const Address& addr = *i; i++; try { ConnectionSettings cs(settings); if (addr.protocol.size()) cs.protocol = addr.protocol; cs.host = addr.host; cs.port = addr.port; open(cs); break; } catch (const Exception& /*e*/) { if (i == url.end()) throw; } } while (i != url.end()); }
std::string VariantImpl::asString() const { switch(type) { case VAR_VOID: return EMPTY; case VAR_BOOL: return value.b ? TRUE : FALSE; case VAR_UINT8: return boost::lexical_cast<std::string>((int) value.ui8); case VAR_UINT16: return boost::lexical_cast<std::string>(value.ui16); case VAR_UINT32: return boost::lexical_cast<std::string>(value.ui32); case VAR_UINT64: return boost::lexical_cast<std::string>(value.ui64); case VAR_INT8: return boost::lexical_cast<std::string>((int) value.i8); case VAR_INT16: return boost::lexical_cast<std::string>(value.i16); case VAR_INT32: return boost::lexical_cast<std::string>(value.i32); case VAR_INT64: return boost::lexical_cast<std::string>(value.i64); case VAR_DOUBLE: return boost::lexical_cast<std::string>(value.d); case VAR_FLOAT: return boost::lexical_cast<std::string>(value.f); case VAR_STRING: return *reinterpret_cast<std::string*>(value.v); case VAR_LIST: return toString(asList()); case VAR_MAP: return toString(asMap()); default: throw InvalidConversion(QPID_MSG("Cannot convert from " << getTypeName(type) << " to " << getTypeName(VAR_STRING))); } }
bool DataBuilder::nest(const qpid::types::Variant& n) { switch (nested.top()->getType()) { case qpid::types::VAR_MAP: if (nested.size() > 1 || nested.top()->asMap().size() > 0) { QPID_LOG(error, QPID_MSG("Expecting map key; got " << n << " " << *(nested.top()))); } break; case qpid::types::VAR_LIST: nested.top()->asList().push_back(n); nested.push(&nested.top()->asList().back()); break; default: qpid::types::Variant& value = *(nested.top()); value = n; nested.pop(); nested.push(&value); break; } return true; }
void ThreadPrivate::start(ThreadPrivate::shared_ptr& tp) { getTlsIndex(); // fail here if OS problem, not in new thread initCompleted = CreateEvent (NULL, TRUE, FALSE, NULL); QPID_WINDOWS_CHECK_CRT_NZ(initCompleted); qpidThreadDone = CreateEvent (NULL, TRUE, FALSE, NULL); QPID_WINDOWS_CHECK_CRT_NZ(qpidThreadDone); #ifdef _DLL { ScopedCriticalSection l(threadLock); if (terminating) throw qpid::Exception(QPID_MSG("creating thread after exit/FreeLibrary")); runningThreads++; } #endif uintptr_t h = _beginthreadex(0, 0, runThreadPrivate, (void *)this, 0, &threadId); #ifdef _DLL if (h == NULL) { ScopedCriticalSection l(threadLock); if (--runningThreads == 0) SetEvent(threadsDone); } #endif QPID_WINDOWS_CHECK_CRT_NZ(h); // Success keepAlive = tp; threadHandle = reinterpret_cast<HANDLE>(h); SetEvent (initCompleted); }