/* 对给定两文件的绝对路径, 将两文件中相同的行去掉,输入文件分别备份 */ void WWidget::deal_with_file(const QString fir_path, const QString sec_path) { /* 备份文件 */ const QString fir_bak = backup_file(fir_path); const QString sec_bak = backup_file(sec_path); QHash<QString, bool> str_hash; QString fir_line, sec_line; QFile fir_in(fir_bak), sec_in(sec_bak); QTextStream fir_ts(&fir_in), sec_ts(&sec_in); std::cout << "dealing with the files, please wait...." << std::endl; std::cout << "fir = " << fir_bak.toStdString() << std::endl; std::cout << "sec = " << sec_bak.toStdString() << std::endl; if (!fir_in.open(QIODevice::ReadOnly | QIODevice::Text)) { std::cout << "can not open file:" << fir_bak.toStdString() << std::endl; return; } if (!sec_in.open(QIODevice::ReadOnly | QIODevice::Text)) { std::cout << "can not open file:" << sec_bak.toStdString() << std::endl; return; } /* 寻找相同的行, 保存于str_hash中 */ while (!fir_ts.atEnd()) { sec_ts.seek(0); fir_line = fir_ts.readLine(); while (!sec_ts.atEnd()) { sec_line = sec_ts.readLine(); /* 相等 */ if (QString::compare(fir_line, sec_line) == 0) { str_hash[fir_line] = true; } } } if (str_hash.size() <= 0) { return; /* do not exist the same line! */ } QFile::remove(fir_path); QFile::remove(sec_path); reflesh_file(fir_path, fir_bak, str_hash); reflesh_file(sec_path, sec_bak, str_hash); }
/* * make a backup of users .newsrc in case of the bogie man */ void backup_newsrc( void) { char dirbuf[PATH_LEN]; char filebuf[PATH_LEN]; struct stat statbuf; #ifdef NNTP_ABLE if (read_news_via_nntp && !read_saved_news && nntp_tcp_port != IPPORT_NNTP) snprintf(filebuf, sizeof(filebuf), "%s:%d", nntp_server, nntp_tcp_port); else #endif /* NNTP_ABLE */ { STRCPY(filebuf, nntp_server); } JOINPATH(dirbuf, rcdir, filebuf); joinpath(filebuf, dirbuf, OLDNEWSRC_FILE); if (-1 == stat(dirbuf, &statbuf)) { if (-1 == my_mkdir(dirbuf, (mode_t) (S_IRWXU))) /* Can't create directory: Fall back on Homedir */ joinpath(filebuf, homedir, OLDNEWSRC_FILE); } if (!backup_file(newsrc, filebuf)) error_message(_(txt_filesystem_full_backup), NEWSRC_FILE); }
std::ostream * colvarproxy_io::output_stream(std::string const &output_name, std::ios_base::openmode mode) { if (cvm::debug()) { cvm::log("Using colvarproxy::output_stream()\n"); } std::list<std::ostream *>::iterator osi = output_files.begin(); std::list<std::string>::iterator osni = output_stream_names.begin(); for ( ; osi != output_files.end(); osi++, osni++) { if (*osni == output_name) { return *osi; } } if (!(mode & (std::ios_base::app | std::ios_base::ate))) { backup_file(output_name); } std::ofstream *os = new std::ofstream(output_name.c_str(), mode); if (!os->is_open()) { cvm::error("Error: cannot write to file/channel \""+output_name+"\".\n", FILE_ERROR); return NULL; } output_stream_names.push_back(output_name); output_files.push_back(os); return os; }
bool FileManager::ReplaceFile(const wxString& old_file, const wxString& new_file) { wxString backup_file(old_file + _T(".backup")); // rename the old file into a backup file if(wxRenameFile(old_file, backup_file)) { // now rename the new created (temporary) file to the "old" filename if(wxRenameFile(new_file, old_file)) { if (Manager::IsAppShuttingDown()) { // app shut down, forget delayed deletion wxRemoveFile(backup_file); } else { // issue a delayed deletion of the back'd up (old) file delayedDeleteThread.Queue(new DelayedDelete(backup_file)); } return true; } else { // if final rename operation failed, restore the old file from backup wxRenameFile(backup_file, old_file); } } return false; }
void ZSolveAPI<T>::compute() { check_consistency(); Algorithm <T>* algorithm; DefaultController <T> * controller; std::ofstream* log_file = 0; if (options.loglevel () > 0) { std::string log_name = options.project () + ".log"; log_file = new std::ofstream (log_name.c_str(), options.resume () ? std::ios::out | std::ios::app : std::ios::out); } controller = new DefaultController <T> (&std::cout, log_file, options); std::string backup_name = options.project () + ".backup"; std::ifstream backup_file (backup_name.c_str()); if (backup_file.good () && !options.resume ()) { throw IOException ("Found backup file. Please restart with -r or delete backup file!\n", false); } if (options.resume()) { if (!backup_file.good()) { throw IOException ("Started in resume mode, but no backup file found!\n", false); } backup_file >> options; algorithm = new Algorithm <T> (backup_file, controller); } else if (mat) {
static int backup_epoch(uint32_t epoch) { char path[PATH_MAX]; char suffix[256]; struct timeval tv; struct tm tm; gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm); strftime(suffix, sizeof(suffix), "%Y-%m-%d_%H%M%S", &tm); snprintf(path, sizeof(path), "%s%08u", epoch_path, epoch); return backup_file(path, suffix); }
bool uninstallFont(const QString &file_path) { qDebug() << "Uninstalling font" << file_path; if (file_path.isEmpty()) return true; if (not QFileInfo(file_path).exists()) return true; QFile file(file_path); if (file.exists()) { if (Settings().saveUninstalledFonts()) { try { Path::ensurePath(Settings().fontBackupFolder()); } catch (pathEnsureError *e) { return false; } QString backup_file_path = fontBackupPath(file_path); qDebug() << "Backing up font file" << file_path << "to" << backup_file_path; QFile backup_file(backup_file_path); if (backup_file.exists()) { if (not backup_file.remove()) { qDebug() << "Error removing old backup font file" << backup_file_path; return false; } } if (not file.copy(backup_file_path)) { qDebug() << "Failed backing up font file to" << backup_file_path; return false; } } if (not file.remove()) qDebug() << "Error deleting font file" << file_path; return false; } return true; }
static void act_save(void) { static int backed_up = FALSE; if (!backed_up) { if (!backup_file()) { display_beep(); strcpy (message, "Unable to back up file!"); return; } backed_up = TRUE; } if (!save_file()) { display_beep(); strcpy (message, "Unable to save file!"); return; } modified = FALSE; }
int restoreFromDump(mysqlpp::Connection* conn, const wxString& filename) { int toRet = 1; wxFFile backup_file(filename); if(backup_file.IsOpened()) { wxString fileContent; backup_file.ReadAll(&fileContent); // wxMessageBox(fileContent); //wxRegEx comments(_("--[^x22\\x27].*"), wxRE_NEWLINE); // \x22[^\x22]*\x22|\x27[^\x27]*\x27|/\*.*?\*/|(\#|--)([^\x22\x27]*?)$ - groups 1 and 2 wxRegEx comments(_("\\x22\\x27[^\\x22\\x27]*\\x22\\x27|/\\*.*?\\*/|(\\#|--)[^\\x22\\x27]*?$"), wxRE_ADVANCED|wxRE_NEWLINE); //wxRegEx comments(_("\\x22[^\\x22]*\\x22|\\x27[^\\x27]*\\x27|/\\*.*?\\*/|(\\#|--)([^\\x22\\x27]*?)$"), wxRE_ADVANCED|wxRE_NEWLINE); comments.ReplaceAll(&fileContent, _("")); //comments.ReplaceAll(&fileContent, _("*\\2")); fileContent.Trim(); wxRegEx semicolons(_("(?m);\\s*$"), wxRE_ADVANCED|wxRE_NEWLINE); semicolons.ReplaceAll(&fileContent, _("^")); //in the future take care of that - if ^ symbol is inside the satatement //wxMessageBox(fileContent); wxStringTokenizer tkz(fileContent, _("^")); while ( tkz.HasMoreTokens() ) { wxString sql_query = tkz.GetNextToken().Trim(false); //wxMessageBox(sql_query); mysqlpp::Query query = conn->query(); query << wx2std(sql_query, wxConvUI); query.execute(); } } else { wxMessageBox(_T("Failed to open backup file.")); toRet = 0; } return toRet; }
/* backup config and epoch info */ static int backup_store(void) { char suffix[256]; struct timeval tv; struct tm tm; int ret; gettimeofday(&tv, NULL); localtime_r(&tv.tv_sec, &tm); strftime(suffix, sizeof(suffix), "%Y-%m-%d_%H%M%S", &tm); ret = backup_file(config_path, suffix); if (ret < 0) return ret; for_each_epoch(backup_epoch); return 0; }
bool FileSystem::write_file(QString settings) { QFile file("lts.conf"); backup_file(); if(!file.open(QFile::WriteOnly | QFile::Text)) //Check if we can open the lts.conf for writing { qDebug() << "Could not open file for writing" << endl; //Return an error if we can't open it return false; } QTextStream lts_settings(&file); //Open a textstream for inserting things into the file lts_settings << settings; //Write settings into lts.conf file.flush(); //Flush the file contents to ensure everything is written to disk file.close(); qDebug() << "File written successfully." << endl; //Give feedback after writing the file return true; }
int move_file(const char *from, const char *to) { int fromfd; ssize_t i; /* to stdout? */ if (strEQ(to, "-")) { #ifdef DEBUGGING if (debug & 4) say("Moving %s to stdout.\n", from); #endif fromfd = open(from, O_RDONLY); if (fromfd < 0) pfatal("internal error, can't reopen %s", from); while ((i = read(fromfd, buf, buf_size)) > 0) if (write(STDOUT_FILENO, buf, i) != i) pfatal("write failed"); close(fromfd); return 0; } if (backup_file(to) < 0) { say("Can't backup %s, output is in %s: %s\n", to, from, strerror(errno)); return -1; } #ifdef DEBUGGING if (debug & 4) say("Moving %s to %s.\n", from, to); #endif if (rename(from, to) < 0) { if (errno != EXDEV || copy_file(from, to) < 0) { say("Can't create %s, output is in %s: %s\n", to, from, strerror(errno)); return -1; } } return 0; }
/* * backup_work * * Start the NDMP backup (V2 only). */ int backup_work(char *bk_path, tlm_job_stats_t *job_stats, ndmp_run_args_t *np, tlm_commands_t *commands, ndmp_lbr_params_t *nlp) { struct full_dir_info dir_info; /* the blob to push/pop with cstack_t */ struct full_dir_info *t_dir_info, *p_dir_info; struct stat64 ret_attr; /* attributes of current file name */ fs_fhandle_t ret_fh; char *first_name; /* where the first name is located */ char *dname; int erc; int retval; cstack_t *stk; unsigned long fileid; tlm_acls_t tlm_acls; int dname_size; longlong_t fsize; bk_selector_t bks; tlm_cmd_t *local_commands; long dpos; NDMP_LOG(LOG_DEBUG, "nr_chkpnted %d nr_ldate: %u bk_path: \"%s\"", NLP_ISCHKPNTED(nlp), nlp->nlp_ldate, bk_path); /* Get every name in this directory */ dname = ndmp_malloc(TLM_MAX_PATH_NAME); if (dname == NULL) return (-ENOMEM); local_commands = commands->tcs_command; retval = 0; (void) memset(&bks, 0, sizeof (bks)); bks.bs_cookie = (void *)nlp; bks.bs_level = nlp->nlp_clevel; bks.bs_ldate = nlp->nlp_ldate; bks.bs_fn = timecmp; /* * should we skip the whole thing? */ if (tlm_is_excluded("", bk_path, np->nr_excls)) { NDMP_LOG(LOG_DEBUG, "%s excluded", bk_path); free(dname); return (0); } /* * Search for the top-level file-directory */ if (NLP_ISCHKPNTED(nlp)) { first_name = np->nr_chkp_nm; (void) strlcpy(first_name, bk_path, TLM_MAX_PATH_NAME); } else { first_name = tlm_build_snapshot_name(bk_path, np->nr_chkp_nm, nlp->nlp_jstat->js_job_name); } (void) memset(&ret_fh, 0, sizeof (ret_fh)); erc = fs_getstat(first_name, &ret_fh, &ret_attr); if (erc != 0) { NDMP_LOG(LOG_ERR, "Path %s not found.", first_name); free(dname); return (-EINVAL); } if ((stk = cstack_new()) == NULL) { free(dname); NDMP_LOG(LOG_DEBUG, "cstack_new failed"); return (-ENOMEM); } (void) strlcpy(dir_info.fd_dir_name, first_name, TLM_MAX_PATH_NAME); (void) memcpy(&dir_info.fd_dir_fh, &ret_fh, sizeof (fs_fhandle_t)); p_dir_info = dup_dir_info(&dir_info); /* * Push the first name onto the stack so that we can pop it back * off as part of the normal cycle */ if (cstack_push(stk, p_dir_info, 0)) { free(dname); free(p_dir_info); cstack_delete(stk); NDMP_LOG(LOG_DEBUG, "cstack_push failed"); return (-ENOMEM); } (void) memset(&tlm_acls, 0, sizeof (tlm_acls)); /* * Did NDMP create a checkpoint? */ if (NLP_ISCHKPNTED(nlp) || fs_is_rdonly(bk_path)) { tlm_acls.acl_checkpointed = FALSE; } else { /* Use the checkpoint created by NDMP */ tlm_acls.acl_checkpointed = TRUE; } /* * This is level-backup. It never resets the archive bit. */ tlm_acls.acl_clear_archive = FALSE; NDMP_LOG(LOG_DEBUG, "acls.chkpnt: %c acls.clear_arcbit: %c", NDMP_YORN(tlm_acls.acl_checkpointed), NDMP_YORN(tlm_acls.acl_clear_archive)); while (commands->tcs_reader == TLM_BACKUP_RUN && local_commands->tc_reader == TLM_BACKUP_RUN && cstack_pop(stk, (void **)&p_dir_info, 0) == 0) { if (NLP_ISCHKPNTED(nlp)) (void) strlcpy(np->nr_unchkp_nm, p_dir_info->fd_dir_name, TLM_MAX_PATH_NAME); else (void) tlm_remove_checkpoint(p_dir_info->fd_dir_name, np->nr_unchkp_nm); (void) backup_dir(np->nr_unchkp_nm, &tlm_acls, local_commands, job_stats, &bks); while (commands->tcs_reader == TLM_BACKUP_RUN && local_commands->tc_reader == TLM_BACKUP_RUN) { dname_size = TLM_MAX_PATH_NAME - 1; NDMP_LOG(LOG_DEBUG, "dir_name: %s", p_dir_info->fd_dir_name); (void) memset(&ret_fh, 0, sizeof (ret_fh)); erc = fs_readdir(&p_dir_info->fd_dir_fh, p_dir_info->fd_dir_name, &dpos, dname, &dname_size, &ret_fh, &ret_attr); if (erc == 0) { fileid = ret_fh.fh_fid; } else { NDMP_LOG(LOG_DEBUG, "Filesystem readdir in [%s]", p_dir_info->fd_dir_name); retval = -ENOENT; break; } /* an empty name size marks the end of the list */ if (dname_size == 0) break; dname[dname_size] = '\0'; NDMP_LOG(LOG_DEBUG, "dname: \"%s\"", dname); /* * If name refers to a directory, push its file * handle onto the stack (skip "." and ".."). */ if (rootfs_dot_or_dotdot(dname)) { fileid = 0; continue; } /* * Skip the: * non-dir entries which should not be backed up * Or * dir-type entries which have have nothing under * their hierarchy to be backed up. */ if (!dbm_getone(nlp->nlp_bkmap, (u_longlong_t)fileid)) { NDMP_LOG(LOG_DEBUG, "Skipping %s/%s", p_dir_info->fd_dir_name, dname); fileid = 0; continue; } if (tlm_is_excluded(np->nr_unchkp_nm, dname, np->nr_excls)) { fileid = 0; continue; } if (S_ISDIR(ret_attr.st_mode)) { /* * only directories get pushed onto this stack, * so we do not have to test for regular files. */ t_dir_info = tlm_new_dir_info(&ret_fh, p_dir_info->fd_dir_name, dname); if (t_dir_info == NULL) { NDMP_LOG(LOG_DEBUG, "While backing up [%s][%s]", p_dir_info->fd_dir_name, dname); } else if (cstack_push(stk, t_dir_info, 0) != 0) { NDMP_LOG(LOG_DEBUG, "No enough memory stack_push"); retval = -ENOMEM; break; } } else if (S_ISREG(ret_attr.st_mode) || S_ISLNK(ret_attr.st_mode)) { fsize = backup_file(np->nr_unchkp_nm, dname, &tlm_acls, commands, local_commands, job_stats, &bks); if (fsize >= 0) { job_stats->js_files_so_far++; job_stats->js_bytes_total += fsize; } else job_stats->js_errors++; fileid = 0; } } fileid = 0; free(p_dir_info); if (retval != 0) break; } free(dname); while (cstack_pop(stk, (void **)&p_dir_info, 0) == 0) { free(p_dir_info); } cstack_delete(stk); return (retval); }
// ************************************************** // // // Function Name: main // // Description: // // // // // ************************************************** // int main(int argc, char *argv[]) { int listen_sock, client_sock = INVALID_HANDLE; char buffer[BUFFER_SIZE + 1] = {0}; // +1 for safety int n = 0, buf_size = 0; int fp_fwlog = INVALID_HANDLE; int fp_bkplog = INVALID_HANDLE; char filename[MAX_PATH + 1] = {0}; // +1 for safety char filename_prev[MAX_PATH + 1] = {0}; // +1 for safety uint max_file_size = MAX_FILE_SIZE; struct stat st; pthread_t thread; if (argc < 3) { fprintf(stderr,"Usage: ./logProxy [listen port] [log file] [backup directory]\n"); exit(EXIT_FAILURE); } // Max file size is an optional value if(argc > 4) { max_file_size = atol(argv[4]); } listen_sock = create_listen_socket(atoi(argv[1])); // // If we arrive here the listen socket was created successfully, otherwise we would have exited the process // // Create the backup file names strncpy(filename,argv[3], MAX_PATH - sizeof(FILE_NAME)); strncpy(filename_prev,argv[3], MAX_PATH - sizeof(FILE_NAME_PREV)); strcat(filename, FILE_NAME); strcat(filename_prev, FILE_NAME_PREV); fp_bkplog = create_file(filename); // Create the core_dump thread //pthread_create(&thread, NULL, (void *) &core_dump_thread, NULL); // Main Loop while(1) { // Check on the client connection status if ( (socket_enabled == 1) && (client_sock == INVALID_HANDLE || socket_connected == 0) ) { client_sock = accept_client(listen_sock); } if(fp_fwlog != INVALID_HANDLE) { // Read the fwlog sysfs file - This is a blocking function buf_size = read_file(fp_fwlog, buffer); if(buf_size == INVALID_HANDLE) { error("driver unloaded: fwlog has been removed"); fp_fwlog = INVALID_HANDLE; continue; } // Create a new file if the log file exceeds the max size stat(filename, &st); if(st.st_size >= max_file_size) { close(fp_bkplog); rename(filename, filename_prev); fp_bkplog = create_file(filename); } // keep alive keep_alive(client_sock); if(buf_size > 0) { // write the log data into the backup file backup_file(fp_bkplog, buffer, buf_size); // Try to send the logs to the remote client send_data(client_sock, buffer, buf_size); } } else { // To prevent high io/cpu usage sleep between attempts sleep(FILE_POLL_INTERVAL); // Try to open the fwlog file fp_fwlog = open_fwlog(fp_fwlog, argv[2]); } } return 0; }
int cwritefile(char *fname, int r0, int c0, int rn, int cn) { register FILE *f; int pipefd[2]; int fildes; int pid; char save[PATHLEN]; char *fn; char *busave; if (*fname == '\0') fname = &curfile[0]; fn = fname; while (*fn && (*fn == ' ')) /* Skip leading blanks */ fn++; if (*fn == '|') { error("Can't have encrypted pipe"); return (-1); } (void) strcpy(save, fname); busave = findhome(save); #ifdef DOBACKUPS if (!backup_file(busave) && (yn_ask("Could not create backup copy, Save anyway?: (y,n)") != 1)) return (0); #endif if ((fildes = open (busave, O_TRUNC|O_WRONLY|O_CREAT, 0600)) < 0) { error("Can't create file \"%s\"", save); return (-1); } if (pipe(pipefd) < 0) { error("Can't make pipe to child\n"); return (-1); } if (KeyWord[0] == '\0') { deraw(1); (void) strcpy(KeyWord, getpass("Enter key:")); goraw(); } if ((pid=fork()) == 0) { /* if child */ (void) close(0); /* close stdin */ (void) close(1); /* close stdout */ (void) close(pipefd[1]); /* close pipe output */ (void) dup(pipefd[0]); /* connect to pipe input */ (void) dup(fildes); /* standard out to file */ (void) fprintf(stderr, " "); (void) execl(CRYPT_PATH, "crypt", KeyWord, 0); (void) fprintf(stderr, "execl(%s, \"crypt\", %s, 0) in cwritefile() failed", CRYPT_PATH, KeyWord); exit (-127); } else { /* else parent */ (void) close(fildes); (void) close(pipefd[0]); /* close pipe input */ f = fdopen(pipefd[1], "w"); if (f == 0) { (void) kill(pid, -9); error("Can't fdopen file \"%s\"", save); (void) close(pipefd[1]); return (-1); } } write_fd(f, r0, c0, rn, cn); (void) fclose(f); (void) close(pipefd[1]); while (pid != wait(&fildes)) /**/; (void) strcpy(curfile,save); modflg = 0; error("File \"%s\" written (encrypted).", curfile); return (0); }
int vedit(const char *filename, const char *saveheader, char *bname) { int ch, foo; int lastcharindent = -1; BOOL firstkey = TRUE; char bakfile[PATHLEN]; int old_rows = t_lines, old_columns = t_columns; sethomefile(bakfile, curuser.userid, UFNAME_EDIT); if ((saveheader || uinfo.mode == EDITPLAN || uinfo.mode == EDITBMWEL) && isfile(bakfile) /* lthuang */ #ifdef GUEST && strcmp(curuser.userid, GUEST) #endif ) { clear(); outs(_msg_edit_8); if (getkey() != '2') mycp(bakfile, filename); } if (!isfile(filename)) unlink(bakfile); if (saveheader) do_article_sig(filename); read_file(filename); top_of_win = firstline; currline = firstline; curr_window_line = 0; currpnt = 0; ansi_mode = FALSE; clear(); display_buffer(); move(curr_window_line, currpnt); while ((ch = getkey()) != EOF) { if (firstkey) { firstkey = FALSE; show_help_msg(); } if (talkrequest) /* lthuang */ { backup_file(bakfile); talkreply(); pressreturn(); ch = CTRL('G'); /* redraw screen */ } else if (msqrequest) /* lthuang */ { msqrequest = FALSE; msq_reply(); #if 0 ch = CTRL('G'); #endif } if (old_rows != t_lines || old_columns != t_columns) { static const char *msg_resized = "[1;34;47m螢幕大小已改變, 按(Ctrl-G)回到頁首![m"; old_rows = t_lines; old_columns = t_columns; top_of_win = firstline; currline = top_of_win; curr_window_line = 0; currpnt = 0; shift = 0; redraw_everything = TRUE; move(t_lines / 2, (t_columns - strlen(msg_resized)) / 2); outs(msg_resized); while (getkey() != CTRL('G')); } else if (ch < 0x100 && isprint2(ch)) { insert_char(ch); lastcharindent = -1; } else switch (ch) { case KEY_UP: if (lastcharindent == -1) lastcharindent = currpnt; if (!currline->prev) { bell(); break; } curr_window_line--; currline = currline->prev; currpnt = (currline->len > lastcharindent) ? lastcharindent : currline->len; break; case KEY_DOWN: if (lastcharindent == -1) lastcharindent = currpnt; if (!currline->next) { bell(); break; } curr_window_line++; currline = currline->next; currpnt = (currline->len > lastcharindent) ? lastcharindent : currline->len; break; default: lastcharindent = -1; switch (ch) { case CTRL('T'): top_of_win = back_line(lastline, b_lines - 2); currline = lastline; curr_window_line = getlineno(); currpnt = 0; redraw_everything = TRUE; break; case CTRL('S'): top_of_win = firstline; currline = top_of_win; curr_window_line = 0; currpnt = 0; redraw_everything = TRUE; break; case '\t': do { insert_char(' '); } while (currpnt & 0x7); break; case CTRL('U'): case CTRL('V'): insert_char(0x1b); break; case CTRL('C'): insert_char(0x1b); insert_char('['); insert_char('m'); break; case KEY_RIGHT: case CTRL('F'): if (currline->len == currpnt) { if (!currline->next) bell(); else { currpnt = 0; curr_window_line++; currline = currline->next; } } else currpnt++; break; case KEY_LEFT: case CTRL('B'): if (currpnt == 0) { if (!currline->prev) bell(); else { currline = currline->prev; currpnt = currline->len; curr_window_line--; } } else currpnt--; break; case CTRL('G'): clear(); redraw_everything = TRUE; break; case CTRL('Z'): vedit_help(); break; case KEY_PGUP: case CTRL('P'): top_of_win = back_line(top_of_win, b_lines - 2); currline = top_of_win; currpnt = 0; curr_window_line = 0; redraw_everything = TRUE; break; case KEY_PGDN: case CTRL('N'): top_of_win = forward_line(top_of_win, b_lines - 2); currline = top_of_win; currpnt = 0; curr_window_line = 0; redraw_everything = TRUE; break; case KEY_HOME: case CTRL('A'): currpnt = 0; break; case KEY_END: case CTRL('E'): currpnt = currline->len; break; case CTRL('R'): #if 0 backup_file(bakfile); #endif msq_reply(); #if 0 redraw_everything = TRUE; /* lthuang */ #endif break; case CTRL('Q'): ansi_mode = TRUE; display_buffer(); pressreturn(); ansi_mode = FALSE; display_buffer(); break; case CTRL('X'): case CTRL('W'): backup_file(bakfile); clear(); foo = write_file(filename, saveheader, bname); if (foo == BACKUP_EDITING) return foo; else if (foo != KEEP_EDITING) { unlink(bakfile); return foo; } redraw_everything = TRUE; /* lthuang */ break; case '\r': case '\n': split(currline, currpnt); /* lthuang: reduce the times of backup */ if (total_num_of_line % 7 == 0) backup_file(bakfile); break; case '\177': case CTRL('H'): if (currpnt == 0) { if (!currline->prev) { bell(); break; } curr_window_line--; currline = currline->prev; currpnt = currline->len; if (*killsp(currline->next->data) == '\0') { delete_line(currline->next); redraw_everything = TRUE; } else { join_currline(); } if (curr_window_line == -1) { curr_window_line = 0; top_of_win = currline; rscroll(); } break; } currpnt--; delete_char(); break; case CTRL('D'): if (currline->len == currpnt) join_currline(); else delete_char(); break; case CTRL('Y'): currpnt = 0; currline->len = 0; delete_currline(); break; case CTRL('K'): if (currline->len == 0) delete_currline(); else if (currline->len == currpnt) join_currline(); else { currline->len = currpnt; currline->data[currpnt] = '\0'; } break; default: break; } break; } if (curr_window_line == -1) { curr_window_line = 0; if (!top_of_win->prev) { indigestion(6); bell(); } else { top_of_win = top_of_win->prev; rscroll(); } } if (curr_window_line == t_lines - 1) { curr_window_line = t_lines - 2; if (!top_of_win->next) { indigestion(7); bell(); } else { top_of_win = top_of_win->next; scroll(); } } /* lthuang: 99/07 */ if (currpnt - shift >= t_columns - 1) { shift = (currpnt / (t_columns - 1)) * (t_columns - 1) - 1; redraw_everything = TRUE; } else if (currpnt - shift < 0) { shift = 0; redraw_everything = TRUE; } if (redraw_everything) { display_buffer(); redraw_everything = FALSE; } else { move(curr_window_line, 0); clrtoeol(); /* lthuang */ vedit_outs(currline->data); } move(curr_window_line, currpnt - shift); /* lthuang: 99/07 */ } if (uinfo.mode == POSTING || uinfo.mode == SMAIL) unlink(filename); return ABORT_EDITING; }
gboolean ifnet_flush_to_file (const char *config_file, gchar **out_backup) { GIOChannel *channel; GError **error = NULL; gpointer key, value, name, network; GHashTableIter iter, iter_network; GList *list_iter; gchar *out_line = NULL; gsize bytes_written; gboolean result = FALSE; gchar *backup; if (!net_parser_data_changed) return TRUE; if (!conn_table || !global_settings_table) return FALSE; backup = backup_file (config_file); channel = g_io_channel_new_file (config_file, "w", NULL); if (!channel) { nm_log_warn (LOGD_SETTINGS, "Can't open file %s for writing", config_file); g_free (backup); return FALSE; } g_hash_table_iter_init (&iter, global_settings_table); nm_log_info (LOGD_SETTINGS, "Writing to %s", config_file); g_io_channel_write_chars (channel, "#Generated by NetworkManager\n" "###### Global Configuration ######\n", -1, &bytes_written, error); /* Writing global data */ while (g_hash_table_iter_next (&iter, &key, &value)) { out_line = g_strdup_printf ("%s=\"%s\"\n", (gchar *) key, (gchar *) value); g_io_channel_write_chars (channel, out_line, -1, &bytes_written, error); if (bytes_written == 0 || (error && *error)) break; g_free (out_line); } if (error && *error) { nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message); goto done; } /* Writing connection data */ g_io_channel_write_chars (channel, "\n###### Connection Configuration ######\n", -1, &bytes_written, error); g_hash_table_iter_init (&iter, conn_table); while (g_hash_table_iter_next (&iter, &name, &network)) { g_hash_table_iter_init (&iter_network, (GHashTable *) network); g_io_channel_write_chars (channel, "#----------------------------------\n", -1, &bytes_written, error); while (g_hash_table_iter_next (&iter_network, &key, &value)) { if (!g_str_has_prefix ((gchar *) key, "name") && !g_str_has_prefix ((gchar *) key, "type")) { /* These keys contain brackets */ if (strcmp ((gchar *) key, "config") == 0 || strcmp ((gchar *) key, "routes") == 0 || strcmp ((gchar *) key, "pppd") == 0 || strcmp ((gchar *) key, "chat") == 0) format_ips (value, &out_line, (gchar *) key, (gchar *) name); else out_line = g_strdup_printf ("%s_%s=\"%s\"\n", (gchar *) key, (gchar *) name, (gchar *) value); g_io_channel_write_chars (channel, out_line, -1, &bytes_written, error); if (bytes_written == 0 || (error && *error)) break; g_free (out_line); } } } if (error && *error) { nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message); goto done; } /* Writing reserved functions */ if (functions_list) { g_io_channel_write_chars (channel, "\n###### Reserved Functions ######\n", -1, &bytes_written, error); /* Writing functions */ for (list_iter = functions_list; list_iter; list_iter = g_list_next (list_iter)) { out_line = g_strdup_printf ("%s\n", (gchar *) list_iter->data); g_io_channel_write_chars (channel, out_line, -1, &bytes_written, error); if (bytes_written == 0 || (error && *error)) break; g_free (out_line); } if (error && *error) { nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message); goto done; } } g_io_channel_flush (channel, error); if (error && *error) { nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message); goto done; } result = TRUE; net_parser_data_changed = FALSE; done: if (result && out_backup) *out_backup = backup; else g_free (backup); g_io_channel_shutdown (channel, FALSE, NULL); g_io_channel_unref (channel); return result; }
int sysdb_check_upgrade_02(struct sss_domain_info *domains, const char *db_path) { TALLOC_CTX *tmp_ctx = NULL; struct ldb_context *ldb; char *ldb_file; struct sysdb_ctx *sysdb; struct sss_domain_info *dom; struct ldb_message_element *el; struct ldb_message *msg; struct ldb_result *res; struct ldb_dn *verdn; const char *version = NULL; bool do_02_upgrade = false; bool ctx_trans = false; int ret; tmp_ctx = talloc_new(NULL); if (!tmp_ctx) { return ENOMEM; } ret = sysdb_get_db_file(tmp_ctx, "local", "UPGRADE", db_path, &ldb_file); if (ret != EOK) { goto exit; } ret = sysdb_ldb_connect(tmp_ctx, ldb_file, &ldb); if (ret != EOK) { DEBUG(1, ("sysdb_ldb_connect failed.\n")); return ret; } verdn = ldb_dn_new(tmp_ctx, ldb, SYSDB_BASE); if (!verdn) { ret = EIO; goto exit; } ret = ldb_search(ldb, tmp_ctx, &res, verdn, LDB_SCOPE_BASE, NULL, NULL); if (ret != LDB_SUCCESS) { ret = EIO; goto exit; } if (res->count > 1) { ret = EIO; goto exit; } if (res->count == 1) { el = ldb_msg_find_element(res->msgs[0], "version"); if (el) { if (el->num_values != 1) { ret = EINVAL; goto exit; } version = talloc_strndup(tmp_ctx, (char *)(el->values[0].data), el->values[0].length); if (!version) { ret = ENOMEM; goto exit; } if (strcmp(version, SYSDB_VERSION) == 0) { /* all fine, return */ ret = EOK; goto exit; } DEBUG(4, ("Upgrading DB from version: %s\n", version)); if (strcmp(version, SYSDB_VERSION_0_1) == 0) { /* convert database */ ret = sysdb_upgrade_01(ldb, &version); if (ret != EOK) goto exit; } if (strcmp(version, SYSDB_VERSION_0_2) == 0) { /* need to convert database to split files */ do_02_upgrade = true; } } } if (!do_02_upgrade) { /* not a v2 upgrade, return and let the normal code take over any * further upgrade */ ret = EOK; goto exit; } /* == V2->V3 UPGRADE == */ DEBUG(0, ("UPGRADING DB TO VERSION %s\n", SYSDB_VERSION_0_3)); /* ldb uses posix locks, * posix is stupid and kills all locks when you close *any* file * descriptor associated to the same file. * Therefore we must close and reopen the ldb file here */ /* == Backup and reopen ldb == */ /* close */ talloc_zfree(ldb); /* backup*/ ret = backup_file(ldb_file, 0); if (ret != EOK) { goto exit; } /* reopen */ ret = sysdb_ldb_connect(tmp_ctx, ldb_file, &ldb); if (ret != EOK) { DEBUG(1, ("sysdb_ldb_connect failed.\n")); return ret; } /* open a transaction */ ret = ldb_transaction_start(ldb); if (ret != LDB_SUCCESS) { DEBUG(1, ("Failed to start ldb transaction! (%d)\n", ret)); ret = EIO; goto exit; } /* == Upgrade contents == */ for (dom = domains; dom; dom = dom->next) { struct ldb_dn *domain_dn; struct ldb_dn *users_dn; struct ldb_dn *groups_dn; int i; /* skip local */ if (strcasecmp(dom->provider, "local") == 0) { continue; } /* create new dom db */ ret = sysdb_domain_init_internal(tmp_ctx, dom, db_path, false, &sysdb); if (ret != EOK) { goto done; } ret = ldb_transaction_start(sysdb->ldb); if (ret != LDB_SUCCESS) { DEBUG(1, ("Failed to start ldb transaction! (%d)\n", ret)); ret = EIO; goto done; } ctx_trans = true; /* search all entries for this domain in local, * copy them all in the new database, * then remove them from local */ domain_dn = ldb_dn_new_fmt(tmp_ctx, sysdb->ldb, SYSDB_DOM_BASE, sysdb->domain->name); if (!domain_dn) { ret = ENOMEM; goto done; } ret = ldb_search(ldb, tmp_ctx, &res, domain_dn, LDB_SCOPE_SUBTREE, NULL, NULL); if (ret != LDB_SUCCESS) { ret = EIO; goto done; } users_dn = ldb_dn_new_fmt(tmp_ctx, sysdb->ldb, SYSDB_TMPL_USER_BASE, sysdb->domain->name); if (!users_dn) { ret = ENOMEM; goto done; } groups_dn = ldb_dn_new_fmt(tmp_ctx, sysdb->ldb, SYSDB_TMPL_GROUP_BASE, sysdb->domain->name); if (!groups_dn) { ret = ENOMEM; goto done; } for (i = 0; i < res->count; i++) { struct ldb_dn *orig_dn; msg = res->msgs[i]; /* skip pre-created congtainers */ if ((ldb_dn_compare(msg->dn, domain_dn) == 0) || (ldb_dn_compare(msg->dn, users_dn) == 0) || (ldb_dn_compare(msg->dn, groups_dn) == 0)) { continue; } /* regenerate the DN against the new ldb as it may have different * casefolding rules (example: name changing from case insensitive * to case sensitive) */ orig_dn = msg->dn; msg->dn = ldb_dn_new(msg, sysdb->ldb, ldb_dn_get_linearized(orig_dn)); if (!msg->dn) { ret = ENOMEM; goto done; } ret = ldb_add(sysdb->ldb, msg); if (ret != LDB_SUCCESS) { DEBUG(0, ("WARNING: Could not add entry %s," " to new ldb file! (%d [%s])\n", ldb_dn_get_linearized(msg->dn), ret, ldb_errstring(sysdb->ldb))); } ret = ldb_delete(ldb, orig_dn); if (ret != LDB_SUCCESS) { DEBUG(0, ("WARNING: Could not remove entry %s," " from old ldb file! (%d [%s])\n", ldb_dn_get_linearized(orig_dn), ret, ldb_errstring(ldb))); } } /* now remove the basic containers from local */ /* these were optional so debug at level 9 in case * of failure just for tracing */ ret = ldb_delete(ldb, groups_dn); if (ret != LDB_SUCCESS) { DEBUG(9, ("WARNING: Could not remove entry %s," " from old ldb file! (%d [%s])\n", ldb_dn_get_linearized(groups_dn), ret, ldb_errstring(ldb))); } ret = ldb_delete(ldb, users_dn); if (ret != LDB_SUCCESS) { DEBUG(9, ("WARNING: Could not remove entry %s," " from old ldb file! (%d [%s])\n", ldb_dn_get_linearized(users_dn), ret, ldb_errstring(ldb))); } ret = ldb_delete(ldb, domain_dn); if (ret != LDB_SUCCESS) { DEBUG(9, ("WARNING: Could not remove entry %s," " from old ldb file! (%d [%s])\n", ldb_dn_get_linearized(domain_dn), ret, ldb_errstring(ldb))); } ret = ldb_transaction_commit(sysdb->ldb); if (ret != LDB_SUCCESS) { DEBUG(1, ("Failed to commit ldb transaction! (%d)\n", ret)); ret = EIO; goto done; } ctx_trans = false; talloc_zfree(domain_dn); talloc_zfree(groups_dn); talloc_zfree(users_dn); talloc_zfree(res); } /* conversion done, upgrade version number */ msg = ldb_msg_new(tmp_ctx); if (!msg) { ret = ENOMEM; goto done; } msg->dn = ldb_dn_new(tmp_ctx, ldb, SYSDB_BASE); if (!msg->dn) { ret = ENOMEM; goto done; } ret = ldb_msg_add_empty(msg, "version", LDB_FLAG_MOD_REPLACE, NULL); if (ret != LDB_SUCCESS) { ret = ENOMEM; goto done; } ret = ldb_msg_add_string(msg, "version", SYSDB_VERSION_0_3); if (ret != LDB_SUCCESS) { ret = ENOMEM; goto done; } ret = ldb_modify(ldb, msg); if (ret != LDB_SUCCESS) { ret = sysdb_error_to_errno(ret); goto done; } ret = ldb_transaction_commit(ldb); if (ret != LDB_SUCCESS) { DEBUG(1, ("Failed to commit ldb transaction! (%d)\n", ret)); ret = EIO; goto exit; } ret = EOK; done: if (ret != EOK) { if (ctx_trans) { ret = ldb_transaction_cancel(sysdb->ldb); if (ret != LDB_SUCCESS) { DEBUG(1, ("Failed to cancel ldb transaction! (%d)\n", ret)); } } ret = ldb_transaction_cancel(ldb); if (ret != LDB_SUCCESS) { DEBUG(1, ("Failed to cancel ldb transaction! (%d)\n", ret)); } } exit: talloc_free(tmp_ctx); return ret; }
int makeDump(mysqlpp::Connection* conn, const wxString& filename) { wxFFile backup_file(filename , _("w")); if(backup_file.IsOpened()) { // backup_file.Write(_("Proverko zapisi fajla")); wxString backup_statement = _("SET SQL_MODE=\"NO_AUTO_VALUE_ON_ZERO\";\n"); mysqlpp::Query query = conn->query(); query << "SHOW TABLES"; mysqlpp::StoreQueryResult res = query.store(); if (res) // list of all tables in our database { mysqlpp::Row row; mysqlpp::StoreQueryResult::size_type i; for (i = 0; i < res.num_rows(); ++i) { row = res[i]; query << "SHOW CREATE TABLE " << std::string(row[0]); mysqlpp::StoreQueryResult res2 = query.store(); if(res2) //statement to create current table (firs value - table name) { row = res2[0]; backup_statement << _("DROP TABLE IF EXISTS `") << std2wx(std::string(row[0]),wxConvUI) << _("`;\n"); backup_statement << std2wx(std::string(row[1]),wxConvUI) << _(";\n"); query << "SELECT * FROM " << std::string(row[0]); mysqlpp::StoreQueryResult res3 = query.store(); if(res3) //data in current table { if(res3.num_rows() > 0) //table is not empty { wxString insert_statement = _("INSERT INTO `") + std2wx(std::string(row[0]), wxConvUI) + _("` ("); for (size_t k = 0; k < res3.field_names()->size(); k++) { insert_statement << _("`") << std2wx(res3.field_name(k), wxConvUI) << _("`"); if(k != res3.field_names()->size() - 1) { insert_statement << _(", "); } } insert_statement << _(") VALUES\n"); for (int h = 0; h < res3.num_rows(); ++h) { row = res3[h]; insert_statement << _("("); for (size_t g = 0; g < res3.field_names()->size(); g++) { mysqlpp::FieldTypes::value_type ft = res3.field_type(g); if(ft.quote_q ()) //need to be quoted { insert_statement << _("'") << std2wx(std::string(row[g]),wxConvUI) << _("'"); } else { insert_statement << std2wx(std::string(row[g]),wxConvUI); } if(g != res3.field_names()->size() - 1) { insert_statement << _(", "); } } insert_statement << _(")"); if(h != res3.num_rows() - 1) { insert_statement << _(",\n"); } } backup_statement << insert_statement << _(";\n"); } } } } backup_file.Write(backup_statement); } return 1; } else { wxMessageBox(_T("Failed to save backup file. Check write permissions.")); return 0; } }
gboolean wpa_flush_to_file (const char *config_file) { GIOChannel *channel; GError **error = NULL; gpointer key, value, ssid, security; GHashTableIter iter, iter_security; gchar *out_line; gsize bytes_written; gboolean result = FALSE; if (!wpa_parser_data_changed) return TRUE; if (!wsec_table || !wsec_global_table) return FALSE; backup_file (config_file); channel = g_io_channel_new_file (config_file, "w", NULL); if (!channel) { nm_log_warn (LOGD_SETTINGS, "Can't open file %s for writing", config_file); return FALSE; } g_hash_table_iter_init (&iter, wsec_global_table); nm_log_info (LOGD_SETTINGS, "Writing to %s", config_file); g_io_channel_write_chars (channel, "#Generated by NetworkManager\n" "###### Global Configuration ######\n", -1, &bytes_written, error); /* Writing global information */ while (g_hash_table_iter_next (&iter, &key, &value)) { out_line = g_strdup_printf ("%s=%s\n", (gchar *) key, (gchar *) value); g_io_channel_write_chars (channel, out_line, -1, &bytes_written, error); if (bytes_written == 0 || (error && *error)) break; g_free (out_line); } if (error && *error) { nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message); goto done; } g_io_channel_write_chars (channel, "\n###### Security Configuration ######\n", -1, &bytes_written, error); g_hash_table_iter_init (&iter, wsec_table); /* Writing security */ while (g_hash_table_iter_next (&iter, &ssid, &security)) { g_hash_table_iter_init (&iter_security, (GHashTable *) security); g_io_channel_write_chars (channel, "network={\n", -1, &bytes_written, error); while (g_hash_table_iter_next (&iter_security, &key, &value)) { out_line = g_strdup_printf (need_quote ((gchar *) key) ? "\t%s=\"%s\"\n" : "\t%s=%s\n", (gchar *) key, (gchar *) value); g_io_channel_write_chars (channel, out_line, -1, &bytes_written, error); if (bytes_written == 0 || (error && *error)) break; g_free (out_line); } g_io_channel_write_chars (channel, "}\n\n", -1, &bytes_written, error); } if (error && *error) { nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message); goto done; } g_io_channel_flush (channel, error); if (error && *error) { nm_log_warn (LOGD_SETTINGS, "Found error: %s", (*error)->message); goto done; } wpa_parser_data_changed = FALSE; result = TRUE; done: g_io_channel_shutdown (channel, FALSE, NULL); g_io_channel_unref (channel); return result; }