// // Constructor // SSLSocket::SSLSocket(const InetAddress& address, in_port_t port, SSLContext* context) throw(IOException, SystemException) : Socket(address, port), _context(context), _session(NULL) { // TODO: check if context is != NULL /* Connect the SSL socket */ _ssl = SSL_new(_context->_ctx); _sbio = BIO_new_socket(_impl->_fd, BIO_NOCLOSE); SSL_set_bio(_ssl, _sbio, _sbio); //SSL_set_connect_state(_ssl); // Verify certificate if (SSL_get_verify_result(_ssl) != X509_V_OK) { throw IOException("SSLSocket: Certificate doesn't verified"); } _session_creation = true; _use_client_mode = true; }
// Close the file handle. void FileHandleImplUNIX::close() { vprDEBUG(vprDBG_ALL, vprDBG_VERB_LVL) << "[vpr::FileHandleImplUNIX::close()] Closing file descriptor " << mFdesc << std::endl << vprDEBUG_FLUSH; if ( ::close(mFdesc) == -1 ) { vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << "[vpr::FileHandleImplUNIX::close()] Could not close " << mName << ": " << strerror(errno) << std::endl << vprDEBUG_FLUSH; throw IOException("[vpr::FileHandleImplUNIX::close()] Could not close " + mName + ": " + std::string(strerror(errno)), VPR_LOCATION); } else { mFdesc = -1; mOpen = false; } }
// Open the file handle. void FileHandleImplUNIX::open() { int open_flags(mOpenMode); if ( ! mOpenBlocking ) { open_flags |= O_NONBLOCK; } mFdesc = ::open(mName.c_str(), open_flags); // If the file handle was not returned successfully, print an error // message explaining why. if ( mFdesc == -1 ) { // If we are opening in non-blocking mode, we do not want to bomb out. if ( errno == EWOULDBLOCK && ! mOpenBlocking ) { mOpen = true; throw WouldBlockException("Would block.", VPR_LOCATION); } // Otherwise, report the error. else { mOpen = false; vprDEBUG(vprDBG_ERROR, vprDBG_CRITICAL_LVL) << "[vpr::FileHandleImplUNIX::open()] Could not open " << mName << ": " << strerror(errno) << std::endl << vprDEBUG_FLUSH; throw IOException("[vpr::FileHandleImplUNIX::open()] Could not open " + mName + ": " + std::string(strerror(errno)), VPR_LOCATION); } } // Otherwise, set mOpen to true. else { mOpen = true; mBlocking = mOpenBlocking; } }
void NoSeekFile::fill_cache(std::streamsize size) { #ifdef GNASH_NOSEEK_FD_VERBOSE std::cerr << boost::format(" fill_cache(%d) called") % size << std::endl; #endif assert(size >= 0); // See how big is the cache while (_cached < static_cast<size_t>(size)) { #ifdef GNASH_NOSEEK_FD_VERBOSE size_t bytesNeeded = size - _cached; bytesNeeded = std::min<size_t>(bytesNeeded, chunkSize); std::cerr << boost::format(" bytes needed = %d") % bytesNeeded << std::endl; #endif std::streamsize bytesRead = ::read(_fd, _buf, chunkSize); if (bytesRead < 0) { std::cerr << boost::format(_("Error reading %d bytes from " "input stream")) % chunkSize << std::endl; _running = false; // this looks like a CRITICAL error (since we don't handle it..) throw IOException("Error reading from input stream"); } if (bytesRead < chunkSize) { if (bytesRead == 0) { #ifdef GNASH_NOSEEK_FD_VERBOSE std::cerr << "EOF reached" << std::endl; #endif _running = false; return; } } cache(_buf, bytesRead); } }
StringSet SourceHighlightUtils::getFileNames(const std::string path, const std::string fileExtension) { StringSet strings; DIR *dp; struct dirent *ep; dp = opendir(path.c_str()); if (dp != NULL) { while ((ep = readdir(dp))) { const string name(ep->d_name); if (get_file_extension(name) == fileExtension) { strings.insert(name); } } (void) closedir(dp); } else { throw IOException("Couldn't open the directory", path); } return strings; }
void MemoryStream::Seek(sint64 offset, sint32 origin) { uint64 newPosition; switch (origin) { default: case STREAM_SEEK_BEGIN: newPosition = offset; break; case STREAM_SEEK_CURRENT: newPosition = GetPosition() + offset; break; case STREAM_SEEK_END: newPosition = _dataSize + offset; break; } if (newPosition > _dataSize) { throw IOException("New position out of bounds."); } _position = (void*)((uintptr_t)_data + (uintptr_t)newPosition); }
void BinTreeNodeReader::fillArray(QByteArray& buffer, quint32 len) { char data[1025]; buffer.clear(); // bool ready = true; /* if (socket->bytesAvailable() < 1) { Utilities::logData("fillArray() waiting for bytes"); ready = socket->waitForReadyRead(READ_TIMEOUT); } if (!ready) { Utilities::logData("fillArray() not ready / timed out"); throw IOException(socket->error()); } */ int needToRead = len; while (needToRead > 0) { int bytesRead = socket->read(data,(needToRead > 1024) ? 1024 : needToRead); if (bytesRead < 0) throw IOException(socket->error()); if (bytesRead == 0) // socket->waitForReadyRead(READ_TIMEOUT); qApp->processEvents(); else { needToRead -= bytesRead; buffer.append(data,bytesRead); } } }
CDEC_NS_BEGIN // -------------------------------------------------------------------------- // #if !defined(X_OS_WINDOWS) #include <unistd.h> #include <fcntl.h> void FileWrapper::Open(PCWSTR path, AccessMode access, ShareMode share, bool fCreate) { ASSERT(!IsOpen() && path != NULL && *path != 0); size_t len = wstrlen16(path); std::string patha = cdec::Encoding::get_Default()->FromUnicode(path, len); int oflag = 0; switch (access) { case AccessMode::AccessRead: oflag |= O_RDONLY; break; case AccessMode::AccessWrite: oflag |= O_WRONLY; break; case AccessMode::AccessReadWrite: oflag |= O_RDWR; break; default: cdec_throw(IOException(EC_InvalidArg)); } if (fCreate) m_fd = open(patha.c_str(), oflag | O_CREAT, S_IRWXU); else m_fd = open(patha.c_str(), oflag); if (m_fd == -1) cdec_throw_stdc_lasterr(IOException); }
qint64 BgzfReader::read(char *buff, qint64 maxSize) { if(0 == maxSize) { return 0; } stream.next_out = (Bytef *)buff; stream.avail_out = maxSize; while(stream.avail_out > 0) { if(0 == stream.avail_in) { qint64 returnedValue = ioAdapter.readBlock(buffer, sizeof(buffer)); if(-1 == returnedValue) { coreLog.error(QString("in BgzfReader::read, failed to read %1 bytes from ioAdapter, after %2 bytes already read. %3") .arg(sizeof(buffer)) .arg(ioAdapter.bytesRead()) .arg(ioAdapter.errorString())); throw IOException(BAMDbiPlugin::tr("Can't read input")); } else if(0 == returnedValue) { endOfFile = true; break; } else { stream.avail_in = returnedValue; stream.next_in = (Bytef *)buffer; } } int returnedValue = inflate(&stream, Z_SYNC_FLUSH); if(Z_STREAM_END == returnedValue) { nextBlock(); } else if(Z_OK != returnedValue) { coreLog.error(QString("in BgzfReader::read, failed to decompress %1 bytes, after %2 raw bytes already read") .arg(sizeof(buffer)) .arg(ioAdapter.bytesRead())); throw InvalidFormatException(BAMDbiPlugin::tr("Can't decompress data")); } } if(0 == stream.avail_in) { nextBlock(); } qint64 bytesRead = maxSize - stream.avail_out; return bytesRead; }
std::vector<std::vector<unsigned char> > SerialThrustMasterBase::read() { std::vector<std::vector<unsigned char> > results; int availableBytes; if (ioctl(handle, FIONREAD, &availableBytes) == -1) { throw IOException("Failed to get number of bytes available for " + name + ": " + std::strerror(errno)); } // If a full packet is available or a timeout has occurred, process all available data. if (availableBytes >= 9 || getTime() > timeout) { int remainingBytes = availableBytes; std::vector<unsigned char> buffer(remainingBytes); /** * While we know how many bytes are avialable, read can still be interrupted by signals, * so call it in a loop. */ while (remainingBytes) { remainingBytes -= SerialDevice::read(&buffer[0] + (availableBytes - remainingBytes), remainingBytes); } /** * Only return the data to the caller if exactly one full packet arrived. If a timeout * occurred or extra bytes arrived, discard all of the data. */ if (availableBytes == 9) { results.push_back(buffer); } /** * Request the next state update from the device. Sending requests too quickly can corrupt * the device's output, so we only send a new request when at least a full packet has * arrived or a timeout occured. */ requestData(); } return results; }
void Thread::StartNonDetachedWithCleanup() { if(! runnable_) { LOG_ERROR("Null runnable, Thread already started??"); throw fungi::IOException("Thread already started"); } ManagedRunnable* wrapper = new ManagedRunnable(*runnable_, true); runnable_ = 0; int res = pthread_create(&thread_, &attr_, thread_start_util_, wrapper); if (res != 0) { throw IOException("Thread::start", "pthread_create", res); } }
void DownloadOperation::onDownloadReply() { if (m_fos != NULL) { try { m_fos->close(); } catch (...) { } delete m_fos; } if (m_file != NULL) { delete m_file; } m_file = new File(m_pathToTargetFile.getString()); if (m_fileOffset == 0) { m_file->truncate(); } try { m_fos = new FileOutputStream(m_file); FileSeeker fileSeeker(m_fos->getFD()); if (!fileSeeker.seek((INT64)m_fileOffset)) { throw IOException(_T("Cannot seek to initial file position")); } m_totalBytesCopied += m_fileOffset; } catch (IOException &ioEx) { notifyFailedToDownload(ioEx.getMessage()); gotoNext(); return ; } UINT32 dataSize = 1024 * 8; bool compression = m_replyBuffer->isCompressionSupported(); m_sender->sendDownloadDataRequest(dataSize, compression); }
void FileOutputStream::open(const String fileName, bool append) { Locker locker(m_mutex); if (m_fileDescriptor != -1) { close(); } // Write access, create if needed int flags = O_WRONLY | O_CREAT; // Support large files if the OS supports it #ifdef O_LARGEFILE flags |= O_LARGEFILE; #endif // If passed in append, mask on the append option, // otherwise truncate the file if (append) { flags |= O_APPEND; } else { flags |= O_TRUNC; } m_fileDescriptor = UnixUtil::sys_open(fileName.c_str(), // File name flags, // Creation flags, see above 0666); // File mask if created if (m_fileDescriptor == -1) { throw IOException(String("Failed to open file: ") + UnixUtil::getLastErrorMessage()); } }
void Thread::StartWithoutCleanup() { if(! runnable_) { LOG_ERROR("Null runnable, Thread already started??"); throw fungi::IOException("Thread already started"); } std::pair<Runnable*, Thread*>* pa= new std::pair<Runnable*, Thread*>(runnable_, this); runnable_ = 0; int res = pthread_create(&thread_, &attr_, &::second_thread_start_util, pa); if (res != 0) { throw IOException("Thread::start", "pthread_create", res); } }
vpr::Uint32 SerialPortImplWin32::write_i(const void* buffer, const vpr::Uint32 length, const vpr::Interval& timeout) { unsigned long bytes; if ( vpr::Interval::NoTimeout != timeout ) { vprDEBUG(vprDBG_ALL,vprDBG_WARNING_LVL) << "[vpr::SerialPortImplWin32::write_i()] Timeout not supported\n" << vprDEBUG_FLUSH; } if ( ! WriteFile(mHandle, buffer, length, &bytes, NULL) ) { std::stringstream msg_stream; msg_stream << "Failed to write to serial port " << mName << ": " << getErrorMessageWithCode(GetLastError()); throw IOException(msg_stream.str(), VPR_LOCATION); } return bytes; }
DeflatingStreamBuf::DeflatingStreamBuf(std::ostream& ostr, StreamType type, int level): BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::out), _pIstr(0), _pOstr(&ostr), _eof(false) { _zstr.zalloc = Z_NULL; _zstr.zfree = Z_NULL; _zstr.opaque = Z_NULL; _zstr.next_in = 0; _zstr.avail_in = 0; _zstr.next_out = 0; _zstr.avail_out = 0; _buffer = new char[DEFLATE_BUFFER_SIZE]; int rc = deflateInit2(&_zstr, level, Z_DEFLATED, 15 + (type == STREAM_GZIP ? 16 : 0), 8, Z_DEFAULT_STRATEGY); if (rc != Z_OK) { delete [] _buffer; throw IOException(zError(rc)); } }
int SerialChannelImpl::writeImpl(const std::string& data) { if (0 == data.length()) return 0; std::string d = data; if (_config.getUseEOFImpl()) { size_t pos = d.find(_config.getEOFCharImpl()); if (pos != d.npos) d = d.substr(0, pos+1); } DWORD written = 0; DWORD length = static_cast<DWORD>(d.length()); if (!WriteFile(_handle, d.data(), length, &written, NULL) || ((written != length) && (0 != written))) handleError(_name); else if (0 == written) throw IOException("Error writing to " + _name); return written; }
ByteArray TCPSocket::read(size_t maxSize) { ByteArray ba(maxSize); // Return empty array if size is 0 if (maxSize == 0) { return ba; } // Read from socket ssize_t size = ::read(d->fd, ba.data(), ba.size()); // Check for errors if (size < 0) { switch (errno) { case EAGAIN: case ETIMEDOUT: throw TimeoutException("TCPSocket::read", strerror(errno)); case EPIPE: throw DisconnectedException("TCPSocket::read", strerror(errno)); default: throw IOException("TCPSocket::read", strerror(errno)); } } // If size is 0, means the socket is disconnected if (size == 0) { throw DisconnectedException("TCPSocket::read", "Disconnected"); } // Return a byte-array of the actual read size return ByteArray(ba.constData(), size); }
vector<string> resolveHostname(const string &hostname, unsigned int port, bool shuffle) { string portString = toString(port); struct addrinfo hints, *res, *current; vector<string> result; int ret; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; ret = getaddrinfo(hostname.c_str(), (port == 0) ? NULL : portString.c_str(), &hints, &res); if (ret != 0) { throw IOException(string("Error resolving ") + hostname + ": " + gai_strerror(ret)); } for (current = res; current != NULL; current = current->ai_next) { char host[NI_MAXHOST]; ret = getnameinfo(current->ai_addr, current->ai_addrlen, host, sizeof(host) - 1, NULL, 0, NI_NUMERICHOST); if (ret == 0) { result.push_back(host); } else { P_WARN("Cannot get name info for one of the resolved " "IP addresses in host name " << hostname); } } freeaddrinfo(res); if (shuffle) { random_shuffle(result.begin(), result.end()); } return result; }
// Get the character size (the bits per byte). vpr::SerialTypes::CharacterSizeOption SerialPortImplWin32::getCharacterSize() const { vpr::SerialTypes::CharacterSizeOption size; DCB dcb; if ( GetCommState(mHandle, &dcb) ) { switch ( dcb.ByteSize ) { case 5: size = vpr::SerialTypes::CS_BITS_5; break; case 6: size = vpr::SerialTypes::CS_BITS_6; break; case 7: size = vpr::SerialTypes::CS_BITS_7; break; case 8: size = vpr::SerialTypes::CS_BITS_8; break; } } else { std::stringstream msg_stream; msg_stream << "Failed to acquire bits/byte: " << getErrorMessageWithCode(GetLastError()); vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL) << clrOutBOLD(clrYELLOW, "WARNING") << ": " << msg_stream.str() << std::endl << vprDEBUG_FLUSH; throw IOException(msg_stream.str(), VPR_LOCATION); } return size; }
void FileImpl::handleLastErrorImpl(const std::string& path) { switch (errno) { case EIO: throw IOException(path, errno); case EPERM: throw FileAccessDeniedException("insufficient permissions", path, errno); case EACCES: throw FileAccessDeniedException(path, errno); case ENOENT: throw FileNotFoundException(path, errno); case ENOTDIR: throw OpenFileException("not a directory", path, errno); case EISDIR: throw OpenFileException("not a file", path, errno); case EROFS: throw FileReadOnlyException(path, errno); case EEXIST: throw FileExistsException(path, errno); case ENOSPC: throw FileException("no space left on device", path, errno); case EDQUOT: throw FileException("disk quota exceeded", path, errno); #if !defined(_AIX) case ENOTEMPTY: throw FileException("directory not empty", path, errno); #endif case ENAMETOOLONG: throw PathSyntaxException(path, errno); case ENFILE: case EMFILE: throw FileException("too many open files", path, errno); default: throw FileException(std::strerror(errno), path, errno); } }
void TCPSocket::flush() { size_t sent = 0; while (sent < d->sendbuf.size()) { ssize_t size = ::write(d->fd, d->sendbuf.data(), d->sendbuf.size()); if (size < 0) { switch (errno) { case EAGAIN: case ETIMEDOUT: throw TimeoutException("TCPSocket::flush", strerror(errno)); case EPIPE: throw DisconnectedException("TCPSocket::flush", strerror(errno)); default: throw IOException("TCPSocket::flush", strerror(errno)); } } sent += size; } d->sendbuf.clear(); }
void DFA::read(Source &r) { #undef pt #define pt(a) //pr(a) reset(); int v; r >> v; pt((" version = %d\n",v)); if (v != VERSION) throw IOException("Bad version in DFA"); short sCnt; short sState; short tokenNameCount; r >> sCnt >> sState >> tokenNameCount; pt((" # states=%d, start=%d\n",sCnt,sState)); for (int i = 0; i < sCnt; i++) { addState(i); DFAState &s = getState(i); pt((" reading state %d\n",i)); s.read(r); } setStartState(sState); for (int i = 0; i < tokenNameCount; i++) { String n; r >> n; tokenNames_.add(n); pt((" token %d= %s\n",i,n.chars() )); } pt((" done reading\n")); }
string GetInputFileName(string prompt) { string temp = ""; bool validFileName = true; do{ cin.clear(); //Prompt the user to enter a value. cout << prompt; //place the value in string temp getline(cin, temp); //check to see if CTRL-Z has been pressed if (cin.eof()){ throw IOException(ERROR_EOF, EXIT); cin.clear(); return 0; } validFileName = ValidateFileName(temp); } while (!validFileName);//end while loop return temp; }
uint64 CStdFile::GetPosition() { long long pos = _ftelli64(m_fp); if (pos == -1LL) { char* msg; switch (errno) { case EBADF: msg = "Handle is not a valid file pointer or the file is not open"; break; case EINVAL: msg = "Handle is not a valid file stream"; break; default: msg = "IO error"; } raise(IOException(msg)); } return (uint64)pos; }
InflatingStreamBuf::InflatingStreamBuf(std::istream& istr, int windowBits): BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::in), _pIstr(&istr), _pOstr(0), _eof(false), _check(false) { _zstr.zalloc = Z_NULL; _zstr.zfree = Z_NULL; _zstr.opaque = Z_NULL; _zstr.next_in = 0; _zstr.avail_in = 0; _zstr.next_out = 0; _zstr.avail_out = 0; _buffer = new char[INFLATE_BUFFER_SIZE]; int rc = inflateInit2(&_zstr, windowBits); if (rc != Z_OK) { delete [] _buffer; throw IOException(zError(rc)); } }
OldUDPSocket::OldUDPSocket(const IPv4Address &addr, int _port){ #ifdef USE_EMBEDDED_CLASSNAMES setClassName(__xvr2_Net_OldUDPSocket); #endif flags = MSG_NOSIGNAL; port = _port; bzero(&ipv4addr, sizeof(struct ::sockaddr_in)); ipv4addr.sin_family = AF_INET; ipv4addr.sin_port = htons(_port); ipv4addr.sin_addr = *addr.address(); tsock = socket(ipv4addr.sin_family, SOCK_DGRAM, 0); if(tsock < 0){ switch(errno){ case EMFILE: throw ProcOutOfFileDescriptors(); break; case ENFILE: throw SysOutOfFileDescriptors(); break; default: throw IOException(); } } }
BitInputStream::BitInputStream(std::string filename): InputStream() { jcommon::Object::SetClassName("jio::BitInputStream"); haveByte = false; show = false; currentMask = 0; currentByte = 0; try { file = new File(filename); stream = new FileInputStream(file); } catch (...) { if (file != NULL) { delete file; } file = NULL; stream = NULL; throw IOException("Cannot open file in BitInputStream"); } }
InflatingStreamBuf::InflatingStreamBuf(std::ostream& ostr, StreamType type): BufferedStreamBuf(STREAM_BUFFER_SIZE, std::ios::out), _pIstr(0), _pOstr(&ostr), _eof(false), _check(type != STREAM_ZIP) { _zstr.zalloc = Z_NULL; _zstr.zfree = Z_NULL; _zstr.opaque = Z_NULL; _zstr.next_in = 0; _zstr.avail_in = 0; _zstr.next_out = 0; _zstr.avail_out = 0; _buffer = new char[INFLATE_BUFFER_SIZE]; int rc = inflateInit2(&_zstr, 15 + (type == STREAM_GZIP ? 16 : 0)); if (rc != Z_OK) { delete [] _buffer; throw IOException(zError(rc)); } }
void InflaterIOChannel::go_to_end() { if (m_error) { throw IOException("InflaterIOChannel is in error condition, " "can't seek to end"); } // Keep reading until we can't read any more. unsigned char temp[ZBUF_SIZE]; // Seek forwards. for (;;) { const std::streamsize bytes_read = inflate_from_stream(temp, ZBUF_SIZE); if (!bytes_read) { // We've seeked as far as we can. break; } } }