int SecureSocketImpl::completeHandshake() { poco_assert (_pSocket->initialized()); poco_check_ptr (_pSSL); int rc; do { rc = SSL_do_handshake(_pSSL); } while (rc <= 0 && _pSocket->lastError() == POCO_EINTR); if (rc <= 0) { return handleError(rc); } _needHandshake = false; return rc; }
void Context::enableSessionCache(bool flag, const std::string& sessionIdContext) { poco_assert (isForServerUse()); if (flag) { SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_SERVER); } else { SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_OFF); } unsigned length = static_cast<unsigned>(sessionIdContext.length()); if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) length = SSL_MAX_SSL_SESSION_ID_LENGTH; int rc = SSL_CTX_set_session_id_context(_pSSLContext, reinterpret_cast<const unsigned char*>(sessionIdContext.data()), length); if (rc != 1) throw SSLContextException("cannot set session ID context"); }
void JobManager::WakeUp(InternalJob::Pointer job, Poco::Timestamp::TimeDiff delay) { poco_assert(delay >= 0); // "Scheduling delay is negative" { Poco::ScopedLock<Poco::Mutex> m_managerLock (m_mutex); //cannot wake up if it is not sleeping if (job->GetState() != Job::SLEEPING) return; DoSchedule(job, delay); } //call the pool outside sync block to avoid deadlock m_Pool->JobQueued(); /// IListenerExtension only notify of wake up if immediate if (delay == 0) m_JobListeners.Awake(job.Cast<Job>()); }
void ZipLocalFileHeader::init( const Poco::Path& fName, ZipCommon::CompressionMethod cm, ZipCommon::CompressionLevel cl) { poco_assert (_fileName.empty()); setSearchCRCAndSizesAfterData(false); Poco::Path fileName(fName); fileName.setDevice(""); // clear device! setFileName(fileName.toString(Poco::Path::PATH_UNIX), fileName.isDirectory()); setRequiredVersion(2, 0); if (fileName.isFile()) { setCompressionMethod(cm); setCompressionLevel(cl); } else setCompressionMethod(ZipCommon::CM_STORE); }
const std::string& PatternFormatter::getPriorityName(int prio) { static std::string priorities[] = { "", "Fatal", "Critical", "Error", "Warning", "Notice", "Information", "Debug", "Trace" }; poco_assert (1 <= prio && prio <= 8); return priorities[prio]; }
void SecureSocketImpl::acceptSSL() { poco_assert (!_pSSL); BIO* pBIO = BIO_new(BIO_s_socket()); if (!pBIO) throw SSLException("Cannot create BIO object"); BIO_set_fd(pBIO, static_cast<int>(_pSocket->sockfd()), BIO_NOCLOSE); _pSSL = SSL_new(_pContext->sslContext()); if (!_pSSL) { BIO_free(pBIO); throw SSLException("Cannot create SSL object"); } SSL_set_bio(_pSSL, pBIO, pBIO); SSL_set_accept_state(_pSSL); _needHandshake = true; }
void BundleFile::list(const std::string& path, std::vector<std::string>& files) const { poco_assert (_pArchive); files.clear(); int depth = 0; std::string parent; if (!path.empty()) { // ensure parent ends with a slash Path parentPath(path, Path::PATH_UNIX); parentPath.makeDirectory(); parent = parentPath.toString(Path::PATH_UNIX); } ZipArchive::FileHeaders::const_iterator it; ZipArchive::FileHeaders::const_iterator end(_pArchive->headerEnd()); if (path.empty()) { it = _pArchive->headerBegin(); } else { it = _pArchive->findHeader(parent); if (it != end) ++it; depth = Path(parent).depth(); } std::set<std::string> fileSet; while (it != end && isSubdirectoryOf(it->first, parent)) { Path p(it->first, Path::PATH_UNIX); p.makeFile(); if (p.depth() == depth) { std::string name = p.getFileName(); if (fileSet.find(name) == fileSet.end()) { files.push_back(name); fileSet.insert(name); } } ++it; } }
std::size_t Preparation::maxDataSize(std::size_t pos) const { poco_assert (pos >= 0 && pos < _pValues.size()); std::size_t sz = 0; std::size_t maxsz = getMaxFieldSize(); try { ODBCColumn col(_rStmt, pos); sz = col.length(); if (ODBCColumn::FDT_STRING == col.type()) ++sz; } catch (StatementException&) { } if (!sz || sz > maxsz) sz = maxsz; return sz; }
void FileImpl::setSizeImpl(FileSizeImpl size) { poco_assert (!_path.empty()); int fd = open(_path.c_str(), O_WRONLY, S_IRWXU); if (fd != -1) { try { if (ftruncate(fd, size) != 0) handleLastErrorImpl(_path); } catch (...) { close(fd); throw; } } }
int StreamConverterBuf::readFromDevice() { poco_assert_dbg (_pIstr); if (_pos < _sequenceLength) return _buffer[_pos++]; _pos = 0; _sequenceLength = 0; int c = _pIstr->get(); if (c == -1) return -1; poco_assert (c < 256); int uc; _buffer [0] = (unsigned char) c; int n = _inEncoding.queryConvert(_buffer, 1); int read = 1; while (-1 > n) { poco_assert_dbg(-n <= sizeof(_buffer)); _pIstr->read((char*) _buffer + read, -n - read); read = -n; n = _inEncoding.queryConvert(_buffer, -n); } if (-1 >= n) { uc = _defaultChar; ++_errors; } else { uc = n; } _sequenceLength = _outEncoding.convert(uc, _buffer, sizeof(_buffer)); if (_sequenceLength == 0) _sequenceLength = _outEncoding.convert(_defaultChar, _buffer, sizeof(_buffer)); if (_sequenceLength == 0) return -1; else return _buffer[_pos++]; }
DateTime::DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond): _year(year), _month(month), _day(day), _hour(hour), _minute(minute), _second(second), _millisecond(millisecond), _microsecond(microsecond) { poco_assert (year >= 0 && year <= 9999); poco_assert (month >= 1 && month <= 12); poco_assert (day >= 1 && day <= daysOfMonth(year, month)); poco_assert (hour >= 0 && hour <= 23); poco_assert (minute >= 0 && minute <= 59); poco_assert (second >= 0 && second <= 59); poco_assert (millisecond >= 0 && millisecond <= 999); poco_assert (microsecond >= 0 && microsecond <= 999); _utcTime = toUtcTime(toJulianDay(year, month, day)) + 10*(hour*Timespan::HOURS + minute*Timespan::MINUTES + second*Timespan::SECONDS + millisecond*Timespan::MILLISECONDS + microsecond); }
void Binder::bind(std::size_t pos, const DateTime& val, Direction dir) { poco_assert(dir == PD_IN); MYSQL_TIME mt = {0}; mt.year = val.year(); mt.month = val.month(); mt.day = val.day(); mt.hour = val.hour(); mt.minute = val.minute(); mt.second = val.second(); mt.second_part = val.millisecond(); mt.time_type = MYSQL_TIMESTAMP_DATETIME; _dates.push_back(mt); realBind(pos, MYSQL_TYPE_DATETIME, &_dates.back(), sizeof(mt)); }
void FileImpl::copyToImpl(const std::string& path) const { poco_assert (!_path.empty()); int sd = open(_path.c_str(), O_RDONLY, 0); if (sd == -1) handleLastErrorImpl(_path); struct stat st; if (fstat(sd, &st) != 0) { close(sd); handleLastErrorImpl(_path); } const long blockSize = st.st_blksize; int dd = open(path.c_str(), O_CREAT | O_TRUNC | O_WRONLY, st.st_mode & S_IRWXU); if (dd == -1) { close(sd); handleLastErrorImpl(path); } Buffer<char> buffer(blockSize); try { int n; while ((n = read(sd, buffer.begin(), blockSize)) > 0) { if (write(dd, buffer.begin(), n) != n) handleLastErrorImpl(path); } if (n < 0) handleLastErrorImpl(_path); } catch (...) { close(sd); close(dd); throw; } close(sd); close(dd); }
SemaphoreImpl::SemaphoreImpl(int n, int max): _n(n), _max(max) { poco_assert (n >= 0 && max > 0 && n <= max); #if defined(POCO_VXWORKS) // This workaround is for VxWorks 5.x where // pthread_mutex_init() won't properly initialize the mutex // resulting in a subsequent freeze in pthread_mutex_destroy() // if the mutex has never been used. std::memset(&_mutex, 0, sizeof(_mutex)); #endif if (pthread_mutex_init(&_mutex, NULL)) throw SystemException("cannot create semaphore (mutex)"); #if defined(POCO_HAVE_MONOTONIC_PTHREAD_COND_TIMEDWAIT) pthread_condattr_t attr; if (pthread_condattr_init(&attr)) { pthread_mutex_destroy(&_mutex); throw SystemException("cannot create semaphore (condition attribute)"); } if (pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)) { pthread_condattr_destroy(&attr); pthread_mutex_destroy(&_mutex); throw SystemException("cannot create semaphore (condition attribute clock)"); } if (pthread_cond_init(&_cond, &attr)) { pthread_condattr_destroy(&attr); pthread_mutex_destroy(&_mutex); throw SystemException("cannot create semaphore (condition)"); } pthread_condattr_destroy(&attr); #else if (pthread_cond_init(&_cond, NULL)) { pthread_mutex_destroy(&_mutex); throw SystemException("cannot create semaphore (condition)"); } #endif }
ThreadPool::ThreadPool(int minCapacity, int maxCapacity, int idleTime, int stackSize): _minCapacity(minCapacity), _maxCapacity(maxCapacity), _idleTime(idleTime), _serial(0), _age(0), _stackSize(stackSize) { poco_assert (minCapacity >= 1 && maxCapacity >= minCapacity && idleTime > 0); for (int i = 0; i < _minCapacity; i++) { PooledThread* pThread = createThread(); _threads.push_back(pThread); pThread->start(); } }
AbstractSession& SimpleSessionStore::getSession(const std::string& sessionId) { std::unique_lock<std::mutex> lock(_mutex); SessionMap::iterator sessionsIter = _sessionMap.find(sessionId); if (sessionsIter != _sessionMap.end()) { // This must be valid b/c it's designed that way and we // need to return a reference. poco_assert(sessionsIter->second); return (*sessionsIter->second); } else { throw Poco::InvalidAccessException("Session " + sessionId + " not found."); } }
Decompress::Decompress(std::istream& in, const Poco::Path& outputDir, bool flattenDirs, bool keepIncompleteFiles): _in(in), _outDir(outputDir), _flattenDirs(flattenDirs), _keepIncompleteFiles(keepIncompleteFiles), _mapping() { _outDir.makeAbsolute(); _outDir.makeDirectory(); poco_assert (_in.good()); Poco::File tmp(_outDir); if (!tmp.exists()) { tmp.createDirectories(); } if (!tmp.isDirectory()) throw Poco::IOException("Failed to create/open directory: " + _outDir.toString()); EOk += Poco::Delegate<Decompress, std::pair<const ZipLocalFileHeader, const Poco::Path> >(this, &Decompress::onOk); }
void ZipLocalFileHeader::init( const Poco::Path& fName, ZipCommon::CompressionMethod cm, ZipCommon::CompressionLevel cl) { poco_assert (_fileName.empty()); setSearchCRCAndSizesAfterData(false); Poco::Path fileName(fName); fileName.setDevice(""); // clear device! setFileName(fileName.toString(Poco::Path::PATH_UNIX), fileName.isDirectory()); setRequiredVersion(2, 0); if (fileName.isFile()) { setCompressionMethod(cm); setCompressionLevel(cl); } else setCompressionMethod(ZipCommon::CM_STORE); _rawHeader[GENERAL_PURPOSE_POS+1] |= 0x08; // Set "language encoding flag" to indicate that filenames and paths are in UTF-8. }
bool FileImpl::existsImpl() const { poco_assert (!_path.empty()); DWORD attr = GetFileAttributes(_path.c_str()); if (attr == 0xFFFFFFFF) { switch (GetLastError()) { case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: case ERROR_NOT_READY: case ERROR_INVALID_DRIVE: return false; default: handleLastErrorImpl(_path); } } return true; }
void FileImpl::setExecutableImpl(bool flag) { poco_assert (!_path.empty()); struct stat st; if (stat(_path.c_str(), &st) != 0) handleLastErrorImpl(_path); mode_t mode; if (flag) { mode = st.st_mode | S_IXUSR; } else { mode_t wmask = S_IXUSR | S_IXGRP | S_IXOTH; mode = st.st_mode & ~wmask; } if (chmod(_path.c_str(), mode) != 0) handleLastErrorImpl(_path); }
int TextConverter::convert(const std::string& source, std::string& destination, Transform trans) { int errors = 0; TextIterator it(source, _inEncoding); TextIterator end(source); unsigned char buffer[TextEncoding::MAX_SEQUENCE_LENGTH]; while (it != end) { int c = *it; if (c == -1) { ++errors; c = _defaultChar; } c = trans(c); int n = _outEncoding.convert(c, buffer, sizeof(buffer)); if (n == 0) n = _outEncoding.convert(_defaultChar, buffer, sizeof(buffer)); poco_assert (n <= sizeof(buffer)); destination.append((const char*) buffer, n); ++it; } return errors; }
void NodeAppender::appendChild(Node* newChild) { poco_check_ptr (newChild); poco_assert (_pLast == 0 || _pLast->_pNext == 0); if (static_cast<AbstractNode*>(newChild)->_pOwner != _pParent->_pOwner) throw DOMException(DOMException::WRONG_DOCUMENT_ERR); if (newChild->nodeType() == Node::DOCUMENT_FRAGMENT_NODE) { AbstractContainerNode* pFrag = static_cast<AbstractContainerNode*>(newChild); AbstractNode* pChild = pFrag->_pFirstChild; if (pChild) { if (_pLast) _pLast->_pNext = pChild; else _pParent->_pFirstChild = pChild; while (pChild) { _pLast = pChild; pChild->_pParent = _pParent; pChild = pChild->_pNext; } pFrag->_pFirstChild = 0; } } else { AbstractNode* pAN = static_cast<AbstractNode*>(newChild); pAN->duplicate(); if (pAN->_pParent) pAN->_pParent->removeChild(pAN); pAN->_pParent = _pParent; if (_pLast) _pLast->_pNext = pAN; else _pParent->_pFirstChild = pAN; _pLast = pAN; } }
std::string& SerialChannelImpl::readImpl(std::string& buffer, std::size_t length) { buffer.clear(); int bufSize = length ? (int) length : (int) _config.getBufferSizeImpl(); if (0 == bufSize) return buffer; char* pReadBuf = new char[bufSize+1]; DWORD read = 0; DWORD readCount = 0; buffer.clear(); do { ZeroMemory(pReadBuf, bufSize+1); if (!ReadFile(_handle, pReadBuf + readCount, bufSize - readCount, &read, NULL)) { delete[] pReadBuf; handleError(_name); } else if (0 == read) break; poco_assert(read <= bufSize - readCount); buffer.append(pReadBuf + readCount, read); if (length) readCount += read; if (_config.getUseEOFImpl()) { size_t pos = buffer.find(_config.getEOFCharImpl()); if (pos != buffer.npos) { buffer = buffer.substr(0, pos); PurgeComm(_handle, PURGE_RXCLEAR); break; } } if (length && readCount >= length) break; }while(true); delete[] pReadBuf; return buffer; }
void FileStreamBuf::open(const std::string& path, std::ios::openmode mode) { poco_assert (_handle == INVALID_HANDLE_VALUE); _path = path; _pos = 0; setMode(mode); resetBuffers(); DWORD access = 0; if (mode & std::ios::in) access |= GENERIC_READ; if (mode & std::ios::out) access |= GENERIC_WRITE; DWORD shareMode = FILE_SHARE_READ; if (!(mode & std::ios::out)) shareMode |= FILE_SHARE_WRITE; DWORD creationDisp = OPEN_EXISTING; if (mode & std::ios::trunc) creationDisp = CREATE_ALWAYS; else if (mode & std::ios::out) creationDisp = OPEN_ALWAYS; DWORD flags = FILE_ATTRIBUTE_NORMAL; #if defined (POCO_WIN32_UTF8) std::wstring utf16Path; UnicodeConverter::toUTF16(path, utf16Path); _handle = CreateFile2(utf16Path.c_str(), access, shareMode, creationDisp, NULL); #else _handle = CreateFileA(path.c_str(), access, shareMode, NULL, creationDisp, flags, NULL); #endif if (_handle == INVALID_HANDLE_VALUE) File::handleLastError(_path); if ((mode & std::ios::ate) || (mode & std::ios::app)) seekoff(0, std::ios::end, mode); }
std::streamsize StreamCopier::copyToString(std::istream& istr, std::string& str, unsigned bufferSize) { poco_assert (bufferSize > 0); Buffer<char> buffer(bufferSize); std::streamsize len = 0; istr.read(buffer.begin(), bufferSize); std::streamsize n = istr.gcount(); while (n > 0) { len += n; str.append(buffer.begin(), static_cast<std::string::size_type>(n)); if (istr) { istr.read(buffer.begin(), bufferSize); n = istr.gcount(); } else n = 0; } return len; }
std::streamsize StreamCopier::copyStream(std::istream& istr, std::ostream& ostr, unsigned bufferSize) { poco_assert (bufferSize > 0); Buffer<char> buffer(bufferSize); std::streamsize len = 0; istr.read(buffer.begin(), bufferSize); std::streamsize n = istr.gcount(); while (n > 0) { len += n; ostr.write(buffer.begin(), n); if (istr && ostr) { istr.read(buffer.begin(), bufferSize); n = istr.gcount(); } else n = 0; } return len; }
Timestamp FileImpl::createdImpl() const { poco_assert (!_path.empty()); #if defined(__APPLE__) && defined(st_birthtime) && !defined(POCO_NO_STAT64) // st_birthtime is available only on 10.5 struct stat64 st; if (stat64(_path.c_str(), &st) == 0) return Timestamp::fromEpochTime(st.st_birthtime); #elif defined(__FreeBSD__) struct stat st; if (stat(_path.c_str(), &st) == 0) return Timestamp::fromEpochTime(st.st_birthtime); #else struct stat st; if (stat(_path.c_str(), &st) == 0) return Timestamp::fromEpochTime(st.st_ctime); #endif else handleLastErrorImpl(_path); return 0; }
DateTime& DateTime::assign(int year, int month, int day, int hour, int minute, int second, int millisecond, int microsecond) { poco_assert (year >= 0 && year <= 9999); poco_assert (month >= 1 && month <= 12); poco_assert (day >= 1 && day <= daysOfMonth(year, month)); poco_assert (hour >= 0 && hour <= 23); poco_assert (minute >= 0 && minute <= 59); poco_assert (second >= 0 && second <= 59); poco_assert (millisecond >= 0 && millisecond <= 999); poco_assert (microsecond >= 0 && microsecond <= 999); _utcTime = toUtcTime(toJulianDay(year, month, day)) + 10*(hour*Timespan::HOURS + minute*Timespan::MINUTES + second*Timespan::SECONDS + millisecond*Timespan::MILLISECONDS + microsecond); _year = year; _month = month; _day = day; _hour = hour; _minute = minute; _second = second; _millisecond = millisecond; _microsecond = microsecond; return *this; }
std::string& replaceInPlace(std::string& str, const std::string& from, const std::string& to, std::string::size_type start) { poco_assert (from.size() > 0); std::string result; std::string::size_type pos = 0; result.append(str, 0, start); do { pos = str.find(from, start); if (pos != std::string::npos) { result.append(str, start, pos - start); result.append(to); start = pos + from.length(); } else result.append(str, start, str.size() - start); } while (pos != std::string::npos); str.swap(result); return str; }
void run() { poco_assert (_pIsolate == _pExecutor->isolate()); v8::Locker locker(_pIsolate); v8::Isolate::Scope isoScope(_pIsolate); v8::HandleScope handleScope(_pIsolate); v8::Local<v8::Context> context(v8::Local<v8::Context>::New(_pIsolate, _pExecutor->scriptContext())); v8::Context::Scope contextScope(context); ServiceRefWrapper wrapper; v8::Persistent<v8::Object>& serviceRefWrapper(wrapper.wrapNativePersistent(_pIsolate, _pServiceRef)); v8::Local<v8::Function> localFunction(v8::Local<v8::Function>::New(_pIsolate, _function)); v8::Local<v8::Value> receiver(v8::Null(_pIsolate)); v8::Local<v8::Value> args[] = { v8::Local<v8::Object>::New(_pIsolate, serviceRefWrapper) }; _pExecutor->callInContext(localFunction, receiver, 1, args); }