void ConsoleTools::listTypes(bool load, bool useNames){ Writer *writer = null; try{ writer = new StreamWriter(stdout, outputEncodingIndex, bomOutput); ParserFactory pf(catalogPath); HRCParser *hrcParser = pf.getHRCParser(); fprintf(stderr, "\nloading file types...\n"); for(int idx = 0;; idx++){ FileType *type = hrcParser->enumerateFileTypes(idx); if (type == null) break; if (useNames){ writer->write(StringBuffer(type->getName())+"\n"); }else{ if (type->getGroup() != null){ writer->write(StringBuffer(type->getGroup()) + ": "); } writer->write(type->getDescription()); writer->write(DString("\n")); } if (load) type->getBaseScheme(); } delete writer; }catch(Exception &e){ delete writer; fprintf(stderr, "%s\n", e.getMessage()->getChars()); } }
/* * Returns the value of the given property * *@param prop - the property name * *@return A NULL StringBuffer in the returned implies that * the property was not set. Otherwise the value it was * set to is returned (which can be "", the empty string). */ StringBuffer SQLKeyValueStore::readPropertyValue(const char *prop) const { StringBuffer sqlQuery = sqlGetPropertyString(StringBuffer(prop)); Enumeration& en = query(sqlQuery); if (en.hasMoreElement()) { KeyValuePair * kvp = (KeyValuePair*)(en.getNextElement()); return kvp->getValue(); } return StringBuffer(NULL); }
const byte *FileInputSource::openStream() { if (stream != null) throw InputSourceException(StringBuffer("openStream(): source stream already opened: '")+baseLocation+"'"); int source = open(baseLocation->getChars(), O_BINARY); if (source == -1) throw InputSourceException(StringBuffer("Can't open file '")+baseLocation+"'"); struct stat st; fstat(source, &st); len = st.st_size; stream = new byte[len]; read(source, stream, len); close(source); return stream; };
void CFileSpraySoapBindingEx::xsltTransform(const char* xml, const char* sheet, IProperties *params, StringBuffer& ret) { StringBuffer xsl; if (!checkFileExists(sheet)) throw MakeStringException(ECLWATCH_FILE_NOT_EXIST, "Cannot open stylesheet %s",sheet); Owned<IXslProcessor> proc = getXslProcessor(); Owned<IXslTransform> trans = proc->createXslTransform(); trans->setXmlSource(xml, strlen(xml)); trans->loadXslFromFile(sheet); if (params) { Owned<IPropertyIterator> it = params->getIterator(); for (it->first(); it->isValid(); it->next()) { const char *key = it->getPropKey(); //set parameter in the XSL transform skipping over the @ prefix, if any const char* paramName = *key == '@' ? key+1 : key; trans->setParameter(paramName, StringBuffer().append('\'').append(params->queryProp(key)).append('\'').str()); } } trans->transform(ret); }
bool CWsDfuXRefEx::onDFUXRefCleanDirectories(IEspContext &context, IEspDFUXRefCleanDirectoriesRequest &req, IEspDFUXRefCleanDirectoriesResponse &resp) { try { if (!context.validateFeatureAccess(FEATURE_URL, SecAccess_Write, false)) throw MakeStringException(ECLWATCH_DFU_XREF_ACCESS_DENIED, "Failed to clean Xref Directories. Permission denied."); StringBuffer username; context.getUserID(username); DBGLOG("CWsDfuXRefEx::onDFUXRefDirectories User=%s",username.str()); if (!req.getCluster() || !*req.getCluster()) throw MakeStringExceptionDirect(ECLWATCH_INVALID_INPUT, "Cluster not defined."); Owned<IXRefNode> xRefNode = XRefNodeManager->getXRefNode(req.getCluster()); if (xRefNode.get() == 0) return false; StringBuffer buf; xRefNode->removeEmptyDirectories(buf); DBGLOG("xRefNode->removeEmptyDirectories result=%s",buf.str()); resp.setRedirectUrl(StringBuffer("/WsDFUXRef/DFUXRefDirectories?Cluster=").append(req.getCluster())); } catch(IException* e) { FORWARDEXCEPTION(context, e, ECLWATCH_INTERNAL_ERROR); } return true; }
/** Triggers a JS-side exception explaining (in English text) that no overloads could be matched to the given arguments. */ static inline v8::Handle<v8::Value> Call( v8::Arguments const & argv ) { return Toss(StringBuffer()<<"No predicates in the " << "argument dispatcher matched the given " << "arguments (arg count="<<argv.Length() << ")."); }
static bool Cmd_ConScribe_RegisterLog_Execute(COMMAND_ARGS) { UInt32 DefaultFlag = 0; char Buffer[kMaxMessageLength]; const char* ModName = ResolveModName(scriptObj); if (Buffer == NULL || ModName == NULL) return true; else if (!ExtractFormatStringArgs(0, Buffer, paramInfo, arg1, opcodeOffsetPtr, scriptObj, eventList, kCommandInfo_RegisterLog.numParams, &DefaultFlag)) return true; LogManager::GetSingleton()->RegisterMod(ModName); static std::string InvalidChars = "\\/*:?\"<>;|."; std::string StringBuffer(Buffer); if (StringBuffer.find_first_of(InvalidChars) != std::string::npos) { _MESSAGE("Invalid log name '%s' passed in script %08x", Buffer, scriptObj->refID); return true; } else LogManager::GetSingleton()->RegisterLog(ModName, Buffer); if (DefaultFlag) LogManager::GetSingleton()->SetDefaultLog(ModName, Buffer); return true; }
const StringBuffer &CEspApplicationPort::getTitleBarHtml(IEspContext& ctx, bool rawXml) { if (xslp) { VStringBuffer titleBarXml("<EspHeader><BuildVersion>%s</BuildVersion><ConfigAccess>%d</ConfigAccess>", build_ver, viewConfig); const char* authMethod = ctx.getAuthenticationMethod(); if (authMethod && !strieq(authMethod, "none") && (ctx.getDomainAuthType() != AuthPerRequestOnly)) titleBarXml.append("<LogOut>1</LogOut>"); const char* user = ctx.queryUserId(); if (user && *user) titleBarXml.appendf("<LoginId>%s</LoginId>", user); titleBarXml.append("</EspHeader>"); if (rawXml) { titleBarHtml.set(titleBarXml); } else { Owned<IXslTransform> xform = xslp->createXslTransform(); xform->loadXslFromFile(StringBuffer(getCFD()).append("./xslt/espheader.xsl").str()); xform->setXmlSource(titleBarXml.str(), titleBarXml.length()+1); xform->transform(titleBarHtml.clear()); } } return titleBarHtml; }
bool CWsPackageProcessEx::onAddPackage(IEspContext &context, IEspAddPackageRequest &req, IEspAddPackageResponse &resp) { PackageMapUpdater updater; updater.setFlag(PKGADD_MAP_CREATE); updater.setFlag(PKGADD_MAP_ACTIVATE, req.getActivate()); updater.setFlag(PKGADD_MAP_REPLACE, req.getOverWrite()); updater.setFlag(PKGADD_ALLOW_FOREIGN, req.getAllowForeignFiles()); updater.setFlag(PKGADD_PRELOAD_ALL, req.getPreloadAllPackages()); updater.setPMID(req.getTarget(), req.getPackageMap(), req.getGlobalScope()); updater.setProcess(req.getProcess()); updater.setUser(context.queryUserId(), context.queryPassword()); updater.setDerivedDfsLocation(req.getDaliIp(), req.getSourceProcess()); unsigned updateFlags = 0; if (req.getOverWrite()) updateFlags |= (DALI_UPDATEF_PACKAGEMAP | DALI_UPDATEF_REPLACE_FILE | DALI_UPDATEF_CLONE_FROM | DALI_UPDATEF_SUPERFILES); if (req.getReplacePackageMap()) updateFlags |= DALI_UPDATEF_PACKAGEMAP; if (req.getUpdateCloneFrom()) updateFlags |= DALI_UPDATEF_CLONE_FROM; if (req.getUpdateSuperFiles()) updateFlags |= DALI_UPDATEF_SUPERFILES; if (req.getAppendCluster()) updateFlags |= DALI_UPDATEF_APPEND_CLUSTER; StringArray filesNotFound; updater.create(req.getPackageMap(), req.getInfo(), updateFlags, filesNotFound); resp.setFilesNotFound(filesNotFound); resp.updateStatus().setCode(0); resp.updateStatus().setDescription(StringBuffer("Successfully loaded ").append(req.getPackageMap())); return true; }
void ConsoleTools::setInputEncoding(const String &str) { delete inputEncoding; inputEncoding = new SString(str); inputEncodingIndex = Encodings::getEncodingIndex(inputEncoding->getChars()); if (inputEncodingIndex == -1) throw Exception(StringBuffer("Unknown input encoding: ")+inputEncoding); if (outputEncoding == null) outputEncodingIndex = inputEncodingIndex; }
JARInputSource::JARInputSource(const String *basePath, InputSource *base){ if (basePath == null) throw InputSourceException(StringBuffer("Can't create jar source")); // absolute jar uri int ex_idx = basePath->lastIndexOf('!'); if (ex_idx == -1) throw InputSourceException(StringBuffer("Bad jar uri format: ") + basePath); inJarLocation = new SString(basePath, ex_idx+1, -1); sharedIS = new SharedInputSource(&DString(basePath, 4, ex_idx-4), base); sharedIS->addref(); baseLocation = new SString(sharedIS->getLocation()); stream = null; len = 0; };
ESP_FACTORY IEspProtocol * esp_protocol_factory(const char *name, const char* type, IPropertyTree *cfg, const char *process) { if (strcmp(type, "http_protocol")==0) { return new CHttpProtocol; } else if(strcmp(type, "secure_http_protocol") == 0) { IPropertyTree *sslSettings; sslSettings = cfg->getPropTree(StringBuffer("Software/EspProcess[@name=\"").append(process).append("\"]").append("/EspProtocol[@name=\"").append(name).append("\"]").str()); if(sslSettings != NULL) { return new CSecureHttpProtocol(sslSettings); } else { throw MakeStringException(-1, "can't find ssl settings in the config file"); } } else { throw MakeStringException(-1, "Unknown protocol %s", name); } return NULL; }
const StringBuffer &CEspApplicationPort::getTitleBarHtml(IEspContext& ctx, bool rawXml) { if (xslp) { StringBuffer titleBarXml; const char* user = ctx.queryUserId(); if (!user || !*user) titleBarXml.appendf("<EspHeader><BuildVersion>%s</BuildVersion><ConfigAccess>%d</ConfigAccess>" "<LoginId><nobody></LoginId><NoUser>1</NoUser></EspHeader>", build_ver, viewConfig); else titleBarXml.appendf("<EspHeader><BuildVersion>%s</BuildVersion><ConfigAccess>%d</ConfigAccess>" "<LoginId>%s</LoginId></EspHeader>", build_ver, viewConfig, user); if (rawXml) { titleBarHtml.set(titleBarXml); } else { Owned<IXslTransform> xform = xslp->createXslTransform(); xform->loadXslFromFile(StringBuffer(getCFD()).append("./xslt/espheader.xsl").str()); xform->setXmlSource(titleBarXml.str(), titleBarXml.length()+1); xform->transform(titleBarHtml.clear()); } } return titleBarHtml; }
const StringBuffer &CEspApplicationPort::getAppFrameHtml(time_t &modified, const char *inner, StringBuffer &html, IEspContext* ctx) { if (!xslp) throw MakeStringException(0,"Error - CEspApplicationPort XSLT processor not initialized"); bool embedded_url=(inner&&*inner); StringBuffer params; bool needRefresh = true; if (!getUrlParams(ctx->queryRequestParameters(), params)) { if (params.length()==0) needRefresh = false; if (ctx->getClientVersion()>0) { params.appendf("%cver_=%g", params.length()?'&':'?', ctx->getClientVersion()); needRefresh = true; } } if (needRefresh || embedded_url || !appFrameHtml.length()) { int passwordDaysRemaining = scPasswordExpired;//-1 means dont display change password screen #ifdef _USE_OPENLDAP ISecUser* user = ctx->queryUser(); ISecManager* secmgr = ctx->querySecManager(); if(user && secmgr) { passwordDaysRemaining = user->getPasswordDaysRemaining();//-1 if expired, -2 if never expires int passwordExpirationDays = (int)secmgr->getPasswordExpirationWarningDays(); if (passwordDaysRemaining == scPasswordNeverExpires || passwordDaysRemaining > passwordExpirationDays) passwordDaysRemaining = scPasswordExpired; } #endif StringBuffer xml; StringBuffer encoded_inner; if(inner && *inner) encodeXML(inner, encoded_inner); // replace & with &s; params.replaceString("&","&"); xml.appendf("<EspApplicationFrame title=\"%s\" navWidth=\"%d\" navResize=\"%d\" navScroll=\"%d\" inner=\"%s\" params=\"%s\" passwordDays=\"%d\"/>", getESPContainer()->getFrameTitle(), navWidth, navResize, navScroll, (inner&&*inner) ? encoded_inner.str() : "?main", params.str(), passwordDaysRemaining); Owned<IXslTransform> xform = xslp->createXslTransform(); xform->loadXslFromFile(StringBuffer(getCFD()).append("./xslt/appframe.xsl").str()); xform->setXmlSource(xml.str(), xml.length()+1); xform->transform( (needRefresh || embedded_url) ? html.clear() : appFrameHtml.clear()); } if (!needRefresh && !embedded_url) html.clear().append(appFrameHtml.str()); static time_t startup_time = time(NULL); modified = startup_time; return html; }
const byte *JARInputSource::openStream() { if (stream != null) throw InputSourceException(StringBuffer("openStream(): source stream already opened: '")+baseLocation+"'"); MemoryFile *mf = new MemoryFile; mf->stream = sharedIS->getStream(); mf->length = sharedIS->length(); zlib_filefunc_def zlib_ff; fill_mem_filefunc(&zlib_ff, mf); unzFile fid = unzOpen2(null, &zlib_ff); if (fid == 0) throw InputSourceException(StringBuffer("Can't locate file in JAR content: '")+inJarLocation+"'"); int ret = unzLocateFile(fid, inJarLocation->getChars(), 0); if (ret != UNZ_OK) throw InputSourceException(StringBuffer("Can't locate file in JAR content: '")+inJarLocation+"'"); unz_file_info file_info; ret = unzGetCurrentFileInfo(fid, &file_info, null, 0, null, 0, null, 0); if (ret != UNZ_OK) throw InputSourceException(StringBuffer("Can't retrieve current file in JAR content: '")+inJarLocation+"'"); len = file_info.uncompressed_size; stream = new byte[len]; ret = unzOpenCurrentFile(fid); if (ret != UNZ_OK) throw InputSourceException(StringBuffer("Can't open current file in JAR content: '")+inJarLocation+"'"); ret = unzReadCurrentFile(fid, stream, len); if (ret <= 0) throw InputSourceException(StringBuffer("Can't read current file in JAR content: '")+inJarLocation+"' ("+SString(ret)+")"); ret = unzCloseCurrentFile(fid); if (ret == UNZ_CRCERROR) throw InputSourceException(StringBuffer("Bad JAR file CRC")); ret = unzClose(fid); return stream; };
void DocumentBuilder::consume(String &s){ int idx; for(idx = 0; idx < s.length() && peek() == s[idx]; idx++){ get(); } if (idx < s.length()){ throw ParseException(StringBuffer("Invalid sequence. waiting for '")+s+"'"); } }
Matrix3 SvgTransformParser::parseMatrixTransform() { if (args_.size() == 6) { return Matrix3(args_[0], args_[2], args_[4], args_[1], args_[3], args_[5]); } else { throw std::runtime_error(StringBuffer() << "Invalid argument count for SVG transform type \"" << type_ << "\"."); } }
//SHA-1 hash function bool __fastcall SHA1_Hash( FILE *Input) { //Parameters check if (HashFamilyID != HASH_ID_SHA1 || Input == nullptr) { fwprintf_s(stderr, L"Parameters error.\n"); return false; } //Initialization std::shared_ptr<char> Buffer(new char[FILE_BUFFER_SIZE]()), StringBuffer(new char[FILE_BUFFER_SIZE]()); auto HashInstance = std::make_shared<SHA1_State>(); memset(Buffer.get(), 0, FILE_BUFFER_SIZE); memset(StringBuffer.get(), 0, FILE_BUFFER_SIZE); memset(HashInstance.get(), 0, sizeof(SHA1_State)); size_t ReadLength = 0; //SHA-1 initialization SHA1_Init(HashInstance.get()); //Hash process while (!feof(Input)) { memset(Buffer.get(), 0, FILE_BUFFER_SIZE); ReadLength = fread_s(Buffer.get(), FILE_BUFFER_SIZE, sizeof(char), FILE_BUFFER_SIZE, Input); if (ReadLength == 0 && errno == EINVAL) { fwprintf_s(stderr, L"Hash process error.\n"); return false; } else { SHA1_Process(HashInstance.get(), (uint8_t *)Buffer.get(), (unsigned long)ReadLength); } } //Binary to hex memset(Buffer.get(), 0, FILE_BUFFER_SIZE); SHA1_Done(HashInstance.get(), (uint8_t *)Buffer.get()); if (sodium_bin2hex(StringBuffer.get(), FILE_BUFFER_SIZE, (const unsigned char *)Buffer.get(), SHA1_SIZE_DIGEST) == nullptr) { fwprintf_s(stderr, L"Convert binary to hex error.\n"); return false; } else { //Print to screen. std::string HashResult = StringBuffer.get(); CaseConvert(true, HashResult); for (size_t Index = 0;Index < HashResult.length();++Index) fwprintf_s(stderr, L"%c", HashResult.c_str()[Index]); fwprintf_s(stderr, L"\n"); } return true; }
Matrix3 SvgTransformParser::parseScaleTransform() { if (args_.size() == 1) { return Matrix3(args_[0], 0.0f, 0.0f, 0.0f, args_[0], 0.0f); } else if (args_.size() == 2) { return Matrix3(args_[0], 0.0f, 0.0f, 0.0f, args_[1], 0.0f); } else { throw std::runtime_error(StringBuffer() << "Invalid argument count for SVG transform type \"" << type_ << "\"."); } }
void DocumentBuilder::consume(char *s, int len){ int idx; if (len == -1){ len = strlen(s); } for(idx = 0; idx < len && peek() == s[idx]; idx++){ get(); } if (idx < len){ throw ParseException(StringBuffer("Invalid sequence. waiting for '")+s+"'"); } }
JARInputSource::JARInputSource(const String *basePath, InputSource *base){ if (basePath == null) throw InputSourceException(StringBuffer("Can't create jar source")); // absolute jar uri int ex_idx = basePath->lastIndexOf('!'); if (ex_idx == -1) throw InputSourceException(StringBuffer("Bad jar uri format: ") + basePath); inJarLocation = new SString(basePath, ex_idx+1, -1); DString ds_bp(basePath, 4, ex_idx-4); sharedIS = SharedInputSource::getInputSource(&ds_bp, base); StringBuffer str("jar:"); str.append(sharedIS->getLocation()); str.append(DString("!")); str.append(inJarLocation); baseLocation = new SString(&str); stream = null; len = 0; }
const byte *FileInputSource::openStream() { if (stream != null) throw InputSourceException(StringBuffer("openStream(): source stream already opened: '")+baseLocation+"'"); #ifdef _UNICODE int source = open(Wide2MB(baseLocation->getWChars()).c_str(), O_BINARY); #else int source = open(baseLocation->getChars(), O_BINARY); #endif if (source == -1) { fprintf(stderr, "failed to open %ls\n", baseLocation->getWChars()); throw InputSourceException(StringBuffer("Can't open file '")+baseLocation+"'"); } struct stat st; fstat(source, &st); len = st.st_size; stream = new byte[len]; memset(stream,0, sizeof(byte)*len); read(source, stream, len); close(source); return stream; };
Matrix3 SvgTransformParser::parseTransform() { if (type_ == "matrix") { return parseMatrixTransform(); } else if (type_ == "rotate") { return parseRotateTransform(); } else if (type_ == "scale") { return parseScaleTransform(); } else if (type_ == "translate") { return parseTranslateTransform(); } else { throw std::runtime_error(StringBuffer() << "Invalid SVG transform type \"" << type_ << "\"."); } }
void replaceHeader(StringBuffer& buf, const char* name, const char* value) { StringBuffer newbuf; const char* hdr = strstr(buf.str(), StringBuffer(name).append(":").str()); if(hdr) { newbuf.append(hdr - buf.str(), buf.str()); newbuf.append(name).append(": ").append(value); const char* eol = strstr(hdr, "\r"); if(eol) { newbuf.append(eol); } buf.swapWith(newbuf); } }
Matrix3 SvgTransformParser::parseRotateTransform() { if (args_.size() == 1) { return Matrix3(std::cos(args_[0]), -std::sin(args_[0]), 0.0f, std::sin(args_[0]), std::cos(args_[0]), 0.0f); } else if (args_.size() == 3) { return (Matrix3(1.0f, 0.0f, args_[1], 0.0f, 1.0f, args_[2]) * Matrix3(std::cos(args_[0]), -std::sin(args_[0]), 0.0f, std::sin(args_[0]), std::cos(args_[0]), 0.0f) * Matrix3(1.0f, 0.0f, -args_[1], 0.0f, 1.0f, -args_[2])); } else { throw std::runtime_error(StringBuffer() << "Invalid argument count for SVG transform type \"" << type_ << "\"."); } }
JARInputSource::JARInputSource(const String *basePath, JARInputSource *base, bool faked){ // relative jar uri JARInputSource *parent = base; if (parent == null) throw InputSourceException(StringBuffer("Bad jar uri format: ") + basePath); sharedIS = parent->getShared(); sharedIS->addref(); inJarLocation = getAbsolutePath(parent->getInJarLocation(), basePath); StringBuffer str("jar:"); str.append(sharedIS->getLocation()); str.append(DString("!")); str.append(inJarLocation); baseLocation = new SString(&str); stream = null; len = 0; };
ESP_FACTORY IEspProtocol * esp_protocol_factory(const char *name, const char* type, IPropertyTree *cfg, const char *process) { if (strcmp(type, "http_protocol")==0) { return new CHttpProtocol; } else if(strcmp(type, "secure_http_protocol") == 0) { IPropertyTree *sslSettings; sslSettings = cfg->getPropTree(StringBuffer("Software/EspProcess[@name=\"").append(process).append("\"]").append("/EspProtocol[@name=\"").append(name).append("\"]").str()); if(sslSettings != NULL) { return new CSecureHttpProtocol(sslSettings); } } return NULL; }
int CXslTransform::setStringParameter(const char *pszName, const char *pszString) { m_XalanTransformer.setStylesheetParam(XalanDOMString(pszName), XalanDOMString(StringBuffer("'").append(pszString).append("'").str())); return 0; }
void CDiskWriteSlaveActivityBase::process() { calcFileCrc = false; uncompressedBytesWritten = 0; replicateDone = 0; StringBuffer tmpStr; fName.set(getPartFilename(*partDesc, 0, tmpStr).str()); if (diskHelperBase->getFlags() & TDXtemporary && !container.queryJob().queryUseCheckpoints()) container.queryTempHandler()->registerFile(fName, container.queryOwner().queryGraphId(), usageCount, true); try { ActPrintLog("handling fname : %s", fName.get()); try { open(); assertex(out||outraw); write(); } catch (IException *) { abortSoon = true; close(); throw; } catch (CATCHALL) { abortSoon = true; close(); throw; } close(); } catch (IException *) { calcFileCrc = false; throw; } catch(CATCHALL) { calcFileCrc = false; throw; } unsigned crc = compress?~0:fileCRC.get(); ActPrintLog("Wrote %"RCPF"d records%s", processed & THORDATALINK_COUNT_MASK, calcFileCrc?StringBuffer(", crc=0x").appendf("%X", crc).str() : ""); }
// Produce a buffer suitable for use by the serialize method. Used by // template methods that do not inherently know the buffer type. StringBuffer makeBuffer() const { return StringBuffer(); }