/* * Process /proc/self/cgroup figuring out what cgroup * sub-path the current process is assigned to. ie not * neccessarily in the root */ static int virCgroupDetectPlacement(virCgroupPtr group) { int i; FILE *mapping = NULL; char line[1024]; mapping = fopen("/proc/self/cgroup", "r"); if (mapping == NULL) { VIR_ERROR(_("Unable to open /proc/self/cgroup")); return -ENOENT; } while (fgets(line, sizeof(line), mapping) != NULL) { char *controllers = strchr(line, ':'); char *path = controllers ? strchr(controllers+1, ':') : NULL; char *nl = path ? strchr(path, '\n') : NULL; if (!controllers || !path) continue; if (nl) *nl = '\0'; *path = '\0'; controllers++; path++; for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) { const char *typestr = virCgroupControllerTypeToString(i); int typelen = strlen(typestr); char *tmp = controllers; while (tmp) { char *next = strchr(tmp, ','); int len; if (next) { len = next-tmp; next++; } else { len = strlen(tmp); } if (typelen == len && STREQLEN(typestr, tmp, len) && !(group->controllers[i].placement = strdup(STREQ(path, "/") ? "" : path))) goto no_memory; tmp = next; } } } VIR_FORCE_FCLOSE(mapping); return 0; no_memory: VIR_FORCE_FCLOSE(mapping); return -ENOMEM; }
/* Allocate BUF to the size of FILE. Read FILE into buffer BUF. Upon any failure, diagnose it and return -1, but don't bother trying to preserve errno. Otherwise, return the number of bytes copied into BUF. */ int virtTestLoadFile(const char *file, char **buf) { FILE *fp = fopen(file, "r"); struct stat st; char *tmp; int len, tmplen, buflen; if (!fp) { fprintf(stderr, "%s: failed to open: %s\n", file, strerror(errno)); return -1; } if (fstat(fileno(fp), &st) < 0) { fprintf(stderr, "%s: failed to fstat: %s\n", file, strerror(errno)); VIR_FORCE_FCLOSE(fp); return -1; } tmplen = buflen = st.st_size + 1; if (VIR_ALLOC_N(*buf, buflen) < 0) { fprintf(stderr, "%s: larger than available memory (> %d)\n", file, buflen); VIR_FORCE_FCLOSE(fp); return -1; } tmp = *buf; (*buf)[0] = '\0'; if (st.st_size) { /* read the file line by line */ while (fgets(tmp, tmplen, fp) != NULL) { len = strlen(tmp); /* stop on an empty line */ if (len == 0) break; /* remove trailing backslash-newline pair */ if (len >= 2 && tmp[len-2] == '\\' && tmp[len-1] == '\n') { len -= 2; tmp[len] = '\0'; } /* advance the temporary buffer pointer */ tmp += len; tmplen -= len; } if (ferror(fp)) { fprintf(stderr, "%s: read failed: %s\n", file, strerror(errno)); VIR_FORCE_FCLOSE(fp); VIR_FREE(*buf); return -1; } } VIR_FORCE_FCLOSE(fp); return strlen(*buf); }
static int linuxTestCompareFiles(const char *cpuinfofile, char *sysfs_dir, virArch arch, const char *outputfile) { int ret = -1; char *actualData = NULL; char *expectData = NULL; virNodeInfo nodeinfo; FILE *cpuinfo; if (virtTestLoadFile(outputfile, &expectData) < 0) goto fail; cpuinfo = fopen(cpuinfofile, "r"); if (!cpuinfo) { fprintf(stderr, "unable to open: %s : %s\n", cpuinfofile, strerror(errno)); goto fail; } memset(&nodeinfo, 0, sizeof(nodeinfo)); if (linuxNodeInfoCPUPopulate(cpuinfo, sysfs_dir, arch, &nodeinfo) < 0) { if (virTestGetDebug()) { virErrorPtr error = virSaveLastError(); if (error && error->code != VIR_ERR_OK) fprintf(stderr, "\n%s\n", error->message); virFreeError(error); } VIR_FORCE_FCLOSE(cpuinfo); goto fail; } VIR_FORCE_FCLOSE(cpuinfo); if (virAsprintf(&actualData, "CPUs: %u/%u, MHz: %u, Nodes: %u, Sockets: %u, " "Cores: %u, Threads: %u\n", nodeinfo.cpus, VIR_NODEINFO_MAXCPUS(nodeinfo), nodeinfo.mhz, nodeinfo.nodes, nodeinfo.sockets, nodeinfo.cores, nodeinfo.threads) < 0) goto fail; if (STRNEQ(actualData, expectData)) { virtTestDifference(stderr, expectData, actualData); goto fail; } ret = 0; fail: VIR_FREE(expectData); VIR_FREE(actualData); return ret; }
static int testCompareFiles(virArch hostmachine, const char *xml_rel, const char *cpuinfo_rel, const char *capabilities_rel) { char *expectxml = NULL; char *actualxml = NULL; FILE *fp1 = NULL, *fp2 = NULL; virCapsPtr caps = NULL; int ret = -1; char *xml = NULL; char *cpuinfo = NULL; char *capabilities = NULL; if (virAsprintf(&xml, "%s/%s", abs_srcdir, xml_rel) < 0 || virAsprintf(&cpuinfo, "%s/%s", abs_srcdir, cpuinfo_rel) < 0 || virAsprintf(&capabilities, "%s/%s", abs_srcdir, capabilities_rel) < 0) goto fail; if (virtTestLoadFile(xml, &expectxml) < 0) goto fail; if (!(fp1 = fopen(cpuinfo, "r"))) goto fail; if (!(fp2 = fopen(capabilities, "r"))) goto fail; if (!(caps = xenHypervisorMakeCapabilitiesInternal(NULL, hostmachine, fp1, fp2))) goto fail; if (!(actualxml = virCapabilitiesFormatXML(caps))) goto fail; if (STRNEQ(expectxml, actualxml)) { virtTestDifference(stderr, expectxml, actualxml); goto fail; } ret = 0; fail: VIR_FREE(expectxml); VIR_FREE(actualxml); VIR_FREE(xml); VIR_FREE(cpuinfo); VIR_FREE(capabilities); VIR_FORCE_FCLOSE(fp1); VIR_FORCE_FCLOSE(fp2); virObjectUnref(caps); return ret; }
static int testCompareFiles(const char *hostmachine, const char *xml_rel, const char *cpuinfo_rel, const char *capabilities_rel) { char xmlData[MAX_FILE]; char *expectxml = &(xmlData[0]); char *actualxml = NULL; FILE *fp1 = NULL, *fp2 = NULL; virCapsPtr caps = NULL; int ret = -1; char xml[PATH_MAX]; char cpuinfo[PATH_MAX]; char capabilities[PATH_MAX]; snprintf(xml, sizeof xml - 1, "%s/%s", abs_srcdir, xml_rel); snprintf(cpuinfo, sizeof cpuinfo - 1, "%s/%s", abs_srcdir, cpuinfo_rel); snprintf(capabilities, sizeof capabilities - 1, "%s/%s", abs_srcdir, capabilities_rel); if (virtTestLoadFile(xml, &expectxml, MAX_FILE) < 0) goto fail; if (!(fp1 = fopen(cpuinfo, "r"))) goto fail; if (!(fp2 = fopen(capabilities, "r"))) goto fail; if (!(caps = xenHypervisorMakeCapabilitiesInternal(NULL, hostmachine, fp1, fp2))) goto fail; if (!(actualxml = virCapabilitiesFormatXML(caps))) goto fail; if (STRNEQ(expectxml, actualxml)) { virtTestDifference(stderr, expectxml, actualxml); goto fail; } ret = 0; fail: free(actualxml); VIR_FORCE_FCLOSE(fp1); VIR_FORCE_FCLOSE(fp2); virCapabilitiesFree(caps); return ret; }
/* * Process /proc/mounts figuring out what controllers are * mounted and where */ static int virCgroupDetectMounts(virCgroupPtr group) { int i; FILE *mounts = NULL; struct mntent entry; char buf[CGROUP_MAX_VAL]; mounts = fopen("/proc/mounts", "r"); if (mounts == NULL) { VIR_ERROR(_("Unable to open /proc/mounts")); return -ENOENT; } while (getmntent_r(mounts, &entry, buf, sizeof(buf)) != NULL) { if (STRNEQ(entry.mnt_type, "cgroup")) continue; for (i = 0 ; i < VIR_CGROUP_CONTROLLER_LAST ; i++) { const char *typestr = virCgroupControllerTypeToString(i); int typelen = strlen(typestr); char *tmp = entry.mnt_opts; while (tmp) { char *next = strchr(tmp, ','); int len; if (next) { len = next-tmp; next++; } else { len = strlen(tmp); } /* NB, the same controller can appear >1 time in mount list * due to bind mounts from one location to another. Pick the * first entry only */ if (typelen == len && STREQLEN(typestr, tmp, len) && !group->controllers[i].mountPoint && !(group->controllers[i].mountPoint = strdup(entry.mnt_dir))) goto no_memory; tmp = next; } } } VIR_FORCE_FCLOSE(mounts); return 0; no_memory: VIR_FORCE_FCLOSE(mounts); return -ENOMEM; }
static int virStorageBackendVzIsMounted(virStoragePoolObjPtr pool) { int ret = -1; virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool); FILE *mtab; struct mntent ent; char buf[1024]; VIR_AUTOFREE(char *) cluster = NULL; if (virAsprintf(&cluster, "vstorage://%s", def->source.name) < 0) return -1; if ((mtab = fopen(_PATH_MOUNTED, "r")) == NULL) { virReportSystemError(errno, _("cannot read mount list '%s'"), _PATH_MOUNTED); goto cleanup; } while ((getmntent_r(mtab, &ent, buf, sizeof(buf))) != NULL) { if (STREQ(ent.mnt_dir, def->target.path) && STREQ(ent.mnt_fsname, cluster)) { ret = 1; goto cleanup; } } ret = 0; cleanup: VIR_FORCE_FCLOSE(mtab); return ret; }
static int hostsfileWrite(const char *path, dnsmasqDhcpHost *hosts, unsigned int nhosts) { char *tmp; FILE *f; bool istmp = true; unsigned int i; int rc = 0; if (nhosts == 0) return rc; if (virAsprintf(&tmp, "%s.new", path) < 0) return ENOMEM; if (!(f = fopen(tmp, "w"))) { istmp = false; if (!(f = fopen(path, "w"))) { rc = errno; goto cleanup; } } for (i = 0; i < nhosts; i++) { if (fputs(hosts[i].host, f) == EOF || fputc('\n', f) == EOF) { rc = errno; VIR_FORCE_FCLOSE(f); if (istmp) unlink(tmp); goto cleanup; } } if (VIR_FCLOSE(f) == EOF) { rc = errno; goto cleanup; } if (istmp) { if (rename(tmp, path) < 0) { rc = errno; unlink(tmp); goto cleanup; } if (unlink(tmp) < 0) { rc = errno; goto cleanup; } } cleanup: VIR_FREE(tmp); return rc; }
static int openvzWriteConfigParam(const char * conf_file, const char *param, const char *value) { char * temp_file = NULL; int temp_fd = -1; FILE *fp; char *line = NULL; size_t line_size = 0; if (virAsprintf(&temp_file, "%s.tmp", conf_file)<0) { virReportOOMError(); return -1; } fp = fopen(conf_file, "r"); if (fp == NULL) goto error; temp_fd = open(temp_file, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (temp_fd == -1) { goto error; } while (1) { if (getline(&line, &line_size, fp) <= 0) break; if (!(STRPREFIX(line, param) && line[strlen(param)] == '=')) { if (safewrite(temp_fd, line, strlen(line)) != strlen(line)) goto error; } } if (safewrite(temp_fd, param, strlen(param)) < 0 || safewrite(temp_fd, "=\"", 2) < 0 || safewrite(temp_fd, value, strlen(value)) < 0 || safewrite(temp_fd, "\"\n", 2) < 0) goto error; if (VIR_FCLOSE(fp) < 0) goto error; if (VIR_CLOSE(temp_fd) < 0) goto error; if (rename(temp_file, conf_file) < 0) goto error; VIR_FREE(line); return 0; error: VIR_FREE(line); VIR_FORCE_FCLOSE(fp); VIR_FORCE_CLOSE(temp_fd); if (temp_file) unlink(temp_file); VIR_FREE(temp_file); return -1; }
int nodeGetInfo(virConnectPtr conn ATTRIBUTE_UNUSED, virNodeInfoPtr nodeinfo) { virArch hostarch = virArchFromHost(); if (virStrcpyStatic(nodeinfo->model, virArchToString(hostarch)) == NULL) return -1; #ifdef __linux__ { int ret = -1; FILE *cpuinfo = fopen(CPUINFO_PATH, "r"); if (!cpuinfo) { virReportSystemError(errno, _("cannot open %s"), CPUINFO_PATH); return -1; } ret = linuxNodeInfoCPUPopulate(cpuinfo, SYSFS_SYSTEM_PATH, nodeinfo); if (ret < 0) goto cleanup; /* Convert to KB. */ nodeinfo->memory = physmem_total() / 1024; cleanup: VIR_FORCE_FCLOSE(cpuinfo); return ret; } #else /* XXX Solaris will need an impl later if they port QEMU driver */ virReportError(VIR_ERR_NO_SUPPORT, "%s", _("node info not implemented on this platform")); return -1; #endif }
int nodeGetInfo(virConnectPtr conn ATTRIBUTE_UNUSED, virNodeInfoPtr nodeinfo) { struct utsname info; memset(nodeinfo, 0, sizeof(*nodeinfo)); uname(&info); if (virStrcpyStatic(nodeinfo->model, info.machine) == NULL) return -1; #ifdef __linux__ { int ret; FILE *cpuinfo = fopen(CPUINFO_PATH, "r"); if (!cpuinfo) { virReportSystemError(errno, _("cannot open %s"), CPUINFO_PATH); return -1; } ret = linuxNodeInfoCPUPopulate(cpuinfo, nodeinfo, true); VIR_FORCE_FCLOSE(cpuinfo); if (ret < 0) return -1; /* Convert to KB. */ nodeinfo->memory = physmem_total () / 1024; return ret; } #else /* XXX Solaris will need an impl later if they port QEMU driver */ nodeReportError(VIR_ERR_NO_SUPPORT, "%s", _("node info not implemented on this platform")); return -1; #endif }
/* Function to check if the type file in the given sysfs_path is a * Direct-Access device (i.e. type 0). Return -1 on failure, type of * the device otherwise. */ static int getDeviceType(uint32_t host, uint32_t bus, uint32_t target, uint32_t lun, int *type) { char *type_path = NULL; char typestr[3]; char *gottype, *p; FILE *typefile; int retval = 0; if (virAsprintf(&type_path, "/sys/bus/scsi/devices/%u:%u:%u:%u/type", host, bus, target, lun) < 0) { virReportOOMError(); goto out; } typefile = fopen(type_path, "r"); if (typefile == NULL) { virReportSystemError(errno, _("Could not find typefile '%s'"), type_path); /* there was no type file; that doesn't seem right */ retval = -1; goto out; } gottype = fgets(typestr, 3, typefile); VIR_FORCE_FCLOSE(typefile); if (gottype == NULL) { virReportSystemError(errno, _("Could not read typefile '%s'"), type_path); /* we couldn't read the type file; have to give up */ retval = -1; goto out; } /* we don't actually care about p, but if you pass NULL and the last * character is not \0, virStrToLong_i complains */ if (virStrToLong_i(typestr, &p, 10, type) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, _("Device type '%s' is not an integer"), typestr); /* Hm, type wasn't an integer; seems strange */ retval = -1; goto out; } VIR_DEBUG("Device type is %d", *type); out: VIR_FREE(type_path); return retval; }
static int hostsfileWrite(const char *path, dnsmasqDhcpHost *hosts, unsigned int nhosts) { char *tmp, *content = NULL; FILE *f; bool istmp = true; int rc = 0; /* even if there are 0 hosts, create a 0 length file, to allow * for runtime addition. */ if (virAsprintf(&tmp, "%s.new", path) < 0) return -ENOMEM; if (!(f = fopen(tmp, "w"))) { istmp = false; if (!(f = fopen(path, "w"))) { rc = -errno; goto cleanup; } } if (!(content = dnsmasqDhcpHostsToString(hosts, nhosts))) { rc = -ENOMEM; goto cleanup; } if (fputs(content, f) == EOF) { rc = -errno; VIR_FORCE_FCLOSE(f); if (istmp) unlink(tmp); goto cleanup; } if (VIR_FCLOSE(f) == EOF) { rc = -errno; goto cleanup; } if (istmp && rename(tmp, path) < 0) { rc = -errno; unlink(tmp); goto cleanup; } cleanup: VIR_FREE(content); VIR_FREE(tmp); return rc; }
static int linuxCPUStatsCompareFiles(const char *cpustatfile, size_t ncpus, const char *outfile) { int ret = -1; char *actualData = NULL; FILE *cpustat = NULL; virNodeCPUStatsPtr params = NULL; virBuffer buf = VIR_BUFFER_INITIALIZER; size_t i; int nparams = 0; if (!(cpustat = fopen(cpustatfile, "r"))) { virReportSystemError(errno, "failed to open '%s': ", cpustatfile); goto fail; } if (linuxNodeGetCPUStats(NULL, 0, NULL, &nparams) < 0) goto fail; if (VIR_ALLOC_N(params, nparams) < 0) goto fail; if (linuxNodeGetCPUStats(cpustat, VIR_NODE_CPU_STATS_ALL_CPUS, params, &nparams) < 0) goto fail; if (linuxCPUStatsToBuf(&buf, VIR_NODE_CPU_STATS_ALL_CPUS, params, nparams) < 0) goto fail; for (i = 0; i < ncpus; i++) { if (linuxNodeGetCPUStats(cpustat, i, params, &nparams) < 0) goto fail; if (linuxCPUStatsToBuf(&buf, i, params, nparams) < 0) goto fail; } if (!(actualData = virBufferContentAndReset(&buf))) { virReportOOMError(); goto fail; } if (virtTestCompareToFile(actualData, outfile) < 0) goto fail; ret = 0; fail: virBufferFreeAndReset(&buf); VIR_FORCE_FCLOSE(cpustat); VIR_FREE(actualData); VIR_FREE(params); return ret; }
static int openvz_copyfile(char* from_path, char* to_path) { char *line = NULL; size_t line_size = 0; FILE *fp; int copy_fd; int bytes_read; fp = fopen(from_path, "r"); if (fp == NULL) return -1; copy_fd = open(to_path, O_WRONLY | O_CREAT | O_TRUNC, 0644); if (copy_fd == -1) { VIR_FORCE_FCLOSE(fp); return -1; } while (1) { if (getline(&line, &line_size, fp) <= 0) break; bytes_read = strlen(line); if (safewrite(copy_fd, line, bytes_read) != bytes_read) goto error; } if (VIR_FCLOSE(fp) < 0) goto error; if (VIR_CLOSE(copy_fd) < 0) goto error; VIR_FREE(line); return 0; error: VIR_FREE(line); VIR_FORCE_FCLOSE(fp); VIR_FORCE_CLOSE(copy_fd); return -1; }
int vmwareExtractPid(const char * vmxPath) { char *vmxDir = NULL; char *logFilePath = NULL; FILE *logFile = NULL; char line[1024]; char *tmp = NULL; int pid_value = -1; if ((vmxDir = mdir_name(vmxPath)) == NULL) goto cleanup; if (virAsprintf(&logFilePath, "%s/vmware.log", vmxDir) < 0) { virReportOOMError(); goto cleanup; } if ((logFile = fopen(logFilePath, "r")) == NULL) goto cleanup; if (!fgets(line, sizeof(line), logFile)) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("unable to read vmware log file")); goto cleanup; } if ((tmp = strstr(line, " pid=")) == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("cannot find pid in vmware log file")); goto cleanup; } tmp += strlen(" pid="); /* Although 64-bit windows allows 64-bit pid_t, a domain id has to be * 32 bits. For now, we just reject pid values that overflow int. */ if (virStrToLong_i(tmp, &tmp, 10, &pid_value) < 0 || *tmp != ' ') { virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("cannot parse pid in vmware log file")); goto cleanup; } cleanup: VIR_FREE(vmxDir); VIR_FREE(logFilePath); VIR_FORCE_FCLOSE(logFile); return pid_value; }
/** * @conn connection to report errors against * @pool storage pool to check for status * * Determine if a storage pool is already mounted * * Return 0 if not mounted, 1 if mounted, -1 on error */ static int virStorageBackendFileSystemIsMounted(virStoragePoolObjPtr pool) { FILE *mtab; struct mntent ent; char buf[1024]; if ((mtab = fopen(_PATH_MOUNTED, "r")) == NULL) { virReportSystemError(errno, _("cannot read mount list '%s'"), _PATH_MOUNTED); return -1; } while ((getmntent_r(mtab, &ent, buf, sizeof(buf))) != NULL) { if (STREQ(ent.mnt_dir, pool->def->target.path)) { VIR_FORCE_FCLOSE(mtab); return 1; } } VIR_FORCE_FCLOSE(mtab); return 0; }
static int openvzGetProcessInfo(unsigned long long *cpuTime, int vpsid) { FILE *fp; char *line = NULL; size_t line_size = 0; unsigned long long usertime, systime, nicetime; int readvps = vpsid + 1; /* ensure readvps is initially different */ ssize_t ret; int err = 0; /* read statistic from /proc/vz/vestat. sample: Version: 2.2 VEID user nice system uptime idle other.. 33 78 0 1330 59454597 142650441835148 other.. 55 178 0 5340 59424597 542650441835148 other.. */ if ((fp = fopen("/proc/vz/vestat", "r")) == NULL) return -1; /*search line with VEID=vpsid*/ while (1) { ret = getline(&line, &line_size, fp); if (ret < 0) { err = !feof(fp); break; } if (sscanf (line, "%d %llu %llu %llu", &readvps, &usertime, &nicetime, &systime) == 4 && readvps == vpsid) { /*found vpsid*/ /* convert jiffies to nanoseconds */ *cpuTime = (1000ull * 1000ull * 1000ull * (usertime + nicetime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK)); break; } } VIR_FREE(line); VIR_FORCE_FCLOSE(fp); if (err) return -1; if (readvps != vpsid) /*not found*/ return -1; return 0; }
static int openvzGetVPSUUID(int vpsid, char *uuidstr, size_t len) { char *conf_file; char *line = NULL; size_t line_size = 0; char *saveptr = NULL; char *uuidbuf; char *iden; FILE *fp; int retval = -1; if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0) return -1; fp = fopen(conf_file, "r"); if (fp == NULL) goto cleanup; while (1) { if (getline(&line, &line_size, fp) < 0) { if (feof(fp)) { /* EOF, UUID was not found */ uuidstr[0] = 0; break; } else { goto cleanup; } } iden = strtok_r(line, " ", &saveptr); uuidbuf = strtok_r(NULL, "\n", &saveptr); if (iden != NULL && uuidbuf != NULL && STREQ(iden, "#UUID:")) { if (virStrcpy(uuidstr, uuidbuf, len) == NULL) { virReportError(VIR_ERR_INTERNAL_ERROR, _("invalid uuid %s"), uuidbuf); goto cleanup; } break; } } retval = 0; cleanup: VIR_FREE(line); VIR_FORCE_FCLOSE(fp); VIR_FREE(conf_file); return retval; }
static unsigned long virNodeCountThreadSiblings(const char *dir, unsigned int cpu) { unsigned long ret = 0; char *path; FILE *pathfp; char str[1024]; size_t i; if (virAsprintf(&path, "%s/cpu%u/topology/thread_siblings", dir, cpu) < 0) return 0; pathfp = fopen(path, "r"); if (pathfp == NULL) { /* If file doesn't exist, then pretend our only * sibling is ourself */ if (errno == ENOENT) { VIR_FREE(path); return 1; } virReportSystemError(errno, _("cannot open %s"), path); VIR_FREE(path); return 0; } if (fgets(str, sizeof(str), pathfp) == NULL) { virReportSystemError(errno, _("cannot read from %s"), path); goto cleanup; } i = 0; while (str[i] != '\0') { if (c_isdigit(str[i])) ret += count_one_bits(str[i] - '0'); else if (str[i] >= 'A' && str[i] <= 'F') ret += count_one_bits(str[i] - 'A' + 10); else if (str[i] >= 'a' && str[i] <= 'f') ret += count_one_bits(str[i] - 'a' + 10); i++; } cleanup: VIR_FORCE_FCLOSE(pathfp); VIR_FREE(path); return ret; }
static void libxlDriverConfigDispose(void *obj) { libxlDriverConfigPtr cfg = obj; virObjectUnref(cfg->caps); libxl_ctx_free(cfg->ctx); xtl_logger_destroy(cfg->logger); if (cfg->logger_file) VIR_FORCE_FCLOSE(cfg->logger_file); VIR_FREE(cfg->configDir); VIR_FREE(cfg->autostartDir); VIR_FREE(cfg->logDir); VIR_FREE(cfg->stateDir); VIR_FREE(cfg->libDir); VIR_FREE(cfg->saveDir); }
static unsigned long count_thread_siblings(unsigned int cpu) { unsigned long ret = 0; char *path; FILE *pathfp; char str[1024]; int i; if (virAsprintf(&path, "%s/cpu%u/topology/thread_siblings", sysfs_path, cpu) < 0) { virReportOOMError(); return 0; } pathfp = fopen(path, "r"); if (pathfp == NULL) { virReportSystemError(errno, _("cannot open %s"), path); VIR_FREE(path); return 0; } if (fgets(str, sizeof(str), pathfp) == NULL) { virReportSystemError(errno, _("cannot read from %s"), path); goto cleanup; } i = 0; while (str[i] != '\0') { if (c_isdigit(str[i])) ret += count_one_bits(str[i] - '0'); else if (str[i] >= 'A' && str[i] <= 'F') ret += count_one_bits(str[i] - 'A' + 10); else if (str[i] >= 'a' && str[i] <= 'f') ret += count_one_bits(str[i] - 'a' + 10); i++; } cleanup: VIR_FORCE_FCLOSE(pathfp); VIR_FREE(path); return ret; }
/* * value will be freed before a new value is assigned to it, the caller is * responsible for freeing it afterwards. * * Returns <0 on error, 0 if not found, 1 if found. */ int openvzReadConfigParam(const char *conf_file, const char *param, char **value) { char *line = NULL; size_t line_size = 0; FILE *fp; int err = 0; char *sf, *token, *saveptr = NULL; fp = fopen(conf_file, "r"); if (fp == NULL) return -1; VIR_FREE(*value); while (1) { if (getline(&line, &line_size, fp) < 0) { err = !feof(fp); break; } if (! STREQLEN(line, param, strlen(param))) continue; sf = line + strlen(param); if (*sf++ != '=') continue; saveptr = NULL; if ((token = strtok_r(sf, "\"\t\n", &saveptr)) != NULL) { VIR_FREE(*value); *value = strdup(token); if (*value == NULL) { err = 1; break; } /* keep going - last entry wins */ } } VIR_FREE(line); VIR_FORCE_FCLOSE(fp); return err ? -1 : *value ? 1 : 0; }
/* Return the positive decimal contents of the given * DIR/cpu%u/FILE, or -1 on error. If MISSING_OK and the * file could not be found, return 1 instead of an error; this is * because some machines cannot hot-unplug cpu0, or because * hot-unplugging is disabled. */ static int virNodeGetCpuValue(const char *dir, unsigned int cpu, const char *file, bool missing_ok) { char *path; FILE *pathfp; int value = -1; char value_str[INT_BUFSIZE_BOUND(value)]; char *tmp; if (virAsprintf(&path, "%s/cpu%u/%s", dir, cpu, file) < 0) { virReportOOMError(); return -1; } pathfp = fopen(path, "r"); if (pathfp == NULL) { if (missing_ok && errno == ENOENT) value = 1; else virReportSystemError(errno, _("cannot open %s"), path); goto cleanup; } if (fgets(value_str, sizeof(value_str), pathfp) == NULL) { virReportSystemError(errno, _("cannot read from %s"), path); goto cleanup; } if (virStrToLong_i(value_str, &tmp, 10, &value) < 0) { nodeReportError(VIR_ERR_INTERNAL_ERROR, _("could not convert '%s' to an integer"), value_str); goto cleanup; } cleanup: VIR_FORCE_FCLOSE(pathfp); VIR_FREE(path); return value; }
/* Do actual checking for UUID presence in conf file, * assign if not present. */ int openvzSetDefinedUUID(int vpsid, unsigned char *uuid) { char *conf_file; char uuidstr[VIR_UUID_STRING_BUFLEN]; FILE *fp = NULL; int ret = -1; if (uuid == NULL) return -1; if (openvzLocateConfFile(vpsid, &conf_file, "conf") < 0) return -1; if (openvzGetVPSUUID(vpsid, uuidstr, sizeof(uuidstr))) goto cleanup; if (uuidstr[0] == 0) { fp = fopen(conf_file, "a"); /* append */ if (fp == NULL) goto cleanup; virUUIDFormat(uuid, uuidstr); /* Record failure if fprintf or VIR_FCLOSE fails, and be careful always to close the stream. */ if ((fprintf(fp, "\n#UUID: %s\n", uuidstr) < 0) || (VIR_FCLOSE(fp) == EOF)) goto cleanup; } ret = 0; cleanup: VIR_FORCE_FCLOSE(fp); VIR_FREE(conf_file); return ret; }
/** * virNetDevMacVLanTapOpen: * Open the macvtap's tap device. * @ifname: Name of the macvtap interface * @retries : Number of retries in case udev for example may need to be * waited for to create the tap chardev * Returns negative value in case of error, the file descriptor otherwise. */ static int virNetDevMacVLanTapOpen(const char *ifname, int retries) { FILE *file; char path[64]; int ifindex; char tapname[50]; int tapfd; if (snprintf(path, sizeof(path), "/sys/class/net/%s/ifindex", ifname) >= sizeof(path)) { virReportSystemError(errno, "%s", _("buffer for ifindex path is too small")); return -1; } file = fopen(path, "r"); if (!file) { virReportSystemError(errno, _("cannot open macvtap file %s to determine " "interface index"), path); return -1; } if (fscanf(file, "%d", &ifindex) != 1) { virReportSystemError(errno, "%s",_("cannot determine macvtap's tap device " "interface index")); VIR_FORCE_FCLOSE(file); return -1; } VIR_FORCE_FCLOSE(file); if (snprintf(tapname, sizeof(tapname), "/dev/tap%d", ifindex) >= sizeof(tapname)) { virReportSystemError(errno, "%s", _("internal buffer for tap device is too small")); return -1; } while (1) { /* may need to wait for udev to be done */ tapfd = open(tapname, O_RDWR); if (tapfd < 0 && retries > 0) { retries--; usleep(20000); continue; } break; } if (tapfd < 0) virReportSystemError(errno, _("cannot open macvtap tap device %s"), tapname); return tapfd; }
static int testSELinuxLoadFileList(const char *testname, testSELinuxFile **files, size_t *nfiles) { int ret = -1; char *path = NULL; FILE *fp = NULL; char *line = NULL; *files = NULL; *nfiles = 0; if (virAsprintf(&path, "%s/securityselinuxlabeldata/%s.txt", abs_srcdir, testname) < 0) goto cleanup; if (!(fp = fopen(path, "r"))) goto cleanup; if (VIR_ALLOC_N(line, 1024) < 0) goto cleanup; while (!feof(fp)) { char *file = NULL, *context = NULL, *tmp; if (!fgets(line, 1024, fp)) { if (!feof(fp)) goto cleanup; break; } tmp = strchr(line, ';'); if (!tmp) { virReportError(VIR_ERR_INTERNAL_ERROR, "unexpected format for line '%s'", line); goto cleanup; } *tmp = '\0'; tmp++; if (virAsprintf(&file, "%s/securityselinuxlabeldata%s", abs_builddir, line) < 0) goto cleanup; if (*tmp != '\0' && *tmp != '\n') { if (VIR_STRDUP(context, tmp) < 0) { VIR_FREE(file); goto cleanup; } tmp = strchr(context, '\n'); if (tmp) *tmp = '\0'; } if (VIR_EXPAND_N(*files, *nfiles, 1) < 0) { VIR_FREE(file); VIR_FREE(context); goto cleanup; } (*files)[(*nfiles)-1].file = file; (*files)[(*nfiles)-1].context = context; } ret = 0; cleanup: VIR_FORCE_FCLOSE(fp); VIR_FREE(path); VIR_FREE(line); return ret; }
int main(int argc, char **argv) { int i, n; char **origenv; char **newenv; char *cwd; FILE *log = fopen(abs_builddir "/commandhelper.log", "w"); if (!log) goto error; for (i = 1 ; i < argc ; i++) { fprintf(log, "ARG:%s\n", argv[i]); } origenv = environ; n = 0; while (*origenv != NULL) { n++; origenv++; } if (VIR_ALLOC_N(newenv, n) < 0) { exit(EXIT_FAILURE); } origenv = environ; n = i = 0; while (*origenv != NULL) { newenv[i++] = *origenv; n++; origenv++; } qsort(newenv, n, sizeof(newenv[0]), envsort); for (i = 0 ; i < n ; i++) { /* Ignore the variables used to instruct the loader into * behaving differently, as they could throw the tests off. */ if (!STRPREFIX(newenv[i], "LD_")) fprintf(log, "ENV:%s\n", newenv[i]); } for (i = 0 ; i < sysconf(_SC_OPEN_MAX) ; i++) { int f; int closed; if (i == fileno(log)) continue; closed = fcntl(i, F_GETFD, &f) == -1 && errno == EBADF; if (!closed) fprintf(log, "FD:%d\n", i); } fprintf(log, "DAEMON:%s\n", getpgrp() == getsid(0) ? "yes" : "no"); if (!(cwd = getcwd(NULL, 0))) return EXIT_FAILURE; if (strlen(cwd) > strlen(".../commanddata") && STREQ(cwd + strlen(cwd) - strlen("/commanddata"), "/commanddata")) strcpy(cwd, ".../commanddata"); fprintf(log, "CWD:%s\n", cwd); VIR_FREE(cwd); VIR_FORCE_FCLOSE(log); if (argc > 1 && STREQ(argv[1], "--close-stdin")) { if (freopen("/dev/null", "r", stdin) != stdin) goto error; usleep(100*1000); } char buf[1024]; ssize_t got; fprintf(stdout, "BEGIN STDOUT\n"); fflush(stdout); fprintf(stderr, "BEGIN STDERR\n"); fflush(stderr); for (;;) { got = read(STDIN_FILENO, buf, sizeof(buf)); if (got < 0) goto error; if (got == 0) break; if (safewrite(STDOUT_FILENO, buf, got) != got) goto error; if (safewrite(STDERR_FILENO, buf, got) != got) goto error; } fprintf(stdout, "END STDOUT\n"); fflush(stdout); fprintf(stderr, "END STDERR\n"); fflush(stderr); return EXIT_SUCCESS; error: return EXIT_FAILURE; }
static int addnhostsWrite(const char *path, dnsmasqAddnHost *hosts, unsigned int nhosts) { char *tmp; FILE *f; bool istmp = true; size_t i, j; int rc = 0; /* even if there are 0 hosts, create a 0 length file, to allow * for runtime addition. */ if (virAsprintf(&tmp, "%s.new", path) < 0) return -ENOMEM; if (!(f = fopen(tmp, "w"))) { istmp = false; if (!(f = fopen(path, "w"))) { rc = -errno; goto cleanup; } } for (i = 0; i < nhosts; i++) { if (fputs(hosts[i].ip, f) == EOF || fputc('\t', f) == EOF) { rc = -errno; VIR_FORCE_FCLOSE(f); if (istmp) unlink(tmp); goto cleanup; } for (j = 0; j < hosts[i].nhostnames; j++) { if (fputs(hosts[i].hostnames[j], f) == EOF || fputc('\t', f) == EOF) { rc = -errno; VIR_FORCE_FCLOSE(f); if (istmp) unlink(tmp); goto cleanup; } } if (fputc('\n', f) == EOF) { rc = -errno; VIR_FORCE_FCLOSE(f); if (istmp) unlink(tmp); goto cleanup; } } if (VIR_FCLOSE(f) == EOF) { rc = -errno; goto cleanup; } if (istmp && rename(tmp, path) < 0) { rc = -errno; unlink(tmp); goto cleanup; } cleanup: VIR_FREE(tmp); return rc; }
int nodeGetInfo(virNodeInfoPtr nodeinfo) { virArch hostarch = virArchFromHost(); memset(nodeinfo, 0, sizeof(*nodeinfo)); if (virStrcpyStatic(nodeinfo->model, virArchToString(hostarch)) == NULL) return -1; #ifdef __linux__ { int ret = -1; FILE *cpuinfo = fopen(CPUINFO_PATH, "r"); if (!cpuinfo) { virReportSystemError(errno, _("cannot open %s"), CPUINFO_PATH); return -1; } ret = linuxNodeInfoCPUPopulate(cpuinfo, SYSFS_SYSTEM_PATH, nodeinfo); if (ret < 0) goto cleanup; /* Convert to KB. */ nodeinfo->memory = physmem_total() / 1024; cleanup: VIR_FORCE_FCLOSE(cpuinfo); return ret; } #elif defined(__FreeBSD__) { nodeinfo->nodes = 1; nodeinfo->sockets = 1; nodeinfo->threads = 1; nodeinfo->cpus = freebsdNodeGetCPUCount(); if (nodeinfo->cpus == -1) return -1; nodeinfo->cores = nodeinfo->cpus; unsigned long cpu_freq; size_t cpu_freq_len = sizeof(cpu_freq); if (sysctlbyname("dev.cpu.0.freq", &cpu_freq, &cpu_freq_len, NULL, 0) < 0) { virReportSystemError(errno, "%s", _("cannot obtain CPU freq")); return -1; } nodeinfo->mhz = cpu_freq; /* get memory information */ int mib[2] = { CTL_HW, HW_PHYSMEM }; unsigned long physmem; size_t len = sizeof(physmem); if (sysctl(mib, 2, &physmem, &len, NULL, 0) == -1) { virReportSystemError(errno, "%s", _("cannot obtain memory size")); return -1; } nodeinfo->memory = (unsigned long)(physmem / 1024); return 0; } #else /* XXX Solaris will need an impl later if they port QEMU driver */ virReportError(VIR_ERR_NO_SUPPORT, "%s", _("node info not implemented on this platform")); return -1; #endif }