void read_out() { int k=0; FILE *fopen(),*fp; int count; fp=fopen("database.txt","r"); if(check_file(fp)==0){printf("Problem reading the file SLOTS_BEST_productN.txt, have you created it yet?\r\n");} else { count=getc(fp); while(count!=EOF) { count=getc(fp); putchar(count); } }//open the file and put the characters onto the screen fclose(fp); wait_for_user(); }
void run_bst_del(char *file, std::vector<char *> & strvec) { if (FALSE == check_file(file)) { exit(1); } ifstream fin(file); if (!fin.good()) { cerr << "read file: " << file << " failed.\n"; exit(1); } Bst bst(fin); bst.build(); for (size_t i=0; i< strvec.size(); i++) { cout << "\nDeleted \""<< strvec[i] << "\":\n\n"; bst.del(strvec[i]); bst.display(); } }
int Command_load(Command *cmd) { bstring db_file = option(cmd, "db", "config.sqlite"); bstring conf_file = option(cmd, "config", "mongrel2.conf"); bstring what = NULL; bstring why = NULL; check_file(conf_file, "config file", R_OK); Config_load(bdata(conf_file), bdata(db_file)); what = bfromcstr("load"); why = bfromcstr("command"); log_action(db_file, what, why, NULL, conf_file); error: // fallthrough bdestroy(what); bdestroy(why); return 0; }
int check_directory(const char* dirpath) { int num_error = 0; std::vector<std::string>* subdir_names = NULL; std::vector<std::string> file_names; std::vector<std::string>* link_names = NULL; mooon::sys::CDirUtils::list(dirpath, subdir_names, &file_names, link_names); for (std::vector<std::string>::size_type i=0; i<file_names.size(); ++i) { if (mooon::db_proxy::is_sql_log_filename(file_names[i])) { const std::string filepath = mooon::utils::CStringUtils::format_string("%s/%s", dirpath, file_names[i].c_str()); if (check_file(filepath.c_str()) != 0) ++num_error; } } return 0 == num_error; }
void send_file(t_all *all, char *cmd) { int fd; char buff[MAX_SIZE]; cmd = cmd + 4; if (check_file(cmd) == -1) display_return_and_explanation(cmd, all->sv->c_sock, 0, 'f'); else { if ((fd = open(cmd, O_RDONLY)) == -1) server_error("OPEN"); if (read(fd, buff, MAX_SIZE - 1) == -1) server_error("READ"); // printf("%lu\n", sizeof(buff)); // all. send(all->sv->c_sock, buff, ft_strlen(buff), 0); } /*send(all->sv->c_sock, pwd, ft_strlen(pwd), 0);*/ }
static void test(void) { int rv = 0; const char file_a [] = "/FTP/127.0.0.1/a.txt"; const char file_b [] = "/FTP/127.0.0.1/b.txt"; rv = rtems_bsdnet_initialize_network(); rtems_test_assert(rv == 0); rv = rtems_initialize_ftpd(); rtems_test_assert(rv == 0); initialize_ftpfs(); change_self_priority(); create_file(file_a, &content [0], sizeof(content)); copy_file(file_a, file_b); check_file(file_b); check_file_size(file_a, sizeof(content)); check_file_size(file_b, sizeof(content)); }
int FileOperation::write_file(const char* buf, const int32_t nbytes) { const char *p_tmp = buf; int32_t left = nbytes; int32_t written_len = 0; int i = 0; while (left > 0) { ++i; if (i >= MAX_DISK_TIMES) { break; } if (check_file() < 0) return -errno; if ((written_len = ::write(fd_, p_tmp, left)) <= 0) { written_len = -errno; if (EINTR == -written_len || EAGAIN == -written_len) { continue; } if (EBADF == -written_len) { fd_ = -1; continue; } else { return written_len; } } left -= written_len; p_tmp += written_len; } return p_tmp - buf; }
int CTimerFile::write_data(const void *data, uint32_t len) { if (check_file() == -1) { return -1; } size_t res = fwrite(data, 1, len, m_file_stream); if (res != len) { LOG_DEBUG("Write to file failed. %d, %s", errno, strerror(errno)); return -1; } fflush(m_file_stream); m_cur_file_line++; m_last_write_time = std::time(nullptr); return 0; }
static struct classifier_config* read_config(FILE *input) { assert(input); struct file_range types_section, atoms_section; struct classifier_config *config = NULL; struct classifier_types *types = NULL; if (!(types = classifier_types_new()) || !(config = classifier_config_new()) || check_file(input, &types_section, &atoms_section) || read_types(types, input, types_section) || read_atoms(config, types, input, atoms_section) || config_copy_classes(config, types)) { classifier_config_free(config); config = NULL; } classifier_types_free(types); return config; }
int main(int argc, char **argv) { unsigned char uchar_out[DIM1_LEN] = {0, 128, 255}; int format[MAX_NUM_FORMATS]; int num_formats; int f = 0; printf("\n*** Testing netcdf data conversion.\n"); determine_test_formats(&num_formats, format); for (f = 0; f < num_formats; f++) { printf("*** Testing conversion in netCDF %s files... ", format_name[f]); create_file(format[f], uchar_out); check_file(format[f], uchar_out); SUMMARIZE_ERR; } FINAL_RESULTS; }
LPTR load_file(LPTR address, status_t* result) { header_t* h = address; *result = check_file(h); if (*result != status_t::Ok) return nullptr; ph_t* ph = nullptr; for (int i = 0; i < h->pht_entry_c; ++i) { ph = (uint32_t)h + h->pht_off + i*h->pht_entry_s; if (ph->type != ph_type::Load) continue; memory::memcpy(ph->p_addr, (uint32_t)h +ph->offset, ph->size); } return h->entry; }
/* This opens and checks a netCDF file. */ int open_and_check_file(MPI_Comm comm, int iosysid, int iotype, int *ncid, char *fname, char *attname, char *dimname, int disable_close, int my_rank) { int mode = PIO_WRITE; int ret; /* Open the file. */ if ((ret = PIOc_openfile(iosysid, ncid, &iotype, fname, mode))) return ret; /* Check the file. */ if ((ret = check_file(comm, iosysid, iotype, *ncid, fname, attname, dimname, my_rank))) return ret; /* Close the file, maybe. */ if (!disable_close) if ((ret = PIOc_closefile(*ncid))) return ret; return PIO_NOERR; }
/* verify that the filesystem matches the package database */ static int check_files(alpm_pkg_t *pkg) { alpm_filelist_t *filelist = alpm_pkg_get_files(pkg); char path[PATH_MAX], *rel; const char *pkgname = alpm_pkg_get_name(pkg); unsigned int i; int ret = 0; size_t space; strncpy(path, alpm_option_get_root(handle), PATH_MAX); rel = path + strlen(path); space = PATH_MAX - (rel - path); for(i = 0; i < filelist->count; ++i) { alpm_file_t file = filelist->files[i]; int isdir = 0; size_t len; if(skip_noextract && match_noextract(handle, file.name)) { continue; } strncpy(rel, file.name, space); len = strlen(file.name); if(rel[len - 1] == '/') { isdir = 1; rel[len - 1] = '\0'; } if(check_file(pkgname, path, isdir) != 0) { ret = 1; } } if(include_db_files && check_db_files(pkg) != 0) { ret = 1; } if(!quiet && !ret) { eprintf("%s: all files match database\n", alpm_pkg_get_name(pkg)); } return ret; }
std::optional<std::string> plugin_searcher::find_extension(const std::string& name) { LOG(DEBUG) << "Searching for Extension: " << name << "\n"; for (auto folder : active_mod_folder_list) { #if _WIN64 || __X86_64__ std::string test_path = folder + "\\intercept\\" + name + "_x64.dll"; #else #ifdef __linux__ std::string test_path = folder + "/intercept/" + name + ".so"; #else std::string test_path = folder + "\\intercept\\" + name + ".dll"; #endif #endif LOG(DEBUG) << "Mod: " << test_path << "\n"; std::ifstream check_file(test_path); if (check_file.good()) { return test_path; } } LOG(ERROR) << "Client plugin: " << name << " was not found.\n"; return std::optional<std::string>(); }
void test_group<test_data>::object::test<3>() { set_test_name("Test append-release recycling"); ensure_equals(file.get_block_count(), 1); file.release_block(0); ensure_equals(file.get_block_count(), 0); ensure_equals(file.append_block(create_test_block(0)), 0); ensure_equals(file.get_block_count(), 1); ensure_equals(file.append_block(create_test_block(100)), 1); ensure_equals(file.get_block_count(), 2); file.close(); commons::io::recycling_block_file check_file("recycling_test_block_file", 512, free_block_initializer()); ensure_equals(check_file.get_block_count(), 2); ensure_blocks_are_equals(check_file.read_block(0), create_test_block(0)); ensure_blocks_are_equals(check_file.read_block(1), create_test_block(100)); }
void redirr_proc(t_node *tree) { char *file; int fd; t_data *data; file = ft_strtrim(tree->left->word); data = init_data(0); if (data->tmp_fdout == -1) get_tmpfd(&data->tmp_fdout, "/.temp_out"); if (data->tmp_fdout != -1 && (fd = check_file(file)) != -1) { add_outfildes(&data->outfildes, file, fd); read_tree(tree->right); } else { update_data(&data); g_pid.built = 0; } ft_strdel(&file); }
int main(int ac, char **av) { int fd; int i; int *lines; int *ia_goal; if (ac > 2) error("ERROR\n"); if (ac == 2) { fd = open(av[1], O_RDONLY); if (fd < 0) error("ERROR\n"); } else fd = 0; i = check_file(&lines, &ia_goal, fd); if (i == 0) error("ERROR\n"); play(lines, ia_goal, i - 1); return (0); }
int load_map( const char* file, char map[MAP_HSIZE][MAP_WSIZE] ){ memset( map, EMPTY, sizeof(char) * MAP_HSIZE * MAP_WSIZE ); char path[120]; get_path( path, file ); if( !check_file( path ) ) return 0; FILE* fp = fopen( path, "r" ); int i = 0, ii = 0; char ch; while( ( ch = fgetc( fp ) ) != EOF ){ if( ch == '\n' ){ if( ++i >= MAP_HSIZE ){ fclose( fp ); return 1; } ii = 0; } else { if( ii < MAP_WSIZE ) map[i][ii] = ch; ii++; } } fclose( fp ); return 1; }
int main(int ac, char **av) { int fd; char **tetris; char *solution; if (ac != 2) ft_exit(); fd = open(av[1], O_RDONLY); if (fd < 0) ft_exit(); tetris = check_file(fd); close(fd); if (tetris == NULL) ft_exit(); solution = solver(tetris); if (solution == NULL) ft_exit(); ft_putstr(solution); clear_tab(tetris); free(solution); return (0); }
static void brcmf_usb_probe_phase2(struct device *dev, const struct firmware *fw, void *nvram, u32 nvlen) { struct brcmf_bus *bus = dev_get_drvdata(dev); struct brcmf_usbdev_info *devinfo; int ret; brcmf_dbg(USB, "Start fw downloading\n"); devinfo = bus->bus_priv.usb->devinfo; ret = check_file(fw->data); if (ret < 0) { brcmf_err("invalid firmware\n"); release_firmware(fw); goto error; } devinfo->image = fw->data; devinfo->image_len = fw->size; ret = brcmf_usb_fw_download(devinfo); release_firmware(fw); if (ret) goto error; ret = brcmf_usb_bus_setup(devinfo); if (ret) goto error; mutex_unlock(&devinfo->dev_init_lock); return; error: brcmf_dbg(TRACE, "failed: dev=%s, err=%d\n", dev_name(dev), ret); mutex_unlock(&devinfo->dev_init_lock); device_release_driver(dev); }
static int brcmf_usb_get_fw(struct brcmf_usbdev_info *devinfo) { s8 *fwname; const struct firmware *fw; int err; devinfo->image = g_image.data; devinfo->image_len = g_image.len; /* * if we have an image we can leave here. */ if (devinfo->image) return 0; fwname = BRCMF_USB_43236_FW_NAME; err = request_firmware(&fw, fwname, devinfo->dev); if (!fw) { brcmf_dbg(ERROR, "fail to request firmware %s\n", fwname); return err; } if (check_file(fw->data) < 0) { brcmf_dbg(ERROR, "invalid firmware %s\n", fwname); return -EINVAL; } devinfo->image = vmalloc(fw->size); /* plus nvram */ if (!devinfo->image) return -ENOMEM; memcpy(devinfo->image, fw->data, fw->size); devinfo->image_len = fw->size; release_firmware(fw); return 0; }
int main(int ac, char **av) { if (ac == 1) my_printf("Usage: ./asm file.s ...\n"); else { while ((--ac + 1) > 1) { if (!check_file(av[ac])) { my_printf("\033[7;36m#Assembling %s started...\n\033[0m", av[ac]); if (!asm_treatment(av[ac])) my_printf("\033[1;36m#Assembling completed.\n\033[0m"); else my_printf("\033[1;31m#Assembling fail.\n\033[0m"); } else my_printf("\033[7;31mAsm: File %s isn't a valid type.\n\033[0m", av[ac]); } } return (EXIT_SUCCESS); }
int main(void) { int frame = 0, ret = 0, got_picture = 0, frameFinished = 0, videoStream = 0, check_yuv = 0; int frame_size = 0, bitrate = 0; int streamIdx = 0; unsigned i=0; enum AVMediaType mediaType; struct SwsContext *sws_ctx = NULL; AVStream *video_st = NULL; AVCodecContext *pCodecCtx = NULL, *ctxEncode = NULL; AVFrame *pFrame = NULL; AVPacket input_pkt, output_pkt; check_yuv = check_file(); // Register all formats and codecs av_register_all(); if (open_input_file(check_yuv) < 0) exit(1); if (open_output_file() < 0) exit(1); init_parameter(&input_pkt, &output_pkt); //init parameter function pictureEncoded_init(); // initialize SWS context for software scaling sws_ctx = sws_getContext(inFmtCtx->streams[streamIdx]->codec->width, inFmtCtx->streams[streamIdx]->codec->height, inFmtCtx->streams[streamIdx]->codec->pix_fmt, clip_width, clip_height, PIX_FMT_YUV420P, SWS_BILINEAR, NULL, NULL, NULL); while (av_read_frame(inFmtCtx, &input_pkt) >= 0) { streamIdx = input_pkt.stream_index; mediaType = inFmtCtx->streams[streamIdx]->codec->codec_type; av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n", streamIdx); av_log(NULL, AV_LOG_DEBUG, "Going to reencode \n"); pFrame = av_frame_alloc(); if (!pFrame) { ret = AVERROR(ENOMEM); break; } av_packet_rescale_ts(&input_pkt, inFmtCtx->streams[videoStream]->time_base, inFmtCtx->streams[streamIdx]->codec->time_base); if (mediaType == AVMEDIA_TYPE_VIDEO){ ret = avcodec_decode_video2(inFmtCtx->streams[streamIdx]->codec, pFrame, &frameFinished, &input_pkt); // Decode video frame (input_pkt-> pFrame) if (ret < 0) { av_frame_free(&pFrame); av_log(NULL, AV_LOG_ERROR, "Decoding failed\n"); break; } if (frameFinished){ frame_num++; sws_scale(sws_ctx, (const uint8_t * const *)pFrame->data, pFrame->linesize, 0, clip_height, pictureEncoded->data, pictureEncoded->linesize); pictureEncoded->pts = av_frame_get_best_effort_timestamp(pFrame); //pictureEncoded-> output_pkt //avcodec_encode_video2(ctxEncode, &output_pkt, pictureEncoded, &got_picture); avcodec_encode_video2(ofmt_ctx->streams[streamIdx]->codec, &output_pkt, pictureEncoded, &got_picture); av_frame_free(&pFrame); //if the function is working if (got_picture){ printf("Encoding %d \n", frame_use); frame_use++; av_packet_rescale_ts(&output_pkt, ofmt_ctx->streams[streamIdx]->codec->time_base, ofmt_ctx->streams[streamIdx]->time_base); //av_packet_rescale_ts(&output_pkt, ctxEncode->time_base, video_st->time_base); ret = av_interleaved_write_frame(ofmt_ctx, &output_pkt); if (ret < 0) { fprintf(stderr, "Error muxing packet\n"); break; } } } av_free_packet(&input_pkt); av_free_packet(&output_pkt); } } //flush encoders for (i = 0; i < inFmtCtx->nb_streams; i++) { if (inFmtCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) { ret = flush_encoder(i); if (ret < 0) { av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n"); exit(1); } } } printf("\n\n total frame_num : %d , frame_encode: %d \n", frame_num-1, frame_use-1); /* Write the trailer, if any. The trailer must be written before you * close the CodecContexts open when you wrote the header; otherwise * av_write_trailer() may try to use memory that was freed on * av_codec_close(). */ av_write_trailer(ofmt_ctx); // Free the YUV frame av_frame_free(&pFrame); av_frame_free(&pictureEncoded); // Close the codecs //avcodec_close(pCodecCtx); // Close the video file avformat_close_input(&inFmtCtx); //avcodec_close(ctxEncode); return 0; }
int main(){ int socket_fd; struct sockaddr_in dest; char buffer[B_SIZE]; socket_fd = socket(PF_INET, SOCK_STREAM, 0); bzero(&dest, sizeof(dest)); dest.sin_family = PF_INET; dest.sin_port = htons(8889); dest.sin_addr.s_addr = htonl(INADDR_ANY); bind(socket_fd, (struct sockaddr*)&dest, sizeof(dest)); listen(socket_fd, 20); FILE *fp; bzero(&buffer, B_SIZE); int client; struct sockaddr_in client_addr; socklen_t addlen; addlen = sizeof(client_addr); client = accept(socket_fd, (struct sockaddr*)&client_addr, &addlen); int check=0; char command='\0'; while(1){ bzero(&buffer, B_SIZE); /*always clear the buffer*/ recv(client, &command, sizeof(command), 0); switch(command){ case 'c': recv(client, &buffer, B_SIZE, 0); check = check_file(client, buffer); //only when file doesn't exist, server will create the file. if(check == -1){ fp = fopen(buffer, "w"); fclose(fp); break; } case 'e': edit_file(client); break; case 'r': /* Here is the remove function. */ recv(client, &buffer, B_SIZE, 0); check = check_file(client, buffer); if(check==1) remove(buffer); break; case 'l': list_file(client); break; case 'd': trans_file(client); break; case 'q': break; } if(command == 'q') break; } close(socket_fd); return 0; }
void change_record()//change something in the database { fp=fopen("employee.dat","r"); if(check_file(fp)==TRUE) { fclose(fp); c=0;i=0; count=0; fp=fopen("employee.dat","r"); c=getc(fp); while(c!=EOF){if(c=='\n'){count++;}c=getc(fp);} fclose(fp); fp=fopen("employee.dat","r"); while(i<=count) { fscanf(fp,"%d %s %s %lf %lf %d %lf %lf",&DB[i].id,&DB[i].ln,&DB[i].fn,&DB[i].wh,&DB[i].pay,&DB[i].tax,&DB[i].g_inc,&DB[i].n_inc); i++; } fclose(fp); //LINEN printf("Please input a search code\r\n"); printf("1.by first name\r\n"); printf("2.by last name\r\n"); printf("3.By ID number\r\n"); scanf("%d",&answer); switch(answer) { case 1: { printf("Please enter a first name\r\n"); scanf("%s",&A.fn); for(i=0;i<=count;i++) { if(strcmp(A.fn,DB[i].fn)==0) { printf("\nID:%d\n Lname:%s\n fname:%s\n Hours:%lf\n pay:%lf\n tax:%d\n G-inc:%lf\n N-inc:%lf\r\n",DB[i].id,DB[i].ln,DB[i].fn,DB[i].wh,DB[i].pay,DB[i].tax,DB[i].g_inc,DB[i].n_inc); printf("Is this the person you are looking for?\r\n"); printf("Y or N\r\n"); scanf("%s",&answer1); if(answer1[0]=='y'||answer1[0]=='Y'){break;} } } //printf("i=%d,%d=count\r\n",i,count); if(i==(count+1)){NEMP} else { wait_for_user(); printf("Are you sure you want to change this person?\r\n"); printf("Y to change , N to go back to main menu\r\n"); scanf("%s",&answer2); if(answer2[0]=='y'||answer2[0]=='Y'){change_file(i);} else {options();} } break; } case 2: { printf("Please enter a last name\r\n"); scanf("%s",&A.ln); for(i=0;i<=count;i++) { if(strcmp(A.ln,DB[i].ln)==0) { printf("\nID:%d\n Lname:%s\n fname:%s\n Hours:%lf\n pay:%lf\n tax:%d\n G-inc:%lf\n N-inc:%lf\r\n",DB[i].id,DB[i].ln,DB[i].fn,DB[i].wh,DB[i].pay,DB[i].tax,DB[i].g_inc,DB[i].n_inc); printf("Is this the person you are looking for?\r\n"); printf("Y or N\r\n"); scanf("%s",&answer2); if(answer2[0]=='y'||answer2[0]=='Y'){break;} } } //printf("i=%d,%d=count\r\n",i,count); if(i==(count+1)){NEMP} else { wait_for_user(); printf("Are you sure you want to change this person?\r\n"); printf("Y to change , N to go back to main menu\r\n"); scanf("%s",&answer2); if(answer2[0]=='y'||answer2[0]=='Y'){change_file(i);} else {options();} } break; } default: { printf("Please enter the ID\r\n"); scanf("%d",&A.id); for(i=0;i<=count;i++) { if(A.id==DB[i].id) { printf("\nID:%d\n Lname:%s\n fname:%s\n Hours:%lf\n pay:%lf\n tax:%d\n G-inc:%lf\n N-inc:%lf\r\n",DB[i].id,DB[i].ln,DB[i].fn,DB[i].wh,DB[i].pay,DB[i].tax,DB[i].g_inc,DB[i].n_inc); printf("Is this the person you are looking for?\r\n"); printf("Y or N\r\n"); scanf("%s",&answer1); if(answer1[0]=='y'||answer1[0]=='Y'){break;} } } printf("i=%d,%d=count\r\n",i,count); if(i==count){NEMP} else { wait_for_user(); printf("Are you sure you want to change this person?\r\n"); printf("Y to change , N to go back to main menu\r\n"); scanf("%s",&answer2); if(answer2[0]=='y'||answer2[0]=='Y'){change_file(i);} else {options();} } break; } } }
static int lfs_f_setmode(lua_State *L) { return lfs_g_setmode(L, check_file(L, 1, "setmode"), 2); }
static void check_file_fopen(const char *filename, const char *mode) { if (!strcmp("r", mode)) check_file(filename, CRUMB_ACCESS_TYPE_READ, CRUMB_ACCESS_TYPE_OPEN_RDONLY); else if (!strcmp("r+", mode)) check_file(filename, CRUMB_ACCESS_TYPE_READ, CRUMB_ACCESS_TYPE_OPEN_RDONLY); else if (!strcmp("w", mode)) check_file(filename, CRUMB_ACCESS_TYPE_MODIFY, CRUMB_ACCESS_TYPE_CREATE_RDWR); else if (!strcmp("w+", mode)) check_file(filename, CRUMB_ACCESS_TYPE_MODIFY, CRUMB_ACCESS_TYPE_OPEN_RDWR); else if (!strcmp("a", mode)) check_file(filename, CRUMB_ACCESS_TYPE_MODIFY, CRUMB_ACCESS_TYPE_CREATE_RDWR); else if (!strcmp("a+", mode)) check_file(filename, CRUMB_ACCESS_TYPE_MODIFY, CRUMB_ACCESS_TYPE_OPEN_RDWR); else if (!strcmp("rb", mode)) check_file(filename, CRUMB_ACCESS_TYPE_READ, CRUMB_ACCESS_TYPE_OPEN_RDONLY); else if (!strcmp("r+b", mode)) check_file(filename, CRUMB_ACCESS_TYPE_READ, CRUMB_ACCESS_TYPE_OPEN_RDONLY); else if (!strcmp("wb", mode)) check_file(filename, CRUMB_ACCESS_TYPE_MODIFY, CRUMB_ACCESS_TYPE_CREATE_RDWR); else if (!strcmp("w+b", mode)) check_file(filename, CRUMB_ACCESS_TYPE_MODIFY, CRUMB_ACCESS_TYPE_OPEN_RDWR); else if (!strcmp("ab", mode)) check_file(filename, CRUMB_ACCESS_TYPE_MODIFY, CRUMB_ACCESS_TYPE_CREATE_RDWR); else if (!strcmp("a+b", mode)) check_file(filename, CRUMB_ACCESS_TYPE_MODIFY, CRUMB_ACCESS_TYPE_OPEN_RDWR); }
//! //! Loads an instance structure data from the instance.xml file under the instance's //! work blobstore path. //! //! @param[in] instanceId the instance identifier string (i-XXXXXXXX) //! //! @return A pointer to the instance structure if successful or otherwise NULL. //! //! @pre The instanceId parameter must not be NULL. //! //! @post On success, a newly allocated pointer to the instance is returned where the stateCode //! is set to NO_STATE. //! ncInstance *load_instance_struct(const char *instanceId) { DIR *insts_dir = NULL; char tmp_path[EUCA_MAX_PATH] = ""; char user_paths[EUCA_MAX_PATH] = ""; char checkpoint_path[EUCA_MAX_PATH] = ""; ncInstance *instance = NULL; struct dirent *dir_entry = NULL; struct stat mystat = { 0 }; // Allocate memory for our instance if ((instance = EUCA_ZALLOC(1, sizeof(ncInstance))) == NULL) { LOGERROR("out of memory (for instance struct)\n"); return (NULL); } // We know the instance indentifier euca_strncpy(instance->instanceId, instanceId, sizeof(instance->instanceId)); // we don't know userId, so we'll look for instanceId in every user's // directory (we're assuming that instanceIds are unique in the system) set_path(user_paths, sizeof(user_paths), NULL, NULL); if ((insts_dir = opendir(user_paths)) == NULL) { LOGERROR("failed to open %s\n", user_paths); goto free; } // Scan every path under the user path for one that conaints our instance while ((dir_entry = readdir(insts_dir)) != NULL) { snprintf(tmp_path, sizeof(tmp_path), "%s/%s/%s", user_paths, dir_entry->d_name, instance->instanceId); if (stat(tmp_path, &mystat) == 0) { // found it. Now save our user identifier euca_strncpy(instance->userId, dir_entry->d_name, sizeof(instance->userId)); break; } } // Done with the directory closedir(insts_dir); insts_dir = NULL; // Did we really find one? if (strlen(instance->userId) < 1) { LOGERROR("didn't find instance %s\n", instance->instanceId); goto free; } // set various instance-directory-relative paths in the instance struct set_instance_paths(instance); // Check if there is a binary checkpoint file, used by versions up to 3.3, // and load metadata from it (as part of a "warm" upgrade from 3.3.0 and 3.3.1). set_path(checkpoint_path, sizeof(checkpoint_path), instance, "instance.checkpoint"); set_path(instance->xmlFilePath, sizeof(instance->xmlFilePath), instance, INSTANCE_FILE_NAME); if (check_file(checkpoint_path) == 0) { ncInstance33 instance33; { // read in the checkpoint int fd = open(checkpoint_path, O_RDONLY); if (fd < 0) { LOGERROR("failed to load metadata for %s from %s: %s\n", instance->instanceId, checkpoint_path, strerror(errno)); goto free; } size_t meta_size = (size_t) sizeof(ncInstance33); assert(meta_size <= SSIZE_MAX); // beyond that read() behavior is unspecified ssize_t bytes_read = read(fd, &instance33, meta_size); close(fd); if (bytes_read < meta_size) { LOGERROR("metadata checkpoint for %s (%ld bytes) in %s is too small (< %ld)\n", instance->instanceId, bytes_read, checkpoint_path, meta_size); goto free; } } // Convert the 3.3 struct into the current struct. // Currently, a copy is sufficient, but if ncInstance // ever changes so that its beginning differs from ncInstanc33, // we may have to write something more elaborate or to break // the ability to upgrade from 3.3. We attempt to detect such a // change with the following if-statement, which compares offsets // in the structs of the last member in the 3.3 version. if (((unsigned long)&(instance->last_stat) - (unsigned long)instance) != ((unsigned long)&(instance33.last_stat) - (unsigned long)&instance33)) { LOGERROR("BUG: upgrade from v3.3 is not possible due to changes to instance struct\n"); goto free; } memcpy(instance, &instance33, sizeof(ncInstance33)); LOGINFO("[%s] upgraded instance checkpoint from v3.3\n", instance->instanceId); } else { // no binary checkpoint, so we expect an XML-formatted checkpoint if (read_instance_xml(instance->xmlFilePath, instance) != EUCA_OK) { LOGERROR("failed to read instance XML\n"); goto free; } } // Reset some fields for safety since they would now be wrong instance->stateCode = NO_STATE; instance->params.root = NULL; instance->params.kernel = NULL; instance->params.ramdisk = NULL; instance->params.swap = NULL; instance->params.ephemeral0 = NULL; // fix up the pointers vbr_parse(&(instance->params), NULL); // perform any upgrade-related manipulations to bring the struct up to date // save the struct back to disk after the upgrade routine had a chance to modify it if (gen_instance_xml(instance) != EUCA_OK) { LOGERROR("failed to create instance XML in %s\n", instance->xmlFilePath); goto free; } // remove the binary checkpoint because it is no longer needed and not used past 3.3 unlink(checkpoint_path); return (instance); free: EUCA_FREE(instance); return (NULL); }
/* * check_process_fds * check [process] open file descriptors * * in : pid * out : -1 if error * 0 if no match * 1 if match */ static int check_process_fds(fdOpenInfoRef info, int pid) { int buf_used; int i; int status; // get list of open file descriptors buf_used = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0); if (buf_used <= 0) { return -1; } while (1) { if (buf_used > info->fds_size) { // if we need to allocate [more] space while (buf_used > info->fds_size) { info->fds_size += (sizeof(struct proc_fdinfo) * 32); } if (info->fds == NULL) { info->fds = malloc(info->fds_size); } else { info->fds = reallocf(info->fds, info->fds_size); } if (info->fds == NULL) { return -1; } } buf_used = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, info->fds, (int)info->fds_size); if (buf_used <= 0) { return -1; } if ((buf_used + sizeof(struct proc_fdinfo)) >= info->fds_size) { // if not enough room in the buffer for an extra fd buf_used = (int)(info->fds_size + sizeof(struct proc_fdinfo)); continue; } info->fds_count = (int)(buf_used / sizeof(struct proc_fdinfo)); break; } // iterate through each file descriptor for (i = 0; i < info->fds_count; i++) { struct proc_fdinfo *fdp; fdp = &info->fds[i]; switch (fdp->proc_fdtype) { case PROX_FDTYPE_VNODE : { int buf_used; struct vnode_fdinfo vi; buf_used = proc_pidfdinfo(pid, fdp->proc_fd, PROC_PIDFDVNODEINFO, &vi, sizeof(vi)); if (buf_used <= 0) { if (errno == ENOENT) { /* * The file descriptor's vnode may have been revoked. This is a * bit of a hack, since an ENOENT error might not always mean the * descriptor's vnode has been revoked. As the libproc API * matures, this code may need to be revisited. */ continue; } return -1; } else if (buf_used < sizeof(vi)) { // if we didn't get enough information return -1; } if ((info->flags & PROC_LISTPIDSPATH_EXCLUDE_EVTONLY) && (vi.pfi.fi_openflags & O_EVTONLY)) { // if this file should be excluded continue; } status = check_file(info, &vi.pvi.vi_stat); if (status != 0) { // if error or match return status; } break; } default : break; } } return 0; }
/* * check_process_threads * check [process] thread working directories * * in : pid * out : -1 if error * 0 if no match * 1 if match */ static int check_process_threads(fdOpenInfoRef info, int pid) { int buf_used; int status; struct proc_taskallinfo tai; buf_used = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, sizeof(tai)); if (buf_used <= 0) { if (errno == ESRCH) { // if the process is gone return 0; } return -1; } else if (buf_used < sizeof(tai)) { // if we didn't get enough information return -1; } // check thread info if (tai.pbsd.pbi_flags & PROC_FLAG_THCWD) { int i; // get list of threads buf_used = tai.ptinfo.pti_threadnum * sizeof(uint64_t); while (1) { if (buf_used > info->thr_size) { // if we need to allocate [more] space while (buf_used > info->thr_size) { info->thr_size += (sizeof(uint64_t) * 32); } if (info->threads == NULL) { info->threads = malloc(info->thr_size); } else { info->threads = reallocf(info->threads, info->thr_size); } if (info->threads == NULL) { return -1; } } buf_used = proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, info->threads, (int)info->thr_size); if (buf_used <= 0) { return -1; } if ((buf_used + sizeof(uint64_t)) >= info->thr_size) { // if not enough room in the buffer for an extra thread buf_used = (int)(info->thr_size + sizeof(uint64_t)); continue; } info->thr_count = buf_used / sizeof(uint64_t); break; } // iterate through each thread for (i = 0; i < info->thr_count; i++) { uint64_t thr = info->threads[i]; struct proc_threadwithpathinfo tpi; buf_used = proc_pidinfo(pid, PROC_PIDTHREADPATHINFO, thr, &tpi, sizeof(tpi)); if (buf_used <= 0) { if ((errno == ESRCH) || (errno == EINVAL)) { // if the process or thread is gone continue; } } else if (buf_used < sizeof(tai)) { // if we didn't get enough information return -1; } status = check_file(info, &tpi.pvip.vip_vi.vi_stat); if (status != 0) { // if error or match return status; } } } return 0; }