char * rcFile(char *base) { if (base && (base[0] == '/' || (base[0] == '.' && (base[1] == '/' || (base[1] == '.' && base[2] == '/'))) || (base[0] == '~' && base[1] == '/'))) /* /file, ./file, ../file, ~/file */ return expandPath(base); return expandPath(Strnew_m_charp(rc_dir, "/", base, NULL)->ptr); }
bool launchFolder(const char* path) { if (!path) return false; ERROR_OUTPUT(__func__); std::string fullPath = expandPath(path); pid_t id = fork(); if (id != 0) { int status; waitpid(id, &status, 0); if (WEXITSTATUS(status) == 0) return true; else return false; } setenv("LD_LIBRARY_PATH", "", 1); execlp("xdg-open", "xdg-open", fullPath.c_str(), NULL); //um shit. We shouldnt be here. :( printf("Failed to execlp %s. Error: %d\n", fullPath.c_str(), errno); exit(-1); return false; }
/** * will save the sent email if a place is specified in the * configuration file It will append each email to one particular * file called 'email.sent' **/ static int saveSentEmail(dstrbuf *msg) { FILE *save; char *save_file = NULL; dstrbuf *path; save_file = getConfValue("SAVE_SENT_MAIL"); if (!save_file) { return ERROR; } path = expandPath(save_file); dsbCat(path, "/email.sent"); if (!(save = fopen(path->str, "a"))) { warning("Could not open file: %s", path->str); dsbDestroy(path); return ERROR; } fputs(msg->str, save); fflush(save); fclose(save); return SUCCESS; }
void prepareMeleeDir (void) { char buf[PATH_MAX]; const char *meleeDirName; meleeDirName = getenv("UQM_MELEE_DIR"); if (meleeDirName == NULL) meleeDirName = MELEEDIR; if (expandPath (buf, PATH_MAX - 13, meleeDirName, EP_ALL_SYSTEM) == -1) { // Doesn't have to be fatal, but might mess up things when saving // config files. log_add (log_Fatal, "Fatal error: Invalid path to config files."); exit (EXIT_FAILURE); } meleeDirName = buf; setenv("UQM_MELEE_DIR", meleeDirName, 1); // Create the path upto the save dir, if not already existing. if (mkdirhier (meleeDirName) == -1) exit (EXIT_FAILURE); meleeDir = uio_openDirRelative (configDir, "teams", 0); // TODO: this doesn't work if the save dir is not // "teams" in the config dir. if (meleeDir == NULL) { log_add (log_Fatal, "Fatal error: Could not open melee teams dir: %s", strerror (errno)); exit (EXIT_FAILURE); } }
void FileHandle::open(const char* fileName, FILE_MODE mode, uint64 offset) { if (m_bIsOpen) close(); if (!fileName) throw gcException(ERR_BADPATH, "Cant open file with null path"); std::string fullFile = expandPath(fileName); if (fullFile == "") fullFile = fileName; #ifdef DEBUG m_szFileName = fullFile; #endif m_uiOffset = offset; FILE* fh = NULL; switch (mode) { case FILE_READ: fh = fopen64(fullFile.c_str(), "rb"); m_szMode = "rb"; break; case FILE_WRITE: fh = fopen64(fullFile.c_str(), "wb"); m_szMode = "wb"; break; case FILE_APPEND: fh = fopen64(fullFile.c_str(), "rb+"); m_szMode = "rb+"; if (fh) fseek(fh, 0, SEEK_END); else fh = fopen64(fullFile.c_str(), "wb"); break; default: throw gcException(ERR_INVALID, "The mode was invalid"); break; } if (!fh) { printf("Error opening %s as %d: %d\n", fullFile.c_str(), mode, errno); throw gcException(ERR_INVALIDFILE, gcString("Couldnt open the file [{0}] in mode {1}", fullFile.c_str(), mode)); } m_hFileHandle = fh; m_bIsOpen = true; }
/** * ModuleUsage will take an argument for the specified * module and print out help information on the topic. * information is stored in a written file in the location * in Macro EMAIL_DIR. and also specified with EMAIL_HELP_FILE */ static void moduleUsage(const char *module) { FILE *help=NULL; short found=0; char *moduleptr=NULL; dstrbuf *buf = DSB_NEW; dstrbuf *help_file = expandPath(EMAIL_HELP_FILE); if (!(help = fopen(help_file->str, "r"))) { fatal("Could not open help file: %s", help_file->str); dsbDestroy(help_file); properExit(ERROR); } dsbDestroy(help_file); while (!feof(help)) { dsbReadline(buf, help); if ((buf->str[0] == '#') || (buf->str[0] == '\n')) { continue; } chomp(buf->str); moduleptr = strtok(buf->str, "|"); if (strcasecmp(moduleptr, module) != 0) { while ((moduleptr = strtok(NULL, "|")) != NULL) { if (strcasecmp(moduleptr, module) == 0) { found = 1; break; } } } else { found = 1; } if (!found) { continue; } while (!feof(help)) { dsbReadline(buf, help); if (!strcmp(buf->str, "EOH\n")) { break; } printf("%s", buf->str); } break; } if (feof(help)) { printf("There is no help in the module: %s\n", module); usage(); } dsbDestroy(buf); fclose(help); exit(0); }
QgsBrowser::QgsBrowser( QWidget *parent, Qt::WFlags flags ) : QMainWindow( parent, flags ) , mDirtyMetadata( true ) , mDirtyPreview( true ) , mDirtyAttributes( true ) , mLayer( 0 ) , mParamWidget( 0 ) , mAttributeTableFilterModel( 0 ) { setupUi( this ); // Disable tabs by default tabWidget->setTabEnabled( tabWidget->indexOf( paramTab ), false ); tabWidget->setTabEnabled( tabWidget->indexOf( metaTab ), false ); tabWidget->setTabEnabled( tabWidget->indexOf( previewTab ), false ); tabWidget->setTabEnabled( tabWidget->indexOf( attributesTab ), false ); mModel = new QgsBrowserModel( treeView ); treeView->setModel( mModel ); // Last expanded is stored, don't cover whole height with file system //treeView->expand( mModel->index(0,0) ); connect( treeView, SIGNAL( clicked( const QModelIndex& ) ), this, SLOT( itemClicked( const QModelIndex& ) ) ); treeView->setExpandsOnDoubleClick( false ); connect( treeView, SIGNAL( doubleClicked( const QModelIndex& ) ), this, SLOT( itemDoubleClicked( const QModelIndex& ) ) ); connect( treeView, SIGNAL( expanded( const QModelIndex& ) ), this, SLOT( itemExpanded( const QModelIndex& ) ) ); connect( tabWidget, SIGNAL( currentChanged( int ) ), this, SLOT( tabChanged() ) ); connect( mActionNewVectorLayer, SIGNAL( triggered() ), this, SLOT( newVectorLayer() ) ); connect( stopRenderingButton, SIGNAL( clicked() ), this, SLOT( stopRendering() ) ); mapCanvas->setCanvasColor( Qt::white ); QSettings settings; QString lastPath = settings.value( "/Browser/lastExpanded" ).toString(); QgsDebugMsg( "lastPath = " + lastPath ); if ( !lastPath.isEmpty() ) { expandPath( lastPath ); } //Set the icon size of for all the toolbars created in the future. int size = settings.value( "/IconSize", QGIS_ICON_SIZE ).toInt(); setIconSize( QSize( size, size ) ); //Change all current icon sizes. QList<QToolBar *> toolbars = findChildren<QToolBar *>(); foreach ( QToolBar * toolbar, toolbars ) { toolbar->setIconSize( QSize( size, size ) ); }
//takes an XML element definition and creates an object from it GuiComponent* ThemeComponent::createElement(pugi::xml_node data, GuiComponent* parent) { std::string type = data.child("type").text().get(); if(type == "image") { std::string path = expandPath(data.child("path").text().get()); if(!boost::filesystem::exists(path)) { LOG(LogError) << "Error - theme image \"" << path << "\" does not exist."; return NULL; } std::string pos = data.child("pos").text().get(); std::string dim = data.child("dim").text().get(); std::string origin = data.child("origin").text().get(); bool tiled = data.child("tiled") != 0; //split position and dimension information std::string posX, posY; splitString(pos, ' ', &posX, &posY); std::string dimW, dimH; splitString(dim, ' ', &dimW, &dimH); std::string originX, originY; splitString(origin, ' ', &originX, &originY); //resolve to pixels from percentages/variables int x = (int)(resolveExp(posX) * Renderer::getScreenWidth()); int y = (int)(resolveExp(posY) * Renderer::getScreenHeight()); int w = (int)(resolveExp(dimW) * Renderer::getScreenWidth()); int h = (int)(resolveExp(dimH) * Renderer::getScreenHeight()); float ox = strToFloat(originX); float oy = strToFloat(originY); ImageComponent* comp = new ImageComponent(mWindow, x, y, "", w, h, true); comp->setOrigin(ox, oy); comp->setTiling(tiled); comp->setImage(path); addChild(comp); return comp; } LOG(LogError) << "Theme component type \"" << type << "\" unknown!"; return NULL; }
bool launchProcessXDG(const char* exe, const char* libPath) { if (!exe) return false; ERROR_OUTPUT(__func__); std::string fullExe = expandPath(exe); pid_t id = fork(); if (id != 0) { int status; waitpid(id, &status, 0); if (WEXITSTATUS(status) == 0) return true; else return false; } else { pid_t pid_kill = fork(); if (pid_kill != 0) { exit(0); } else { char* old_lc_all = NULL; old_lc_all = getenv("OLD_LC_ALL"); if (old_lc_all) setenv("LC_ALL", old_lc_all, 1); else setenv("LC_ALL", "", 1); if (libPath) setenv("LD_LIBRARY_PATH", libPath, 1); else unsetenv("LD_LIBRARY_PATH"); std::string wd = UTIL::FS::Path(fullExe.c_str(), "", true).getFolderPath(); (void)chdir(wd.c_str()); ERROR_OUTPUT("Launching with xdg-open"); execlp("xdg-open", "xdg-open", fullExe.c_str(), NULL); //um shit. We shouldnt be here. :( printf("Failed to exec xdg-open for %s. Error: %d\n", fullExe.c_str(), errno); exit(-1); } } return false; }
void prepareConfigDir (const char *configDirName) { char buf[PATH_MAX]; static uio_AutoMount *autoMount[] = { NULL }; uio_MountHandle *contentHandle; if (configDirName == NULL) { configDirName = getenv("UQM_CONFIG_DIR"); if (configDirName == NULL) configDirName = CONFIGDIR; } if (expandPath (buf, PATH_MAX - 13, configDirName, EP_ALL_SYSTEM) == -1) { // Doesn't have to be fatal, but might mess up things when saving // config files. log_add (log_Fatal, "Fatal error: Invalid path to config files."); exit (EXIT_FAILURE); } configDirName = buf; log_add (log_Debug, "Using config dir '%s'", configDirName); // Set the environment variable UQM_CONFIG_DIR so UQM_MELEE_DIR // and UQM_SAVE_DIR can refer to it. setenv("UQM_CONFIG_DIR", configDirName, 1); // Create the path upto the config dir, if not already existing. if (mkdirhier (configDirName) == -1) exit (EXIT_FAILURE); contentHandle = uio_mountDir (repository, "/", uio_FSTYPE_STDIO, NULL, NULL, configDirName, autoMount, uio_MOUNT_TOP, NULL); if (contentHandle == NULL) { log_add (log_Fatal, "Fatal error: Could not mount config dir: %s", strerror (errno)); exit (EXIT_FAILURE); } configDir = uio_openDir (repository, "/", 0); if (configDir == NULL) { log_add (log_Fatal, "Fatal error: Could not open config dir: %s", strerror (errno)); exit (EXIT_FAILURE); } }
/** * checks to see if the TEMP_FILE is around... if it is * it will move it to the users home directory as dead.letter. **/ static void deadLetter() { dstrbuf *path = expandPath("~/dead.letter"); FILE *out = fopen(path->str, "w"); if (!out || !global_msg) { warning("Could not save dead letter to %s", path->str); } else { fwrite(global_msg->str, sizeof(char), global_msg->len, out); } dsbDestroy(path); }
bool RippleCalc::addPathState(STPath const& path, TER& resultCode) { auto pathState = std::make_shared<PathState> ( saDstAmountReq_, saMaxAmountReq_); if (!pathState) { resultCode = temUNKNOWN; return false; } pathState->expandPath ( mActiveLedger, path, uDstAccountID_, uSrcAccountID_); if (pathState->status() == tesSUCCESS) pathState->checkNoRipple (uDstAccountID_, uSrcAccountID_); if (pathState->status() == tesSUCCESS) pathState->checkFreeze (); pathState->setIndex (pathStateList_.size ()); WriteLog (lsDEBUG, RippleCalc) << "rippleCalc: Build direct:" << " status: " << transToken (pathState->status()); // Return if malformed. if (isTemMalformed (pathState->status())) { resultCode = pathState->status(); return false; } if (pathState->status () == tesSUCCESS) { resultCode = pathState->status(); pathStateList_.push_back (pathState); } else if (pathState->status () != terNO_LINE) { resultCode = pathState->status(); } return true; }
boost::filesystem::path ParameterValue::convert(const std::string &s, ComponentRegistryPtr reg) { namespace bf = boost::filesystem; std::string workingPath; if (GlobalCurrentExperiment) { workingPath = GlobalCurrentExperiment->getWorkingPath(); } bf::path fullPath(expandPath(workingPath, s)); if (!bf::exists(fullPath)) { throw SimpleException("Path does not exist", fullPath.string()); } return fullPath; }
bool fileExists(const char* file) { char buffer[PATH_MAX]; snprintf(buffer, PATH_MAX, "%s (%s)", __func__, file); ERROR_OUTPUT(buffer); std::string fullFile = expandPath(file); struct stat stFileInfo; int intStat; // Attempt to get the file attributes intStat = stat(fullFile.c_str(), &stFileInfo); if (intStat == 0) return true; else return false; }
Font* ThemeComponent::resolveFont(pugi::xml_node node, std::string defaultPath, unsigned int defaultSize) { if(!node) return NULL; std::string path = expandPath(node.child("path").text().get()); unsigned int size = (unsigned int)(strToFloat(node.child("size").text().get()) * Renderer::getScreenHeight()); if(!boost::filesystem::exists(path)) { path = defaultPath; } if(size == 0) { size = defaultSize; } return new Font(path, size); }
static struct mailcap * loadMailcap(char *filename) { FILE *f; int i, n; Str tmp; struct mailcap *mcap; f = fopen(expandPath(filename), "r"); if (f == NULL) return NULL; i = 0; while (tmp = Strfgets(f), tmp->length > 0) { if (tmp->ptr[0] != '#') i++; } fseek(f, 0, 0); n = i; mcap = New_N(struct mailcap, n + 1); i = 0; while (tmp = Strfgets(f), tmp->length > 0) { if (tmp->ptr[0] == '#') continue; redo: while (IS_SPACE(Strlastchar(tmp))) Strshrink(tmp, 1); if (Strlastchar(tmp) == '\\') { /* continuation */ Strshrink(tmp, 1); Strcat(tmp, Strfgets(f)); goto redo; } if (extractMailcapEntry(tmp->ptr, &mcap[i])) i++; } memset(&mcap[i], 0, sizeof(struct mailcap)); fclose(f); return mcap; }
/** * will invoke the path specified to sendmail with any * options specified and it will send the mail via sendmail... **/ int processInternal(const char *sm_bin, dstrbuf *msgcon) { int written_bytes=0, bytes = 0; struct prbar *bar; FILE *open_sendmail; char *ptr = msgcon->str; dstrbuf *smpath; bar = prbarInit(msgcon->len); smpath = expandPath(sm_bin); open_sendmail = popen(smpath->str, "w"); dsbDestroy(smpath); if (!open_sendmail) { fatal("Could not open internal sendmail path: %s", smpath->str); return ERROR; } /* Loop through getting what's out of message and sending it to sendmail */ while (*ptr != '\0') { bytes = strlen(ptr); if (bytes > CHUNK_BYTES) { bytes = CHUNK_BYTES; } written_bytes = fwrite(ptr, sizeof(char), bytes, open_sendmail); if (Mopts.verbose && bar != NULL) { prbarPrint(written_bytes, bar); } ptr += written_bytes; } fflush(open_sendmail); fclose(open_sendmail); prbarDestroy(bar); return SUCCESS; }
// contentDirName is an explicitely specified location for the content, // or NULL if none was explicitely specified. // execFile is the path to the uqm executable, as acquired through // main()'s argv[0]. void prepareContentDir (const char *contentDirName, const char* addonDirName, const char *execFile) { const char *testFile = "version"; const char *loc; if (contentDirName == NULL) { // Try the default content locations. const char *locs[] = { CONTENTDIR, /* defined in config.h */ "", "content", "../../content" /* For running from MSVC */ }; loc = findFileInDirs (locs, sizeof locs / sizeof locs[0], testFile); #ifdef __APPLE__ /* On OSX, if the content can't be found in any of the static * locations, attempt to look inside the application bundle, * by looking relative to the location of the uqm executable. */ if (loc == NULL) { char *tempDir = (char *) HMalloc (PATH_MAX); snprintf (tempDir, PATH_MAX, "%s/../Resources/content", dirname (execFile)); loc = findFileInDirs ((const char **) &tempDir, 1, testFile); HFree (tempDir); } #endif } else { // Only use the explicitely supplied content dir. loc = findFileInDirs (&contentDirName, 1, testFile); } if (loc == NULL) { log_add (log_Fatal, "Fatal error: Could not find content."); exit (EXIT_FAILURE); } if (expandPath (baseContentPath, sizeof baseContentPath, loc, EP_ALL_SYSTEM) == -1) { log_add (log_Fatal, "Fatal error: Could not expand path to content " "directory: %s", strerror (errno)); exit (EXIT_FAILURE); } log_add (log_Debug, "Using '%s' as base content dir.", baseContentPath); contentMountHandle = mountContentDir (repository, baseContentPath); if (addonDirName) log_add (log_Debug, "Using '%s' as addon dir.", addonDirName); mountAddonDir (repository, contentMountHandle, addonDirName); #ifndef __APPLE__ (void) execFile; #endif }
bool launchProcess(const char* exe, const std::map<std::string, std::string> &info) { if (!exe) return false; ERROR_OUTPUT(__func__); std::string fullExe = expandPath(exe); if (!fileExists(fullExe.c_str())) return false; //we double fork so that the new process is not a child of this process pid_t pid = fork(); if (pid != 0) { int status; waitpid(pid, &status, 0); if (WEXITSTATUS(status) == 0) return true; else return false; } else { pid_t pid_kill = fork(); if (pid_kill != 0) { exit(0); } else { UTIL::FS::Path path(fullExe.c_str(), "", true); std::string workingDir; std::string libPath; std::string args; std::string e = path.getFullPath(); typedef const std::map<std::string, std::string>::const_iterator MapIterator; MapIterator &wd = info.find("wd"); if (wd != info.end()) workingDir = expandPath( (*wd).second.c_str() ); if (workingDir == "") workingDir = path.getFolderPath(); MapIterator &lp = info.find("lp"); if (lp != info.end()) libPath = (*lp).second.c_str(); MapIterator &cla = info.find("cla"); if (cla != info.end()) args = (*cla).second.c_str(); gcString orgLibPath = getenv("OLD_LIB_PATH"); if (orgLibPath.size() > 0) { if (libPath.size() > 0) libPath += ":"; libPath += orgLibPath; } if (libPath.size() > 0) setenv("LD_LIBRARY_PATH", libPath.c_str(), 1); else unsetenv("LD_LIBRARY_PATH"); std::vector<std::string> out; const char* argv[10] = {0}; argv[0] = e.c_str(); if (args.size() > 0) { ConvertToArgs(args.c_str(), out); for (size_t x=0; x<out.size(); x++) { if (x == 9) break; argv[x+1] = out[x].c_str(); } } (void)chdir(workingDir.c_str()); execv(fullExe.c_str(), (char* const*)argv); printf("Failed to execl %s [%s] error: %d\n", fullExe.c_str(), args.c_str(), errno); exit(-1); } } return false; }
char * DtMail::Session::expandPath(DtMailEnv & error, const char * path) { const char * fold_path; if (path == NULL) { error.setError(DTME_BadArg); return(NULL); } error.clear(); char * exp_name = (char *)malloc(MAXIMUM_PATH_LENGTH); if (exp_name == NULL) { error.setError(DTME_NoMemory); return(NULL); } if (strchr(path, '$') != NULL) { sprintf (exp_name, "echo %s", path); FILE *fp; if ((fp = popen(exp_name, "r")) != NULL) { exp_name[0] = '\0'; if (fgets(exp_name, MAXIMUM_PATH_LENGTH, fp) != NULL && exp_name[0] != '\0') // get rid of \n at end of string exp_name[strlen(exp_name)-1] = '\0'; else strcpy(exp_name, path); pclose(fp); } else strcpy(exp_name, path); } else strcpy(exp_name, path); char * exp_name2 = (char *)malloc(MAXIMUM_PATH_LENGTH); exp_name2[0] = '\0'; switch (exp_name[0]) { case '+': // This is relative to the folder path. Figure out what that is. { _mail_rc->getValue(error, "folder", &fold_path); if (error.isNotSet()) { if (*fold_path != '/' && *fold_path != '.' && *fold_path != '~' && *fold_path != '$') strcpy(exp_name2, "~/"); strcat(exp_name2, fold_path); strcat(exp_name2, "/"); } else // Use the default folder strcpy(exp_name2, "~/"); strcat(exp_name2, &exp_name[1]); // We need to call ourselves again to deal with // relative paths in the folder directory. // char * old_exp = exp_name2; exp_name2 = expandPath(error, old_exp); free(old_exp); break; } case '~': // This is relative to the user's home directory. { passwd pw; const char * start; if (exp_name[1] == '/' || exp_name[1] == '\0') { GetPasswordEntry(pw); start = &exp_name[1]; } else { passwd * pw_p; char * slash = strchr(&exp_name[1], '/'); if (slash == NULL) { error.clear(); error.setError(DTME_NoSuchFile); break; } int len = slash - &exp_name[1]; char * name = new char[len + 1]; strncpy(name, &exp_name[1], len); name[len] = 0; pw_p = getpwnam(name); if (!pw_p) { error.clear(); error.setError(DTME_NoSuchFile); break; } pw = *pw_p; delete [] name; start = slash; } strcpy(exp_name2, pw.pw_dir); strcat(exp_name2, start); break; } // We have a directory or no specials. Just copy the path and // return. case '.': case '/': default: strcpy(exp_name2, exp_name); break; } free(exp_name); return(exp_name2); }
// This routine takes a path and checks to see if the path can be // expressed relative to the "folder" path. If it can, it returns // the relative path; otherwise, it returns the original path. char * DtMail::Session::getRelativePath(DtMailEnv & error, const char * path) { const char * fold_path; if (path == NULL) { error.setError(DTME_BadArg); return(NULL); } error.clear(); char * exp_name = (char *)malloc(MAXIMUM_PATH_LENGTH); if (!exp_name) { error.setError(DTME_NoMemory); return(NULL); } exp_name[0] = '\0'; // Just for errors. switch (path[0]) { case '/': // This is an absolute path, so there is a chance that // we can trim it down to a relative path if it goes down // the same way as the folder path. { _mail_rc->getValue(error, "folder", &fold_path); if (error.isNotSet()) { strcpy(exp_name, fold_path); // We need to call ourselves again to deal with // relative paths in the folder directory. // char * old_exp = exp_name; exp_name = expandPath(error, old_exp); free(old_exp); // Check to see if the path starts with the folder path. char * matched_path = const_cast<char *>(strstr(path, exp_name)); if (matched_path == path) { // Yes it does, make it a relative path to the folder dir. int folder_path_length = strlen(exp_name); while (path[folder_path_length] == '/') folder_path_length++; strcpy(exp_name, &path[folder_path_length]); break; } else { strcpy(exp_name, path); break; } } else { // There is no folder variable so just fall through to the // default. error.clear(); } } case '+': // This is relative to the folder path. Leave it alone. // The only time we are likely to see a leading '+' is // when the path was carried over from mailtool in the .mailrc. case '~': // This is relative to the user's home directory. Leave it alone. // The only time we are likely to see a leading '~' is // when the path was carried over from mailtool in the .mailrc. case '.': // This is relative to the current directory where dtmail is // running. Leave it alone. The only time we are likely to see // a leading '.' is when the path was carried over from mailtool // in the .mailrc. default: { strcpy(exp_name, path); break; } } return(exp_name); }
Datum ExperimentPackager::packageExperiment(const boost::filesystem::path filename) { namespace bf = boost::filesystem; IncludedFilesParser parser(filename.string()); std::string working_path_string; Datum include_files; try{ parser.parse(false); working_path_string = parser.getWorkingPathString(); include_files = parser.getIncludedFilesManifest(); } catch(std::exception& e){ merror(M_PARSER_MESSAGE_DOMAIN, "Experiment packaging failed: %s", e.what()); return Datum(); } Datum eventPayload(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS); { // Use getDocumentData to get the experiment file with any preprocessing and/or // XInclude substitutions already applied std::vector<xmlChar> fileData; parser.getDocumentData(fileData); Datum contents(reinterpret_cast<char *>(&(fileData.front())), fileData.size()); eventPayload.addElement(M_PACKAGER_EXPERIMENT_STRING, packageSingleFile(contents, XMLParser::squashFileName(filename.string()))); } if(include_files.getNElements() >= 1) { Datum mediaFilesPayload(M_LIST, include_files.getNElements()); for(int i=0; i< include_files.getNElements(); ++i) { // DDC there seem to be a lot of unnecessary steps here // simplified hackily for the moment std::string mediaName(include_files.getElement(i).getString()); bf::path mediaPath = expandPath(working_path_string, mediaName); //bf::path mediaPath(include_files.getElement(i).getElement(M_PACKAGER_FULL_NAME).getString()); //std::string mediaName(include_files.getElement(i).getElement(M_PACKAGER_RELATIVE_NAME).getString()); Datum mediaElement = packageSingleFile(mediaPath, mediaName); if(!mediaElement.isUndefined()) { mediaFilesPayload.addElement(mediaElement); } else { merror(M_FILE_MESSAGE_DOMAIN, "Can't find file: %s", mediaPath.string().c_str()); Datum undef; return undef; } } eventPayload.addElement(M_PACKAGER_MEDIA_BUFFERS_STRING, mediaFilesPayload); } return SystemEventFactory::systemEventPackage(M_SYSTEM_DATA_PACKAGE, M_EXPERIMENT_PACKAGE, eventPayload); }
void ThemeComponent::readXML(std::string path) { if(mPath == path) return; setDefaults(); deleteComponents(); mPath = path; if(path.empty()) return; LOG(LogInfo) << "Loading theme \"" << path << "\"..."; pugi::xml_document doc; pugi::xml_parse_result result = doc.load_file(path.c_str()); if(!result) { LOG(LogError) << "Error parsing theme \"" << path << "\"!\n" << " " << result.description(); return; } pugi::xml_node root; if(!mDetailed) { //if we're using the basic view, check if there's a basic version of the theme root = doc.child("basicTheme"); } if(!root) { root = doc.child("theme"); } if(!root) { LOG(LogError) << "No theme tag found in theme \"" << path << "\"!"; return; } //load non-component theme stuff mColorMap["primary"] = resolveColor(root.child("listPrimaryColor").text().get(), mColorMap["primary"]); mColorMap["secondary"] = resolveColor(root.child("listSecondaryColor").text().get(), mColorMap["secondary"]); mColorMap["selector"] = resolveColor(root.child("listSelectorColor").text().get(), mColorMap["selector"]); mColorMap["selected"] = resolveColor(root.child("listSelectedColor").text().get(), mColorMap["selected"]); mColorMap["description"] = resolveColor(root.child("descColor").text().get(), mColorMap["description"]); mColorMap["fastSelect"] = resolveColor(root.child("fastSelectColor").text().get(), mColorMap["fastSelect"]); mBoolMap["hideHeader"] = root.child("hideHeader") != 0; mBoolMap["hideDividers"] = root.child("hideDividers") != 0; //GuiBox theming data mBoxData.backgroundPath = expandPath(root.child("boxBackground").text().get()); mBoxData.backgroundTiled = root.child("boxBackgroundTiled") != 0; mBoxData.horizontalPath = expandPath(root.child("boxHorizontal").text().get()); mBoxData.horizontalTiled = root.child("boxHorizontalTiled") != 0; mBoxData.verticalPath = expandPath(root.child("boxVertical").text().get()); mBoxData.verticalTiled = root.child("boxVerticalTiled") != 0; mBoxData.cornerPath = expandPath(root.child("boxCorner").text().get()); //list stuff mBoolMap["listCentered"] = !root.child("listLeftAlign"); mFloatMap["listOffsetX"] = strToFloat(root.child("listOffsetX").text().get(), mFloatMap["listOffsetX"]); mFloatMap["listTextOffsetX"] = strToFloat(root.child("listTextOffsetX").text().get(), mFloatMap["listTextOffsetX"]); //game image stuff std::string artPos = root.child("gameImagePos").text().get(); std::string artDim = root.child("gameImageDim").text().get(); std::string artOrigin = root.child("gameImageOrigin").text().get(); std::string artPosX, artPosY, artWidth, artHeight, artOriginX, artOriginY; splitString(artPos, ' ', &artPosX, &artPosY); splitString(artDim, ' ', &artWidth, &artHeight); splitString(artOrigin, ' ', &artOriginX, &artOriginY); mFloatMap["gameImageOffsetX"] = resolveExp(artPosX, mFloatMap["gameImageOffsetX"]); mFloatMap["gameImageOffsetY"] = resolveExp(artPosY, mFloatMap["gameImageOffsetY"]); mFloatMap["gameImageWidth"] = resolveExp(artWidth, mFloatMap["gameImageWidth"]); mFloatMap["gameImageHeight"] = resolveExp(artHeight, mFloatMap["gameImageHeight"]); mFloatMap["gameImageOriginX"] = resolveExp(artOriginX, mFloatMap["gameImageOriginX"]); mFloatMap["gameImageOriginY"] = resolveExp(artOriginY, mFloatMap["gameImageOriginY"]); mStringMap["imageNotFoundPath"] = expandPath(root.child("gameImageNotFound").text().get()); //sounds mSoundMap["menuScroll"]->loadFile(expandPath(root.child("menuScrollSound").text().get())); mSoundMap["menuSelect"]->loadFile(expandPath(root.child("menuSelectSound").text().get())); mSoundMap["menuBack"]->loadFile(expandPath(root.child("menuBackSound").text().get())); mSoundMap["menuOpen"]->loadFile(expandPath(root.child("menuOpenSound").text().get())); //fonts mListFont = resolveFont(root.child("listFont"), Font::getDefaultPath(), Renderer::getDefaultFont(Renderer::MEDIUM)->getSize()); mDescFont = resolveFont(root.child("descriptionFont"), Font::getDefaultPath(), Renderer::getDefaultFont(Renderer::SMALL)->getSize()); mFastSelectFont = resolveFont(root.child("fastSelectFont"), Font::getDefaultPath(), Renderer::getDefaultFont(Renderer::LARGE)->getSize()); //actually read the components createComponentChildren(root, this); LOG(LogInfo) << "Theme loading complete."; }
int main(int argc, char *argv[], char **envp) { Str mailcapfile; extern char *getenv(); char *p; int length; Str qs = NULL; struct parsed_tagarg *cgiarg; char *mode; char *sent_cookie; GC_INIT(); p = getenv("REQUEST_METHOD"); if (p == NULL || strcasecmp(p, "post")) goto request_err; p = getenv("CONTENT_LENGTH"); if (p == NULL || (length = atoi(p)) <= 0) goto request_err; qs = Strfgets(stdin); Strchop(qs); if (qs->length != length) goto request_err; cgiarg = cgistr2tagarg(qs->ptr); p = getenv("LOCAL_COOKIE_FILE"); if (p) { FILE *f = fopen(p, "r"); if (f) { local_cookie = Strfgets(f)->ptr; fclose(f); } } sent_cookie = tag_get_value(cgiarg, "cookie"); if (local_cookie == NULL || sent_cookie == NULL || strcmp(local_cookie, sent_cookie) != 0) { /* Local cookie doesn't match */ bye("Local cookie doesn't match: It may be an illegal execution", ""); } mode = tag_get_value(cgiarg, "mode"); mailcapfile = Strnew_charp(expandPath(USER_MAILCAP)); if (mode && !strcmp(mode, "edit")) { char *referer; /* check if I can edit my mailcap */ if ((referer = getenv("HTTP_REFERER")) != NULL) { if (strncmp(referer, "file://", 7) != 0 && strncmp(referer, "exec://", 7) != 0) { /* referer is not file: nor exec: */ bye("It may be an illegal execution\n referer=", referer); } } /* edit mailcap */ editMailcap(mailcapfile->ptr, cgiarg); } else { /* initial panel */ printMailcapPanel(mailcapfile->ptr); } return 0; request_err: bye("Incomplete Request:", qs ? qs->ptr : "(null)"); exit(1); }
QString Utils::Fs::expandPathAbs(const QString &path) { return QDir(expandPath(path)).absolutePath(); }
int main(int argc, char **argv) { int get; int opt_index = 0; /* for getopt */ char *cc_string = NULL; char *bcc_string = NULL; const char *opts = "f:n:a:p:oVedvtb?c:s:r:u:i:g:m:H:x:"; /* Set certian global options to NULL */ conf_file = NULL; memset(&Mopts, 0, sizeof(struct mailer_options)); Mopts.encoding = true; /* Check if they need help */ if ((argc > 1) && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "-help") || !strcmp(argv[1], "--help"))) { if (argc == 3) { moduleUsage(argv[2]); } else if (argc == 2) { usage(); } else { fprintf(stderr, "Only specify one option with %s: \n", argv[1]); usage(); } } table = dhInit(28, defaultDestr); if (!table) { fprintf(stderr, "ERROR: Could not initialize Hash table.\n"); exit(0); } while ((get = getopt_long_only(argc, argv, opts, Gopts, &opt_index)) > EOF) { switch (get) { case 'n': setConfValue("MY_NAME", xstrdup(optarg)); break; case 'f': setConfValue("MY_EMAIL", xstrdup(optarg)); break; case 'a': if (!Mopts.attach) { Mopts.attach = dlInit(defaultDestr); } dlInsertTop(Mopts.attach, xstrdup(optarg)); break; case 'V': Mopts.verbose = true; break; case 'p': setConfValue("SMTP_PORT", xstrdup(optarg)); break; case 'o': Mopts.priority = 1; break; case 'e': Mopts.gpg_opts |= GPG_ENC; break; case 's': Mopts.subject = optarg; break; case 'r': setConfValue("SMTP_SERVER", xstrdup(optarg)); break; case 'c': conf_file = optarg; break; case 't': checkConfig(); printf("Configuration file is proper.\n"); dhDestroy(table); return (0); break; case 'v': printf("email - By Dean Jones; Version %s\n", EMAIL_VERSION); dhDestroy(table); exit(EXIT_SUCCESS); break; case 'b': Mopts.blank = 1; break; case 'u': setConfValue("SMTP_AUTH_USER", xstrdup(optarg)); break; case 'i': setConfValue("SMTP_AUTH_PASS", xstrdup(optarg)); break; case 'm': setConfValue("SMTP_AUTH", xstrdup(optarg)); break; case 'g': setConfValue("GPG_PASS", xstrdup(optarg)); break; case 'H': if (!Mopts.headers) { Mopts.headers = dlInit(defaultDestr); } dlInsertTop(Mopts.headers, xstrdup(optarg)); break; case 'x': setConfValue("TIMEOUT", xstrdup(optarg)); break; case '?': usage(); break; case 1: Mopts.html = 1; break; case 2: Mopts.gpg_opts |= GPG_SIG; break; case 3: cc_string = optarg; break; case 4: bcc_string = optarg; break; case 5: /* To name? */ break; case 6: setConfValue("USE_TLS", xstrdup("true")); break; case 7: Mopts.encoding = false; break; default: /* Print an error message here */ usage(); break; } } /* first let's check to make sure they specified some recipients */ if (optind == argc) { usage(); } configure(); /* Check to see if we need to attach a vcard. */ if (getConfValue("VCARD")) { dstrbuf *vcard = expandPath(getConfValue("VCARD")); if (!Mopts.attach) { Mopts.attach = dlInit(defaultDestr); } dlInsertTop(Mopts.attach, xstrdup(vcard->str)); dsbDestroy(vcard); } /* set to addresses if argc is > 1 */ if (!(Mopts.to = getNames(argv[optind]))) { fatal("You must specify at least one recipient!\n"); properExit(ERROR); } /* Set CC and BCC addresses */ if (cc_string) { Mopts.cc = getNames(cc_string); } if (bcc_string) { Mopts.bcc = getNames(bcc_string); } signal(SIGTERM, properExit); signal(SIGINT, properExit); signal(SIGPIPE, properExit); signal(SIGHUP, properExit); signal(SIGQUIT, properExit); createMail(); properExit(0); /* We never get here, but gcc will whine if i don't return something */ return 0; }
void BlockDataManagerConfig::parseArgs(int argc, char* argv[]) { /*** --testnet: run db against testnet bitcoin network --regtest: run db against regression test network --rescan: delete all processed history data and rescan blockchain from the first block --rebuild: delete all DB data and build and scan from scratch --rescanSSH: delete balance and txcount data and rescan it. Much faster than rescan or rebuild. --datadir: path to the operation folder --dbdir: path to folder containing the database files. If empty, a new db will be created there --satoshi-datadir: path to blockchain data folder (blkXXXXX.dat files) --ram_usage: defines the ram use during scan operations. 1 level averages 128MB of ram (without accounting the base amount, ~400MB). Defaults at 4. Can't be lower than 1. Can be changed in between processes --thread-count: defines how many processing threads can be used during db builds and scans. Defaults to maximum available CPU threads. Can't be lower than 1. Can be changed in between processes --zcthread-count: defines the maximum number on threads the zc parser can create for processing incoming transcations from the network node --db-type: sets the db type: DB_BARE: tracks wallet history only. Smallest DB. DB_FULL: tracks wallet history and resolves all relevant tx hashes. ~750MB DB at the time of 0.95 release. Default DB type. DB_SUPER: tracks all blockchain history. XXL DB (100GB+). Not implemented yet db type cannot be changed in between processes. Once a db has been built with a certain type, it will always function according to that type. Specifying another type will do nothing. Build a new db to change type. --cookie: create a cookie file holding a random authentication key to allow local clients to make use of elevated commands, like shutdown. --fcgi-port: sets the DB listening port. --clear-mempool: delete all zero confirmation transactions from the DB. ***/ try { //parse cli args map<string, string> args; for (int i = 1; i < argc; i++) { //check prefix if (strlen(argv[i]) < 2) throw DbErrorMsg("invalid CLI arg"); string prefix(argv[i], 2); if (prefix != "--") throw DbErrorMsg("invalid CLI arg"); //string prefix and tokenize string line(argv[i] + 2); auto&& argkeyval = getKeyValFromLine(line, '='); args.insert(make_pair( argkeyval.first, stripQuotes(argkeyval.second))); } processArgs(args, true); //figure out datadir auto argIter = args.find("datadir"); if (argIter != args.end()) { dataDir_ = argIter->second; args.erase(argIter); } else { if (!testnet_ && !regtest_) dataDir_ = defaultDataDir_; else if (!regtest_) dataDir_ = defaultTestnetDataDir_; else dataDir_ = defaultRegtestDataDir_; } expandPath(dataDir_); //get datadir auto configPath = dataDir_; appendPath(configPath, "armorydb.conf"); if (DBUtils::fileExists(configPath, 2)) { ConfigFile cf(configPath); auto mapIter = cf.keyvalMap_.find("datadir"); if (mapIter != cf.keyvalMap_.end()) throw DbErrorMsg("datadir is illegal in .conf file"); processArgs(cf.keyvalMap_, false); } processArgs(args, false); //figure out defaults bool autoDbDir = false; if (dbDir_.size() == 0) { dbDir_ = dataDir_; appendPath(dbDir_, dbDirExtention_); autoDbDir = true; } if (blkFileLocation_.size() == 0) { if (!testnet_) blkFileLocation_ = defaultBlkFileLocation_; else blkFileLocation_ = defaultTestnetBlkFileLocation_; } //expand paths if necessary expandPath(dbDir_); expandPath(blkFileLocation_); if (blkFileLocation_.size() < 6 || blkFileLocation_.substr(blkFileLocation_.length() - 6, 6) != "blocks") { appendPath(blkFileLocation_, "blocks"); } logFilePath_ = dataDir_; appendPath(logFilePath_, "dbLog.txt"); //test all paths auto testPath = [](const string& path, int mode) { if (!DBUtils::fileExists(path, mode)) { stringstream ss; ss << path << " is not a valid path"; cout << ss.str() << endl; throw DbErrorMsg(ss.str()); } }; testPath(dataDir_, 6); //create dbdir if was set automatically if (autoDbDir) { try { testPath(dbDir_, 0); } catch (DbErrorMsg&) { #ifdef _WIN32 CreateDirectory(dbDir_.c_str(), NULL); #else mkdir(dbDir_.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif } } //now for the regular test, let it throw if it fails testPath(dbDir_, 6); testPath(blkFileLocation_, 2); //fcgi port if (useCookie_ && !customFcgiPort_) { //no custom fcgi port was provided and the db was spawned with a //cookie file, fcgi port will be randomized srand(time(0)); while (1) { auto port = rand() % 15000 + 49150; stringstream portss; portss << port; if (!testConnection("127.0.0.1", portss.str())) { fcgiPort_ = portss.str(); break; } } } } catch (...) { exceptionPtr_ = current_exception(); } }
char * helpFile(char *base) { return expandPath(Strnew_m_charp(w3m_help_dir(), "/", base, NULL)->ptr); }
int main(int argc, char *argv[], char **envp) { extern char *getenv(); char *p; int length; Str qs = NULL; struct parsed_tagarg *cgiarg; char *mode; char *bmark; char *url; char *title; char *sent_cookie; p = getenv("REQUEST_METHOD"); if (p == NULL || strcasecmp(p, "post")) goto request_err; p = getenv("CONTENT_LENGTH"); if (p == NULL || (length = atoi(p)) <= 0) goto request_err; qs = Strfgets(stdin); Strchop(qs); if (qs->length != length) goto request_err; cgiarg = cgistr2tagarg(qs->ptr); p = getenv("LOCAL_COOKIE_FILE"); if (p) { FILE *f = fopen(p, "r"); if (f) { Local_cookie = Strfgets(f)->ptr; fclose(f); } } sent_cookie = tag_get_value(cgiarg, "cookie"); if (sent_cookie == NULL || Local_cookie == NULL || strcmp(sent_cookie, Local_cookie) != 0) { /* local cookie doesn't match: It may be an illegal invocation */ printf("Content-Type: text/plain\n\n"); printf("Local cookie doesn't match: It may be an illegal invocation\n"); exit(1); } mode = tag_get_value(cgiarg, "mode"); bmark = expandPath(tag_get_value(cgiarg, "bmark")); url = tag_get_value(cgiarg, "url"); title = tag_get_value(cgiarg, "title"); if (bmark == NULL || url == NULL) goto request_err; if (mode && !strcmp(mode, "panel")) { if (title == NULL) title = ""; print_bookmark_panel(bmark, url, title); } else if (mode && !strcmp(mode, "register")) { printf("Content-Type: text/plain\n"); if (insert_bookmark(bmark, cgiarg)) { printf("w3m-control: BACK\n"); printf("w3m-control: BACK\n"); } printf("\n"); } return 0; request_err: printf("Content-Type: text/plain\n\n"); printf("Incomplete Request: %s\n", qs ? qs->ptr : "(null)"); exit(1); }
boost::filesystem::path ComponentRegistry::getPath(std::string working_path, std::string expression){ return expandPath(working_path, expression); }