void net::ssl::SSLConnectionClientFactory::initializeContext() { #if defined(USE_OPENSSL) SSL_library_init(); SSL_load_error_strings(); #if defined(OPENSSL_0_9_8) SSL_METHOD *method = SSLv23_client_method(); #else const SSL_METHOD *method = SSLv23_client_method(); #endif if(method == NULL) { throw net::ssl::SSLException(Ctxt(FmtX("SSLv23_client_method failed"))); } mCtx = SSL_CTX_new(method); if(mCtx == NULL) { throw net::ssl::SSLException(Ctxt(FmtX("SSL_CTX_new failed"))); } if(mClientAuthentication) { // Load our keys and certificates if(!(SSL_CTX_use_certificate_file(mCtx, mKeyfile.c_str(), SSL_FILETYPE_PEM))) throw net::ssl::SSLException(Ctxt("Can't read certificate file")); //SSL_CTX_set_default_passwd_cb(mCtx, password_cb); if(!(SSL_CTX_use_PrivateKey_file(mCtx, mKeyfile.c_str(), SSL_FILETYPE_PEM))) throw net::ssl::SSLException(Ctxt("Can't read key file")); // Load the CAs we trust if(!(SSL_CTX_load_verify_locations(mCtx, mCAList.c_str(), 0))) throw net::ssl::SSLException(Ctxt("Can't read CA list")); // Set our cipher list if(mCiphers) { SSL_CTX_set_cipher_list(mCtx, mCiphers); } } // Load randomness /* if(!RAND_load_file("random.pem", 1024*1024)) throw net::ssl::SSLException(Ctxt("Couldn't load randomness")); */ #if (OPENSSL_VERSION_NUMBER < 0x00905100L) SSL_CTX_set_verify_depth(mCtx, 1); #endif #endif }
void ImageSubheader::setPixelInformation(std::string pvtype, nitf::Uint32 nbpp, nitf::Uint32 abpp, std::string justification, std::string irep, std::string icat, std::vector<nitf::BandInfo>& bands) throw(nitf::NITFException) { const size_t bandCount = bands.size(); nitf_BandInfo ** bandInfo = (nitf_BandInfo **)NITF_MALLOC( sizeof(nitf_BandInfo*) * bandCount); if (!bandInfo) { throw nitf::NITFException(Ctxt(FmtX("Out of Memory"))); } for (size_t i = 0; i < bandCount; i++) { bandInfo[i] = nitf_BandInfo_clone(bands[i].getNative(), &error); if (!bandInfo[i]) throw nitf::NITFException(&error); } NITF_BOOL x = nitf_ImageSubheader_setPixelInformation(getNativeOrThrow(), pvtype.c_str(), nbpp, abpp, justification.c_str(), irep.c_str(), icat.c_str(), static_cast<nitf::Uint32>(bandCount), bandInfo, &error); if (!x) throw nitf::NITFException(&error); }
void sys::File::create(const std::string& str, int accessFlags, int creationFlags) { // If the truncate bit is on AND the file does exist, // we need to set the mode to TRUNCATE_EXISTING if ((creationFlags & sys::File::TRUNCATE) && sys::OS().exists(str) ) { creationFlags = TRUNCATE_EXISTING; } else { creationFlags = ~sys::File::TRUNCATE & creationFlags; } mHandle = CreateFile(str.c_str(), accessFlags, FILE_SHARE_READ, NULL, creationFlags, FILE_ATTRIBUTE_NORMAL, NULL); if (mHandle == SYS_INVALID_HANDLE) { throw sys::SystemException(Ctxt(FmtX("Error opening file: [%s]", str.c_str()))); } mPath = str; }
std::string sys::OSWin32::getPlatformName() const { OSVERSIONINFO info; info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); if (!GetVersionEx(&info)) throw sys::SystemException("While performing GetVersionEx()"); std::string platform; if (info.dwPlatformId == VER_PLATFORM_WIN32s) { platform = "Windows on Win32 3.1"; } else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { platform = "Windows on Win32 95"; } else if (info.dwPlatformId = VER_PLATFORM_WIN32_NT) { platform = "Windows on Win32 NT"; } else { platform = "Unknown Windows OS"; } return FmtX("%s: %d.%d [build: %d], %s", platform.c_str(), info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber, info.szCSDVersion); }
void sys::OSWin32::setEnv(const std::string& var, const std::string& val, bool overwrite) { BOOL ret = SetEnvironmentVariable(var.c_str(), val.c_str()); if(!ret) throw sys::SystemException(Ctxt(FmtX("Unable to set windows environment variable %s", var.c_str()))); }
std::string sys::OSUnix::getPlatformName() const { struct utsname name; if (uname(&name) == -1) throw sys::SystemException("Uname failed"); return FmtX("%s (%s): %s [build: %s]", name.sysname, name.machine, name.release, name.version); }
sys::SSize_T net::ssl::SSLConnection::read(sys::byte* b, sys::Size_T len) { sys::SSize_T numBytes(0); int val(0); if (len == 0) return -1; numBytes = SSL_read(mSSL, (char*)b, len); #if defined(__DEBUG_SOCKET) std::cout << "======= READ FROM SECURE CONNECTION =========" << std::endl; #endif if (((val = SSL_get_error(mSSL, numBytes)) != SSL_ERROR_NONE) || (numBytes == -1 && (NATIVE_SOCKET_GETLASTERROR() != NATIVE_SOCKET_ERROR(WOULDBLOCK)))) { #if defined(__DEBUG_SOCKET) std::cout << " Error on read!!!" << std::endl; std::cout << "=============================================" << std::endl << std::endl; #endif throw net::ssl::SSLException(Ctxt(FmtX("When receiving %d bytes", len)) ); } else if (numBytes == 0) { #if defined(__DEBUG_SOCKET) std::cout << " Zero byte read (End of connection)" << std::endl; std::cout << "=============================================" << std::endl << std::endl; #endif return -1; } #if defined(__DEBUG_SOCKET) std::cout << FmtX("Read %d bytes from socket:", numBytes) << std::endl; std::cout << "---------------------------------------------" << std::endl; std::cout << std::string(b, numBytes) << std::endl; std::cout << "---------------------------------------------" << std::endl; std::cout << "=============================================" << std::endl << std::endl; #endif return numBytes; }
void io::MMapInputStream::open(const std::string& fname, char* flags) { mLength = mOs.getSize(fname); // std::cout << mLength << std::endl; mFile = fopen(fname.c_str(), "r"); if (!mFile) throw sys::SystemException(FmtX("Failure while opening file: %s", fname.c_str())); _map(); }
void io::StandardErrStream::write(const sys::byte* b, sys::Size_T len) { _STDSTREAM_BEGIN_CS_SEMICOLON_ std::cerr.write((const char*)b, len); //int returnVal = fwrite(b, len, len, stderr); _STDSTREAM_END_CS_SEMICOLON_ if (!std::cerr.good()) throw except::IOException( Ctxt( FmtX("std::cerr stream is bad after requested write: (%d)", len) ) ); }
void sys::DLL::load(const std::string& libName) { // First we get the library name in case you ask mLibName = libName; // Next we load the library mLib = LoadLibrary( mLibName.c_str() ); // Now we check the return value if (!mLib) throw(sys::DLLException(FmtX("Failed to load() DLL: %s", mLibName.c_str() ) ) ); }
_STDERR_DEFINE_MUTEX_SEMICOLON_ _STDOUT_DEFINE_MUTEX_SEMICOLON_ void io::StandardOutStream::write(const sys::byte* b, sys::Size_T len) { _STDSTREAM_BEGIN_CS_SEMICOLON_ std::cout.write((const char*)b, len); _STDSTREAM_END_CS_SEMICOLON_ //int returnVal = fwrite(b, len, len, stdout); if (!std::cout.good()) throw except::IOException( Ctxt( FmtX("std::cout stream is bad after requested write: (%d)", len)) ); }
void sys::File::create(const std::string& str, int accessFlags, int creationFlags) throw (sys::SystemException) { if (accessFlags & sys::File::WRITE_ONLY) creationFlags |= sys::File::TRUNCATE; mHandle = open(str.c_str(), accessFlags | creationFlags, _SYS_DEFAULT_PERM); if (mHandle < 0) { throw sys::SystemException(Ctxt(FmtX("Error opening file [%d]: [%s]", mHandle, str.c_str()))); } mPath = str; }
std::string sys::OSWin32::getEnv(const std::string& s) const { std::string result; DWORD size = GetEnvironmentVariable(s.c_str(), NULL, 0); if (size == 0) throw sys::SystemException(Ctxt(FmtX("Unable to get windows environment variable %s", s.c_str()))); // If we can use a normal size buffer, lets not bother to malloc char *buffer = new char[size + 1]; DWORD retVal = GetEnvironmentVariable(s.c_str(), buffer, size); result = buffer; delete [] buffer; return result; }
std::string io::FileUtils::createFile(std::string dirname, std::string filename, bool overwrite) throw (except::IOException) { sys::OS os; if (!os.exists(dirname)) throw except::IOException(Ctxt(FmtX("Directory does not exist: %s", dirname.c_str()))); str::trim(filename); bool emptyName = filename.empty(); //to protect against full paths being passed in filename = emptyName ? filename : sys::Path::basename(filename); std::string outFilename = sys::Path::joinPaths(dirname, filename); if (emptyName || (os.exists(outFilename) && !overwrite)) { std::string ext = ""; if (!emptyName) { sys::Path::StringPair nameExt = sys::Path::splitExt(filename); filename = nameExt.first; ext = nameExt.second; int count = 0; while (os.exists(outFilename)) { std::string base = filename + "-" + str::toString(++count); outFilename = sys::Path::joinPaths(dirname, base); if (!ext.empty()) { outFilename += ext; } } } else { //just create a temp filename outFilename = os.getTempName(dirname); } //now, touch it io::FileUtils::touchFile(outFilename); } return outFilename; }
sys::Off_T sys::File::lastModifiedTime() { FILETIME creationTime, lastAccessTime, lastWriteTime; BOOL ret = GetFileTime(mHandle, &creationTime, &lastAccessTime, &lastWriteTime); if (ret) { ULARGE_INTEGER uli; uli.LowPart = lastWriteTime.dwLowDateTime; uli.HighPart = lastWriteTime.dwHighDateTime; ULONGLONG stInMillis(uli.QuadPart/10000); return (sys::Off_T)stInMillis; } throw sys::SystemException(Ctxt( FmtX("Error getting last modified time for path %s", mPath.c_str()))); }
/* * Dump all files out to the local directory * */ std::vector<std::string> extractXML(std::string inputFile, const sys::Path& outputDir) { std::vector<std::string> allFiles; std::string prefix = sys::Path::basename(inputFile, true); nitf::Reader reader; nitf::IOHandle io(inputFile); nitf::Record record = reader.read(io); nitf::Uint32 numDES = record.getNumDataExtensions(); for (nitf::Uint32 i = 0; i < numDES; ++i) { nitf::DESegment segment = record.getDataExtensions()[i]; nitf::DESubheader subheader = segment.getSubheader(); nitf::SegmentReader deReader = reader.newDEReader(i); nitf::Off size = deReader.getSize(); std::string typeID = subheader.getTypeID().toString(); str::trim(typeID); sys::Path fileName(outputDir, FmtX("%s-%s%d.xml", prefix.c_str(), typeID.c_str(), i)); char* xml = new char[size]; deReader.read(xml, size); io::StringStream oss; oss.write(xml, size); xml::lite::MinidomParser parser; parser.parse(oss); xml::lite::Document* doc = parser.getDocument(); io::FileOutputStream fos(fileName.getPath()); doc->getRootElement()->prettyPrint(fos); fos.close(); delete[] xml; allFiles.push_back(fileName.getPath()); } io.close(); return allFiles; }
net::ssl::SSLConnection::SSLConnection(std::auto_ptr<net::Socket> socket, SSL_CTX * ctx, bool serverAuth, const std::string& host) : NetConnection(socket), mServerAuthentication(serverAuth) { mSSL = NULL; mBioErr = BIO_new_fp(stderr, BIO_NOCLOSE); mSSL = SSL_new(ctx); if(mSSL == NULL) { throw net::ssl::SSLException(Ctxt(FmtX("SSL_new failed"))); } setupSocket(host); }
XMLElem ComplexXMLParser10x::convertAntennaParamArrayToXML( const std::string& name, const GainAndPhasePolys* array, XMLElem apXML) const { //! mandatory field in 1.0 if (array) { XMLElem arrXML = newElement("Array", apXML); common().createPoly2D("GainPoly", array->gainPoly, arrXML); common().createPoly2D("PhasePoly", array->phasePoly, arrXML); return arrXML; } else { throw except::Exception(Ctxt(FmtX( "[Array] is a mandatory field in AntennaParams of [%s] in 1.0", name.c_str()))); } }
DLL_FUNCTION_PTR sys::DLL:: retrieve(const std::string& functionName) { // Check to make sure we have a library if ( mLib != NULL ) { // Now we get a ptr DLL_FUNCTION_PTR ptr = (DLL_FUNCTION_PTR) GetProcAddress(mLib, functionName.c_str()); // Now we check the ptr value if (ptr == NULL) throw(sys::DLLException(FmtX("Failed to load function: %s", functionName.c_str()))); return ptr; } else { throw(sys::DLLException("No library loaded") ); }; }
void net::ssl::SSLConnection::write(const sys::byte* b, sys::Size_T len) { int numBytes(0); if (len <= 0) return; numBytes = SSL_write(mSSL, (const char*)b, len); if (numBytes != len) { throw net::ssl::SSLException(Ctxt(FmtX("Tried sending %d bytes, %d sent", len, numBytes)) ); } #if defined(__DEBUG_SOCKET) std::cout << "========== WROTE TO SECURE CONNECTION =============" << std::endl; std::cout << "---------------------------------------------" << std::endl; std::cout << std::string(b, len) << std::endl; std::cout << "---------------------------------------------" << std::endl; std::cout << "=============================================" << std::endl << std::endl; #endif }
void net::ssl::SSLConnection::setupSocket(const std::string& hostName) { net::Socket_T fd = mSocket->getHandle(); BIO *sbio = BIO_new_socket(fd, BIO_NOCLOSE); SSL_set_bio(mSSL, sbio, sbio); int val = SSL_connect(mSSL); if(val <= 0) { #if defined(__DEBUG_SOCKET) if(SSL_get_error(mSSL, val) == SSL_ERROR_WANT_CONNECT) printf("ERROR_WANT_CONNECT\n"); else if(SSL_get_error(mSSL, val) == SSL_ERROR_ZERO_RETURN) printf("ERROR_ZERO_RETURN\n"); else if(SSL_get_error(mSSL, val) == SSL_ERROR_SSL) { printf("ERROR_SSL: "); char buffer[120]; ERR_error_string(val, buffer); BIO_printf(mBioErr, "%s\n", buffer); } else if(SSL_get_error(mSSL, val) == SSL_ERROR_SYSCALL) { printf("ERROR_SYSCALL: "); char buffer[120]; ERR_error_string(val, buffer); BIO_printf(mBioErr, "%s\n", buffer); } else if(SSL_get_error(mSSL, val) == SSL_ERROR_NONE) printf("NO ERROR: WHY AM I HERE?\n"); #endif throw net::ssl::SSLException (Ctxt(FmtX("SSL_connect failed: %d", SSL_get_error(mSSL, val)))); } if(mServerAuthentication) { verifyCertificate(hostName); } }
void DerivedClassification::setSecurity(const std::string& prefix, logging::Logger& log, nitf::FileSecurity security) const { if (classification != "U") { if (!releasableTo.empty()) { std::string releasableToStr; for (size_t ii = 0; ii < releasableTo.size(); ++ii) { if (ii > 0) { releasableToStr += " "; } releasableToStr += releasableTo[ii]; } security.getReleasingInstructions().set(releasableToStr); const std::string fieldKey = NITFImageInfo::generateFieldKey(NITFImageInfo::REL, prefix); log.debug(Ctxt(FmtX("Setting NITF [%s] from sicd/sidd: [%s]", fieldKey.c_str(), releasableToStr.c_str()))); } if (!classifiedBy.empty()) { security.getClassificationAuthority().set(classifiedBy); std::string fieldKey = NITFImageInfo::generateFieldKey(NITFImageInfo::CAUT, prefix); log.debug(Ctxt(FmtX("Setting NITF [%s] from sicd/sidd: [%s]", fieldKey.c_str(), classifiedBy.c_str()))); // classifiedBy attribute represents the name of the original // classification authority const std::string classAuthorityType("O"); security.getClassificationAuthorityType().set(classAuthorityType); fieldKey = NITFImageInfo::generateFieldKey(NITFImageInfo::CATP, prefix); log.debug(Ctxt(FmtX("Setting NITF [%s] from sicd/sidd: [%s]", fieldKey.c_str(), classAuthorityType.c_str()))); } if (!classificationReason.empty()) { security.getClassificationReason().set(classificationReason); const std::string fieldKey = NITFImageInfo::generateFieldKey(NITFImageInfo::CRSN, prefix); log.debug(Ctxt(FmtX("Setting NITF [%s] from sicd/sidd: [%s]", fieldKey.c_str(), classificationReason.c_str()))); } // By default, mark as exempt from automatic declassification std::string declassType("X"); if (declassDate.get() != NULL) { std::string declassDateStr; declassDate->format("%Y%m%d", declassDateStr); str::trim(declassDateStr); security.getDeclassificationDate().set(declassDateStr); const std::string fieldKey = NITFImageInfo::generateFieldKey(NITFImageInfo::DCDT, prefix); log.debug(Ctxt(FmtX("Setting NITF [%s] from sicd/sidd: [%s]", fieldKey.c_str(), declassDateStr.c_str()))); // Declassify on a specific date declassType = "DD"; } if (!declassEvent.empty()) { security.getClassificationText().set(declassEvent); const std::string fieldKey = NITFImageInfo::generateFieldKey(NITFImageInfo::CLTX, prefix); log.debug(Ctxt(FmtX("Setting NITF [%s] from sicd/sidd: [%s]", fieldKey.c_str(), declassEvent.c_str()))); // Declassify upon occurrence of an event declassType = "DE"; } if (!exemptedSourceType.empty()) { // Attributes are 'OADR' or 'X[1-8]' // TODO Should the NITF field get set to something if this is set // to 'OADR'? if (exemptedSourceType.length() == 2 && exemptedSourceType[0] == 'X' && exemptedSourceType[1] >= '1' && exemptedSourceType[1] <= '8') { security.getDeclassificationExemption().set( exemptedSourceType); const std::string fieldKey = NITFImageInfo::generateFieldKey(NITFImageInfo::DCXM, prefix); log.debug(Ctxt(FmtX("Setting NITF [%s] from sicd/sidd: [%s]", fieldKey.c_str(), exemptedSourceType.c_str()))); // Exempt from automatic declassification declassType = "X"; } } if (!declassException.empty()) { // declassException attributes are named // '25X[1-9]' or '25X1-human' // Corresponding NITF Declassification Exemption field values are // named 'X25[1-9]' std::string declassExemption; if (declassException == "25X1-human") { declassExemption = "X251"; } else if (declassException.length() == 4 && declassException[0] == '2' && declassException[1] == '5' && declassException[2] == 'X') { const char ch(declassException[3]); if (ch >= '1' && ch <= '9') { declassExemption = "X25" + ch; } } if (!declassExemption.empty()) { security.getDeclassificationExemption().set(declassExemption); const std::string fieldKey = NITFImageInfo::generateFieldKey(NITFImageInfo::DCXM, prefix); log.debug(Ctxt(FmtX("Setting NITF [%s] from sicd/sidd: [%s]", fieldKey.c_str(), declassExemption.c_str()))); // Exempt from automatic declassification declassType = "X"; } } // Now that we've gone through all the things that could modify the // declassification type, set it security.getDeclassificationType().set(declassType); log.debug(Ctxt(FmtX( "Setting NITF [%s] from sicd/sidd: [%s]", NITFImageInfo::generateFieldKey(NITFImageInfo::DCTP, prefix).c_str(), declassType.c_str()))); } }
/*! * Returns an ID that represents this particular object. * Currently, the ID is the stringized memory address of the underlying * memory. * * This *could* be used for equality purposes, however be warned, because * as objects die, etc. the memory addresses will be reused. */ std::string getObjectID() const { return FmtX("%p", getNative()); }