/* * look for a plan 9 partition table on drive `unit' in the second * sector (sector 1) of partition `name'. * if found, add the partitions defined in the table. */ static void p9part(SDunit *unit, char *name) { SDpart *p; char *field[4], *line[Npart+1]; uvlong start, end; int i, n; dprint("p9part %s %s\n", unit->name, name); p = sdfindpart(unit, name); if(p == nil) return; if(sdreadblk(unit, p, partbuf, unit->secsize, 0) < 0) return; partbuf[unit->secsize-1] = '\0'; if(strncmp((char*)partbuf, "part ", 5) != 0) return; n = gettokens((char*)partbuf, line, Npart+1, "\n"); if(n == 0) return; for(i = 0; i < n && unit->npart < SDnpart; i++){ if(strncmp(line[i], "part ", 5) != 0) break; if(gettokens(line[i], field, 4, " ") != 4) break; start = strtoull(field[2], 0, 0); end = strtoull(field[3], 0, 0); if(start >= end || end > unit->sectors) break; sdaddpart(unit, field[1], p->start+start, p->start+end); } }
static void oldp9part(SDunit *unit) { SDpart *pp; char *field[3], *line[Npart+1]; ulong n; uvlong start, end; int i; /* * We have some partitions already. */ pp = &unit->part[unit->npart]; /* * We prefer partition tables on the second to last sector, * but some old disks use the last sector instead. */ strcpy(pp->name, "partition"); pp->start = unit->sectors - 2; pp->end = unit->sectors - 1; dprint("oldp9part %s\n", unit->name); if(sdreadblk(unit, pp, partbuf, 0, 0) < 0) return; if(strncmp((char*)partbuf, MAGIC, sizeof(MAGIC)-1) != 0) { /* not found on 2nd last sector; look on last sector */ pp->start++; pp->end++; if(sdreadblk(unit, pp, partbuf, 0, 0) < 0) return; if(strncmp((char*)partbuf, MAGIC, sizeof(MAGIC)-1) != 0) return; print("%s: using old plan9 partition table on last sector\n", unit->name); }else print("%s: using old plan9 partition table on 2nd-to-last sector\n", unit->name); /* we found a partition table, so add a partition partition */ unit->npart++; partbuf[unit->secsize-1] = '\0'; /* * parse partition table */ n = gettokens((char*)partbuf, line, Npart+1, "\n"); if(n && strncmp(line[0], MAGIC, sizeof(MAGIC)-1) == 0){ for(i = 1; i < n && unit->npart < SDnpart; i++){ if(gettokens(line[i], field, 3, " ") != 3) break; start = strtoull(field[1], 0, 0); end = strtoull(field[2], 0, 0); if(start >= end || end > unit->sectors) break; sdaddpart(unit, field[0], start, end); } } }
int main(int argc,char** argv){ int used_stdin = 0; /* If no arguments are supplied, check stdin for any. */ if(*(argv+1) == NULL){ char line[MAX_LINE]; if(isatty(fileno(stdin))) fprintf(stderr,"Enter the names of one or more environment variables, seperated by spaces.\n"); if(fgets(line,MAX_LINE,stdin)){ used_stdin = 1; line[strlen(line)-1] = '\0'; int num_tokens = countTokens(line); argv = gettokens(line); argc = num_tokens + 1; } } if(argc < 2){ fprintf(stderr,"Must have at least 1 argument.\n"); fprintf(stderr,"%s\n",USAGE); exit(1); } if(!used_stdin) argv++; //increment past ./showenv showEnv(argv); exit(0); }
int environment_set(char* line) // Assign a value to one (or various) environment variable // Return 1 if assignations were processed, else return 0 { // Split line in different assignations char* array[10]; int numAssignations = gettokens(line, array, 10, "="); // If line has at least one assignation, do them if(numAssignations > 1) { char* value = array[numAssignations-1]; // Remove trailing new line int len = strlen(value); if(value[len-1] == '\n') value[len-1] = '\0'; // Do the assignations numAssignations -= 2; for(; numAssignations >= 0; --numAssignations) putenv(array[numAssignations], value); return 1; } return 0; }
static Path* walkto(char *a, char **lastp) { char *els[Nels], *path; int nels; Path *p; path = fsname(a); nels = gettokens(path, els, Nels, "/"); if(nels < 1){ free(path); error("invalid path"); } if(catcherror()){ free(path); error("walkpath: %r"); } if(lastp != nil){ p = walkpath(fs->root, els, nels-1); *lastp = a + strlen(a) - strlen(els[nels-1]); }else p = walkpath(fs->root, els, nels); free(path); noerror(); if(verb) print("walked to %H\n", p->f[p->nf-1]); return p; }
char* getPath(char* command) // Search for `command` on the different directories specified on the path and // return the executable full path. // If command is not found, it returns the last processed full path { char* env = getenv(ENV_PATH); char* array[10]; int numTokens = gettokens(env, array, 10, PATH_TOKEN_SPLIT); char* path = calloc(256, sizeof(char)); int i; for(i = 0; i < numTokens; ++i) { // Calc command path strncpy(path, array[i],256); strncat(path, "/", 256); strncat(path, command, 256); // If command exists at dir, return it Dir* d = dirstat(path); free(d); if(d) // We are only interested on the pointer, not on it's content... break; } free(env); return path; }
void threadmain(int argc, char *argv[]) { char *dev; char *args[Nels]; int i, j, nargs; dev = "disk"; ARGBEGIN{ case 'v': verb++; break; case 'f': dev = EARGF(usage()); break; default: if(ARGC() >= 'A' && ARGC() <= 'Z'){ dbg['d'] = 1; dbg[ARGC()] = 1; }else usage(); }ARGEND; if(argc == 0) usage(); fatalaborts = 1; fmtinstall('H', mbfmt); fmtinstall('M', dirmodefmt); errinit(Errstack); if(catcherror()){ fprint(2, "cmd failed: %r\n"); threadexitsall("failed"); } fsopen(dev); for(i = 0; i < argc; i++){ if(verb>1) fsdump(0, Mem); print("%% %s\n", argv[i]); nargs = gettokens(argv[i], args, Nels, "!"); for(j = 0; j < nelem(cmds); j++){ if(strcmp(cmds[j].name, argv[i]) != 0) continue; if(cmds[j].nargs != 0 && cmds[j].nargs != nargs) fprint(2, "usage: %s\n", cmds[j].usage); else cmds[j].f(nargs, args); break; } if(j == nelem(cmds)){ fprint(2, "no such command\n"); for(j = 0; j < nelem(cmds); j++) fprint(2, "\t%s\n", cmds[j].usage); break; } } if(verb>1) fsdump(0, Mem); noerror(); threadexitsall(nil); }
void commandline() { while (1) // infinite loop that depends on quit { printf("> "); gets(curline); // reads in line gettokens(); // calls gettokens memset(curline, NULL, LINESIZE); // clears curline //printf("token is %s\n", tokens[0]); if (strcmp(tokens[0], "quit") == 0) // quit { printf("Bye!\n"); break; } else if (strcmp(tokens[0], "sum") == 0) // sum { int sum = 0; for (int i = 0; i < TCOUNT; i++) { if (i > 0 && i < tokensize) // making sure only integer values are included { sum += atoi(tokens[i]); // atoi to get integer values } for (int j = 0; j < TSIZE; j++) // loop for clearing the 2D array { tokens[i][j] = NULL; } } printf("%d", sum); printf("\n"); } else if (strcmp(tokens[0], "prod") == 0) // prod { int prod = 1; for (int i = 0; i < 10; i++) { if(i > 0 && i < tokensize) // making sure only integer values are included { prod *= atoi(tokens[i]); //printf("atoi is %d\n", atoi(tokens[i])); } for (int j = 0; j < TSIZE; j++) // clearing tokens { tokens[i][j] = NULL; } } printf("%d", prod); printf("\n"); } else // error { printf("ERROR Sytem does not recognize this command\n"); } } }
int setreport(char *s) /* **----------------------------------------------------------- ** Input: *s = report format command ** Output: none ** Returns: error code ** Purpose: processes a report formatting command ** issued by the ENsetreport function **----------------------------------------------------------- */ { Ntokens = gettokens(s); return(reportdata()); }
void process(Tokenrow *trp) { int anymacros = 0; for (;;) { if (trp->tp >= trp->lp) { trp->tp = trp->lp = trp->bp; outbufp = outbuf; anymacros |= gettokens(trp, 1); trp->tp = trp->bp; } if (trp->tp->type == END) { if (--incdepth >= 0) { if (cursource->ifdepth) error(ERROR, "Unterminated conditional in #include"); unsetsource(); cursource->line += cursource->lineinc; trp->tp = trp->lp; genline(); continue; } if (ifdepth) error(ERROR, "Unterminated #if/#ifdef/#ifndef"); break; } if (trp->tp->type == SHARP) { trp->tp += 1; control(trp); } else if (!skipping && anymacros) expandrow(trp, NULL); if (skipping) setempty(trp); puttokens(trp); anymacros = 0; cursource->line += cursource->lineinc; if (cursource->lineinc > 1) { genline(); } } }
void script_process(char* script) { // Split script in independent pipelines char* array[10]; int numPipelines = gettokens(script, array, 10, ";"); // run script commands int i; for(i = 0; i < numPipelines; ++i) { // expand environment variables and substitute command line char pointer // with the one with expanded environment variables (if necesary) // char* expanded = expand_envVars(array[i]); // if(expanded) array[i] = expanded; array[i] = environment_expand(array[i]); // move commands to background (if necesary) background(array[i]); // Exec `cd` (it's a built-in, but must change shell environment itself, // so we check and exec for it directly here) if(builtin_cd(array[i])) { free(array[i]); continue; } // Set environment variable if(environment_set(array[i])) { free(array[i]); continue; } // run foreground command pipeline_process(array[i]); // free line created by environment variables expansion free(array[i]); } }
int main (int argc, char** argv, char** envp){ /* Record the directory where the executable files are. */ init_dir = (char *)malloc(sizeof(char)*MAX_LINE); getcwd(init_dir,sizeof(char)*MAX_LINE); init_dir[strlen(init_dir)] = '\0'; /* Prompt for input until ctrl-d or exit have been entered */ char *line = (char *)malloc(sizeof(char)*MAX_LINE); fprintf(stdout,"$>"); while(fgets(line,MAX_LINE,stdin)){ line[strlen(line)-1] = '\0'; // Nip the buf int num_tokens = countTokens(line); char **tokens = (char **) malloc(sizeof(char *) * num_tokens); tokens = gettokens(line); /* exit was entered into the terminal so free heap space and quit. */ if (*tokens != NULL && strcmp("exit",tokens[0]) == 0){ freeStringArray(tokens); free(line); free(init_dir); exit(0); } /* Nothing entered in stdin. Continue prompting */ if(*tokens == NULL){ fprintf(stdout,"$> "); continue; } if (DEBUG) fprintf(stderr,"about to eval.\n"); evaluateCommand(tokens); /* free memory */ line = (char *)realloc(line,sizeof(char)*MAX_LINE); freeStringArray(tokens); fprintf(stdout,"$> "); } return 0; }
/* * Evaluate the ## operators in a tokenrow */ void doconcat(Tokenrow *trp) { Token *ltp, *ntp; STATIC Tokenrow ntr; int len; CHECKIN(); for (trp->tp=trp->bp; trp->tp<trp->lp; trp->tp++) { if (trp->tp->type==DSHARP1) trp->tp->type = DSHARP; else if (trp->tp->type==DSHARP) { STATIC char tt[128]; ltp = trp->tp-1; ntp = trp->tp+1; if (ltp<trp->bp || ntp>=trp->lp) { error(ERROR, "## occurs at border of replacement"); continue; } len = ltp->len + ntp->len; strncpy((char*)tt, (char*)ltp->t, ltp->len); strncpy((char*)tt+ltp->len, (char*)ntp->t, ntp->len); tt[len] = '\0'; setsource("<##>", -1, tt); maketokenrow(3, &ntr); gettokens(&ntr, 1); unsetsource(); if (ntr.lp-ntr.bp!=2 || ntr.bp->type==UNCLASS) error(WARNING, "Bad token %r produced by ##", &ntr); ntr.lp = ntr.bp+1; trp->tp = ltp; makespace(&ntr); insertrow(trp, (ntp-ltp)+1, &ntr); dofree(ntr.bp); trp->tp--; } } CHECKOUT(); }
/** * process - 处理c源程序的总函数 * @trp: 用来存储c源程序中的一行Token */ void process(Tokenrow *trp) { int anymacros = 0; for (;;) { if (trp->tp >= trp->lp) { /* 如果当前token row中没有有效数据 */ trp->tp = trp->lp = trp->bp; /* 重置token row的当前token指针 */ outp = outbuf; /* 重置输出缓冲区的当前指针 */ anymacros |= gettokens(trp, 1); /* 得到一行Token */ trp->tp = trp->bp; } if (trp->tp->type == END) { /* 如果遇到EOFC结束符 */ if (--incdepth >= 0) { if (cursource->ifdepth) error(ERROR,"Unterminated conditional in #include"); unsetsource(); cursource->line += cursource->lineinc; trp->tp = trp->lp; genline(); continue; } if (ifdepth) error(ERROR, "Unterminated #if/#ifdef/#ifndef"); break; } if (trp->tp->type==SHARP) { /* 如果当前Token是'#'字符 */ trp->tp += 1; /* tp移动到token row中的下一个token */ control(trp); /* 处理预处理指令部分(宏定义,条件编译,头文件包含) */ } else if (!skipping && anymacros) expandrow(trp, NULL); if (skipping) /* 如果当前是忽略状态 */ setempty(trp); /* 置空当前行 */ puttokens(trp); /* 输出当前行 */ anymacros = 0; cursource->line += cursource->lineinc; if (cursource->lineinc>1) { genline(); } } }
int background(char* line) // Check and exec on background all the commands ended with '&' on the command // line and return the last, foreground command { // Split pipeline in independent commands char* array[10]; int numCommands = gettokens(line, array, 10, "&"); // run script commands int i; for(i = 0; i < numCommands-1; ++i) { switch(fork()) { case -1: return -1; case 0: // child { // redirect stdin to /dev/null redirect_stdin("/dev/null"); // process pipeline pipeline_process(array[i]); exitError(); } // parent loop to exec in background the next command (if any) } } // collapse line to let only the last (not background) command on it int len = strlen(array[numCommands-1]); memmove(line, array[numCommands-1], len); *(line+len) = '\0'; return 0; }
int readdata() /* **-------------------------------------------------------------- ** Input: none ** Output: returns error code ** Purpose: reads contents of input data file **-------------------------------------------------------------- */ { char line[MAXLINE+1], /* Line from input data file */ wline[MAXLINE+1]; /* Working copy of input line */ int sect,newsect, /* Data sections */ errcode = 0, /* Error code */ inperr,errsum; /* Error code & total error count */ /* Allocate input buffer */ X = (double *) calloc(MAXTOKS, sizeof(double)); ERRCODE(MEMCHECK(X)); if (!errcode) { /* Initialize number of network components */ Ntitle = 0; Nnodes = 0; Njuncs = 0; Ntanks = 0; Nlinks = 0; Npipes = 0; Npumps = 0; Nvalves = 0; Ncontrols = 0; Nrules = 0; Ncurves = MaxCurves; Npats = MaxPats; PrevPat = NULL; PrevCurve = NULL; sect = -1; errsum = 0; /* Read each line from input file. */ while (fgets(line,MAXLINE,InFile) != NULL) { /* Make copy of line and scan for tokens */ strcpy(wline,line); Ntokens = gettokens(wline); /* Skip blank lines and comments */ if (Ntokens == 0) continue; if (*Tok[0] == ';') continue; /* Check if max. length exceeded */ if (strlen(line) >= MAXLINE) { sprintf(Msg,ERR214); writeline(Msg); writeline(line); errsum++; } /* Check if at start of a new input section */ if (*Tok[0] == '[') { newsect = findmatch(Tok[0],SectTxt); if (newsect >= 0) { sect = newsect; if (sect == _END) break; continue; } else { inperrmsg(201,sect,line); errsum++; break; } } /* Otherwise process next line of input in current section */ else { inperr = newline(sect,line); if (inperr > 0) { inperrmsg(inperr,sect,line); errsum++; } } /* Stop if reach end of file or max. error count */ if (errsum == MAXERRS) break; } /* End of while */ /* Check for errors */ if (errsum > 0) errcode = 200; } /* Check for unlinked nodes */ if (!errcode) errcode = unlinked(); /* Get pattern & curve data from temp. lists */ if (!errcode) errcode = getpatterns(); if (!errcode) errcode = getcurves(); if (!errcode) errcode = getpumpparams(); /* Free input buffer */ free(X); return(errcode); } /* End of readdata */
void setup(int argc, char **argv) { int c, fd, i; char *fp, *dp; Tokenrow tr; extern void setup_kwtab(void); setup_kwtab(); while ((c = getopt(argc, argv, "MNOVv+I:D:U:F:lg")) != -1) switch (c) { case 'N': for (i=0; i<NINCLUDE; i++) if (includelist[i].always==1) includelist[i].deleted = 1; break; case 'I': for (i=NINCLUDE-2; i>=0; i--) { if (includelist[i].file==NULL) { includelist[i].always = 1; includelist[i].file = optarg; break; } } if (i<0) error(FATAL, "Too many -I directives"); break; case 'D': case 'U': setsource("<cmdarg>", -1, optarg); maketokenrow(3, &tr); gettokens(&tr, 1); doadefine(&tr, c); unsetsource(); break; case 'M': Mflag++; break; case 'v': fprintf(stderr, "%s %s\n", argv[0], rcsid); break; case 'V': verbose++; break; case '+': Cplusplus++; break; default: break; } dp = "."; fp = "<stdin>"; fd = 0; if (optind<argc) { if ((fp = strrchr(argv[optind], '/')) != NULL) { int len = fp - argv[optind]; dp = (char*)newstring((uchar*)argv[optind], len+1, 0); dp[len] = '\0'; } fp = (char*)newstring((uchar*)argv[optind], strlen(argv[optind]), 0); if ((fd = open(fp, 0)) <= 0) error(FATAL, "Can't open input file %s", fp); } if (optind+1<argc) { int fdo = creat(argv[optind+1], 0666); if (fdo<0) error(FATAL, "Can't open output file %s", argv[optind+1]); dup2(fdo, 1); } if(Mflag) setobjname(fp); includelist[NINCLUDE-1].always = 0; includelist[NINCLUDE-1].file = dp; setsource(fp, fd, NULL); }
static int uboxInit(char* users, int len) { User *g, *u; Ubox *box, *obox; int blank, comment, i, nline, nuser; char *buf, *f[5], **line, *p, *q, *s; /* * Strip out whitespace and comments. * Note that comments are pointless, they disappear * when the server writes the database back out. */ blank = 1; comment = nline = 0; s = p = buf = vtMemAlloc(len+1); for(q = users; *q != '\0'; q++){ if(*q == '\r' || *q == '\t' || *q == ' ') continue; if(*q == '\n'){ if(!blank){ if(p != s){ *p++ = '\n'; nline++; s = p; } blank = 1; } comment = 0; continue; } if(*q == '#') comment = 1; blank = 0; if(!comment) *p++ = *q; } *p = '\0'; line = vtMemAllocZ((nline+2)*sizeof(char*)); if((i = gettokens(buf, line, nline+2, "\n")) != nline){ fprint(2, "nline %d (%d) botch\n", nline, i); vtMemFree(line); vtMemFree(buf); return 0; } /* * Everything is updated in a local Ubox until verified. */ box = vtMemAllocZ(sizeof(Ubox)); /* * First pass - check format, check for duplicates * and enter in hash buckets. */ nuser = 0; for(i = 0; i < nline; i++){ s = vtStrDup(line[i]); if(getfields(s, f, nelem(f), 0, ":") != 4){ fprint(2, "bad line '%s'\n", line[i]); vtMemFree(s); continue; } if(*f[0] == '\0' || *f[1] == '\0'){ fprint(2, "bad line '%s'\n", line[i]); vtMemFree(s); continue; } if(!validUserName(f[0])){ fprint(2, "invalid uid '%s'\n", f[0]); vtMemFree(s); continue; } if(_userByUid(box, f[0]) != nil){ fprint(2, "duplicate uid '%s'\n", f[0]); vtMemFree(s); continue; } if(!validUserName(f[1])){ fprint(2, "invalid uname '%s'\n", f[0]); vtMemFree(s); continue; } if(_userByUname(box, f[1]) != nil){ fprint(2, "duplicate uname '%s'\n", f[1]); vtMemFree(s); continue; } u = userAlloc(f[0], f[1]); uboxAddUser(box, u); line[nuser] = line[i]; nuser++; vtMemFree(s); } assert(box->nuser == nuser); /* * Second pass - fill in leader and group information. */ for(i = 0; i < nuser; i++){ s = vtStrDup(line[i]); getfields(s, f, nelem(f), 0, ":"); assert(g = _userByUname(box, f[1])); if(*f[2] != '\0'){ if((u = _userByUname(box, f[2])) == nil) g->leader = vtStrDup(g->uname); else g->leader = vtStrDup(u->uname); box->len += strlen(g->leader); } for(p = f[3]; p != nil; p = q){ if((q = utfrune(p, L',')) != nil) *q++ = '\0'; if(!_groupAddMember(box, g, p)){ // print/log error here } } vtMemFree(s); } vtMemFree(line); vtMemFree(buf); for(i = 0; usersMandatory[i] != nil; i++){ if((u = _userByUid(box, usersMandatory[i])) == nil){ vtSetError("user '%s' is mandatory", usersMandatory[i]); uboxFree(box); return 0; } if(strcmp(u->uid, u->uname) != 0){ vtSetError("uid/uname for user '%s' must match", usersMandatory[i]); uboxFree(box); return 0; } } vtLock(ubox.lock); obox = ubox.box; ubox.box = box; vtUnlock(ubox.lock); if(obox != nil) uboxFree(obox); return 1; }
/* returns with *locp filled in and locp->fd open, if possible */ static void findnvram(Nvrwhere *locp) { char *nvrlen, *nvroff, *nvrcopy, *db, *v[2]; int fd, i, safeoff, safelen; if (nvrfile == nil) { nvrfile = getenv("nvram"); db = getenv("nvramdebug"); nvramdebug = db != nil; free(db); } if (cputype == nil) cputype = getenv("cputype"); if(cputype == nil) cputype = strdup("mips"); if(strcmp(cputype, "386")==0 || strcmp(cputype, "alpha")==0) { free(cputype); cputype = strdup("pc"); } fd = -1; safeoff = -1; safelen = -1; if(nvrfile != nil && *nvrfile != '\0'){ /* accept device and device!file */ nvrcopy = strdup(nvrfile); i = gettokens(nvrcopy, v, nelem(v), "!"); if (i < 1) { i = 1; v[0] = ""; v[1] = nil; } if(nvramdebug) fprint(2, "nvram at %s?...", v[0]); fd = open(v[0], ORDWR); if (fd < 0) fd = open(v[0], OREAD); safelen = sizeof(Nvrsafe); if(strstr(v[0], "/9fat") == nil) safeoff = 0; nvrlen = getenv("nvrlen"); if(nvrlen != nil) safelen = atoi(nvrlen); nvroff = getenv("nvroff"); if(nvroff != nil){ if(strcmp(nvroff, "dos") == 0) safeoff = -1; else safeoff = atoi(nvroff); } if(safeoff < 0 && fd >= 0){ safelen = 512; safeoff = finddosfile(fd, i == 2? v[1]: "plan9.nvr"); if(safeoff < 0){ /* didn't find plan9.nvr? */ close(fd); fd = -1; } } free(nvrcopy); free(nvroff); free(nvrlen); }else{ for(i=0; i<nelem(nvtab); i++){ if(strcmp(cputype, nvtab[i].cputype) != 0) continue; if(nvramdebug) fprint(2, "nvram at %s?...", nvtab[i].file); if((fd = open(nvtab[i].file, ORDWR)) < 0 && (fd = open(nvtab[i].file, OREAD)) < 0) continue; safeoff = nvtab[i].off; safelen = nvtab[i].len; if(safeoff == -1){ safeoff = finddosfile(fd, "plan9.nvr"); if(safeoff < 0){ /* didn't find plan9.nvr? */ close(fd); fd = -1; continue; } } nvrfile = strdup(nvtab[i].file); break; } if(i >= nelem(nvtab)) /* tried them all? */ werrstr(""); /* ignore failed opens */ } locp->fd = fd; locp->safelen = safelen; locp->safeoff = safeoff; }
/* * Gather an arglist, starting in trp with tp pointing at the macro name. * Return total number of tokens passed, stash number of args found. * trp->tp is not changed relative to the tokenrow. */ int gatherargs(Tokenrow *trp, Tokenrow **atr, int *narg) { int parens = 1; int ntok = 0; Token *bp, *lp; Tokenrow ttr; int ntokp; int needspace; *narg = -1; /* means that there is no macro call */ /* look for the ( */ for (;;) { trp->tp++; ntok++; if (trp->tp >= trp->lp) { gettokens(trp, 0); if ((trp->lp-1)->type==END) { trp->lp -= 1; trp->tp -= ntok; return ntok; } } if (trp->tp->type==LP) break; if (trp->tp->type!=NL) return ntok; } *narg = 0; ntok++; ntokp = ntok; trp->tp++; /* search for the terminating ), possibly extending the row */ needspace = 0; while (parens>0) { if (trp->tp >= trp->lp) gettokens(trp, 0); if (needspace) { needspace = 0; makespace(trp); } if (trp->tp->type==END) { trp->lp -= 1; trp->tp -= ntok; error(ERROR, "EOF in macro arglist"); return ntok; } if (trp->tp->type==NL) { trp->tp += 1; adjustrow(trp, -1); trp->tp -= 1; makespace(trp); needspace = 1; continue; } if (trp->tp->type==LP) parens++; else if (trp->tp->type==RP) parens--; trp->tp++; ntok++; } trp->tp -= ntok; /* Now trp->tp won't move underneath us */ lp = bp = trp->tp+ntokp; for (; parens>=0; lp++) { if (lp->type == LP) { parens++; continue; } if (lp->type==RP) parens--; if (lp->type==DSHARP) lp->type = DSHARP1; /* ## not special in arg */ if (lp->type==COMMA && parens==0 || parens<0 && (lp-1)->type!=LP) { if (*narg>=NARG-1) error(FATAL, "Sorry, too many macro arguments"); ttr.bp = ttr.tp = bp; ttr.lp = lp; atr[(*narg)++] = normtokenrow(&ttr); bp = lp+1; } } return ntok; }
/* * get key info out of nvram. since there isn't room in the PC's nvram use * a disk partition there. */ int readnvram(Nvrsafe *safep, int flag) { char buf[1024], in[128], *cputype, *nvrfile, *nvrlen, *nvroff, *v[2]; int fd, err, i, safeoff, safelen; Nvrsafe *safe; err = 0; memset(safep, 0, sizeof(*safep)); nvrfile = getenv("nvram"); cputype = getenv("cputype"); if(cputype == nil) cputype = "mips"; if(strcmp(cputype, "386")==0 || strcmp(cputype, "alpha")==0) cputype = "pc"; fd = -1; safeoff = -1; safelen = -1; if(nvrfile != nil){ /* accept device and device!file */ i = gettokens(nvrfile, v, nelem(v), "!"); fd = open(v[0], ORDWR); safelen = sizeof(Nvrsafe); if(strstr(v[0], "/9fat") == nil) safeoff = 0; nvrlen = getenv("nvrlen"); if(nvrlen != nil) safelen = atoi(nvrlen); nvroff = getenv("nvroff"); if(nvroff != nil){ if(strcmp(nvroff, "dos") == 0) safeoff = -1; else safeoff = atoi(nvroff); } if(safeoff < 0 && fd >= 0){ safelen = 512; safeoff = finddosfile(fd, i == 2 ? v[1] : "plan9.nvr"); if(safeoff < 0){ close(fd); fd = -1; } } free(nvrfile); if(nvrlen != nil) free(nvrlen); if(nvroff != nil) free(nvroff); }else{ for(i=0; i<nelem(nvtab); i++){ if(strcmp(cputype, nvtab[i].cputype) != 0) continue; if((fd = open(nvtab[i].file, ORDWR)) < 0) continue; safeoff = nvtab[i].off; safelen = nvtab[i].len; if(safeoff == -1){ safeoff = finddosfile(fd, "plan9.nvr"); if(safeoff < 0){ close(fd); fd = -1; continue; } } break; } } if(fd < 0 || seek(fd, safeoff, 0) < 0 || read(fd, buf, safelen) != safelen){ err = 1; if(flag&(NVwrite|NVwriteonerr)) fprint(2, "can't read nvram: %r\n"); memset(safep, 0, sizeof(*safep)); safe = safep; }else{ memmove(safep, buf, sizeof *safep); safe = safep; err |= check(safe->machkey, DESKEYLEN, safe->machsum, "bad nvram key"); /* err |= check(safe->config, CONFIGLEN, safe->configsum, "bad secstore key"); */ err |= check(safe->authid, ANAMELEN, safe->authidsum, "bad authentication id"); err |= check(safe->authdom, DOMLEN, safe->authdomsum, "bad authentication domain"); } if((flag&NVwrite) || (err && (flag&NVwriteonerr))){ xreadcons("authid", nil, 0, safe->authid, sizeof(safe->authid)); xreadcons("authdom", nil, 0, safe->authdom, sizeof(safe->authdom)); xreadcons("secstore key", nil, 1, safe->config, sizeof(safe->config)); for(;;){ if(xreadcons("password", nil, 1, in, sizeof in) == nil) goto Out; if(passtokey(safe->machkey, in)) break; } safe->machsum = nvcsum(safe->machkey, DESKEYLEN); safe->configsum = nvcsum(safe->config, CONFIGLEN); safe->authidsum = nvcsum(safe->authid, sizeof(safe->authid)); safe->authdomsum = nvcsum(safe->authdom, sizeof(safe->authdom)); memmove(buf, safe, sizeof *safe); if(seek(fd, safeoff, 0) < 0 || write(fd, buf, safelen) != safelen){ fprint(2, "can't write key to nvram: %r\n"); err = 1; }else err = 0; } Out: close(fd); return err ? -1 : 0; }
void setup(int argc, char **argv) { int c, fd, i, n; char *fp, *dp; Tokenrow tr; setup_kwtab(); #if defined(MACOSX) || defined(AIX) || defined(_WIN32) while ((c = stgetopt(argc, argv, "NOPV:I:D:U:F:A:X:u:l:+")) != -1) #else while ((c = getopt(argc, argv, "NOPV:I:D:U:F:A:X:u:l:+")) != -1) #endif switch (c) { case 'N': for (i = 0; i < NINCLUDE; i++) if (includelist[i].always == 1) includelist[i].deleted = 1; break; case 'I': for (i = NINCLUDE - 2; i >= 0; i--) { if (includelist[i].file == NULL) { includelist[i].always = 1; includelist[i].file = optarg; break; } } if (i < 0) error(FATAL, "Too many -I directives"); break; case 'D': case 'U': case 'A': setsource("<cmdarg>", -1, -1, optarg, 0); maketokenrow(3, &tr); gettokens(&tr, 1); doadefine(&tr, c); dofree(tr.bp); unsetsource(); break; case 'P': /* Lineinfo */ Pflag++; break; case 'V': for (n = 0; (c = optarg[n]) != '\0'; n++) switch (c) { case 'i': Iflag++; break; case 'm': Mflag = 1; break; case 'x': Mflag = 2; break; case 't': Vflag++; break; case 'v': fprintf(stderr, "%s\n", argv[0]); break; default: error(WARNING, "Unknown verbose option %c", c); } break; case 'X': for (n = 0; (c = optarg[n]) != '\0'; n++) switch (c) { case 'a': Aflag++; break; case 'i': Xflag++; break; case 'c': Cflag++; break; case 'd': Dflag++; break; case 'w': dp = &optarg[n + 1]; n += (int)strlen(dp); while (isspace(*dp)) dp++; for (i = NINCLUDE - 1; i >= 0; i--) { if (wraplist[i].file == NULL) { wraplist[i].file = dp; break; } } if (i < 0) error(WARNING, "Too many -Xw directives"); break; default: error(WARNING, "Unknown extension option %c", c); } break; case '+': Cplusplus++; break; case 'u': /* -undef fuer GCC (dummy) */ case 'l': /* -lang-c++ fuer GCC (dummy) */ break; default: break; } dp = "."; fp = "<stdin>"; fd = 0; if (optind < argc) { if ((fp = strrchr(argv[optind], '/')) != NULL) { int len = (int)(fp - argv[optind]); dp = (char *) newstring((uchar *) argv[optind], len + 1, 0); dp[len] = '\0'; } fp = (char *) newstring((uchar *) argv[optind], strlen(argv[optind]), 0); if ((fd = open(fp, O_RDONLY)) <= 0) error(FATAL, "Can't open input file %s", fp); } if (optind + 1 < argc) { int fdo = creat(argv[optind + 1], 0666); if (fdo < 0) error(FATAL, "Can't open output file %s", argv[optind + 1]); dup2(fdo, 1); } includelist[NINCLUDE - 1].always = 0; includelist[NINCLUDE - 1].file = dp; setsource(fp, -1, fd, NULL, 0); }
void main(int argc, char **argv) { Biobuf bout; char *fields[NFLDS], name[2*LEN], *p, *namep; char *uid, *gid; uint32_t mode, mtime; uint64_t bytes; quotefmtinstall(); namep = name; ARGBEGIN{ case 'd': p = ARGF(); if(strlen(p) >= LEN) error("destination fs name too long\n"); strcpy(name, p); namep = name + strlen(name); break; case 'h': hflag = 1; Binit(&bout, 1, OWRITE); break; case 'u': uflag = 1; Tflag = 1; break; case 'T': Tflag = 1; break; case 'v': vflag = 1; break; default: usage(); }ARGEND Binits(&bin, 0, OREAD, binbuf, sizeof binbuf); while(p = Brdline(&bin, '\n')){ p[Blinelen(&bin)-1] = '\0'; strcpy(linebuf, p); p = linebuf; if(strcmp(p, "end of archive") == 0){ Bterm(&bout); fprint(2, "done\n"); exits(0); } if (gettokens(p, fields, NFLDS, " \t") != NFLDS){ warn("too few fields in file header"); continue; } p = unquotestrdup(fields[0]); strcpy(namep, p); free(p); mode = strtoul(fields[1], 0, 8); uid = fields[2]; gid = fields[3]; mtime = strtoul(fields[4], 0, 10); bytes = strtoull(fields[5], 0, 10); if(argc){ if(!selected(namep, argc, argv)){ if(bytes) seekpast(bytes); continue; } mkdirs(name, namep); } if(hflag){ Bprint(&bout, "%q %luo %q %q %lu %llu\n", name, mode, uid, gid, mtime, bytes); if(bytes) seekpast(bytes); continue; } if(mode & DMDIR) mkdir(name, mode, mtime, uid, gid); else extract(name, mode, mtime, uid, gid, bytes); } fprint(2, "premature end of archive\n"); exits("premature end of archive"); }
/* * Evaluate the ## operators in a tokenrow */ void doconcat(Tokenrow * trp) { Token *ltp, *ntp; Tokenrow ntr; size_t len; for (trp->tp = trp->bp; trp->tp < trp->lp; trp->tp++) { if (trp->tp->type == DSHARP1) trp->tp->type = DSHARP; else if (trp->tp->type == DSHARP) { int i; char tt[NCONCAT]; ltp = trp->tp - 1; ntp = trp->tp + 1; if (ltp < trp->bp || ntp >= trp->lp) { error(ERROR, "## occurs at border of replacement"); continue; } ntp = ltp; i = 1; len = 0; do { if (len + ntp->len + ntp->wslen > sizeof(tt)) { error(ERROR, "## string concatination buffer overrun"); break; } if (ntp != trp->tp + 1) { strncpy((char *) tt + len, (char *) ntp->t - ntp->wslen, ntp->len + ntp->wslen); len += ntp->len + ntp->wslen; } else // Leerzeichen um ## herum entfernen: { strncpy((char *) tt + len, (char *) ntp->t, ntp->len); len += ntp->len; } ntp = trp->tp + i; i++; } while (ntp < trp->lp); tt[len] = '\0'; setsource("<##>", -1, -1, tt, 0); maketokenrow(3, &ntr); gettokens(&ntr, 1); unsetsource(); if (ntr.bp->type == UNCLASS) error(WARNING, "Bad token %r produced by ##", &ntr); while ((ntr.lp-1)->len == 0 && ntr.lp != ntr.bp) ntr.lp--; doconcat(&ntr); trp->tp = ltp; makespace(&ntr, ltp); insertrow(trp, (int)(ntp - ltp), &ntr); dofree(ntr.bp); trp->tp--; } } }
BOOL GenerateRules() { char **tokens, rule[256]; int num_tokens,j, i; KeyVal *opt_head, *opt_cptr, *opt_pptr; RuleNode *new_rule, **node_ptr, *node; RulesHead *rules_head; BOOL bError; var_list = NULL; for (j = 0; j < 256; j++) { if (rule_text[j].rule[0] == '\0') break; if (rule_text[j].bEnabled == FALSE) continue; bError = FALSE; lstrcpy(rule, rule_text[j].rule); tokens = gettokens(rule, &num_tokens); // Add variables to the Variable linked list if (!lstrcmp(tokens[0], "var")) { tokens[2][lstrlen(tokens[2])-1] = '\0'; // get rid of the semicolon AddToVarList(tokens[1], tokens[2]); continue; } /* replace any variable with its actual value */ for (i = 0; i < num_tokens; i++) { debug(tokens[i]); debug(" "); if (tokens[i][0] == '$') tokens[i] = getValue(tokens[i]); if (tokens[i] == NULL) // this variable has not been defined { bError = TRUE; break; } } // if there was an error, don't add this rule to chain if (bError) { debug(" << ERROR >> \r\n"); continue; } debug("\r\n"); if (!lstrcmp(tokens[0], "alert")) rules_head = &root.alert; else if (!lstrcmp(tokens[0], "log")) rules_head = &root.log; else if (!lstrcmp(tokens[0], "counter")) rules_head = &root.counter; else continue; if (!lstrcmp(tokens[1], "icmp")) node_ptr = &rules_head->IcmpList; else if (!lstrcmp(tokens[1], "udp")) node_ptr = &rules_head->UdpList; else if (!lstrcmp(tokens[1], "tcp")) node_ptr = &rules_head->TcpList; else if (!lstrcmp(tokens[1], "arp")) node_ptr = &rules_head->ArpList; else continue; new_rule = (RuleNode *) malloc(sizeof(RuleNode)); memset(new_rule, 0, sizeof(RuleNode)); new_rule->sip_op = getIPop(tokens[2]); new_rule->sip = getIP(tokens[2]); new_rule->smask = getMask(tokens[2]); new_rule->dip_op = getIPop(tokens[5]); new_rule->dip = getIP(tokens[5]); new_rule->dmask = getMask(tokens[5]); new_rule->lsp = getPortMin(tokens[3]); new_rule->hsp = getPortMax(tokens[3]); new_rule->ldp = getPortMin(tokens[6]); new_rule->hdp = getPortMax(tokens[6]); if (tokens[4][0] == '<') // is '<>' new_rule->dir = BI_DIR; else // is '->' new_rule->dir = UNI_DIR; opt_head = getOptionList(tokens[7]); PopulateOptions( new_rule, opt_head); DumpRule(new_rule); /* Add the rule to the appropriate linked list (icmp, tcp or udp) */ if (*node_ptr == NULL) *node_ptr = new_rule; else { node = *node_ptr; while (node->next != NULL) node = node->next; node->next = new_rule; } /* delete the keyword/value list (no longer needed) */ opt_cptr = opt_head; while (opt_cptr != NULL) { opt_pptr = opt_cptr; opt_cptr= opt_cptr->next; free(opt_pptr); } free(tokens); debug("done generating this rule\r\n"); } /* free up memory allocated for variables */ while (var_list != NULL) { free(var_list->keyword); free(var_list->value); opt_pptr = var_list; var_list = var_list->next; free(opt_pptr); } return TRUE; }
/* * loadservers - load list of NTP servers from configuration file */ void loadservers( char *cfgpath ) { register int i; int errflg; int peerversion; int minpoll; int maxpoll; /* int ttl; */ int srvcnt; /* u_long peerkey; */ int peerflags; struct sockaddr_in peeraddr; FILE *fp; char line[MAXLINE]; char *(tokens[MAXTOKENS]); int ntokens; int tok; const char *config_file; #ifdef SYS_WINNT char *alt_config_file; LPTSTR temp; char config_file_storage[MAX_PATH]; char alt_config_file_storage[MAX_PATH]; #endif /* SYS_WINNT */ struct server *server, *srvlist; /* * Initialize, initialize */ srvcnt = 0; srvlist = 0; errflg = 0; #ifdef DEBUG debug = 0; #endif /* DEBUG */ #ifndef SYS_WINNT config_file = cfgpath ? cfgpath : CONFIG_FILE; #else if (cfgpath) { config_file = cfgpath; } else { temp = CONFIG_FILE; if (!ExpandEnvironmentStrings((LPCTSTR)temp, (LPTSTR)config_file_storage, (DWORD)sizeof(config_file_storage))) { msyslog(LOG_ERR, "ExpandEnvironmentStrings CONFIG_FILE failed: %m\n"); exit(1); } config_file = config_file_storage; } temp = ALT_CONFIG_FILE; if (!ExpandEnvironmentStrings((LPCTSTR)temp, (LPTSTR)alt_config_file_storage, (DWORD)sizeof(alt_config_file_storage))) { msyslog(LOG_ERR, "ExpandEnvironmentStrings ALT_CONFIG_FILE failed: %m\n"); exit(1); } alt_config_file = alt_config_file_storage; M #endif /* SYS_WINNT */ if ((fp = fopen(FindConfig(config_file), "r")) == NULL) { fprintf(stderr, "getconfig: Couldn't open <%s>\n", FindConfig(config_file)); msyslog(LOG_INFO, "getconfig: Couldn't open <%s>", FindConfig(config_file)); #ifdef SYS_WINNT /* Under WinNT try alternate_config_file name, first NTP.CONF, then NTP.INI */ if ((fp = fopen(FindConfig(alt_config_file), "r")) == NULL) { /* * Broadcast clients can sometimes run without * a configuration file. */ fprintf(stderr, "getconfig: Couldn't open <%s>\n", FindConfig(alt_config_file)); msyslog(LOG_INFO, "getconfig: Couldn't open <%s>", FindConfig(alt_config_file)); return; } #else /* not SYS_WINNT */ return; #endif /* not SYS_WINNT */ } while ((tok = gettokens(fp, line, tokens, &ntokens)) != CONFIG_UNKNOWN) { switch(tok) { case CONFIG_PEER: case CONFIG_SERVER: if (ntokens < 2) { msyslog(LOG_ERR, "No address for %s, line ignored", tokens[0]); break; } if (!getnetnum(tokens[1], &peeraddr, 1)) { /* Resolve now, or lose! */ break; } else { errflg = 0; /* Shouldn't be able to specify multicast */ if (IN_CLASSD(ntohl(peeraddr.sin_addr.s_addr)) || ISBADADR(&peeraddr)) { msyslog(LOG_ERR, "attempt to configure invalid address %s", ntoa(&peeraddr)); break; } } peerversion = NTP_VERSION; minpoll = NTP_MINDPOLL; maxpoll = NTP_MAXDPOLL; /* peerkey = 0; */ peerflags = 0; /* ttl = 0; */ for (i = 2; i < ntokens; i++) switch (matchkey(tokens[i], mod_keywords)) { case CONF_MOD_VERSION: if (i >= ntokens-1) { msyslog(LOG_ERR, "peer/server version requires an argument"); errflg = 1; break; } peerversion = atoi(tokens[++i]); if ((u_char)peerversion > NTP_VERSION || (u_char)peerversion < NTP_OLDVERSION) { msyslog(LOG_ERR, "inappropriate version number %s, line ignored", tokens[i]); errflg = 1; } break; case CONF_MOD_KEY: if (i >= ntokens-1) { msyslog(LOG_ERR, "key: argument required"); errflg = 1; break; } ++i; /* peerkey = (int)atol(tokens[i]); */ peerflags |= FLAG_AUTHENABLE; break; case CONF_MOD_MINPOLL: if (i >= ntokens-1) { msyslog(LOG_ERR, "minpoll: argument required"); errflg = 1; break; } minpoll = atoi(tokens[++i]); if (minpoll < NTP_MINPOLL) minpoll = NTP_MINPOLL; break; case CONF_MOD_MAXPOLL: if (i >= ntokens-1) { msyslog(LOG_ERR, "maxpoll: argument required" ); errflg = 1; break; } maxpoll = atoi(tokens[++i]); if (maxpoll > NTP_MAXPOLL) maxpoll = NTP_MAXPOLL; break; case CONF_MOD_PREFER: peerflags |= FLAG_PREFER; break; case CONF_MOD_BURST: peerflags |= FLAG_BURST; break; case CONF_MOD_SKEY: peerflags |= FLAG_SKEY | FLAG_AUTHENABLE; break; case CONF_MOD_TTL: if (i >= ntokens-1) { msyslog(LOG_ERR, "ttl: argument required"); errflg = 1; break; } ++i; /* ttl = atoi(tokens[i]); */ break; case CONF_MOD_MODE: if (i >= ntokens-1) { msyslog(LOG_ERR, "mode: argument required"); errflg = 1; break; } ++i; /* ttl = atoi(tokens[i]); */ break; case CONFIG_UNKNOWN: errflg = 1; break; } if (minpoll > maxpoll) { msyslog(LOG_ERR, "config error: minpoll > maxpoll"); errflg = 1; } if (errflg == 0) { server = (struct server *)emalloc(sizeof(struct server)); memset((char *)server, 0, sizeof(struct server)); server->srcadr = peeraddr; server->version = peerversion; server->dispersion = PEER_MAXDISP; server->next_server = srvlist; srvlist = server; srvcnt++; } break; case CONFIG_KEYS: if (ntokens >= 2) { key_file = (char *) emalloc(strlen(tokens[1]) + 1); strcpy(key_file, tokens[1]); } break; } } (void) fclose(fp); /* build final list */ sys_numservers = srvcnt; sys_servers = (struct server **) emalloc(sys_numservers * sizeof(struct server *)); for(i=0;i<sys_numservers;i++) { sys_servers[i] = srvlist; srvlist = srvlist->next_server; } }