void findfile(const char *p, const char *pat, void (func)(const char *)) { WIN32_FIND_DATAA FindFileData; HANDLE hFind; char tmppath[MAX_PATH+1]; const char *path = (p ==NULL)? "." : p; const char *pattern = (pat==NULL)? "" : pat; checkpath(tmppath,path); if(PATHSEP != tmppath[strlen(tmppath)-1]) strcat(tmppath, "\\*"); else strcat(tmppath, "*"); hFind = FindFirstFileA(tmppath, &FindFileData); if(hFind != INVALID_HANDLE_VALUE) { do { if(strcmp(FindFileData.cFileName, ".") == 0) continue; if(strcmp(FindFileData.cFileName, "..") == 0) continue; sprintf(tmppath,"%s%c%s",path,PATHSEP,FindFileData.cFileName); if(FindFileData.cFileName && strstr(FindFileData.cFileName, pattern)) { func(tmppath); } if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { findfile(tmppath, pat, func); } } while(FindNextFileA(hFind, &FindFileData) != 0); FindClose(hFind); } return; }
/*! Write to file. */ int write(uint32_t fd, const void *buffer, unsigned size) { uint8_t* addr_e; struct supp_table *st; /* Check the validity of given pointer */ if ((!checkva(buffer)) || (!checkva(buffer + size))) exit(-1); /* Checking we are not writing to unwritable pages. */ int write_size = 0; if (fd == STDOUT_FILENO) { /* If std-out, then write using putbuf() */ putbuf(buffer, size); write_size = size; } else { /* Otherwise, first find the file of this fd. */ struct f_info* f = findfile(fd); /* We should write to a directory just like a file. */ if (f->isdir) exit(-1); struct file* fout = f->f; off_t pos = f->pos; /* Write to the file at f->pos */ //lock_acquire(&filesys_lock); write_size = (int) file_write_at(fout, buffer, (off_t) size, pos); f->pos += (off_t) write_size; //lock_release(&filesys_lock); } return write_size; }
int select_preset (const gchar *preset) { int ret = SELECT_PRESET_OK; /* I'm copying this behavior as is. As it seems applying the * factory_defaults preset does nothing, which I'm not sure * if that was what the author intended. * -- Shlomi Fish */ if (strcmp (preset, factory_defaults)) { gchar *rel = g_build_filename ("Presets", preset, NULL); gchar *abs = findfile (rel); g_free (rel); if (abs) { if (load_preset (abs)) ret = SELECT_PRESET_LOAD_FAILED; g_free (abs); } else { ret = SELECT_PRESET_FILE_NOT_FOUND; } } if (ret == SELECT_PRESET_OK) { /* This is so the colorbrushes param (that is not stored in the * preset will be set correctly upon the preset loading. * */ set_colorbrushes (pcvals.selected_brush); } return ret; }
int openfile(char *name) { int ret=0; if(name[0] != '/') { printf("filename error"); return 0; } if(findfile(name)) { //open //return fd ret=1; } else // create new file { } return ret; }
bool Environment::run(const char *file) { #ifdef EXCEPTIONS_ENABLED lua_pushlightuserdata(L, (void *) wrap_exceptions); luaJIT_setmode(L, -1, LUAJIT_MODE_WRAPCFUNC | LUAJIT_MODE_ON); pop(1); #endif pushTrace(); int error = luaL_loadfile(L, findfile(file, "r")) || lua_pcall(L, 0, 0, 1); remove(1); if (error) { const char *errmsg = to(-1, wrapType<const char *>()); conoutf(CON_ERROR, "Could not execute file (%s):\n%s", file, errmsg); pop(1); return false; } return true; }
void getrptentries(RDArsrc *mainrsrc) { int x,selected=0; char *tmp=NULL,*dirx=NULL,*temp=NULL; if(FINDRSCGETINT(mainrsrc,"MODULE LIST",&selected)) return; if(rptavl!=NULL) freeapplib(rptavl); rptavl=APPlibNEW(); dirx=Rmalloc(RDAstrlen(CURRENTDIRECTORY)+RDAstrlen(modlstx->libs[selected])+3); #ifndef WIN32 sprintf(dirx,"%s/%s/",CURRENTDIRECTORY,modlstx->libs[selected]); #endif #ifdef WIN32 sprintf(dirx,"%s\\%s\\",CURRENTDIRECTORY,modlstx->libs[selected]); #endif for(x=0;findfile(dirx,"*.RPT",&tmp,(int)x+1);++x) { tmp[RDAstrlen(tmp)-4]=0; temp=stripdashes(tmp); addAPPlib(rptavl,temp); if(temp!=NULL) Rfree(temp); temp=NULL; } if(rptavl->numlibs<1) { addAPPlib(rptavl,"No Report Definitions Available"); } if(dirx!=NULL) Rfree(dirx); if(tmp!=NULL) Rfree(tmp); SORTAPPlib(rptavl); if(mainrsrc!=NULL) { if(!FINDRSCLISTAPPlib(mainrsrc,"REPORTS AVAILABLE",0,rptavl)) updatersrc(mainrsrc,"REPORTS AVAILABLE"); } setvalues(mainrsrc); }
static void getvrtentries(RDArsrc *mainrsrc) { int x,selectedm=0; char *tmp=NULL,*dirx=NULL; if(FINDRSCGETINT(mainrsrc,"MODULE LIST",&selectedm)) return; if(modlst!=NULL) { freeapplib(modlst); modlst=NULL; } modlst=APPlibNEW(); dirx=Rmalloc(RDAstrlen(CURRENTDIRECTORY)+6); #ifndef WIN32 sprintf(dirx,"%s/rda/",CURRENTDIRECTORY); #endif #ifdef WIN32 sprintf(dirx,"%s\\rda\\",CURRENTDIRECTORY); #endif for(x=0;findfile(dirx,"*.TBL",&tmp,(int)x+1);++x) { tmp[RDAstrlen(tmp)-4]=0; addAPPlib(modlst,tmp); } if(modlst->numlibs<1) { addAPPlib(modlst,"Contains No Database Libraries"); selectedm=0; } else { SORTAPPlib(modlst); if(selectedm>=modlst->numlibs) selectedm=0; } if(tmp!=NULL) Rfree(tmp); if(dirx!=NULL) Rfree(dirx); if(!FINDRSCLISTAPPlib(mainrsrc,"MODULE LIST",selectedm,modlst)) { updatersrc(mainrsrc,"MODULE LIST"); } domodulelist(mainrsrc); }
/* main, menu */ void makedir (void) { register char *p; if (! (p = getstring (60, NULL, " Make directory ", "Create the directory"))) return; switch (exist (p)) { default: case 'f': error ("File %s exists", p); break; case 'd': error ("Directory %s already exists", p); break; case 0: if (runl(1, "/bin/mkdir", "mkdir", p, NULL)) { error ("Cannot create directory %s", p); break; } setdir (cur == left ? right : left, NULL); setdir (cur, NULL); findfile (cur, p); break; } }
int main(int argc, char *argv[]) { int n, l, complete_type = 0, not_allowed = 0, argv_mode = 0; #ifdef USING_GLFTPD int gnum = 0, unum = 0; char myflags[20]; #endif char *ext, exec[4096], *complete_bar = 0, *inc_point[2]; unsigned int crc; struct stat fileinfo; uid_t f_uid; gid_t f_gid; double temp_time = 0; DIR *dir, *parent; struct dirent *dp; long loc; time_t timenow; #if (test_for_password || extract_nfo || zip_clean) off_t tempstream; #endif short rescan_quick = rescan_default_to_quick; char one_name[NAME_MAX]; char *temp_p = NULL; int chdir_allowed = 0, argnum = 0; GLOBAL g; #if (enable_rescan_script) char target[PATH_MAX+NAME_MAX]; #endif #if ( program_uid > 0 ) setegid(program_gid); seteuid(program_uid); #endif umask(0666 & 000); d_log("rescan: PZS-NG (rescan v2) %s debug log.\n", ng_version); d_log("rescan: Rescan executed by: (uid/gid) %d/%d\n", geteuid(), getegid()); #ifdef _ALT_MAX d_log("rescan: PATH_MAX not found - using predefined settings! Please report to the devs!\n"); #endif d_log("rescan: Allocating memory for variables\n"); g.ui = ng_realloc2(g.ui, sizeof(*g.ui) * 30, 1, 1, 1); g.gi = ng_realloc2(g.gi, sizeof(*g.gi) * 30, 1, 1, 1); bzero(one_name, NAME_MAX); #ifdef USING_GLFTPD if (getenv("FLAGS")) { strlcpy(myflags, getenv("FLAGS"), sizeof(myflags)); n = strlen(myflags); while (n > 0) { --n; l = strlen(rescan_chdir_flags); while(l > 0) { --l; if (myflags[n] == rescan_chdir_flags[l]) chdir_allowed = 1; } } } if (!geteuid()) chdir_allowed = 1; #endif /* With glftpd we can use env vars, rest of the world: commandline. */ #ifndef USING_GLFTPD if (argc < 7) { print_syntax(chdir_allowed); ng_free(g.ui); ng_free(g.gi); return 0; } argnum = 6; if (chdir(argv[5]) != 0) { printf("Could not chdir to <cwd = '%s'>, ftpd agnostic mode: %s\n", argv[5], strerror(errno)); d_log("rescan: Could not chdir to <cwd = '%s'>, ftpd agnostic mode: %s\n", argv[5], strerror(errno)); ng_free(g.ui); ng_free(g.gi); return 1; } #else argnum = 1; #endif while ((argnum < argc) && argc > 1) { if (!strncasecmp(argv[argnum], "--quick", 7)) rescan_quick = TRUE; else if (!strncasecmp(argv[argnum], "--normal", 8)) rescan_quick = FALSE; else if (!strncasecmp(argv[argnum], "--dir=", 6) && (strlen(argv[argnum]) > 7) && chdir_allowed) { temp_p = argv[argnum] + 6; if ((!matchpath(nocheck_dirs, temp_p)) && (matchpath(zip_dirs, temp_p) || matchpath(sfv_dirs, temp_p)) && !matchpath(group_dirs, temp_p)) { if (chdir(temp_p)) { d_log("rescan: Failed to chdir() to %s : %s\n", temp_p, strerror(errno)); not_allowed = 1; } } else { printf("Not allowed to chdir() to %s\n", temp_p); ng_free(g.ui); ng_free(g.gi); return 1; } printf("PZS-NG Rescan %s: Rescanning %s\n", ng_version, temp_p); argv_mode = 1; } else if (!strncasecmp(argv[argnum], "--chroot=", 9) && (strlen(argv[argnum]) > 10) && chdir_allowed) { if (temp_p == NULL) { temp_p = argv[argnum] + 9; if (chroot(temp_p) == -1) { d_log("rescan: Failed to chroot() to %s : %s\n", temp_p, strerror(errno)); not_allowed = 1; } } else { temp_p = argv[argnum] + 9; printf("Not allowed to chroot() to %s\n", temp_p); ng_free(g.ui); ng_free(g.gi); return 1; } printf("PZS-NG Rescan %s: Chroot'ing to %s\n", ng_version, temp_p); argv_mode = 1; } else if (!strncasecmp(argv[argnum], "--help", 6) || !strncasecmp(argv[argnum], "/?", 2) || !strncasecmp(argv[argnum], "--?", 3)) { print_syntax(chdir_allowed); ng_free(g.ui); ng_free(g.gi); return 0; } else { strlcpy(one_name, argv[argnum], sizeof(one_name)); rescan_quick = FALSE; printf("PZS-NG Rescan %s: Rescanning in FILE mode\n", ng_version); if (one_name[strlen(one_name) - 1] == '*') { one_name[strlen(one_name) - 1] = '\0'; } else if (!fileexists(one_name)) { d_log("PZS-NG Rescan: No file named '%s' exists.\n", one_name); one_name[0] = '\0'; not_allowed = 1; } argv_mode = 1; } argnum++; } if (one_name[0] == '\0') { if (rescan_quick == TRUE) { printf("PZS-NG Rescan %s: Rescanning in QUICK mode.\n", ng_version); } else { printf("PZS-NG Rescan %s: Rescanning in NORMAL mode.\n", ng_version); } } printf("PZS-NG Rescan %s: Use --help for options.\n\n", ng_version); if (not_allowed) { ng_free(g.ui); ng_free(g.gi); return 1; } if (!getcwd(g.l.path, PATH_MAX)) { d_log("rescan: getcwd() failed: %s\n", strerror(errno)); } if (subcomp(g.l.path, g.l.basepath) && (g.l.basepath[0] == '\0')) strlcpy(g.l.basepath, g.l.path, sizeof(g.l.basepath)); if (strncmp(g.l.path, g.l.basepath, PATH_MAX)) d_log("rescan: We are in subdir of %s\n", g.l.basepath); strlcpy(g.v.misc.current_path, g.l.path, sizeof(g.v.misc.current_path)); strlcpy(g.v.misc.basepath, g.l.basepath, sizeof(g.v.misc.basepath)); if ((matchpath(nocheck_dirs, g.l.path) && !rescan_nocheck_dirs_allowed) || (matchpath(group_dirs, g.l.path) && argv_mode) || (!matchpath(nocheck_dirs, g.l.path) && !matchpath(zip_dirs, g.l.path) && !matchpath(sfv_dirs, g.l.path) && !matchpath(group_dirs, g.l.path)) || insampledir(g.l.path)) { d_log("rescan: Dir matched with nocheck_dirs/sample_list, or is not in the zip/sfv/group-dirs.\n"); d_log("rescan: Freeing memory, and exiting.\n"); printf("Notice: Unable to rescan this dir - check config.\n\n"); ng_free(g.ui); ng_free(g.gi); return 0; } g.v.misc.slowest_user[0] = ULONG_MAX; bzero(&g.v.total, sizeof(struct race_total)); g.v.misc.fastest_user[0] = 0; g.v.misc.release_type = RTYPE_NULL; g.v.misc.write_log = 0; #ifdef USING_GLFTPD if (getenv("SECTION") == NULL) { sprintf(g.v.sectionname, "DEFAULT"); } else { snprintf(g.v.sectionname, sizeof(g.v.sectionname), "%s", getenv("SECTION")); } #else snprintf(g.v.sectionname, sizeof(g.v.sectionname), argv[4]); #endif g.l.length_path = (int)strlen(g.l.path); g.l.length_zipdatadir = sizeof(storage); n = g.l.length_path + g.l.length_zipdatadir + 11; g.l.race = ng_realloc2(g.l.race, n, 1, 1, 1); g.l.sfv = ng_realloc2(g.l.sfv, n - 1, 1, 1, 1); g.l.sfvbackup = ng_realloc2(g.l.sfvbackup, n + 1, 1, 1, 1); g.l.leader = ng_realloc2(g.l.leader, n - 2, 1, 1, 1); g.l.sfv_incomplete = 0; getrelname(&g); #ifdef USING_GLFTPD gnum = buffer_groups(GROUPFILE, 0); unum = buffer_users(PASSWDFILE, 0); #endif sprintf(g.l.sfv, storage "/%s/sfvdata", g.l.path); sprintf(g.l.sfvbackup, storage "/%s/sfvbackup", g.l.path); sprintf(g.l.leader, storage "/%s/leader", g.l.path); sprintf(g.l.race, storage "/%s/racedata", g.l.path); d_log("rescan: Creating directory to store racedata in\n"); maketempdir(g.l.path); d_log("rescan: Locking release\n"); while (1) { if ((l = create_lock(&g.v, g.l.path, PROGTYPE_RESCAN, 3, 0))) { d_log("rescan: Failed to lock release.\n"); if (l == 1) { d_log("rescan: version mismatch. Exiting.\n"); printf("Error. You need to rm -fR ftp-data/pzs-ng/* before rescan will work.\n"); /* */ ng_free(g.ui); ng_free(g.gi); ng_free(g.l.sfv); ng_free(g.l.sfvbackup); ng_free(g.l.leader); ng_free(g.l.race); #ifdef USING_GLFTPD buffer_groups(GROUPFILE, gnum); buffer_users(PASSWDFILE, unum); #endif exit(EXIT_FAILURE); } if (l == PROGTYPE_POSTDEL) { n = (signed int)g.v.data_incrementor; d_log("rescan: Detected postdel running - sleeping for one second.\n"); if (!create_lock(&g.v, g.l.path, PROGTYPE_RESCAN, 0, g.v.data_queue)) break; usleep(1000000); if (!create_lock(&g.v, g.l.path, PROGTYPE_RESCAN, 0, g.v.data_queue)) break; if ( n == (signed int)g.v.data_incrementor) { d_log("rescan: Failed to get lock. Forcing unlock.\n"); if (create_lock(&g.v, g.l.path, PROGTYPE_RESCAN, 2, g.v.data_queue)) { d_log("rescan: Failed to force a lock.\n"); d_log("rescan: Exiting with error.\n"); ng_free(g.ui); ng_free(g.gi); ng_free(g.l.sfv); ng_free(g.l.sfvbackup); ng_free(g.l.leader); ng_free(g.l.race); #ifdef USING_GLFTPD buffer_groups(GROUPFILE, gnum); buffer_users(PASSWDFILE, unum); #endif exit(EXIT_FAILURE); } break; } } else { for (l = 0; l <= max_seconds_wait_for_lock * 10; ++l) { d_log("rescan: sleeping for .1 second before trying to get a lock (queue: %d).\n", g.v.data_queue); usleep(100000); if (!create_lock(&g.v, g.l.path, PROGTYPE_RESCAN, 0, g.v.data_queue)) break; } if (l >= max_seconds_wait_for_lock * 10) { d_log("rescan: Failed to get lock. Will not force unlock.\n"); ng_free(g.ui); ng_free(g.gi); ng_free(g.l.sfv); ng_free(g.l.sfvbackup); ng_free(g.l.leader); ng_free(g.l.race); #ifdef USING_GLFTPD buffer_groups(GROUPFILE, gnum); buffer_users(PASSWDFILE, unum); #endif exit(EXIT_FAILURE); } } } usleep(10000); if (update_lock(&g.v, 1, 0) != -1) break; } move_progress_bar(1, &g.v, g.ui, g.gi); if (g.l.incomplete) unlink(g.l.incomplete); if (del_completebar) removecomplete(); dir = opendir("."); parent = opendir(".."); if (!((rescan_quick && findfileext(dir, ".sfv")) || *one_name)) { if (g.l.sfv) unlink(g.l.sfv); if (g.l.race) unlink(g.l.race); } printf("Rescanning files...\n"); if (findfileext(dir, ".zip")) { if (!fileexists(unzip_bin)) { printf("rescan: ERROR! Not able to check zip-files - %s does not exist!\n", unzip_bin); closedir(dir); closedir(parent); ng_free(g.ui); ng_free(g.gi); ng_free(g.l.sfv); ng_free(g.l.sfvbackup); ng_free(g.l.leader); ng_free(g.l.race); #ifdef USING_GLFTPD buffer_groups(GROUPFILE, gnum); buffer_users(PASSWDFILE, unum); #endif remove_lock(&g.v); exit(EXIT_FAILURE); } else { crc = 0; rewinddir(dir); timenow = time(NULL); while ((dp = readdir(dir))) { ext = find_last_of(dp->d_name, "."); if (*ext == '.') ext++; if (!strcasecmp(ext, "zip")) { stat(dp->d_name, &fileinfo); f_uid = fileinfo.st_uid; f_gid = fileinfo.st_gid; if ((timenow == fileinfo.st_ctime) && (fileinfo.st_mode & 0111)) { d_log("rescan.c: Seems this file (%s) is in the process of being uploaded. Ignoring for now.\n", dp->d_name); continue; } #ifdef USING_GLFTPD strlcpy(g.v.user.name, get_u_name(f_uid), sizeof(g.v.user.name)); strlcpy(g.v.user.group, get_g_name(f_gid), sizeof(g.v.user.group)); #else strlcpy(g.v.user.name, argv[1], sizeof(g.v.user.name)); strlcpy(g.v.user.group, argv[2], sizeof(g.v.user.group)); #endif strlcpy(g.v.file.name, dp->d_name, sizeof(g.v.file.name)); g.v.file.speed = 2005 * 1024; g.v.file.size = fileinfo.st_size; g.v.total.start_time = 0; #if (test_for_password || extract_nfo) tempstream = telldir(dir); if ((!findfileextcount(dir, ".nfo") || findfileextcount(dir, ".zip")) && !mkdir(".unzipped", 0777)) snprintf(exec, sizeof(exec), "%s -qqjo \"%s\" -d .unzipped 2>.delme", unzip_bin, g.v.file.name); else snprintf(exec, sizeof(exec), "%s -qqt \"%s\" 2>.delme", unzip_bin, g.v.file.name); seekdir(dir, tempstream); #else snprintf(exec, sizeof(exec), "%s -qqt \"%s\" 2>.delme", unzip_bin, g.v.file.name); #endif if (system(exec) == 0 || (allow_error2_in_unzip == TRUE && errno < 3 )) { writerace(g.l.race, &g.v, crc, F_CHECKED); } else { writerace(g.l.race, &g.v, crc, F_BAD); if (g.v.file.name) unlink(g.v.file.name); removedir(".unzipped"); continue; } #if (test_for_password || extract_nfo || zip_clean) tempstream = telldir(dir); if ((!findfileextcount(dir, ".nfo") || findfileextcount(dir, ".zip")) && check_zipfile(".unzipped", g.v.file.name, findfileextcount(dir, ".nfo"))) { d_log("rescan: File %s is password protected.\n", g.v.file.name); writerace(g.l.race, &g.v, crc, F_BAD); if (g.v.file.name) unlink(g.v.file.name); seekdir(dir, tempstream); continue; } seekdir(dir, tempstream); #endif if (!fileexists("file_id.diz")) { snprintf(exec, sizeof(exec), "%s -qqjnCLL \"%s\" file_id.diz 2>.delme", unzip_bin, g.v.file.name); if (execute(exec) != 0) { d_log("rescan: No file_id.diz found (#%d): %s\n", errno, strerror(errno)); } else { if (fileexists("file_id.diz.bad")) { loc = findfile(dir, "file_id.diz.bad"); seekdir(dir, loc); dp = readdir(dir); unlink(dp->d_name); } if (chmod("file_id.diz", 0666)) d_log("rescan: Failed to chmod %s: %s\n", "file_id.diz", strerror(errno)); } } } } if (fileexists(".delme")) unlink(".delme"); g.v.total.files = read_diz(); if (!g.v.total.files) { g.v.total.files = 1; unlink("file_id.diz"); } g.v.total.files_missing = g.v.total.files; readrace(g.l.race, &g.v, g.ui, g.gi); sortstats(&g.v, g.ui, g.gi); if (g.v.total.files_missing < 0) { g.v.total.files -= g.v.total.files_missing; g.v.total.files_missing = 0; } buffer_progress_bar(&g.v); if (g.v.total.files_missing == 0) { complete(&g, complete_type); createstatusbar(convert(&g.v, g.ui, g.gi, zip_completebar)); #if (chmod_completebar) if (!matchpath(group_dirs, g.l.path)) { if (chmod_each(convert(&g.v, g.ui, g.gi, zip_completebar), 0222)) d_log("rescan: Failed to chmod a statusbar: %s\n", strerror(errno)); } #endif } else { if (!matchpath(group_dirs, g.l.path) || create_incomplete_links_in_group_dirs) { if (create_incomplete()) { d_log("rescan: create_incomplete() returned something\n"); } } move_progress_bar(0, &g.v, g.ui, g.gi); } if (g.l.nfo_incomplete) { if (findfileext(dir, ".nfo")) { d_log("rescan: Removing missing-nfo indicator (if any)\n"); remove_nfo_indicator(&g); } else if (matchpath(check_for_missing_nfo_dirs, g.l.path) && (!matchpath(group_dirs, g.l.path) || create_incomplete_links_in_group_dirs)) { if (!g.l.in_cd_dir) { d_log("rescan: Creating missing-nfo indicator %s.\n", g.l.nfo_incomplete); if (create_incomplete_nfo()) { d_log("rescan: create_incomplete_nfo() returned something\n"); } } else { if (findfileextparent(parent, ".nfo")) { d_log("rescan: Removing missing-nfo indicator (if any)\n"); remove_nfo_indicator(&g); } else { d_log("rescan: Creating missing-nfo indicator (base) %s.\n", g.l.nfo_incomplete); if (create_incomplete_nfo()) { d_log("rescan: create_incomplete_nfo() returned something\n"); } } } } } } } else if ((temp_p = findfileext(dir, ".sfv")) || (create_missing_sfv && file_count(dir))) { if (!temp_p && create_missing_sfv && file_count(dir)) { d_log("rescan: No sfv found - creating one.\n"); make_sfv(g.l.path); if (!(temp_p = findfileext(dir, ".sfv"))) { d_log("rescan: Freeing memory, removing lock and exiting.\n"); unlink(g.l.sfv); if (fileexists(g.l.sfvbackup)) unlink(g.l.sfvbackup); unlink(g.l.race); closedir(dir); closedir(parent); ng_free(g.ui); ng_free(g.gi); ng_free(g.l.sfv); ng_free(g.l.sfvbackup); ng_free(g.l.leader); ng_free(g.l.race); #ifdef USING_GLFTPD buffer_groups(GROUPFILE, gnum); buffer_users(PASSWDFILE, unum); #endif remove_lock(&g.v); return 0; } } #if ( create_missing_sfv_link == TRUE ) d_log("rescan: Removing missing-sfv indicator (if any)\n"); unlink(g.l.sfv_incomplete); #endif strlcpy(g.v.file.name, temp_p, sizeof(g.v.file.name)); maketempdir(g.l.path); stat(g.v.file.name, &fileinfo); if (copysfv(g.v.file.name, g.l.sfv, &g.v)) { printf("Found invalid entries in SFV - Exiting.\n"); while ((dp = readdir(dir))) { ext = find_last_of(dp->d_name, "-"); if (!strcasecmp(ext, "-missing")) unlink(dp->d_name); } d_log("rescan: Freeing memory, removing lock and exiting\n"); unlink(g.l.sfv); if (fileexists(g.l.sfvbackup)) unlink(g.l.sfvbackup); unlink(g.l.race); closedir(dir); closedir(parent); ng_free(g.ui); ng_free(g.gi); ng_free(g.l.sfv); ng_free(g.l.sfvbackup); ng_free(g.l.leader); ng_free(g.l.race); #ifdef USING_GLFTPD buffer_groups(GROUPFILE, gnum); buffer_users(PASSWDFILE, unum); #endif remove_lock(&g.v); return 0; } g.v.total.start_time = 0; rewinddir(dir); while ((dp = readdir(dir))) { if (*one_name && strncasecmp(one_name, dp->d_name, strlen(one_name))) continue; l = (int)strlen(dp->d_name); ext = find_last_of(dp->d_name, ".-"); if (*ext == '.') ext++; if (!update_lock(&g.v, 1, 0)) { d_log("rescan: Another process wants the lock - will comply and remove lock, then exit.\n"); closedir(dir); closedir(parent); ng_free(g.ui); ng_free(g.gi); ng_free(g.l.sfv); ng_free(g.l.sfvbackup); ng_free(g.l.leader); ng_free(g.l.race); #ifdef USING_GLFTPD buffer_groups(GROUPFILE, gnum); buffer_users(PASSWDFILE, unum); #endif remove_lock(&g.v); exit(EXIT_FAILURE); } if ( !strcomp(ignored_types, ext) && (!(strcomp(allowed_types, ext) && !matchpath(allowed_types_exemption_dirs, g.l.path))) && strcasecmp("sfv", ext) && strcasecmp("nfo", ext) && strcasecmp("bad", ext) && strcasecmp("-missing", ext) && strncmp(dp->d_name, ".", 1) ) { stat(dp->d_name, &fileinfo); if (S_ISDIR(fileinfo.st_mode)) continue; if (ignore_zero_sized_on_rescan && !fileinfo.st_size) continue; f_uid = fileinfo.st_uid; f_gid = fileinfo.st_gid; #ifdef USING_GLFTPD strlcpy(g.v.user.name, get_u_name(f_uid), sizeof(g.v.user.name)); strlcpy(g.v.user.group, get_g_name(f_gid), sizeof(g.v.user.group)); #else strlcpy(g.v.user.name, argv[1], sizeof(g.v.user.name)); strlcpy(g.v.user.group, argv[2], sizeof(g.v.user.group)); #endif strlcpy(g.v.file.name, dp->d_name, sizeof(g.v.file.name)); g.v.file.speed = 2005 * 1024; g.v.file.size = fileinfo.st_size; temp_time = fileinfo.st_mtime; if (g.v.total.start_time == 0) g.v.total.start_time = temp_time; else g.v.total.start_time = (g.v.total.start_time < temp_time ? g.v.total.start_time : temp_time); g.v.total.stop_time = (temp_time > g.v.total.stop_time ? temp_time : g.v.total.stop_time); /* Hide users in group_dirs */ if (matchpath(group_dirs, g.l.path) && (hide_group_uploaders == TRUE)) { d_log("rescan: Hiding user in group-dir:\n"); if ((int)strlen(hide_gname) > 0) { snprintf(g.v.user.group, sizeof(g.v.user.group), "%s", hide_gname); d_log("rescan: Changing groupname\n"); } if ((int)strlen(hide_uname) > 0) { snprintf(g.v.user.name, sizeof(g.v.user.name), "%s", hide_uname); d_log("rescan: Changing username\n"); } #if (show_users_in_group_dirs == FALSE) if ((int)strlen(hide_uname) == 0) { d_log("rescan: Making username = groupname\n"); snprintf(g.v.user.name, sizeof(g.v.user.name), "%s", g.v.user.group); } #endif } if (!rescan_quick || (g.l.race && !match_file(g.l.race, dp->d_name))) crc = calc_crc32(dp->d_name); else crc = 1; if (!S_ISDIR(fileinfo.st_mode)) { if (g.v.file.name) unlink_missing(g.v.file.name); if (l > 44) { if (crc == 1) printf("\nFile: %s CHECKED", dp->d_name + l - 44); else printf("\nFile: %s %.8x", dp->d_name + l - 44, crc); } else { if (crc == 1) printf("\nFile: %-44s CHECKED", dp->d_name); else printf("\nFile: %-44s %.8x", dp->d_name, crc); } } if(fflush(stdout)) d_log("rescan: ERROR: %s\n", strerror(errno)); if (!rescan_quick || (g.l.race && !match_file(g.l.race, dp->d_name)) || !fileexists(dp->d_name)) writerace(g.l.race, &g.v, crc, F_NOTCHECKED); } } printf("\n"); testfiles(&g.l, &g.v, 1); printf("\n"); readsfv(g.l.sfv, &g.v, 0); readrace(g.l.race, &g.v, g.ui, g.gi); sortstats(&g.v, g.ui, g.gi); buffer_progress_bar(&g.v); if (g.l.nfo_incomplete) { if (findfileext(dir, ".nfo")) { d_log("rescan: Removing missing-nfo indicator (if any)\n"); remove_nfo_indicator(&g); } else if (matchpath(check_for_missing_nfo_dirs, g.l.path) && (!matchpath(group_dirs, g.l.path) || create_incomplete_links_in_group_dirs)) { if (!g.l.in_cd_dir) { d_log("rescan: Creating missing-nfo indicator %s.\n", g.l.nfo_incomplete); if (create_incomplete_nfo()) { d_log("rescan: create_incomplete_nfo() returned something\n"); } } else { if (findfileextparent(parent, ".nfo")) { d_log("rescan: Removing missing-nfo indicator (if any)\n"); remove_nfo_indicator(&g); } else { d_log("rescan: Creating missing-nfo indicator (base) %s.\n", g.l.nfo_incomplete); /* This is not pretty, but should be functional. */ if ((inc_point[0] = find_last_of(g.l.path, "/")) != g.l.path) *inc_point[0] = '\0'; if ((inc_point[1] = find_last_of(g.v.misc.release_name, "/")) != g.v.misc.release_name) *inc_point[1] = '\0'; if (create_incomplete_nfo()) { d_log("rescan: create_incomplete_nfo() returned something\n"); } if (*inc_point[0] == '\0') *inc_point[0] = '/'; if (*inc_point[1] == '\0') *inc_point[1] = '/'; } } } } #if (create_missing_sample_link) if (g.l.sample_incomplete) { if (findfileextsub(dir) || matchpartialdirname(missing_sample_check_ignore_list, g.v.misc.release_name, missing_sample_check_ignore_dividers)) { d_log("rescan: Removing missing-sample indicator (if any)\n"); remove_sample_indicator(&g); } else if (matchpath(check_for_missing_sample_dirs, g.l.path) && (!matchpath(group_dirs, g.l.path) || create_incomplete_links_in_group_dirs)) { if (!g.l.in_cd_dir) { d_log("rescan: Creating missing-sample indicator %s.\n", g.l.sample_incomplete); if (create_incomplete_sample()) { d_log("rescan: create_incomplete_sample() returned something\n"); } } else { if (findfileextsubp(dir)) { d_log("rescan: Removing missing-sample indicator (if any)\n"); remove_sample_indicator(&g); } else { d_log("rescan: Creating missing-sample indicator (base) %s.\n", g.l.sample_incomplete); /* This is not pretty, but should be functional. */ if ((inc_point[0] = find_last_of(g.l.path, "/")) != g.l.path) *inc_point[0] = '\0'; if ((inc_point[1] = find_last_of(g.v.misc.release_name, "/")) != g.v.misc.release_name) *inc_point[1] = '\0'; if (create_incomplete_sample()) { d_log("rescan: create_incomplete_sample() returned something\n"); } if (*inc_point[0] == '\0') *inc_point[0] = '/'; if (*inc_point[1] == '\0') *inc_point[1] = '/'; } } } } #endif if (g.v.misc.release_type == RTYPE_AUDIO) { get_audio_info(findfileextfromlist(dir, audio_types), &g.v.audio); /* Sort if we're not in a group-dir/nosort-dir. */ if (!matchpath(group_dirs, g.l.path) && !matchpath(audio_nosort_dirs, g.l.path)) { printf(" Resorting release.\n"); audioSort(&g.v.audio, g.l.link_source, g.l.link_target); } } if ((g.v.total.files_missing == 0) && (g.v.total.files > 0)) { switch (g.v.misc.release_type) { case RTYPE_RAR: complete_bar = rar_completebar; break; case RTYPE_OTHER: complete_bar = other_completebar; break; case RTYPE_AUDIO: complete_bar = audio_completebar; #if ( create_m3u == TRUE ) n = snprintf(exec, sizeof(exec), "%s", findfileext(dir, ".sfv")); strcpy(exec + n - 3, "m3u"); create_indexfile(g.l.race, &g.v, exec); #endif break; case RTYPE_VIDEO: complete_bar = video_completebar; break; } complete(&g, complete_type); if (complete_bar) { createstatusbar(convert(&g.v, g.ui, g.gi, complete_bar)); #if (chmod_completebar) if (!matchpath(group_dirs, g.l.path)) { if (chmod_each(convert(&g.v, g.ui, g.gi, complete_bar), 0222)) d_log("rescan: Failed to chmod a statusbar: %s\n", strerror(errno)); } #endif } #if (enable_rescan_script) d_log("rescan: Executing rescan_script script\n"); if (!fileexists(rescan_script)) { d_log("rescan: Warning - rescan_script (%s) - file does not exist!\n", rescan_script); } else { snprintf(target, sizeof(target), rescan_script " \"%s\"", g.v.file.name); if (execute(target) != 0) d_log("rescan: Failed to execute rescan_script: %s\n", strerror(errno)); } #endif } else { if (!matchpath(group_dirs, g.l.path) || create_incomplete_links_in_group_dirs) { if (create_incomplete()) { d_log("rescan: create_incomplete() returned something\n"); } } move_progress_bar(0, &g.v, g.ui, g.gi); } } else { int empty = 1; #if (create_missing_sfv_link == TRUE) if ((!matchpath(group_dirs, g.l.path) || create_incomplete_links_in_group_dirs) && g.l.sfv_incomplete && !matchpath(nocheck_dirs, g.l.path) && !matchpath(allowed_types_exemption_dirs, g.l.path)) { rewinddir(dir); while ((dp = readdir(dir))) { stat(dp->d_name, &fileinfo); if (S_ISREG(fileinfo.st_mode)) { ext = find_last_of(dp->d_name, "."); if (*ext == '.') ext++; if (*ext && get_filetype(&g, ext) == 3) { d_log("rescan: Creating missing-sfv indicator %s.\n", g.l.sfv_incomplete); if (create_incomplete_sfv()) d_log("rescan: create_incomplete_sfv() returned something.\n"); empty = 0; break; } } } } #endif if (empty && mark_empty_dirs_as_incomplete_on_rescan) { if (create_incomplete()) { d_log("rescan: create_incomplete() returned something\n"); } printf(" Empty dir - marking as incomplete.\n"); } } printf(" Passed : %i\n", (int)g.v.total.files - (int)g.v.total.files_missing); printf(" Failed : %i\n", (int)g.v.total.files_bad); printf(" Missing: %i\n", (int)g.v.total.files_missing); printf(" Total : %i\n", (int)g.v.total.files); if (g.v.total.files && !g.v.total.files_missing) { g.v.misc.data_completed = 1; } else { g.v.misc.data_completed = 0; } d_log("rescan: Freeing memory and removing lock.\n"); closedir(dir); closedir(parent); ng_free(g.l.race); ng_free(g.l.sfv); ng_free(g.l.sfvbackup); ng_free(g.l.leader); remove_lock(&g.v); updatestats_free(&g); #ifdef USING_GLFTPD buffer_groups(GROUPFILE, gnum); buffer_users(PASSWDFILE, unum); #endif exit(0); }
/* main, menu */ void renmove (void) { char buf [MAXPATHLEN+20]; char *name; register struct file *p; register c; int done, all, ch; int exd, exf; if (c = tagged ()) { /* move group of files */ sprintf (buf, "Rename or move %d file%s to", c, c>1 ? "s" : ""); if (! (name = getstring (60, (cur==left?right:left)->cwd, " Rename ", buf))) return; runset (name); exd = exist (name); all = 0; for (p=cur->d.cat; p<cur->d.cat+cur->d.num; ++p) if (p->tag) { sprintf (buf, "%s/%s", name, p->name); exf = exd=='d' ? exist (buf) : 0; if (exd=='f' || exf=='f') { if (! all) { ch = getchoice (1, " Rename ", "File exists", exf=='f' ? buf : name, " Overwrite ", " All ", " Cancel "); switch (ch) { default: case 2: /* cancel */ continue; case 1: /* all */ all = 1; } } } else if (exf == 'd') { error ("%s is a directory", buf); continue; } runarg (p->name); } message (" Move ", "Moving %d file%s to %s ...", c, c>1 ? "s" : "", name); done = rundone ("/bin/mv", "mv"); if (done) { endmesg (); message (" Move ", "Done"); } else error ("Error while moving %d file%s to %s", c, c>1 ? "s" : "", name); endmesg (); name = 0; } else if ((c = (p = &cur->d.cat[cur->d.curfile])->mode & S_IFMT) == S_IFDIR) { /* rename directory */ sprintf (buf, "Rename \"%s\" to", strtail (p->name, '/', 60)); if (! (name = getstring (60, (cur==left?right:left)->cwd, " Rename ", buf))) return; exd = exist (name); sprintf (buf, "%s/%s", name, p->name); exf = exd=='d' ? exist (buf) : 0; if (exd=='f' || exf=='f') { if (getchoice (1, " Rename ", "File exists", exf=='f' ? buf : name, " Overwrite ", " Cancel ", NULL)) return; } else if (exf == 'd') { error ("Directory %s exists", buf); return; } if (runl(1, "/bin/mv", "mv", p->name, name, NULL)) { error ("Cannot move %s to %s", p->name, name); return; } } else if (c == S_IFREG) { /* move regular file */ sprintf (buf, "Rename or move \"%s\" to", p->name); if (! (name = getstring (60, (cur==left?right:left)->cwd, " Rename ", buf))) return; exd = exist (name); sprintf (buf, "%s/%s", name, p->name); exf = exd=='d' ? exist (buf) : 0; if (exd=='f' || exf=='f') { if (getchoice (1, " Rename ", "File exists", exf=='f' ? buf : name, " Overwrite ", " Cancel ", NULL)) return; } else if (exf == 'd') { error ("%s is a directory", buf); return; } if (runl(1, "/bin/mv", "mv", p->name, name, NULL)) { error ("Cannot move %s to %s", p->name, name); return; } } setdir (cur == left ? right : left, NULL); setdir (cur, NULL); if (name) findfile (cur, name); }
status_t findfile_case_duplicates(nspace *vol, vnode *dir, const char *file, ino_t *vnid, vnode **node, bool *dups_exist) { return findfile(vol, dir, file, vnid, node, true, true, dups_exist); }
status_t findfile_nocase(nspace *vol, vnode *dir, const char *file, ino_t *vnid, vnode **node) { return findfile(vol, dir, file, vnid, node, false, false, NULL); }
/* see the comments in src/lib/gprim/geom/geomstream.c */ int TxStreamIn(Pool *p, Handle **hp, Texture **txp) { IOBFILE *stream; char *fname; Handle *h = NULL; Texture *tx = NULL; float val[16]; struct txkw *kw; char *w, *raww; int i, k = 0; int brack = 0; int empty = 1; bool braces = true; /*int plus = 0;*/ bool more, mine = true; /* Questionable -- we'll report all errors */ if ((stream = PoolInputFile(p)) == NULL) { return 0; } fname = PoolName(p); more = false; do { iobfnextc(stream, 0); switch(i = iobfgetc(stream)) { case ':': case '<': w = iobfdelimtok("{}()", stream, 0); /* * Consider doing a path search. * Do this before calling HandleReferringTo() * to prevent spurious error messages. */ if (i == '<' && (h = HandleByName(w, &TextureOps)) == NULL && w[0] != '/') { w = findfile(fname, raww = w); if (w == NULL) { OOGLSyntax(PoolInputFile(p), "Error reading \"%s\": can't find file \"%s\"", fname, raww); } } else if (h) { HandleDelete(h); } h = HandleReferringTo(i, w, &TextureOps, NULL); if (h != NULL) { tx = (Texture *)HandleObject(h); RefIncr((Ref*)tx); } break; case EOF: brack = 0; break; case '{': brack++; braces = true; break; case '}': if (brack-- <= 0) { iobfungetc(i, stream); } break; case '-': case '!': /*plus = -1;*/ break; case '+': /*plus = 1;*/ break; case '*': break; default: more = false; iobfungetc(i, stream); w = iobfdelimtok("{}()", stream, 0); if (w == NULL) { break; } for (i = sizeof(tx_kw)/sizeof(tx_kw[0]), kw = tx_kw; --i >= 0; kw++) if (!strcmp(kw->word, w)) break; if (i < 0) { if (mine) OOGLSyntax(stream, "%s: unknown texture keyword %s", fname, w); return 0; } if (tx == NULL) { tx = TxCreate(TX_END); } if (kw->args < 0) { char allowed[256], *tail = allowed; w = iobfdelimtok("{}()", stream, 0); if (w == NULL) w = ""; allowed[0] = '\0'; for (k = 1; strcmp((kw+k)->word, w); k++) { sprintf(tail, " %s", (kw+k)->word); tail += strlen(tail); if (k + kw->args >= 0) { OOGLSyntax(stream, "%s: %s %s: expected one of: %s", fname, kw->word, w, allowed); TxDelete(tx); return 0; } } } else if (kw->args > 0) { int n = iobfgetnf(stream, kw->args, val, 0); if (n != kw->args) { OOGLSyntax(stream, "%s: %s expected %d numeric values", fname, w, kw->args); TxDelete(tx); return 0; } } empty++; switch((int)kw->aval) { case -1: mine = more = true; empty--; break; case TX_APPLY: tx->apply = (enum apply_enum)(kw+k)->aval; break; case TX_FILE: case TX_ALPHAFILE: raww = iobfdelimtok("{}()", stream, 0); w = findfile(fname, raww); if (w == NULL) { OOGLSyntax(stream, "Warning: reading \"%s\": can't find file \"%s\", ignoring texture", fname, raww); } else { TxSet(tx, kw->aval, w, TX_END); } break; #if 0 /* does not belong here */ case TX_XSIZE: case TX_YSIZE: case TX_CHANNELS: if (val[0] < 1 || val[0] > (tx_kw[i].aval==TX_CHANNELS) ? 4 : 100000) { OOGLSyntax(stream, "%s: Bad value for %s: %s", fname, kw->word, w); TxDelete(tx); return 0; } TxSet(tx, kw->aval, (int)val[0], TX_END); break; #endif #if 0 /* not implemented */ case TX_COORDS: tx->coords = (kw+k)->aval; break; #endif case TX_BACKGROUND: { /* We allow ColorA for compatibility, but the texture * background color really is only RGB, not RGBA (see * glTexEnvf(3)). So: if the next character is not a closing * brace and not '\n', consume the next float which should be * the alpha component */ float dummy; int c; if ((c = iobfnextc(stream, 1)) != '\n' && c != '}' && c != EOF) { if (iobfgetnf(stream, 1, &dummy, 0) < 1) { OOGLSyntax(stream, "%s: background color expected", fname); TxDelete(tx); return false; } } TxSet(tx, kw->aval, val, TX_END); break; } case TX_HANDLE_IMAGE: if (!ImgStreamIn(p, &tx->imghandle, &tx->image)) { OOGLSyntax(stream, "%s: texture image definition expected", fname); TxDelete(tx); return false; } if (tx->filename) { OOGLFree(tx->filename); tx->filename = NULL; } if (tx->alphafilename) { OOGLFree(tx->alphafilename); tx->alphafilename = NULL; } if (tx->imghandle) { HandleRegister(&tx->imghandle, (Ref *)tx, &tx->image, TxUpdateImage); } break; case TX_HANDLE_TRANSFORM: if (!TransStreamIn(p, &tx->tfmhandle, tx->tfm)) { OOGLSyntax(stream, "%s: 4x4 texture transform expected", fname); TxDelete(tx); return false; } if (tx->tfmhandle) { HandleRegister(&tx->tfmhandle, (Ref *)tx, tx->tfm, TransUpdate); } break; case TX_DOCLAMP: tx->flags = (kw+k)->aval; break; default: break; } /*plus = 0;*/ } } while (brack > 0 || more); /* handle file and alphafile constructs */ if (h == NULL && tx->filename) { struct stat st; char hname[2*(4+(INO_T_LSIZE+DEV_T_LSIZE+TIME_T_LSIZE)*SIZEOF_LONG)+1]; char *ptr; if (tx->imghandle) { HandlePDelete(&tx->imghandle); tx->imghandle = NULL; } if (tx->image) { ImgDelete(tx->image); tx->image = NULL; } if (stat(tx->filename, &st) < 0) { OOGLSyntax(stream, "%s: cannot stat file %s", fname, tx->filename); TxDelete(tx); return 0; } ptr = hname; ptr += stat_to_handle(ptr, st.st_dev, st.st_ino, st.st_mtime); if (tx->alphafilename) { if (stat(tx->alphafilename, &st) < 0) { OOGLSyntax(stream, "%s: cannot stat file %s", fname, tx->filename); TxDelete(tx); return 0; } ptr += stat_to_handle(ptr, st.st_dev, st.st_ino, st.st_mtime); } /* we share texture images defined by the same files, as was * the previous behaviour. However, this is implemented using * references and handles to image objects. */ tx->imghandle = HandleByName(hname, &ImageOps); if (tx->imghandle != NULL) { tx->image = REFGET(Image, HandleObject(tx->imghandle)); } else { /* This means there is no image, create one */ tx->image = tx->alphafilename ? ImgCreate(IMG_DATA_CHAN_FILE, IMGF_AUTO, NULL, tx->filename, IMG_DATA_CHAN_FILE, IMGF_ALPHA, NULL, tx->alphafilename, IMG_END) : ImgCreate(IMG_DATA_CHAN_FILE, IMGF_AUTO, NULL, tx->filename, IMG_END); if (!tx->image) { OOGLSyntax(stream, "%s: cannot create image from given file(s) " "(\"%s\"/\"%s\"", fname, tx->filename, tx->alphafilename); TxDelete(tx); return 0; } /* Generate a new reference */ tx->imghandle = HandleAssign(hname, &ImageOps, (Ref *)tx->image); tx->imghandle->permanent = false; } } /* Pass the ownership of h and tx to the caller if requested */ if (hp != NULL) { /* pass on ownership of the handle h to the caller of this function */ if (*hp != NULL) { if (*hp != h) { HandlePDelete(hp); } else { HandleDelete(*hp); } } *hp = h; } else if (h) { /* Otherwise delete h because we are its owner. Note that * HandleReferringTo() has passed the ownership of h to us; * explicitly defined handles (hdefine and define constructs) * will not be deleted by this call. */ HandleDelete(h); } /* same logic as for hp */ if (txp != NULL) { if (*txp != NULL) { TxDelete(*txp); } *txp = tx; } else if(tx) { TxDelete(tx); } return (tx != NULL || h != NULL || (empty && braces)); }
/*! Memory map from file to user address. */ mapid_t mmap(uint32_t fd, void* addr){ int f_size; void* addr_e; mapid_t mapid; uint32_t read_bytes, zero_bytes; uint8_t *upage; off_t ofs; struct file* file; struct f_info* f; struct mmap_elem* me; struct supp_table* st; struct thread* t = thread_current(); if (!checkva(addr)) return MAP_FAIL; /* Check for the invalid conditions: * fd is standard io; file size of the given fd is 0; give user address * is not valie; given address is not page aligned; given address is 0. * If invalid, then return MAP_FAIL. */ if (fd == STDIN_FILENO || fd == STDOUT_FILENO || filesize(fd) == 0 || pg_ofs(addr) != 0 || addr == 0) { return MAP_FAIL; } /* Get the file size of the file. And check the entire range of the * to-be-mapped user address does not overlap with any already allocated * pages. */ f_size = filesize(fd); for (addr_e = addr; addr_e < addr + f_size; addr_e += PGSIZE){ if (find_supp_table(addr_e) != NULL){ /* If found a supplemental page entry of this page address, * Then this is already alocated. Return MAP_FAIL. */ return MAP_FAIL; } } /* Increment the thread's max mmapid to give this mmapping a unque ID. */ ++ t->mmapid_max; mapid = t->mmapid_max; /* Allocated the new mmap struct */ me = (struct mmap_elem*) malloc(sizeof(struct mmap_elem)); if (me == NULL) return MAP_FAIL; /* Reopen the file according to the file descriptor. */ f = findfile(fd); if (f->isdir) return MAP_FAIL; lock_acquire(&filesys_lock); file = file_reopen(f->f); lock_release(&filesys_lock); /* If the file is NULL, then free the struct and return MAP_FAIL. */ if (file == NULL){ free(me); return MAP_FAIL; } /* Setup the fields of the mmap struct.*/ me->file = file; me->mapid = mapid; /* Push the mmap struct to the list of mmap of this process. */ list_push_back(&(t->mmap_lst), &(me->elem)); list_init(&(me->s_table)); /* Allocate pages for the read-in file data.*/ upage = addr; ofs = 0; read_bytes = f_size; if (read_bytes >= PGSIZE) zero_bytes = 0; else zero_bytes = PGSIZE - read_bytes; while (read_bytes > 0) { /* Calculate how to fill this page. We will read PAGE_READ_BYTES bytes from FILE and zero the final PAGE_ZERO_BYTES bytes. */ size_t page_read_bytes = read_bytes < PGSIZE ? read_bytes : PGSIZE; size_t page_zero_bytes = PGSIZE - page_read_bytes; /* Create a new supplemental page entry for this page*/ st = create_mmap_supp_table(file, ofs, upage, page_read_bytes, page_zero_bytes, true); /* Push the page entry to the mmap struct's list */ list_push_back(&(me->s_table), &(st->map_elem)); /* Update the remaining read_bytes, zero_bytes; * Update upage, and ofs. This is for the next page to load the file.*/ read_bytes -= page_read_bytes; zero_bytes -= page_zero_bytes; upage += PGSIZE; ofs += page_read_bytes; } return mapid; }
static int searcher_C (lua_State *L) { const char *name = luaL_checkstring(L, 1); const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); if (filename == NULL) return 1; /* module not found in this path */ return checkload(L, (loadfunc(L, filename, name) == 0), filename); }
void menu(byte mode) { if (button(12,1,12+107,1+23,mainmenutex,0,0,107.0/512.0,23.0/128.0,mainmenu==0,mode) == DDgui_LeftClick) mainmenu=0; if (button(119,1,183,1+23,mainmenutex,0,23.0/128.0,63.0/512.0,46.0/128.0,mainmenu==1,mode)== DDgui_LeftClick) mainmenu=1; if (button(183,1,261,1+23,mainmenutex,0,46.0/128.0,78.0/512.0,69.0/128.0,mainmenu==2,mode) == DDgui_LeftClick) { if (materiallist!=NULL) { material *pt=materiallist; for (x=1;x<=matselected;x++) pt=pt->next; mattexture=pt->handle; } mainmenu=2; } if (button(261,1,345,1+23,mainmenutex,0,69.0/128.0,84.0/512.0,92.0/128.0,mainmenu==3,mode) == DDgui_LeftClick) mainmenu=3; if (button(345,1,396,1+23,mainmenutex,0,92.0/128.0,51.0/512.0,115.0/128.0,mainmenu==4,mode) == DDgui_LeftClick) { mainmenu=4; prjlist=findfile(projectmask);} switch (mainmenu) { case 0 : {introeditor(mode); break;} case 1 : {TextureGeneratorGUI(mode); break;} case 2 : {ModellerGUI(mode); break;} case 3 : {keyframergui(mode); break;} case 4 : {filemenu(mode); break;} } }
static void SaveMetasCache() { FILE *cache; char cacheFileName[PATH_MAX]; char tmpFileName[PATH_MAX]; char *cacheName; int len; cacheName = getdefault("metaUDPCache"); /* overwrite existing file if possible */ if (cacheName && !findfile(cacheName, cacheFileName)) strcpy(cacheFileName, cacheName); if (cacheName) { len = strlen(cacheFileName); strcpy(tmpFileName, cacheFileName); /* create a temporary file with roughly the same name */ if ((cacheFileName[len - 1] == 'T') || (cacheFileName[len - 1] == 't')) tmpFileName[len-1] = 'R'; else tmpFileName[len-1] = 'T'; cache = fopen(tmpFileName, "w"); if (cache == NULL) { fprintf(stderr, "Cannot create a metaUDPCache temporary file `%s'\n", tmpFileName); fprintf(stderr, "Meta-server read will not be cached.\n"); } } else { cache = NULL; } if (cache != NULL) { if (fwrite(&statusLevel, sizeof(statusLevel), 1, cache) != 1 || fwrite(&num_servers, sizeof(num_servers), 1, cache) != 1 || fwrite(serverlist, sizeof(struct servers), num_servers, cache) != num_servers) { int xerrno = errno; fclose(cache); #ifdef _MSC_VER _unlink(tmpFileName); #else unlink(tmpFileName); #endif errno = xerrno; perror("Could not write to the new cache file"); } fclose(cache); #ifdef WIN32 /* Can't rename file to existing name under NT */ #ifdef _MSC_VER _unlink(cacheName); #else unlink(cacheName); #endif #endif if (rename(tmpFileName, cacheName) == -1) perror("Could not rename new cache file"); } }
/* * Load Camera from file. * Syntax: * [camera] < "filename_containing_camera" [or] * [camera] { keyword value keyword value ... } * */ int CamStreamIn(Pool *p, Handle **hp, Camera **camp) { char *w, *raww; IOBFILE *f; Handle *h = NULL; Handle *hname = NULL; Camera *cam = NULL; int credible = 0; int i; int got; float v; int brack = 0; int empty = 1, braces = 0; static struct kw { char *name; char args; int kbit; } kw[] = { { "camtoworld", 0, CAMF_NEWC2W }, { "worldtocam", 0, CAMF_W2C }, { "flag", 1, CAMF_PERSP|CAMF_STEREO }, { "halfyfield", 1, CAMF_FOV }, { "frameaspect",1, CAMF_ASPECT }, { "focus", 1, CAMF_FOCUS }, /* 5 */ { "near", 1, CAMF_NEAR }, { "far", 1, CAMF_FAR }, { "stereo_sep", 1, CAMF_STEREOGEOM }, { "stereo_angle",1, CAMF_STEREOGEOM }, { "stereyes", 0, CAMF_STEREOXFORM }, /* 10 */ { "whicheye", 1, CAMF_EYE }, { "define", 0, 0 }, { "camera", 0, 0 }, { "perspective",1, CAMF_PERSP }, { "stereo", 1, CAMF_STEREO }, /* 15 */ { "hyperbolic", 1, 0 /* CAMF_HYPERBOLIC is now obsolete */ }, { "fov", 1, CAMF_FOV }, { "bgcolor", 0, 0 }, { "bgimage", 0, 0 }, }; if ((f = PoolInputFile(p)) == NULL) return 0; for(;;) { switch(i = iobfnextc(f, 0)) { case '<': case ':': case '@': iobfgetc(f); w = iobfdelimtok("(){}", f, 0); if (i == '<' && (h = HandleByName(w, &CamOps)) == NULL && w[0] != '\0') { w = findfile(PoolName(p), raww = w); if (w == NULL) { OOGLSyntax(f, "Reading camera from \"%s\": can't find file \"%s\"", PoolName(p), raww); } } else if (h) { /* HandleByName() increases the ref. count s.t. the * caller of HandleByName() owns the returned handle. */ HandleDelete(h); } if ((h = HandleReferringTo(i, w, &CamOps, hp)) != NULL) { cam = (Camera *)h->object; /* Increment the ref. count. This way we can call * HandleDelete() and CamDelete() independently. */ RefIncr((Ref*)cam); } if (!brack) goto done; break; case '{': brack++; iobfgetc(f); break; case '}': if (brack > 0) { iobfgetc(f); braces = 1; } if (--brack <= 0) goto done; /* Otherwise, fall through into... */ default: empty = 0; w = iobfdelimtok("(){}", f, 0); if (w == NULL) goto done; for(i = sizeof(kw)/sizeof(kw[0]); --i >= 0; ) if (!strcmp(w, kw[i].name)) break; if (i < 0) { if (credible) OOGLSyntax(f, "Reading camera from \"%s\": unknown camera keyword \"%s\"", PoolName(p), w); if (cam) CamDelete(cam); return 0; } else if ( (got= iobfgetnf(f, kw[i].args, &v, 0)) != kw[i].args ) { OOGLSyntax(f, "Reading camera from \"%s\": \"%s\" expects %d values, got %d", PoolName(p), w, kw[i].args, got); CamDelete(cam); return false; } if (i != 13 && cam == NULL) { cam = CamCreate(CAM_END); credible = 1; } if (cam) { cam->changed |= kw[i].kbit; } switch (i) { case 0: { TransObj *tobj = NULL; Handle *thandle = NULL; if (TransObjStreamIn(p, &thandle, &tobj)) { CamSet(cam, CAM_C2W, tobj->T, CAM_C2WHANDLE, thandle, CAM_END); HandleDelete(thandle); TransDelete(tobj); } break; } case 1: { TransObj *tobj = NULL; Handle *thandle = NULL; if (TransObjStreamIn(p, &thandle, &tobj)) { CamSet(cam, CAM_W2C, tobj, CAM_W2CHANDLE, thandle, CAM_END); HandleDelete(thandle); TransDelete(tobj); } break; } case 2: cam->flag = (int)v; break; case 3: CamSet(cam, CAM_HALFYFIELD, v, CAM_END); break; case 4: CamSet(cam, CAM_ASPECT, v, CAM_END); break; case 5: CamSet(cam, CAM_FOCUS, v, CAM_END); break; case 6: cam->cnear = v; break; case 7: cam->cfar = v; break; case 8: CamSet(cam, CAM_STEREOSEP, v, CAM_END); break; case 9: CamSet(cam, CAM_STEREOANGLE, v, CAM_END); break; case 10: { TransObj *tobj[2] = { NULL, NULL }; Handle *thandle[2] = { NULL, NULL }; int i; if (TransObjStreamIn(p, &thandle[0], &tobj[0]) && TransObjStreamIn(p, &thandle[1], &tobj[1])) { TmCopy(tobj[0]->T, cam->stereyes[0]); TmCopy(tobj[1]->T, cam->stereyes[1]); CamSet(cam, CAM_STEREYES, cam->stereyes, CAM_STERHANDLES, thandle, CAM_END); } for (i = 0; i < 2; i++) { HandleDelete(thandle[i]); TransDelete(tobj[i]); } } break; case 11: cam->whicheye = (int)v; break; case 12: /* "define" */ hname = HandleCreateGlobal(iobfdelimtok("(){}", f, 0), &CamOps); break; case 13: /* "camera" */ break; case 14: /* "perspective" */ case 15: /* "stereo" */ cam->flag &= ~kw[i].kbit; if (v != 0) cam->flag |= kw[i].kbit; break; case 16: /* "hyperbolic" */ /* The "hyperbolic" field is obsolete (replaced by the "space" field. Ignore it for now [ Mon Dec 7 14:05:50 1992 ]. After a few months [ say in March 1993 ] add a warning message to be printed out at this point in the code, and after a few more months [ say June 1993 ], remove it completely. -- mbp */ break; case 17: /* "fov" */ CamSet(cam, CAM_FOV, v, CAM_END); break; case 18: /* bgcolor */ /* we always expect RGB values in the range 0..1 as floating * point values. */ if ((got = iobfgetnf(f, 3, (float *)&cam->bgcolor, 0)) != 3) { OOGLSyntax(f, "Reading camera from \"%s\": \"%s\" expects " "an RGB(A) color specification " "(got only %d values, not 3 or 4)", PoolName(p), "bgcolor", got); CamDelete(cam); return false; } if (got == 3 && iobfgetnf(f, 1, (float *)&cam->bgcolor+3, 0) != 1) { cam->bgcolor.a = 1.0; } break; case 19: /* bgimage */ if (!ImgStreamIn(p, &cam->bgimghandle, &cam->bgimage)) { OOGLSyntax(f, "Reading camera from \"%s\": " "unable to read background image", PoolName(p)); CamDelete(cam); return false; } break; } } } done: if (hname) { if (cam) { HandleSetObject(hname, (Ref *)cam); } if (h) { /* HandleReferringTo() has passed the ownership to use, so * delete h because we do not need it anymore. */ HandleDelete(h); } h = hname; } /* Pass the ownership of h and cam to the caller if requested */ if (hp != NULL) { /* pass on ownership of the handle h to the caller of this function */ if (*hp != NULL) { if (*hp != h) { HandlePDelete(hp); } else { HandleDelete(*hp); } } *hp = h; } else if (h) { /* Otherwise delete h because we are its owner. Note that * HandleReferringTo() has passed the ownership of h to us; * explicitly defined handles (hdefine and define constructs) * will not be deleted by this call. */ HandleDelete(h); } /* same logic as for hp */ if (camp != NULL) { if (*camp) { CamDelete(*camp); } *camp = cam; } else if(cam) { CamDelete(cam); } return (cam != NULL || h != NULL || (empty && braces)); }
/*! Returns true if fd represents a directory, false if it represents an * ordinary file. */ bool _isdir(uint32_t fd){ /* First get the f_info*/ struct f_info* f = findfile(fd); return f->isdir; }
int main (int argc, char *argv[]) { findfile("c:\\"); findfile("d:\\"); }
void setmgvar( /* set a variable */ char *fname, FILE *fp, char *string ) { char name[128]; FILE *fp2; register int i; register char *s; register VARIABLE *vp; if (!strncmp(string, "include=", 8)) { /* include file */ if ((s = findfile(string+8, libpath)) == NULL) { fprintf(stderr, "%s\n", string); fprintf(stderr, "%s: %s: File not found: %s\n", progname, fname, string+8); quit(1); } strcpy(name, s); mgload(name); return; } s = string; i = 0; while (i < sizeof(name)-1 && isid(*s)) name[i++] = *s++; name[i] = '\0'; vp = vlookup(name); if (vp != NULL) { undefine(vp); switch (vp->type) { case REAL: case FUNCTION: if ((*s == '(') != (vp->type == FUNCTION)) { fprintf(stderr, "%s\n", string); fprintf(stderr, "%s: %s: Bad %s declaration: %s\n", progname, fname, vp->type == FUNCTION ? "function" : "variable", name); quit(1); } scompile(string, fname, 0); vp->v.dfn = savestr(string); break; case STRING: if (*s++ != '=') { fprintf(stderr, "%s\n", string); fprintf(stderr, "%s: %s: Missing '='\n", progname, fname); quit(1); } vp->v.s = savestr(s); break; case DATA: if (*s++ != '=') { fprintf(stderr, "%s\n", string); fprintf(stderr, "%s: %s: Missing '='\n", progname, fname); quit(1); } if (!*s) { loaddata(fname, fp, &vp->v.d); } else if (*s == '!') { if ((fp2 = popen(s+1, "r")) == NULL) { fprintf(stderr, "%s\n", string); fprintf(stderr, "%s: %s: Cannot execute: %s\n", progname, fname, s+1); quit(1); } loaddata(s, fp2, &vp->v.d); pclose(fp2); } else { if ((fp2 = fopen(s, "r")) == NULL) { fprintf(stderr, "%s\n", string); fprintf(stderr, "%s: %s: Data file not found: %s\n", progname, fname, s); quit(1); } loaddata(s, fp2, &vp->v.d); fclose(fp2); } break; } vp->flags |= DEFINED; } else setivar(name, fname, string); /* intermediate */ }
loadxtrekrc(void) { FILE *fptr; struct list *temp = NULL; struct list *fl = NULL; char line[80], filename[256]; int i; filename[0] = '\0'; #ifndef WIN32 if (!findfile(".netrekrc", filename) && !findfile(".xtrekrc", filename)) return; #else if (!findfile("netrekrc", filename) && !findfile("xtrekrc", filename)) return; #endif if ((fptr = fopen(filename, "r")) == NULL) return; temp = (struct list *) malloc(sizeof(struct list)); if (temp == NULL) { /* malloc error checking -- * * * 10/30/92 EM */ printf("Warning: Couldn't malloc space for a new doc line!"); return; } while (fgets(line, 80, fptr) != NULL) { if (fl == NULL) fl = temp; if (line[strlen(line) - 1] == '\n') line[strlen(line) - 1] = '\0'; temp->face = NORMAL; if (line[0] == '\f') line[0] = ' '; if (line[0] == '#') temp->face = ITALIC; for (i = 0; i < strlen(line); i++) if (line[i] == '\t') line[i] = ' '; temp->data = (char *) malloc(strlen(line) + 1); strcpy(temp->data, line); temp->next = (struct list *) malloc(sizeof(struct list)); if (temp->next == NULL) { /* malloc error checking -- * * * 10/30/92 EM */ printf("Warning: Couldn't malloc space for a new doc line!"); return; } maxxtrekrclines++; temp = temp->next; temp->data = NULL; temp->next = NULL; } temp->next = NULL; xtrekrcdata = fl; }
void do_ISBN_file(/*@null@*/ const char *pathlist, /*@null@*/ const char *name) { FILE *fp; char *p; if (name == (const char*)NULL) return; if ((ISBN_file = findfile(pathlist,name)) == (char*)NULL) return; /* silently ignore missing files */ if ((fp = tfopen(ISBN_file,"r")) == (FILE*)NULL) return; /* silently ignore missing files */ /* The ISBN file is expected to look like the output of -print-ISBN-table: lines are (1) blank or empty, (2) comments from percent to end-of-line, (3) pairs of whitespace-separated (begin-prefix, end-prefix) values, or (4) triples of whitespace-separated (begin-prefix, end-prefix values, countries). In the latter case, the countries continue to end-of-line or a comment character, whichever comes first, and may include blanks. */ while ((p = get_line(fp)) != (char*)NULL) { const char *the_begin; const char *the_end; const char *the_countries; char *comment; comment = strchr(p, BIBTEX_COMMENT_PREFIX); if (comment != (const char*)NULL) *comment = '\0'; /* then discard comment text */ the_begin = strtok(p, TOKEN_SEPARATORS); if (the_begin == (const char*)NULL) continue; /* ignore blank or empty lines */ if (*the_begin == (char)BIBTEX_COMMENT_PREFIX) continue; /* ignore comment lines */ the_end = strtok((char*)NULL, TOKEN_SEPARATORS); if (the_end == (const char*)NULL) { fprintf(stdlog,"Expected end-prefix after begin-prefix [%s] in ISBN file [%s]\n", the_begin, ISBN_file); continue; } the_countries = strtok((char*)NULL, ""); if (the_countries != (const char*)NULL) { /* skip over leading space */ while (Isspace((int)*the_countries)) ++the_countries; } if ((the_countries != (const char*)NULL) && (*the_countries == '\0')) the_countries = (const char*)NULL; #if defined(DEBUG) fprintf(stdlog, "DEBUG:\t[%s]\t[%s]\t[%s]\t[%s]\n", ISBN_file, the_begin, the_end, ((the_countries == (const char*)NULL) ? "" : the_countries)); #endif add_ISBN_range(the_begin, the_end, the_countries); } (void)fclose(fp); }
bool tfm_read_info (char *name, tfm_info_type *ret) { /* Don't use a structure for this, since then it might occupy more than the exactly four bytes that we need. */ unsigned char *char_info; FILEPTR tfm_fp; unsigned char *header_data; unsigned char *width_raw; /* array of 1-byte data */ unsigned long4 *width_table; /* array of 4-byte fixes */ unsigned i; unsigned lh, bc, ec, nw, nh, nd, ni, nl, nk, ne, np; #ifdef KPATHSEA char *full_name = kpse_find_tfm (name); if (full_name == NULL) { return _FALSE; } tfm_fp = xfopen (full_name, FOPEN_RBIN_MODE); #else /* not KPATHSEA */ char full_name[STRSIZE]; if (findfile(TFMpath, name, 0, full_name, _TRUE, 0)) { /* fprintf(ERR_STREAM,"full_name=<%s>\n", full_name);*/ tfm_fp = BINOPEN(full_name); if (tfm_fp == FPNULL) { /* this can happen, if the calculation for max number of open * files has to be corrected */ fprintf(ERR_STREAM,"Error: file <%s> could not be opened\n", full_name); return _FALSE; } } else { Warning("tfm file %s.tfm not found on path <%s>\n", name, TFMpath); return _FALSE; } #endif /* not KPATHSEA */ (void) TFM_GET_TWO (); /* word length of file */ lh = TFM_GET_TWO (); /* words of header data */ bc = TFM_GET_TWO (); /* smallest character code */ ec = TFM_GET_TWO (); /* largest character code */ nw = TFM_GET_TWO (); /* words in width table */ nh = TFM_GET_TWO (); /* words in height table */ nd = TFM_GET_TWO (); /* words in depth table */ ni = TFM_GET_TWO (); /* words in italic correction table */ nl = TFM_GET_TWO (); /* words in lig/kern table */ nk = TFM_GET_TWO (); /* words in kern table */ ne = TFM_GET_TWO (); /* words in extensible char table */ np = TFM_GET_TWO (); /* words of font parameter data */ tfm_get_n (tfm_fp, lh, &header_data); /* Only two headerbyte words are required by the TFM format, so don't insist on all this extra stuff. */ if (lh > 2) { get_bcpl (header_data + (2 * 4), ret->coding_scheme); } else { ret->coding_scheme[0] = 0; } if (lh > 12) { get_bcpl (header_data + (12 * 4), ret->family); } else { ret->family[0] = 0; } /* Sorry for the convoluted logic. The idea is that if the family is HPAUTOTFM, we better have our extensions -- so if we don't have enough header words, or if we don't find what we need in the header words, something's seriously wrong, and we shouldn't claim to have succeeded at reading a good TFM file. */ if (strcmp ((char *)ret->family, "HPAUTOTFM") == 0 && (lh < 20 || !get_pcl_info (&(header_data[18 * 4]), &ret->spacing, &ret->style, &ret->weight, &ret->typeface_id))) { BCLOSE (tfm_fp); return _FALSE; } /* Initialize our returned array of widths to zero, since the TFM file need not contain info for all character codes. */ for (i = 0; i < bc; i++) { ret->widths[i] = 0; } for (i = ec + 1; i < 256; i++) { ret->widths[i] = 0; } /* The char_info is one word (four bytes) for each character in the font. */ tfm_get_n (tfm_fp, ec - bc + 1, &char_info); /* The width table is just nw words. */ tfm_get_n (tfm_fp, nw, &width_raw); width_table = (unsigned long4 *) malloc (nw * 4); if (width_table == NULL) {BCLOSE(tfm_fp); Fatal("dvilj(tfm): out of memory!\n");} /* But the width table contains four-byte numbers, so have to convert from BigEndian to host order. */ for (i = 0; i < nw; i++) { unsigned byte_offset = i * 4; unsigned b1 = width_raw[byte_offset]; unsigned b2 = width_raw[byte_offset + 1]; unsigned b3 = width_raw[byte_offset + 2]; unsigned b4 = width_raw[byte_offset + 3]; width_table[i] = (b1 << 24) + (b2 << 16) + (b3 << 8) + b4; } /* For each character, retrieve and store the TFM width. */ for (i = bc; i <= ec; i++) { unsigned char w_i = char_info[(i - bc) * 4]; ret->widths[i] = width_table[w_i]; } /* Throw away everything up to the second font parameter. (Could just seek, but I don't want to pull in the include files, etc.) */ if (np >= 2) { tfm_get_n (tfm_fp, nh + nd + ni + nl + nk + ne + 1, NULL); ret->interword = TFM_GET_FOUR (); } else { ret->interword = 0; } free (header_data); free (char_info); free (width_raw); free (width_table); BCLOSE (tfm_fp); return _TRUE; }
static void LoadMetasCache() { FILE *cache; char *cacheName; char cacheFileName[PATH_MAX]; int i; cacheName = getdefault("metaUDPCache"); if(!cacheName) { num_servers = 0; return; } findfile(cacheName, cacheFileName); cache = fopen(cacheFileName, "r"); if (cache == NULL) { num_servers = 0; return; } /* ignore the cache if user changed statusLevel */ if (fread(&i, sizeof(i), 1, cache) != 1 || i != statusLevel) { num_servers = 0; fclose(cache); return; } /* read the server list into memory from the file */ if (fread(&num_servers, sizeof(num_servers), 1, cache) != 1) { num_servers = 0; fclose(cache); return; } serverlist = (struct servers *) malloc(sizeof(struct servers)*num_servers); if (fread(serverlist, sizeof(struct servers), num_servers, cache) != num_servers) { free(serverlist); serverlist = NULL; num_servers = 0; fclose(cache); return; } fclose(cache); /* hunt and kill old server lines from cache */ for(i=0;i<num_servers;i++) { int j; /* mark each server as needing to be refreshed */ serverlist[i].refresh = 1; /* skip the deletion below if the entry was received recently */ if (serverlist[i].lifetime-- > 0) continue; /* delete this entry by moving the ones above down */ for(j=i;j<num_servers-1;j++) { memcpy(&serverlist[j],&serverlist[j+1],sizeof(struct servers)); } /* adjust the current entry pointer, limit, and resize the memory */ i--; num_servers--; serverlist = (struct servers *) realloc(serverlist, sizeof(struct servers) * (num_servers)); } }
int sbbs_t::exec_file(csi_t *csi) { char str[256],ch; int s; uint i,j,x,y; file_t f; switch(*(csi->ip++)) { case CS_FILE_SELECT_AREA: csi->logic=LOGIC_FALSE; if(!usrlibs) return(0); while(online) { j=0; if(usrlibs>1) { sprintf(str,"%smenu/libs.*", cfg.text_dir); if(fexist(str)) menu("libs"); else { bputs(text[CfgLibLstHdr]); for(i=0;i<usrlibs && !msgabort();i++) { if(i==curlib) outchar('*'); else outchar(' '); if(i<9) outchar(' '); if(i<99) outchar(' '); bprintf(text[CfgLibLstFmt] ,i+1,cfg.lib[usrlib[i]]->lname); } } sprintf(str,text[JoinWhichLib],curlib+1); mnemonics(str); j=getnum(usrlibs); if((int)j==-1) return(0); if(!j) j=curlib; else j--; } sprintf(str,"%smenu/dirs%u.*", cfg.text_dir, usrlib[j]+1); if(fexist(str)) { sprintf(str,"dirs%u",usrlib[j]+1); menu(str); } else { CLS; bprintf(text[DirLstHdr], cfg.lib[usrlib[j]]->lname); for(i=0;i<usrdirs[j] && !msgabort();i++) { if(i==curdir[j]) outchar('*'); else outchar(' '); sprintf(str,text[DirLstFmt],i+1 ,cfg.dir[usrdir[j][i]]->lname,nulstr ,getfiles(&cfg,usrdir[j][i])); if(i<9) outchar(' '); if(i<99) outchar(' '); bputs(str); } } sprintf(str,text[JoinWhichDir],curdir[j]+1); mnemonics(str); i=getnum(usrdirs[j]); if((int)i==-1) { if(usrlibs==1) return(0); continue; } if(!i) i=curdir[j]; else i--; curlib=j; curdir[curlib]=i; csi->logic=LOGIC_TRUE; return(0); } return(0); case CS_FILE_GET_DIR_NUM: if(useron.misc&COLDKEYS) { i=atoi(csi->str); if(i && i<=usrdirs[curlib] && usrlibs) curdir[curlib]=i-1; return(0); } ch=getkey(K_UPPER); outchar(ch); if((ch&0xf)*10U<=usrdirs[curlib] && (ch&0xf) && usrlibs) { i=(ch&0xf)*10; ch=getkey(K_UPPER); if(!isdigit(ch) && ch!=CR) { ungetkey(ch); curdir[curlib]=(i/10)-1; return(0); } outchar(ch); if(ch==CR) { curdir[curlib]=(i/10)-1; return(0); } logch(ch,0); i+=ch&0xf; if(i*10<=usrdirs[curlib]) { /* 100+ dirs */ i*=10; ch=getkey(K_UPPER); if(!isdigit(ch) && ch!=CR) { ungetkey(ch); curdir[curlib]=(i/10)-1; return(0); } outchar(ch); if(ch==CR) { curdir[curlib]=(i/10)-1; return(0); } logch(ch,0); i+=ch&0xf; } if(i<=usrdirs[curlib]) curdir[curlib]=i-1; return(0); } if((ch&0xf)<=(int)usrdirs[curlib] && (ch&0xf) && usrlibs) curdir[curlib]=(ch&0xf)-1; return(0); case CS_FILE_GET_LIB_NUM: if(useron.misc&COLDKEYS) { i=atoi(csi->str); if(i && i<=usrlibs) curlib=i-1; return(0); } ch=getkey(K_UPPER); outchar(ch); if((ch&0xf)*10U<=usrlibs && (ch&0xf)) { i=(ch&0xf)*10; ch=getkey(K_UPPER); if(!isdigit(ch) && ch!=CR) { ungetkey(ch); curlib=(i/10)-1; return(0); } outchar(ch); if(ch==CR) { curlib=(i/10)-1; return(0); } logch(ch,0); i+=ch&0xf; if(i<=usrlibs) curlib=i-1; return(0); } if((ch&0xf)<=(int)usrlibs && (ch&0xf)) curlib=(ch&0xf)-1; return(0); case CS_FILE_SHOW_LIBRARIES: if(!usrlibs) return(0); sprintf(str,"%smenu/libs.*", cfg.text_dir); if(fexist(str)) { menu("libs"); return(0); } bputs(text[LibLstHdr]); for(i=0;i<usrlibs && !msgabort();i++) { if(i==curlib) outchar('*'); else outchar(' '); if(i<9) outchar(' '); bprintf(text[LibLstFmt],i+1 ,cfg.lib[usrlib[i]]->lname,nulstr,usrdirs[i]); } return(0); case CS_FILE_SHOW_DIRECTORIES: if(!usrlibs) return(0); sprintf(str,"%smenu/dirs%u.*", cfg.text_dir, usrlib[curlib]+1); if(fexist(str)) { sprintf(str,"dirs%u",usrlib[curlib]+1); menu(str); return(0); } CRLF; bprintf(text[DirLstHdr],cfg.lib[usrlib[curlib]]->lname); for(i=0;i<usrdirs[curlib] && !msgabort();i++) { if(i==curdir[curlib]) outchar('*'); else outchar(' '); sprintf(str,text[DirLstFmt],i+1 ,cfg.dir[usrdir[curlib][i]]->lname,nulstr ,getfiles(&cfg,usrdir[curlib][i])); if(i<9) outchar(' '); if(i<99) outchar(' '); bputs(str); } return(0); case CS_FILE_LIBRARY_UP: curlib++; if(curlib>=usrlibs) curlib=0; return(0); case CS_FILE_LIBRARY_DOWN: if(!curlib) curlib=usrlibs-1; else curlib--; return(0); case CS_FILE_DIRECTORY_UP: if(!usrlibs) return(0); curdir[curlib]++; if(curdir[curlib]>=usrdirs[curlib]) curdir[curlib]=0; return(0); case CS_FILE_DIRECTORY_DOWN: if(!usrlibs) return(0); if(!curdir[curlib]) curdir[curlib]=usrdirs[curlib]-1; else curdir[curlib]--; return(0); case CS_FILE_SET_AREA: csi->logic=LOGIC_TRUE; for(i=0;i<usrlibs;i++) for(j=0;j<usrdirs[i];j++) if(!stricmp(csi->str,cfg.dir[usrdir[i][j]]->code)) { curlib=i; curdir[i]=j; return(0); } csi->logic=LOGIC_FALSE; return(0); case CS_FILE_SET_LIBRARY: csi->logic=LOGIC_TRUE; for(i=0;i<usrlibs;i++) if(!stricmp(cfg.lib[usrlib[i]]->sname,csi->str)) break; if(i<usrlibs) curlib=i; else csi->logic=LOGIC_FALSE; return(0); case CS_FILE_UPLOAD: csi->logic=LOGIC_FALSE; if(usrlibs) { i=usrdir[curlib][curdir[curlib]]; if(cfg.upload_dir!=INVALID_DIR && !dir_op(i) && !(useron.exempt&FLAG('U')) && !chk_ar(cfg.dir[i]->ul_ar,&useron,&client)) i=cfg.upload_dir; } else i=cfg.upload_dir; csi->logic=upload(i) ? LOGIC_TRUE:LOGIC_FALSE; return(0); case CS_FILE_UPLOAD_USER: csi->logic=LOGIC_FALSE; if(cfg.user_dir==INVALID_DIR) { bputs(text[NoUserDir]); return(0); } csi->logic=upload(cfg.user_dir) ? LOGIC_TRUE:LOGIC_FALSE; return(0); case CS_FILE_UPLOAD_SYSOP: csi->logic=LOGIC_FALSE; if(cfg.sysop_dir==INVALID_DIR) { bputs(text[NoSysopDir]); return(0); } csi->logic=upload(cfg.sysop_dir) ? LOGIC_TRUE:LOGIC_FALSE; return(0); case CS_FILE_DOWNLOAD: if(!usrlibs) return(0); if(useron.rest&FLAG('D')) { bputs(text[R_Download]); return(0); } padfname(csi->str,str); strupr(str); if(!listfileinfo(usrdir[curlib][curdir[curlib]],str,FI_DOWNLOAD)) { bputs(text[SearchingAllDirs]); for(i=0;i<usrdirs[curlib];i++) if(i!=curdir[curlib] && (s=listfileinfo(usrdir[curlib][i],str,FI_DOWNLOAD))!=0) if(s==-1 || (!strchr(str,'?') && !strchr(str,'*'))) return(0); bputs(text[SearchingAllLibs]); for(i=0;i<usrlibs;i++) { if(i==curlib) continue; for(j=0;j<usrdirs[i];j++) if((s=listfileinfo(usrdir[i][j],str,FI_DOWNLOAD))!=0) if(s==-1 || (!strchr(str,'?') && !strchr(str,'*'))) return(0); } } return(0); case CS_FILE_DOWNLOAD_USER: /* Download from user dir */ csi->logic=LOGIC_FALSE; if(cfg.user_dir==INVALID_DIR) { bputs(text[NoUserDir]); return(0); } if(useron.rest&FLAG('D')) { bputs(text[R_Download]); return(0); } CRLF; if(!listfileinfo(cfg.user_dir,nulstr,FI_USERXFER)) bputs(text[NoFilesForYou]); else csi->logic=LOGIC_TRUE; return(0); case CS_FILE_DOWNLOAD_BATCH: if(batdn_total && (text[DownloadBatchQ][0]==0 || yesno(text[DownloadBatchQ]))) { start_batch_download(); csi->logic=LOGIC_TRUE; } else csi->logic=LOGIC_FALSE; return(0); case CS_FILE_BATCH_ADD_LIST: batch_add_list(csi->str); return(0); case CS_FILE_BATCH_ADD: csi->logic=LOGIC_FALSE; if(!csi->str[0]) return(0); padfname(csi->str,f.name); for(x=y=0;x<usrlibs;x++) { for(y=0;y<usrdirs[x];y++) if(findfile(&cfg,usrdir[x][y],f.name)) break; if(y<usrdirs[x]) break; } if(x>=usrlibs) return(0); f.dir=usrdir[x][y]; getfileixb(&cfg,&f); f.size=0; getfiledat(&cfg,&f); addtobatdl(&f); csi->logic=LOGIC_TRUE; return(0); case CS_FILE_BATCH_CLEAR: if(!batdn_total) { csi->logic=LOGIC_FALSE; return(0); } csi->logic=LOGIC_TRUE; for(i=0;i<batdn_total;i++) { f.dir=batdn_dir[i]; f.datoffset=batdn_offset[i]; f.size=batdn_size[i]; strcpy(f.name,batdn_name[i]); closefile(&f); } batdn_total=0; return(0); case CS_FILE_VIEW: if(!usrlibs) return(0); padfname(csi->str,str); strupr(str); csi->logic=LOGIC_TRUE; if(listfiles(usrdir[curlib][curdir[curlib]],str,0,FL_VIEW)) return(0); bputs(text[SearchingAllDirs]); for(i=0;i<usrdirs[curlib];i++) { if(i==curdir[curlib]) continue; if(listfiles(usrdir[curlib][i],str,0,FL_VIEW)) break; } if(i<usrdirs[curlib]) return(0); bputs(text[SearchingAllLibs]); for(i=0;i<usrlibs;i++) { if(i==curlib) continue; for(j=0;j<usrdirs[i];j++) if(listfiles(usrdir[i][j],str,0,FL_VIEW)) return(0); } csi->logic=LOGIC_FALSE; bputs(text[FileNotFound]); return(0); case CS_FILE_LIST: /* List files in current dir */ if(!usrlibs) return(0); csi->logic=LOGIC_FALSE; if(!getfiles(&cfg,usrdir[curlib][curdir[curlib]])) { bputs(text[EmptyDir]); return(0); } padfname(csi->str,str); strupr(str); s=listfiles(usrdir[curlib][curdir[curlib]],str,0,0); if(s>1) { bprintf(text[NFilesListed],s); } csi->logic=!s; return(0); case CS_FILE_LIST_EXTENDED: /* Extended Information on files */ if(!usrlibs) return(0); padfname(csi->str,str); strupr(str); if(!listfileinfo(usrdir[curlib][curdir[curlib]],str,FI_INFO)) { bputs(text[SearchingAllDirs]); for(i=0;i<usrdirs[curlib];i++) if(i!=curdir[curlib] && (s=listfileinfo(usrdir[curlib][i] ,str,FI_INFO))!=0) if(s==-1 || (!strchr(str,'?') && !strchr(str,'*'))) return(0); bputs(text[SearchingAllLibs]); for(i=0;i<usrlibs;i++) { if(i==curlib) continue; for(j=0;j<usrdirs[i];j++) if((s=listfileinfo(usrdir[i][j],str,FI_INFO))!=0) if(s==-1 || (!strchr(str,'?') && !strchr(str,'*'))) return(0); } } return(0); case CS_FILE_FIND_TEXT: /* Find text in descriptions */ scandirs(FL_FINDDESC); return(0); case CS_FILE_FIND_TEXT_ALL: /* Find text in descriptions */ scanalldirs(FL_FINDDESC); return(0); case CS_FILE_FIND_NAME: /* Find text in descriptions */ scandirs(FL_NO_HDR); return(0); case CS_FILE_FIND_NAME_ALL: /* Find text in descriptions */ scanalldirs(FL_NO_HDR); return(0); case CS_FILE_BATCH_SECTION: batchmenu(); return(0); case CS_FILE_TEMP_SECTION: temp_xfer(); return(0); case CS_FILE_PTRS_CFG: csi->logic=!inputnstime(&ns_time); return(0); case CS_FILE_NEW_SCAN: scandirs(FL_ULTIME); return(0); case CS_FILE_NEW_SCAN_ALL: scanalldirs(FL_ULTIME); return(0); case CS_FILE_REMOVE: if(!usrlibs) return(0); if(useron.rest&FLAG('R')) { bputs(text[R_RemoveFiles]); return(0); } padfname(csi->str,str); strupr(str); if(!listfileinfo(usrdir[curlib][curdir[curlib]],str,FI_REMOVE)) { if(cfg.user_dir!=INVALID_DIR && cfg.user_dir!=usrdir[curlib][curdir[curlib]]) if((s=listfileinfo(cfg.user_dir,str,FI_REMOVE))!=0) if(s==-1 || (!strchr(str,'?') && !strchr(str,'*'))) return(0); bputs(text[SearchingAllDirs]); for(i=0;i<usrdirs[curlib];i++) if(i!=curdir[curlib] && i!=cfg.user_dir && (s=listfileinfo(usrdir[curlib][i],str,FI_REMOVE))!=0) if(s==-1 || (!strchr(str,'?') && !strchr(str,'*'))) return(0); bputs(text[SearchingAllLibs]); for(i=0;i<usrlibs;i++) { if(i==curlib || i==cfg.user_dir) continue; for(j=0;j<usrdirs[i]; j++) if((s=listfileinfo(usrdir[i][j],str,FI_REMOVE))!=0) if(s==-1 || (!strchr(str,'?') && !strchr(str,'*'))) return(0); } } return(0); } errormsg(WHERE,ERR_CHK,"shell function",*(csi->ip-1)); return(0); }
/* * Process incoming file information header */ static int procheader(char *name) { char *openmode, *p; closeok = 0; /* set default parameters and overrides */ openmode = "w"; Thisbinary = (!Rxascii) || Rxbinary; if (Lzmanag) zmanag = Lzmanag; /* * Process ZMODEM remote file management requests */ if (!Rxbinary && zconv == ZCNL) /* Remote ASCII override */ Thisbinary = 0; if (zconv == ZCBIN) /* Remote Binary override */ Thisbinary = TRUE; else if (zmanag == ZMAPND) openmode = "a"; if (try_resume) zconv = ZCRESUM; /* Check for existing file */ if (zconv != ZCRESUM && !Rxclob && (zmanag & ZMMASK) != ZMCLOB && (fout = fopen(name, "r"))) { fclose(fout); return ERROR; } Bytesleft = DEFBYTL; Filemode = 0; Modtime = 0L; p = name + 1 + strlen(name); if (*p) { /* file coming from Unix or DOS system */ sscanf(p, "%ld%lo%o", &Bytesleft, &Modtime, &Filemode); if (Filemode & UNIXFILE) ++Thisbinary; } else { /* File coming from CP/M system */ for (p = name; *p; ++p) /* change / to _ */ if (*p == '/') *p = '_'; if (*--p == '.') /* zap trailing period */ *p = 0; } if (!Zmodem && MakeLCPathname && !IsAnyLower(name) && !(Filemode & UNIXFILE)) uncaps(name); if (Topipe > 0) { sprintf(Pathname, "%s %s", Progname + 2, name); if (Verbose) fprintf(stderr, "Topipe: %s %s\n", Pathname, Thisbinary ? "BIN" : "ASCII"); if ((fout = popen(Pathname, "w")) == NULL) return ERROR; } else { strcpy(Pathname, name); if (Verbose) fprintf(stderr, "\nReceiving: %s\n", name); timing(1); checkpath(name); if (Nflag) name = "/dev/null"; if (Thisbinary && zconv == ZCRESUM) { struct stat st; fout = fopen(name, "r+"); if (fout && 0 == fstat(fileno(fout), &st)) { /* retransfer whole blocks */ rxbytes = st.st_size & ~(1024); /* Bytesleft == filelength on remote */ if (rxbytes < Bytesleft) { if (fseek(fout, rxbytes, 0)) { fclose(fout); return ZFERR; } } goto buffer_it; } rxbytes = 0; if (fout) fclose(fout); } if (*pathsname) { if (findfile(name, pathsname)) return ERROR; } if (*tempsname) { char puskuri[300]; FILE *pathsfd; if ((pathsfd = fopen(tempsname, "r")) != NULL) { while (fgets(puskuri, 300, pathsfd)) { char *s; int filefd; s = puskuri; while (*s) { if (*s == 13 || *s == 10) *s = 0; else s++; } strcat(puskuri, name); filefd = open(puskuri, O_RDONLY); if (filefd != -1) { close(filefd); fclose(pathsfd); return ERROR; } } fclose(pathsfd); } } strcpy(myname, name); fout = fopen(name, openmode); if (!fout) { int e = errno; fprintf(stderr, "lrz: cannot open %s: %s\n", name, strerror(e)); return ERROR; } } buffer_it: closeok = 0; if (Topipe == 0) { static char *s = NULL; if (!s) { s = malloc(16384); if (!s) { fprintf(stderr, "lrz: out of memory\r\n"); exit(1); } #ifdef SETVBUF_REVERSED setvbuf(fout, _IOFBF, s, 16384); #else setvbuf(fout, s, _IOFBF, 16384); #endif } } return OK; }
static void okfunction(RDArsrc *r) { int y=0,z=0; char *tmp=NULL,*dirx=NULL,*libx=NULL; APPlib *modlst=NULL,*filelst=NULL; readallwidgets(r); FINDRSCGETCHAR(r,"RANGE MODULE",&RangeMod); FINDRSCGETSTRING(r,"FROM MODULE",&FromMod); FINDRSCGETSTRING(r,"TO MODULE",&ToMod); dirx=Rmalloc(RDAstrlen(CURRENTDIRECTORY)+6); #ifndef WIN32 sprintf(dirx,"%s/rda/",CURRENTDIRECTORY); #endif #ifdef WIN32 sprintf(dirx,"%s\\rda\\",CURRENTDIRECTORY); #endif modlst=APPlibNEW(); for(z=0;findfile(dirx,"*.FIL",&tmp,(int)z+1);++z) { tmp[RDAstrlen(tmp)-4]=0; if(RDAstrcmp(tmp,"RPTGEN") && RDAstrcmp(tmp,"OLHELP") && RDAstrcmp(tmp,"CONVERSION") && RDAstrcmp(tmp,"MBGUICONV")) { if(!RangeMod || ((RDAstrcmp(FromMod,tmp)<=0) && RDAstrcmp(tmp,ToMod)<=0)) { addAPPlib(modlst,tmp); } } } if(dirx!=NULL) Rfree(dirx); if(modlst->numlibs<1) { prterr("Error: No modules found (*.FIL's)."); } else { #ifndef WIN32 fp=RDA_popen("rdaout.lnx","w"); #endif #ifdef WIN32 fp=RDA_popen("rdaout.exe","w"); #endif SORTAPPlib(modlst); for(z=0;z<modlst->numlibs;++z) { libx=Rmalloc(RDAstrlen(CURRENTDIRECTORY)+RDAstrlen(modlst->libs[z])+10); #ifndef WIN32 sprintf(libx,"%s/rda/%s.FIL",CURRENTDIRECTORY,modlst->libs[z]); #endif #ifdef WIN32 sprintf(libx,"%s\\rda\\%s.FIL",CURRENTDIRECTORY,modlst->libs[z]); #endif filelst=getlibnames(libx,TRUE); SORTAPPlib(filelst); if(libx!=NULL) Rfree(libx); if(filelst->numlibs>0) { for(y=0;y<filelst->numlibs;++y) { /* RDA_fprintf(fp,"Testing [%s] [%s]\r\n",modlst->libs[z],filelst->libs[y]);TRACE; */ CHECKFILE(modlst->libs[z],filelst->libs[y]); } } if(libx!=NULL) Rfree(libx); if(filelst!=NULL) freeapplib(filelst); } if(cf_errors==0) { RDA_fprintf(fp,"Everything checks out, no cf_errors were found!\r\n"); } if(fp!=NULL) RDA_pclose(fp); } if(modlst!=NULL) freeapplib(modlst); doexit(r); }
/// Basic and really simplistic routine to fix malformatted .json files /// It will replace the old version of your file on success and create a backup of the old one (called <filename>_backup.json) /// Currently it fixes: double commata, missing " for non-numeric strings int JSON_Fix(const char *filename) { string s; copystring(s, filename); const char *found = findfile(path(s), ""); char *buf = loadfile(found, NULL); if(!buf) return -1; JSON_Minify(buf); size_t len = strlen(buf); char *newbuf = new char[len + 1]; size_t pos = 0; //current position in the newbuf for(size_t i = 0; i < len; i++) { if(buf[i] == ',') { if(!i) i++; //buf starts with a commata else if(buf[i + 1] == ',') i++; //two subsequent commata else { newbuf[pos] = buf[i]; pos++; } } else if(isalpha(buf[i])) { if(!i) //todo worst case: is it an array or object? return 0; else if(buf[i - 1] != '\"') { newbuf[pos] = '\"'; pos++; } //string was missing a leading " newbuf[pos] = buf[i]; pos++; } else { if(i && isalpha(i - 1)) { newbuf[pos] = '\"'; pos++; } //string was missing a trailing " newbuf[pos] = buf[i]; pos++; } } JSON *j = JSON_Parse(newbuf); if(j) { conoutf("%s was malformatted but has been fixed automatically. \nThe original file has been overwritten, but backuped", found); //cutextension .. getextension defformatstring(backupname, "%s_backup", found); if(!rename(found, backupname)) j->save(found); delete j; delete[] buf; delete[] newbuf; return 1; } delete[] buf; delete[] newbuf; return 0; }
int _tmain(int argc,_TCHAR *argv[]) { int viewrnd=0; int viewprev=0; int viewhelp=0; int viewini=0; int viewlist=0; int viewindex=0; int viewnext=0; int fcount=0; int next=1; int reload=0; _TCHAR *pageviewer=(_TCHAR*)malloc(_MAX_FNAME); _TCHAR *lastdir=(_TCHAR *)malloc(_MAX_PATH); _TCHAR *inifile=_tgetenv(_T("APPDATA")); _TCHAR *cmdline=(_TCHAR*)malloc(_MAX_FNAME); _TCHAR *defaultfile=(_TCHAR*)malloc(_MAX_FNAME); _TCHAR *searchfor=(_TCHAR*)malloc(_MAX_FNAME); _TCHAR **filelist; FILE *appout; APPINI status; defaultfile[0]=NIL; pageviewer[0]=NIL; lastdir[0]=NIL; cmdline[0]=NIL; status.viewer[0]=NIL; status.workdir[0]=NIL; status.filename[0]=NIL; #ifdef _DEBUG appout=_tfopen(_T("text.txt"),_T("wb")); #else appout=stdout; #endif _tcscat(inifile,_T("\\") _T(APPNAME)); _tmkdir(inifile); _tcscat(inifile,_T("\\rview.ini")); while (--argc>0) { /*if argv start at '-')*/ if (argv[argc][0]==_T('-')) { switch(argv[argc][1]) { case _T('r'): case _T('R'): reload=1; break; case _T('h'): case _T('H'): viewhelp=1; break; case _T('v'): case _T('V'): viewini=1; break; case _T('l'): case _T('L'): viewlist=1; break; case _T('n'): case _T('N'): viewnext=1; break; case _T('p'): case _T('P'): viewprev=1; break; case _T('z'): case _T('Z'): viewrnd=1; break; case _T('c'): case _T('C'): _tcscpy(pageviewer,(_TCHAR*)&(argv[argc][2])); break; case _T('f'): case _T('F'): _tcscpy(defaultfile,(_TCHAR*)&(argv[argc][2])); break; } } else viewindex=_ttoi(argv[argc]); } if (viewhelp==1) { fprintf(appout,"%s\n",APPINFO); fprintf(appout,"%s\n",APPHELP); return 0; } _tgetcwd(lastdir,_MAX_PATH); if (loadpre(&status,inifile)==0) { status.workdir[0] =NIL;// _tcscpy(status.workdir,lastdir); status.viewer[0]=NIL;//_tcscpy(status.viewer,pageviewer); status.filename[0] = NIL; } #ifndef _DEBUG _ftprintf(appout,_T("CURLINE:%d\n"),__LINE__); _ftprintf(appout,_T("Viewer:%s\n"),status.viewer); _ftprintf(appout,_T("Workdir:%s\n"),status.workdir); _ftprintf(appout,_T("Filename:%s\n"),status.filename); #endif if (status.workdir[0]==NIL) _tcscpy(status.workdir ,lastdir); if (pageviewer[0]!=NIL) _tcscpy(status.viewer,pageviewer); else if (status.viewer[0]==NIL) _tcscpy(status.viewer,DEFAULTVIEWER); if (viewini==1) { _ftprintf(appout,_T("DefaultViewer:%s\nWorkDir:%s\nLastFile:%s"),status.viewer,status.workdir,status.filename ); savecur(&status,inifile); return 0; } if (reload==1) { int c=0; fprintf(appout,"原先目录是:"); _ftprintf(appout,_T("%s\n"), status.workdir); fprintf(appout,"当前目录是:"); _ftprintf(appout,_T("%s\n"),lastdir); fprintf(appout,"确定要将当前目录设定为工作目录?(Y/N)"); //fflush(stdin); c=_fgettchar(); if (c==_T('Y') || c==_T('y')) { _tcscpy(status.workdir,lastdir); status.filename[0] = NIL; savecur(&status,inifile); } } //_chdir(status.workdir); //DEBUGStr(status.workdir) if (defaultfile[0]!=NIL) _tcscpy(status.filename ,defaultfile); if (status.filename[0]==NIL) viewnext=1; /* DEBUGInt(viewnext); DEBUGInt(viewlist); DEBUGInt(viewrnd); DEBUGInt(viewindex);*/ if ((viewlist)||(viewrnd)||(viewindex)||(viewnext)) { searchfor=buildpath(searchfor,status.workdir,WILDNAME); #ifdef _DEBUG //DEBUGStr(status.workdir); _ftprintf(appout,_T("%s\n"),status.workdir); _ftprintf(appout,_T("%s\n"),WILDNAME); _ftprintf(appout,_T("%s\n"),searchfor); #endif fcount=countfile(searchfor,_A_ARCH); if (fcount<=0) return 0; filelist=(_TCHAR **)malloc(sizeof(_TCHAR*)*(fcount+1)); fcount=findfile(searchfor,_A_ARCH,filelist,fcount); qsort((void*)filelist,(size_t) fcount,sizeof(_TCHAR*),(int(_cdecl*)(const void*,const void*))&wcscmp); //viewlist if (viewlist==1) { int i; for (i=0;i<fcount;i++){ _ftprintf(appout,_T("[%4d]:%s\n"),i+1,filelist[i]); } return(0); } else if (viewindex>0) { //viewindex next=viewindex-1; } else if (viewrnd==1) { //viewrnd srand( (unsigned)time( NULL ) ); next= rand( ) % fcount; } else if (status.filename[0]==NIL) { next=0; } else if (viewnext==1) { next=getindex(status.filename,filelist,fcount)+1; } else if (viewprev==1) { next=getindex(status.filename,filelist,fcount)-1; } if ((next>fcount-1) || next<0 ) next=0; _tcscpy(status.filename ,filelist[next]); } /*DEBUGStr(status.viewer ) DEBUGStr(status.workdir ) DEBUGStr(status.filename )*/ savecur(&status,inifile); defaultfile=buildpath(defaultfile,status.workdir ,status.filename ); _stprintf(cmdline,_T("%s \"%s\""),status.viewer,defaultfile); //printf("%s:\n",status.filename); #ifdef _DEBUG _ftprintf(appout,_T("Viewer:%s\n"),status.viewer); _ftprintf(appout,_T("Workdir:%s\n"),status.workdir); _ftprintf(appout,_T("Filename:%s\n"),status.filename); _ftprintf(appout,_T("DefaultFile:%s\n"),defaultfile); _ftprintf(appout,_T("Cmdline:%s\n"),cmdline); #endif system(cmdline); _ftprintf(appout,_T("[%s]\n"),defaultfile); fclose(appout); return (0); }