/* this is the command execution machine */ int Parser_commands(void) { char *line, *s; int rc = 0, save_error = 0; int interactive; interactive = init_input(); while(!done) { line = readline(interactive ? parser_prompt : NULL); if (!line) break; s = skipwhitespace(line); if (*s) { add_history(s); rc = execute_line(s); } /* stop on error if not-interactive */ if (rc != 0 && !interactive) { if (save_error == 0) save_error = rc; if (!ignore_errors) done = 1; } free(line); } if (save_error) rc = save_error; return rc; }
/* this is the command execution machine */ void Parser_commands(void) { char *line, *s; using_history(); stifle_history(HISTORY); rl_attempted_completion_function = command_completion; rl_completion_entry_function = &command_generator; while(!done) { line = readline(parser_prompt); if (!line) break; s = skipwhitespace(line); if (*s) { add_history(s); execute_line(s); } free(line); } }
/* apparently, strtol() does not work correctly on very large hexadecimal values */ SC_FUNC ucell hex2ucell(const char *s,const char **n) { ucell result=0L; int negate=FALSE; int digit; /* ignore leading whitespace */ s=skipwhitespace(s); assert(*s!='\0'); /* allow a negation sign to create the two's complement of numbers */ if (*s=='-') { negate=TRUE; s++; } /* if */ assert((*s>='0' && *s<='9') || (*s>='a' && *s<='f') || (*s>='a' && *s<='f')); for ( ;; ) { if (*s>='0' && *s<='9') digit=*s-'0'; else if (*s>='a' && *s<='f') digit=*s-'a' + 10; else if (*s>='A' && *s<='F') digit=*s-'A' + 10; else break; /* probably whitespace */ result=(result<<4) | digit; s++; } /* for */ if (n!=NULL) *n=(char*)s; if (negate) result=(~result)+1; /* take two's complement of the result */ return (ucell)result; }
void getnamelink(char *l, char **name, char **link) { /* "page NAME title-or-link" splitup */ char *p; dbgprintf("getnamelink(%s, ...)\n", textornull(l)); *name = null_text; *link = null_text; /* Skip page/subpage keyword, and whitespace after that */ p = skipwhitespace(skipword(l)); *name = p; p = skipword(p); if (*p) { *p = '\0'; /* Null-terminate pagename */ p++; *link = skipwhitespace(p); } }
void getgrouptitle(char *l, char *pageset, char **title, char **onlycols, char **exceptcols) { char grouponlytag[100], groupexcepttag[100], grouptag[100]; *title = null_text; *onlycols = NULL; *exceptcols = NULL; sprintf(grouponlytag, "%sgroup-only", pageset); sprintf(groupexcepttag, "%sgroup-except", pageset); sprintf(grouptag, "%sgroup", pageset); dbgprintf("getgrouptitle(%s, ...)\n", textornull(l)); if (strncmp(l, grouponlytag, strlen(grouponlytag)) == 0) { char *p; *onlycols = skipwhitespace(skipword(l)); p = skipword(*onlycols); if (*p) { *p = '\0'; p++; *title = skipwhitespace(p); } } else if (strncmp(l, groupexcepttag, strlen(groupexcepttag)) == 0) { char *p; *exceptcols = skipwhitespace(skipword(l)); p = skipword(*exceptcols); if (*p) { *p = '\0'; p++; *title = skipwhitespace(p); } } else if (strncmp(l, grouptag, strlen(grouptag)) == 0) { *title = skipwhitespace(skipword(l)); } }
int countwords(char *buf, int bufsize) { int count; char *p; count=0; for(p=buf;;) { if(!(p=skipwhitespace(p,buf,bufsize))) break; count++; if(!(p=skipword(p,buf,bufsize))) break; } return count; }
void getparentnamelink(char *l, xymongen_page_t *toppage, xymongen_page_t **parent, char **name, char **link) { /* "subparent NAME PARENTNAME title-or-link" splitup */ char *p; char *parentname; xymonpagelist_t *walk; dbgprintf("getnamelink(%s, ...)\n", textornull(l)); *name = null_text; *link = null_text; /* Skip page/subpage keyword, and whitespace after that */ parentname = p = skipwhitespace(skipword(l)); p = skipword(p); if (*p) { *p = '\0'; /* Null-terminate pagename */ p++; *name = p = skipwhitespace(p); p = skipword(p); if (*p) { *p = '\0'; /* Null-terminate parentname */ p++; *link = skipwhitespace(p); } } for (walk = pagelisthead; (walk && (strcmp(walk->pageentry->name, parentname) != 0)); walk = walk->next) ; if (walk) { *parent = walk->pageentry; } else { errprintf("Cannot find parent page '%s'\n", parentname); *parent = NULL; } }
/* returns the command_t * (NULL if not found) corresponding to a _partial_ match with the first token in name. It sets *next to point to the following token. Does not modify *name. */ static command_t * find_cmd(char * name, command_t cmds[], char ** next) { int i, len; if (!cmds || !name ) return NULL; /* This sets name to point to the first non-white space character, and next to the first whitespace after name, len to the length: do this with strtok*/ name = skipwhitespace(name); *next = skiptowhitespace(name); len = (int)(*next - name); if (len == 0) return NULL; for (i = 0; cmds[i].pc_name; i++) { if (strncasecmp(name, cmds[i].pc_name, len) == 0) { *next = skipwhitespace(*next); return(&cmds[i]); } } return NULL; }
char * getParam(char *arg,char *argv[],int *iPtr) { while ( *arg == '-' || *arg == '/' || *arg == '=' ) { arg++; arg = skipwhitespace(arg); if ( ! *arg ) { (*iPtr) ++; arg = argv[*iPtr]; if ( ! arg ) return NULL; } } return arg; }
int parseformat( char *name) { #define kDupmatch -2 int namelen, maxlen, i, match, matchat; char lname[kMaxFormName+1]; skipwhitespace(name); namelen = strlen(name); if (namelen == 0) return kNoformat; else if (isdigit((int) *name)) { i = atol( name); /*if (i < kMinFormat | i > kMaxFormat) return kNoformat;*/ if (i < kMinFormat || i > kMaxFormat) return kNoformat; else return i; } /* else match character name */ maxlen = min( kMaxFormName, namelen); for (i=0; i<maxlen; i++) lname[i] = to_lower(name[i]); lname[maxlen]=0; matchat = kNoformat; for (i=0; i<kFormCount; i++) { match = strncmp( lname, formname[i].name, maxlen); if (match == 0) { if ((int) strlen(formname[i].name) == namelen) return (formname[i].num); else if (matchat == kNoformat) matchat = i; else matchat = kDupmatch; /* 2 or more partial matches */ } } if (matchat == kNoformat || matchat == kDupmatch) return kNoformat; else return formname[matchat].num; }
extern int main( int argc, char *argv[]) #endif { boolean closein = false; short ifile, format, err = 0, seqtype = kDNA, nlines=0, seqout = 0, phylvers = 2; long atseq, nseq, i, skiplines, seqlen, seqlen0=0; /* changed atseq and nseq from short to long - James J (UQ) */ unsigned long checksum= 0, checkall= 0; char *seq=NULL, *cp=NULL, *firstseq = NULL, *seqlist=NULL, *progname; /*char tempname[] = "readseqXXXXXX";*/ char *tempname = NULL; char seqid[MAXLINE], *seqidptr = seqid; char stempstore[256], *stemp = stempstore; FILE *ftmp=NULL, *fin=NULL, *fout=NULL; long outindexmax= 0, noutindex= 0, *outindex = NULL; #define exit_main(err) { \ if (closeout) fclose(fout); \ if (closein) fclose(fin); \ if (tempname != NULL) remove(tempname); \ Exit(err); } #define indexout() if (interleaved) {\ if (noutindex>=outindexmax) {\ outindexmax= noutindex + 20;\ outindex= (long*) realloc(outindex, sizeof(long)*outindexmax);\ if (outindex==NULL) { err= eMemFull; erralert(err); exit_main(err); }\ }\ outindex[noutindex++]= ftell(fout);\ } resetGlobals(); foo = stdout; progname = argv[0]; *oname = 0; /* initialize gPretty ?? -- done in header */ for (i=1; i < argc; i++) { err= readopt( argv[i]); if (err <= 0) exit_main(err); } /* pipe input from stdin !? */ if (dopipe && !gotinputfile) { int c; int fd; /* tmpnam(tempname); inputfile = tempname; ftmp = fopen( inputfile, "w"); */ tempname = strdup("readseqXXXXXX"); fd = mkstemp(tempname); if (fd == -1) { erralert(eFileCreate); exit_main(eFileCreate); } strcpy(inputfile, tempname); while ((c = getc(stdin)) != EOF) write(fd, &c, 1); close(fd); gotinputfile= true; } quietly = (dopipe || (gotinputfile && (listonly || whichSeq != 0))); if (verbose || (!quietly && !gotinputfile)) fprintf( stderr, "%s", title); ifile = 1; /* UI: Choose output */ if (askout && !closeout && !quietly) { askout = false; fprintf(stderr,"\nName of output file (?=help, defaults to display): \n"); fgets(oname= onamestore, 128, stdin); skipwhitespace(oname); if (*oname == '?') { usage(); exit_main(0); } else if (*oname != 0) { closeout = true; foo = fopen( oname, "w"); if (!foo) { erralert(eFileCreate); exit_main(eFileCreate); } } } fout = foo; if (outform == kNoformat) outform = chooseFormat(quietly); /* set up formats ... */ switch ((int) outform) { case kPhylip2: interleaved= false; phylvers = 2; outform = kPhylip; break; case kPhylip4: interleaved= true; phylvers = 4; outform = kPhylip; break; case kMSF: case kPAUP: interleaved= true; break; case kPretty: gPretty.isactive= true; interleaved= true; break; } if (gPretty.isactive && gPretty.noleaves) interleaved= false; if (interleaved) { fout = ftmp = tmpfile(); outindexmax= 30; noutindex= 0; outindex = (long*) malloc(outindexmax*sizeof(long)); if (outindex==NULL) { err= eMemFull; erralert(err); exit_main(err); } } /* big loop over all input files */ do { /* select next input file */ /*gotinputfile = (*tempname != 0);*/ gotinputfile = (tempname != NULL); while ((ifile < argc) && (!gotinputfile)) { if (*argv[ifile] != '-') { strcpy( inputfile, argv[ifile]); gotinputfile = (*inputfile != 0); --nfile; } ifile++; } while (!gotinputfile) { fprintf(stderr,"\nName an input sequence or -option: \n"); inputfile= inputfilestore; fgets(stemp= stempstore, 256, stdin); if (*stemp==0) goto fini; /* !! need this to finish work during interactive use */ stemp= strtok(stempstore, " \n\r\t"); while (stemp) { err= readopt( stemp); /* will read inputfile if it exists */ if (err<0) exit_main(err); stemp= strtok( NULL, " \n\r\t"); } } /* thanks to [email protected] for this PHYLIP3 fix: */ /* head for end (interleave if needed) */ if (*inputfile == 0) break; format = seqFileFormat( inputfile, &skiplines, &err); if (err == 0) { #ifdef NCBI if (format == kASNseqentry || format == kASNseqset) seqlist = listASNSeqs( inputfile, skiplines, format, &nseq, &err); else #endif seqlist = listSeqs( inputfile, skiplines, format, &nseq, &err); } if (err != 0) erralert(err); else if (listonly) { dumpSeqList(seqlist,format); free( seqlist); } else { /* choose whichSeq if needed */ if (nseq == 1 || chooseall || (quietly && whichSeq == 0)) { chooseall= true; whichSeq = 1; quietly = true; /* no loop */ } else if (whichSeq > nseq && quietly) { erralert(eItemNotFound); err= eItemNotFound; } else if (whichSeq > nseq || !quietly) { dumpSeqList(seqlist, format); fprintf(stderr,"\nChoose a sequence (# or All): \n"); fgets(stemp= stempstore, 256, stdin); skipwhitespace(stemp); if (to_lower(*stemp) == 'a') { chooseall= true; whichSeq = 1; quietly = true; /* !? this means we don't ask for another file as well as no more whichSeqs... */ } else if (isdigit((int) *stemp)) whichSeq= atol(stemp); else whichSeq= 1; /* default */ } free( seqlist); if (false /*chooseall*/) { /* this isn't debugged yet...*/ fin = fopen(inputfile, "r"); closein= true; } while (whichSeq > 0 && whichSeq <= nseq) { /* need to open multiple output files ? */ manyout = ((chooseall || nwhichlist>1) && nseq > 1 && (outform == kPlain || outform == kGCG)); if (manyout) { if ( whichSeq == 1 ) erralert(eOneFormat); else if (closeout) { sprintf( stemp,"%s_%ld", oname, whichSeq); freopen( stemp, "w", fout); fprintf( stderr,"Writing sequence %ld to file %s\n", whichSeq, stemp); } } if (closein) { /* !! this fails... skips most seqs... */ /* !! in sequential read, must count seqs already read from whichSeq ... */ /* need major revision of ureadseq before we can do this */ atseq= whichSeq-1; seqidptr= seqid; seq = readSeqFp( whichSeq, fin, skiplines, format, &seqlen, &atseq, &err, seqidptr); skiplines= 0; } else { atseq= 0; seqidptr= seqid; #ifdef NCBI if (format == kASNseqentry || format == kASNseqset) { seqidptr= NULL; seq = readASNSeq( whichSeq, inputfile, skiplines, format, &seqlen, &atseq, &err, &seqidptr); } else #endif seq = readSeq( whichSeq, inputfile, skiplines, format, &seqlen, &atseq, &err, seqidptr); } if (gPretty.degap) { char *newseq; long newlen; newseq= compressSeq( gPretty.gapchar, seq, seqlen, &newlen); if (newseq) { free(seq); seq= newseq; seqlen= newlen; } } if (outform == kMSF) checksum= GCGchecksum(seq, seqlen, &checkall); else if (verbose) checksum= seqchecksum(seq, seqlen, &checkall); if (verbose) fprintf( stderr, "Sequence %ld, length= %ld, checksum= %X, format= %s, id= %s\n", whichSeq, seqlen, (int)checksum, formatstr(format), seqidptr); if (err != 0) erralert(err); else { /* format fixes that writeseq doesn't do */ switch ((int) outform) { case kPIR: if (seqout == 0) fprintf( foo,"\\\\\\\n"); break; case kASN1: if (seqout == 0) fprintf( foo, "%s", kASN1headline); break; case kPhylip: if (seqout == 0) { if (!interleaved) { /* bug, nseq is for 1st infile only */ if (chooseall) i= nseq; else i=1; if (phylvers >= 4) fprintf(foo," %ld %ld\n", i, seqlen); else fprintf(foo," %ld %ld YF\n", i, seqlen); } seqlen0 = seqlen; } else if (seqlen != seqlen0) { erralert(eUnequalSize); if (seqlen < seqlen0) seq = (char *)realloc(seq, seqlen0); for (i=seqlen; i<seqlen0; i++) seq[i]= gPretty.gapchar; seqlen = seqlen0; seq[seqlen] = 0; } break; case kPAUP: if (seqout == 0) { seqtype= getseqtype(seq, seqlen); seqlen0 = seqlen; } else if (seqlen != seqlen0) { erralert(eUnequalSize); if (seqlen < seqlen0) seq = (char *)realloc(seq, seqlen0); for (i=seqlen; i<seqlen0; i++) seq[i]= gPretty.gapchar; seqlen = seqlen0; seq[seqlen] = 0; } break; } if (doupper) for (i = 0; i<seqlen; i++) seq[i] = to_upper(seq[i]); else if (dolower) for (i = 0; i<seqlen; i++) seq[i] = to_lower(seq[i]); if (doreverse) { long j, k; char ctemp; for (j=0, k=seqlen-1; j <= k; j++, k--) { ctemp = compl[seq[j] - ' ']; seq[j] = compl[seq[k] - ' ']; seq[k] = ctemp; } } if ((gPretty.isactive || outform==kPAUP) && gPretty.domatch && firstseq != NULL) { for (i=0; i<seqlen; i++) if (seq[i]==firstseq[i]) seq[i]= gPretty.matchchar; } if (gPretty.isactive && gPretty.numtop && seqout == 0) { gPretty.numline = 1; indexout(); (void) writeSeq( fout, seq, seqlen, outform, seqidptr); gPretty.numline = 2; indexout(); (void) writeSeq( fout, seq, seqlen, outform, seqidptr); gPretty.numline = 0; } indexout(); nlines = writeSeq( fout, seq, seqlen, outform, seqidptr); seqout++; } if ((gPretty.isactive || outform==kPAUP) && gPretty.domatch && firstseq == NULL) { firstseq= seq; seq = NULL; } else if (seq!=NULL) { free(seq); seq = NULL; } #ifdef NCBI if ( (format == kASNseqentry || format == kASNseqset) && seqidptr && seqidptr!= seqid) free(seqidptr); #endif if (chooseall) whichSeq++; else if (iwhichlist<nwhichlist) whichSeq= whichlist[iwhichlist++]; else whichSeq= 0; } if (closein) { fclose(fin); closein= false; } } whichSeq = 0; } while (nfile > 0 || !quietly); fini: if (firstseq) { free(firstseq); firstseq= NULL; } if (err || listonly) exit_main(err); if (gPretty.isactive && gPretty.numbot) { gPretty.numline = 2; indexout(); (void) writeSeq( fout, seq, seqlen, outform, seqidptr); gPretty.numline = 1; indexout(); (void) writeSeq( fout, seq, seqlen, outform, seqidptr); gPretty.numline = 0; } if (outform == kMSF) { if (*oname) cp= oname; else cp= inputfile; fprintf(foo, "\n %s MSF: %ld Type: N January 01, 1776 12:00 Check: %ld ..\n\n", cp, seqlen, checkall); } if (outform == kPAUP) { fprintf(foo,"#NEXUS\n"); if (*oname) cp= oname; else cp= inputfile; fprintf(foo,"[%s -- data title]\n\n", cp); /* ! now have header lines for each sequence... put them before "begin data;... */ } if (outform==kPhylip && interleaved) { if (phylvers >= 4) fprintf(foo," %d %ld\n", seqout, seqlen); else fprintf(foo," %d %ld YF\n", seqout, seqlen); } if (interleaved) { /* interleave species lines in true output */ /* nlines is # lines / sequence */ short iline, j, leaf, iseq; char *s = stempstore; indexout(); noutindex--; /* mark eof */ for (leaf=0; leaf<nlines; leaf++) { if (outform == kMSF && leaf == 1) { fputs("//\n\n", foo); } if (outform == kPAUP && leaf==1) { switch (seqtype) { case kDNA : cp= "dna"; break; case kRNA : cp= "rna"; break; case kNucleic : cp= "dna"; break; case kAmino : cp= "protein"; break; case kOtherSeq: cp= "dna"; break; } fprintf(foo,"\nbegin data;\n"); fprintf(foo," dimensions ntax=%d nchar=%ld;\n", seqout, seqlen); fprintf(foo," format datatype=%s interleave missing=%c", cp, gPretty.gapchar); if (gPretty.domatch) fprintf(foo," matchchar=%c", gPretty.matchchar); fprintf(foo,";\n matrix\n"); } for (iseq=0; iseq<noutindex; iseq++) { fseek(ftmp, outindex[iseq], 0); for (iline=0; iline<=leaf; iline++) if (!fgets(s, 256, ftmp)) *s= 0; if (ftell(ftmp) <= outindex[iseq+1]) fputs( s, foo); } for (j=0; j<gPretty.interline; j++) fputs( "\n", foo); /* some want spacer line */ } fclose(ftmp); /* tmp disappears */ fout= foo; } if (outform == kASN1) fprintf( foo, "} }\n"); if (outform == kPAUP) fprintf( foo,";\n end;\n"); if (outindex != NULL) free(outindex); exit_main(0); }
char *init_tcp_services(void) { static char *xymonnetsvcs = NULL; static time_t lastupdate = 0; char filename[PATH_MAX]; struct stat st; FILE *fd = NULL; strbuffer_t *inbuf; svclist_t *head, *tail, *first, *walk; char *searchstring; int svcnamebytes = 0; int svccount = 0; int i; MEMDEFINE(filename); filename[0] = '\0'; if (xgetenv("XYMONHOME")) { sprintf(filename, "%s/etc/", xgetenv("XYMONHOME")); } strcat(filename, "protocols.cfg"); if ((stat(filename, &st) == 0) && xymonnetsvcs) { /* See if we have already run and the file is unchanged - if so just pickup the result */ if (st.st_mtime == lastupdate) return xymonnetsvcs; /* File has changed - reload configuration. But clean up first so we dont leak memory. */ if (svcinfo != default_svcinfo) { for (i=0; (svcinfo[i].svcname); i++) { if (svcinfo[i].svcname) xfree(svcinfo[i].svcname); if (svcinfo[i].sendtxt) xfree(svcinfo[i].sendtxt); if (svcinfo[i].exptext) xfree(svcinfo[i].exptext); } xfree(svcinfo); svcinfo = default_svcinfo; } xfree(xymonnetsvcs); xymonnetsvcs = NULL; } if (xgetenv("XYMONNETSVCS") == NULL) { putenv("XYMONNETSVCS=smtp telnet ftp pop pop3 pop-3 ssh imap ssh1 ssh2 imap2 imap3 imap4 pop2 pop-2 nntp"); } fd = fopen(filename, "r"); if (fd == NULL) { errprintf("Cannot open TCP service-definitions file %s - using defaults\n", filename); xymonnetsvcs = strdup(xgetenv("XYMONNETSVCS")); MEMUNDEFINE(filename); return xymonnetsvcs; } lastupdate = st.st_mtime; head = tail = first = NULL; inbuf = newstrbuffer(0); initfgets(fd); while (unlimfgets(inbuf, fd)) { char *l, *eol; sanitize_input(inbuf, 1, 0); l = STRBUF(inbuf); if (*l == '[') { char *svcname; eol = strchr(l, ']'); if (eol) *eol = '\0'; l = skipwhitespace(l+1); svcname = strtok(l, "|"); first = NULL; while (svcname) { svclist_t *newitem; svccount++; svcnamebytes += (strlen(svcname) + 1); newitem = (svclist_t *) malloc(sizeof(svclist_t)); newitem->rec = (svcinfo_t *)calloc(1, sizeof(svcinfo_t)); newitem->rec->svcname = strdup(svcname); newitem->next = NULL; if (first == NULL) first = newitem; if (head == NULL) { head = tail = newitem; } else { tail->next = newitem; tail = newitem; } svcname = strtok(NULL, "|"); } } else if (strncmp(l, "send ", 5) == 0) { if (first) { getescapestring(skipwhitespace(l+4), &first->rec->sendtxt, &first->rec->sendlen); for (walk = first->next; (walk); walk = walk->next) { walk->rec->sendtxt = strdup(first->rec->sendtxt); walk->rec->sendlen = first->rec->sendlen; } } } else if (strncmp(l, "expect ", 7) == 0) { if (first) { getescapestring(skipwhitespace(l+6), &first->rec->exptext, &first->rec->explen); for (walk = first->next; (walk); walk = walk->next) { walk->rec->exptext = strdup(first->rec->exptext); walk->rec->explen = first->rec->explen; walk->rec->expofs = 0; /* HACK - not used right now */ } } } else if (strncmp(l, "options ", 8) == 0) { if (first) { char *opt; first->rec->flags = 0; l = skipwhitespace(l+7); opt = strtok(l, ","); while (opt) { if (strcmp(opt, "ssl") == 0) first->rec->flags |= TCP_SSL; else if (strcmp(opt, "banner") == 0) first->rec->flags |= TCP_GET_BANNER; else if (strcmp(opt, "telnet") == 0) first->rec->flags |= TCP_TELNET; else errprintf("Unknown option: %s\n", opt); opt = strtok(NULL, ","); } for (walk = first->next; (walk); walk = walk->next) { walk->rec->flags = first->rec->flags; } } } else if (strncmp(l, "port ", 5) == 0) { if (first) { first->rec->port = atoi(skipwhitespace(l+4)); for (walk = first->next; (walk); walk = walk->next) { walk->rec->port = first->rec->port; } } } } if (fd) fclose(fd); freestrbuffer(inbuf); /* Copy from the svclist to svcinfo table */ svcinfo = (svcinfo_t *) malloc((svccount+1) * sizeof(svcinfo_t)); for (walk=head, i=0; (walk && (i < svccount)); walk = walk->next, i++) { svcinfo[i].svcname = walk->rec->svcname; svcinfo[i].sendtxt = walk->rec->sendtxt; svcinfo[i].sendlen = walk->rec->sendlen; svcinfo[i].exptext = walk->rec->exptext; svcinfo[i].explen = walk->rec->explen; svcinfo[i].expofs = walk->rec->expofs; svcinfo[i].flags = walk->rec->flags; svcinfo[i].port = walk->rec->port; } memset(&svcinfo[svccount], 0, sizeof(svcinfo_t)); /* This should not happen */ if (walk) { errprintf("Whoa - didnt copy all services! svccount=%d, next service '%s'\n", svccount, walk->rec->svcname); } /* Free the temp. svclist list */ while (head) { /* * Note: Dont free the strings inside the records, * as they are now owned by the svcinfo records. */ walk = head; head = head->next; xfree(walk); } searchstring = strdup(xgetenv("XYMONNETSVCS")); xymonnetsvcs = (char *) malloc(strlen(xgetenv("XYMONNETSVCS")) + svcnamebytes + 1); strcpy(xymonnetsvcs, xgetenv("XYMONNETSVCS")); for (i=0; (svcinfo[i].svcname); i++) { char *p; strcpy(searchstring, xgetenv("XYMONNETSVCS")); p = strtok(searchstring, " "); while (p && (strcmp(p, svcinfo[i].svcname) != 0)) p = strtok(NULL, " "); if (p == NULL) { strcat(xymonnetsvcs, " "); strcat(xymonnetsvcs, svcinfo[i].svcname); } } xfree(searchstring); if (debug) { dump_tcp_services(); dbgprintf("XYMONNETSVCS set to : %s\n", xymonnetsvcs); } MEMUNDEFINE(filename); return xymonnetsvcs; }
SC_FUNC int assemble(FILE *fout,FILE *fin) { AMX_HEADER hdr; AMX_FUNCSTUB func; int numpublics,numnatives,numoverlays,numlibraries,numpubvars,numtags; int padding; long nametablesize,nameofs; char line[512]; char *instr,*params; int i,pass,size; int16_t count; symbol *sym; symbol **nativelist; constvalue *constptr; cell mainaddr; char nullchar; #if !defined NDEBUG /* verify that the opcode list is sorted (skip entry 1; it is reserved * for a non-existant opcode) */ { #define MAX_OPCODE 176 unsigned char opcodearray[MAX_OPCODE+1]; assert(opcodelist[1].name!=NULL); memset(opcodearray,0,sizeof opcodearray); for (i=2; i<(sizeof opcodelist / sizeof opcodelist[0]); i++) { assert(opcodelist[i].name!=NULL); assert(stricmp(opcodelist[i].name,opcodelist[i-1].name)>0); /* also verify that no opcode number appears twice */ assert((int)opcodelist[i].opcode<=MAX_OPCODE); assert(opcodelist[i].opcode==0 || opcodearray[(int)opcodelist[i].opcode]==0); opcodearray[(int)opcodelist[i].opcode] += 1; } /* for */ } #endif writeerror=FALSE; nametablesize=sizeof(int16_t); numpublics=0; numnatives=0; numpubvars=0; numoverlays=0; mainaddr=-1; /* count number of public and native functions and public variables */ for (sym=glbtab.next; sym!=NULL; sym=sym->next) { int match=0; if (sym->ident==iFUNCTN) { if ((sym->usage & uNATIVE)!=0 && (sym->usage & uREAD)!=0 && sym->index>=0) match=++numnatives; if ((sym->usage & uPUBLIC)!=0 && (sym->usage & uDEFINE)!=0) match=++numpublics; if (pc_overlays>0 && (sym->usage & uNATIVE)==0 && (sym->usage & (uREAD | uPUBLIC))!=0 && (sym->usage & uDEFINE)!=0) { if (strcmp(sym->name,uENTRYFUNC)!=0) ++numoverlays; /* there is no stub function for state entry functions */ if (sym->states!=NULL) { /* for functions with states, write an overlay block for every implementation */ statelist *stlist; for (stlist=sym->states->next; stlist!=NULL; stlist=stlist->next) ++numoverlays; } /* if */ } /* if */ if (strcmp(sym->name,uMAINFUNC)==0) { assert(sym->vclass==sGLOBAL); mainaddr=(pc_overlays>0) ? sym->index : sym->addr; } /* if */ } else if (sym->ident==iVARIABLE) { if ((sym->usage & uPUBLIC)!=0 && (sym->usage & (uREAD | uWRITTEN))!=0) match=++numpubvars; } /* if */ if (match) { char alias[sNAMEMAX+1]; assert(sym!=NULL); if ((sym->usage & uNATIVE)==0 || !lookup_alias(alias,sym->name)) { assert(strlen(sym->name)<=sNAMEMAX); strcpy(alias,sym->name); } /* if */ nametablesize+=(int)strlen(alias)+1; } /* if */ } /* for */ assert(numnatives==ntv_funcid); /* count number of libraries */ numlibraries=0; if (pc_addlibtable) { for (constptr=libname_tab.next; constptr!=NULL; constptr=constptr->next) { if (constptr->value>0) { assert(strlen(constptr->name)>0); numlibraries++; nametablesize+=(int)strlen(constptr->name)+1; } /* if */ } /* for */ } /* if */ /* count number of public tags */ numtags=0; for (constptr=tagname_tab.next; constptr!=NULL; constptr=constptr->next) { if ((constptr->value & PUBLICTAG)!=0) { assert(strlen(constptr->name)>0); numtags++; nametablesize+=(int)strlen(constptr->name)+1; } /* if */ } /* for */ /* adjust the number of overlays by the special overlays */ if (pc_overlays>0) for (i=0; i<ovlFIRST; i++) if (pc_ovl0size[i][1]!=0) numoverlays++; /* pad the header to sc_dataalign * => thereby the code segment is aligned * => since the code segment is padded to a sc_dataalign boundary, the data segment is aligned * => and thereby the stack top is aligned too */ assert(sc_dataalign!=0); padding= (int)(sc_dataalign - (sizeof hdr + nametablesize) % sc_dataalign); if (padding==sc_dataalign) padding=0; /* write the abstract machine header */ memset(&hdr, 0, sizeof hdr); if (pc_cellsize==2) hdr.magic=(unsigned short)AMX_MAGIC_16; else if (pc_cellsize==4) hdr.magic=(unsigned short)AMX_MAGIC_32; else if (pc_cellsize==8) hdr.magic=(unsigned short)AMX_MAGIC_64; hdr.file_version=CUR_FILE_VERSION; hdr.amx_version=MIN_AMX_VERSION; hdr.flags=(short)(sc_debug & sSYMBOLIC); if (sc_debug==0) hdr.flags|=AMX_FLAG_NOCHECKS; if (pc_memflags & suSLEEP_INSTR) hdr.flags|=AMX_FLAG_SLEEP; if (pc_overlays>0) hdr.flags|=AMX_FLAG_OVERLAY; if (pc_cryptkey!=0) hdr.flags|=AMX_FLAG_CRYPT; hdr.defsize=sizeof(AMX_FUNCSTUB); hdr.publics=sizeof hdr; /* public table starts right after the header */ hdr.natives=hdr.publics + numpublics*sizeof(AMX_FUNCSTUB); hdr.libraries=hdr.natives + numnatives*sizeof(AMX_FUNCSTUB); hdr.pubvars=hdr.libraries + numlibraries*sizeof(AMX_FUNCSTUB); hdr.tags=hdr.pubvars + numpubvars*sizeof(AMX_FUNCSTUB); hdr.overlays=hdr.tags + numtags*sizeof(AMX_FUNCSTUB); hdr.nametable=hdr.overlays + numoverlays*sizeof(AMX_OVERLAYINFO); hdr.cod=hdr.nametable + nametablesize + padding; hdr.dat=(int32_t)(hdr.cod + code_idx); hdr.hea=(int32_t)(hdr.dat + glb_declared*pc_cellsize); hdr.stp=(int32_t)(hdr.hea + pc_stksize*pc_cellsize); hdr.cip=(int32_t)(mainaddr); hdr.size=hdr.hea; pc_writebin(fout,&hdr,sizeof hdr); /* dump zeros up to the rest of the header, so that we can easily "seek" */ nullchar='\0'; for (nameofs=sizeof hdr; nameofs<hdr.cod; nameofs++) pc_writebin(fout,&nullchar,1); nameofs=hdr.nametable+sizeof(int16_t); /* write the public functions table */ count=0; for (sym=glbtab.next; sym!=NULL; sym=sym->next) { if (sym->ident==iFUNCTN && (sym->usage & uPUBLIC)!=0 && (sym->usage & uDEFINE)!=0) { assert(sym->vclass==sGLOBAL); /* in the case of overlays, write the overlay index rather than the address */ func.address=(uint32_t)((pc_overlays>0) ? sym->index : sym->addr); func.nameofs=nameofs; #if BYTE_ORDER==BIG_ENDIAN align32(&func.address); align32(&func.nameofs); #endif pc_resetbin(fout,hdr.publics+count*sizeof(AMX_FUNCSTUB)); pc_writebin(fout,&func,sizeof func); pc_resetbin(fout,nameofs); pc_writebin(fout,sym->name,(int)strlen(sym->name)+1); nameofs+=(int)strlen(sym->name)+1; count++; } /* if */ } /* for */ /* write the natives table */ /* The native functions must be written in sorted order. (They are * sorted on their "id", not on their name). A nested loop to find * each successive function would be an O(n^2) operation. But we * do not really need to sort, because the native function id's * are sequential and there are no duplicates. So we first walk * through the complete symbol list and store a pointer to every * native function of interest in a temporary table, where its id * serves as the index in the table. Now we can walk the table and * have all native functions in sorted order. */ if (numnatives>0) { nativelist=(symbol **)malloc(numnatives*sizeof(symbol *)); if (nativelist==NULL) error(103); /* insufficient memory */ #if !defined NDEBUG memset(nativelist,0,numnatives*sizeof(symbol *)); /* for NULL checking */ #endif for (sym=glbtab.next; sym!=NULL; sym=sym->next) { if (sym->ident==iFUNCTN && (sym->usage & uNATIVE)!=0 && (sym->usage & uREAD)!=0 && sym->index>=0) { assert(sym->index < numnatives); nativelist[(int)sym->index]=sym; } /* if */ } /* for */ count=0; for (i=0; i<numnatives; i++) { char alias[sNAMEMAX+1]; sym=nativelist[i]; assert(sym!=NULL); if (!lookup_alias(alias,sym->name)) { assert(strlen(sym->name)<=sNAMEMAX); strcpy(alias,sym->name); } /* if */ assert(sym->vclass==sGLOBAL); func.address=0; func.nameofs=nameofs; #if BYTE_ORDER==BIG_ENDIAN align32(&func.address); align32(&func.nameofs); #endif pc_resetbin(fout,hdr.natives+count*sizeof(AMX_FUNCSTUB)); pc_writebin(fout,&func,sizeof func); pc_resetbin(fout,nameofs); pc_writebin(fout,alias,(int)strlen(alias)+1); nameofs+=(int)strlen(alias)+1; count++; } /* for */ free(nativelist); } /* if */ /* write the libraries table */ if (pc_addlibtable) { count=0; for (constptr=libname_tab.next; constptr!=NULL; constptr=constptr->next) { if (constptr->value>0) { assert(strlen(constptr->name)>0); func.address=0; func.nameofs=nameofs; #if BYTE_ORDER==BIG_ENDIAN align32(&func.address); align32(&func.nameofs); #endif pc_resetbin(fout,hdr.libraries+count*sizeof(AMX_FUNCSTUB)); pc_writebin(fout,&func,sizeof func); pc_resetbin(fout,nameofs); pc_writebin(fout,constptr->name,(int)strlen(constptr->name)+1); nameofs+=(int)strlen(constptr->name)+1; count++; } /* if */ } /* for */ } /* if */ /* write the public variables table */ count=0; for (sym=glbtab.next; sym!=NULL; sym=sym->next) { if (sym->ident==iVARIABLE && (sym->usage & uPUBLIC)!=0 && (sym->usage & (uREAD | uWRITTEN))!=0) { assert((sym->usage & uDEFINE)!=0); assert(sym->vclass==sGLOBAL); func.address=(uint32_t)sym->addr; func.nameofs=nameofs; #if BYTE_ORDER==BIG_ENDIAN align32(&func.address); align32(&func.nameofs); #endif pc_resetbin(fout,hdr.pubvars+count*sizeof(AMX_FUNCSTUB)); pc_writebin(fout,&func,sizeof func); pc_resetbin(fout,nameofs); pc_writebin(fout,sym->name,(int)strlen(sym->name)+1); nameofs+=(int)strlen(sym->name)+1; count++; } /* if */ } /* for */ /* write the public tagnames table */ count=0; for (constptr=tagname_tab.next; constptr!=NULL; constptr=constptr->next) { if ((constptr->value & PUBLICTAG)!=0) { assert(strlen(constptr->name)>0); func.address=(uint32_t)(constptr->value & TAGMASK); func.nameofs=nameofs; #if BYTE_ORDER==BIG_ENDIAN align32(&func.address); align32(&func.nameofs); #endif pc_resetbin(fout,hdr.tags+count*sizeof(AMX_FUNCSTUB)); pc_writebin(fout,&func,sizeof func); pc_resetbin(fout,nameofs); pc_writebin(fout,constptr->name,(int)strlen(constptr->name)+1); nameofs+=(int)strlen(constptr->name)+1; count++; } /* if */ } /* for */ /* write the "maximum name length" field in the name table */ assert(nameofs==hdr.nametable+nametablesize); pc_resetbin(fout,hdr.nametable); count=sNAMEMAX; #if BYTE_ORDER==BIG_ENDIAN align16(&count); #endif pc_writebin(fout,&count,sizeof count); /* write the overlay table */ if (pc_overlays>0) { AMX_OVERLAYINFO info; #if !defined NDEBUG int count=0; #endif pc_resetbin(fout,hdr.overlays); /* first the special overlay(s) for the return point(s) */ for (i=0; i<ovlFIRST; i++) { if (pc_ovl0size[i][1]!=0) { info.offset=pc_ovl0size[i][0]; info.size=pc_ovl0size[i][1]; #if BYTE_ORDER==BIG_ENDIAN align32(&info.offset); align32(&info.size); #endif pc_writebin(fout,&info,sizeof info); #if !defined NDEBUG count++; #endif } /* if */ } /* for */ /* now all real overlay functions */ for (sym=glbtab.next; sym!=NULL; sym=sym->next) { if (sym->ident==iFUNCTN && (sym->usage & uNATIVE)==0 && (sym->usage & (uREAD | uPUBLIC))!=0 && (sym->usage & uDEFINE)!=0) { assert(sym->vclass==sGLOBAL); assert(strcmp(sym->name,uENTRYFUNC)==0 || sym->index==count++);/* overlay indices must be in sequential order */ assert(strcmp(sym->name,uENTRYFUNC)==0 || sym->addr<sym->codeaddr); /* write the overlay for the stub function first */ if (strcmp(sym->name,uENTRYFUNC)!=0) { /* there is no stub function for state entry functions */ info.offset=(int32_t)sym->addr; info.size=(uint32_t)(sym->codeaddr - sym->addr); #if BYTE_ORDER==BIG_ENDIAN align32(&info.offset); align32(&info.size); #endif pc_writebin(fout,&info,sizeof info); } /* if */ if (sym->states!=NULL) { /* for functions with states, write an overlay block for every implementation */ statelist *stlist; for (stlist=sym->states->next; stlist!=NULL; stlist=stlist->next) { assert(stlist->label==count++); info.offset=(int32_t)stlist->addr; info.size=(int32_t)(stlist->endaddr - stlist->addr); #if BYTE_ORDER==BIG_ENDIAN align32(&info.offset); align32(&info.size); #endif pc_writebin(fout,&info,sizeof info); } /* for */ } /* if */ } /* if */ } /* for */ } /* if */ pc_resetbin(fout,hdr.cod); /* First pass: relocate all labels */ /* This pass is necessary because the code addresses of labels is only known * after the peephole optimization flag. Labels can occur inside expressions * (e.g. the conditional operator), which are optimized. */ lbltab=NULL; if (sc_labnum>0) { cell codeindex=0; /* address of the current opcode similar to "code_idx" */ /* only very short programs have zero labels; no first pass is needed * if there are no labels */ lbltab=(cell *)malloc(sc_labnum*sizeof(cell)); if (lbltab==NULL) error(103); /* insufficient memory */ memset(lbltab,0,sc_labnum*sizeof(cell)); pc_resetasm(fin); while (pc_readasm(fin,line,sizeof line)!=NULL) { stripcomment(line); instr=skipwhitespace(line); /* ignore empty lines */ if (*instr=='\0') continue; if (tolower(*instr)=='l' && *(instr+1)=='.') { int lindex=(int)hex2ucell(instr+2,NULL); assert(lindex>=0 && lindex<sc_labnum); assert(lbltab[lindex]==0); /* should not already be declared */ lbltab[lindex]=codeindex; } else { /* get to the end of the instruction (make use of the '\n' that fgets() * added at the end of the line; this way we will *always* drop on a * whitespace character) */ for (params=instr; *params!='\0' && !isspace(*params); params++) /* nothing */; assert(params>instr); i=findopcode(instr,(int)(params-instr)); assert(opcodelist[i].name!=NULL); assert(opcodelist[i].opt_level<=pc_optimize || pc_optimize==0 && opcodelist[i].opt_level<=1); if (opcodelist[i].segment==sIN_CSEG) codeindex+=opcodelist[i].func(NULL,skipwhitespace(params),opcodelist[i].opcode,codeindex); } /* if */ } /* while */ } /* if */ /* Second pass (actually 2 more passes, one for all code and one for all data) */ for (pass=sIN_CSEG; pass<=sIN_DSEG; pass++) { cell codeindex=0; /* address of the current opcode similar to "code_idx" */ pc_resetasm(fin); while (pc_readasm(fin,line,sizeof line)!=NULL) { stripcomment(line); instr=skipwhitespace(line); /* ignore empty lines and labels (labels have a special syntax, so these * must be parsed separately) */ if (*instr=='\0' || tolower(*instr)=='l' && *(instr+1)=='.') continue; /* get to the end of the instruction (make use of the '\n' that fgets() * added at the end of the line; this way we will *always* drop on a * whitespace character) */ for (params=instr; *params!='\0' && !isspace(*params); params++) /* nothing */; assert(params>instr); i=findopcode(instr,(int)(params-instr)); assert(opcodelist[i].name!=NULL); assert(opcodelist[i].opt_level<=pc_optimize || pc_optimize==0 && opcodelist[i].opt_level<=1); if (opcodelist[i].segment==pass) codeindex+=opcodelist[i].func(fout,skipwhitespace(params),opcodelist[i].opcode,codeindex); } /* while */ } /* for */ if (lbltab!=NULL) { free(lbltab); #if !defined NDEBUG lbltab=NULL; #endif } /* if */ assert(hdr.size==pc_lengthbin(fout)); if (!writeerror && (sc_debug & sSYMBOLIC)!=0) append_dbginfo(fout); /* optionally append debug file */ if (writeerror) error(101,"disk full"); /* adjust the header (for Big Endian architectures) */ size=(int)hdr.cod; /* save, the value in the header may need to be swapped */ #if BYTE_ORDER==BIG_ENDIAN align32(&hdr.size); align16(&hdr.magic); align16(&hdr.flags); align16(&hdr.defsize); align32(&hdr.publics); align32(&hdr.natives); align32(&hdr.libraries); align32(&hdr.pubvars); align32(&hdr.tags); align32(&hdr.nametable); align32(&hdr.cod); align32(&hdr.dat); align32(&hdr.hea); align32(&hdr.stp); align32(&hdr.cip); pc_resetbin(fout,0); pc_writebin(fout,&hdr,sizeof hdr); #endif /* return the size of the header (including name tables, but excluding code * or data sections) */ return size; }
xymongen_page_t *load_layout(char *pgset) { char pagetag[100], subpagetag[100], subparenttag[100], vpagetag[100], vsubpagetag[100], vsubparenttag[100], grouptag[100], summarytag[100], titletag[100], hosttag[100]; char *name, *link, *onlycols, *exceptcols; char hostname[MAX_LINE_LEN]; xymongen_page_t *toppage, *curpage, *cursubpage, *cursubparent; group_t *curgroup; host_t *curhost; char *curtitle; int ip1, ip2, ip3, ip4; char *p; int fqdn = get_fqdn(); char *cfgdata, *inbol, *ineol, insavchar = '\0'; if (loadhostsfromxymond) { if (load_hostnames("@", NULL, fqdn) != 0) { errprintf("Cannot load host configuration from xymond\n"); return NULL; } } else { if (load_hostnames(xgetenv("HOSTSCFG"), "dispinclude", fqdn) != 0) { errprintf("Cannot load host configuration from %s\n", xgetenv("HOSTSCFG")); return NULL; } } if (first_host() == NULL) { errprintf("Empty configuration from %s\n", (loadhostsfromxymond ? "xymond" : xgetenv("HOSTSCFG"))); return NULL; } dbgprintf("load_layout(pgset=%s)\n", textornull(pgset)); /* * load_hostnames() picks up the hostname definitions, but not the page * layout. So we will scan the file again, this time doing the layout. */ if (pgset == NULL) pgset = ""; sprintf(pagetag, "%spage", pgset); sprintf(subpagetag, "%ssubpage", pgset); sprintf(subparenttag, "%ssubparent", pgset); sprintf(vpagetag, "v%spage", pgset); sprintf(vsubpagetag, "v%ssubpage", pgset); sprintf(vsubparenttag, "v%ssubparent", pgset); sprintf(grouptag, "%sgroup", pgset); sprintf(summarytag, "%ssummary", pgset); sprintf(titletag, "%stitle", pgset); sprintf(hosttag, "%s:", pgset); for (p=hosttag; (*p); p++) *p = toupper((int)*p); toppage = init_page("", "", 0); addtopagelist(toppage); curpage = NULL; cursubpage = NULL; curgroup = NULL; curhost = NULL; cursubparent = NULL; curtitle = NULL; inbol = cfgdata = hostscfg_content(); while (inbol && *inbol) { inbol += strspn(inbol, " \t"); ineol = strchr(inbol, '\n'); if (ineol) { while ((ineol > inbol) && (isspace(*ineol) || (*ineol == '\n'))) ineol--; if (*ineol != '\n') ineol++; insavchar = *ineol; *ineol = '\0'; } dbgprintf("load_layout: -- got line '%s'\n", inbol); if ((strncmp(inbol, pagetag, strlen(pagetag)) == 0) || (strncmp(inbol, vpagetag, strlen(vpagetag)) == 0)) { getnamelink(inbol, &name, &link); if (curpage == NULL) { /* First page - hook it on toppage as a subpage from there */ curpage = toppage->subpages = init_page(name, link, (strncmp(inbol, vpagetag, strlen(vpagetag)) == 0)); } else { curpage = curpage->next = init_page(name, link, (strncmp(inbol, vpagetag, strlen(vpagetag)) == 0)); } curpage->parent = toppage; if (curtitle) { curpage->pretitle = curtitle; curtitle = NULL; } cursubpage = NULL; cursubparent = NULL; curgroup = NULL; curhost = NULL; addtopagelist(curpage); } else if ( (strncmp(inbol, subpagetag, strlen(subpagetag)) == 0) || (strncmp(inbol, vsubpagetag, strlen(vsubpagetag)) == 0) ) { if (curpage == NULL) { errprintf("'subpage' ignored, no preceding 'page' tag : %s\n", inbol); goto nextline; } getnamelink(inbol, &name, &link); if (cursubpage == NULL) { cursubpage = curpage->subpages = init_page(name, link, (strncmp(inbol, vsubpagetag, strlen(vsubpagetag)) == 0)); } else { cursubpage = cursubpage->next = init_page(name, link, (strncmp(inbol, vsubpagetag, strlen(vsubpagetag)) == 0)); } cursubpage->parent = curpage; if (curtitle) { cursubpage->pretitle = curtitle; curtitle = NULL; } cursubparent = NULL; curgroup = NULL; curhost = NULL; addtopagelist(cursubpage); } else if ( (strncmp(inbol, subparenttag, strlen(subparenttag)) == 0) || (strncmp(inbol, vsubparenttag, strlen(vsubparenttag)) == 0) ) { xymongen_page_t *parentpage, *walk; getparentnamelink(inbol, toppage, &parentpage, &name, &link); if (parentpage == NULL) { errprintf("'subparent' ignored, unknown parent page: %s\n", inbol); goto nextline; } cursubparent = init_page(name, link, (strncmp(inbol, vsubparenttag, strlen(vsubparenttag)) == 0)); if (parentpage->subpages == NULL) { parentpage->subpages = cursubparent; } else { for (walk = parentpage->subpages; (walk->next); (walk = walk->next)) ; walk->next = cursubparent; } if (curtitle) { cursubparent->pretitle = curtitle; curtitle = NULL; } cursubparent->parent = parentpage; curgroup = NULL; curhost = NULL; addtopagelist(cursubparent); } else if (strncmp(inbol, grouptag, strlen(grouptag)) == 0) { int sorthosts = (strstr(inbol, "group-sorted") != NULL); getgrouptitle(inbol, pgset, &link, &onlycols, &exceptcols); if (curgroup == NULL) { curgroup = init_group(link, onlycols, exceptcols, sorthosts); if (cursubparent != NULL) { cursubparent->groups = curgroup; } else if (cursubpage != NULL) { /* We're in a subpage */ cursubpage->groups = curgroup; } else if (curpage != NULL) { /* We're on a main page */ curpage->groups = curgroup; } else { /* We're on the top page */ toppage->groups = curgroup; } } else { curgroup->next = init_group(link, onlycols, exceptcols, sorthosts); curgroup = curgroup->next; } if (curtitle) { curgroup->pretitle = curtitle; curtitle = NULL; } curhost = NULL; } else if (sscanf(inbol, "%3d.%3d.%3d.%3d %s", &ip1, &ip2, &ip3, &ip4, hostname) == 5) { void *xymonhost = NULL; int dialup, nonongreen, crittime = 1; double warnpct = reportwarnlevel; int warnstops = reportwarnstops; char *displayname, *clientalias, *comment, *description; char *alertlist, *onwaplist, *reporttime; char *nopropyellowlist, *nopropredlist, *noproppurplelist, *nopropacklist; char *targetpagelist[MAX_TARGETPAGES_PER_HOST]; int targetpagecount; char *hval; /* Check for ".default." hosts - they are ignored. */ if (*hostname == '.') goto nextline; if (!fqdn) { /* Strip any domain from the hostname */ char *p = strchr(hostname, '.'); if (p) *p = '\0'; } /* Get the info */ xymonhost = hostinfo(hostname); if (xymonhost == NULL) { errprintf("Confused - hostname '%s' cannot be found. Ignored\n", hostname); goto nextline; } /* Check for no-display hosts - they are ignored. */ /* But only when we're building the default pageset */ if ((strlen(pgset) == 0) && (xmh_item(xymonhost, XMH_FLAG_NODISP) != NULL)) goto nextline; for (targetpagecount=0; (targetpagecount < MAX_TARGETPAGES_PER_HOST); targetpagecount++) targetpagelist[targetpagecount] = NULL; targetpagecount = 0; dialup = (xmh_item(xymonhost, XMH_FLAG_DIALUP) != NULL); nonongreen = (xmh_item(xymonhost, XMH_FLAG_NONONGREEN) != NULL); alertlist = xmh_item(xymonhost, XMH_NK); hval = xmh_item(xymonhost, XMH_NKTIME); if (hval) crittime = within_sla(xmh_item(xymonhost, XMH_HOLIDAYS), hval, 0); onwaplist = xmh_item(xymonhost, XMH_WML); nopropyellowlist = xmh_item(xymonhost, XMH_NOPROPYELLOW); if (nopropyellowlist == NULL) nopropyellowlist = xmh_item(xymonhost, XMH_NOPROP); nopropredlist = xmh_item(xymonhost, XMH_NOPROPRED); noproppurplelist = xmh_item(xymonhost, XMH_NOPROPPURPLE); nopropacklist = xmh_item(xymonhost, XMH_NOPROPACK); displayname = xmh_item(xymonhost, XMH_DISPLAYNAME); comment = xmh_item(xymonhost, XMH_COMMENT); description = xmh_item(xymonhost, XMH_DESCRIPTION); hval = xmh_item(xymonhost, XMH_WARNPCT); if (hval) warnpct = atof(hval); hval = xmh_item(xymonhost, XMH_WARNSTOPS); if (hval) warnstops = atof(hval); reporttime = xmh_item(xymonhost, XMH_REPORTTIME); clientalias = xmh_item(xymonhost, XMH_CLIENTALIAS); if (xymonhost && (strcmp(xmh_item(xymonhost, XMH_HOSTNAME), clientalias) == 0)) clientalias = NULL; if (xymonhost && (strlen(pgset) > 0)) { /* Walk the clone-list and pick up the target pages for this host */ void *cwalk = xymonhost; do { hval = xmh_item_walk(cwalk); while (hval) { if (strncasecmp(hval, hosttag, strlen(hosttag)) == 0) targetpagelist[targetpagecount++] = strdup(hval+strlen(hosttag)); hval = xmh_item_walk(NULL); } cwalk = next_host(cwalk, 1); } while (cwalk && (strcmp(xmh_item(cwalk, XMH_HOSTNAME), xmh_item(xymonhost, XMH_HOSTNAME)) == 0) && (targetpagecount < MAX_TARGETPAGES_PER_HOST) ); /* * HACK: Check if the pageset tag is present at all in the host * entry. If it isn't, then drop this incarnation of the host. * * Without this, the following hosts.cfg file will have the * www.hswn.dk host listed twice on the alternate pageset: * * adminpage nyc NYC * * 127.0.0.1 localhost # bbd http://localhost/ CLIENT:osiris * 172.16.10.2 www.xymon.com # http://www.xymon.com/ ADMIN:nyc ssh noinfo * * page superdome Superdome * 172.16.10.2 www.xymon.com # noconn * */ if (strstr(inbol, hosttag) == NULL) targetpagecount = 0; } if (strlen(pgset) == 0) { /* * Default pageset generated. Put the host into * whatever group or page is current. */ if (curhost == NULL) { curhost = init_host(hostname, 0, displayname, clientalias, comment, description, ip1, ip2, ip3, ip4, dialup, warnpct, warnstops, reporttime, alertlist, crittime, onwaplist, nopropyellowlist, nopropredlist, noproppurplelist, nopropacklist); if (curgroup != NULL) { curgroup->hosts = curhost; } else if (cursubparent != NULL) { cursubparent->hosts = curhost; } else if (cursubpage != NULL) { cursubpage->hosts = curhost; } else if (curpage != NULL) { curpage->hosts = curhost; } else { toppage->hosts = curhost; } } else { curhost = curhost->next = init_host(hostname, 0, displayname, clientalias, comment, description, ip1, ip2, ip3, ip4, dialup, warnpct, warnstops, reporttime, alertlist, crittime, onwaplist, nopropyellowlist,nopropredlist, noproppurplelist, nopropacklist); } curhost->parent = (cursubparent ? cursubparent : (cursubpage ? cursubpage : curpage)); if (curtitle) { curhost->pretitle = curtitle; curtitle = NULL; } curhost->nonongreen = nonongreen; } else if (targetpagecount) { int pgnum; for (pgnum=0; (pgnum < targetpagecount); pgnum++) { char *targetpagename = targetpagelist[pgnum]; char savechar; int wantedgroup = 0; xymonpagelist_t *targetpage = NULL; /* Put the host into the page specified by the PGSET: tag */ p = strchr(targetpagename, ','); if (p) { savechar = *p; *p = '\0'; wantedgroup = atoi(p+1); } else { savechar = '\0'; p = targetpagename + strlen(targetpagename); } /* Find the page */ if (strcmp(targetpagename, "*") == 0) { *targetpagename = '\0'; } for (targetpage = pagelisthead; (targetpage && (strcmp(targetpagename, targetpage->pageentry->name) != 0)); targetpage = targetpage->next) ; *p = savechar; if (targetpage == NULL) { errprintf("Warning: Cannot find any target page named '%s' in set '%s' - dropping host '%s'\n", targetpagename, pgset, hostname); } else { host_t *newhost = init_host(hostname, 0, displayname, clientalias, comment, description, ip1, ip2, ip3, ip4, dialup, warnpct, warnstops, reporttime, alertlist, crittime, onwaplist, nopropyellowlist,nopropredlist, noproppurplelist, nopropacklist); if (wantedgroup > 0) { group_t *gwalk; host_t *hwalk; int i; for (gwalk = targetpage->pageentry->groups, i=1; (gwalk && (i < wantedgroup)); i++,gwalk=gwalk->next) ; if (gwalk) { if (gwalk->hosts == NULL) gwalk->hosts = newhost; else { for (hwalk = gwalk->hosts; (hwalk->next); hwalk = hwalk->next) ; hwalk->next = newhost; } } else { errprintf("Warning: Cannot find group %d for host %s - dropping host\n", wantedgroup, hostname); } } else { /* Just put in on the page's hostlist */ host_t *walk; if (targetpage->pageentry->hosts == NULL) targetpage->pageentry->hosts = newhost; else { for (walk = targetpage->pageentry->hosts; (walk->next); walk = walk->next) ; walk->next = newhost; } } newhost->parent = targetpage->pageentry; if (curtitle) newhost->pretitle = curtitle; } curtitle = NULL; } } } else if (strncmp(inbol, summarytag, strlen(summarytag)) == 0) { /* summary row.column IP-ADDRESS-OF-PARENT http://xymon.com/ */ char sumname[MAX_LINE_LEN]; char receiver[MAX_LINE_LEN]; char url[MAX_LINE_LEN]; summary_t *newsum; if (sscanf(inbol, "summary %s %s %s", sumname, receiver, url) == 3) { newsum = init_summary(sumname, receiver, url); newsum->next = sumhead; sumhead = newsum; } } else if (strncmp(inbol, titletag, strlen(titletag)) == 0) { /* Save the title for the next entry */ curtitle = strdup(skipwhitespace(skipword(inbol))); } nextline: if (ineol) { *ineol = insavchar; if (*ineol != '\n') ineol = strchr(ineol, '\n'); inbol = (ineol ? ineol+1 : NULL); } else inbol = NULL; } xfree(cfgdata); return toppage; }
static void append_dbginfo(FILE *fout) { AMX_DBG_HDR dbghdr; AMX_DBG_LINE dbgline; AMX_DBG_SYMBOL dbgsym; AMX_DBG_SYMDIM dbgidxtag[sDIMEN_MAX]; int index,dim,dbgsymdim; const char *str,*prevstr,*name,*prevname; ucell codeidx,previdx; constvalue *constptr; char symname[2*sNAMEMAX+16]; int16_t id1,id2; ucell address; /* header with general information */ memset(&dbghdr, 0, sizeof dbghdr); dbghdr.size=sizeof dbghdr; dbghdr.magic=AMX_DBG_MAGIC; dbghdr.file_version=CUR_FILE_VERSION; dbghdr.amx_version=MIN_AMX_VERSION; /* first pass: collect the number of items in various tables */ /* file table */ previdx=0; prevstr=NULL; prevname=NULL; for (index=0; (str=get_dbgstring(index))!=NULL; index++) { assert(str!=NULL); assert(str[0]!='\0' && str[1]==':'); if (str[0]=='F') { codeidx=hex2ucell(str+2,&name); if (codeidx!=previdx) { if (prevstr!=NULL) { assert(prevname!=NULL); dbghdr.files++; dbghdr.size+=(int32_t)(sizeof(AMX_DBG_FILE)+strlen(prevname)); } /* if */ previdx=codeidx; } /* if */ prevstr=str; prevname=skipwhitespace(name); } /* if */ } /* for */ if (prevstr!=NULL) { assert(prevname!=NULL); dbghdr.files++; dbghdr.size+=(int32_t)(sizeof(AMX_DBG_FILE)+strlen(prevname)); } /* if */ /* line number table */ for (index=0; (str=get_dbgstring(index))!=NULL; index++) { assert(str!=NULL); assert(str[0]!='\0' && str[1]==':'); if (str[0]=='L') { dbghdr.lines++; dbghdr.size+=sizeof(AMX_DBG_LINE); } /* if */ } /* for */ /* symbol table */ for (index=0; (str=get_dbgstring(index))!=NULL; index++) { assert(str!=NULL); assert(str[0]!='\0' && str[1]==':'); if (str[0]=='S') { dbghdr.symbols++; str=strchr(str+2,':'); assert(str!=NULL); name=skipwhitespace(str+1); str=strchr(name,' '); assert(str!=NULL); assert((int)(str-name)<sizeof symname); strlcpy(symname,name,(int)(str-name)+1); dbghdr.size+=(int32_t)(sizeof(AMX_DBG_SYMBOL)+strlen(symname)); if ((prevstr=strchr(name,'['))!=NULL) while ((prevstr=strchr(prevstr+1,':'))!=NULL) dbghdr.size+=sizeof(AMX_DBG_SYMDIM); } /* if */ } /* for */ /* tag table */ for (constptr=tagname_tab.next; constptr!=NULL; constptr=constptr->next) { assert(strlen(constptr->name)>0); dbghdr.tags++; dbghdr.size+=(int32_t)(sizeof(AMX_DBG_TAG)+strlen(constptr->name)); } /* for */ /* automaton table */ for (constptr=sc_automaton_tab.next; constptr!=NULL; constptr=constptr->next) { assert(constptr->index==0 && strlen(constptr->name)==0 || strlen(constptr->name)>0); dbghdr.automatons++; dbghdr.size+=(int32_t)(sizeof(AMX_DBG_MACHINE)+strlen(constptr->name)); } /* for */ /* state table */ for (constptr=sc_state_tab.next; constptr!=NULL; constptr=constptr->next) { assert(strlen(constptr->name)>0); dbghdr.states++; dbghdr.size+=(int32_t)(sizeof(AMX_DBG_STATE)+strlen(constptr->name)); } /* for */ /* pass 2: generate the tables */ #if BYTE_ORDER==BIG_ENDIAN align32((uint32_t*)&dbghdr.size); align16(&dbghdr.magic); align16(&dbghdr.flags); align16(&dbghdr.files); align16(&dbghdr.lines); align16(&dbghdr.symbols); align16(&dbghdr.tags); align16(&dbghdr.automatons); align16(&dbghdr.states); #endif writeerror |= !pc_writebin(fout,&dbghdr,sizeof dbghdr); /* file table */ previdx=0; prevstr=NULL; prevname=NULL; for (index=0; (str=get_dbgstring(index))!=NULL; index++) { assert(str!=NULL); assert(str[0]!='\0' && str[1]==':'); if (str[0]=='F') { codeidx=hex2ucell(str+2,&name); if (codeidx!=previdx) { if (prevstr!=NULL) { assert(prevname!=NULL); #if BYTE_ORDER==BIG_ENDIAN align32(&previdx); #endif writeerror |= !pc_writebin(fout,&previdx,sizeof(uint32_t)); writeerror |= !pc_writebin(fout,prevname,(int)strlen(prevname)+1); } /* if */ previdx=codeidx; } /* if */ prevstr=str; prevname=skipwhitespace(name); } /* if */ } /* for */ if (prevstr!=NULL) { assert(prevname!=NULL); #if BYTE_ORDER==BIG_ENDIAN align32(&previdx); #endif writeerror |= !pc_writebin(fout,&previdx,sizeof(uint32_t)); writeerror |= !pc_writebin(fout,prevname,(int)strlen(prevname)+1); } /* if */ /* line number table */ for (index=0; (str=get_dbgstring(index))!=NULL; index++) { assert(str!=NULL); assert(str[0]!='\0' && str[1]==':'); if (str[0]=='L') { dbgline.address=(uint32_t)hex2ucell(str+2,&str); dbgline.line=(int32_t)hex2ucell(str,NULL); #if BYTE_ORDER==BIG_ENDIAN align32(&dbgline.address); align32(&dbgline.line); #endif writeerror |= !pc_writebin(fout,&dbgline,sizeof dbgline); } /* if */ } /* for */ /* symbol table */ for (index=0; (str=get_dbgstring(index))!=NULL; index++) { assert(str!=NULL); assert(str[0]!='\0' && str[1]==':'); if (str[0]=='S') { dbgsym.address=(uint32_t)hex2ucell(str+2,&str); dbgsym.tag=(int16_t)hex2ucell(str,&str); str=skipwhitespace(str); assert(*str==':'); name=skipwhitespace(str+1); str=strchr(name,' '); assert(str!=NULL); assert((int)(str-name)<sizeof symname); strlcpy(symname,name,(int)(str-name)+1); dbgsym.codestart=(uint32_t)hex2ucell(str,&str); dbgsym.codeend=(uint32_t)hex2ucell(str,&str); dbgsym.ident=(char)hex2ucell(str,&str); dbgsym.vclass=(char)hex2ucell(str,&str); dbgsym.dim=0; str=skipwhitespace(str); if (*str=='[') { while (*(str=skipwhitespace(str+1))!=']') { dbgidxtag[dbgsym.dim].size=(uint32_t)hex2ucell(str,&str); dbgsym.dim++; } /* while */ } /* if */ dbgsymdim = dbgsym.dim; #if BYTE_ORDER==BIG_ENDIAN align32(&dbgsym.address); align16(&dbgsym.tag); align32(&dbgsym.codestart); align32(&dbgsym.codeend); align16(&dbgsym.dim); #endif writeerror |= !pc_writebin(fout,&dbgsym.address,sizeof dbgsym.codeend); writeerror |= !pc_writebin(fout,&dbgsym.tag,sizeof dbgsym.tag); writeerror |= !pc_writebin(fout,&dbgsym.codestart,sizeof dbgsym.codeend); writeerror |= !pc_writebin(fout,&dbgsym.codeend,sizeof dbgsym.codeend); writeerror |= !pc_writebin(fout,&dbgsym.ident,sizeof dbgsym.ident); writeerror |= !pc_writebin(fout,&dbgsym.vclass,sizeof dbgsym.vclass); writeerror |= !pc_writebin(fout,&dbgsym.dim,sizeof dbgsym.dim); writeerror |= !pc_writebin(fout,symname,(int)strlen(symname)+1); for (dim=0; dim<dbgsymdim; dim++) { #if BYTE_ORDER==BIG_ENDIAN align16(&dbgidxtag[dim].tag); align32(&dbgidxtag[dim].size); #endif writeerror |= !pc_writebin(fout,&dbgidxtag[dim].tag,sizeof dbgidxtag[dim].tag); writeerror |= !pc_writebin(fout,&dbgidxtag[dim].size,sizeof dbgidxtag[dim].size); } /* for */ } /* if */ } /* for */ /* tag table */ for (constptr=tagname_tab.next; constptr!=NULL; constptr=constptr->next) { assert(strlen(constptr->name)>0); id1=(int16_t)(constptr->value & TAGMASK); #if BYTE_ORDER==BIG_ENDIAN align16(&id1); #endif writeerror |= !pc_writebin(fout,&id1,sizeof id1); writeerror |= !pc_writebin(fout,constptr->name,(int)strlen(constptr->name)+1); } /* for */ /* automaton table */ for (constptr=sc_automaton_tab.next; constptr!=NULL; constptr=constptr->next) { assert(constptr->index==0 && strlen(constptr->name)==0 || strlen(constptr->name)>0); id1=(int16_t)constptr->index; address=(ucell)constptr->value; #if BYTE_ORDER==BIG_ENDIAN align16(&id1); align32(&address); #endif writeerror |= !pc_writebin(fout,&id1,sizeof id1); writeerror |= !pc_writebin(fout,&address,sizeof(uint32_t)); writeerror |= !pc_writebin(fout,constptr->name,(int)strlen(constptr->name)+1); } /* for */ /* state table */ for (constptr=sc_state_tab.next; constptr!=NULL; constptr=constptr->next) { assert(strlen(constptr->name)>0); id1=(int16_t)constptr->value; id2=(int16_t)constptr->index; address=(ucell)constptr->value; #if BYTE_ORDER==BIG_ENDIAN align16(&id1); align16(&id2); #endif writeerror |= !pc_writebin(fout,&id1,sizeof id1); writeerror |= !pc_writebin(fout,&id2,sizeof id2); writeerror |= !pc_writebin(fout,constptr->name,(int)strlen(constptr->name)+1); } /* for */ delete_dbgstringtable(); }
int main(int argc, char *argv[]) { strbuffer_t *inbuf; char *ackbuf; char *subjectline = NULL; char *returnpathline = NULL; char *fromline = NULL; char *firsttxtline = NULL; int inheaders = 1; char *p; pcre *subjexp; const char *errmsg; int errofs, result; int ovector[30]; char cookie[10]; int duration = 0; int argi; char *envarea = NULL; for (argi=1; (argi < argc); argi++) { if (strcmp(argv[argi], "--debug") == 0) { debug = 1; } else if (argnmatch(argv[argi], "--env=")) { char *p = strchr(argv[argi], '='); loadenv(p+1, envarea); } else if (argnmatch(argv[argi], "--area=")) { char *p = strchr(argv[argi], '='); envarea = strdup(p+1); } } initfgets(stdin); inbuf = newstrbuffer(0); while (unlimfgets(inbuf, stdin)) { sanitize_input(inbuf, 0, 0); if (!inheaders) { /* We're in the message body. Look for a "delay=N" line here. */ if ((strncasecmp(STRBUF(inbuf), "delay=", 6) == 0) || (strncasecmp(STRBUF(inbuf), "delay ", 6) == 0)) { duration = durationvalue(STRBUF(inbuf)+6); continue; } else if ((strncasecmp(STRBUF(inbuf), "ack=", 4) == 0) || (strncasecmp(STRBUF(inbuf), "ack ", 4) == 0)) { /* Some systems cannot generate a subject. Allow them to ack * via text in the message body. */ subjectline = (char *)malloc(STRBUFLEN(inbuf) + 1024); sprintf(subjectline, "Subject: Xymon [%s]", STRBUF(inbuf)+4); } else if (*STRBUF(inbuf) && !firsttxtline) { /* Save the first line of the message body, but ignore blank lines */ firsttxtline = strdup(STRBUF(inbuf)); } continue; /* We don't care about the rest of the message body */ } /* See if we're at the end of the mail headers */ if (inheaders && (STRBUFLEN(inbuf) == 0)) { inheaders = 0; continue; } /* Is it one of those we want to keep ? */ if (strncasecmp(STRBUF(inbuf), "return-path:", 12) == 0) returnpathline = strdup(skipwhitespace(STRBUF(inbuf)+12)); else if (strncasecmp(STRBUF(inbuf), "from:", 5) == 0) fromline = strdup(skipwhitespace(STRBUF(inbuf)+5)); else if (strncasecmp(STRBUF(inbuf), "subject:", 8) == 0) subjectline = strdup(skipwhitespace(STRBUF(inbuf)+8)); } freestrbuffer(inbuf); /* No subject ? No deal */ if (subjectline == NULL) { dbgprintf("Subject-line not found\n"); return 1; } /* Get the alert cookie */ subjexp = pcre_compile(".*(Xymon|Hobbit|BB)[ -]* \\[*(-*[0-9]+)[\\]!]*", PCRE_CASELESS, &errmsg, &errofs, NULL); if (subjexp == NULL) { dbgprintf("pcre compile failed - 1\n"); return 2; } result = pcre_exec(subjexp, NULL, subjectline, strlen(subjectline), 0, 0, ovector, (sizeof(ovector)/sizeof(int))); if (result < 0) { dbgprintf("Subject line did not match pattern\n"); return 3; /* Subject did not match what we expected */ } if (pcre_copy_substring(subjectline, ovector, result, 2, cookie, sizeof(cookie)) <= 0) { dbgprintf("Could not find cookie value\n"); return 4; /* No cookie */ } pcre_free(subjexp); /* See if there's a "DELAY=" delay-value also */ subjexp = pcre_compile(".*DELAY[ =]+([0-9]+[mhdw]*)", PCRE_CASELESS, &errmsg, &errofs, NULL); if (subjexp == NULL) { dbgprintf("pcre compile failed - 2\n"); return 2; } result = pcre_exec(subjexp, NULL, subjectline, strlen(subjectline), 0, 0, ovector, (sizeof(ovector)/sizeof(int))); if (result >= 0) { char delaytxt[4096]; if (pcre_copy_substring(subjectline, ovector, result, 1, delaytxt, sizeof(delaytxt)) > 0) { duration = durationvalue(delaytxt); } } pcre_free(subjexp); /* See if there's a "msg" text also */ subjexp = pcre_compile(".*MSG[ =]+(.*)", PCRE_CASELESS, &errmsg, &errofs, NULL); if (subjexp == NULL) { dbgprintf("pcre compile failed - 3\n"); return 2; } result = pcre_exec(subjexp, NULL, subjectline, strlen(subjectline), 0, 0, ovector, (sizeof(ovector)/sizeof(int))); if (result >= 0) { char msgtxt[4096]; if (pcre_copy_substring(subjectline, ovector, result, 1, msgtxt, sizeof(msgtxt)) > 0) { firsttxtline = strdup(msgtxt); } } pcre_free(subjexp); /* Use the "return-path:" header if we didn't see a From: line */ if ((fromline == NULL) && returnpathline) fromline = returnpathline; if (fromline) { /* Remove '<' and '>' from the fromline - they mess up HTML */ while ((p = strchr(fromline, '<')) != NULL) *p = ' '; while ((p = strchr(fromline, '>')) != NULL) *p = ' '; } /* Setup the acknowledge message */ if (duration == 0) duration = 60; /* Default: Ack for 60 minutes */ if (firsttxtline == NULL) firsttxtline = "<No cause specified>"; ackbuf = (char *)malloc(4096 + strlen(firsttxtline) + (fromline ? strlen(fromline) : 0)); p = ackbuf; p += sprintf(p, "xymondack %s %d %s", cookie, duration, firsttxtline); if (fromline) { p += sprintf(p, "\nAcked by: %s", fromline); } if (debug) { printf("%s\n", ackbuf); return 0; } sendmessage(ackbuf, NULL, XYMON_TIMEOUT, NULL); return 0; }
static char *parse_histlogfile(char *hostname, char *servicename, char *timespec) { char cause[MAX_LINE_LEN]; char fn[PATH_MAX]; char *p; FILE *fd; char l[MAX_LINE_LEN]; int causefull = 0; cause[0] = '\0'; sprintf(fn, "%s/%s", xgetenv("XYMONHISTLOGS"), commafy(hostname)); for (p = strrchr(fn, '/'); (*p); p++) if (*p == ',') *p = '_'; sprintf(p, "/%s/%s", servicename, timespec); dbgprintf("Looking at history logfile %s\n", fn); fd = fopen(fn, "r"); if (fd != NULL) { while (!causefull && fgets(l, sizeof(l), fd)) { p = strchr(l, '\n'); if (p) *p = '\0'; if ((l[0] == '&') && (strncmp(l, "&green", 6) != 0)) { p = skipwhitespace(skipword(l)); if ((strlen(cause) + strlen(p) + strlen("<BR>\n") + 1) < sizeof(cause)) { strcat(cause, p); strcat(cause, "<BR>\n"); } else causefull = 1; } } #if 1 if (strlen(cause) == 0) { strcpy(cause, "See detailed log"); } #else /* What is this code supposed to do ? The sscanf seemingly never succeeds */ /* storner, 2006-06-02 */ if (strlen(cause) == 0) { int offset; rewind(fd); if (fgets(l, sizeof(l), fd)) { p = strchr(l, '\n'); if (p) *p = '\0'; if (sscanf(l, "%*s %*s %*s %*s %*s %*s %*s %n", &offset) == 1) { strncpy(cause, l+offset, sizeof(cause)); } else { errprintf("Scan of file %s failed, l='%s'\n", fn, l); } cause[sizeof(cause)-1] = '\0'; } } #endif if (causefull) { cause[sizeof(cause) - strlen(" [Truncated]") - 1] = '\0'; strcat(cause, " [Truncated]"); } fclose(fd); } else { strcpy(cause, "No historical status available"); } return strdup(cause); }