int main(int argc, char **argv) { int i; sigset_t set; #if ENABLE_MPEGTS uint32_t adapter_mask = 0; #endif int log_level = LOG_INFO; int log_options = TVHLOG_OPT_MILLIS | TVHLOG_OPT_STDERR | TVHLOG_OPT_SYSLOG; const char *log_debug = NULL, *log_trace = NULL; char buf[512]; main_tid = pthread_self(); /* Setup global mutexes */ pthread_mutex_init(&ffmpeg_lock, NULL); pthread_mutex_init(&fork_lock, NULL); pthread_mutex_init(&global_lock, NULL); pthread_mutex_init(&atomic_lock, NULL); pthread_cond_init(>imer_cond, NULL); /* Defaults */ tvheadend_webui_port = 9981; tvheadend_webroot = NULL; tvheadend_htsp_port = 9982; tvheadend_htsp_port_extra = 0; /* Command line options */ int opt_help = 0, opt_version = 0, opt_fork = 0, opt_firstrun = 0, opt_stderr = 0, opt_syslog = 0, opt_uidebug = 0, opt_abort = 0, opt_noacl = 0, opt_fileline = 0, opt_threadid = 0, opt_ipv6 = 0, opt_tsfile_tuner = 0, opt_dump = 0, opt_xspf = 0; const char *opt_config = NULL, *opt_user = NULL, *opt_group = NULL, *opt_logpath = NULL, *opt_log_debug = NULL, *opt_log_trace = NULL, *opt_pidpath = "/var/run/tvheadend.pid", #if ENABLE_LINUXDVB *opt_dvb_adapters = NULL, #endif *opt_bindaddr = NULL, *opt_subscribe = NULL, *opt_user_agent = NULL; str_list_t opt_satip_xml = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) }; str_list_t opt_tsfile = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) }; cmdline_opt_t cmdline_opts[] = { { 0, NULL, "Generic Options", OPT_BOOL, NULL }, { 'h', "help", "Show this page", OPT_BOOL, &opt_help }, { 'v', "version", "Show version infomation", OPT_BOOL, &opt_version }, { 0, NULL, "Service Configuration", OPT_BOOL, NULL }, { 'c', "config", "Alternate config path", OPT_STR, &opt_config }, { 'f', "fork", "Fork and run as daemon", OPT_BOOL, &opt_fork }, { 'u', "user", "Run as user", OPT_STR, &opt_user }, { 'g', "group", "Run as group", OPT_STR, &opt_group }, { 'p', "pid", "Alternate pid path", OPT_STR, &opt_pidpath }, { 'C', "firstrun", "If no user account exists then create one with\n" "no username and no password. Use with care as\n" "it will allow world-wide administrative access\n" "to your Tvheadend installation until you edit\n" "the access-control from within the Tvheadend UI", OPT_BOOL, &opt_firstrun }, #if ENABLE_LINUXDVB { 'a', "adapters", "Only use specified DVB adapters (comma separated)", OPT_STR, &opt_dvb_adapters }, #endif #if ENABLE_SATIP_CLIENT { 0, "satip_xml", "URL with the SAT>IP server XML location", OPT_STR_LIST, &opt_satip_xml }, #endif { 0, NULL, "Server Connectivity", OPT_BOOL, NULL }, { '6', "ipv6", "Listen on IPv6", OPT_BOOL, &opt_ipv6 }, { 'b', "bindaddr", "Specify bind address", OPT_STR, &opt_bindaddr}, { 0, "http_port", "Specify alternative http port", OPT_INT, &tvheadend_webui_port }, { 0, "http_root", "Specify alternative http webroot", OPT_STR, &tvheadend_webroot }, { 0, "htsp_port", "Specify alternative htsp port", OPT_INT, &tvheadend_htsp_port }, { 0, "htsp_port2", "Specify extra htsp port", OPT_INT, &tvheadend_htsp_port_extra }, { 0, "useragent", "Specify User-Agent header for the http client", OPT_STR, &opt_user_agent }, { 0, "xspf", "Use xspf playlist instead M3U", OPT_BOOL, &opt_xspf }, { 0, NULL, "Debug Options", OPT_BOOL, NULL }, { 'd', "stderr", "Enable debug on stderr", OPT_BOOL, &opt_stderr }, { 's', "syslog", "Enable debug to syslog", OPT_BOOL, &opt_syslog }, { 'l', "logfile", "Enable debug to file", OPT_STR, &opt_logpath }, { 0, "debug", "Enable debug subsystems", OPT_STR, &opt_log_debug }, #if ENABLE_TRACE { 0, "trace", "Enable trace subsystems", OPT_STR, &opt_log_trace }, #endif { 0, "fileline", "Add file and line numbers to debug", OPT_BOOL, &opt_fileline }, { 0, "threadid", "Add the thread ID to debug", OPT_BOOL, &opt_threadid }, { 0, "uidebug", "Enable webUI debug (non-minified JS)", OPT_BOOL, &opt_uidebug }, { 'A', "abort", "Immediately abort", OPT_BOOL, &opt_abort }, { 'D', "dump", "Enable coredumps for daemon", OPT_BOOL, &opt_dump }, { 0, "noacl", "Disable all access control checks", OPT_BOOL, &opt_noacl }, { 'j', "join", "Subscribe to a service permanently", OPT_STR, &opt_subscribe }, { 0, NULL, "TODO: testing", OPT_BOOL, NULL }, { 0, "tsfile_tuners", "Number of tsfile tuners", OPT_INT, &opt_tsfile_tuner }, { 0, "tsfile", "tsfile input (mux file)", OPT_STR_LIST, &opt_tsfile }, }; /* Get current directory */ tvheadend_cwd = dirname(dirname(tvh_strdupa(argv[0]))); /* Set locale */ setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); /* make sure the timezone is set */ tzset(); /* Process command line */ for (i = 1; i < argc; i++) { /* Find option */ cmdline_opt_t *opt = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]); if (!opt) show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), "invalid option specified [%s]", argv[i]); /* Process */ if (opt->type == OPT_BOOL) *((int*)opt->param) = 1; else if (++i == argc) show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), "option %s requires a value", opt->lopt); else if (opt->type == OPT_INT) *((int*)opt->param) = atoi(argv[i]); else if (opt->type == OPT_STR_LIST) { str_list_t *strl = opt->param; if (strl->num < strl->max) strl->str[strl->num++] = argv[i]; } else *((char**)opt->param) = argv[i]; /* Stop processing */ if (opt_help) show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL); if (opt_version) show_version(argv[0]); } /* Additional cmdline processing */ #if ENABLE_LINUXDVB if (!opt_dvb_adapters) { adapter_mask = ~0; } else { char *p, *e; char *r = NULL; char *dvb_adapters = strdup(opt_dvb_adapters); adapter_mask = 0x0; p = strtok_r(dvb_adapters, ",", &r); while (p) { int a = strtol(p, &e, 10); if (*e != 0 || a < 0 || a > 31) { tvhlog(LOG_ERR, "START", "Invalid adapter number '%s'", p); free(dvb_adapters); return 1; } adapter_mask |= (1 << a); p = strtok_r(NULL, ",", &r); } free(dvb_adapters); if (!adapter_mask) { tvhlog(LOG_ERR, "START", "No adapters specified!"); return 1; } } #endif if (tvheadend_webroot) { char *tmp; if (*tvheadend_webroot == '/') tmp = strdup(tvheadend_webroot); else { tmp = malloc(strlen(tvheadend_webroot)+2); *tmp = '/'; strcpy(tmp+1, tvheadend_webroot); } if (tmp[strlen(tmp)-1] == '/') tmp[strlen(tmp)-1] = '\0'; tvheadend_webroot = tmp; } tvheadend_webui_debug = opt_uidebug; /* Setup logging */ if (isatty(2)) log_options |= TVHLOG_OPT_DECORATE; if (opt_stderr || opt_syslog || opt_logpath) { if (!opt_log_trace && !opt_log_debug) log_debug = "all"; log_level = LOG_DEBUG; if (opt_stderr) log_options |= TVHLOG_OPT_DBG_STDERR; if (opt_syslog) log_options |= TVHLOG_OPT_DBG_SYSLOG; if (opt_logpath) log_options |= TVHLOG_OPT_DBG_FILE; } if (opt_fileline) log_options |= TVHLOG_OPT_FILELINE; if (opt_threadid) log_options |= TVHLOG_OPT_THREAD; if (opt_log_trace) { log_level = LOG_TRACE; log_trace = opt_log_trace; } if (opt_log_debug) log_debug = opt_log_debug; tvhlog_init(log_level, log_options, opt_logpath); tvhlog_set_debug(log_debug); tvhlog_set_trace(log_trace); signal(SIGPIPE, handle_sigpipe); // will be redundant later /* Daemonise */ if(opt_fork) { const char *homedir; gid_t gid; uid_t uid; struct group *grp = getgrnam(opt_group ?: "video"); struct passwd *pw = opt_user ? getpwnam(opt_user) : NULL; FILE *pidfile = fopen(opt_pidpath, "w+"); if(grp != NULL) { gid = grp->gr_gid; } else { gid = 1; } if (pw != NULL) { if (getuid() != pw->pw_uid) { gid_t glist[10]; int gnum; gnum = get_user_groups(pw, glist, 10); if (setgroups(gnum, glist)) { tvhlog(LOG_ALERT, "START", "setgroups() failed, do you have permission?"); return 1; } } uid = pw->pw_uid; homedir = pw->pw_dir; setenv("HOME", homedir, 1); } else { uid = 1; } if ((getgid() != gid) && setgid(gid)) { tvhlog(LOG_ALERT, "START", "setgid() failed, do you have permission?"); return 1; } if ((getuid() != uid) && setuid(uid)) { tvhlog(LOG_ALERT, "START", "setuid() failed, do you have permission?"); return 1; } if(daemon(0, 0)) { exit(2); } if(pidfile != NULL) { fprintf(pidfile, "%d\n", getpid()); fclose(pidfile); } /* Make dumpable */ if (opt_dump) { #ifdef PLATFORM_LINUX if (chdir("/tmp")) tvhwarn("START", "failed to change cwd to /tmp"); prctl(PR_SET_DUMPABLE, 1); #else tvhwarn("START", "Coredumps not implemented on your platform"); #endif } umask(0); } tvheadend_running = 1; /* Start log thread (must be done post fork) */ tvhlog_start(); /* Alter logging */ if (opt_fork) tvhlog_options &= ~TVHLOG_OPT_STDERR; if (!isatty(2)) tvhlog_options &= ~TVHLOG_OPT_DECORATE; /* Initialise clock */ pthread_mutex_lock(&global_lock); time(&dispatch_clock); /* Signal handling */ sigfillset(&set); sigprocmask(SIG_BLOCK, &set, NULL); trap_init(argv[0]); /* SSL library init */ OPENSSL_config(NULL); SSL_load_error_strings(); SSL_library_init(); /* Initialise configuration */ uuid_init(); idnode_init(); config_init(opt_config); /** * Initialize subsystems */ intlconv_init(); api_init(); fsmonitor_init(); #if ENABLE_LIBAV libav_init(); transcoding_init(); #endif imagecache_init(); http_client_init(opt_user_agent); esfilter_init(); service_init(); #if ENABLE_MPEGTS mpegts_init(adapter_mask, &opt_satip_xml, &opt_tsfile, opt_tsfile_tuner); #endif channel_init(); subscription_init(); access_init(opt_firstrun, opt_noacl); #if ENABLE_TIMESHIFT timeshift_init(); #endif tcp_server_init(opt_ipv6); http_server_init(opt_bindaddr); webui_init(opt_xspf); #if ENABLE_UPNP upnp_server_init(opt_bindaddr); #endif service_mapper_init(); descrambler_init(); epggrab_init(); epg_init(); dvr_init(); htsp_init(opt_bindaddr); if(opt_subscribe != NULL) subscription_dummy_join(opt_subscribe, 1); avahi_init(); bonjour_init(); epg_updated(); // cleanup now all prev ref's should have been created pthread_mutex_unlock(&global_lock); /** * Wait for SIGTERM / SIGINT, but only in this thread */ sigemptyset(&set); sigaddset(&set, SIGTERM); sigaddset(&set, SIGINT); signal(SIGTERM, doexit); signal(SIGINT, doexit); pthread_sigmask(SIG_UNBLOCK, &set, NULL); tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, " "running as PID:%d UID:%d GID:%d, CWD:%s CNF:%s", tvheadend_version, getpid(), getuid(), getgid(), getcwd(buf, sizeof(buf)), hts_settings_get_root()); if(opt_abort) abort(); mainloop(); #if ENABLE_UPNP tvhftrace("main", upnp_server_done); #endif tvhftrace("main", htsp_done); tvhftrace("main", http_server_done); tvhftrace("main", webui_done); tvhftrace("main", fsmonitor_done); #if ENABLE_MPEGTS tvhftrace("main", mpegts_done); #endif tvhftrace("main", http_client_done); // Note: the locking is obviously a bit redundant, but without // we need to disable the gtimer_arm call in epg_save() pthread_mutex_lock(&global_lock); tvhftrace("main", epg_save); #if ENABLE_TIMESHIFT tvhftrace("main", timeshift_term); #endif pthread_mutex_unlock(&global_lock); tvhftrace("main", epggrab_done); tvhftrace("main", tcp_server_done); tvhftrace("main", descrambler_done); tvhftrace("main", service_mapper_done); tvhftrace("main", service_done); tvhftrace("main", channel_done); tvhftrace("main", dvr_done); tvhftrace("main", subscription_done); tvhftrace("main", access_done); tvhftrace("main", epg_done); tvhftrace("main", avahi_done); tvhftrace("main", bonjour_done); tvhftrace("main", imagecache_done); tvhftrace("main", idnode_done); tvhftrace("main", lang_code_done); tvhftrace("main", api_done); tvhftrace("main", config_done); tvhftrace("main", hts_settings_done); tvhftrace("main", dvb_done); tvhftrace("main", lang_str_done); tvhftrace("main", esfilter_done); tvhftrace("main", intlconv_done); tvhftrace("main", urlparse_done); tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend"); tvhlog_end(); if(opt_fork) unlink(opt_pidpath); free(opt_tsfile.str); free(opt_satip_xml.str); /* OpenSSL - welcome to the "cleanup" hell */ ENGINE_cleanup(); RAND_cleanup(); CRYPTO_cleanup_all_ex_data(); EVP_cleanup(); CONF_modules_free(); COMP_zlib_cleanup(); ERR_remove_state(0); ERR_free_strings(); { sk_SSL_COMP_free(SSL_COMP_get_compression_methods()); } /* end of OpenSSL cleanup code */ return 0; } /** * */ void tvh_str_set(char **strp, const char *src) { free(*strp); *strp = src ? strdup(src) : NULL; } /** * */ int tvh_str_update(char **strp, const char *src) { if(src == NULL) return 0; free(*strp); *strp = strdup(src); return 1; } /** * */ void scopedunlock(pthread_mutex_t **mtxp) { pthread_mutex_unlock(*mtxp); }
static int pkg_repo_binary_try_fetch(struct pkg_repo *repo, struct pkg *pkg, bool already_tried, bool mirror, const char *destdir) { char dest[MAXPATHLEN]; char url[MAXPATHLEN]; char *dir = NULL; int fetched = 0; char cksum[SHA256_DIGEST_LENGTH * 2 +1]; int64_t pkgsize; struct stat st; char *path = NULL; const char *packagesite = NULL, *repourl; int retcode = EPKG_OK; const char *name, *version, *sum; assert((pkg->type & PKG_REMOTE) == PKG_REMOTE); pkg_get(pkg, PKG_CKSUM, &sum, PKG_NAME, &name, PKG_VERSION, &version, PKG_PKGSIZE, &pkgsize, PKG_REPOPATH, &repourl); if (mirror) { const char *cachedir; if (destdir != NULL) cachedir = destdir; else cachedir = pkg_object_string(pkg_config_get("PKG_CACHEDIR")); snprintf(dest, sizeof(dest), "%s/%s", cachedir, repourl); } else pkg_repo_binary_get_cached_name(repo, pkg, dest, sizeof(dest)); /* If it is already in the local cachedir, dont bother to * download it */ if (access(dest, F_OK) == 0) goto checksum; /* Create the dirs in cachedir */ dir = strdup(dest); if (dir == NULL || (path = dirname(dir)) == NULL) { pkg_emit_errno("dirname", dest); retcode = EPKG_FATAL; goto cleanup; } if ((retcode = mkdirs(path)) != EPKG_OK) goto cleanup; /* * In multi-repos the remote URL is stored in pkg[PKG_REPOURL] * For a single attached database the repository URL should be * defined by PACKAGESITE. */ packagesite = pkg_repo_url(repo); if (packagesite == NULL || packagesite[0] == '\0') { pkg_emit_error("PACKAGESITE is not defined"); retcode = 1; goto cleanup; } if (packagesite[strlen(packagesite) - 1] == '/') pkg_snprintf(url, sizeof(url), "%S%R", packagesite, pkg); else pkg_snprintf(url, sizeof(url), "%S/%R", packagesite, pkg); if (!mirror && strncasecmp(packagesite, "file://", 7) == 0) { pkg_set(pkg, PKG_REPOPATH, url + 7); return (EPKG_OK); } retcode = pkg_fetch_file(repo, url, dest, 0); fetched = 1; if (retcode != EPKG_OK) goto cleanup; checksum: /* checksum calculation is expensive, if size does not match, skip it and assume failed checksum. */ if (stat(dest, &st) == -1 || pkgsize != st.st_size) { if (already_tried) { pkg_emit_error("cached package %s-%s: " "size mismatch, cannot continue", name, version); retcode = EPKG_FATAL; goto cleanup; } unlink(dest); pkg_emit_error("cached package %s-%s: " "size mismatch, fetching from remote", name, version); return (pkg_repo_binary_try_fetch(repo, pkg, true, mirror, destdir)); } retcode = sha256_file(dest, cksum); if (retcode == EPKG_OK) { if (strcmp(cksum, sum)) { if (already_tried || fetched == 1) { pkg_emit_error("%s-%s failed checksum " "from repository", name, version); retcode = EPKG_FATAL; } else { pkg_emit_error("cached package %s-%s: " "checksum mismatch, fetching from remote", name, version); unlink(dest); return (pkg_repo_binary_try_fetch(repo, pkg, true, mirror, destdir)); } } } cleanup: if (retcode != EPKG_OK) unlink(dest); else if (!mirror && path != NULL) { (void)pkg_repo_binary_create_symlink(pkg, dest, path); } /* allowed even if dir is NULL */ free(dir); return (retcode); }
void Filesystem::createDirectoriesFor(const std::string& file) { createDirectories(dirname(file)); }
int32_t xar_linuxattr_extract(xar_t x, xar_file_t f, const char* file, char *buffer, size_t len) { #if defined HAVE_SYS_XATTR_H && defined(HAVE_LSETXATTR) && !defined(__APPLE__) const char *fsname = "bogus"; struct statfs sfs; int eaopt = 0; struct _linuxattr_context context; xar_prop_t p; memset(&context,0,sizeof(struct _linuxattr_context)); /* data buffers, can't store linux attrs */ if(len){ return 0; } /* Check for EA extraction behavior */ memset(&sfs, 0, sizeof(sfs)); if( statfs(file, &sfs) != 0 ) { char *tmp, *bname; tmp = strdup(file); bname = dirname(tmp); statfs(bname, &sfs); free(tmp); } switch(sfs.f_type) { case EXT3_SUPER_MAGIC: fsname = "ext3"; break; /* assume ext3 */ case JFS_SUPER_MAGIC: fsname = "jfs" ; break; case REISERFS_SUPER_MAGIC:fsname = "reiser" ; break; case XFS_SUPER_MAGIC: fsname = "xfs" ; break; }; for(p = xar_prop_pfirst(f); p; p = xar_prop_pnext(p)) { const char *fs = NULL; const char *prop; const char *eaname = NULL; xar_prop_t tmpp; prop = xar_prop_getkey(p); if( strncmp(prop, XAR_EA_FORK, strlen(XAR_EA_FORK)) != 0 ) continue; if( strlen(prop) != strlen(XAR_EA_FORK) ) continue; tmpp = xar_prop_pget(p, "fstype"); if( tmpp ) fs = xar_prop_getvalue(tmpp); if( !eaopt && fs && strcmp(fs, fsname) != 0 ) { continue; } if( !fs ) continue; tmpp = xar_prop_pget(p, "name"); if( tmpp ) eaname = xar_prop_getvalue(tmpp); context.file = file; context.attrname = eaname; xar_attrcopy_from_heap(x, f, p, xar_linuxattr_write, &context); } #endif return 0; }
int make_policy(char **type, char **data, int count, char **presult, int derive) { static char result[4096]; char one[2048]; int i; int nfilename, isfilename; result[0] = '\0'; nfilename = 0; for (i = 0; i < count; i++) { isfilename = 0; /* Special case for non existing filenames */ if (strstr(data[i], "<non-existent filename>") != NULL) { snprintf(result, sizeof(result), "filename%s sub \"<non-existent filename>\" then deny[enoent]", i ? "[1]" : ""); break; } if (!strcmp(type[i], "uid") || !strcmp(type[i], "gid") || !strcmp(type[i], "argv")) continue; /* Special case for system calls with more than one filename */ if (!strcmp(type[i], "filename")) { isfilename = 1; nfilename++; } if (strlen(result)) { if (strlcat(result, " and ", sizeof(result)) >= sizeof(result)) return (-1); } /* Special treatment for filenames */ if (isfilename) { char filename[2048]; char *operator = "eq"; if (derive) { operator = "match"; snprintf(filename, sizeof(filename), "%s/*", dirname(data[i])); } else strlcpy(filename, data[i], sizeof(filename)); /* Make useful replacements */ while (strrpl(filename, sizeof(filename), home, "$HOME") != NULL) ; while (strrpl(filename, sizeof(filename), username, "$USER") != NULL) ; snprintf(one, sizeof(one), "%s%s %s \"%s\"", type[i], isfilename && nfilename == 2 ? "[1]" : "", operator, filename); } else { snprintf(one, sizeof(one), "%s eq \"%s\"", type[i], data[i]); } if (strlcat(result, one, sizeof(result)) >= sizeof(result)) return (-1);; } if (!strlen(result)) return (-1); /* Normal termination */ if (i == count) strlcat(result, " then permit", sizeof(result)); *presult = result; return (nfilename); }
stream2file_error_msg_t start_recording(const char * const filename, const char * const info, const unsigned short vpid, const unsigned short * const pids, const unsigned int numpids) { int fd; char buf[FILENAMEBUFFERSIZE]; struct statfs s; // rip rec_filename if(autoshift) sprintf(rec_filename, "%s_temp", filename); else sprintf(rec_filename, "%s", filename); // write stream information (should wakeup the disk from standby, too) sprintf(buf, "%s.xml", rec_filename); char * dir = strdup(buf); int ret = statfs(dirname(dir), &s); free(dir); if((ret != 0) || (s.f_type == 0x72b6) || (s.f_type == 0x24051905)) { return STREAM2FILE_INVALID_DIRECTORY; } if ((fd = open(buf, O_SYNC | O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) >= 0) { write(fd, info, strlen(info)); fdatasync(fd); close(fd); } else { return STREAM2FILE_INVALID_DIRECTORY; } exit_flag = STREAM2FILE_STATUS_RUNNING; sprintf(buf, "%s.ts", rec_filename); dprintf(DEBUG_NORMAL, "[Stream2File] Record start: file %s vpid 0x%x apid 0x%x\n", buf, vpid, pids[0]); fd = open(buf, O_CREAT | O_RDWR | O_LARGEFILE | O_TRUNC , S_IRWXO | S_IRWXG | S_IRWXU); if(fd < 0) { perror(buf); return STREAM2FILE_INVALID_DIRECTORY; } genpsi(fd); // init record if(!record) { if(channel) record = new cRecord( channel->getFeIndex() ); } // open record->Open(numpids); // start_recording if(!record->Start(fd, (unsigned short ) vpid, (unsigned short *) pids, numpids)) { record->Stop(); delete record; record = NULL; return STREAM2FILE_INVALID_DIRECTORY; } if(channel) { cam0->setCaPmt(channel->getCaPmt(), 0, 1, true); // demux 0+2 , update } return STREAM2FILE_OK; }
static int envfs_load_data(struct envfs_super *super, void *buf, size_t size, const char *dir, unsigned flags) { int fd, ret = 0; char *str, *tmp; int headerlen_full; /* for envfs < 1.0 */ struct envfs_inode_end inode_end_dummy; struct stat s; inode_end_dummy.mode = ENVFS_32(S_IRWXU | S_IRWXG | S_IRWXO); inode_end_dummy.magic = ENVFS_32(ENVFS_INODE_END_MAGIC); while (size) { struct envfs_inode *inode; struct envfs_inode_end *inode_end; uint32_t inode_size, inode_headerlen, namelen; inode = buf; buf += sizeof(struct envfs_inode); if (ENVFS_32(inode->magic) != ENVFS_INODE_MAGIC) { printf("envfs: wrong magic\n"); ret = -EIO; goto out; } inode_size = ENVFS_32(inode->size); inode_headerlen = ENVFS_32(inode->headerlen); namelen = strlen(inode->data) + 1; if (super->major < 1) inode_end = &inode_end_dummy; else inode_end = buf + PAD4(namelen); debug("loading %s size %d namelen %d headerlen %d\n", inode->data, inode_size, namelen, inode_headerlen); str = concat_path_file(dir, inode->data); headerlen_full = PAD4(inode_headerlen); buf += headerlen_full; if (ENVFS_32(inode_end->magic) != ENVFS_INODE_END_MAGIC) { printf("envfs: wrong inode_end_magic\n"); ret = -EIO; goto out; } tmp = strdup(str); make_directory(dirname(tmp)); free(tmp); ret = stat(str, &s); if (!ret && (flags & ENV_FLAG_NO_OVERWRITE)) { printf("skip %s\n", str); goto skip; } if (S_ISLNK(ENVFS_32(inode_end->mode))) { debug("symlink: %s -> %s\n", str, (char*)buf); if (!strcmp(buf, basename(str))) { unlink(str); } else { if (!ret) unlink(str); ret = symlink(buf, str); if (ret < 0) printf("symlink: %s -> %s : %s\n", str, (char*)buf, strerror(-errno)); } free(str); } else { fd = open(str, O_WRONLY | O_CREAT | O_TRUNC, 0644); free(str); if (fd < 0) { printf("Open %s\n", errno_str()); ret = fd; goto out; } ret = write(fd, buf, inode_size); if (ret < inode_size) { perror("write"); ret = -errno; close(fd); goto out; } close(fd); } skip: buf += PAD4(inode_size); size -= headerlen_full + PAD4(inode_size) + sizeof(struct envfs_inode); } recursive_action(dir, ACTION_RECURSE | ACTION_DEPTHFIRST, NULL, dir_remove_action, NULL, 0); ret = 0; out: return ret; }
/* * Like fgets, but go through the list of files chaining them together. * Set len to the length of the line. */ int mf_fgets(SPACE *sp, enum e_spflag spflag) { struct stat sb; ssize_t len; static char *p = NULL; static size_t plen = 0; int c; static int firstfile; if (infile == NULL) { /* stdin? */ if (files->fname == NULL) { if (inplace != NULL) errx(1, "-I or -i may not be used with stdin"); infile = stdin; fname = "stdin"; outfile = stdout; outfname = "stdout"; } firstfile = 1; } for (;;) { if (infile != NULL && (c = getc(infile)) != EOF) { (void)ungetc(c, infile); break; } /* If we are here then either eof or no files are open yet */ if (infile == stdin) { sp->len = 0; return (0); } if (infile != NULL) { fclose(infile); if (*oldfname != '\0') { /* if there was a backup file, remove it */ unlink(oldfname); /* * Backup the original. Note that hard links * are not supported on all filesystems. */ if ((link(fname, oldfname) != 0) && (rename(fname, oldfname) != 0)) { warn("rename()"); if (*tmpfname) unlink(tmpfname); exit(1); } *oldfname = '\0'; } if (*tmpfname != '\0') { if (outfile != NULL && outfile != stdout) if (fclose(outfile) != 0) { warn("fclose()"); unlink(tmpfname); exit(1); } outfile = NULL; if (rename(tmpfname, fname) != 0) { /* this should not happen really! */ warn("rename()"); unlink(tmpfname); exit(1); } *tmpfname = '\0'; } outfname = NULL; } if (firstfile == 0) files = files->next; else firstfile = 0; if (files == NULL) { sp->len = 0; return (0); } fname = files->fname; if (inplace != NULL) { if (lstat(fname, &sb) != 0) err(1, "%s", fname); if (!(sb.st_mode & S_IFREG)) errx(1, "%s: %s %s", fname, "in-place editing only", "works for regular files"); if (*inplace != '\0') { strlcpy(oldfname, fname, sizeof(oldfname)); len = strlcat(oldfname, inplace, sizeof(oldfname)); if (len > (ssize_t)sizeof(oldfname)) errx(1, "%s: name too long", fname); } len = snprintf(tmpfname, sizeof(tmpfname), "%s/.!%ld!%s", dirname(fname), (long)getpid(), basename(fname)); if (len >= (ssize_t)sizeof(tmpfname)) errx(1, "%s: name too long", fname); unlink(tmpfname); if (outfile != NULL && outfile != stdout) fclose(outfile); if ((outfile = fopen(tmpfname, "w")) == NULL) err(1, "%s", fname); fchown(fileno(outfile), sb.st_uid, sb.st_gid); fchmod(fileno(outfile), sb.st_mode & 777); outfname = tmpfname; if (!ispan) { linenum = 0; resetstate(); } } else { outfile = stdout; outfname = "stdout"; } if ((infile = fopen(fname, "r")) == NULL) { warn("%s", fname); rval = 1; continue; } } /* * We are here only when infile is open and we still have something * to read from it. * * Use getline() so that we can handle essentially infinite input * data. The p and plen are static so each invocation gives * getline() the same buffer which is expanded as needed. */ len = getline(&p, &plen, infile); if (len == -1) err(1, "%s", fname); if (len != 0 && p[len - 1] == '\n') { sp->append_newline = 1; len--; } else if (!lastline()) { sp->append_newline = 1; } else { sp->append_newline = 0; } cspace(sp, p, len, spflag); linenum++; return (1); }
int main(int argc, char * argv[]){ if(argc != 2){ printf("Usage: %s <file_path> \n", argv[0]); return 1; } // Prepares paths to be used during the execution char * basepath; basepath = basename(argv[1]); char * path = argv[1]; char textFilename[MAX_BUFFER]; strcpy(textFilename,path); path = dirname(path); char wordsFilename[MAX_BUFFER]; strcpy(wordsFilename,path); strcat(wordsFilename, "/words.txt"); char tempFilename[MAX_BUFFER]; strcpy(tempFilename,path); strcat(tempFilename, "/temp"); strcat(tempFilename, basepath); // Tries to open words file int fdWords = open(wordsFilename, O_RDONLY); if(fdWords == -1){ printf("%s\n", wordsFilename); perror("Words File missing...\n"); return 2; } // Creates a new temporary file int fdTemp = open(tempFilename, O_WRONLY | O_CREAT | O_TRUNC, 0777); if(fdTemp == -1){ perror("Cannot creat tempFile...\n"); return 3; } // Initializes the pipe to be used in searching process int fd[2]; pipe(fd); int status; int pid; char word[MAX_BUFFER]; while(readLine(fdWords, word) != 0){ pid = fork(); if(pid == 0){ close(fd[READ]); dup2(fd[WRITE],STDOUT_FILENO); // Execute searching process, result is sent to pipe execlp("grep", "grep", "-n", "-o", "-w" , word,textFilename,NULL); return 0; } else if(pid == -1){ perror("Fork error"); return 3; } else{ // Avoids zumbie processes waitpid(-1, &status, WNOHANG); } memset(word,0,sizeof(word)); } close(fdWords); close(fd[WRITE]); char line[MAX_BUFFER]; char * formatedLine; // Puts every searched words in a temporary file while(readLine(fd[READ], line) != 0){ formatedLine = formatLine(line,basepath); write(fdTemp, formatedLine, strnlen(formatedLine, MAX_BUFFER)); write(fdTemp, "\n", 1); memset(line,0,sizeof(line)); } close(fdTemp); return 0; }
int main(int argc, char **argv) { int i; int searching = 1; char searchname[SPCS_S_MAXMODNAME]; char line[SPCS_S_MAXLINE]; char tline[SPCS_S_MAXLINE]; char *p, *p2; (void) strcpy(help_path, dirname(argv[0])); (void) strcat(help_path, "/errgen.help"); if ((argc == 1) || ((argc == 2) && (strcmp(argv[1], "-h") == 0))) { help(); exit(0); } if (argc != 3) fatal("Bad number of arguments"); p = argv[2]; p2 = modname; while (*p) *p2++ = toupper(*p++); *p2 = 0; switch (argv[1][1]) { case 'c': mode = C_MODE; break; case 'j': mode = J_MODE; break; case 'e': mode = E_MODE; break; case 'm': mode = M_MODE; break; case 't': mode = T_MODE; break; case 'x': mode = X_MODE; break; default: fatal("Unknown option switch"); } if (strcmp(modname, "DSW") == 0) { (void) strcpy(searchname, "II"); } else if (strcmp(modname, "RDC") == 0) { (void) strcpy(searchname, "SNDR"); } else if (strcmp(modname, "SDCTL") == 0) { (void) strcpy(searchname, "NSCTL"); } else { (void) strcpy(searchname, modname); } i = 0; do { if (strcmp(module_names[i++], searchname) == 0) { searching = 0; mod_number = i - 1; break; } } while (module_names[i]); if (searching) { if (i != SPCS_M_MAX) (void) fprintf(stderr, "NULL in module_names before SPCS_M_MAX\n"); fatal("Undefined module name"); } do_preamble(); while (!feof(stdin)) { (void) fgets(line, SPCS_S_MAXLINE, stdin); if (feof(stdin)) { if (count == 0) fatal("errgen file empty"); do_trailer(); exit(0); } line[strlen(line)-1] = 0; if ((strlen(line) != 0) && (line[0] != '#')) { (void) strcpy(tline, line); p = strchr(tline, ' '); if (p == NULL) { (void) fprintf(stderr, "blank separator missing at line: %d\n", count); fatal(""); } *p = 0; if (strlen(p) > SPCS_S_MAXKEY) { (void) fprintf(stderr, "message label too long at line: %d\n", count); fatal(""); } (void) strcpy(key, tline); if (strlen(key) == 0) { (void) fprintf(stderr, "leading blank at line: %d\n", count); fatal(""); } p++; if (*p != '=') { (void) fprintf(stderr, "= separator missing at line: %d\n", count); fatal(""); } p++; if (*p != ' ') { (void) fprintf(stderr, "blank separator missing at line: %d\n", count); fatal(""); } p++; if (! *p) { (void) fprintf(stderr, "msg text missing at line:%d\n", count); fatal(""); } (void) strcpy(text, p); do_line(); count++; } } return (0); }
FB::variant ibrowserAPI::downloadFile(const std::string& url,const std::string& filename,const boost::optional<FB::JSObjectPtr>& pcb, F_ADD) { if(url.empty() || filename.empty()) ERRO("url or filename is empty!"); THREAD(&ibrowserAPI::downloadFile,url,filename,pcb); curl_global_init(CURL_GLOBAL_ALL); double fileSize = -1; CURL *fileSizeCurl = curl_easy_init(); curl_easy_setopt(fileSizeCurl, CURLOPT_URL,url.c_str()); curl_easy_setopt(fileSizeCurl, CURLOPT_HEADER, 1); curl_easy_setopt(fileSizeCurl, CURLOPT_NOBODY, 1); curl_easy_perform(fileSizeCurl); curl_easy_getinfo(fileSizeCurl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &fileSize); curl_easy_cleanup(fileSizeCurl); log("download file size:%.0f",fileSize); if(0 >= fileSize) { ERRO("get file size error"); } char tmpName[1024]; sprintf(tmpName,"%s/%s",dirname(tmpnam(NULL)),filename.c_str()); log("start download, save file:%s, use %d threads",tmpName,this->downloadThreads); double partSize=fileSize/this->downloadThreads; pthread_t threads[this->downloadThreads]; std::vector<double> counter; for(int i=0;i<this->downloadThreads;i++) { double start=partSize*i; double end=0; if(i+1<this->downloadThreads) end=partSize*(i+1)-1; else end=fileSize; FILE *tmpFile=fopen(tmpName,"wb+"); if(!tmpFile) ERRO("create tmp file error"); fseek(tmpFile,start,SEEK_SET); counter.push_back(0); log("threadid:%d,range:%.0f-%.0f",i,start,end); DownloadConfig *cfg=new DownloadConfig(i,url,tmpFile,*pcb,fileSize,start,end,&counter); pthread_create(&threads[i],NULL,&ibrowserAPI::downloadThread,cfg); } for(int i=0; i< this->downloadThreads; i++) { pthread_join(threads[i], NULL); } curl_global_cleanup(); double downloadSize=0; int len=counter.size(); for(int i=0;i<len;i++) { downloadSize+=counter.at(i); } //downloadSize+=1; log("downloadSize:%.0f",downloadSize); if(downloadSize == fileSize) { SUCC(tmpName); }else{ ERRO("download error"); } return true; }
/* output must be a file, which is a (compressed) tar file, of the file denoted by "file", without any of its directory paths etc etc */ static void create_fullfile(struct file *file) { char *origin; char *tarname = NULL; char *rename_source = NULL; char *rename_target = NULL; char *rename_tmpdir = NULL; int ret; struct stat sbuf; char *empty, *indir, *outdir; char *param1, *param2; if (file->is_deleted) { return; /* file got deleted -> by definition we cannot tar it up */ } empty = config_empty_dir(); indir = config_image_base(); outdir = config_output_dir(); string_or_die(&tarname, "%s/%i/files/%s.tar", outdir, file->last_change, file->hash); if (access(tarname, R_OK) == 0) { /* output file already exists...done */ free(tarname); return; } free(tarname); //printf("%s was missing\n", file->hash); string_or_die(&origin, "%s/%i/full/%s", indir, file->last_change, file->filename); if (lstat(origin, &sbuf) < 0) { /* no input file: means earlier phase of update creation failed */ LOG(NULL, "Failed to stat", "%s: %s", origin, strerror(errno)); assert(0); } if (file->is_dir) { /* directories are easy */ char *tmp1, *tmp2, *dir, *base; tmp1 = strdup(origin); assert(tmp1); base = basename(tmp1); tmp2 = strdup(origin); assert(tmp2); dir = dirname(tmp2); string_or_die(&rename_tmpdir, "%s/XXXXXX", outdir); if (!mkdtemp(rename_tmpdir)) { LOG(NULL, "Failed to create temporary directory for %s move", origin); assert(0); } string_or_die(¶m1, "--exclude=%s/?*", base); string_or_die(¶m2, "./%s", base); char *const tarcfcmd[] = { TAR_COMMAND, "-C", dir, TAR_PERM_ATTR_ARGS_STRLIST, "-cf", "-", param1, param2, NULL }; char *const tarxfcmd[] = { TAR_COMMAND, "-C", rename_tmpdir, TAR_PERM_ATTR_ARGS_STRLIST, "-xf", "-", NULL }; int tarcmdresult = system_argv_pipe(tarcfcmd, tarxfcmd); if (tarcmdresult != 0) { LOG(NULL, "Tar command for copying directory full file failed with code %d", tarcmdresult); assert(0); } free(param1); free(param2); string_or_die(&rename_source, "%s/%s", rename_tmpdir, base); string_or_die(&rename_target, "%s/%s", rename_tmpdir, file->hash); if (rename(rename_source, rename_target)) { LOG(NULL, "rename failed for %s to %s", rename_source, rename_target); assert(0); } free(rename_source); /* for a directory file, tar up simply with gzip */ string_or_die(¶m1, "%s/%i/files/%s.tar", outdir, file->last_change, file->hash); char *const tarcmd[] = { TAR_COMMAND, "-C", rename_tmpdir, TAR_PERM_ATTR_ARGS_STRLIST, "-zcf", param1, file->hash, NULL }; if (system_argv(tarcmd) != 0) { assert(0); } free(param1); if (rmdir(rename_target)) { LOG(NULL, "rmdir failed for %s", rename_target); } free(rename_target); if (rmdir(rename_tmpdir)) { LOG(NULL, "rmdir failed for %s", rename_tmpdir); } free(rename_tmpdir); free(tmp1); free(tmp2); } else { /* files are more complex */ char *gzfile = NULL, *bzfile = NULL, *xzfile = NULL; char *tempfile; uint64_t gz_size = LONG_MAX, bz_size = LONG_MAX, xz_size = LONG_MAX; /* step 1: hardlink the guy to an empty directory with the hash as the filename */ string_or_die(&tempfile, "%s/%s", empty, file->hash); if (link(origin, tempfile) < 0) { LOG(NULL, "hardlink failed", "%s due to %s (%s -> %s)", file->filename, strerror(errno), origin, tempfile); char *const argv[] = { "cp", "-a", origin, tempfile, NULL }; if (system_argv(argv) != 0) { assert(0); } } /* step 2a: tar it with each compression type */ // lzma string_or_die(¶m1, "--directory=%s", empty); string_or_die(¶m2, "%s/%i/files/%s.tar.xz", outdir, file->last_change, file->hash); char *const tarlzmacmd[] = { TAR_COMMAND, param1, TAR_PERM_ATTR_ARGS_STRLIST, "-Jcf", param2, file->hash, NULL }; if (system_argv(tarlzmacmd) != 0) { assert(0); } free(param1); free(param2); // gzip string_or_die(¶m1, "--directory=%s", empty); string_or_die(¶m2, "%s/%i/files/%s.tar.gz", outdir, file->last_change, file->hash); char *const targzipcmd[] = { TAR_COMMAND, param1, TAR_PERM_ATTR_ARGS_STRLIST, "-zcf", param2, file->hash, NULL }; if (system_argv(targzipcmd) != 0) { assert(0); } free(param1); free(param2); #ifdef SWUPD_WITH_BZIP2 string_or_die(¶m1, "--directory=%s", empty); string_or_die(¶m2, "%s/%i/files/%s.tar.bz2", outdir, file->last_change, file->hash); char *const tarbzip2cmd[] = { TAR_COMMAND, param1, TAR_PERM_ATTR_ARGS_STRLIST, "-jcf", param2, file->hash, NULL }; if (system_argv(tarbzip2cmd) != 0) { assert(0); } free(param1); free(param2); #endif /* step 2b: pick the smallest of the three compression formats */ string_or_die(&gzfile, "%s/%i/files/%s.tar.gz", outdir, file->last_change, file->hash); if (stat(gzfile, &sbuf) == 0) { gz_size = sbuf.st_size; } string_or_die(&bzfile, "%s/%i/files/%s.tar.bz2", outdir, file->last_change, file->hash); if (stat(bzfile, &sbuf) == 0) { bz_size = sbuf.st_size; } string_or_die(&xzfile, "%s/%i/files/%s.tar.xz", outdir, file->last_change, file->hash); if (stat(xzfile, &sbuf) == 0) { xz_size = sbuf.st_size; } string_or_die(&tarname, "%s/%i/files/%s.tar", outdir, file->last_change, file->hash); if (gz_size <= xz_size && gz_size <= bz_size) { ret = rename(gzfile, tarname); } else if (xz_size <= bz_size) { ret = rename(xzfile, tarname); } else { ret = rename(bzfile, tarname); } if (ret != 0) { LOG(file, "post-tar rename failed", "ret=%d", ret); } unlink(bzfile); unlink(xzfile); unlink(gzfile); free(bzfile); free(xzfile); free(gzfile); free(tarname); /* step 3: remove the hardlink */ unlink(tempfile); free(tempfile); } free(indir); free(outdir); free(empty); free(origin); }
// This is Scramble. int main(int argc, string argv[]) { // ensure proper usage if (argc > 2) { printf("Usage: %s [#]\n", basename(argv[0])); return 1; } // seed pseudorandom number generator if (argc == 2) { int seed = atoi(argv[1]); if (seed <= 0) { printf("Invalid grid.\n"); return 1; } srand(seed); } else srand(time(NULL)); // determine path to dictionary string directory = dirname(argv[0]); char path[strlen(directory) + 1 + strlen(DICTIONARY) + 1]; sprintf(path, "%s/%s", directory, DICTIONARY); // load dictionary if (!load(path)) { printf("Could not open dictionary.\n"); return 1; } // initialize the grid initialize(); // initialize user's score int score = 0; // calculate time of game's end int end = time(NULL) + DURATION; // open log log = fopen("log.txt", "a"); if (log == NULL) { printf("Could not open log.\n"); return 1; } // accept words until timer expires while (true) { // clear the screen clear(); // draw the current state of the grid draw(); // log board for (int row = 0; row < DIMENSION; row++) { for (int col = 0; col < DIMENSION; col++) fprintf(log, "%c", grid[row][col]); fprintf(log, "\n"); } // get current time int now = time(NULL); // report score printf("Score: %d\n", score); fprintf(log, "%d\n", score); // check for game's end if (now >= end) { printf("\033[31m"); // red printf("Time: %d\n\n", 0); printf("\033[39m"); // default break; } // report time remaining printf("Time: %d\n\n", end - now); // prompt for word printf("> "); string word = GetString(); if (word != NULL) { //define the string length as an integer int word_length = strlen(word); //set each individual character in the string to be uppercase for(int i=0; i < word_length; i++) word[i] = toupper(word[i]); // log word fprintf(log, "%s\n", word); // check whether to scramble grid if (strcmp(word, "SCRAMBLE") == 0) scramble(); // or to look for word on grid and in dictionary else { if (find(word) == true && lookup(word) == true) score += strlen(word); } } } // close log fclose(log); return 0; }
int tiny_mkdir(const char *path, mode_t mode) { tiny_inode i_tmp, parent_inode; tiny_dentry *d_tmp, *child_dentry; char *token; char *path_copy; char *dir_name; char *base_name; int i, j; int ret = 0; if ( strlen(path) > NAME_LEN_MAX - 1/*\0*/ ) { return -ENAMETOOLONG; } /* Get inode of the parent directory */ path_copy = (char*)malloc(strlen(path) + 1); strcpy(path_copy, path); dir_name = dirname(path_copy); token = strtok(dir_name, "/"); ReadInode(&i_tmp, tiny_superblk.s_rdirino); memcpy(&parent_inode, &i_tmp, sizeof(tiny_inode)); while (token) { memcpy(&parent_inode, &i_tmp, sizeof(tiny_inode)); d_tmp = __find_dentry(&i_tmp, token); if (!d_tmp || d_tmp->type == FILE_TYPE_FILE) { ret = -ENOTDIR; goto err; } ReadInode(&i_tmp, d_tmp->inodeNum); token = strtok(NULL, "/"); } /* Get dentry of the target */ free(path_copy); path_copy = (char*)malloc(strlen(path) + 1); strcpy(path_copy, path); base_name = basename(path_copy); child_dentry = __find_dentry(&i_tmp, base_name); /* There is no such file */ if (child_dentry == NULL) { // make a directory!! if ( MakeDirentry(&parent_inode, base_name) == WRONG_VALUE ) { return -EDQUOT; } goto err; } else { // already file exists ret = -EEXIST; goto err; } err: free(child_dentry); free(path_copy); return ret; }
/* ================== Sys_Dirname ================== */ const char *Sys_Dirname( char *path ) { return dirname( path ); }
int main(int argc, char* argv[]) { jq_state *jq = NULL; int ret = 0; int compiled = 0; int parser_flags = 0; int nfiles = 0; if (argc) progname = argv[0]; jq = jq_init(); if (jq == NULL) { perror("malloc"); ret = 2; goto out; } const char* program = 0; jq_util_input_state input_state = jq_util_input_init(NULL, NULL); // XXX add err_cb int further_args_are_files = 0; int jq_flags = 0; size_t short_opts = 0; jv program_arguments = jv_array(); jv lib_search_paths = jv_null(); for (int i=1; i<argc; i++, short_opts = 0) { if (further_args_are_files) { jq_util_input_add_input(input_state, jv_string(argv[i])); nfiles++; } else if (!strcmp(argv[i], "--")) { if (!program) usage(2); further_args_are_files = 1; } else if (!isoptish(argv[i])) { if (program) { jq_util_input_add_input(input_state, jv_string(argv[i])); nfiles++; } else { program = argv[i]; } } else { if (argv[i][1] == 'L') { if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) lib_search_paths = jv_array(); if (argv[i][2] != 0) { // -Lname (faster check than strlen) lib_search_paths = jv_array_append(lib_search_paths, jv_string(argv[i]+2)); } else if (i >= argc - 1) { fprintf(stderr, "-L takes a parameter: (e.g. -L /search/path or -L/search/path)\n"); die(); } else { lib_search_paths = jv_array_append(lib_search_paths, jv_string(argv[i+1])); i++; } continue; } if (isoption(argv[i], 's', "slurp", &short_opts)) { options |= SLURP; if (!short_opts) continue; } if (isoption(argv[i], 'r', "raw-output", &short_opts)) { options |= RAW_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'c', "compact-output", &short_opts)) { options |= COMPACT_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'C', "color-output", &short_opts)) { options |= COLOUR_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'M', "monochrome-output", &short_opts)) { options |= NO_COLOUR_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'a', "ascii-output", &short_opts)) { options |= ASCII_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 0, "unbuffered", &short_opts)) { options |= UNBUFFERED_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'S', "sort-keys", &short_opts)) { options |= SORTED_OUTPUT; if (!short_opts) continue; } if (isoption(argv[i], 'R', "raw-input", &short_opts)) { options |= RAW_INPUT; if (!short_opts) continue; } if (isoption(argv[i], 'n', "null-input", &short_opts)) { options |= PROVIDE_NULL; if (!short_opts) continue; } if (isoption(argv[i], 'f', "from-file", &short_opts)) { options |= FROM_FILE; if (!short_opts) continue; } if (isoption(argv[i], 'j', "join-output", &short_opts)) { options |= RAW_OUTPUT | RAW_NO_LF; if (!short_opts) continue; } if (isoption(argv[i], 0, "seq", &short_opts)) { options |= SEQ; if (!short_opts) continue; } if (isoption(argv[i], 0, "stream", &short_opts)) { parser_flags |= JV_PARSE_STREAMING; if (!short_opts) continue; } if (isoption(argv[i], 0, "stream-errors", &short_opts)) { parser_flags |= JV_PARSE_STREAM_ERRORS; if (!short_opts) continue; } if (isoption(argv[i], 'e', "exit-status", &short_opts)) { options |= EXIT_STATUS; if (!short_opts) continue; } // FIXME: For --arg* we should check that the varname is acceptable if (isoption(argv[i], 0, "arg", &short_opts)) { if (i >= argc - 2) { fprintf(stderr, "%s: --arg takes two parameters (e.g. -a varname value)\n", progname); die(); } jv arg = jv_object(); arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1])); arg = jv_object_set(arg, jv_string("value"), jv_string(argv[i+2])); program_arguments = jv_array_append(program_arguments, arg); i += 2; // skip the next two arguments if (!short_opts) continue; } if (isoption(argv[i], 0, "argjson", &short_opts)) { if (i >= argc - 2) { fprintf(stderr, "%s: --argjson takes two parameters (e.g. -a varname text)\n", progname); die(); } jv v = jv_parse(argv[i+2]); if (!jv_is_valid(v)) { fprintf(stderr, "%s: invalid JSON text passed to --argjson\n", progname); die(); } jv arg = jv_object(); arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1])); arg = jv_object_set(arg, jv_string("value"), v); program_arguments = jv_array_append(program_arguments, arg); i += 2; // skip the next two arguments if (!short_opts) continue; } if (isoption(argv[i], 0, "argfile", &short_opts)) { if (i >= argc - 2) { fprintf(stderr, "%s: --argfile takes two parameters (e.g. -a varname filename)\n", progname); die(); } jv arg = jv_object(); arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1])); jv data = jv_load_file(argv[i+2], 0); if (!jv_is_valid(data)) { data = jv_invalid_get_msg(data); fprintf(stderr, "%s: Bad JSON in --argfile %s %s: %s\n", progname, argv[i+1], argv[i+2], jv_string_value(data)); jv_free(data); ret = 2; goto out; } arg = jv_object_set(arg, jv_string("value"), jv_array_get(data, 0)); program_arguments = jv_array_append(program_arguments, arg); i += 2; // skip the next two arguments if (!short_opts) continue; } if (isoption(argv[i], 0, "debug-dump-disasm", &short_opts)) { options |= DUMP_DISASM; if (!short_opts) continue; } if (isoption(argv[i], 0, "debug-trace", &short_opts)) { jq_flags |= JQ_DEBUG_TRACE; if (!short_opts) continue; } if (isoption(argv[i], 'h', "help", &short_opts)) { usage(0); if (!short_opts) continue; } if (isoption(argv[i], 'V', "version", &short_opts)) { printf("jq-%s\n", JQ_VERSION); ret = 0; goto out; } if (isoption(argv[i], 0, "run-tests", &short_opts)) { i++; // XXX Pass program_arguments, even a whole jq_state *, through; // could be useful for testing jv_free(program_arguments); ret = jq_testsuite(lib_search_paths, argc - i, argv + i); goto out; } // check for unknown options... if this argument was a short option if (strlen(argv[i]) != short_opts + 1) { fprintf(stderr, "%s: Unknown option %s\n", progname, argv[i]); die(); } } } int dumpopts = 0; #ifndef WIN32 /* Disable colour by default on Windows builds as Windows terminals tend not to display it correctly */ if (isatty(fileno(stdout))) dumpopts |= JV_PRINT_COLOUR; #endif if (options & SORTED_OUTPUT) dumpopts |= JV_PRINT_SORTED; if (!(options & COMPACT_OUTPUT)) dumpopts |= JV_PRINT_PRETTY; if (options & ASCII_OUTPUT) dumpopts |= JV_PRINT_ASCII; if (options & COLOUR_OUTPUT) dumpopts |= JV_PRINT_COLOUR; if (options & NO_COLOUR_OUTPUT) dumpopts &= ~JV_PRINT_COLOUR; if (jv_get_kind(lib_search_paths) == JV_KIND_NULL) { // Default search path list lib_search_paths = JV_ARRAY(jv_string("~/.jq"), jv_string("$ORIGIN/../lib/jq"), jv_string("$ORIGIN/lib")); } jq_set_attr(jq, jv_string("JQ_LIBRARY_PATH"), lib_search_paths); char *origin = strdup(argv[0]); if (origin == NULL) { fprintf(stderr, "Error: out of memory\n"); exit(1); } jq_set_attr(jq, jv_string("JQ_ORIGIN"), jv_string(dirname(origin))); free(origin); if (strchr(JQ_VERSION, '-') == NULL) jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string(JQ_VERSION)); else jq_set_attr(jq, jv_string("VERSION_DIR"), jv_string_fmt("%.*s-master", (int)(strchr(JQ_VERSION, '-') - JQ_VERSION), JQ_VERSION)); #if (!defined(WIN32) && defined(HAVE_ISATTY)) || defined(HAVE__ISATTY) #if defined(HAVE__ISATTY) && defined(isatty) #undef isatty #define isatty _isatty #endif if (!program && isatty(STDOUT_FILENO) && !isatty(STDIN_FILENO)) program = "."; #endif if (!program) usage(2); if ((options & PROVIDE_NULL) && (options & (RAW_INPUT | SLURP))) { fprintf(stderr, "%s: --null-input cannot be used with --raw-input or --slurp\n", progname); die(); } if (options & FROM_FILE) { char *program_origin = strdup(program); if (program_origin == NULL) { perror("malloc"); exit(2); } jv data = jv_load_file(program, 1); if (!jv_is_valid(data)) { data = jv_invalid_get_msg(data); fprintf(stderr, "%s: %s\n", progname, jv_string_value(data)); jv_free(data); ret = 2; goto out; } jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string(dirname(program_origin)))); compiled = jq_compile_args(jq, jv_string_value(data), program_arguments); free(program_origin); jv_free(data); } else { jq_set_attr(jq, jv_string("PROGRAM_ORIGIN"), jq_realpath(jv_string("."))); // XXX is this good? compiled = jq_compile_args(jq, program, program_arguments); } if (!compiled){ ret = 3; goto out; } if (options & DUMP_DISASM) { jq_dump_disassembly(jq, 0); printf("\n"); } if ((options & SEQ)) parser_flags |= JV_PARSE_SEQ; if (!(options & RAW_INPUT)) jq_util_input_set_parser(input_state, jv_parser_new(parser_flags), (options & SLURP) ? 1 : 0); // Let jq program read from inputs jq_set_input_cb(jq, jq_util_input_next_input_cb, input_state); // Let jq program call `debug` builtin and have that go somewhere jq_set_debug_cb(jq, debug_cb, &dumpopts); if (nfiles == 0) jq_util_input_add_input(input_state, jv_string("-")); if (options & PROVIDE_NULL) { ret = process(jq, jv_null(), jq_flags, dumpopts); } else { jv value; while (jq_util_input_open_errors(input_state) == 0 && (jv_is_valid((value = jq_util_input_next_input(input_state))) || jv_invalid_has_msg(jv_copy(value)))) { if (jv_is_valid(value)) { ret = process(jq, value, jq_flags, dumpopts); continue; } // Parse error jv msg = jv_invalid_get_msg(value); if (!(options & SEQ)) { // --seq -> errors are not fatal ret = 4; fprintf(stderr, "parse error: %s\n", jv_string_value(msg)); jv_free(msg); break; } fprintf(stderr, "ignoring parse error: %s\n", jv_string_value(msg)); jv_free(msg); } } if (jq_util_input_open_errors(input_state) != 0) ret = 2; out: /* XXX We really should catch ENOSPC and such errors in jv_dumpf()! */ if (fclose(stdout)!=0) { fprintf(stderr,"Error: writing output failed: %s\n", strerror(errno)); ret = 2; } jq_util_input_free(&input_state); jq_teardown(&jq); if (ret >= 10 && (options & EXIT_STATUS)) return ret - 10; if (ret >= 10) return 0; return ret; }
/* * Write counter updates in counter_updates to disk. */ void stats_flush(void) { struct counters *counters; bool need_cleanup = false; bool should_flush = false; int i; assert(conf); if (!conf->stats) { return; } init_counter_updates(); for (i = 0; i < STATS_END; ++i) { if (counter_updates->data[i] > 0) { should_flush = true; break; } } if (!should_flush) return; if (!stats_file) { char *stats_dir; /* * A NULL stats_file means that we didn't get past calculate_object_hash(), * so we just choose one of stats files in the 16 subdirectories. */ stats_dir = format("%s/%x", conf->cache_dir, hash_from_int(getpid()) % 16); stats_file = format("%s/stats", stats_dir); free(stats_dir); } if (!lockfile_acquire(stats_file, lock_staleness_limit)) { return; } counters = counters_init(STATS_END); stats_read(stats_file, counters); for (i = 0; i < STATS_END; ++i) { counters->data[i] += counter_updates->data[i]; } stats_write(stats_file, counters); lockfile_release(stats_file); if (!str_eq(conf->log_file, "")) { for (i = 0; i < STATS_END; ++i) { if (counter_updates->data[stats_info[i].stat] != 0 && !(stats_info[i].flags & FLAG_NOZERO)) { cc_log("Result: %s", stats_info[i].message); } } } if (conf->max_files != 0 && counters->data[STATS_NUMFILES] > conf->max_files / 16) { need_cleanup = true; } if (conf->max_size != 0 && counters->data[STATS_TOTALSIZE] > conf->max_size / 1024 / 16) { need_cleanup = true; } if (need_cleanup) { char *p = dirname(stats_file); cleanup_dir(conf, p); free(p); } }
int check_pkg_symlinks(struct xbps_handle *xhp, const char *pkgname, void *arg) { xbps_array_t array; xbps_object_t obj; xbps_dictionary_t filesd = arg; unsigned int i; const char *file, *tgt = NULL; char *path, *p, *buf, *buf2, *lnk, *dname, *tgt_path; int rv; bool broken = false; array = xbps_dictionary_get(filesd, "links"); if (array == NULL) return false; for (i = 0; i < xbps_array_count(array); i++) { obj = xbps_array_get(array, i); if (!xbps_dictionary_get_cstring_nocopy(obj, "target", &tgt)) { xbps_warn_printf("%s: `%s' symlink with " "empty target object!\n", pkgname, file); continue; } xbps_dictionary_get_cstring_nocopy(obj, "file", &file); if (strcmp(tgt, "") == 0) { xbps_warn_printf("%s: `%s' symlink with " "empty target object!\n", pkgname, file); continue; } if (strcmp(xhp->rootdir, "/")) { tgt_path = xbps_xasprintf("%s%s", xhp->rootdir, tgt); path = xbps_xasprintf("%s%s", xhp->rootdir, file); } else { path = strdup(file); tgt_path = strdup(tgt); } lnk = symlink_target(pkgname, path); if (lnk == NULL) { free(tgt_path); free(path); continue; } p = strdup(path); assert(p); dname = dirname(p); buf = xbps_xasprintf("%s/%s", dname, lnk); buf2 = realpath(path, NULL); if (buf2 == NULL) { xbps_warn_printf("%s: broken symlink %s (target: %s)\n", pkgname, file, tgt); free(path); free(tgt_path); free(p); free(buf); free(lnk); continue; } rv = 1; if (lnk[0] != '/') { /* relative symlink */ if ((strcmp(lnk, tgt) == 0) || (strcmp(buf, tgt_path) == 0) || (strcmp(buf2, tgt_path) == 0)) rv = 0; } else { /* absolute symlink */ if (strcmp(lnk, tgt) == 0) rv = 0; } if (rv) { xbps_warn_printf("%s: modified symlink %s " "points to %s (shall be %s)\n", pkgname, file, lnk, tgt); broken = true; } free(p); free(buf); free(path); free(tgt_path); free(lnk); } return broken; }
int BarFlyID3WriteFile(char const* file_path, struct id3_tag const* tag, BarSettings_t const* settings) { /* * './' + artist + '/' + album + '/' + BAR_FLY_TMP_MP3_FILE_NAME + '\0' */ int const TMP_FILE_PATH_LENGTH = 2 + BAR_FLY_NAME_LENGTH + 1 + BAR_FLY_NAME_LENGTH + 1 + strlen(BAR_FLY_TMP_MP3_FILE_NAME) + 1; int exit_status = 0; int status_int; id3_length_t size1; id3_length_t size2; id3_byte_t* tag_buffer = NULL; FILE* audio_file = NULL; FILE* tmp_file = NULL; uint8_t audio_buffer[BAR_FLY_COPY_BLOCK_SIZE]; char * tmp_path = NULL; char tmp_file_path[TMP_FILE_PATH_LENGTH]; size_t read_count; size_t write_count; tmp_file_path[0] = '\0'; /* * For starters libid3tag kinda sucks. It will only write a tag to a file * if the new tag is the same size as the old tag. Which in this case, * since there is no tag, will never work. So writing of the tag to the * file has to be done manually. */ /* * Render the tag to a buffer that can then be written to the audio file. */ size1 = id3_tag_render(tag, NULL); tag_buffer = malloc(size1); if (tag_buffer == NULL) { BarUiMsg(settings, MSG_ERR, "Failed to allocate memory (bytes = %d).\n", size1); goto error; } size2 = id3_tag_render(tag, tag_buffer); if (size1 != size2) { BarUiMsg(settings, MSG_ERR, "Invalid tag size (expected = %d, " "recevied = %d).\n", size1, size2); goto error; } /* * Prepending data to a file is not trivial in C. Here the approach taken * is to create a temporary file, write the tag to the beginning of the * file, copy the audio file block by block to the tmp file, then overwrite * the audio file with the tmp file. This was done in order to minimize the * chance of ending up with a broken audio file in case the program stopped * durring this process. */ /* * Open the audio file. */ audio_file = fopen(file_path, "rb"); if (audio_file == NULL) { BarUiMsg(settings, MSG_ERR, "Could not read the audio file (%s) " "(%d:%s).\n", file_path, errno, strerror(errno)); goto error; } /* * Open the tmp file. */ if (strchr(file_path, '/') == NULL) { strcpy(tmp_file_path, BAR_FLY_TMP_MP3_FILE_NAME); } else { strncpy(tmp_file_path, file_path, TMP_FILE_PATH_LENGTH); tmp_file_path[TMP_FILE_PATH_LENGTH - 1] = '\0'; tmp_path = dirname(tmp_file_path); strncpy(tmp_file_path, tmp_path, strlen(tmp_path) + 1); strcat(tmp_file_path, "/"); strcat(tmp_file_path, BAR_FLY_TMP_MP3_FILE_NAME); } tmp_file = fopen(tmp_file_path, "w+b"); if (tmp_file == NULL) { BarUiMsg(settings, MSG_ERR, "Could not open the temporary file (%s) " "(%d:%s).\n", tmp_file_path, errno, strerror(errno)); goto error; } /* * Write the tag to the tmp file. */ write_count = fwrite(tag_buffer, 1, size2, tmp_file); if (write_count != size2) { BarUiMsg(settings, MSG_ERR, "Could not write the tag to the file (%s) " "(%d:%s).\n", tmp_file_path, errno, strerror(errno)); goto error; } /* * Read the audio file block by block until the end is reached. Each block * is written to the tmp file. */ while (feof(audio_file) == 0) { read_count = fread(audio_buffer, 1, BAR_FLY_COPY_BLOCK_SIZE, audio_file); if ((read_count != BAR_FLY_COPY_BLOCK_SIZE) && (feof(audio_file) == 0)) { BarUiMsg(settings, MSG_ERR, "Failed to read the audio file (%s) " "(%d:%s).\n", file_path, errno, strerror(errno)); goto error; } write_count = fwrite(audio_buffer, 1, read_count, tmp_file); if (write_count != read_count) { BarUiMsg(settings, MSG_ERR, "Failed to write to the tmp file " "(%s).\n", tmp_file_path); goto error; } } /* * The entire contents of the audio file was copied to the tmp file. Close * the two files. */ fclose(tmp_file); tmp_file = NULL; fclose(audio_file); audio_file = NULL; /* * Overwrite the audio file with the tmp file. */ status_int = rename(tmp_file_path, file_path); if (status_int != 0) { BarUiMsg(settings, MSG_ERR, "Could not overwrite the audio file " "(%d:%s).\n", errno, strerror(errno)); goto error; } goto end; error: /* * Delete the tmp file if it exists. */ unlink(tmp_file_path); exit_status = -1; end: if (tag_buffer != NULL) { free(tag_buffer); } if (audio_file != NULL) { fclose(audio_file); } if (tmp_file != NULL) { fclose(tmp_file); } return exit_status; }
mlt_repository mlt_factory_init( const char *directory ) { // Load the system locales setlocale( LC_ALL, "" ); if ( ! global_properties ) global_properties = mlt_properties_new( ); // Allow property refresh on a subsequent initialisation if ( global_properties ) { mlt_properties_set_or_default( global_properties, "MLT_NORMALISATION", getenv( "MLT_NORMALISATION" ), "PAL" ); mlt_properties_set_or_default( global_properties, "MLT_PRODUCER", getenv( "MLT_PRODUCER" ), "loader" ); mlt_properties_set_or_default( global_properties, "MLT_CONSUMER", getenv( "MLT_CONSUMER" ), "sdl" ); mlt_properties_set( global_properties, "MLT_TEST_CARD", getenv( "MLT_TEST_CARD" ) ); mlt_properties_set_or_default( global_properties, "MLT_PROFILE", getenv( "MLT_PROFILE" ), "dv_pal" ); mlt_properties_set_or_default( global_properties, "MLT_DATA", getenv( "MLT_DATA" ), PREFIX_DATA ); #if defined(WIN32) char path[1024]; DWORD size = sizeof( path ); GetModuleFileName( NULL, path, size ); #elif defined(__DARWIN__) && defined(RELOCATABLE) char path[1024]; uint32_t size = sizeof( path ); _NSGetExecutablePath( path, &size ); #endif #if defined(WIN32) || (defined(__DARWIN__) && defined(RELOCATABLE)) char *path2 = strdup( path ); char *appdir = dirname( path2 ); mlt_properties_set( global_properties, "MLT_APPDIR", appdir ); free( path2 ); #endif } // Only initialise once if ( mlt_directory == NULL ) { #if !defined(WIN32) && !(defined(__DARWIN__) && defined(RELOCATABLE)) // Allow user overrides if ( directory == NULL || !strcmp( directory, "" ) ) directory = getenv( "MLT_REPOSITORY" ); #endif // If no directory is specified, default to install directory if ( directory == NULL ) directory = PREFIX_LIB; // Store the prefix for later retrieval #if defined(WIN32) || (defined(__DARWIN__) && defined(RELOCATABLE)) char *exedir = mlt_environment( "MLT_APPDIR" ); size_t size = strlen( exedir ); if ( global_properties && !getenv( "MLT_DATA" ) ) { mlt_directory = calloc( 1, size + strlen( PREFIX_DATA ) + 1 ); strcpy( mlt_directory, exedir ); strcat( mlt_directory, PREFIX_DATA ); mlt_properties_set( global_properties, "MLT_DATA", mlt_directory ); free( mlt_directory ); } mlt_directory = calloc( 1, size + strlen( directory ) + 1 ); strcpy( mlt_directory, exedir ); strcat( mlt_directory, directory ); #else mlt_directory = strdup( directory ); #endif // Initialise the pool mlt_pool_init( ); // Create and set up the events object event_object = mlt_properties_new( ); mlt_events_init( event_object ); mlt_events_register( event_object, "producer-create-request", ( mlt_transmitter )mlt_factory_create_request ); mlt_events_register( event_object, "producer-create-done", ( mlt_transmitter )mlt_factory_create_done ); mlt_events_register( event_object, "filter-create-request", ( mlt_transmitter )mlt_factory_create_request ); mlt_events_register( event_object, "filter-create-done", ( mlt_transmitter )mlt_factory_create_done ); mlt_events_register( event_object, "transition-create-request", ( mlt_transmitter )mlt_factory_create_request ); mlt_events_register( event_object, "transition-create-done", ( mlt_transmitter )mlt_factory_create_done ); mlt_events_register( event_object, "consumer-create-request", ( mlt_transmitter )mlt_factory_create_request ); mlt_events_register( event_object, "consumer-create-done", ( mlt_transmitter )mlt_factory_create_done ); // Create the repository of services repository = mlt_repository_init( mlt_directory ); // Force a clean up when app closes atexit( mlt_factory_close ); } if ( global_properties ) { char *path = getenv( "MLT_PRESETS_PATH" ); if ( path ) { mlt_properties_set( global_properties, "MLT_PRESETS_PATH", path ); } else { path = malloc( strlen( mlt_environment( "MLT_DATA" ) ) + strlen( PRESETS_DIR ) + 1 ); strcpy( path, mlt_environment( "MLT_DATA" ) ); strcat( path, PRESETS_DIR ); mlt_properties_set( global_properties, "MLT_PRESETS_PATH", path ); free( path ); } } return repository; }
void parse_opts(int *argcp, char ***argvp) { static char* shortopts = "+H:T:hJ:"; static struct option longopts[] = { { "home", required_argument, 0, 'H' }, { "tab", required_argument, 0, 'T' }, { "build", required_argument, 0, 'b' }, { "lisp", no_argument, &lisp_prompt, 1 }, { "help", no_argument, 0, 'h' }, { "sysimage", required_argument, 0, 'J' }, { "code-coverage", optional_argument, 0, 'c' }, { "track-allocation",required_argument, 0, 'm' }, { "check-bounds", required_argument, 0, 300 }, { "int-literals", required_argument, 0, 301 }, { "dump-bitcode", required_argument, 0, 302 }, { "compile", required_argument, 0, 303 }, { 0, 0, 0, 0 } }; int c; opterr = 0; int imagepathspecified=0; image_file = system_image; int skip = 0; int lastind = optind; while ((c = getopt_long(*argcp,*argvp,shortopts,longopts,0)) != -1) { switch (c) { case 0: break; case '?': if (optind != lastind) skip++; lastind = optind; break; case 'H': julia_home = strdup(optarg); break; case 'b': jl_compileropts.build_path = strdup(optarg); if (!imagepathspecified) image_file = NULL; break; case 'J': image_file = strdup(optarg); imagepathspecified = 1; break; case 'h': printf("%s%s", usage, opts); exit(0); case 'c': if (optarg != NULL) { if (!strcmp(optarg,"user")) codecov = JL_LOG_USER; else if (!strcmp(optarg,"all")) codecov = JL_LOG_ALL; else if (!strcmp(optarg,"none")) codecov = JL_LOG_NONE; break; } else { codecov = JL_LOG_USER; } break; case 'm': if (optarg != NULL) { if (!strcmp(optarg,"user")) malloclog = JL_LOG_USER; else if (!strcmp(optarg,"all")) malloclog = JL_LOG_ALL; else if (!strcmp(optarg,"none")) malloclog = JL_LOG_NONE; break; } case 300: if (!strcmp(optarg,"yes")) jl_compileropts.check_bounds = JL_COMPILEROPT_CHECK_BOUNDS_ON; else if (!strcmp(optarg,"no")) jl_compileropts.check_bounds = JL_COMPILEROPT_CHECK_BOUNDS_OFF; break; case 301: if (!strcmp(optarg,"32")) jl_compileropts.int_literals = 32; else if (!strcmp(optarg,"64")) jl_compileropts.int_literals = 64; else { ios_printf(ios_stderr, "julia: invalid integer literal size (%s)\n", optarg); exit(1); } break; case 302: if (!strcmp(optarg,"yes")) jl_compileropts.dumpbitcode = JL_COMPILEROPT_DUMPBITCODE_ON; else if (!strcmp(optarg,"no")) jl_compileropts.dumpbitcode = JL_COMPILEROPT_DUMPBITCODE_OFF; break; case 303: if (!strcmp(optarg,"yes")) jl_compileropts.compile_enabled = 1; else if (!strcmp(optarg,"no")) jl_compileropts.compile_enabled = 0; else if (!strcmp(optarg,"all")) jl_compileropts.compile_enabled = 2; else { ios_printf(ios_stderr, "julia: invalid argument to --compile (%s)\n", optarg); exit(1); } break; default: ios_printf(ios_stderr, "julia: unhandled option -- %c\n", c); ios_printf(ios_stderr, "This is a bug, please report it.\n"); exit(1); } } jl_compileropts.code_coverage = codecov; jl_compileropts.malloc_log = malloclog; if (!julia_home) { julia_home = getenv("JULIA_HOME"); if (julia_home) { julia_home = strdup(julia_home); } else { char *julia_path = (char*)malloc(PATH_MAX); size_t path_size = PATH_MAX; uv_exepath(julia_path, &path_size); julia_home = strdup(dirname(julia_path)); free(julia_path); } } optind -= skip; *argvp += optind; *argcp -= optind; if (image_file==NULL && *argcp > 0) { if (strcmp((*argvp)[0], "-")) { program = (*argvp)[0]; } } if (image_file) { if (image_file[0] != PATHSEP) { uv_stat_t stbuf; char path[512]; if (!imagepathspecified) { // build time path relative to JULIA_HOME snprintf(path, sizeof(path), "%s%s%s", julia_home, PATHSEPSTRING, system_image); image_file = strdup(path); } else if (jl_stat(image_file, (char*)&stbuf) != 0) { // otherwise try julia_home/../lib/julia/%s snprintf(path, sizeof(path), "%s%s%s", julia_home, PATHSEPSTRING ".." PATHSEPSTRING "lib" PATHSEPSTRING "julia" PATHSEPSTRING, image_file); image_file = strdup(path); } } } }
//unlinks a file void my_unlink(char *path) { int ino, i; int parent_ino; MINODE *mip; MINODE *parent_mip; INODE *ip; INODE *parent_ip; char temp[64]; char my_dirname[64]; char my_basename[64]; if(!path)//check for path { printf("ERROR: no path given\n"); return; } ino = getino(running->cwd, path); if(ino == 0) { printf("ERROR: bad path\n"); return; } mip = iget(dev, ino); if(!mip)//make sure file exists { printf("ERROR: missing minode\n"); return; } if(S_ISDIR(mip->INODE.i_mode))//make sure it's a file { printf("ERROR: can't unlink a directory\n"); return; } printf("doing the unlinking\n"); ip = &mip->INODE; //decrement the links count ip->i_links_count--; //printf("links: %d\n", ip->i_links_count); //deallocate its blocks for(i = 0; i < 12 && ip->i_block[i] != 0; i++) { bdealloc(dev, ip->i_block[i]); } //deallocate its inode idealloc(dev, ino); //get basename and dirname strcpy(temp, path); strcpy(my_dirname, dirname(temp)); strcpy(temp, path); strcpy(my_basename, basename(temp)); printf("dirname is %s basename is %s\n", my_dirname, my_basename); //get its parent parent_ino = getino(running->cwd, my_dirname); parent_mip = iget(dev, parent_ino); parent_ip = &parent_mip->INODE; //remove child from parent printf("removing %s from %s\n", my_basename, my_dirname); rm_child(parent_mip, my_basename); parent_ip->i_atime = time(0L);//update times and mark dirty parent_ip->i_mtime = time(0L); parent_mip->dirty = 1; //write back iput(parent_mip); mip->dirty = 1; iput(mip); return; }
Win32CallstackResolver::Win32CallstackResolver(char *moduleDB, size_t DBSize, string pdbSearchPaths, volatile bool *killSignal) { wstring configPath = StringFormat::UTF82Wide(FileIO::GetAppFolderFilename("config.ini")); { FILE *f = NULL; _wfopen_s(&f, configPath.c_str(), L"a"); if(f) fclose(f); } DWORD sz = 2048; wchar_t *inputBuf = new wchar_t[sz]; for(;;) { DWORD read = GetPrivateProfileStringW(L"renderdoc", L"ignores", NULL, inputBuf, sz, configPath.c_str()); if(read == sz - 1) { sz *= 2; delete[] inputBuf; inputBuf = new wchar_t[sz]; continue; } break; } wstring ignores = inputBuf; delete[] inputBuf; split(ignores, pdbIgnores, L';'); wstring widepdbsearch = StringFormat::UTF82Wide(pdbSearchPaths); split(widepdbsearch, pdbRememberedPaths, L';'); if(memcmp(moduleDB, "WN32CALL", 8)) { RDCWARN("Can't load callstack resolve for this log. Possibly from another platform?"); return; } char *chunks = moduleDB + 8; char *end = chunks + DBSize - 8; EnumModChunk *chunk = (EnumModChunk *)(chunks); WCHAR *modName = (WCHAR *)(chunks + sizeof(EnumModChunk)); // loop over all our modules for(; chunks < end; chunks += sizeof(EnumModChunk) + (chunk->imageNameLen) * sizeof(WCHAR)) { chunk = (EnumModChunk *)chunks; modName = (WCHAR *)(chunks + sizeof(EnumModChunk)); if(killSignal && *killSignal) break; Module m; m.name = modName; m.base = chunk->base; m.size = chunk->size; m.moduleId = 0; if(find(pdbIgnores.begin(), pdbIgnores.end(), m.name) != pdbIgnores.end()) { RDCWARN("Not attempting to get symbols for %ls", m.name.c_str()); modules.push_back(m); continue; } // get default pdb (this also looks up symbol server etc) // Always done in unicode std::wstring defaultPdb = DIA2::LookupModule(modName, chunk->guid, chunk->age); // strip newline if(defaultPdb != L"" && defaultPdb[defaultPdb.length() - 1] == '\n') defaultPdb.pop_back(); // if we didn't even get a default pdb we'll have to prompt first time through bool failed = false; if(defaultPdb == L"") { defaultPdb = strlower(basename(m.name)); size_t it = defaultPdb.find(L".dll"); if(it != wstring::npos) { defaultPdb[it + 1] = L'p'; defaultPdb[it + 2] = L'd'; defaultPdb[it + 3] = L'b'; } it = defaultPdb.find(L".exe"); if(it != wstring::npos) { defaultPdb[it + 1] = L'p'; defaultPdb[it + 2] = L'd'; defaultPdb[it + 3] = L'b'; } failed = true; } std::wstring pdbName = defaultPdb; int fallbackIdx = -1; while(m.moduleId == 0) { if(failed) { fallbackIdx++; // try one of the folders we've been given, just in case the symbols // are there if(fallbackIdx < (int)pdbRememberedPaths.size()) { pdbName = pdbRememberedPaths[fallbackIdx] + L"\\" + basename(pdbName); } else { pdbName = dirname(defaultPdb) + L"\\" + basename(defaultPdb); // prompt for new pdbName, unless it's renderdoc or dbghelp if(pdbName.find(L"renderdoc.") != wstring::npos || pdbName.find(L"dbghelp.") != wstring::npos || pdbName.find(L"symsrv.") != wstring::npos) pdbName = L""; else pdbName = pdbBrowse(pdbName); // user cancelled, just don't load this pdb if(pdbName == L"") break; } failed = false; } m.moduleId = DIA2::GetModule(pdbName.c_str(), chunk->guid, chunk->age); if(m.moduleId == 0) { failed = true; } else { if(fallbackIdx >= (int)pdbRememberedPaths.size()) { wstring dir = dirname(pdbName); if(find(pdbRememberedPaths.begin(), pdbRememberedPaths.end(), dir) == pdbRememberedPaths.end()) { pdbRememberedPaths.push_back(dir); } } } } // didn't load the pdb? go to the next module. if(m.moduleId == 0) { modules.push_back(m); // still add the module, with 0 module id RDCWARN("Couldn't get symbols for %ls", m.name.c_str()); // silently ignore renderdoc.dll, dbghelp.dll, and symsrv.dll without asking to permanently // ignore if(m.name.find(L"renderdoc.") != wstring::npos || m.name.find(L"dbghelp.") != wstring::npos || m.name.find(L"symsrv.") != wstring::npos) continue; wchar_t text[1024]; wsprintf(text, L"Do you want to permanently ignore this file?\nPath: %ls", m.name.c_str()); int ret = MessageBoxW(NULL, text, L"Ignore this pdb?", MB_YESNO); if(ret == IDYES) pdbIgnores.push_back(m.name); continue; } DIA2::SetBaseAddress(m.moduleId, chunk->base); RDCLOG("Loaded Symbols for %ls", m.name.c_str()); modules.push_back(m); } sort(pdbIgnores.begin(), pdbIgnores.end()); pdbIgnores.erase(unique(pdbIgnores.begin(), pdbIgnores.end()), pdbIgnores.end()); merge(pdbIgnores, ignores, L';'); WritePrivateProfileStringW(L"renderdoc", L"ignores", ignores.c_str(), configPath.c_str()); }
/*@-boundswrite@*/ static int buildForTarget(rpmts ts, BTA_t ba) /*@globals rpmGlobalMacroContext, h_errno, fileSystem, internalState @*/ /*@modifies ts, rpmGlobalMacroContext, fileSystem, internalState @*/ { const char * passPhrase = ba->passPhrase; const char * cookie = ba->cookie; int buildAmount = ba->buildAmount; const char * specFile = NULL; const char * specURL = NULL; int specut; const char * s; char * se; const char * arg = ba->specFile; size_t nb = strlen(arg) + BUFSIZ; char * buf = alloca(nb); Spec spec = NULL; int verify = ((ba->buildAmount & RPMBUILD_TRACK) ? 0 : 1); int xx; int rc; if (ba->buildMode == 't') { static const char * sfpats[] = { "Specfile", "\\*.spec", NULL }; static const char _specfn[] = "%{mkstemp:%{_specdir}/rpm-spec.XXXXXX}"; char * tmpSpecFile = (char *) rpmGetPath(_specfn, NULL); FILE *fp; int bingo = 0; int i; for (i = 0; sfpats[i]; i++) { se = rpmExpand("%{uncompress: %{u2p:", arg, "}}", " | %{__tar} -xOvf - %{?__tar_wildcards} ", sfpats[i], " 2>&1 > '", tmpSpecFile, "'", NULL); fp = popen(se, "r"); se = _free(se); if (fp== NULL) continue; s = fgets(buf, nb - 1, fp); xx = pclose(fp); if (!s || !*s || strstr(s, ": Not found in archive")) continue; bingo = 1; break; } if (!bingo) { rpmlog(RPMLOG_ERR, _("Failed to read spec file from %s\n"), arg); xx = Unlink(tmpSpecFile); tmpSpecFile = _free(tmpSpecFile); return 1; } s = se = basename(buf); se += strlen(se); while (--se > s && strchr("\r\n", *se) != NULL) *se = '\0'; specURL = rpmGetPath("%{_specdir}/", s, NULL); specut = urlPath(specURL, &specFile); xx = Rename(tmpSpecFile, specFile); if (xx) { rpmlog(RPMLOG_ERR, _("Failed to rename %s to %s: %m\n"), tmpSpecFile, s); (void) Unlink(tmpSpecFile); } tmpSpecFile = _free(tmpSpecFile); if (xx) return 1; se = buf; *se = '\0'; se = stpcpy(se, "_sourcedir "); (void) urlPath(arg, &s); if (*s != '/') { if (getcwd(se, nb - sizeof("_sourcedir ")) != NULL) se += strlen(se); else se = stpcpy(se, "."); } else se = stpcpy(se, dirname(strcpy(se, s))); while (se > buf && se[-1] == '/') *se-- = '0'; rpmCleanPath(buf + sizeof("_sourcedir ") - 1); rpmDefineMacro(NULL, buf, RMIL_TARBALL); } else { specut = urlPath(arg, &s); se = buf; *se = '\0'; if (*s != '/') { if (getcwd(se, nb - sizeof("_sourcedir ")) != NULL) se += strlen(se); else se = stpcpy(se, "."); *se++ = '/'; se += strlen(strcpy(se,strcpy(se, s))); } else se = stpcpy(se, s); specURL = rpmGetPath(buf, NULL); specut = urlPath(specURL, &specFile); } if (specut != URL_IS_DASH) { struct stat sb; if (Stat(specURL, &sb) < 0) { rpmlog(RPMLOG_ERR, _("failed to stat %s: %m\n"), specURL); rc = 1; goto exit; } if (! S_ISREG(sb.st_mode)) { rpmlog(RPMLOG_ERR, _("File %s is not a regular file.\n"), specURL); rc = 1; goto exit; } /* Try to verify that the file is actually a specfile */ if (!isSpecFile(specURL)) { rpmlog(RPMLOG_ERR, _("File %s does not appear to be a specfile.\n"), specURL); rc = 1; goto exit; } } /* Parse the spec file */ #define _anyarch(_f) \ (((_f)&(RPMBUILD_PREP|RPMBUILD_BUILD|RPMBUILD_INSTALL|RPMBUILD_PACKAGEBINARY)) == 0) if (parseSpec(ts, specURL, ba->rootdir, 0, passPhrase, cookie, _anyarch(buildAmount), 0, verify)) { rc = 1; goto exit; } #undef _anyarch if ((spec = rpmtsSetSpec(ts, NULL)) == NULL) { rc = 1; goto exit; } /* Assemble source header from parsed components */ xx = initSourceHeader(spec, NULL); /* Check build prerequisites */ if (!ba->noDeps && checkSpec(ts, spec->sourceHeader)) { rc = 1; goto exit; } if (buildSpec(ts, spec, buildAmount, ba->noBuild)) { rc = 1; goto exit; } if (ba->buildMode == 't') (void) Unlink(specURL); rc = 0; exit: spec = freeSpec(spec); specURL = _free(specURL); return rc; }
void ProcessInit() { // Initialize compiler state VM::compile_file(0, 0, MD5(), 0); // Install VM's ClassInfoHook ClassInfo::SetHook(&vm_class_info_hook); // ensure that nextTx64 and tx64 are set (void)VM::Transl::Translator::Get(); Transl::TargetCache::requestInit(); Unit* nativeFuncUnit = build_native_func_unit(hhbc_ext_funcs, hhbc_ext_funcs_count); SystemLib::s_nativeFuncUnit = nativeFuncUnit; // Search for systemlib.php in the following places: // 1) ${HHVM_LIB_PATH}/systemlib.php // 2) <dirname(realpath(hhvm))>/systemlib.php (requires proc filesystem) // 3) ${HPHP_LIB}/systemlib.php // 4) <HHVM_LIB_PATH_DEFAULT>/systemlib.php // // HHVM_LIB_PATH allows a manual override at runtime. If systemlib.php // exists next to the hhvm binary, that is likely to be the next best // version to use. The realpath()-based lookup will succeed as long as the // proc filesystem exists (e.g. on Linux and some FreeBSD configurations) // and no hard links are in use for the executable. Under certain build // situations, systemlib.php will not be generated next to hhvm binary, so // ${HPHP_LIB} is checked next. Failing all of those options, the // HHVM_LIB_PATH_DEFAULT-based lookup will always succeed, assuming that the // application was built and installed correctly. String currentDir = g_vmContext->getCwd(); HPHP::Eval::PhpFile* file = NULL; #define SYSTEMLIB_PHP "/systemlib.php" #define LOOKUP_STR(s) do { \ String systemlibPath = String(s) + SYSTEMLIB_PHP; \ file = g_vmContext->lookupPhpFile(systemlibPath.get(), currentDir.data(), \ NULL); \ } while (0) #define LOOKUP_ENV(v) do { \ if (!file) { \ const char* s = getenv(#v); \ if (s && *s) { \ LOOKUP_STR(s); \ } \ } \ } while (0) #define LOOKUP_CPP(v) do { \ if (!file) { \ LOOKUP_STR(v); \ } \ } while (0) LOOKUP_ENV(HHVM_LIB_PATH); if (!file) { char hhvm_exe[PATH_MAX+1]; char hhvm_path[PATH_MAX+1]; ssize_t len = readlink("/proc/self/exe", hhvm_exe, sizeof(hhvm_exe)); if (len >= 0) { hhvm_exe[len] = '\0'; if (realpath(hhvm_exe, hhvm_path) != NULL) { char *hphp_lib = dirname(hhvm_path); LOOKUP_STR(hphp_lib); } } } LOOKUP_ENV(HPHP_LIB); #ifdef HHVM_LIB_PATH_DEFAULT LOOKUP_CPP(HHVM_LIB_PATH_DEFAULT); #endif if (!file) { // Die a horrible death. Logger::Error("Unable to find/load systemlib.php"); _exit(1); } #undef SYSTEMLIB_PHP #undef LOOKUP_STR #undef LOOKUP_ENV #undef LOOKUP_CPP SystemLib::s_phpFile = file; file->incRef(); SystemLib::s_unit = file->unit(); // Load the systemlib unit to build the Class objects SystemLib::s_unit->merge(); // load builtins SystemLib::s_nativeFuncUnit->merge(); #define INIT_SYSTEMLIB_CLASS_FIELD(cls) \ { \ Class *cls = *Unit::GetNamedEntity(s_##cls.get())->clsList(); \ ASSERT(cls); \ SystemLib::s_##cls##Class = cls; \ } // Stash a pointer to the VM Classes for stdclass, Exception, // pinitSentinel and resource INIT_SYSTEMLIB_CLASS_FIELD(stdclass); INIT_SYSTEMLIB_CLASS_FIELD(Exception); INIT_SYSTEMLIB_CLASS_FIELD(BadMethodCallException); INIT_SYSTEMLIB_CLASS_FIELD(InvalidArgumentException); INIT_SYSTEMLIB_CLASS_FIELD(RuntimeException); INIT_SYSTEMLIB_CLASS_FIELD(OutOfBoundsException); INIT_SYSTEMLIB_CLASS_FIELD(InvalidOperationException); INIT_SYSTEMLIB_CLASS_FIELD(Directory); INIT_SYSTEMLIB_CLASS_FIELD(RecursiveDirectoryIterator); INIT_SYSTEMLIB_CLASS_FIELD(SplFileInfo); INIT_SYSTEMLIB_CLASS_FIELD(SplFileObject); INIT_SYSTEMLIB_CLASS_FIELD(pinitSentinel); INIT_SYSTEMLIB_CLASS_FIELD(resource); INIT_SYSTEMLIB_CLASS_FIELD(DOMException); INIT_SYSTEMLIB_CLASS_FIELD(PDOException); INIT_SYSTEMLIB_CLASS_FIELD(SoapFault); #undef INIT_SYSTEMLIB_CLASS_FIELD // We call a special bytecode emitter function to build the native // unit which will contain all of our cppext functions and classes. // Each function and method will have a bytecode body that will thunk // to the native implementation. Unit* nativeClassUnit = build_native_class_unit(hhbc_ext_classes, hhbc_ext_class_count); SystemLib::s_nativeClassUnit = nativeClassUnit; // Load the nativelib unit to build the Class objects SystemLib::s_nativeClassUnit->merge(); // Retrieve all of the class pointers for (long long i = 0LL; i < hhbc_ext_class_count; ++i) { const HhbcExtClassInfo* info = hhbc_ext_classes + i; const StringData* name = StringData::GetStaticString(info->m_name); const NamedEntity* ne = Unit::GetNamedEntity(name); Class* cls = Unit::lookupClass(ne); ASSERT(cls); const ObjectStaticCallbacks* osc = get_object_static_callbacks(info->m_name); ASSERT(osc != NULL); *(osc->os_cls_ptr) = cls; } Stack::ValidateStackSize(); SystemLib::s_inited = true; // For debug build, run some quick unit tests at process start time if (debug) { VM::Transl::FixupMapUnitTest _; } }
HRESULT CoreClrEmbedding::Initialize(BOOL debugMode) { // Much of the CoreCLR bootstrapping process is cribbed from // https://github.com/aspnet/dnx/blob/dev/src/dnx.coreclr.unix/dnx.coreclr.cpp DBG("CoreClrEmbedding::Initialize - Started") HRESULT result = S_OK; char currentDirectory[PATH_MAX]; #ifdef EDGE_PLATFORM_WINDOWS if (!_getcwd(¤tDirectory[0], PATH_MAX)) #else if (!getcwd(¤tDirectory[0], PATH_MAX)) #endif { throwV8Exception("Unable to get the current directory."); return E_FAIL; } char edgeNodePath[PATH_MAX]; #ifdef EDGE_PLATFORM_WINDOWS HMODULE moduleHandle = NULL; GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR) &CoreClrEmbedding::Initialize, &moduleHandle); GetModuleFileName(moduleHandle, edgeNodePath, PATH_MAX); PathRemoveFileSpec(edgeNodePath); #else Dl_info dlInfo; dladdr((void*)&CoreClrEmbedding::Initialize, &dlInfo); strcpy(edgeNodePath, dlInfo.dli_fname); strcpy(edgeNodePath, dirname(edgeNodePath)); #endif DBG("CoreClrEmbedding::Initialize - edge.node path is %s", edgeNodePath); void* libCoreClr = NULL; char bootstrapper[PATH_MAX]; GetPathToBootstrapper(&bootstrapper[0], PATH_MAX); DBG("CoreClrEmbedding::Initialize - Bootstrapper is %s", bootstrapper); char coreClrDirectory[PATH_MAX]; char* coreClrEnvironmentVariable = getenv("CORECLR_DIR"); if (coreClrEnvironmentVariable) { if (coreClrEnvironmentVariable[0] == '"') { strncpy(&coreClrDirectory[0], &coreClrEnvironmentVariable[1], strlen(coreClrEnvironmentVariable) - 2); coreClrDirectory[strlen(coreClrEnvironmentVariable) - 2] = '\0'; } else { strncpy(&coreClrDirectory[0], coreClrEnvironmentVariable, strlen(coreClrEnvironmentVariable) + 1); } DBG("CoreClrEmbedding::Initialize - Trying to load %s from the path specified in the CORECLR_DIR environment variable: %s", LIBCORECLR_NAME, coreClrDirectory); LoadCoreClrAtPath(coreClrDirectory, &libCoreClr); } if (!libCoreClr) { strncpy(&coreClrDirectory[0], currentDirectory, strlen(currentDirectory) + 1); LoadCoreClrAtPath(coreClrDirectory, &libCoreClr); } if (!libCoreClr) { // Try to load CoreCLR from application path #ifdef EDGE_PLATFORM_WINDOWS char* lastSlash = strrchr(&bootstrapper[0], '\\'); #else char* lastSlash = strrchr(&bootstrapper[0], '/'); #endif assert(lastSlash); strncpy(&coreClrDirectory[0], &bootstrapper[0], lastSlash - &bootstrapper[0]); coreClrDirectory[lastSlash - &bootstrapper[0]] = '\0'; LoadCoreClrAtPath(coreClrDirectory, &libCoreClr); } if (!libCoreClr) { std::string pathEnvironmentVariable = getenv("PATH"); #if EDGE_PLATFORM_WINDOWS char delimeter = ';'; #else char delimeter = ':'; #endif size_t previousIndex = 0; size_t currentIndex = pathEnvironmentVariable.find(delimeter); while (!libCoreClr && currentIndex != std::string::npos) { strncpy(&coreClrDirectory[0], pathEnvironmentVariable.substr(previousIndex, currentIndex - previousIndex).c_str(), currentIndex - previousIndex); coreClrDirectory[currentIndex - previousIndex] = '\0'; LoadCoreClrAtPath(coreClrDirectory, &libCoreClr); if (!libCoreClr) { previousIndex = currentIndex + 1; currentIndex = pathEnvironmentVariable.find(delimeter, previousIndex); } } } if (!libCoreClr) { throwV8Exception("Failed to find CoreCLR. Make sure that you have either specified the CoreCLR directory in the CORECLR_DIR environment variable or it exists somewhere in your PATH environment variable, which you do via the \"dnvm install\" and \"dnvm use\" commands."); return E_FAIL; } DBG("CoreClrEmbedding::Initialize - %s loaded successfully from %s", LIBCORECLR_NAME, &coreClrDirectory[0]); std::string assemblySearchDirectories; assemblySearchDirectories.append(¤tDirectory[0]); assemblySearchDirectories.append(":"); assemblySearchDirectories.append(&coreClrDirectory[0]); DBG("CoreClrEmbedding::Initialize - Assembly search path is %s", assemblySearchDirectories.c_str()); coreclr_initializeFunction initializeCoreCLR = (coreclr_initializeFunction) LoadSymbol(libCoreClr, "coreclr_initialize"); if (!initializeCoreCLR) { throwV8Exception("Error loading the coreclr_initialize function from %s: %s.", LIBCORECLR_NAME, GetLoadError()); return E_FAIL; } DBG("CoreClrEmbedding::Initialize - coreclr_initialize loaded successfully"); coreclr_create_delegateFunction createDelegate = (coreclr_create_delegateFunction) LoadSymbol(libCoreClr, "coreclr_create_delegate"); if (!createDelegate) { throwV8Exception("Error loading the coreclr_create_delegate function from %s: %s.", LIBCORECLR_NAME, GetLoadError()); return E_FAIL; } DBG("CoreClrEmbedding::Initialize - coreclr_create_delegate loaded successfully"); const char* propertyKeys[] = { "TRUSTED_PLATFORM_ASSEMBLIES", "APP_PATHS", "APP_NI_PATHS", "NATIVE_DLL_SEARCH_DIRECTORIES", "AppDomainCompatSwitch" }; std::string tpaList; AddToTpaList(coreClrDirectory, &tpaList); std::string appPaths(¤tDirectory[0]); #if EDGE_PLATFORM_WINDOWS appPaths.append(";"); #else appPaths.append(":"); #endif appPaths.append(edgeNodePath); DBG("CoreClrEmbedding::Initialize - Using %s as the app path value", appPaths.c_str()); const char* propertyValues[] = { tpaList.c_str(), appPaths.c_str(), appPaths.c_str(), assemblySearchDirectories.c_str(), "UseLatestBehaviorWhenTFMNotSpecified" }; DBG("CoreClrEmbedding::Initialize - Calling coreclr_initialize()"); result = initializeCoreCLR( bootstrapper, "Edge", sizeof(propertyKeys) / sizeof(propertyKeys[0]), &propertyKeys[0], &propertyValues[0], &hostHandle, &appDomainId); if (FAILED(result)) { throwV8Exception("Call to coreclr_initialize() failed with a return code of 0x%x.", result); return result; } DBG("CoreClrEmbedding::Initialize - CoreCLR initialized successfully"); DBG("CoreClrEmbedding::Initialize - App domain created successfully (app domain ID: %d)", appDomainId); SetCallV8FunctionDelegateFunction setCallV8Function; CREATE_DELEGATE("GetFunc", &getFunc); CREATE_DELEGATE("CallFunc", &callFunc); CREATE_DELEGATE("ContinueTask", &continueTask); CREATE_DELEGATE("FreeHandle", &freeHandle); CREATE_DELEGATE("FreeMarshalData", &freeMarshalData); CREATE_DELEGATE("SetCallV8FunctionDelegate", &setCallV8Function); CREATE_DELEGATE("CompileFunc", &compileFunc); CREATE_DELEGATE("Initialize", &initialize); DBG("CoreClrEmbedding::Initialize - Getting runtime info"); CoreClrGcHandle exception = NULL; BootstrapperContext context; context.runtimeDirectory = &coreClrDirectory[0]; context.applicationDirectory = getenv("EDGE_APP_ROOT"); context.edgeNodePath = &edgeNodePath[0]; if (!context.applicationDirectory) { context.applicationDirectory = ¤tDirectory[0]; } std::string operatingSystem = GetOSName(); std::string operatingSystemVersion = GetOSVersion(); context.architecture = GetOSArchitecture(); context.operatingSystem = operatingSystem.c_str(); context.operatingSystemVersion = operatingSystemVersion.c_str(); DBG("CoreClrEmbedding::Initialize - Operating system: %s", context.operatingSystem); DBG("CoreClrEmbedding::Initialize - Operating system version: %s", context.operatingSystemVersion); DBG("CoreClrEmbedding::Initialize - Architecture: %s", context.architecture); DBG("CoreClrEmbedding::Initialize - Runtime directory: %s", context.runtimeDirectory); DBG("CoreClrEmbedding::Initialize - Application directory: %s", context.applicationDirectory); DBG("CoreClrEmbedding::Initialize - Calling CLR Initialize() function"); initialize(&context, &exception); if (exception) { v8::Local<v8::Value> v8Exception = CoreClrFunc::MarshalCLRToV8(exception, V8TypeException); FreeMarshalData(exception, V8TypeException); throwV8Exception(v8Exception); } else { DBG("CoreClrEmbedding::Initialize - CLR Initialize() function called successfully") } exception = NULL; setCallV8Function(CoreClrNodejsFunc::Call, &exception); if (exception) { v8::Local<v8::Value> v8Exception = CoreClrFunc::MarshalCLRToV8(exception, V8TypeException); FreeMarshalData(exception, V8TypeException); throwV8Exception(v8Exception); } else { DBG("CoreClrEmbedding::Initialize - CallV8Function delegate set successfully"); } DBG("CoreClrEmbedding::Initialize - Completed"); return S_OK; }
int main(int argc, char **argv) { int c; char *lfname = NULL; char *cfname = NULL; char *wfname = NULL; DIR *dir; init_charmap(); init_collate(); init_ctype(); init_messages(); init_monetary(); init_numeric(); init_time(); yydebug = 0; (void) setlocale(LC_ALL, ""); while ((c = getopt(argc, argv, "w:i:cf:u:vUD")) != -1) { switch (c) { case 'D': bsd = 1; break; case 'v': verbose++; break; case 'i': lfname = optarg; break; case 'u': set_wide_encoding(optarg); break; case 'f': cfname = optarg; break; case 'U': undefok++; break; case 'c': warnok++; break; case 'w': wfname = optarg; break; case '?': usage(); break; } } if ((argc - 1) != (optind)) { usage(); } locname = argv[argc - 1]; if (verbose) { (void) printf("Processing locale %s.\n", locname); } if (cfname) { if (verbose) (void) printf("Loading charmap %s.\n", cfname); reset_scanner(cfname); (void) yyparse(); } if (wfname) { if (verbose) (void) printf("Loading widths %s.\n", wfname); reset_scanner(wfname); (void) yyparse(); } if (verbose) { (void) printf("Loading POSIX portable characters.\n"); } add_charmap_posix(); if (lfname) { reset_scanner(lfname); } else { reset_scanner(NULL); } /* make the directory for the locale if not already present */ if (!bsd) { while ((dir = opendir(locname)) == NULL) { if ((errno != ENOENT) || (mkdir(locname, 0755) < 0)) { errf(strerror(errno)); } } (void) closedir(dir); (void) mkdir(dirname(category_file()), 0755); } (void) yyparse(); if (verbose) { (void) printf("All done.\n"); } return (warnings ? 1 : 0); }
int load_config(const char *file) { char *description = NULL, *server_host = NULL, *username = NULL, *password = NULL, *nickname = NULL, *user_complete_name = NULL; int server_index = -1; int linenr = 0; int fd = open(file, O_RDONLY); if (fd == -1) { if (errno == ENOENT) return -1; error_exit(TRUE, "Cannot open config file %s\n", file); } conf_file = strdup(file); for(;;) { char *line = read_line_fd(fd); char *cmd, *par; char *is; if (!line) break; linenr++; if (strlen(line) == 0) { myfree(line); continue; } if (line[0] == '#' || line[0] == ';') { myfree(line); continue; } is = strchr(line, '='); if (!is) error_exit(FALSE, "config: line %d is missing either command or parameter! (%s)", linenr, line); /* find parameter */ par = is + 1; while(*par == ' ') par++; /* remove spaces around command */ /* spaces at the start */ cmd = line; while(*cmd == ' ') cmd++; /* spaces at the end */ *is = 0x00; is--; while(*is == ' ') { *is = 0x00; is--; } if (strcmp(cmd, "server") == 0 || strcmp(cmd, "send_after_login") == 0 || strcmp(cmd, "auto_join") == 0 || strcmp(cmd, "channel") == 0 || strcmp(cmd, "rejoin") == 0) { /* all stuff already known? */ if (server_host) { if (nickname == NULL) error_exit(FALSE, "nickname must be set for %s", server_host); server_index = add_server(server_host, username, password, nickname, user_complete_name, description ? description : server_host); myfree(server_host); server_host = NULL; myfree(username); myfree(password); myfree(nickname); myfree(user_complete_name); myfree(description); username = password = nickname = user_complete_name = description = NULL; } } if (strcmp(cmd, "server") == 0) { /* new server */ server_host = strdup(par); } else if (strcmp(cmd, "favorite") == 0) { int n = -1; string_array_t parts; init_string_array(&parts); split_string(par, " ", TRUE, &parts); n = string_array_get_n(&parts); if (n != 1 && n != 2) error_exit(FALSE, "favorite needs either be in format \"server channel\" or \"channel\""); if (n == 2) add_favorite(string_array_get(&parts, 0), string_array_get(&parts, 1)); else add_favorite(NULL, string_array_get(&parts, 0)); free_splitted_string(&parts); } else if (strcmp(cmd, "username") == 0) username = strdup(par); else if (strcmp(cmd, "password") == 0) password = strdup(par); else if (strcmp(cmd, "nick") == 0 || strcmp(cmd, "nickname") == 0) nickname = strdup(par); else if (strcmp(cmd, "name") == 0) user_complete_name = strdup(par); else if (strcmp(cmd, "dictionary_file") == 0) { const char *filename = explode_path(par); if (!filename) error_exit(TRUE, "Path '%s' is not understood\n", par); dictionary_file = filename; if (load_dictionary() == FALSE) error_exit(TRUE, "Failure loading dictionary file %s (%s)", filename, par); } else if (strcmp(cmd, "description") == 0) description = strdup(par); else if (strcmp(cmd, "server_exit_message") == 0) server_exit_message = strdup(par); else if (strcmp(cmd, "log_dir") == 0) log_dir = strdup(par); else if (strcmp(cmd, "part_message") == 0) part_message = strdup(par); else if (strcmp(cmd, "notify_nick") == 0) notify_nick = strdup(par); else if (strcmp(cmd, "userinfo") == 0) userinfo = strdup(par); else if (strcmp(cmd, "finger_str") == 0) finger_str = strdup(par); else if (strcmp(cmd, "mark_personal_messages") == 0) mark_personal_messages = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "meta-colors") == 0) colors_meta = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "headline_matcher") == 0) add_headline_matcher(par); else if (strcmp(cmd, "all-colors") == 0) colors_all = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "dcc_bind_to") == 0) dcc_bind_to = strdup(par); else if (strcmp(cmd, "update_clock_at_data") == 0) update_clock_at_data = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "nick-color") == 0) nick_color = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "use_nonbasic_colors") == 0) use_nonbasic_colors = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "ignore_unknown_irc_protocol_msgs") == 0) ignore_unknown_irc_protocol_msgs = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "auto_markerline") == 0) auto_markerline = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "inverse_window_heading") == 0) inverse_window_heading = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "keep_channels_sorted") == 0) keep_channels_sorted = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "allow_invite") == 0) allow_invite = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "show_headlines") == 0) show_headlines = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "remember_channels") == 0) remember_channels = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "allow_userinfo") == 0) allow_userinfo = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "extra_highlights") == 0) add_to_string_array(&extra_highlights, par); else if (strcmp(cmd, "only_one_markerline") == 0) only_one_markerline = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "auto_rejoin") == 0) auto_rejoin = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "ignore_mouse") == 0) ignore_mouse = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "irc_keepalive") == 0) irc_keepalive = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "space_after_start_marker") == 0) space_after_start_marker = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "jumpy_navigation") == 0) jumpy_navigation = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "mark_meta") == 0) mark_meta = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "user_column") == 0) user_column = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "full_user") == 0) full_user = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "grep_filter") == 0) add_filter(gp, par, linenr); else if (strcmp(cmd, "headline_filter") == 0) add_filter(hlgp, par, linenr); else if (strcmp(cmd, "show_parts") == 0) show_parts = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "show_mode_changes") == 0) show_mode_changes = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "show_nick_change") == 0) show_nick_change = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "show_joins") == 0) show_joins = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "store_config_on_exit") == 0) store_config_on_exit = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "partial_highlight_match") == 0) partial_highlight_match = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "topic_scroll") == 0) topic_scroll = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "notice_in_serverchannel") == 0) notice_in_server_channel = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "highlight") == 0) highlight = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "fuzzy_highlight") == 0) fuzzy_highlight = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "theme") == 0) { struct stat status; const char *filename = explode_path(par); if (!filename) error_exit(TRUE, "Path '%s' is not understood\n", par); if (stat(filename, &status) == -1) /* file doesn't exist, look for it under SYSCONFDIR */ { int len = strlen(SYSCONFDIR) + strlen(par) + 2; char *theme_path = malloc(len * sizeof(char)); snprintf(theme_path, len, "%s/%s", SYSCONFDIR, par); load_theme(theme_path); theme_file = theme_path; } else { load_theme(filename); theme_file = strdup(par); } myfree(filename); } else if (strcmp(cmd, "ignore_file") == 0) { struct stat status; const char *filename = explode_path(par); if (!filename) error_exit(TRUE, "Path '%s' is not understood\n", par); if (load_ignore_list(par) == TRUE) { } else if (load_ignore_list(filename) == TRUE) { } else if (stat(filename, &status) == -1) /* file doesn't exist, look elsewhere */ { int len = strlen(SYSCONFDIR) + strlen(par) + 2; char *ignore_file = malloc(len * sizeof(char)); /* look for it under SYSCONFDIR */ snprintf(ignore_file, len, "%s/%s", SYSCONFDIR, par); /* look for it under ~/.firc location */ if (stat(ignore_file, &status) == -1) snprintf(ignore_file, len, "%s/%s", dirname(conf_file), par); load_ignore_list(ignore_file); myfree(ignore_file); } myfree(filename); } else if (strcmp(cmd, "send_after_login") == 0) { server *ps = &server_list[server_index]; if (server_index == -1) error_exit(FALSE, "send_after_login: you need to define a server first\n"); add_to_string_array(&ps -> send_after_login, par); } else if (strcmp(cmd, "auto_join") == 0 || strcmp(cmd, "channel") == 0) { if (server_index == -1) error_exit(FALSE, "auto_join: you need to define a server first\n"); add_autojoin(server_index, par); } else if (strcmp(cmd, "rejoin") == 0) { add_channel(server_index, par); if (keep_channels_sorted) sort_channels(server_index); } else if (strcmp(cmd, "auto_private_channel") == 0) auto_private_channel = parse_false_true(par, cmd, linenr); else if (strcmp(cmd, "dcc_path") == 0) dcc_path = strdup(par); else if (strcmp(cmd, "default_colorpair") == 0) default_colorpair = parse_color_spec(par, linenr, cmd); else if (strcmp(cmd, "markerline_colorpair") == 0) markerline_colorpair = parse_color_spec(par, linenr, cmd); else if (strcmp(cmd, "highlight_colorpair") == 0) highlight_colorpair = parse_color_spec(par, linenr, cmd); else if (strcmp(cmd, "meta_colorpair") == 0) meta_colorpair = parse_color_spec(par, linenr, cmd); else if (strcmp(cmd, "error_colorpair") == 0) error_colorpair = parse_color_spec(par, linenr, cmd); else if (strcmp(cmd, "temp_colorpair") == 0) temp_colorpair = parse_color_spec(par, linenr, cmd); else if (strcmp(cmd, "check_for_mail") == 0) check_for_mail = atoi(par); else if (strcmp(cmd, "user_column_width") == 0) user_column_width = atoi(par); else if (strcmp(cmd, "delay_before_reconnect") == 0) delay_before_reconnect = atoi(par); else if (strcmp(cmd, "word_cloud_n") == 0) word_cloud_n = atoi(par); else if (strcmp(cmd, "word_cloud_refresh") == 0) { word_cloud_refresh = atoi(par); word_cloud_last_refresh = time(NULL); } else if (strcmp(cmd, "word_cloud_win_height") == 0) word_cloud_win_height = atoi(par); else if (strcmp(cmd, "max_channel_record_lines") == 0) max_channel_record_lines = atoi(par); else if (strcmp(cmd, "word_cloud_min_word_size") == 0) word_cloud_min_word_size = atoi(par); else { error_exit(FALSE, "'%s=%s' is not understood\n", cmd, par); } myfree(line); } close(fd); if (server_host) { if (nickname == NULL) error_exit(FALSE, "nickname must be set for %s", server_host); add_server(server_host, username, password, nickname, user_complete_name, description); myfree(server_host); myfree(username); myfree(password); myfree(nickname); myfree(user_complete_name); myfree(description); } return 0; }
int copyFile(char *source_file, char *new_file){ int sFile_fd, nDir_fd, nFile_fd; char buffer[BUFFER_SIZE]; int num_read; long totalSize = 0; // Hedef konum bilgisi parse edilerek dosya adi bilgisi alinir. char *filename = basename(new_file); // Hedef konum bilgisi parse edilerek path bilgisi alinir. char *directory = dirname(new_file); // Kaynak dosya acilir. Dosyanin acilmasi sirasinda bir hata olusursa // ilgili hata bilgisi ekrana yazdirilir. sFile_fd = open(source_file, O_RDONLY, 0); if (sFile_fd == -1) { perror("Error opening source file"); exit(1); } // Kopyalama isleminin, verilen klasor yapisina uygun hale getirilmesi // icin bu fonksiyon cagrilarak eksik klasorler olusturulur. checkFolderStructure(directory, &nDir_fd); // Arguman olarak verilmis olan newPath degiskenin icerigi basename/dirname // fonksiyonlari tarafindan degistirildigi icin burada kucuk bir concat // islemi yapilir. sprintf(new_file, "%s/%s", newPath, filename); // Yeni dosya, ilgili dosya adiyla, yazilmak uzere acilir/olusturulur. // Dosyanin acilmasi sirasinda bir hata olusursa // ilgili hata bilgisi ekrana yazdirilir. nFile_fd = open(new_file, O_WRONLY | O_EXCL | O_CREAT, 0644); if (nFile_fd == -1) { perror("Error opening new file"); if (errno == EISDIR) printf("Hedef dosyayi [/dosya] seklinde, basinda / isaretiyle girmeniz geriyor olabilir.\n"); exit(1); } // Kaynak dosyadan, buffer boyutu kadar byte okunur. Eger okuma // sonucunda 0 dan farkli sayida byte okunmus ise islem basarilidir, // donguye tekrar girilir. Okunan bytelar, yeni dosyaya yazilir ve // yazilan toplam byte sayisinin tutuldugu totalSize degiskeninin // icerigi guncellenir. while ((num_read = read(sFile_fd, &buffer, BUFFER_SIZE)) > 0) { write(nFile_fd, &buffer, num_read); totalSize = totalSize + num_read; } // Kopyalanan toplam byte bilgisi ekrana yazdirilir. printf("\nToplam %ld byte kopyalandi.\n\n", totalSize); // Tum file handler'lar kapatilir. // Source file descriptor, New directory file descriptor ve New file file descriptor close(sFile_fd); close(nDir_fd); close(nFile_fd); }
int lp_loadparams(void *it, struct lp_block *b, struct lp_mod *m) { int c; int needed = 0; int param_stack[LP_STACK_MAX]; int stack_ptr = 0; // index of first free slot // XXX not static size char *paramvec = calloc(m->modvars_len, sizeof(char)); // This is pretty gross; there should be a better solution. // dirname() munges its operand. Its result may also be a static // buffer somewhere, hence the 2 copies. char *tmp = strdup(b->source_file); lp_cwd = strdup(dirname(tmp)); // free(tmp); for(c = 0; c < b->params_len; c++) { int pnum, deps; if(!b->params[c]) continue; TOP: pnum = lp_param_name(lp_mod_name(m->name), b->params[c]->name); // Don't initialize things more than once. // Should warn here, probably. if(BIT_TEST(paramvec, pnum)) continue; if(stack_ptr > 0) { for(c = 0; c < b->params_len; c++) { if(lp_param_name(lp_mod_name(m->name), b->params[c]->name) == needed) goto FOUND; } break; } FOUND: deps = m->param_deps[pnum](paramvec); if(deps > -1) { ddbg_assert(stack_ptr < LP_STACK_MAX); param_stack[stack_ptr++] = c; needed = deps; continue; } else { switch(PTYPE(b->params[c])) { case I: ((lp_paramloader_int)m->param_loaders[pnum])(it, IVAL(b->params[c])); break; case D: ((lp_paramloader_double)m->param_loaders[pnum])(it, DVAL(b->params[c])); break; case S: ((lp_paramloader_string)m->param_loaders[pnum])(it, SVAL(b->params[c])); break; case LIST: ((lp_paramloader_list)m->param_loaders[pnum])(it, LVAL(b->params[c])); break; case BLOCK: default: ((lp_paramloader_block)m->param_loaders[pnum])(it, BVAL(b->params[c])); break; } } BIT_SET(paramvec, pnum); if(stack_ptr > 0) { c = param_stack[--stack_ptr]; goto TOP; } } for(c = 0; c < m->modvars_len; c++) { if(m->modvars[c].req && !BIT_TEST(paramvec,c)) { fprintf(stderr, "*** error: in %s spec -- missing required parameter %s\n", m->name, m->modvars[c].name); break; } } free(paramvec); return 0; // ??? }