int LocalPackage::fill_filelist(PACKAGE *package, bool) { if (!package) package=&data; //mDebug("fill_filelist start"); // Retrieving regular files // For setup mode, we can try to enable cached filelists vector<string> file_names; string fname; bool fname_temp = false; if (setupMode && FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist")) { fname = getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist"; } else { fname = get_tmp_file(); fname_temp = true; system("tar tf "+filename+" --exclude install " +" > "+fname + " 2>/dev/null"); } // Parsing file list file_names=ReadFileStrings(fname); if (fname_temp) unlink(fname.c_str()); if (file_names.size()>2) file_names.erase(file_names.begin(), file_names.begin()+2); else { mWarning("Empty file list in package " + package->get_name()); file_names.clear(); } package->set_files(file_names); // Retrieving symlinks (from doinst.sh). string dt; bool dt_temp=false; // Extracting file to the temp dir if (setupMode && FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/doinst.sh")) { dt = getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/doinst.sh"; } else if (!setupMode || !FileExists(getAbsolutePath(getDirectory(filename))+"/.fcache/" + getFilename(filename) + "/flist")) { // Assuming that doinst.sh isn't present if flist is cached dt = get_tmp_file(); extractFromTgz(filename, "install/doinst.sh", dt); dt_temp = true; } if (!dt.empty() && FileExists(dt)) { string lnfname=get_tmp_file(); string sed_cmd = "sed -n 's,^( *cd \\([^ ;][^ ;]*\\) *; *rm -rf \\([^ )][^ )]*\\) *) *$,\\1/\\2,p' < "; sed_cmd += dt + " > " + lnfname; system(sed_cmd); vector<string>link_names=ReadFileStrings(lnfname); for (size_t i=0; i<link_names.size(); ++i) { if (!link_names[i].empty()) package->get_files_ptr()->push_back(link_names[i]); } if (dt_temp) unlink(dt.c_str()); unlink(lnfname.c_str()); } delete_tmp_files(); return 0; }
int convert_package(const string& filename, const string& output_dir) { // char tmp[1000]; say("converting package %s\n", filename.c_str()); int name_start=0; for (int i=filename.length()-1; filename[i]!='/' && i>=0; i--) { name_start=i; } string real_filename; for (unsigned int i=name_start; i<filename.length(); i++) { real_filename+=filename[i]; } string ext_outdir = filename.substr(0,filename.find_last_of("/")); string tmp_dir=get_tmp_file(); string xml_output=tmp_dir+"/install/data.xml"; string reasm="rm "+tmp_dir+" && mkdir -p "+tmp_dir+"/install >/dev/null && cp "+filename+" "+tmp_dir+"/ && cd "+tmp_dir+" && tar xf "+real_filename+" > /dev/null"; system(reasm.c_str()); slack_convert(filename, xml_output); system("mkdir -p " + output_dir+"/"+ext_outdir); reasm="cd "+tmp_dir+" && rm "+real_filename+" && " + MAKEPKG_CMD +" "+output_dir+"/"+ext_outdir + "/" + real_filename+" 2>/dev/null >/dev/null && rm -rf "+tmp_dir; int ret = system(reasm.c_str()); if (ret) say("An error occured while converting package %s\n", filename.c_str()); else say("%s: OK\n", filename.c_str()); delete_tmp_files(); return 0; }
MsgInfo *procmsg_msginfo_new_from_mimeinfo(MsgInfo *src_msginfo, MimeInfo *mimeinfo) { MsgInfo *tmp_msginfo = NULL; MsgFlags flags = {0, 0}; if (!mimeinfo || mimeinfo->type != MIMETYPE_MESSAGE || g_strcasecmp(mimeinfo->subtype, "rfc822")) { g_warning("procmsg_msginfo_new_from_mimeinfo(): unsuitable mimeinfo"); return NULL; } if (mimeinfo->content == MIMECONTENT_MEM) { gchar *tmpfile = get_tmp_file(); str_write_to_file(mimeinfo->data.mem, tmpfile); g_free(mimeinfo->data.mem); mimeinfo->content == MIMECONTENT_FILE; mimeinfo->data.filename = g_strdup(tmpfile); g_free(tmpfile); } tmp_msginfo = procheader_parse_file(mimeinfo->data.filename, flags, TRUE, FALSE); if (tmp_msginfo != NULL) { tmp_msginfo->folder = src_msginfo->folder; tmp_msginfo->plaintext_file = g_strdup(mimeinfo->data.filename); } else { g_warning("procmsg_msginfo_new_from_mimeinfo(): Can't generate new msginfo"); } return tmp_msginfo; }
gpgme_data_t sgpgme_data_from_mimeinfo(MimeInfo *mimeinfo) { gpgme_data_t data = NULL; gpgme_error_t err; FILE *fp = g_fopen(mimeinfo->data.filename, "rb"); gchar *tmp_file = NULL; if (!fp) return NULL; tmp_file = get_tmp_file(); copy_file_part(fp, mimeinfo->offset, mimeinfo->length, tmp_file); fclose(fp); fp = NULL; debug_print("tmp file %s\n", tmp_file); err = gpgme_data_new_from_file(&data, tmp_file, 1); claws_unlink(tmp_file); g_free(tmp_file); debug_print("data %p (%d %d)\n", (void *)&data, mimeinfo->offset, mimeinfo->length); if (err) { debug_print ("gpgme_data_new_from_file failed: %s\n", gpgme_strerror (err)); privacy_set_error(_("Couldn't get data from message, %s"), gpgme_strerror(err)); return NULL; } return data; }
int driverSelectionMenu(CursesInterface &ncInterface) { // First, detect hardware for which we have to install drivers. string tmp_hw = get_tmp_file(); system("lspci > " + tmp_hw); vector<string> hw = ReadFileStrings(tmp_hw); // Check for VirtualBox bool hasVirtualBox=false; int hasNvidia=-1; int hasRadeon=-1; for(size_t i=0; i<hw.size(); ++i) { if (hw[i].find("VirtualBox")!=std::string::npos) hasVirtualBox = true; if (hw[i].find("VGA compatible controller")!=std::string::npos && hw[i].find("nVidia")!=std::string::npos) hasNvidia = i; if (hw[i].find("VGA compatible controller")!=std::string::npos && hw[i].find("Radeon")!=std::string::npos) hasRadeon = i; } if (hasNvidia==-1) return 1; vector<MenuItem> menuItems; menuItems.push_back(MenuItem(_("Latest"), _("Latest GeForce (series 6xxx and later)"))); menuItems.push_back(MenuItem("173", _("GeForce FX series"))); menuItems.push_back(MenuItem("96", _("GeForce 4 series"))); menuItems.push_back(MenuItem(_("Skip"), _("Do not install driver"))); string ret = ncInterface.showMenu2(_("Videocard detected: ") + hw[hasNvidia] + _("\nChoose driver for it:"), menuItems); if (!ret.empty() && ret != _("Skip")) { if (ret!=_("Latest")) { WriteFile(SETUPCONFIG_NVIDIA, string("legacy" + ret)); } else { WriteFile(SETUPCONFIG_NVIDIA, "generic"); } } return 0; }
static gint pop3_retr_recv(Pop3Session *session, const gchar *data, guint len) { gchar *file; gint drop_ok; MailReceiveData mail_receive_data; /* NOTE: we allocate a slightly larger buffer with a zero terminator * because some plugins may think that it has a C string. */ mail_receive_data.session = session; mail_receive_data.data = g_new0(gchar, len + 1); mail_receive_data.data_len = len; memcpy(mail_receive_data.data, data, len); hooks_invoke(MAIL_RECEIVE_HOOKLIST, &mail_receive_data); file = get_tmp_file(); if (pop3_write_msg_to_file(file, mail_receive_data.data, mail_receive_data.data_len, NULL) < 0) { g_free(file); g_free(mail_receive_data.data); session->error_val = PS_IOERR; return -1; } g_free(mail_receive_data.data); if (session->msg[session->cur_msg].partial_recv == POP3_MUST_COMPLETE_RECV) { gchar *old_file = partial_get_filename( session->ac_prefs->recv_server, session->ac_prefs->userid, session->msg[session->cur_msg].uidl); if (old_file) { partial_delete_old(old_file); g_free(old_file); } } /* drop_ok: 0: success 1: don't receive -1: error */ drop_ok = session->drop_message(session, file); g_free(file); if (drop_ok < 0) { session->error_val = PS_IOERR; return -1; } session->cur_total_bytes += session->msg[session->cur_msg].size; session->cur_total_recv_bytes += session->msg[session->cur_msg].size; session->cur_total_num++; session->msg[session->cur_msg].received = TRUE; session->msg[session->cur_msg].partial_recv = POP3_TOTALLY_RECEIVED; session->msg[session->cur_msg].recv_time = drop_ok == 1 ? RECV_TIME_KEEP : session->current_time; return PS_SUCCESS; }
int getProcessPid(const string& name) { string tmp = get_tmp_file(); system("pidof " + name + " > " + tmp); string pid = ReadFile(tmp); unlink(tmp.c_str()); if (pid.empty() || pid.find_first_not_of(" \t\n") == std::string::npos) return -1; else return atoi(pid.c_str()); }
string get_file_md5(const string& filename) { string tmp_md5=get_tmp_file(); system("md5sum '"+filename+"' > "+tmp_md5 + " 2>/dev/null"); string ret = ReadFile(tmp_md5); unlink(tmp_md5.c_str()); if (ret.find(" ")!=std::string::npos) return ret.substr(0, ret.find(" ")); else return ""; }
string Dialog::execInputBox(string header, string default_text, unsigned int height, unsigned int width) { string tmp_file = get_tmp_file(); string exec_str = dialog + " --inputbox \"" + header + "\" " + IntToStr(height) + " " + IntToStr(width) + " \"" + default_text + "\"" + " 2>"+tmp_file; system(exec_str.c_str()); string ret = getReturnValue(tmp_file); unlink(tmp_file.c_str()); return ret; }
static gint pop3_top_recv(Pop3Session *session, const gchar *data, guint len) { gchar *file; gint drop_ok; MailReceiveData mail_receive_data; gchar *partial_notice = NULL; /* NOTE: we allocate a slightly larger buffer with a zero terminator * because some plugins may think that it has a C string. */ mail_receive_data.session = session; mail_receive_data.data = g_new0(gchar, len + 1); mail_receive_data.data_len = len; memcpy(mail_receive_data.data, data, len); hooks_invoke(MAIL_RECEIVE_HOOKLIST, &mail_receive_data); partial_notice = g_strdup_printf("SC-Marked-For-Download: 0\n" "SC-Partially-Retrieved: %s\n" "SC-Account-Server: %s\n" "SC-Account-Login: %s\n" "SC-Message-Size: %d", session->msg[session->cur_msg].uidl, session->ac_prefs->recv_server, session->ac_prefs->userid, session->msg[session->cur_msg].size); file = get_tmp_file(); if (pop3_write_msg_to_file(file, mail_receive_data.data, mail_receive_data.data_len, partial_notice) < 0) { g_free(file); g_free(mail_receive_data.data); session->error_val = PS_IOERR; g_free(partial_notice); return -1; } g_free(mail_receive_data.data); g_free(partial_notice); /* drop_ok: 0: success 1: don't receive -1: error */ drop_ok = session->drop_message(session, file); g_free(file); if (drop_ok < 0) { session->error_val = PS_IOERR; return -1; } session->cur_total_bytes += session->msg[session->cur_msg].size; session->cur_total_recv_bytes += session->msg[session->cur_msg].size; session->cur_total_num++; session->msg[session->cur_msg].received = TRUE; session->msg[session->cur_msg].partial_recv = POP3_PARTIALLY_RECEIVED; session->msg[session->cur_msg].recv_time = drop_ok == 1 ? RECV_TIME_KEEP : session->current_time; return PS_SUCCESS; }
bool LocalPackage::isNative() { string tmp_xml = get_tmp_file(); extractFromTgz(filename, "install/data.xml", tmp_xml); if (!FileNotEmpty(tmp_xml)) { unlink(tmp_xml.c_str()); return false; } unlink(tmp_xml.c_str()); return true; }
int LocalPackage::get_xml() { legacyPackage=false; _parseOk=false; //mDebug("get_xml start"); string tmp_xml=get_tmp_file(); //mDebug("Extracting XML"); extractFromTgz(filename, "install/data.xml", tmp_xml); if (!FileNotEmpty(tmp_xml)) { //mDebug("XML empty, parsing as legacy"); say(_("%s: No XML, converting from legacy\n"), filename.c_str()); legacyPackage=true; FILE *legacy = fopen("/var/log/mpkg-legacy.log", "a"); if (legacy) { fprintf(legacy, "%s\n", filename.c_str()); fclose(legacy); } // In most cases it means that we have legacy Slackware package. // Trying to convert: //mDebug("Converting from legacy to XML"); if (slack2xml(filename, tmp_xml) != 0) { mError("Infernally invalid package! Cannot work with it at all"); unlink(tmp_xml.c_str()); delete_tmp_files(); return -1; } //mDebug("Converted"); } //mDebug("Parsing XML"); PackageConfig p(tmp_xml); unlink(tmp_xml.c_str()); if (!p.parseOk) { //mDebug("Error parsing XML"); delete_tmp_files(); return -100; } int bufsize; xmlChar * membuff = p.getXMLNodeXPtr(&bufsize); __doc = xmlParseMemory((const char *) membuff, bufsize); xmlFree(membuff); _packageXMLNode = xmlDocGetRootElement(__doc); xml2package(p.getXMLDoc(), p.getXMLNode(), &data); //mDebug("get_xml end"); delete_tmp_files(); _parseOk=true; return 0; }
bool Dialog::execYesNo(string header, unsigned int height, unsigned int width, string yes_label, string no_label) { string tmp_file = get_tmp_file(); string opt; if (!yes_label.empty()) opt+=" --yes-label \"" + yes_label + "\" "; if (!no_label.empty()) opt+=" --no-label \"" + no_label + "\" "; string exec_str = dialog + opt + " --yesno \"" + header + "\" " + IntToStr(height) + " " + IntToStr(width); int r = system(exec_str.c_str()); unlink(tmp_file.c_str()); if (r==0) return true; else return false; }
bool isProcessRunning(const string& pid) { if (pid.empty() || pid.find_first_not_of("0123456789")!=std::string::npos) return false; string tmp_file = get_tmp_file(); system("ps -p " + pid + " > " + tmp_file); string result = ReadFile(tmp_file); unlink(tmp_file.c_str()); if (result.find(pid)!=std::string::npos) { // Process is running return true; } else return false; }
int LocalPackage::create_signature(string) { string tmp_sig=get_tmp_file(); system("gpg -ba -o " + tmp_sig + " " + filename); string pgpstr=ReadFile(tmp_sig); unlink(tmp_sig.c_str()); if (pgpstr.empty()) { mError("Unable to read signature temp file"); return 1; } data.pgp_signature = pgpstr; xmlNewChild(_packageXMLNode, NULL, (const xmlChar *)"signature", (const xmlChar *)pgpstr.c_str()); return 0; }
int TextSetup::setAdditionalRepositories() { if (repositories.empty() && !ncInterface.showYesNo(_("Do you want to specify additional repositories?"))) return 0; ncInterface.showMsgBox(_("Edit file and place each repository on separate line")); string tmp_file = get_tmp_file(); WriteFileStrings(tmp_file, repositories); ncInterface.uninit(); system("mcedit " + tmp_file); vector<string> reps = ReadFileStrings(tmp_file); for (size_t i=0; i<reps.size(); ++i) { if (cutSpaces(reps[i]).empty()) continue; if (cutSpaces(reps[i])[0]=='#') continue; repositories.push_back(reps[i]); } unlink(tmp_file.c_str()); return 0; }
bool isMounted(string mountpoint) { if (_cdromMounted) return true; if (mountpoint.find_last_of("/")>=mountpoint.length()-1) mountpoint = mountpoint.substr(0,mountpoint.length()-1); // mountpoint = mountpoint.substr(0,find_last_of("/")-1); // mDebug("Checking if [" + mountpoint + "] is mounted"); #ifdef _MNTENTMCHECK // First, check if device mounted in proper directory. bool mounted=false; struct mntent *mountList; FILE *mtab = fopen("/proc/mounts", "r"); //char volname[2000]; if (mtab) { mountList = getmntent(mtab); while ( !mounted && mountList != NULL ) { if (strcmp(mountList->mnt_dir, mountpoint.c_str())==0) { /*if (strcmp(mountList->mnt_dir, CDROM_DEVICE.c_str())!=0) { umount(mountpoint.c_str()); } else*/ mounted = true; } mountList = getmntent(mtab); } fclose(mtab); } /* if (mounted) mDebug(mountpoint + " is mounted"); else mDebug(mountpoint + " isn't mounted");*/ return mounted; #else string out = get_tmp_file(); system("cat /proc/mounts | grep " + mountpoint + " | wc -l >" + out ); string ret = ReadFile(out); unlink(out.c_str()); if (ret.empty() || ret[0]=='0') { //mDebug(mountpoint + " isn't mounted"); return false; } else { //mDebug(mountpoint + " is already mounted"); return true; } #endif }
bool TextSetupMechanics::checkNvidiaLoad() { int hasNvidia = -1; if (hasNvidia==-1) { string tmp_hw = get_tmp_file(); system("lspci > " + tmp_hw); vector<string> hw = ReadFileStrings(tmp_hw); for(size_t i=0; i<hw.size(); ++i) { if (hw[i].find("VGA compatible controller")!=std::string::npos && hw[i].find("nVidia")!=std::string::npos) hasNvidia = i; } if (hasNvidia == -1) hasNvidia = 0; } // For debugging reasons, check for /tmp/nvidia_force file if (FileExists("/tmp/nvidia_force")) hasNvidia = 1; return hasNvidia > 0; }
int TextSetup::setTimezone() { // TODO: implement some easy way to find your timezone from this f****n' large list string tmpfile = get_tmp_file(); system("( cd /usr/share/zoneinfo && find . -type f | sed -e 's/\\.\\///g') > " + tmpfile); vector<string> tz = ReadFileStrings(tmpfile); unlink(tmpfile.c_str()); vector<MenuItem> m; for (size_t i=0; i<tz.size(); ++i) { m.push_back(MenuItem(tz[i], "")); } settings["timezone"] = ncInterface.showMenu2(_("Select your timezone:"), m, "Europe/Moscow"); if (ncInterface.showYesNo(_("Does your hardware clock stores time in UTC instead of localtime?"))) settings["time_utc"]="1"; else settings["time_utc"]="0"; return 0; }
string TextSetupMechanics::getLABEL(const string& dev) { string tmp_file = get_tmp_file(); string data; int try_count = 0; while (try_count<2 && data.empty()) { system("blkid -s LABEL " + dev + " > " + tmp_file); data = ReadFile(tmp_file); try_count++; } if (data.empty()) return ""; size_t a = data.find_first_of("\""); if (a==std::string::npos || a==data.size()-1) return ""; data.erase(data.begin(), data.begin()+a+1); a = data.find_first_of("\""); if (a==std::string::npos || a==0) return ""; return data.substr(0, a); }
int raidCreateMenu() { if (!ncInterface.showYesNo("ВНИМАНИЕ: ПРОЧТИТЕ ВНИМАТЕЛЬНО!\nВы намереваетесь создать один или несколько RAID-массивов. Для этого вы должны сначала создать разделы типа fd (Linux RAID autodetect) на необходимых жестких дисках.\nХотя массив можно создать поверх любых типов разделов, и даже поверх самих устройств - делать этого не рекомендуется, и данная утилита такого не поддерживает.\n\nПродолжить?")) return 1; string mdstat = get_tmp_file(); vector<RaidArray> activeArrays = getActiveRaidArrays(); vector<pEntry> pList; vector<string> gp; pList = getGoodPartitions(gp); string md_dev = "/dev/md" + IntToStr(activeArrays.size()); // extra check unsigned int shift = 0; check_free_array: for (unsigned int i=0; i<activeArrays.size(); ++i) { if (md_dev == activeArrays[i].md_dev) { shift++; md_dev = "/dev/md" + IntToStr(activeArrays.size()+shift); goto check_free_array; } } vector<MenuItem> usedPartitions; for (unsigned int i=0; i<pList.size(); ++i) { if (pList[i].raid) usedPartitions.push_back(MenuItem(pList[i].devname, pList[i].size + "Mb")); } usedPartitions.push_back(MenuItem("Готово", "Создать массив")); ncInterface.showExMenu("Выберите разделы, которые вы хотите объединить в RAID\nВНИМАНИЕ: ВСЕ ДАННЫЕ ДА ЭТИХ РАЗДЕЛАХ БУДУТ УНИЧТОЖЕНЫ!", usedPartitions); vector<MenuItem> raidLevels; raidLevels.push_back(MenuItem("0", "RAID0 (Stripe)", "Дисковый массив без избыточного хранения данных. Информация разбивается на блоки, которые одновременно записываются на отдельные диски, что обеспечивает практически линейное повышение производительности.\nПлюсы: максимально возможная производительность, 100% использование места\nМинусы: поломка хотя бы одного диска ведет к потере всей информации")); raidLevels.push_back(MenuItem("1", "RAID1 (Mirror)", "Дисковый массив с дублированием информации (зеркалированием данных). В простейшем случае два накопителя содержат одинаковую информацию и являются одним логическим диском. При выходе из строя одного диска его функции выполняет другой. Для реализации массива требуется не меньше двух винчестеров." )); raidLevels.push_back(MenuItem("10", "RAID10 (Stripe+Mirror)", "Комбинация двух предыдущих: зеркало с повышенной производительностью")); raidLevels.push_back(MenuItem("5", "RAID5 (Distributed Parity)", "Самый распространенный уровень. Блоки данных и контрольные суммы циклически записываются на все диски массива, отсутствует выделенный диск для хранения информации о четности, нет асимметричности конфигурации дисков. Допустим выход из строя одного диска")); raidLevels.push_back(MenuItem("6", "RAID6 (Two Independent Distributed Parity Schemes)", "То же что и RAID5, только позволяет выход из строя сразу двух дисков. Производительность ниже чем у RAID5")); string raidLevel = ncInterface.showMenu2("Выберите тип RAID", raidLevels); vector<string> up; for (unsigned int i=0; i<usedPartitions.size()-1; ++i) { if (usedPartitions[i].flag) up.push_back(usedPartitions[i].tag); } deviceCacheActual=false; unsigned int raid_size = up.size(); //if (raidLevel == "5") raid_size = up.size()-1; //if (raidLevel == "6") raid_size = up.size()-2; return createRaid(md_dev, raidLevel, raid_size, up); }
vector<RaidArray> getActiveRaidArrays() { vector<RaidArray> ret; string raw = get_tmp_file(); system("cat /proc/mdstat | grep md | grep active > " + raw); vector<string> mdstat = ReadFileStrings(raw); vector<string> extra; RaidArray *array; string tmp; for (unsigned int i=0; i<mdstat.size(); ++i) { if (mdstat[i].find("md")==0) { ret.push_back(RaidArray()); array = &ret[ret.size()-1]; array->md_dev = "/dev/" + mdstat[i].substr(0, mdstat[i].find(" : ")); tmp = mdstat[i].substr(mdstat[i].find(" active ") + strlen(" active ")); array->level = tmp.substr(0, tmp.find(" ")); array->extra_description = tmp.substr(tmp.find(" ")); if (array->extra_description.empty()) continue; tmp = array->extra_description.substr(1); tmp = cutSpaces(tmp); while(!tmp.empty() && tmp.find_first_not_of("][ ")!=std::string::npos) { tmp = tmp.substr(tmp.find_first_not_of("][ ")); if (tmp.find("[")==std::string::npos) break; array->devices.push_back("/dev/" + tmp.substr(0, tmp.find("["))); if (tmp.find(" ")==std::string::npos) break; else { tmp = tmp.substr(tmp.find(" ")); } } } } for (unsigned int i=0; i<ret.size(); ++i) { ret[i].extra_description = "RAID-массив " + ret[i].level + " ["; for (unsigned int d=0; d<ret[i].devices.size(); ++d) { if (ret[i].devices[d].length()>strlen("/dev/")) ret[i].extra_description += ret[i].devices[d].substr(strlen("/dev/")); else ret[i].extra_description += ret[i].devices[d]; if (d != ret[i].devices.size()-1) ret[i].extra_description += "|"; } ret[i].extra_description += "]"; } return ret; }
gchar* spamassassin_create_tmp_spamc_wrapper(gboolean spam) { gchar *contents; gchar *fname = get_tmp_file(); if (fname != NULL) { contents = g_strdup_printf( "spamc -d %s -p %u -u %s -t %u -s %u -L %s<\"$*\";exit $?", config.hostname, config.port, config.username, config.timeout, config.max_size * 1024, spam?"spam":"ham"); if (str_write_to_file(contents, fname) < 0) { g_free(fname); fname = NULL; } g_free(contents); } /* returned pointer must be free'ed by caller */ return fname; }
static int hotplug_remove_device(void) { int ret; char serv[256]; char *busid; logmsg("bind-driver.c:: removing device" ); busid = get_busid_from_env(); if( busid == NULL ) { logmsg("error retrieving busid"); return -1; } logmsg("busid = '%s'", busid); ret = get_tmp_file(serv, busid); if(ret) { logerr("could not get server from /tmp file" ); return -1; } logmsg("export server is '%s'", serv); /* XXX * we don't do anything here. The server will know by itself, that the * device is no longer available, as the connection will break down, * and it will (afai guess) receive the 'UNAVAILABLE' signal. If we * try to use unexport_from at this point, the driver might already be * unavailable, which will result in a segmentation fault! */ /*ret = unexport_from(serv, busid); if(ret) { logerr("exporting of device failed"); return -1; }*/ remove_tmp_file(serv, busid); logmsg("device removed"); return 0; }
vector<RaidArray> detectRaidArrays() { vector<string> gp; vector<pEntry> pList; vector<string> raw; vector<RaidArray> ret; RaidArray *array = NULL; string tmp; pList= getGoodPartitions(gp); string mdout = get_tmp_file(); for (unsigned int i=0; i<pList.size(); ++i) { if (!pList[i].raid) continue; system("mdadm -Q " + pList[i].devname + " | grep undetected | grep /dev/md > " + mdout + " 2>/dev/tty4"); raw = ReadFileStrings(mdout); if (raw.empty()) continue; if (raw[0].find("/dev/md")==std::string::npos) continue; tmp = raw[0].substr(raw[0].find("/dev/md")); if (tmp.find(".")==std::string::npos) continue; tmp = tmp.substr(0, tmp.find_first_of(".")); //ncInterface.showMsgBox("FOUND: " + tmp); array = NULL; for (unsigned int r=0; r<ret.size(); ++r) { if (ret[r].md_dev == tmp) { array = &ret[r]; break; } } //ncInterface.showMsgBox("Total ret: " + IntToStr(ret.size()) + " but can't find " + tmp); if (!array) { ret.push_back(RaidArray()); array = &ret[ret.size()-1]; array->md_dev = tmp; } array->devices.push_back(pList[i].devname); //ncInterface.showMsgBox("Total ret: " + IntToStr(ret.size()) + " found li " + tmp); } return ret; }
bool Dialog::execCheckList(string header, unsigned int height, unsigned int width, unsigned int menu_height, vector<TagPair>* menuItems) { if (menuItems->empty()) { mError("Empty item list"); return false; } string tmp_file = get_tmp_file(); string exec_str = dialog + " --checklist \"" + header + "\" " + IntToStr(height) + " " + IntToStr(width) + " " + IntToStr(menu_height); for (unsigned int i=0; i<menuItems->size(); i++) { exec_str += " \"" + menuItems->at(i).tag + "\" \"" + menuItems->at(i).value+"\" "; if (menuItems->at(i).checkState) exec_str += "on"; else exec_str += "off"; } exec_str += " 2>"+tmp_file; int d_ret = system(exec_str.c_str()); vector<string> ret = getReturnValues(tmp_file); unlink(tmp_file.c_str()); if (d_ret!=0) return false; for (unsigned int i=0; i<menuItems->size(); i++) { menuItems->at(i).checkState=false; } for (unsigned int i=0; i<ret.size(); i++) { for (unsigned int t=0; t<menuItems->size(); t++) { if (ret[i]==menuItems->at(t).tag) { menuItems->at(t).checkState=true; } } } return true; }
/** * Add a single attribute value to a list. * \param ld LDAP handle. * \param entry LDAP entry to process. * \param attr LDAP attribute name to process. * \return List of values; only one value will be present. */ static GSList *ldapqry_add_single_value( LDAP *ld, LDAPMessage *entry, char *attr ) { GSList *list = NULL; struct berval **vals; if( ( vals = ldap_get_values_len( ld, entry, attr ) ) != NULL ) { if( vals[0] != NULL ) { if (strcmp(attr, "jpegPhoto")) { debug_print("sv\t%s: %s\n", attr?attr:"null", vals[0]->bv_val?vals[0]->bv_val:"null"); list = g_slist_append( list, g_strndup( vals[0]->bv_val, vals[0]->bv_len )); } else { char *file = get_tmp_file(); FILE *fp = claws_fopen(file, "wb"); if (fp) { claws_fwrite(vals[0]->bv_val, 1, vals[0]->bv_len, fp); claws_safe_fclose(fp); } list = g_slist_append( list, file); } } } ldap_value_free_len( vals ); return list; }
int createRaid(string md_dev, string level, int count, vector<string> partitions) { string cmd = "mdadm --create " + md_dev + " -l " + level + " -n " + IntToStr(count); for (unsigned int i=0; i<partitions.size(); ++i) { cmd += " " + partitions[i]; } string log = get_tmp_file(); ncInterface.uninit(); int ret = system(cmd); if (ret == 1) { ncInterface.showMsgBox("Создание RAID-массива не удалось:\n" + ReadFile(log)); return 1; } deviceCacheActual = false; system("dd if=/dev/zero of=" + md_dev + " bs=1024 count=1 > /dev/null 2>/dev/null"); // Clearing partition table system("echo 100000 >/proc/sys/dev/raid/speed_limit_min"); // Let's speed up resyncing process (experimental) system("mdadm --detail " + md_dev + " > " + log); ncInterface.showMsgBox("Массив создан: " + ReadFile(log)); deviceCacheActual = false; // TODO: sync details, and so on - be more informative, don't dump raw stat to user return 0; }
string Dialog::execMenu(string header, unsigned int height, unsigned int width, unsigned int menu_height, vector<TagPair> menuItems, string default_item) { if (menuItems.empty()) { mError("Empty item list"); return ""; } string tmp_file = get_tmp_file(); string def_item; if (!default_item.empty()) { for (unsigned int i=0; i<menuItems.size(); i++) { if (menuItems[i].tag==default_item) { def_item = "--default-item \"" + default_item + "\""; printf("set to %s\n", def_item.c_str()); } } if (def_item.empty()) { mError("No such item " + default_item + ", using defaults"); sleep(1); } } string exec_str = dialog + " " + def_item + " --menu \"" + header + "\" " + IntToStr(height) + " " + IntToStr(width) + " " + IntToStr(menu_height); for (unsigned int i=0; i<menuItems.size(); i++) { exec_str += " \"" + menuItems[i].tag + "\" \"" + menuItems[i].value+"\""; } exec_str += " 2>"+tmp_file; system(exec_str.c_str()); string ret = getReturnValue(tmp_file); unlink(tmp_file.c_str()); return ret; }
bool Ext2::resize(PedPartition *partition, PedSector size, string *results) { if (!can_resize) return false; string output = get_tmp_file(); return (system("resize2fs " + string(ped_partition_get_path(partition)) + IntToStr((long long) (size*partition->disk->dev->sector_size)/1024) + "K")==0); }