std::pair<std::string, std::vector<std::string> > getLocalIps() { std::vector<char> hostname(80); int ret = gethostname(&hostname[0], static_cast<int>(hostname.size())); int err = Platform::OS::BsdSockets::GetLastError(); RCF_VERIFY( ret != -1, RCF::Exception( _RcfError_Socket("gethostname()"), err, RcfSubsystem_Os))(ret); hostent *phe = gethostbyname(&hostname[0]); err = Platform::OS::BsdSockets::GetLastError(); RCF_VERIFY( phe, RCF::Exception( _RcfError_Socket("gethostbyname()"), err, RCF::RcfSubsystem_Os)); std::vector<std::string> ips; for (int i = 0; phe->h_addr_list[i] != 0; ++i) { struct in_addr addr; memcpy(&addr, phe->h_addr_list[i], sizeof( in_addr)); ips.push_back(inet_ntoa(addr)); } return std::make_pair( std::string(&hostname[0]), ips); }
std::size_t Win32NamedPipeClientTransport::implWrite( const std::vector<ByteBuffer> &byteBuffers) { // For now, can't go back to sync calls after doing an async call. // Limitations with Windows IOCP. RCF_ASSERT(!mAsyncMode); // Not using overlapped I/O here because it interferes with the // server session that might be coupled to this transport. const ByteBuffer & byteBuffer = byteBuffers.front(); DWORD count = 0; DWORD dwBytesToWrite = static_cast<DWORD>(byteBuffer.getLength()); BOOL ok = WriteFile( mhPipe, byteBuffer.getPtr(), dwBytesToWrite, &count, NULL); DWORD dwErr = GetLastError(); RCF_VERIFY(ok, Exception(_RcfError_ClientWriteFail(), dwErr)); // Strangely, WriteFile() sometimes returns 1, but at the same time a much too big value in count. RCF_VERIFY(count <= dwBytesToWrite, Exception(_RcfError_ClientWriteFail(), dwErr))(count)(dwBytesToWrite); RCF_VERIFY(count > 0, Exception(_RcfError_ClientWriteFail(), dwErr))(count)(dwBytesToWrite); onTimedSendCompleted( RCF_MIN(count, dwBytesToWrite), 0); return count; }
void ClientStub::instantiateTransport() { CurrentClientStubSentry sentry(*this); if (!mTransport.get()) { RCF_VERIFY(mEndpoint.get(), Exception(_RcfError_NoEndpoint())); mTransport.reset( mEndpoint->createClientTransport().release() ); RCF_VERIFY(mTransport.get(), Exception(_RcfError_TransportCreation())); } if ( mAsync && !mTransport->isAssociatedWithIoService()) { RcfServer * preferred = getAsyncDispatcher(); AsioIoService * pIoService = NULL; if (preferred) { ServerTransport & transport = preferred->getServerTransport(); AsioServerTransport & asioTransport = dynamic_cast<AsioServerTransport &>(transport); pIoService = & asioTransport.getIoService(); } else { pIoService = & getAmiThreadPool().getIoService(); } mTransport->associateWithIoService(*pIoService); } }
void decodeInt(int &value, const RCF::ByteBuffer &byteBuffer, std::size_t &pos) { RCF_VERIFY( pos+1 <= byteBuffer.getLength(), RCF::Exception(RCF::_RcfError_Decoding())); unsigned char ch = byteBuffer.getPtr()[pos]; pos += 1; if (ch < 255) { value = ch; } else { RCF_VERIFY( pos+4 <= byteBuffer.getLength(), RCF::Exception(RCF::_RcfError_Decoding())); BOOST_STATIC_ASSERT(sizeof(int) == 4); memcpy(&value, byteBuffer.getPtr()+pos, 4); RCF::networkToMachineOrder(&value, 4, 1); pos += 4; } }
NullDacl::NullDacl() { ZeroMemory( &mSa, sizeof(mSa) ); mSa.nLength = sizeof( mSa ); mSa.bInheritHandle = FALSE; BOOL ok = InitializeSecurityDescriptor( &mSd, SECURITY_DESCRIPTOR_REVISION ); DWORD dwErr = GetLastError(); RCF_VERIFY(ok, Exception(_RcfError_Win32ApiError("InitializeSecurityDescriptor()"), dwErr)); #pragma warning(push) #pragma warning(disable: 6248) // C6248: Setting a SECURITY_DESCRIPTOR's DACL to NULL will result in an unprotected object. ok = SetSecurityDescriptorDacl( &mSd, TRUE, (PACL) NULL, FALSE); #pragma warning(pop) dwErr = GetLastError(); RCF_VERIFY(ok, Exception(_RcfError_Win32ApiError("SetSecurityDescriptorDacl()"), dwErr)); mSa.lpSecurityDescriptor = &mSd; }
RCF::ByteBuffer Win32Certificate::exportToPfx() { PCCERT_CONTEXT pContext = getWin32Context(); // Create in-memory store HCERTSTORE hMemoryStore; hMemoryStore = CertOpenStore( CERT_STORE_PROV_MEMORY, // Memory store 0, // Encoding type, not used with a memory store NULL, // Use the default provider 0, // No flags NULL); // Not needed DWORD dwErr = GetLastError(); RCF_VERIFY( hMemoryStore, Exception(_RcfError_ApiError("CertOpenStore()"), dwErr)); // Add the certificate. BOOL ok = CertAddCertificateContextToStore( hMemoryStore, // Store handle pContext, // Pointer to a certificate CERT_STORE_ADD_USE_EXISTING, NULL); dwErr = GetLastError(); RCF_VERIFY( ok, Exception(_RcfError_ApiError("CertAddCertificateContextToStore()"), dwErr)); // Export in-memory store. CRYPT_DATA_BLOB pfxBlob = {}; BOOL exportOk = PFXExportCertStore(hMemoryStore, &pfxBlob, L"", 0/*EXPORT_PRIVATE_KEYS*/); dwErr = GetLastError(); RCF_VERIFY( exportOk, Exception(_RcfError_ApiError("PFXExportCertStore()"), dwErr)); RCF::ByteBuffer pfxBuffer(pfxBlob.cbData); pfxBlob.pbData = (BYTE *) pfxBuffer.getPtr(); exportOk = PFXExportCertStore(hMemoryStore, &pfxBlob, L"", 0/*EXPORT_PRIVATE_KEYS*/); dwErr = GetLastError(); RCF_VERIFY( exportOk, Exception(_RcfError_ApiError("PFXExportCertStore()"), dwErr)); CertCloseStore(hMemoryStore, 0); return pfxBuffer; }
void ClientStub::onPollingTimeout() { // Check whether we need to fire a client progress timer callback. if (mNextTimerCallbackMs && 0 == generateTimeoutMs(mNextTimerCallbackMs)) { ClientProgress::Action action = ClientProgress::Continue; mClientProgressPtr->mProgressCallback( 0, 0, ClientProgress::Timer, ClientProgress::Receive, action); RCF_VERIFY( action == ClientProgress::Continue, Exception(_RcfError_ClientCancel())) (mTimerIntervalMs); mNextTimerCallbackMs = RCF::getCurrentTimeMs() + mTimerIntervalMs; mNextTimerCallbackMs |= 1; } // Check that pingbacks have been received. if (mNextPingBackCheckMs && 0 == generateTimeoutMs(mNextPingBackCheckMs)) { boost::uint32_t timeNowMs = RCF::getCurrentTimeMs(); boost::uint32_t timeSinceLastPingBackMs = timeNowMs - mPingBackTimeStamp; // Checking for subsequent pingbacks. RCF_VERIFY( timeSinceLastPingBackMs < mPingBackCheckIntervalMs, Exception(_RcfError_PingBackTimeout(mPingBackCheckIntervalMs))) (mPingBackCheckIntervalMs); // Setup polling for next pingback. mPingBackCheckIntervalMs = 3 * mPingBackIntervalMs; mNextPingBackCheckMs = RCF::getCurrentTimeMs() + mPingBackCheckIntervalMs; mNextPingBackCheckMs |= 1; } }
void decodeBool(bool &value, const RCF::ByteBuffer &byteBuffer, std::size_t &pos) { RCF_VERIFY( pos+1 <= byteBuffer.getLength(), RCF::Exception(RCF::_RcfError_Decoding())); char ch = byteBuffer.getPtr()[pos]; RCF_VERIFY( ch == 0 || ch == 1, RCF::Exception(RCF::_RcfError_Decoding())); pos += 1; value = ch ? true : false; }
void Win32NamedPipeImpersonator::impersonate() { HANDLE hPipe = mPipeSession.mSocketPtr->native(); BOOL ok = ImpersonateNamedPipeClient(hPipe); DWORD dwErr = GetLastError(); RCF_VERIFY(ok, RCF::Exception(_RcfError_Pipe(), dwErr)); }
Win32NamedPipeServerTransport::SessionStatePtr Win32NamedPipeServerTransport::createSessionState() { const std::size_t MaxPipeInstances = PIPE_UNLIMITED_INSTANCES; const DWORD OutBufferSize = 4096; const DWORD InBufferSize = 4096; const DWORD DefaultTimeoutMs = 0; HANDLE hPipe = CreateNamedPipe( mPipeName.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, MaxPipeInstances, OutBufferSize, InBufferSize, DefaultTimeoutMs, mpSec); DWORD dwErr = GetLastError(); RCF_VERIFY(hPipe != INVALID_HANDLE_VALUE, Exception(_RcfError_Pipe(), dwErr)); mpIocp->AssociateDevice(hPipe, 0); SessionStatePtr sessionStatePtr(new SessionState(*this, hPipe)); sessionStatePtr->mWeakThisPtr = sessionStatePtr; return sessionStatePtr; }
void ClientStub::onUiMessage() { ClientProgress::Action action = ClientProgress::Continue; mClientProgressPtr->mProgressCallback( 0, 0, ClientProgress::UiMessage, ClientProgress::Receive, action); RCF_VERIFY( action != ClientProgress::Cancel, Exception(_RcfError_ClientCancel())) (mClientProgressPtr->mUiMessageFilter); // a sample message filter //MSG msg = {0}; //while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) //{ // if (msg.message == WM_QUIT) // { // // } // else if (msg.message == WM_PAINT) // { // TranslateMessage(&msg); // DispatchMessage(&msg); // } //} }
void decodeByteBuffer( RCF::ByteBuffer & value, const RCF::ByteBuffer & byteBuffer, std::size_t & pos) { int len_ = 0; decodeInt(len_, byteBuffer, pos); std::size_t len = static_cast<unsigned int>(len_); RCF_VERIFY( pos+len <= byteBuffer.getLength(), RCF::Exception(RCF::_RcfError_Decoding())); if (len == 0) { value = RCF::ByteBuffer(value, 0, 0); } else { if (value.getLength() < len) { value = RCF::ByteBuffer(len); } value = RCF::ByteBuffer(value, 0, len); memcpy(value.getPtr(), byteBuffer.getPtr()+pos, len); } pos += len; }
void ServerBinding::invoke( const std::string & subInterface, int fnId, RcfSession & session) { // Check access control. { Lock lock(mMutex); if (mCbAccessControl) { bool ok = mCbAccessControl(fnId); if (!ok) { RCF_THROW( RCF::Exception(_RcfError_ServerStubAccessDenied())); } } } // No mutex here, since there is never anyone writing to mInvokeFunctorMap. RCF_VERIFY( mInvokeFunctorMap.find(subInterface) != mInvokeFunctorMap.end(), Exception(_RcfError_UnknownInterface(subInterface))) (subInterface)(fnId)(mInvokeFunctorMap.size())(mMergedStubs.size()); mInvokeFunctorMap[subInterface](fnId, session); }
void serialize_vc6(SF::Archive & ar, boost::array<T, N> & a, const unsigned int) { if (ar.isRead()) { unsigned int count = 0; ar & count; RCF_VERIFY( count == a.size(), RCF::Exception(RCF::_RcfError_RcfError_ArraySizeMismatch(a.size(), count))); for (std::size_t i=0; i<a.size(); ++i) { ar & a[i]; } } else if (ar.isWrite()) { unsigned int count = a.size(); ar & count; for (std::size_t i=0; i<a.size(); ++i) { ar & a[i]; } } }
Win32NamedPipeNetworkSession::Win32NamedPipeNetworkSession( Win32NamedPipeServerTransport & transport, AsioIoService & ioService) : AsioNetworkSession(transport, ioService) { const std::size_t MaxPipeInstances = PIPE_UNLIMITED_INSTANCES; const DWORD OutBufferSize = 4096; const DWORD InBufferSize = 4096; const DWORD DefaultTimeoutMs = 0; HANDLE hPipe = CreateNamedPipe( transport.mPipeName.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, MaxPipeInstances, OutBufferSize, InBufferSize, DefaultTimeoutMs, transport.mpSec); DWORD dwErr = GetLastError(); RCF_VERIFY(hPipe != INVALID_HANDLE_VALUE, Exception(_RcfError_Pipe(), dwErr)); mSocketPtr.reset( new AsioPipeHandle(ioService, hPipe) ); }
void initWinsock() { WORD wVersion = MAKEWORD( 1, 0 ); WSADATA wsaData; int ret = WSAStartup(wVersion, &wsaData); int err = Platform::OS::BsdSockets::GetLastError(); RCF_VERIFY(ret == 0, Exception( _RcfError_Socket("WSAStartup()"), err, RcfSubsystem_Os) ); }
void Win32NamedPipeImpersonator::impersonate() { Win32NamedPipeSessionState & sessionState = dynamic_cast<Win32NamedPipeSessionState &>( RCF::getCurrentRcfSessionPtr()->getSessionState()); BOOL ok = ImpersonateNamedPipeClient(sessionState.mhPipe); DWORD dwErr = GetLastError(); RCF_VERIFY(ok, RCF::Exception(_RcfError_Pipe(), dwErr)); }
Token ObjectFactoryService::addObjectImpl(RcfClientPtr rcfClientPtr) { Token myToken; bool ok = mTokenFactory.requestToken(myToken); RCF_VERIFY(ok, Exception(_RcfError_TokenRequestFailed())); WriteLock writeLock(mStubMapMutex); RCF_UNUSED_VARIABLE(writeLock); RCF_ASSERT(mStubMap.find(myToken) != mStubMap.end())(myToken); StubEntryPtr stubEntryPtr(new StubEntry(rcfClientPtr)); mStubMap[myToken].second = stubEntryPtr; return myToken; }
TokenMappedPtr ObjectFactoryService::getTokenMappedPtr(const Token &token) { ReadLock readLock(mStubMapMutex); RCF_VERIFY( mStubMap.find(token) != mStubMap.end(), Exception(_RcfError_DynamicObjectNotFound(token.getId()))) (token); Lock lock(*mStubMap[token].first); TokenMappedPtr tokenMappedPtr = mStubMap[token].second; return tokenMappedPtr; }
NullDacl::NullDacl() { ZeroMemory( &mSa, sizeof(mSa) ); mSa.nLength = sizeof( mSa ); mSa.bInheritHandle = FALSE; BOOL ok = InitializeSecurityDescriptor( &mSd, SECURITY_DESCRIPTOR_REVISION ); DWORD dwErr = GetLastError(); RCF_VERIFY(ok, Exception(_RcfError_Win32ApiError("InitializeSecurityDescriptor()", dwErr), dwErr)); ok = SetSecurityDescriptorDacl( &mSd, TRUE, (PACL) NULL, FALSE); dwErr = GetLastError(); RCF_VERIFY(ok, Exception(_RcfError_Win32ApiError("SetSecurityDescriptorDacl()", dwErr), dwErr)); mSa.lpSecurityDescriptor = &mSd; }
void ZlibCompressionWriteFilter::resetCompressionState() { if (mCompressionStateInited) { mZerr = deflateEnd(&mCstream); RCF_VERIFY( mZerr == Z_OK || mZerr == Z_DATA_ERROR, FilterException( _RcfError_Zlib(), mZerr, RcfSubsystem_Zlib, "deflateEnd() failed"))(mZerr); mCompressionStateInited = false; } mCstream.zalloc = NULL; mCstream.zfree = NULL; mCstream.opaque = NULL; mZerr = deflateInit(&mCstream, Z_DEFAULT_COMPRESSION); RCF_VERIFY( mZerr == Z_OK, FilterException( _RcfError_Zlib(), mZerr, RcfSubsystem_Zlib, "deflateInit() failed"))(mZerr); mCompressionStateInited = true; }
void ServerStub::invoke( const std::string & subInterface, int fnId, RcfSession & session) { // no mutex here, since there is never anyone writing to mInvokeFunctorMap RCF_VERIFY( mInvokeFunctorMap.find(subInterface) != mInvokeFunctorMap.end(), Exception(_RcfError_UnknownInterface(subInterface))) (subInterface)(fnId)(mInvokeFunctorMap.size())(mMergedStubs.size()); mInvokeFunctorMap[subInterface](fnId, session); }
int UdpClientTransport::send( I_ClientTransportCallback &clientStub, const std::vector<ByteBuffer> &data, unsigned int timeoutMs) { RCF_LOG_4()(mSock)(mDestIp.string()) << "UdpClientTransport - sending data on socket."; RCF_UNUSED_VARIABLE(timeoutMs); RCF_ASSERT(!mAsync); // TODO: optimize for case of single byte buffer with left margin if (mWriteVecPtr.get() == NULL || !mWriteVecPtr.unique()) { mWriteVecPtr.reset( new ReallocBuffer()); } mLastRequestSize = lengthByteBuffers(data); mRunningTotalBytesSent += lengthByteBuffers(data); ReallocBuffer &buffer = *mWriteVecPtr; buffer.resize(lengthByteBuffers(data)); copyByteBuffers(data, &buffer[0]); sockaddr * pDestAddr = NULL; Platform::OS::BsdSockets::socklen_t destAddrSize = 0; mDestIp.getSockAddr(pDestAddr, destAddrSize); int len = sendto( mSock, &buffer[0], static_cast<int>(buffer.size()), 0, pDestAddr, destAddrSize); int err = Platform::OS::BsdSockets::GetLastError(); RCF_VERIFY( len > 0, Exception( _RcfError_Socket("sendto()"), err, RcfSubsystem_Os)); clientStub.onSendCompleted(); return 1; }
void discardPacket(int fd) { char buffer[1]; int len = recvfrom(fd, buffer, 1, 0, NULL, NULL); int err = Platform::OS::BsdSockets::GetLastError(); RCF_VERIFY( len == 1 || (len == -1 && err == Platform::OS::BsdSockets::ERR_EMSGSIZE) || (len == -1 && err == Platform::OS::BsdSockets::ERR_ECONNRESET), Exception( _RcfError_Socket("recvfrom()"), err, RcfSubsystem_Os)); }
void UdpServerTransport::close() { if (mFd != -1) { int ret = Platform::OS::BsdSockets::closesocket(mFd); int err = Platform::OS::BsdSockets::GetLastError(); RCF_VERIFY( ret == 0, Exception( _RcfError_SocketClose(), err, RcfSubsystem_Os, "closesocket() failed"))(mFd); mFd = -1; } }
void decodeString( std::string &value, const RCF::ByteBuffer &byteBuffer, std::size_t &pos) { int len_ = 0; decodeInt(len_, byteBuffer, pos); std::size_t len = static_cast<unsigned int>(len_); RCF_VERIFY( pos+len <= byteBuffer.getLength(), RCF::Exception(RCF::_RcfError_Decoding())); value.assign(byteBuffer.getPtr()+pos, len); pos += len; }
inline void serializeString(SF::Archive & ar, std::basic_string<C,T,A> & s) { if (ar.isRead()) { boost::uint32_t count = 0; ar & count; SF::IStream &is = *ar.getIstream(); s.resize(0); std::size_t minSerializedLength = sizeof(C); if (ar.verifyAgainstArchiveSize(count*minSerializedLength)) { if (count > s.capacity()) { s.reserve(count); } } boost::uint32_t charsRemaining = count; const boost::uint32_t BufferSize = 512; C buffer[BufferSize]; while (charsRemaining) { boost::uint32_t charsToRead = RCF_MIN(BufferSize, charsRemaining); boost::uint32_t bytesToRead = charsToRead*sizeof(C); RCF_VERIFY( is.read( (char *) buffer, bytesToRead) == bytesToRead, RCF::Exception(RCF::_SfError_ReadFailure())) (bytesToRead)(BufferSize)(count); s.append(buffer, charsToRead); charsRemaining -= charsToRead; } } else if (ar.isWrite()) { boost::uint32_t count = static_cast<boost::uint32_t >(s.length()); ar & count; ar.getOstream()->writeRaw( (char *) s.c_str(), count*sizeof(C)); } }
void StoreCertificate::removeFromStore() { if (mpCert) { BOOL ret = CertDeleteCertificateFromStore(mpCert); DWORD dwErr = GetLastError(); RCF_VERIFY( ret, RCF::Exception( _RcfError_CryptoApiError("CertDeleteCertificateFromStore()"), dwErr, RCF::RcfSubsystem_Os)); setHasBeenDeleted(); mpCert = NULL; } }
StoreCertificateIterator::StoreCertificateIterator( Win32CertificateLocation certStoreLocation, Win32CertificateStore certStore) : mhCertStore(NULL), mpCertIterator(NULL) { std::wstring strCertStore; switch (certStore) { case Cs_AddressBook: strCertStore = L"AddressBook"; break; case Cs_AuthRoot: strCertStore = L"AuthRoot"; break; case Cs_CertificateAuthority: strCertStore = L"CA"; break; case Cs_Disallowed: strCertStore = L"Disallowed"; break; case Cs_My: strCertStore = L"MY"; break; case Cs_Root: strCertStore = L"Root"; break; case Cs_TrustedPeople: strCertStore = L"TrustedPeople"; break; case Cs_TrustedPublisher: strCertStore = L"TrustedPublisher"; break; default: RCF_ASSERT(0 && "Invalid certificate store value."); } DWORD dwStoreLocation = 0; switch (certStoreLocation) { case Cl_CurrentUser: dwStoreLocation = CERT_SYSTEM_STORE_CURRENT_USER; break; case Cl_LocalMachine: dwStoreLocation = CERT_SYSTEM_STORE_LOCAL_MACHINE; break; default: RCF_ASSERT(0 && "Invalid certificate store location value."); } mhCertStore = CertOpenStore( (LPCSTR) CERT_STORE_PROV_SYSTEM, X509_ASN_ENCODING, 0, dwStoreLocation, strCertStore.c_str()); DWORD dwErr = GetLastError(); RCF_VERIFY( mhCertStore, Exception(_RcfError_ApiError("CertOpenStore()"), dwErr)); }
I_SerializerAny &Registry::getAnySerializer(const std::string &which) { ReadLock lock(mReadWriteMutex); RCF_UNUSED_VARIABLE(lock); if (mTypenameToRtti.find(which) != mTypenameToRtti.end()) { Rtti rtti = mTypenameToRtti[which]; RCF_VERIFY( mRttiToSerializerAny.find(rtti) != mRttiToSerializerAny.end(), RCF::Exception(RCF::_RcfError_AnySerializerNotFound(which))); return *mRttiToSerializerAny[rtti]; } RCF::Exception e(RCF::_RcfError_AnySerializerNotFound(which)); RCF_THROW(e); return * (I_SerializerAny *) NULL; }