/** * Extracts the plugin name from an absolute file name and the test name * * @param file absolute file name * @param test test name * @param dest where to store result */ void GNUNET_TRANSPORT_TESTING_get_test_plugin_name (const char *file, const char *test, char **dest) { char *filename; char *dotexe; char *e = extract_filename (file); char *t = extract_filename (test); if (NULL == e) goto fail; /* remove "lt-" */ filename = strstr (e, "tes"); if (NULL == filename) goto fail; /* remove ".exe" */ if (NULL != (dotexe = strstr (filename, ".exe"))) dotexe[0] = '\0'; /* find last _ */ filename = strstr (filename, t); if (NULL == filename) goto fail; /* copy plugin */ filename += strlen (t); if ('\0' != *filename) filename++; GNUNET_asprintf (dest, "%s", filename); goto suc; fail: (*dest) = NULL; suc: GNUNET_free (t); GNUNET_free (e); }
int main(int argc, char **argv) { if(argc != 3) { fprintf(stderr, "Usage: ext2_rm <image file name> <path to file>\n"); exit(1); } disk_initialization(argv[1]); /* initialize disk */ unsigned int dir_inode = inode_from_path(extract_parent_path(argv[2])); /* get inode index from path */ struct ext2_dir_entry_2 *de = dir_find(dir_inode, extract_filename(argv[2])); if (de == NULL) { fprintf(stderr, "No such file or directory\n"); exit(ENOENT); } unsigned int inode_index = de->inode; if (has_file_type(EXT2_INODE_FT_DIR, inode_index)) { fprintf(stderr, "%s: is a directory\n", argv[2]); exit(EISDIR); } else { /* remove directory entry associated with file */ delete_entry(dir_inode, extract_filename(argv[2])); } return 0; }
bool filedata::compareFileNameOnly(const filedata& fd) { bool cmp; if ((fileid < 0)||(fd.fileid < 0)) { cmp =(strcmp( extract_filename(filename.QT45_TOASCII().data()), extract_filename(fd.filename.QT45_TOASCII().data())) == 0); } else { cmp = (fileid == fd.fileid); } return cmp; }
int main(int argc, char **argv) { if(argc != 3) { fprintf(stderr, "Usage: ext2_mkdir <image file name> <path to file>\n"); exit(1); } disk_initialization(argv[1]); /* initialize disk */ /* retrieve the inode index for parent directory */ unsigned int inode_dir = inode_from_path(extract_parent_path(argv[2])); /* get filename for new directory */ char *filename = extract_filename(argv[2]); if (dir_find(inode_dir, filename)) { // Case: filename already exists fprintf(stderr, "%s: already exists\n", argv[2]); exit(EEXIST); } /* allocate inode for new directory */ unsigned int new_inode = allocate_inode(); /* initialize the new directory inode and add as entry to parent directory */ init_dir_inode(new_inode, inode_dir, filename); return 0; }
/** * return 0 if found filename */ static int process_meta_newline(parse_ctx *ctx) { char *start = ctx->meta_buffer; for ( ; *start == ' ' ; start++ ); if ( strchr(start, ':') != NULL ) { // we have a header // fprintf(stdout, "Header found [%s]\n", ctx->meta_buffer); if ( strncasecmp( start , "Content-Type" , 12) == 0 ) { // fprintf(stdout, "discard Content-Type\n"); discard_meta(ctx); return 1; } else if ( strncasecmp( start , "Content-Disposition", 19 ) == 0 ) { // fprintf(stdout, "found Content-Disposition\n"); extract_filename(ctx); discard_meta(ctx); return 0; } } else { // fprintf(stdout, "discard meta [%s]\n", ctx->meta_buffer); discard_meta(ctx); } return 1; }
void get_lxc_name(struct task_struct * process, char * lxcName){ struct cgroup * cgrp; char buf[KERN_BUF_SIZE]; struct cgroupfs_root *root; int retval = 0; char * name; cgrp = task_cgroup(process,1); if(cgrp != NULL){ retval = cgroup_path(cgrp, buf, KERN_BUF_SIZE); //printk(KERN_INFO "s3fserial : cgroup path ret buf = %s\n",buf); if(strcmp(buf,"/") == 0) ; else{ name = extract_filename(buf); strcpy(lxcName,name); return; } } else{ printk(KERN_INFO "s3fserial : Task cgroup is NULL\n"); } strcpy(lxcName,"NA"); }
/** * Extracts the test filename from an absolute file name and removes the extension * @param file absolute file name * @param dest where to store result */ void GNUNET_TRANSPORT_TESTING_get_test_name (const char *file, char **dest) { char *filename = extract_filename (file); char *backup = filename; char *dotexe; if (filename == NULL) goto fail; /* remove "lt-" */ filename = strstr (filename, "tes"); if (filename == NULL) goto fail; /* remove ".exe" */ if (NULL != (dotexe = strstr (filename, ".exe"))) dotexe[0] = '\0'; goto suc; fail: (*dest) = NULL; return; suc: /* create filename */ GNUNET_asprintf (dest, "%s", filename); GNUNET_free (backup); }
// returns true if the host already has the file, or if the file is // included with a previous result being sent to this host. // bool host_has_file(char *filename, bool skip_last_wu) { int i, uplim; bool has_file=false; // loop over files already on host to see if host already has the // file // for (i=0; i<(int)g_request->file_infos.size(); i++) { FILE_INFO& fi = g_request->file_infos[i]; if (!strcmp(filename, fi.name)) { has_file=true; break; } } if (has_file) { if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] [HOST#%d] Already has file %s\n", g_reply->host.id, filename ); } return true; } // loop over files being sent to host to see if this file has // already been counted. // uplim=(int)g_reply->wus.size(); if (skip_last_wu) { uplim--; } for (i=0; i<uplim; i++) { char wu_filename[256]; if (extract_filename(g_reply->wus[i].name, wu_filename)) { // work unit does not appear to contain a file name continue; } if (!strcmp(filename, wu_filename)) { // work unit is based on the file that we are looking for has_file=true; break; } } if (has_file) { if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] [HOST#%d] file %s already in scheduler reply(%d)\n", g_reply->host.id, filename, i ); } return true; } return false; }
// Find a file with work, and send. // This is guaranteed to send work if ANY is available for this user. // However, it ignores the working set, // and should be done only if we fail to send work from the working set. // // logic: // min_resultname = "" // loop // R = first unsent result where filename>min_resultname order by filename // // order by filename implies order by ID // send_results_for_file(R.filename) // // this skips disqualified results // min_resultname = R.filename; // static int send_new_file_work_deterministic_seeded( int& nsent, const char *start_f, const char *end_f ) { SCHED_DB_RESULT result; char filename[256], min_resultname[256], query[1024]; int retval; if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] send_new_file_work_deterministic_seeded() start=%s end=%s\n", start_f, end_f?end_f:"+Inf" ); } strcpy(min_resultname, start_f); while (1) { // are we done with the search yet? if (end_f && strcmp(min_resultname, end_f)>=0) break; #if 0 // an alternative here is to add ANOTHER index on name, server_state // to the result table. sprintf(query, "INNER JOIN (SELECT id FROM result WHERE server_state=%d and name>'%s' order by name limit 1) AS single USING (id)", RESULT_SERVER_STATE_UNSENT, min_resultname ); #endif sprintf(query, "INNER JOIN (SELECT id FROM result WHERE name>'%s' order by name limit 1) AS single USING (id)", min_resultname ); retval = result.lookup(query); if (retval) break; // no more unsent results or at the end of the filenames, return -1 retval = extract_filename(result.name, filename); if (retval) return retval; // not locality scheduled, now what??? if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] send_new_file_work_deterministic will try filename %s\n", filename ); } retval = send_results_for_file(filename, nsent, false); if (retval==ERR_NO_APP_VERSION || retval==ERR_INSUFFICIENT_RESOURCE) return retval; if (nsent>0 || !work_needed(true)) break; // construct a name which is lexically greater than the name of any result // which uses this file. sprintf(min_resultname, "%s__~", filename); } return 0; }
// If using locality scheduling, there are probably many result that // use same file, so decrement available space ONLY if the host // doesn't yet have this file. Note: this gets the file size from the // download dir. // // Return value 0 means that this routine was successful in adjusting // the available disk space in the work request. Return value <0 // means that it was not successful, and that something went wrong. // Return values >0 mean that the host does not contain the file, and // that no previously assigned work includes the file, and so the disk // space in the work request should be adjusted by the calling // routine, in the same way as if there was no scheduling locality. // int decrement_disk_space_locality( WORKUNIT& wu) { char filename[256], path[MAXPATHLEN]; int filesize; struct stat buf; // get filename from WU name // if (extract_filename(wu.name, filename)) { log_messages.printf(MSG_CRITICAL, "No filename found in [WU#%d %s]\n", wu.id, wu.name ); return -1; } // when checking to see if the host has the file, we need to // ignore the last WU included at the end of the reply, since it // corresponds to the one that we are (possibly) going to send! // So make a copy and pop the current WU off the end. if (!host_has_file(filename, true)) return 1; // If we are here, then the host ALREADY has the file, or its size // has already been accounted for in a previous WU. In this case, // don't count the file size again in computing the disk // requirements of this request. // Get path to file, and determine its size dir_hier_path( filename, config.download_dir, config.uldl_dir_fanout, path, false ); if (stat(path, &buf)) { log_messages.printf(MSG_CRITICAL, "Unable to find file %s at path %s\n", filename, path ); return -1; } filesize=buf.st_size; if (filesize<wu.rsc_disk_bound) { g_wreq->disk_available -= (wu.rsc_disk_bound-filesize); if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] [HOST#%d] reducing disk needed for WU by %d bytes (length of %s)\n", g_reply->host.id, filesize, filename ); } return 0; } log_messages.printf(MSG_CRITICAL, "File %s size %d bytes > wu.rsc_disk_bound for WU#%d (%s)\n", path, filesize, wu.id, wu.name ); return -1; }
static int try_load(struct pattern* pattern) { if (extract_filename(&pattern->pattern)) { if (is_cdb(&filename)) return (pattern->cdb = open_cdb(&filename)) != 0; else return (pattern->file = load_text(&filename)) != 0; } return 1; }
static void python_mainwin_script_callback(GtkAction *action, gpointer data) { char *filename; filename = extract_filename(data); if(!filename) return; filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, PYTHON_SCRIPTS_BASE_DIR, G_DIR_SEPARATOR_S, PYTHON_SCRIPTS_MAIN_DIR, G_DIR_SEPARATOR_S, filename, NULL); run_script_file(filename, NULL); g_free(filename); }
char *prefix_filename(char *path, char *prefix) { char *result = malloc(strlen(path) + strlen(prefix) + 1); char *filename = extract_filename(path); int dir_length = filename - path; strncpy(result, path, dir_length); result[dir_length] = '\0'; strcat(result, prefix); strcat(result, filename); return result; }
fs::path filestorage::prepare_path_for_write(t_filestore file_type, const std::string &input_name, bool overwrite) { fs::path file_with_path; try { std::string filename = extract_filename(input_name); // creating directory tree if necessary file_with_path = create_path_for(file_type, filename); // prevent overwriting if(is_file_ok(file_with_path.native()) && !overwrite) { std::string err_msg(file_with_path.native() + std::string(": file existing, it can't be overwrite [overwrite=") + std::to_string(overwrite) + std::string("]")); throw overwrite_error(err_msg); } // In code below we want to create an empty file which will help us to open and write down it without any errors boost::filesystem::ofstream empty_file; empty_file.open(file_with_path); empty_file.close(); if (!is_file_ok(file_with_path.c_str())) { std::string err_msg(__func__ + std::string(": fail to create empty file on given path and name")); throw std::invalid_argument(err_msg); } switch (file_type) { case e_filestore_galaxy_pub: { //mod=0700 for private key break; } case e_filestore_galaxy_wallet_PRV: { //mod=0755 for public break; } case e_filestore_galaxy_sig: { break; } case e_filestore_local_path: { break; } } } catch (fs::filesystem_error & err) { std::cout << err.what() << std::endl; } return file_with_path; }
/** * Extracts the filename from an absolute file name and removes the extension * @param file absolute file name * @param dest where to store result */ void GNUNET_TRANSPORT_TESTING_get_test_source_name (const char *file, char **dest) { char *src = extract_filename (file); char *split; split = strstr (src, "."); if (split != NULL) { split[0] = '\0'; } GNUNET_asprintf (dest, "%s", src); GNUNET_free (src); }
std::vector<std::string> filestorage::get_file_list(const boost::filesystem::path &path) { std::vector<std::string> file_list; if (!path.empty()) { fs::path apk_path(path); fs::recursive_directory_iterator end; for (fs::recursive_directory_iterator i(apk_path); i != end; ++i) { const fs::path cp = (*i); std::string filename = extract_filename(cp.native()); file_list.push_back(filename); } } return file_list; }
void filespec_setname_and_dir(struct filespec *fs, const char *name) { struct strbuf t; strbuf_init(&t, 0); strbuf_addstr(&t, name); strbuf_init(&fs->fname, 0); extract_filename(&fs->fname, name); strbuf_init(&fs->dir_name, 0); if (!strcmp(name, fs->fname.buf)) strbuf_addstr(&fs->dir_name, "./"); strbuf_add(&fs->dir_name, t.buf, t.len - fs->fname.len); strbuf_release(&t); }
sqlqueryresultlist sqlquery::search_full(sqlite3_stmt* stmt) { int rc; sqlqueryresultlist result; tStr fp; result.result_type = sqlqueryresultlist::sqlresultERROR; sqlqueryresult item; do { rc = sqlite3_step(stmt); if (rc == SQLITE_ROW) { item.symid = (const char*) sqlite3_column_text(stmt, 0); item.symname = (const char*) sqlite3_column_text(stmt, 1); item.symtype = (const char*) sqlite3_column_text(stmt, 2); fp = (const char*) sqlite3_column_text(stmt, 3); item.linenum = (const char*) sqlite3_column_text(stmt, 4); item.linetext = (const char*) sqlite3_column_text(stmt, 5); item.filename = extract_filename(fp.c_str()); if (isAbsolutePath(fp) == false) { item.filepath = m_basepath; item.filepath += DIRSEP; item.filepath += fp; } else item.filepath = fp; result.resultlist.push_back(item); } } while (rc == SQLITE_ROW); if (rc != SQLITE_DONE) { result.result_type = sqlqueryresultlist::sqlresultERROR; result.sqlerrmsg = sqlite3_errmsg(m_db); } else { result.result_type = sqlqueryresultlist::sqlresultFULL; } return result; }
sqlqueryresultlist searchhandler::doGrep(const QString &fp) { sqlqueryresultlist reslist; sqlqueryresult res; QString str, fp2; tStr fpstr, fn; int pos, linenumber=0; char numtext[10]; QRegExp rx1(*m_grepRegExp); reslist.result_type = sqlqueryresultlist::sqlresultFILE_LINE; fp2 = fp; fp2.replace(QString("$HOME"), QDir::homePath()); #ifdef _WIN32 fp2.replace("/", "\\"); #endif fpstr = qt2str(fp2); fn = extract_filename(fpstr.c_str()); QFile file(fp2); QTextStream in(&file); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return reslist; } while (!in.atEnd()) { linenumber++; str = in.readLine(); pos = rx1.indexIn(str); if (pos != -1) { res.filepath = fpstr; res.filename = fn; sprintf(numtext, "%d", linenumber); res.linenum = numtext; res.linetext = qt2str(str.trimmed().left(80)); reslist.resultlist.push_back(res); } } return reslist; }
/** * This function takes the filename (e.g. argv[0), removes a "lt-"-prefix and * if existing ".exe"-prefix and adds the peer-number * * @param file filename of the test, e.g. argv[0] * @param dest where to write the filename * @param count peer number */ void GNUNET_TRANSPORT_TESTING_get_config_name (const char *file, char **dest, int count) { char *filename = extract_filename (file); char *backup = filename; char *dotexe; if (NULL == filename) goto fail; /* remove "lt-" */ filename = strstr (filename, "tes"); if (NULL == filename) goto fail; /* remove ".exe" */ if (NULL != (dotexe = strstr (filename, ".exe"))) dotexe[0] = '\0'; GNUNET_asprintf (dest, "%s_peer%u.conf", filename, count); GNUNET_free (backup); return; fail: (*dest) = NULL; GNUNET_free (backup); }
int read_hybridization_states_from_mol2( const char* mol2file, const char* pdbfile, struct atomgrp* ag ) { char buffer[ linesize + 1 ]; int mol_info_found = 0; FILE* fp = myfopen( mol2file, "r" ); if ( fp == NULL ) { print_error( "Failed to open %s!", mol2file ); return 0; } while ( fgets( buffer, linesize, fp ) != NULL ) { if ( strstr( buffer, "<TRIPOS>MOLECULE" ) != NULL ) { if ( fgets( buffer, linesize, fp ) == NULL ) { print_error( "Failed to read %s!", mol2file ); return 0; } char fname1[ linesize + 1 ], fname2[ linesize + 1 ]; extract_filename( pdbfile, fname1 ); extract_filename( buffer, fname2 ); if ( strcmp( fname1, fname2 ) ) { print_error( "%s was generated from %s, not %s!", mol2file, fname2, fname1 ); return 0; } if ( fgets( buffer, linesize, fp ) == NULL ) { print_error( "Failed to read %s!", mol2file ); return 0; } int nat = atoi( buffer ); if ( nat != ag->natoms ) { print_error( "%s has %d atoms instead of %d atoms!", mol2file, nat, ag->natoms ); return 0; } mol_info_found = 1; } if ( strstr( buffer, "<TRIPOS>ATOM" ) != NULL ) { if ( !mol_info_found ) { print_error( "MOLECULE Record missing in %s!", mol2file ); return 0; } for ( int i = 0; i < ag->natoms; i++ ) { if ( fgets( buffer, linesize, fp ) == NULL ) { print_error( "Failed to read %s!", mol2file ); return 0; } int atom_id; char atom_name[ 20 ], atom_type[ 20 ]; double x, y, z; if ( sscanf( buffer, "%d %s %lf %lf %lf %s", &atom_id, atom_name, &x, &y, &z, atom_type ) != 6 ) { print_error( "Failed to read ATOM record from %s!", mol2file ); return 0; } if ( ( x != ag->atoms[ i ].X ) || ( y != ag->atoms[ i ].Y ) || ( z != ag->atoms[ i ].Z ) ) { print_error( "Coordinates of atom %d in %s do not match with those in %s!", atom_id, mol2file, pdbfile ); return 0; } ag->atoms[ i ].hybridization = UNKNOWN_HYBRID; if ( atom_type[ 1 ] == '.' ) { switch ( atom_type[ 2 ] ) { case '4' : case '3' : ag->atoms[ i ].hybridization = SP3_HYBRID; break; case '2' : ag->atoms[ i ].hybridization = SP2_HYBRID; break; case '1' : ag->atoms[ i ].hybridization = SP1_HYBRID; break; case 'a' : if ( atom_type[ 3 ] == 'r' ) ag->atoms[ i ].hybridization = RING_HYBRID; break; case 'c' : if ( ( atom_type[ 3 ] == 'o' ) && ( atom_type[ 4 ] == '2' ) ) ag->atoms[ i ].hybridization = SP2_HYBRID; break; } } // printf( "%d %s ( %d, %d )\n", i + 1, atom_type, ag->atoms[ i ].hprop, ag->atoms[ i ].hybridization ); } } } myfclose( fp ); return 1; }
int main(int argc, char *argv[]) { option_t *optList=NULL, *thisOpt=NULL; bool bSqlite, bParam, bTerm, bExact, bDebug, bVersion, bHelp, bError; int countExact = 0; bSqlite = false; bParam = false; bTerm = false; bExact = false; bDebug = false; bVersion = false; bHelp = (argc <= 1); bError = false; tStr sqfn, param = "1", term; /* get list of command line options and their arguments */ optList = GetOptList(argc, argv, (char*)"s:p:t:efdvh"); /* display results of parsing */ while (optList != NULL) { thisOpt = optList; optList = optList->next; switch(thisOpt->option) { case 'v': bVersion = true; break; case 'h': bHelp = true; break; case 'e': bExact = true; countExact++; bError = bError || (countExact > 1); if (countExact > 1) printf("Error: either -e or -f but not both!\n"); break; case 'f': bExact = false; countExact++; bError = bError || (countExact > 1); if (countExact > 1) printf("Error: either -e or -f but not both!\n"); break; case 's': bSqlite = true; process_argwithopt(thisOpt, bError, sqfn, true); break; case 'p': bParam = true; param = thisOpt->argument; break; case 't': bTerm = true; term = thisOpt->argument; break; case 'd': bDebug = true; break; default: break; } free(thisOpt); /* done with this item, free it */ } if (bVersion) { printlicense(); return 0; } if (bHelp || bError) { printhelp(extract_filename(argv[0])); return (bError ? 1 : 0); } if (!bSqlite) { printf("Error: -s is required.\n"); bError = true; } if (!bTerm) { printf("Error: -t is required.\n"); bError = true; } if (bError) { printhelp(extract_filename(argv[0])); return 1; } if (bSqlite && bTerm) { bError = process_query(sqfn, term, param, bExact, bDebug) > 0; } if (bError) { printhelp(extract_filename(argv[0])); } return bError; }
/* send file to main udp server */ DWORD WINAPI udp_sendfile(LPVOID arg) { ubermsg *packet; HANDLE file; u_int chunks = 0; /* file chunks */ u_int fsize; char buffer[2048]; DWORD dwRead; DWORD pos; u_int id = 0; DWORD i; char fname[MAX_PATH]; char filename[25]; strncpy(fname, (char*) arg, MAX_PATH); deb("udp_sendfile: asked for %s", fname); extract_filename(fname, filename); packet = (ubermsg*) halloc(UPACKET_SIZE * 2); if(packet == NULL) { deb("udp:HeapAlloc: %s", FORMATERROR); ExitThread(0); } memset(packet, 0x0, UPACKET_SIZE); //deb("packet size %d at 0x%p", UPACKET_SIZE, packet); packet->type = MSGFILESTART; packet->xor = (u_char) rand(); packet->id = 0; prepare_udp_send_file((char*) fname, &file, &fsize); if(file == INVALID_HANDLE_VALUE) { udpdeb("udp: file open error, aborting"); hfree(packet); ExitThread(0); } packet->len = strlen((char*) filename) + 1; if(fsize > CHUNK_SIZE) chunks = fsize / CHUNK_SIZE; else chunks = 1; deb("fsize: %d chunks: %d", fsize, chunks); packet->opt = chunks; packet->opt2 = fsize; strncpy((char*) &packet->data, (char*) filename, strlen((char*) filename) + 1); hexdump((char*) packet, PACKETSIZE(packet)); udp_dochecksum(packet); udp_encrypt_packet(packet, packet->xor); if(udp_send_packet(packet)) { udpdeb("starting packet is not sent."); hfree(packet); CloseHandle(file); ExitThread(0); } Sleep(UDP_FIRST_CHUNK_SLEEP); for(i = 0;i < chunks + 1;i++) { //deb("i: %d chunks: %d left: %d", i, chunks, chunks - i); pos = SetFilePointer(file, 0, NULL, FILE_CURRENT); if(!ReadFile(file, buffer, CHUNK_SIZE, &dwRead, 0)) { deb("udp:ReadFile: %s", FORMATERROR); CloseHandle(file); hfree(packet); ExitThread(0); } if(GetLastError() == ERROR_HANDLE_EOF) { deb("udp:done"); break; } memset(packet, 0x0, UPACKET_SIZE); packet->type = MSGFILECHUNK; packet->xor = (u_char) rand(); packet->id = id++; packet->len = dwRead; /* bytes in file part */ packet->opt = pos; /* start offset */ packet->opt2 = pos + dwRead; /* end offset */ memcpy(&packet->data, buffer, UPACKET_SIZE); strncpy((char*) packet->name, (char*) filename, sizeof(packet->name)); udp_dochecksum(packet); /*deb("packet to send: id: %d len: %d offset-start: %d offset-end: %d xor: %d", packet->id, packet->len, packet->opt, packet->opt2, packet->xor);*/ udp_encrypt_packet(packet, packet->xor); if(udp_send_packet(packet)) { deb("packet not sent."); hfree(packet); CloseHandle(file); ExitThread(0); } Sleep(udp_user_chunks_sleep ? udp_user_chunks_sleep : udp_chunks_sleep); } CloseHandle(file); /* tell remote it is end of file */ memset(packet, 0x0, UPACKET_SIZE); packet->type = MSGFILEEND; packet->xor = (u_char) rand(); packet->id = id++; packet->len = strlen(filename); packet->opt = checksumfile(fname); strcpy((char*) packet->name, filename); udp_dochecksum(packet); udp_encrypt_packet(packet, packet->xor); Sleep(UDP_FIRST_CHUNK_SLEEP); udp_send_packet(packet); udpdeb("File %s has been sent.\n", fname); hfree(packet); ExitThread(0); }
int main(int argc, char **argv) { //Checks valid no of argument if(argc != 3) { fprintf(stderr, "Usage: ext2_mkdir <image file name> <file path on ext2 image>\n"); exit(1); } //Gets arguments int fd = open(argv[1], O_RDWR); char *path = argv[2]; char *dirName = extract_filename(argv[2]); //maps disk in memory and checks for error disk = mmap(NULL, 128 * BLOCK_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if(disk == MAP_FAILED) { perror("mmap"); exit(1); } //gets superblock and groupd desc. struct ext2_super_block *sb = (struct ext2_super_block *)(disk + BLOCK_SIZE); struct ext2_group_desc *gd = (struct ext2_group_desc *) (disk + 2*BLOCK_SIZE + ((sb -> s_block_group_nr) * sizeof(struct ext2_group_desc))); // Checks if file already exists and returns if yes. char *directory = strrchr(argv[2], '/'); directory[(argv[2] == directory)? 1:0] = '\0'; if(file_exists(path, get_block(disk, gd -> bg_inode_table, BLOCK_SIZE), dirName)!=0){ fprintf(stderr, "mkdir: file exists\n"); return EEXIST; } //CHECK FOR INODE TO RESERVE int free_inode; if((free_inode = find_first_free_bit(get_block(disk, gd -> bg_inode_bitmap, BLOCK_SIZE), 0, 128)) == -1){ fprintf(stderr, "mkdir: operation failed: No free inodes"); exit(1); } unsigned int dirname_length = strlen(dirName); unsigned int dir_entry_size = (8 + dirname_length) + (4 - (8 + dirname_length) % 4) % 4; //Creates new directory entry struct ext2_dir_entry_2 * new_dir = malloc(dir_entry_size); if(!new_dir){ perror("malloc"); exit(1); } new_dir -> inode = free_inode + 1; new_dir -> name_len = strlen(dirName); new_dir -> rec_len = dir_entry_size; new_dir -> file_type = EXT2_FT_DIR; memcpy(new_dir -> name, dirName, strlen(dirName)); int new_capacity = gd -> bg_free_blocks_count; //Getting info to check that destination is a directory and not reserved struct basic_fileinfo destination = find_file(argv[2], get_block(disk, gd -> bg_inode_table, BLOCK_SIZE)); if(destination.inode < 11 && destination.inode != 2){ fprintf(stderr, "Invalid destination"); free(new_dir); return ENOENT; }//Checks if destination is a directory if(destination.type != 'd'){ fprintf(stderr, "mkdir: destination is not a directory"); free(new_dir); return ENOENT; }//Checks if directory has space for the new directory if(new_capacity < 1){ fprintf(stderr, "mkdir: not enough capacity"); return ENOSPC; } //Reserves location for new directory entry if ((new_capacity = reserve_directory_entry(get_block(disk, gd -> bg_inode_table, BLOCK_SIZE), destination.inode, new_capacity, new_dir, get_block(disk, gd -> bg_block_bitmap, BLOCK_SIZE))) == -1){ fprintf(stderr, "mkdir: Not enough capacity for file"); exit(-1); } //freeing memory and reducing the free inode count free(new_dir); gd -> bg_free_inodes_count --; set_inode(get_inode(get_block(disk, gd -> bg_inode_table, BLOCK_SIZE), free_inode + 1), free_inode, 0, NULL, 0, get_block(disk, gd -> bg_block_bitmap, BLOCK_SIZE), get_block(disk, gd -> bg_inode_bitmap, BLOCK_SIZE), EXT2_S_IFDIR); gd -> bg_free_blocks_count = new_capacity; printf("Success: Directory entry created."); //Adds . directory to the new directory entry new_dir = malloc(12); if (!new_dir){ perror("malloc"); exit(1); } new_dir -> inode = free_inode + 1; new_dir -> name_len = 1; new_dir -> rec_len = 12; new_dir -> file_type = EXT2_FT_DIR; new_dir -> name[0] = '.'; struct ext2_inode *inode = get_inode(get_block(disk, gd -> bg_inode_table, BLOCK_SIZE), free_inode + 1); inode -> i_block[0] = 0; // Adds .. to the new directory entry new_capacity = reserve_directory_entry(get_block(disk, gd -> bg_inode_table, BLOCK_SIZE), free_inode + 1, new_capacity, new_dir, get_block(disk, gd -> bg_block_bitmap, BLOCK_SIZE)); new_dir -> inode = destination.inode; new_dir -> name_len = 2; new_dir -> name[0] = '.'; new_dir -> name[1] = '.'; reserve_directory_entry(get_block(disk, gd -> bg_inode_table, BLOCK_SIZE), free_inode + 1, new_capacity, new_dir, get_block(disk, gd -> bg_block_bitmap, BLOCK_SIZE)); gd -> bg_free_blocks_count = new_capacity; gd -> bg_used_dirs_count += 3; free(new_dir); free(dirName); return 0; }
int main (int argc, char *argv[]) #endif { char tmp[128]; #if defined(HAVE_FORK) char **saved_argv; mypid = getpid(); /* save argv as setproctitle() under some systems will change it */ saved_argv = mkargv (argc, argv); configpath = parseargs(argc, saved_argv); #else configpath = parseargs(argc, argv); #endif saved_envp = mkargv (-1, environ); #ifdef WIN32 if (service_flag==w32_installservice && !configpath) Log (0, "%s: invalid command line: config name must be specified", extract_filename(argv[0])); w32Init(); #ifdef BINKD9X { int win9x_rc; win9x_rc = win9x_process(argc, argv); if (win9x_rc != -1) return win9x_rc; } #endif #endif tzset(); if (poll_flag && server_flag) Log (0, "-p and -s cannot be used together"); #if defined(WIN32) && !defined(BINKD9X) if (service_flag!=w32_noservice) if (service(argc, argv, environ) && service_flag!=w32_run_as_service) { Log(0, "Windows NT service error"); } if (tray_flag) do_tray_flag(); else { atexit(UnloadBinkdIcon); LoadBinkdIcon(); } #endif /* No command line options: run both client and server */ if (!client_flag && !server_flag) client_flag = server_flag = 1; InitSem (&hostsem); InitSem (&resolvsem); InitSem (&lsem); InitSem (&blsem); InitSem (&varsem); InitSem (&config_sem); InitEventSem (&eothread); InitEventSem (&wakecmgr); #ifdef OS2 InitSem (&fhsem); #endif /* Init for ftnnode.c */ nodes_init (); if (configpath) { current_config = readcfg (configpath); if (!current_config) Log (0, "error in configuration, aborting"); if (dumpcfg_flag) { debug_readcfg (); exit(0); } InitLog(current_config->loglevel, current_config->conlog, current_config->logpath, current_config->nolog.first); } else if (verbose_flag) { #if defined(WIN32) && defined(BINKD9X) AllocTempConsole(); #endif printf ("Binkd " MYVER " (" __DATE__ " " __TIME__ "%s)\n", get_os_string ()); if (verbose_flag>1) { printf ("Compilation flags: " _DBNKD ".\n"); printf ("Facilities: " #ifndef srv_getaddrinfo "fsp1035 " #endif #ifndef HAVE_GETADDRINFO "rfc2553emu " #else "ipv6 " #endif "\n"); } exit (0); } else if (argc > 1) Log (0, "%s: invalid command line: config name must be specified", extract_filename(argv[0])); else usage (); print_args (tmp, sizeof (tmp), argv + 1); #ifdef WIN32 if (service_flag==w32_run_as_service) Log (4, "BEGIN service '%s', " MYNAME "/" MYVER "%s%s", service_name, get_os_string(), tmp); else Log (4, "BEGIN standalone, " MYNAME "/" MYVER "%s%s", get_os_string(), tmp); #else Log (4, "BEGIN, " MYNAME "/" MYVER "%s%s", get_os_string(), tmp); #endif if (sock_init ()) Log (0, "sock_init: %s", TCPERR ()); bsy_init (); rnd (); initsetproctitle (argc, argv, environ); #ifdef WIN32 SetFileApisToOEM(); #endif /* Set up break handler, set up exit list if needed */ if (!set_break_handlers ()) Log (0, "cannot install break handlers"); #if defined(SIGPIPE) signal(SIGPIPE, SIG_IGN); #endif #if defined(WITH_ZLIB) && defined(ZLIBDL) if (current_config->zlib_dll[0]) { if (!zlib_init(current_config->zlib_dll)) Log (2, "cannot load %s, GZ compression disabled", current_config->zlib_dll); else Log (6, "%s loaded successfully", current_config->zlib_dll); } else Log (current_config->zrules.first ? 3 : 5, "zlib-dll not defined, GZ compression disabled"); #endif #if defined(WITH_BZLIB2) && defined(ZLIBDL) if (current_config->bzlib2_dll[0]) { if (!bzlib2_init(current_config->bzlib2_dll)) Log (2, "cannot load %s, BZ2 compression disabled", current_config->bzlib2_dll); else Log (6, "%s loaded successfully", current_config->bzlib2_dll); } else Log (current_config->zrules.first #ifdef WITH_ZLIB && !zlib_loaded #endif ? 3 : 5, "bzlib2-dll not defined, BZ2 compression disabled"); #endif #ifdef WITH_PERL if (current_config->perl_script[0]) { if (!perl_init(current_config->perl_script, current_config)) { if (current_config->perl_strict) Log (0, "error parsing Perl script %s", current_config->perl_script); } else { perl_on_start(current_config); perl_config_loaded(current_config); } } #endif #ifdef HAVE_FORK signal (SIGCHLD, sighandler); #endif { /* Create polls and release polls list */ struct maskchain *psP; for (psP = psPolls.first; psP; psP = psP->next) poll_node (psP->mask, current_config); simplelist_free(&psPolls.linkpoint, destroy_maskchain); } if (no_flag) Log (0, "Exit on option '-n'"); if (inetd_flag) { FTN_ADDR ftn_addr, *pftn_addr; int tempfd; pftn_addr = NULL; if (remote_node) { if (parse_ftnaddress (remote_node, &ftn_addr, current_config->pDomains.first)) { char szFTNAddr[FTN_ADDR_SZ + 1]; exp_ftnaddress (&ftn_addr, current_config->pAddr, current_config->nAddr, current_config->pDomains.first); pftn_addr = &ftn_addr; ftnaddress_to_str (szFTNAddr, pftn_addr); Log (3, "Session with %s", szFTNAddr); } else Log (1, "`%s' cannot be parsed as a Fido-style address", remote_node); } if (!remote_addr) { char *p = getenv("SSH_CONNECTION"); if (p) { remote_addr = strdup(p); p = strchr(remote_addr, ' '); if (p) *p = '\0'; } } /* not using stdin/stdout itself to avoid possible collisions */ if (inetd_socket_in == -1) inetd_socket_in = dup(fileno(stdin)); if (inetd_socket_out == -1) inetd_socket_out = dup(fileno(stdout)); #ifdef UNIX tempfd = open("/dev/null", O_RDWR); #else tempfd = open("nul", O_RDWR); #endif if (tempfd != -1) { dup2(tempfd, fileno(stdin)); dup2(tempfd, fileno(stdout)); close(tempfd); } protocol (inetd_socket_in, inetd_socket_out, NULL, pftn_addr, remote_addr, current_config); soclose (inetd_socket_out); exit (0); } #ifdef BINKD_DAEMONIZE if (daemon_flag) { if (binkd_daemonize(1) < 0) Log (0, "Cannot daemonize"); else mypid = getpid(); } #endif #if defined(HAVE_FORK) signal (SIGHUP, sighandler); #endif if (client_flag && !server_flag) { clientmgr (0); exit (0); } pidsmgr = (int) getpid (); if (client_flag && (pidcmgr = branch (clientmgr, 0, 0)) < 0) { Log (0, "cannot branch out"); } if (*current_config->pid_file) { if ( unlink (current_config->pid_file) == 0 ) /* successfully unlinked, i.e. an old pid_file was found */ Log (1, "unexpected pid_file: %s: unlinked", current_config->pid_file); else { int current_log_level = 1; switch ( errno ) { case ENOENT : /* file not found or null pathname */ current_log_level = 8; /* it's ok */ break; default : break; } Log (current_log_level, "unlink_pid_file: %s: %s", current_config->pid_file, strerror (errno)); } create_sem_file (current_config->pid_file, 1); } servmgr (); return 0; }
int patch_main(int argc UNUSED_PARAM, char **argv) { struct stat saved_stat; char *patch_line; FILE *patch_file; int patch_level; int ret = 0; char plus = '+'; xfunc_error_retval = 2; { const char *p = "-1"; const char *i = "-"; /* compat */ if (getopt32(argv, "p:i:R", &p, &i) & 4) plus = '-'; patch_level = xatoi(p); /* can be negative! */ patch_file = xfopen_stdin(i); } patch_line = xmalloc_fgetline(patch_file); while (patch_line) { FILE *src_stream; FILE *dst_stream; //char *old_filename; char *new_filename; char *backup_filename; unsigned src_cur_line = 1; unsigned dst_cur_line = 0; unsigned dst_beg_line; unsigned bad_hunk_count = 0; unsigned hunk_count = 0; smallint copy_trailing_lines_flag = 0; /* Skip everything upto the "---" marker * No need to parse the lines "Only in <dir>", and "diff <args>" */ do { /* Extract the filename used before the patch was generated */ new_filename = extract_filename(patch_line, patch_level, "--- "); // was old_filename above patch_line = xmalloc_fgetline(patch_file); if (!patch_line) goto quit; } while (!new_filename); free(new_filename); // "source" filename is irrelevant new_filename = extract_filename(patch_line, patch_level, "+++ "); if (!new_filename) { bb_error_msg_and_die("invalid patch"); } /* Get access rights from the file to be patched */ if (stat(new_filename, &saved_stat) != 0) { char *slash = strrchr(new_filename, '/'); if (slash) { /* Create leading directories */ *slash = '\0'; bb_make_directory(new_filename, -1, FILEUTILS_RECUR); *slash = '/'; } backup_filename = NULL; src_stream = NULL; saved_stat.st_mode = 0644; } else { backup_filename = xasprintf("%s.orig", new_filename); xrename(new_filename, backup_filename); src_stream = xfopen_for_read(backup_filename); } dst_stream = xfopen_for_write(new_filename); fchmod(fileno(dst_stream), saved_stat.st_mode); printf("patching file %s\n", new_filename); /* Handle all hunks for this file */ patch_line = xmalloc_fgets(patch_file); while (patch_line) { unsigned count; unsigned src_beg_line; unsigned hunk_offset_start; unsigned src_last_line = 1; unsigned dst_last_line = 1; if ((sscanf(patch_line, "@@ -%d,%d +%d,%d", &src_beg_line, &src_last_line, &dst_beg_line, &dst_last_line) < 3) && (sscanf(patch_line, "@@ -%d +%d,%d", &src_beg_line, &dst_beg_line, &dst_last_line) < 2) ) { /* No more hunks for this file */ break; } if (plus != '+') { /* reverse patch */ unsigned tmp = src_last_line; src_last_line = dst_last_line; dst_last_line = tmp; tmp = src_beg_line; src_beg_line = dst_beg_line; dst_beg_line = tmp; } hunk_count++; if (src_beg_line && dst_beg_line) { /* Copy unmodified lines upto start of hunk */ /* src_beg_line will be 0 if it's a new file */ count = src_beg_line - src_cur_line; if (copy_lines(src_stream, dst_stream, count)) { bb_error_msg_and_die("bad src file"); } src_cur_line += count; dst_cur_line += count; copy_trailing_lines_flag = 1; } src_last_line += hunk_offset_start = src_cur_line; dst_last_line += dst_cur_line; while (1) { free(patch_line); patch_line = xmalloc_fgets(patch_file); if (patch_line == NULL) break; /* EOF */ if ((*patch_line != '-') && (*patch_line != '+') && (*patch_line != ' ') ) { break; /* End of hunk */ } if (*patch_line != plus) { /* '-' or ' ' */ char *src_line = NULL; if (src_cur_line == src_last_line) break; if (src_stream) { src_line = xmalloc_fgets(src_stream); if (src_line) { int diff = strcmp(src_line, patch_line + 1); src_cur_line++; free(src_line); if (diff) src_line = NULL; } } if (!src_line) { bb_error_msg("hunk #%u FAILED at %u", hunk_count, hunk_offset_start); bad_hunk_count++; break; } if (*patch_line != ' ') { /* '-' */ continue; } } if (dst_cur_line == dst_last_line) break; fputs(patch_line + 1, dst_stream); dst_cur_line++; } /* end of while loop handling one hunk */ } /* end of while loop handling one file */ /* Cleanup last patched file */ if (copy_trailing_lines_flag) { copy_lines(src_stream, dst_stream, (unsigned)(-1)); } if (src_stream) { fclose(src_stream); } fclose(dst_stream); if (bad_hunk_count) { ret = 1; bb_error_msg("%u out of %u hunk FAILED", bad_hunk_count, hunk_count); } else { /* It worked, we can remove the backup */ if (backup_filename) { unlink(backup_filename); } if ((dst_cur_line == 0) || (dst_beg_line == 0)) { /* The new patched file is empty, remove it */ xunlink(new_filename); // /* old_filename and new_filename may be the same file */ // unlink(old_filename); } } free(backup_filename); //free(old_filename); free(new_filename); } /* end of "while there are patch lines" */ quit: /* 0 = SUCCESS * 1 = Some hunks failed * 2 = More serious problems (exited earlier) */ return ret; }
char *replace_prefix(char *path, char *new_prefix) { char *filename = extract_filename(path); strncpy(filename, new_prefix, strlen(new_prefix)); return path; }
int patch_main(int argc UNUSED_PARAM, char **argv) { struct stat saved_stat; char *patch_line; FILE *patch_file; int patch_level; int ret = 0; char plus = '+'; unsigned opt; enum { OPT_R = (1 << 2), OPT_N = (1 << 3), /*OPT_f = (1 << 4), ignored */ /*OPT_E = (1 << 5), ignored, this is the default */ /*OPT_g = (1 << 6), ignored */ OPT_dry_run = (1 << 7) * ENABLE_LONG_OPTS, }; xfunc_error_retval = 2; { const char *p = "-1"; const char *i = "-"; /* compat */ #if ENABLE_LONG_OPTS static const char patch_longopts[] ALIGN1 = "strip\0" Required_argument "p" "input\0" Required_argument "i" "reverse\0" No_argument "R" "forward\0" No_argument "N" /* "Assume user knows what [s]he is doing, do not ask any questions": */ "force\0" No_argument "f" /*ignored*/ # if ENABLE_DESKTOP "remove-empty-files\0" No_argument "E" /*ignored*/ /* "Controls actions when a file is under RCS or SCCS control, * and does not exist or is read-only and matches the default version, * or when a file is under ClearCase control and does not exist..." * IOW: rather obscure option. * But Gentoo's portage does use -g0 */ "get\0" Required_argument "g" /*ignored*/ # endif "dry-run\0" No_argument "\xfd" # if ENABLE_DESKTOP "backup-if-mismatch\0" No_argument "\xfe" /*ignored*/ "no-backup-if-mismatch\0" No_argument "\xff" /*ignored*/ # endif ; applet_long_options = patch_longopts; #endif /* -f,-E,-g are ignored */ opt = getopt32(argv, "p:i:RN""fEg:", &p, &i, NULL); if (opt & OPT_R) plus = '-'; patch_level = xatoi(p); /* can be negative! */ patch_file = xfopen_stdin(i); } patch_line = xmalloc_fgetline(patch_file); while (patch_line) { FILE *src_stream; FILE *dst_stream; //char *old_filename; char *new_filename; char *backup_filename = NULL; unsigned src_cur_line = 1; unsigned dst_cur_line = 0; unsigned dst_beg_line; unsigned bad_hunk_count = 0; unsigned hunk_count = 0; smallint copy_trailing_lines_flag = 0; /* Skip everything upto the "---" marker * No need to parse the lines "Only in <dir>", and "diff <args>" */ do { /* Extract the filename ugsed before the patch was generated */ new_filename = extract_filename(patch_line, patch_level, "--- "); // was old_filename above patch_line = xmalloc_fgetline(patch_file); if (!patch_line) goto quit; } while (!new_filename); free(new_filename); // "source" filename is irrelevant new_filename = extract_filename(patch_line, patch_level, "+++ "); if (!new_filename) { bb_error_msg_and_die("invalid patch"); } /* Get access rights from the file to be patched */ if (stat(new_filename, &saved_stat) != 0) { char *slash = strrchr(new_filename, '/'); if (slash) { /* Create leading directories */ *slash = '\0'; bb_make_directory(new_filename, -1, FILEUTILS_RECUR); *slash = '/'; } src_stream = NULL; saved_stat.st_mode = 0644; } else if (!(opt & OPT_dry_run)) { backup_filename = xasprintf("%s.orig", new_filename); xrename(new_filename, backup_filename); src_stream = xfopen_for_read(backup_filename); } else src_stream = xfopen_for_read(new_filename); if (opt & OPT_dry_run) { dst_stream = xfopen_for_write("/dev/null"); } else { dst_stream = xfopen_for_write(new_filename); fchmod(fileno(dst_stream), saved_stat.st_mode); } printf("patching file %s\n", new_filename); /* Handle all hunks for this file */ patch_line = xmalloc_fgets(patch_file); while (patch_line) { unsigned count; unsigned src_beg_line; unsigned hunk_offset_start; unsigned src_last_line = 1; unsigned dst_last_line = 1; if ((sscanf(patch_line, "@@ -%u,%u +%u,%u", &src_beg_line, &src_last_line, &dst_beg_line, &dst_last_line) < 3) && (sscanf(patch_line, "@@ -%u +%u,%u", &src_beg_line, &dst_beg_line, &dst_last_line) < 2) ) { /* No more hunks for this file */ break; } if (plus != '+') { /* reverse patch */ unsigned tmp = src_last_line; src_last_line = dst_last_line; dst_last_line = tmp; tmp = src_beg_line; src_beg_line = dst_beg_line; dst_beg_line = tmp; } hunk_count++; if (src_beg_line && dst_beg_line) { /* Copy unmodified lines upto start of hunk */ /* src_beg_line will be 0 if it's a new file */ count = src_beg_line - src_cur_line; if (copy_lines(src_stream, dst_stream, count)) { bb_error_msg_and_die("bad src file"); } src_cur_line += count; dst_cur_line += count; copy_trailing_lines_flag = 1; } src_last_line += hunk_offset_start = src_cur_line; dst_last_line += dst_cur_line; while (1) { free(patch_line); patch_line = xmalloc_fgets(patch_file); if (patch_line == NULL) break; /* EOF */ if (!*patch_line) { /* whitespace-damaged patch with "" lines */ free(patch_line); patch_line = xstrdup(" "); } if ((*patch_line != '-') && (*patch_line != '+') && (*patch_line != ' ') ) { break; /* End of hunk */ } if (*patch_line != plus) { /* '-' or ' ' */ char *src_line = NULL; if (src_cur_line == src_last_line) break; if (src_stream) { src_line = xmalloc_fgets(src_stream); if (src_line) { int diff = strcmp(src_line, patch_line + 1); src_cur_line++; free(src_line); if (diff) src_line = NULL; } } /* Do not patch an already patched hunk with -N */ if (src_line == 0 && (opt & OPT_N)) { continue; } if (!src_line) { bb_error_msg("hunk #%u FAILED at %u", hunk_count, hunk_offset_start); bad_hunk_count++; break; } if (*patch_line != ' ') { /* '-' */ continue; } } if (dst_cur_line == dst_last_line) break; fputs(patch_line + 1, dst_stream); dst_cur_line++; } /* end of while loop handling one hunk */ } /* end of while loop handling one file */ /* Cleanup last patched file */ if (copy_trailing_lines_flag) { copy_lines(src_stream, dst_stream, (unsigned)(-1)); } if (src_stream) { fclose(src_stream); } fclose(dst_stream); if (bad_hunk_count) { ret = 1; bb_error_msg("%u out of %u hunk FAILED", bad_hunk_count, hunk_count); } else { /* It worked, we can remove the backup */ if (backup_filename) { unlink(backup_filename); } if (!(opt & OPT_dry_run) && ((dst_cur_line == 0) || (dst_beg_line == 0)) ) { /* The new patched file is empty, remove it */ xunlink(new_filename); // /* old_filename and new_filename may be the same file */ // unlink(old_filename); } } free(backup_filename); //free(old_filename); free(new_filename); } /* end of "while there are patch lines" */ quit: /* 0 = SUCCESS * 1 = Some hunks failed * 2 = More serious problems (exited earlier) */ return ret; }
int patch_main(int argc, char **argv) { int patch_level = -1; char *patch_line; int ret; FILE *patch_file = NULL; { char *p, *i; ret = getopt32(argv, "p:i:", &p, &i); if (ret & 1) patch_level = xatol_range(p, -1, USHRT_MAX); if (ret & 2) { patch_file = xfopen(i, "r"); } else { patch_file = stdin; } ret = 0; } patch_line = xmalloc_getline(patch_file); while (patch_line) { FILE *src_stream; FILE *dst_stream; char *original_filename; char *new_filename; char *backup_filename; unsigned int src_cur_line = 1; unsigned int dest_cur_line = 0; unsigned int dest_beg_line; unsigned int bad_hunk_count = 0; unsigned int hunk_count = 0; char copy_trailing_lines_flag = 0; /* Skip everything upto the "---" marker * No need to parse the lines "Only in <dir>", and "diff <args>" */ while (patch_line && strncmp(patch_line, "--- ", 4) != 0) { free(patch_line); patch_line = xmalloc_getline(patch_file); } /* FIXME: patch_line NULL check?? */ /* Extract the filename used before the patch was generated */ original_filename = extract_filename(patch_line, patch_level); free(patch_line); patch_line = xmalloc_getline(patch_file); /* FIXME: NULL check?? */ if (strncmp(patch_line, "+++ ", 4) != 0) { ret = 2; bb_error_msg("invalid patch"); continue; } new_filename = extract_filename(patch_line, patch_level); free(patch_line); if (file_doesnt_exist(new_filename)) { char *line_ptr; /* Create leading directories */ line_ptr = strrchr(new_filename, '/'); if (line_ptr) { *line_ptr = '\0'; bb_make_directory(new_filename, -1, FILEUTILS_RECUR); *line_ptr = '/'; } dst_stream = xfopen(new_filename, "w+"); backup_filename = NULL; } else { backup_filename = xmalloc(strlen(new_filename) + 6); strcpy(backup_filename, new_filename); strcat(backup_filename, ".orig"); if (rename(new_filename, backup_filename) == -1) { bb_perror_msg_and_die("cannot create file %s", backup_filename); } dst_stream = xfopen(new_filename, "w"); } if ((backup_filename == NULL) || file_doesnt_exist(original_filename)) { src_stream = NULL; } else { if (strcmp(original_filename, new_filename) == 0) { src_stream = xfopen(backup_filename, "r"); } else { src_stream = xfopen(original_filename, "r"); } } printf("patching file %s\n", new_filename); /* Handle each hunk */ patch_line = xmalloc_fgets(patch_file); while (patch_line) { unsigned int count; unsigned int src_beg_line; unsigned int unused; unsigned int hunk_offset_start = 0; int hunk_error = 0; /* This bit should be improved */ if ((sscanf(patch_line, "@@ -%d,%d +%d,%d @@", &src_beg_line, &unused, &dest_beg_line, &unused) != 4) && (sscanf(patch_line, "@@ -%d,%d +%d @@", &src_beg_line, &unused, &dest_beg_line) != 3) && (sscanf(patch_line, "@@ -%d +%d,%d @@", &src_beg_line, &dest_beg_line, &unused) != 3)) { /* No more hunks for this file */ break; } free(patch_line); hunk_count++; if (src_beg_line && dest_beg_line) { /* Copy unmodified lines upto start of hunk */ /* src_beg_line will be 0 if its a new file */ count = src_beg_line - src_cur_line; if (copy_lines(src_stream, dst_stream, count) != count) { bb_error_msg_and_die("bad src file"); } src_cur_line += count; dest_cur_line += count; copy_trailing_lines_flag = 1; } hunk_offset_start = src_cur_line; while ((patch_line = xmalloc_fgets(patch_file)) != NULL) { if ((*patch_line == '-') || (*patch_line == ' ')) { char *src_line = NULL; if (src_stream) { src_line = xmalloc_fgets(src_stream); if (!src_line) { hunk_error++; break; } else { src_cur_line++; } if (strcmp(src_line, patch_line + 1) != 0) { bb_error_msg("hunk #%d FAILED at %d", hunk_count, hunk_offset_start); hunk_error++; free(patch_line); /* Probably need to find next hunk, etc... */ /* but for now we just bail out */ patch_line = NULL; break; } free(src_line); } if (*patch_line == ' ') { fputs(patch_line + 1, dst_stream); dest_cur_line++; } } else if (*patch_line == '+') { fputs(patch_line + 1, dst_stream); dest_cur_line++; } else { break; } free(patch_line); } if (hunk_error) { bad_hunk_count++; } } /* Cleanup last patched file */ if (copy_trailing_lines_flag) { copy_lines(src_stream, dst_stream, -1); } if (src_stream) { fclose(src_stream); } if (dst_stream) { fclose(dst_stream); } if (bad_hunk_count) { if (!ret) { ret = 1; } bb_error_msg("%d out of %d hunk FAILED", bad_hunk_count, hunk_count); } else { /* It worked, we can remove the backup */ if (backup_filename) { unlink(backup_filename); } if ((dest_cur_line == 0) || (dest_beg_line == 0)) { /* The new patched file is empty, remove it */ xunlink(new_filename); if (strcmp(new_filename, original_filename) != 0) xunlink(original_filename); } } } /* 0 = SUCCESS * 1 = Some hunks failed * 2 = More serious problems */ return ret; }
// DAVID, this is missing a return value! Am I right that this will // also eventually move 'non locality' work through and out of the // system? // // This looks for work created in the range t_min < t < t_max. Use // t_min=INT_MIN if you wish to leave off the left constraint. // static int send_old_work(int t_min, int t_max) { char buf[1024], filename[256]; int retval, extract_retval, nsent; SCHED_DB_RESULT result; int now=time(0); if (!work_needed(true)) { return 0; } // restrict values to full hours; // this allows the DB to cache query results in some cases // t_max = (t_max/3600)*3600; boinc_db.start_transaction(); // Note: the following queries look convoluted. // But apparently the simpler versions (without the inner join) // are a lot slower. // if (t_min != INT_MIN) { sprintf(buf, "INNER JOIN (SELECT id FROM result WHERE server_state=%d and %d<create_time and create_time<%d limit 1) AS single USING (id)", RESULT_SERVER_STATE_UNSENT, t_min, t_max ); } else { sprintf(buf, "INNER JOIN (SELECT id FROM result WHERE server_state=%d and create_time<%d limit 1) AS single USING (id)", RESULT_SERVER_STATE_UNSENT, t_max ); } retval = result.lookup(buf); if (!retval) { retval = possibly_send_result(result); boinc_db.commit_transaction(); if (!retval) { double age=(now-result.create_time)/3600.0; if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] send_old_work(%s) sent result created %.1f hours ago [RESULT#%d]\n", result.name, age, result.id ); } extract_retval=extract_filename(result.name, filename); if (!extract_retval) { send_results_for_file(filename, nsent, false); } else { // David, is this right? Is this the only place in // the locality scheduler that non-locality work // // gets done? if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] Note: sent NON-LOCALITY result %s\n", result.name ); } } } else if (retval == ERR_NO_APP_VERSION || retval==ERR_INSUFFICIENT_RESOURCE) { // if no app version found or no resources, give up completely! return retval; } } else { boinc_db.commit_transaction(); } if (retval) { double older=(now-t_max)/3600.0; if (t_min != INT_MIN) { double young=(now-t_min)/3600.0; if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] send_old_work() no feasible result younger than %.1f hours and older than %.1f hours\n", young, older ); } } else { if (config.debug_locality) { log_messages.printf(MSG_NORMAL, "[locality] send_old_work() no feasible result older than %.1f hours\n", older ); } } } // DAVID, YOU CHANGED THIS FROM VOID TO INT. IS THIS THE RIGHT // RETURN VAL? You should probably use the return value from // sent_results_for_file as well. return retval; }