Subversion Repositories wimsdev

Rev

Rev 8185 | Rev 11125 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. /*    Copyright (C) 1998-2003 XIAO, Gang of Universite de Nice - Sophia Antipolis
  2.  *
  3.  *  This program is free software; you can redistribute it and/or modify
  4.  *  it under the terms of the GNU General Public License as published by
  5.  *  the Free Software Foundation; either version 2 of the License, or
  6.  *  (at your option) any later version.
  7.  *
  8.  *  This program is distributed in the hope that it will be useful,
  9.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.  *  GNU General Public License for more details.
  12.  *
  13.  *  You should have received a copy of the GNU General Public License
  14.  *  along with this program; if not, write to the Free Software
  15.  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16.  */
  17.  
  18. /* line input / output / translation routines
  19.  * and error routines
  20.  */
  21. #include <utime.h>
  22. #include <sys/socket.h>
  23. #include <sys/un.h>
  24.  
  25. #include "wims.h"
  26.  
  27. int is_class_module=0;
  28.  
  29. int trusted_module(void);
  30. void phtml_put_base(char *fname,int cache);
  31. void module_error(char msg[]);
  32. void user_error(char msg[]);
  33. void accessfile(char *content, char *type, char *s,...);
  34. int remove_tree(char *p);
  35. void output(char *s,...);
  36. char *_getvar(char *vname);
  37. int checkhost(char *hlist);
  38.  
  39. char *lastdata;
  40. char lastdatafile[MAX_FNAME+1];
  41. char *datacache[DATAFIELD_LIMIT];
  42. int  nextdatacache;
  43. struct stat ftst;
  44. char lastftest[MAX_FNAME+1];
  45. int lastftype;
  46. char outbuf[8192];
  47. char *outptr;
  48.  
  49. /* These modules can execute private programs.
  50.  * adm/ modules are always trusted, so need no definition here.
  51.  */
  52. char *trusted_modules="";
  53. /* bit 0: module is not trusted.
  54.   * bit 1: file in wimshome.
  55.   * bit 2: readdef or file in writable directory.
  56.   */
  57. int untrust=0;  /* non-zero if user detrusts the module. */
  58.  
  59. int error_status=0;
  60. char pidbuf[32];
  61.  
  62. void delete_pid(void);
  63.  
  64. /* Internal use only */
  65. void _debug(char *s,...)
  66. {
  67.     va_list vp;
  68.     char buf[MAX_LINELEN+1];
  69.  
  70.     va_start(vp,s);
  71.     vsnprintf(buf,sizeof(buf),s,vp);
  72.     va_end(vp);
  73.     setvar("debug",buf); module_error("debug");
  74.     exit(1);
  75. }
  76.  
  77.  
  78. /* HTTP response header for non-processed CGI interface */
  79. void nph_header(int code)
  80. {
  81.     char *cstr;
  82.     switch(code) {
  83.       case 200: cstr="OK"; break;
  84.       case 301: cstr="Moved Permanently"; break;
  85.       case 302: cstr="Moved Temporarily"; break;
  86.       case 420: cstr="WIMS Nested Error"; break;
  87.       case 450: cstr="WIMS User Error"; break;
  88.       case 500: cstr="WIMS Internal Error"; break;
  89.       case 550: cstr="WIMS Module Error"; break;
  90.       default: cstr="ERROR"; break;
  91.     }
  92.     if(httpd_type!=httpd_wims) printf("Status: %d %s\r\n",code,cstr);
  93.     else {
  94.       char *p, tbuf[256];
  95.       mystrncpy(tbuf,ctime(&nowtime),sizeof(tbuf));
  96.       for(p=tbuf+strlen(tbuf);p>=tbuf && (*(p-1)=='\n' || *(p-1)=='\r'); p--);
  97.       *p=0;
  98.       printf("HTTP/1.0 %d %s\r\n\
  99. Date: %s\r\n\
  100. Connection: close\r\n\
  101. ",code,cstr,tbuf);
  102.     }
  103. }
  104.  
  105. void flushoutput(void)
  106. {
  107.     int l2;
  108.     if(outptr<=outbuf) return;
  109.     l2=outptr-outbuf;
  110.     if(lastout_file!=-1) (void)write(lastout_file,outbuf,l2);
  111.     else fwrite(outbuf,l2,1,stdout);
  112.     outptr=outbuf;
  113. }
  114.  
  115. void internal_warn(char msg[])
  116. {
  117.     char buf[1024];
  118.     fprintf(stderr,"wims: %s\n%s\n",msg,strerror(errno));
  119.     snprintf(buf,sizeof(buf),"%s: %s\n",nowstr,msg);
  120.     accessfile(buf,"a","%s/internal_error.log",log_dir);
  121. }
  122.  
  123. /* Internal error: panic and forget about requester. */
  124. void internal_error(char msg[])
  125. {
  126.     if(error_status<2) {
  127.       nph_header(500);
  128.       printf("Cache-Control: no-cache\nPragma: no-cache\r\n\
  129. Content-type: text/plain\r\n\r\n\r\n\
  130. WIMS panick! %s\n%s\n",msg,strerror(errno));
  131.       error_status=2; internal_warn(msg);
  132.     }
  133.     delete_pid(); exit(1);
  134. }
  135.  
  136. void tex_nospace(char *p)
  137. {
  138.     char *p1, *p2;
  139.     char buf[MAX_LINELEN+1];
  140.     for(p1=buf,p2=p;*p2 && p1-buf<MAX_LINELEN-4;p2++) {
  141.       if(!isspace(*p2)) {*p1++=*p2;continue;}
  142.       while(isspace(*p2)) p2++;
  143.       if(*(p1-1)=='\\' ||
  144.          (p1>buf && myisalnum(*(p1-1)) && myisalnum(*p2)))
  145.         *p1++=' ';
  146.       *p1++=*p2;
  147.     }
  148.     *p1++=0; memmove(p,buf,p1-buf);
  149. }
  150.  
  151. void nametoolong(char *p)
  152. {
  153.     char buf[MAX_FNAME+17];
  154.     snprintf(buf,sizeof(buf),"%s...",p);
  155.     force_setvar("wims_error_data",buf);
  156.     module_error("file_name_too_long");
  157. }
  158.  
  159. off_t ftest_size;
  160.  
  161. /* A simple front-end of stat(). */
  162. int ftest(char *fname)
  163. {
  164.     if(strcmp(fname,lastftest)==0) return lastftype;
  165. /* if(fname[0]=='/' || fname[0]=='.') fprintf(stderr,"ftest: %s\n",fname); */
  166.     mystrncpy(lastftest,fname,sizeof(lastftest));
  167.     if(stat(fname,&ftst)) return lastftype=-1;
  168.     ftest_size=ftst.st_size;
  169.     if(S_ISREG(ftst.st_mode)) {
  170.       if((ftst.st_mode&(S_IXUSR|S_IXGRP|S_IXOTH))!=0) return lastftype=is_exec;
  171.       else return lastftype=is_file;
  172.     }
  173.     if(S_ISDIR(ftst.st_mode)) return lastftype=is_dir;
  174.     if(S_ISFIFO(ftst.st_mode)) return lastftype=is_fifo;
  175.     if(S_ISSOCK(ftst.st_mode)) return lastftype=is_socket;
  176.     return lastftype=is_unknown;
  177. }
  178.  
  179. char fnbuf[MAX_FNAME+1];
  180.  
  181. /* make a filename and check length */
  182. char *mkfname(char buf[], char *s,...)
  183. {
  184.     va_list vp;
  185.     char *p;
  186.  
  187.     if(buf==NULL) p=fnbuf; else p=buf;
  188.     va_start(vp,s);
  189.     vsnprintf(p,MAX_FNAME,s,vp);
  190.     va_end(vp);
  191.     if(strlen(p)>=MAX_FNAME-1) nametoolong(p);
  192.     return p;
  193. }
  194.  
  195. void sysmask_trigger(char *s)
  196. {
  197.     char buf[MAX_FNAME+1];
  198.     struct stat st;
  199.     mkfname(buf,"%s/%s",sysmask_trigger_dir,s);
  200.     stat(buf,&st);
  201. }
  202.  
  203. /* read-in a file into buffer. Use open() and read().
  204.        * Return buffer address which will be malloc'ed if buf=NULL. */
  205. char *readfile(char *fname, char buf[], long int buflen)
  206. {
  207.     int fd, t, st;
  208.     long int l, lc;
  209.     char *bf;
  210.     t=0; if(buf) buf[0]=0;
  211.     st=ftest(fname); if(st!=is_file) {
  212.       if(st==is_exec) { /* refuse to open executable file */
  213.           setvar("executable",fname); module_error("executable");
  214.       }
  215.       return NULL;
  216.     }
  217.     l=ftst.st_size; if(l<0) return NULL;
  218.     if(l>=buflen) {
  219.       if(buflen<MAX_LINELEN) l=buflen-1;
  220.       else {
  221.           if(strncmp(fname,"modules/",strlen("modules/"))==0) {
  222.             setvar(error_data_string,fname); module_error("file_too_long");
  223.           }
  224.           else user_error("cmd_output_too_long");
  225.       }
  226.     }
  227.     fd=open(fname,O_RDONLY); if(fd==-1) return NULL;
  228.     if(buf==NULL) bf=xmalloc(l+8); else {bf=buf;if(l==0) {t=1; l=buflen-1;}}
  229.     lc=read(fd,bf,l); close(fd);
  230.     if(lc<0 || lc>l || (lc!=l && t==0))
  231.       {if(buf==NULL) free(bf); else buf[0]=0; return NULL;}
  232.     bf[lc]=0; _tolinux(bf); return bf;
  233. }
  234.  
  235. /* Get a line in a stored working file.
  236.        * Buffer length is always MAX_LINELEN. */
  237. int wgetline(char buf[], size_t buflen, WORKING_FILE *f)
  238. {
  239.     int i,j; unsigned int n;
  240.     i=f->linepointer; buf[0]=0;
  241.     if(i>=f->linecnt || f->textbuf==NULL) return EOF;
  242.     n=f->lines[i].llen;
  243.     if(n>=buflen) n=buflen-1;
  244.     if(n>0) memmove(buf,f->lines[i].address,n); buf[n]=0;
  245.     for(j=i+1;j<f->linecnt && f->lines[j].isstart==0;j++);
  246.     f->l=i; f->linepointer=j;
  247.     if(j>=f->linecnt && n==0) return EOF; else return n;
  248. }
  249.  
  250. int get_cached_file(char *name)
  251. {
  252.     int i,l,flag;
  253.     l=strlen(name); if(l>=127) return -1;
  254.     if(strncmp(module_prefix,module_dir,strlen(module_dir))!=0) flag=8; else flag=0;
  255.     for(i=0;i<mcachecnt;i++) {
  256.       if(flag==mcache[i].nocache && strcmp(name,mcache[i].name)==0) {
  257.           memmove(&m_file,mcache+i,sizeof(WORKING_FILE));
  258.           m_file.nocache|=4;
  259.           return i;
  260.       }
  261.     }
  262.     return -1;
  263. }
  264.  
  265. /* Open a work file. Returns 0 if OK. */
  266. int open_working_file(WORKING_FILE *f, char *fname)
  267. {
  268.     char *p, *q;
  269.     void *vp;
  270.     int i,j,k,laststart,lc[LINE_LIMIT];
  271.  
  272.     f->linecnt=f->linepointer=0;
  273.     f->for_idx=f->nocache=0;
  274.     f->l=-1; f->lines=NULL;
  275.     f->textbuf=readfile(fname,NULL,WORKFILE_LIMIT);
  276.     if(f->textbuf==NULL) return -1;
  277.     p=f->textbuf; if(*p) {
  278.       for(i=0,p--; i<LINE_LIMIT-1 && p!=NULL;p=strchr(p,'\n')) {
  279.           if(i>0) *p=0;
  280.           lc[i++]=(++p-f->textbuf);
  281.       }
  282.     }
  283.     else i=0;
  284.     if(i>=LINE_LIMIT-1) module_error("file_too_long");
  285.     lc[i]=lc[i-1]+strlen(f->textbuf+lc[i-1])+1;
  286.     f->textbuf[lc[i]]=0;
  287.     f->linecnt=i; laststart=0;
  288.     f->for_stack=xmalloc(MAX_FOR_LEVEL*sizeof(FOR_STACK)+(i+1)*sizeof(LINE_STRUCT));
  289.     vp=f->for_stack+MAX_FOR_LEVEL; f->lines=vp;
  290.     for(j=0;j<i;j++) {
  291.       f->lines[j].address=p=(f->textbuf)+lc[j];
  292.       f->lines[j].llen=lc[j+1]-lc[j]-1;
  293.       (f->lines[j]).execcode=(f->lines[j]).varcode=-1;
  294.       if(j==0) goto normal;
  295.       q=f->lines[laststart].address+f->lines[laststart].llen-1;
  296.       if(q>=f->textbuf && *q=='\\') {
  297.           f->lines[laststart].llen+=f->lines[j].llen; *q='\n';
  298.           f->lines[j].isstart=f->lines[j].llen=0;
  299.           memmove(q+1,p,lc[j+1]-lc[j]);
  300.       }
  301.       else {
  302.           normal: for(q=p;myislspace(*q);q++);
  303.           f->lines[j].isstart=1; laststart=j; k=0;
  304.           switch(*q) {
  305.                   /* isstart: bit 1 = start.
  306.                    * bit 2 = exec
  307.                    * bit 3 (4) = label
  308.                    * bit 4 (8) = hard comment (!!)
  309.                    * bit 5 (16) = soft comment (#) */
  310.             case exec_prefix_char: {
  311.                 if(myisalpha(q[1])) f->lines[j].isstart=3;
  312.                 else f->lines[j].isstart=9;
  313.                 k=1; break;
  314.             }
  315.             case label_prefix_char: {f->lines[j].isstart=5; k=1; break;}
  316.             case comment_prefix_char: {f->lines[j].isstart=17; break;}
  317.             default: {f->lines[j].isstart=1; break;}
  318.           }
  319.           if(k && q>p) {f->lines[j].address=q;f->lines[j].llen-=q-p;}
  320.       }
  321.     }
  322.     f->lines[i].isstart=1; f->lines[i].llen=0;
  323.     f->lines[i].address=(f->textbuf)+lc[i];
  324.     mfilecnt++; return 0;
  325. }
  326.  
  327. /* close an earlier opened working file */
  328. void close_working_file(WORKING_FILE *f, int cache)
  329. {
  330.     f->linepointer=f->l=0;
  331.     if(cache && untrust==0 && mcachecnt<MAX_MCACHE && (f->nocache&7)==0) {
  332.       memmove(mcache+mcachecnt,f,sizeof(WORKING_FILE));
  333.       mcachecnt++;
  334.     }
  335.     else if((f->nocache&4)==0) {
  336.       if(f->for_stack!=NULL) free(f->for_stack);
  337.       if(f->textbuf!=NULL) free(f->textbuf);
  338.     }
  339.     f->for_stack=NULL; f->textbuf=NULL; f->linecnt=0;
  340. }
  341.  
  342. void free_mcache(void)
  343. {
  344.     int i;
  345.     untrust=0;
  346.     for(i=mcachecnt-1;i>=0;i--) close_working_file(mcache+i,0);
  347.     mcachecnt=0;
  348. }
  349.  
  350. void cleantmpdir(void);
  351. void user_error_log(char msg[]);
  352.  
  353. void nested_error(char msg[])
  354. {
  355.     fprintf(stderr,"\nNested error! %s\n",msg);
  356.     nph_header(420);
  357.     printf("\r\n\r\nWIMS error processing aborted on nested error.\r\n\r\n%s\r\n",msg);
  358.     delete_pid(); exit(1);
  359. }
  360.  
  361. /* Send an error message to requester and exit.
  362.  * This is for user errors, language-sensitive.
  363.  */
  364. void user_error(char msg[])
  365. {
  366.     char erfname[MAX_FNAME+1];
  367.  
  368.     if(error_status) nested_error(msg);
  369.     error_status=1;
  370.     mkfname(erfname,"%s.%s",user_error_msg_file,lang);
  371.     if(ftest(erfname)!=is_file) internal_error("user_error(): error message file not found.\n\
  372. Bad installation.");
  373.     force_setvar("wims_user_error",msg);
  374.     if(strcmp(msg,"threshold")!=0) user_error_log(msg);
  375.     memmove(module_prefix,".",2);
  376.     if(lastout_file!=-1 && outputing) {
  377.       flushoutput(); close(lastout_file); lastout_file=-1;
  378.     }
  379.     nph_header(450);
  380.     phtml_put_base(erfname,0);
  381.     if(strcmp(msg,"double_click")!=0) delete_pid();
  382.     else {
  383.       cleantmpdir(); flushlog();
  384.     }
  385.     flushoutput(); exit(0);
  386. }
  387.  
  388. void module_error_log(char msg[]);
  389.  
  390. /* Messages for module errors. English only.
  391.  * This is really rudimentary for the time being.
  392.  */
  393. void module_error(char msg[])
  394. {
  395.     int send=0;
  396.     char *p;
  397.     WORKING_FILE mf;
  398.  
  399.     if(error_status) nested_error(msg);
  400.     error_status=1; untrust=0;
  401.     module_error_log(msg);
  402.     nph_header(550);
  403.     printf("Server: %s %s (%s)\r\n", SHORTSWNAME,wims_version,LONGSWNAME);
  404.     p=getvar("wims_main_font");
  405.     if(p!=NULL && *p!=0) printf("Content-type: text/plain; charset=%s\r\n\r\n",p);
  406.     else printf("Content-type: text/plain\r\n\r\n");
  407.     p=getvar(ro_name[ro_module]); if(p==NULL) p="???";
  408.     printf("ERROR.\n\nwims has detected an error in the module '%s'.",p);
  409.     if(m_file.l>=0) printf("\n\nIn file '%s', line %d:",
  410.                      m_file.name,m_file.l+1);
  411.     printf(" %s.\n\n",msg);
  412.     if(open_working_file(&mf,mkfname(NULL,"%s.%s",module_error_msg_file,lang))!=0)
  413.       internal_error("module_error(): error message file not found.");
  414.     while(wgetline(tmplbuf,MAX_LINELEN,&mf)!=EOF) {
  415.       if(tmplbuf[0]!=tag_prefix_char) {
  416.           if(send) {substit(tmplbuf); puts(tmplbuf);}
  417.           continue;
  418.       }
  419.       strip_trailing_spaces(tmplbuf);
  420.       if(tmplbuf[1]==0 || strcmp(msg,tmplbuf+1)==0) send=1;
  421.       else send=0;
  422.     }
  423.     close_working_file(&mf,0);
  424.     outptr=outbuf; delete_pid(); exit(1);
  425. }
  426.  
  427. /* Output kernel routine */
  428. void _output_(char *s)
  429. {
  430.     int l,l2;
  431.     l=strlen(s); output_length+=l;
  432.     if(output_length>=OUTPUT_LENGTH_LIMIT) {
  433.       module_error("output_too_long"); return;
  434.     }
  435.     l2=sizeof(outbuf)-(outptr-outbuf);
  436.     put: if(l<=l2) {
  437.       memmove(outptr,s,l); outptr+=l; return;
  438.     }
  439.     memmove(outptr,s,l2); s+=l2; l-=l2;
  440.     if(lastout_file!=-1) (void)write(lastout_file,outbuf,sizeof(outbuf));
  441.     else fwrite(outbuf,sizeof(outbuf),1,stdout);
  442.     outptr=outbuf; l2=sizeof(outbuf); goto put;
  443. }
  444.  
  445. /* Output with no var. */
  446. void output0(char buf[])
  447. {
  448.     char *p1, *p2, *ps;
  449.     int dynsave;
  450.     if(backslash_insmath) {
  451.      ps=buf; dynsave=instex_usedynamic;
  452.      for(p1=strstr(buf,"\\("); p1; p1=strstr(p2,"\\(")) {
  453.          p2=find_matching(p1+2,')');
  454.          if(p2==NULL) break;
  455.          if(p1>buf && *(p1-1)=='\\') continue;
  456.          *p1=0; if(*(p2-1)=='\\') *(p2-1)=0; *p2++=0; _output_(ps); ps=p2;
  457.          instex_usedynamic=1; insmath(p1+2);
  458.      }
  459.      if(*ps) _output_(ps); instex_usedynamic=dynsave;
  460.     }
  461.     else _output_(buf);
  462. }
  463.  
  464. /* Output routine */
  465. void output(char *s,...)
  466. {
  467.     va_list vp;
  468.     char buf[4*MAX_LINELEN+1];
  469.  
  470.     va_start(vp,s);
  471.     vsnprintf(buf,sizeof(buf),s,vp);
  472.     va_end(vp);
  473.     output0(buf);
  474. }
  475.  
  476. /* read in tmpf in tmp directory, and places in p.
  477.  * Maximal length: MAX_LINELEN.
  478.  */
  479. void read_tmp_file(char *p, const char *fname)
  480. {
  481.     char *name, *pp;
  482.     name=mkfname(NULL,"%s/%s",tmp_dir,fname);
  483.     if(!exec_is_module || !outputing || !direct_exec
  484.        || strcmp(fname,"exec.out")!=0) {
  485.       readfile(name,p,MAX_LINELEN);
  486.       pp=getvar("wims_exec_dollar_double");
  487.       if(pp && strcmp(pp,"yes")==0) {
  488.           for(pp=strchr(p,'$'); pp; pp=strchr(pp+2,'$'))
  489.             string_modify(p,pp,pp+1,"$$");
  490.       }
  491.     }
  492.     else {
  493.       char *s;
  494.       s=readfile(name,NULL,OUTPUT_LENGTH_LIMIT);
  495.       if(s==NULL) {*p=0; return;}
  496.       if(memcmp(s,"Error: ", strlen("Error: "))==0) mystrncpy(p,s,MAX_LINELEN);
  497.       output_length+=strlen(s);
  498.       if(output_length>=OUTPUT_LENGTH_LIMIT) module_error("output_too_long");
  499.       else _output_(s);
  500.       free(s); *p=0;
  501.       chmod(name,S_IRUSR|S_IWUSR);
  502.     }
  503. }
  504.  
  505. /* verify whether the module is trusted.
  506.  * Returns 1 if yes, 0 if no. -1 for error.
  507.  */
  508. int trusted_module(void)
  509. {
  510.     char *modname, *w, buf[MAX_LINELEN+1];
  511.     int i,n;
  512.     static int _trusted=-1;      /* avoid repeated computations */
  513.  
  514.     if(untrust&255) return 0;
  515.     if(_trusted>=0) return _trusted;
  516.     modname=getvar(ro_name[ro_module]);
  517.     if(modname==NULL || *modname==0) return 0;
  518.     if(memcmp(modname,"adm/",strlen("adm/"))==0 ||
  519.        memcmp(modname,"classes/",strlen("classes/"))==0 ||
  520.        strcmp(modname,home_module)==0 ||
  521.        memcmp(modname,"help/",strlen("help/"))==0) {
  522.       tr:
  523.       if(memcmp(modname,"classes/",strlen("classes/"))==0)
  524.         is_class_module=1;
  525.       setenv("trusted_module","yes",1);
  526.       return _trusted=1;
  527.     }
  528.     n=wordnum(trusted_modules); for(i=0;i<n;i++) {
  529.       w=fnd_word(trusted_modules,i+1,buf);
  530.       if(strcmp(w,modname)==0) goto tr;
  531.     }
  532.     return _trusted=0;
  533. }
  534.  
  535. /* file should be in the module directory, but
  536.  * it may also be somewhere else.
  537.  * buf[] requires MAX_FNAME+1 length.
  538.  * Returns 0 if found.
  539.  */
  540. int find_module_file(char *fname, char buf[], int mode)
  541. {
  542.     char *p, dtest[32];
  543.  
  544.     fname=find_word_start(fname);
  545.     if(*fname==0) return -1;
  546. /* Name checking: no directory backtracing. */
  547.     if(strstr(fname,parent_dir_string)!=NULL) {
  548.       setvar(error_data_string,fname); module_error("illegal_fname");
  549.       return -1;
  550.     }
  551.     p=strchr(fname,'/'); if(p==NULL || p>fname+10) goto openit;
  552.     memmove(dtest,fname,p-fname); dtest[p-fname]=0;
  553.     if(strcmp(dtest,"datamodule")==0) {
  554.       mkfname(buf,"modules/data%s",p); goto lastopen;
  555.     }
  556.     if(strcmp(dtest,"wimshome")==0 && trusted_module()) {
  557.       mkfname(buf,"%s%s",getvar("wims_home"),p); goto lastopen;
  558.     }
  559.     if(strcmp(dtest,"writable")==0) {
  560.       if(strncmp(p+1,"TEMP_",5)==0 && strchr(p+1,'/')==NULL) {
  561.           mkfname(buf,"%s/%s",tmp_dir,p+1);
  562.       }
  563.       else {
  564.           mkfname(buf,"w/%s/%s",module_prefix,p+1);
  565.       }
  566.       untrust|=4;
  567.     }
  568.     else {
  569.       openit: mkfname(buf,"%s/%s",module_prefix,fname);
  570.     }
  571.     if(mode) return 0;
  572.     if(ftest(buf)!=is_file) {
  573.       if(lastftype==is_exec) {
  574. isexec:
  575.           setvar("executable",fname); module_error("executable");
  576.           return -1;
  577.       }
  578.       if(strncmp(fname,"adm/",4)==0 &&
  579.          (!trusted_module() || is_class_module)) return -1;
  580.       mkfname(buf,"scripts/%s",fname);
  581.       lastopen:
  582.       if(mode) return 0;
  583.       if(ftest(buf)!=is_file) {
  584.           if(lastftype==is_exec) goto isexec;
  585.           else return -1;
  586.       }
  587.     }
  588.     return 0;
  589. }
  590.  
  591. /* check whether a file is user-submitted
  592.  * This is deprecated because of the wimshome/ method.
  593.  */
  594. /* int user_file(char *name) {
  595.     if(name[0]=='/' || name[0]=='.' ||
  596.        strstr(name,"classes/")!=NULL ||
  597.        strstr(name,"forums/")!=NULL ||
  598.        strstr(name,"sessions/")!=NULL ||
  599.        strstr(name,"doc/")!=NULL) return 1; else return 0;
  600. }
  601.  */
  602.  
  603. /* returns 1 if violation */
  604. int datafile_check(char *name) {
  605.     if((untrust&255)==0) return 0;
  606.     if(strncmp(name,"data/",strlen("data/"))==0) return 0;
  607.     if(strncmp(name,"authors/",strlen("authors/"))==0) return 0;
  608.     if(strncmp(name,"datamodule/",strlen("datamodule/"))==0) return 0;
  609.     return 1;
  610. }
  611.  
  612. /* returns 0 if success */
  613. void readdatafile(char *name)
  614. {
  615.     char *pp;
  616.     if(strcmp(name,lastdatafile)==0) return;
  617.     lastdata[0]=0; readfile(name,lastdata,WORKFILE_LIMIT);
  618.     mystrncpy(lastdatafile,name,sizeof(lastdatafile));
  619.     datacache[0]=lastdata; nextdatacache=1;
  620.     if(lastdata[0]==tag_string[1]) {
  621.       datacache[1]=lastdata; nextdatacache++;
  622.     }
  623.     pp=strstr(lastdata,tag_string);
  624.     if(pp) datacache[nextdatacache]=pp;
  625.     else datacache[nextdatacache]=lastdata+strlen(lastdata);
  626. }
  627.  
  628. char *_nextdata(char *p)
  629. {
  630.     char *pp;
  631.     if(!*p) return p;
  632.     pp=strstr(p,tag_string);
  633.     if(pp) return pp;
  634.     else return p+strlen(p);
  635. }
  636.  
  637. /* datafile structure: number of records.
  638.  * tag=1 if direct access
  639.  */
  640. unsigned int datafile_recordnum(char *p)
  641. {
  642.     char nbuf[MAX_LINELEN+1], *pp;
  643.     int i, t, ret;
  644.  
  645.     t=untrust; ret=0;
  646.     if(direct_datafile) mystrncpy(nbuf,p,sizeof(nbuf));
  647.     else if(datafile_check(p)!=0 || find_module_file(p,nbuf,0)) goto ret;
  648.     readdatafile(nbuf);
  649.     for(i=nextdatacache, pp=datacache[i]; *pp;) {
  650.       pp=_nextdata(pp+1); i++;
  651.       if(i<DATAFIELD_LIMIT) {
  652.           datacache[i]=pp; nextdatacache=i;
  653.       }
  654.     }
  655.     ret=i-1;
  656.     ret:
  657.     untrust=t;
  658.     return ret;
  659. }
  660.  
  661. /* datafile structure: find record n, starting from 1 */
  662. char *datafile_fnd_record(char *p, int n, char bf[])
  663. {
  664.     char nbuf[MAX_LINELEN+1], *pp, *p2;
  665.     int i, t;
  666.  
  667.     bf[0]=0; t=untrust;
  668.     if(n<0) goto ret;
  669.     if(direct_datafile) mystrncpy(nbuf,p,sizeof(nbuf));
  670.     else if(datafile_check(p)!=0 || find_module_file(p,nbuf,0)) goto ret;
  671.     readdatafile(nbuf); if(*lastdata==0) goto ret;
  672.     if(n>nextdatacache) {
  673.       for(i=nextdatacache, pp=datacache[i]; i<n && *pp;) {
  674.           pp=_nextdata(pp+1); i++;
  675.           if(i<DATAFIELD_LIMIT) {
  676.             datacache[i]=pp; nextdatacache=i;
  677.           }
  678.       }
  679.     }
  680.     else pp=datacache[n];
  681.     if(!*pp) goto ret;
  682.     if(n>1 || (n==1 && *pp!=tag_string[1])) pp+=strlen(tag_string);
  683.     else if(n==1) pp+=strlen(tag_string)-1;
  684.     if(n<nextdatacache) p2=datacache[n+1];
  685.     else {
  686.       p2=strstr(pp,tag_string); if(p2==NULL) p2=pp+strlen(pp);
  687.       if(n<DATAFIELD_LIMIT-1 && n==nextdatacache) {
  688.           nextdatacache++; datacache[nextdatacache]=p2;
  689.       }
  690.     }
  691.     if(p2-pp>=MAX_LINELEN) p2=pp+MAX_LINELEN-1;
  692.     if(p2<pp) p2=pp;
  693.     memmove(bf,pp,p2-pp); bf[p2-pp]=0;
  694.     ret:
  695.     untrust=t; return bf;
  696. }
  697.  
  698. char hex2char(char c1, char c2)
  699. {
  700.     char tbuf[16];
  701.     if(c1<'0' || c1>'f' || c2<'0' || c2>'f') {
  702. invl:
  703.       snprintf(tbuf,sizeof(tbuf),"%%%c%c",c1,c2);
  704.       setvar(error_data_string,tbuf);
  705.       user_error("invalid_char_in_query_string");
  706.     }
  707.     c1=toupper(c1);c2=toupper(c2);
  708.     if(c1>'9' && c1<'A') goto invl;
  709.     if(c2>'9' && c2<'A') goto invl;
  710.     if(c1>'F' || c2>'F') goto invl;
  711.     if(c1>='A') c1=c1-'A'+'9'+1;
  712.     if(c2>='A') c2=c2-'A'+'9'+1;
  713.     return (c1-'0')*16+c2-'0';
  714. }
  715.  
  716. /* Converts back http escaped chars, slight. Does not check buffer length.
  717.  * Returns converted string length.
  718.  */
  719. int _http2env(char outs[], char ins[])
  720. {
  721.     int j,k,l;
  722.     l=strlen(ins);
  723.     for(j=k=0;j<l && !isspace(ins[j]);j++,k++) {
  724.       if(isspace(ins[j])) {  /* skip space characters in query string */
  725.           k--;continue;
  726.       }
  727.       if(ins[j]=='%') {
  728. /* skip Carriage-Return. */
  729.           if(ins[j+1]=='0' && (ins[j+2]=='d' || ins[j+2]=='D')) {
  730.             j+=2; k--; continue;
  731.           }
  732.           outs[k]=hex2char(ins[j+1],ins[j+2]);
  733.           j+=2; continue;
  734.       }
  735.       outs[k]=ins[j];
  736.     }
  737.     outs[k]=0;
  738.     return k;
  739. }
  740.  
  741. /* Converts back http escaped chars. Does not check buffer length.
  742.  * Returns converted string length.
  743.  */
  744. int http2env(char outs[], char ins[])
  745. {
  746.     int j,k,l;
  747.     l=strlen(ins);
  748.     for(j=k=0;j<l && !isspace(ins[j]);j++,k++) {
  749.       if(isspace(ins[j])) {  /* skip space characters in query string */
  750.           k--;continue;
  751.       }
  752.       if(ins[j]=='%') {
  753. /* skip Carriage-Return. */
  754.           if(ins[j+1]=='0' && (ins[j+2]=='d' || ins[j+2]=='D')) {
  755.             j+=2; k--; continue;
  756.           }
  757.           outs[k]=hex2char(ins[j+1],ins[j+2]);
  758.           j+=2; continue;
  759.       }
  760.       if(ins[j]=='+') {
  761.           outs[k]=' '; continue;
  762.       }
  763.       if(ins[j]=='?' || ins[j]=='&') {
  764.           outs[k]=0; continue;
  765.       }
  766.       outs[k]=ins[j];
  767.     }
  768.     outs[k]=0;
  769.     return k;
  770. }
  771.  
  772. /* translate a string to http querystring style.
  773.  * '&' is not translated.
  774.  * Buffer p must be at least MAX_LINELEN.
  775.  */
  776. void tohttpquery(char *p)
  777. {
  778.     char trlist[]="     ()[]{}+-*^|/\"\'!:;,<>\n";
  779.     char *pp;
  780.     for(pp=p;*pp;pp++) {
  781.       if(*pp==' ') {
  782.           *pp='+'; continue;
  783.       }
  784.       if(strchr(trlist,*pp)==NULL) continue;
  785.       if(*pp=='+' && pp>p && *(pp-1)=='&') continue;
  786.       if(pp>p && *(pp-1)=='\\') {
  787.           ovlstrcpy(pp-1,pp);pp--;continue;
  788.       }
  789.       if(*pp=='\n') {
  790.           string_modify(p,pp,pp+1,"%%0D%%0A");pp+=5;
  791.       }
  792.       else {
  793.           string_modify(p,pp,pp+1,"%%%02X",*pp);pp+=2;
  794.       }
  795.     }
  796. }
  797.  
  798. /* substitute backslash parameters. Internal use only. */
  799. void slashsubst(char *p)
  800. {
  801.     char *p1, *p2, *pt, *pp, namebuf[128];
  802.     int n;
  803.  
  804.     n=strlen(mathfont_prefix); memmove(namebuf,mathfont_prefix,n+1);
  805.     for(p1=strchr(p,'\\'); p1!=NULL; p1=strchr(p1,'\\')) {
  806.       p1++; for(p2=p1; myisalnum(*p2) || *p2=='_'; p2++);
  807.       if(p2<=p1 || p2>p1+100) continue;
  808.       memmove(namebuf+n,p1,p2-p1); namebuf[p2-p1+n]=0;
  809.       pt=_getvar(namebuf); if(pt==NULL) continue;
  810.       if(*p2=='[' && (pp=find_matching(p2+1,']'))!=NULL) {
  811.           string_modify(p,pp+1,pp+1,")");
  812.           string_modify(p,p1-1,p1,"$(%s",mathfont_prefix);
  813.       }
  814.       else string_modify(p,p1-1,p1,"$%s",mathfont_prefix);
  815.     }
  816. }
  817.  
  818. /* two alarm handlers. */
  819. void alarm1(int s)
  820. {
  821.     if(killpid>0 && kill(killpid,SIGKILL)) module_error("timeup");
  822.     killpid=0;
  823. }
  824.  
  825. void alarm2(int s)
  826. {
  827.     cleantmpdir();
  828.     alarm1(s); module_error("timeup");
  829. }
  830.  
  831. void finalalarm(void)
  832. {
  833.     time_t curr;
  834.     curr=time(0);
  835.     if(curr>=limtime) alarm2(SIGALRM);
  836.     errno=0;
  837.     if(signal(SIGALRM,alarm2)==SIG_ERR)
  838.       internal_error(strerror(errno));
  839.     alarm(limtime-curr+1);
  840. }
  841.  
  842. void initalarm(void)
  843. {
  844.     limtimex=nowtime+4*rlimit_cpu/3;
  845.     limtime=limtimex+2; finalalarm();
  846. }
  847.  
  848. void forkalarm(void)
  849. {
  850.     time_t curr;
  851.     curr=time(0);
  852.     if(curr>=limtimex) {alarm1(SIGALRM); return;}
  853.     if(signal(SIGALRM,alarm1)==SIG_ERR)
  854.       internal_error(strerror(errno));
  855.     alarm(limtimex-curr+1);
  856. }
  857.  
  858. /* create pid tag */
  859. void create_pid(void)
  860. {
  861.     char buf[MAX_FNAME+1], pbuf[256], obuf[MAX_FNAME+1];
  862.     struct stat dst;
  863.     struct utimbuf ub;
  864.  
  865.     if(robot_access || *session_prefix==0) return;
  866.     if(cmd_type==cmd_getframe) return;
  867.     mkfname(buf,"%s/.pid",s2_prefix);
  868. /* another process running? */
  869.     if(readfile(buf,pbuf,sizeof(pbuf))!=NULL) {
  870.       mkfname(obuf,"/proc/%s",pbuf);
  871.       if(stat(obuf,&dst)==0) user_error("double_click");
  872.     }
  873.     snprintf(pidbuf,sizeof(pidbuf),"%u",getpid());
  874.     accessfile(pidbuf,"w","%s",buf);
  875. /* Touch session time */
  876.     if(strstr(session_prefix,"sessions/")==NULL) return;
  877.     ub.actime=ub.modtime=nowtime;
  878.     utime(session_prefix,&ub);
  879.     if(strchr(session_prefix,'_')!=NULL) { /* touch parent too */
  880.       char sbuf[MAX_FNAME+1], *p;
  881.       mystrncpy(sbuf,session_prefix,sizeof(sbuf));
  882.       p=strchr(sbuf,'_'); if(p!=NULL) *p=0;
  883.       utime(sbuf,&ub);
  884.     }
  885. }
  886.  
  887. struct mxtab mxtab[MAX_MULTIEXEC];
  888. int mxno=0;
  889.  
  890. int execredirected(char *cmdf, char *inf, char *outf, char *errf, char *arg[])
  891. {
  892.     pid_t pid;
  893.     int status, t;
  894.  
  895.     if(robot_access) return 0;
  896.     if(time(0)>=limtimex) {
  897.       if(errf!=NULL)
  898.         accessfile("No time left to execute subprograms.\n","w","%s",errf);
  899.       return -100;
  900.     }
  901.     lastdatafile[0]=lastftest[0]=0;
  902.     fflush(NULL); /* flush all output streams before forking
  903.                    * otherwise they will be doubled
  904.                    */
  905.     pid=fork(); if(pid==-1) return -1;
  906.     if(!pid) {      /* child */
  907.       char buf[MAX_LINELEN+1]; int k;
  908.       (void)nice(10);      /* lower priority for children */
  909.       if(is_multiexec) {
  910.           dup2(mxtab[multiexec_index].pipe_stdin[0],0);
  911.           dup2(mxtab[multiexec_index].pipe_stdout[1],1);
  912.           dup2(mxtab[multiexec_index].pipe_stderr[1],2);
  913.       }
  914.       else {
  915.           if(inf!=NULL) (void)freopen(inf,"r",stdin);
  916.           if(outf!=NULL) (void)freopen(outf,"w",stdout);
  917.           if(errf!=NULL) (void)freopen(errf,"w",stderr);
  918.       }
  919. /* This is to patch LinuxPPC uid wrapping
  920.  * for scripts */
  921.       t=0; if(strchr(cmdf,'/')) {
  922.           int tf;
  923.           char tbuf[16];
  924.           tf=open(cmdf,O_RDONLY); (void)read(tf,tbuf,8); close(tf);
  925.           if(memcmp(tbuf+1,"ELF",3)!=0) t=1;
  926.       }
  927.       if(wrapexec==-1) {
  928.           setreuid(getuid(),getuid());setregid(getgid(),getgid());
  929.       }
  930.       if(wrapexec==1 || (t==1 && wrapexec==0)) {
  931.           setreuid(geteuid(),geteuid());setregid(getegid(),getegid());
  932.       }
  933.       errno=0;
  934.       if(strchr(cmdf,'/')) execve(cmdf,arg,environ);
  935.       else execvp(cmdf,arg);
  936.       snprintf(buf,sizeof(buf),"Failed to execute");
  937.       for(k=0;arg[k];k++) {
  938.           t=strlen(buf);
  939.           snprintf(buf+t,sizeof(buf)-t," %s",arg[k]);
  940.       }
  941.       t=strlen(buf);
  942.       snprintf(buf+t,sizeof(buf)-t,"\n  %s\n",strerror(errno));
  943.       accessfile(buf,"a","%s/exec.fail",tmp_dir);
  944.       exit(127);
  945.     }
  946.     else {      /* parent */
  947.       wrapexec=0; status=0;
  948.       if(exec_wait && !is_multiexec) {
  949.           killpid=pid; forkalarm();
  950.           waitpid(pid,&status,0); killpid=0; finalalarm();
  951.       }
  952.       return WEXITSTATUS(status);
  953.     }
  954. }
  955.  
  956. /* preparation for resident execution.
  957.  * Returns 1 if already up, otherwise 0.
  958.  */
  959. int multiexec(char *cmd, char **abuf)
  960. {
  961.     char *p;
  962.     int i;
  963.  
  964.     if(robot_access) return 0;
  965.     if(strstr(tmp_dir,"sessions/")==NULL) return 0;
  966.     if(strstr(tmp_debug,"yes")!=NULL && checkhost(manager_site)>=1)
  967.       setenv("multiexec_debug","yes",1);
  968.     p=getvar("wims_multiexec");
  969.     if(p==NULL || wordchr(p,cmd)==NULL) return 0; /* not allowed */
  970.     if(!multiexec_random[0]) {
  971.       snprintf(multiexec_random, sizeof(multiexec_random),
  972.              "%lX%lX%lX%lX%lX%lX%lX%lX",
  973.              random(),random(),random(),random(),
  974.              random(),random(),random(),random());
  975.       setenv("multiexec_random",multiexec_random,1);
  976.     }
  977.     for(i=0;i<mxno && strcmp(cmd,mxtab[i].cmd)!=0; i++);
  978.     multiexec_index=i;
  979.     if(i==mxno) {
  980.       if(mxno>=MAX_MULTIEXEC) return 0;
  981.       if(pipe(mxtab[i].pipe_stdin)<0) return 0;
  982.       if(pipe(mxtab[i].pipe_stdout)<0) return 0;
  983.       if(pipe(mxtab[i].pipe_stderr)<0) return 0;
  984.       mystrncpy(mxtab[i].cmd,cmd,sizeof(mxtab[i].cmd));
  985.       mxno++;      is_multiexec=1;
  986.       exportall(); setenv("wims_exec_parm",multiexec_random,1);
  987.       execredirected(abuf[0],NULL,NULL,NULL,abuf);
  988.     }
  989.     is_multiexec=0;
  990.     return 1;
  991. }
  992.  
  993. /* my system(), but with variable parms
  994.  * More secure than system(), and direct fork.
  995.  */
  996. int call_ssh(char *s,...)
  997. {
  998.     va_list vp;
  999.     char buf[MAX_LINELEN+1];
  1000.     char *arg[1024];
  1001.     char *inf=NULL, *outf=NULL, *errf=NULL;
  1002.     char *cmdf, *p, *p2;
  1003.     int i, d;
  1004.  
  1005.     if(robot_access) return 0;
  1006.     va_start(vp,s);
  1007.     vsnprintf(buf,sizeof(buf),s,vp);
  1008.     va_end(vp);
  1009.     p=find_word_start(buf); if(*p==0) return 0;
  1010.     cmdf=p;
  1011.     for(i=0;*p!=0 && i<1000; p=find_word_start(p2)) {
  1012.       switch(*p) {
  1013.           case '\'': {
  1014.             p++; p2=strchr(p,'\''); if(p2==NULL) p2=p+strlen(p);
  1015.             d=0; break;
  1016.           }
  1017.           case '"': {
  1018.             p++; p2=strchr(p,'"'); if(p2==NULL) p2=p+strlen(p);
  1019.             d=0; break;
  1020.           }
  1021.           default: d=1; p2=find_word_end(p); break;
  1022.       }
  1023.       if(*p2) *p2++=0;
  1024.       if(!d) {arg[i++]=p; continue;}
  1025.       switch(*p) {
  1026.           case '<': inf=++p; break;
  1027.           case '>': {
  1028.             p++; if(*p=='&') {
  1029.                 merge: p++; errf=outf=p; break;
  1030.             }
  1031.             else outf=p;
  1032.             break;
  1033.           }
  1034.           case '&': {
  1035.             p++; if(*p=='>') goto merge;
  1036.             else break;
  1037.           }
  1038.           case '2': {
  1039.             if(*(p+1)=='>') {errf=p+2; break;}
  1040.           }
  1041.           default: arg[i++]=p; break;
  1042.       }
  1043.     }
  1044.     arg[i]=NULL;
  1045.     return execredirected(cmdf,inf,outf,errf,arg);
  1046. }
  1047.  
  1048. /* Read/write to a file with variable parms to print filename */
  1049. void accessfile(char *content, char *type, char *s,...)
  1050. {
  1051.     va_list vp;
  1052.     char buf[MAX_FNAME+1];
  1053.     int fd;
  1054.  
  1055.     if(robot_access) return;
  1056.     va_start(vp,s);
  1057.     vsnprintf(buf,sizeof(buf),s,vp);
  1058.     va_end(vp);
  1059.     if(strlen(buf)>=MAX_FNAME-1) nametoolong(buf);
  1060.     switch(*type) {
  1061.       case 'r': readfile(buf,content,MAX_LINELEN); return;
  1062.       case 'e': readfile(buf,content,MAX_LINELEN/4); return; /* limited read */
  1063.       case 'w': fd=creat(buf,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); break;
  1064.       case 'a': fd=open(buf,O_WRONLY|O_CREAT|O_APPEND,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); break;
  1065.       default : return;
  1066.     }
  1067.     lastdatafile[0]=lastftest[0]=0;
  1068.     if(fd==-1) return;
  1069.     (void)write(fd,content,strlen(content)); close(fd);
  1070. }
  1071.  
  1072. /* system(), but with variable parms
  1073.  * Uses sh to execute command.
  1074.  */
  1075. int call_sh(char *s,...)
  1076. {
  1077.     va_list vp;
  1078.     char buf[MAX_LINELEN+1];
  1079.     char *abuf[8];
  1080.  
  1081.     if(robot_access) return 0;
  1082.     va_start(vp,s);
  1083.     vsnprintf(buf,sizeof(buf),s,vp);
  1084.     va_end(vp);
  1085.     abuf[0]="sh"; abuf[1]="-c"; abuf[2]=buf; abuf[3]=NULL;
  1086.     return execredirected(abuf[0],NULL,NULL,NULL,abuf);
  1087. }
  1088.  
  1089. void _getdef(char buf[], char *name, char value[])
  1090. {
  1091.     char *p1, *p2, *p3, *p4;
  1092.  
  1093.     if(*name==0) goto nothing;      /* this would create segfault. */
  1094.     for(p1=strstr(buf,name); p1!=NULL; p1=strstr(p1+1,name)) {
  1095.       p2=find_word_start(p1+strlen(name));
  1096.       if((p1>buf && !isspace(*(p1-1))) || *p2!='=') continue;
  1097.       p3=p1; while(p3>buf && *(p3-1)!='\n') p3--;
  1098.       p3=find_word_start(p3);
  1099.       if(p3<p1 && *p3!='!') continue;
  1100.       if(p3<p1) {
  1101.           p3++; p4=find_word_end(p3);
  1102.           if(find_word_start(p4)!=p1) continue;
  1103.           if(p4-p3!=3 || (strncmp(p3,"set",3)!=0 &&
  1104.              strncmp(p3,"let",3)!=0 &&
  1105.              strncmp(p3,"def",3)!=0)) {
  1106.             if(p4-p3!=6 || strncmp(p3,"define",6)!=0) continue;
  1107.           }
  1108.       }
  1109.       p2++;p3=strchr(p2,'\n'); if(p3==NULL) p3=p2+strlen(p2);
  1110.       p2=find_word_start(p2);
  1111.       if(p2>p3) goto nothing;
  1112.       if(p3-p2>=MAX_LINELEN) user_error("cmd_output_too_long");
  1113.       memmove(value,p2,p3-p2); value[p3-p2]=0;
  1114.       strip_trailing_spaces(value); return;
  1115.     }
  1116. nothing:
  1117.     value[0]=0; return;
  1118. }
  1119.  
  1120. /* Get variable definition from a file.
  1121.  * Result stored in buffer value of length MAX_LINELEN.
  1122.  */
  1123. void getdef(char *fname, char *name, char value[])
  1124. {
  1125.     char buf[MAX_LINELEN+1], tbuf[MAX_LINELEN+1], nbuf[MAX_NAMELEN+1];
  1126.     char *p1, *p2;
  1127.  
  1128.     value[0]=0; if(readfile(fname,buf,sizeof(buf)-16)==NULL) return;
  1129.     mystrncpy(value,name,MAX_LINELEN);
  1130.     for(p1=value; *p1; p1=p2) {
  1131.       while(*p1 && !myisalnum(*p1) && *p1!='_') p1++;
  1132.       if(*p1==0) break;
  1133.       for(p2=p1; myisalnum(*p2) || *p2=='_'; p2++);
  1134.       if(p2-p1>MAX_NAMELEN) continue;
  1135.       memmove(nbuf,p1,p2-p1); nbuf[p2-p1]=0;
  1136.       _getdef(buf,nbuf,tbuf);
  1137.       string_modify(value,p1,p2,"%s",tbuf);
  1138.       p2=p1+strlen(tbuf);
  1139.     }
  1140. }
  1141.  
  1142. int _setdef_changed;
  1143.  
  1144. void _setdef(char buf[], char *name, char *value)
  1145. {
  1146.     char *p1, *p2, *p3;
  1147.     int n;
  1148.  
  1149.     for(p1=strstr(buf,name); p1!=NULL; p1=strstr(p1+1,name)) {
  1150.       p2=find_word_start(p1+strlen(name));
  1151.       if((p1>buf && !isspace(*(p1-1))) || *p2!='=') continue;
  1152.       p3=p1; while(p3>buf && *(p3-1)==' ') p3--;
  1153.       if(p3>buf && *(p3-1)!='\n') continue;
  1154.       p2++;p3=strchr(p2,'\n'); if(p3==NULL) p3=p2+strlen(p2);
  1155.       if(strlen(value)!=p3-p2 || strncmp(value,p2,p3-p2)!=0) {
  1156.           string_modify(buf,p2,p3,"%s",value);
  1157.           _setdef_changed++;
  1158.       }
  1159.       return;
  1160.     }
  1161.     n=strlen(buf);
  1162.     if(n>0 && buf[n-1]!='\n')
  1163.       snprintf(buf+n,MAX_LINELEN-n,"\n%s=%s\n",name,value);
  1164.     else
  1165.       snprintf(buf+n,MAX_LINELEN-n,"%s=%s\n",name,value);
  1166.     _setdef_changed++;
  1167. }
  1168.  
  1169. /* Set variable definition to a file. */
  1170. void setdef(char *fname, char *name)
  1171. {
  1172.     char buf[MAX_LINELEN+1];
  1173.     char *p1, *p2, *p3;
  1174.  
  1175.     _setdef_changed=0;
  1176.     if(strchr(name,'=')==NULL) return;
  1177.     for(p1=name;*p1;p1++) {
  1178.       if(isspace(*p1) && *p1!=' ' && *p1!='\n') *p1=' ';
  1179.       if(*p1==' ') {
  1180.           for(p2=p1+1; isspace(*p2) && *p2!='\n'; p2++);
  1181.           if(p2>p1+1) ovlstrcpy(p1+1,p2);
  1182.           p2=p1+1; if(*p2=='=' || *p2=='\n') ovlstrcpy(p1,p2);
  1183.       }
  1184.     }
  1185.     if(readfile(fname,buf,sizeof(buf))==NULL) buf[0]=0;
  1186.     for(p1=find_word_start(name); p1!=NULL; p1=p2) {
  1187.       p2=strchr(p1,'\n'); if(p2!=NULL) *p2++=0;
  1188.       p1=find_word_start(p1);
  1189.       p3=strchr(p1,'='); if(p3==NULL) continue;
  1190.       *p3++=0; p3=find_word_start(p3);
  1191.       _setdef(buf,p1,p3);
  1192.     }
  1193.     if(_setdef_changed) accessfile(buf,"w","%s",fname);
  1194. }
  1195.  
  1196. /* check whether connecting host is part of given list.
  1197.  * Returns 0 if no, 1 if yes.
  1198.  */
  1199. int checkhost(char *hlist)
  1200. {
  1201.     char buf[MAX_LINELEN+1];
  1202.     char lbuf[1024], hbuf1[256], hbuf2[256];
  1203.     char *p1, *p2, *pb, *pe, *pp;
  1204.  
  1205.     if(*remote_addr==0) return 0;
  1206.     snprintf(hbuf1,sizeof(hbuf1),"+%s+",remote_addr);
  1207.     if(*remote_host!=0) {
  1208.       snprintf(hbuf2,sizeof(hbuf2),"+%s+",remote_host);
  1209.       for(p1=hbuf2; *p1; p1++) *p1=tolower(*p1);
  1210.     }
  1211.     else hbuf2[0]=0;
  1212.     mystrncpy(buf,find_word_start(hlist),sizeof(buf)); strip_trailing_spaces(buf);
  1213.     for(p1=buf; *p1; p1++) {
  1214.       *p1=tolower(*p1);
  1215.       if(!myisalnum(*p1) && strchr(".-_",*p1)==NULL) *p1=' ';
  1216.     }
  1217.     if(strcmp(buf,"all")==0) return 1;      /* all is all */
  1218.     for(p1=find_word_start(buf); *p1; p1=find_word_start(p2)) {
  1219.       p2=find_word_end(p1); if(*p2) *p2++=0;
  1220.       if(p2-p1<3) continue;
  1221.       if(myisalnum(*p1)) pb="+"; else pb="";
  1222.       if(myisalnum(*(p2-1))) pe="+"; else pe="";
  1223.       snprintf(lbuf,sizeof(lbuf),"%s%s%s",pb,p1,pe);
  1224.       for(pp=p1; *pp && (myisdigit(*pp) || *pp=='.'); pp++);
  1225.       if(*pp) pp=hbuf2;      /* host name */
  1226.       else pp=hbuf1;         /* ip number */
  1227.       if(strstr(pp,lbuf)!=NULL) return 1;      /* found */
  1228.     }
  1229.     return 0;
  1230. }
  1231.  
  1232. /* return 1 if a word of bf2 is a substring of host.
  1233.  * Like checkhost, but with time check.
  1234.  * The content of bf2[] is destroyed.
  1235.  */
  1236. int checkhostt(char bf2[])
  1237. {
  1238.     char *p1, *p2, *p3;
  1239. /* compare with starting time */
  1240.     for(p1=strchr(bf2,'>'); p1!=NULL; p1=strchr(p1+1,'>')) {
  1241.       if(p1>bf2 && !isspace(*(p1-1))) continue;
  1242.       p3=find_word_start(++p1); p2=find_word_end(p3);
  1243.       if(p2-p3!=14) continue;
  1244.       p3[8]='.'; p3[11]=':'; if(*p2) *p2++=0;
  1245.       if(strncmp(nowstr,p3,14)<0) return 0;
  1246.       ovlstrcpy(p1-1,p2); p1-=2;
  1247.     }
  1248. /* compare with ending time */
  1249.     for(p1=strchr(bf2,'<'); p1!=NULL; p1=strchr(p1+1,'<')) {
  1250.       if(p1>bf2 && !isspace(*(p1-1))) continue;
  1251.       p3=find_word_start(++p1); p2=find_word_end(p3);
  1252.       if(p2-p3!=14) continue;
  1253.       p3[8]='.'; p3[11]=':'; if(*p2) *p2++=0;
  1254.       if(strncmp(nowstr,p3,14)>0) return 0;
  1255.       ovlstrcpy(p1-1,p2); p1-=2;
  1256.     }
  1257.     p1=find_word_start(bf2); if(*p1==0) return 1;
  1258.     return checkhost(p1);
  1259. }
  1260.  
  1261. /* bad identification */
  1262. void bad_ident(void)
  1263. {
  1264.     if(cookiegot[0]!=0) {
  1265.     }
  1266.     user_error("bad_ident");
  1267. }
  1268.  
  1269. void instex_flush(void)
  1270. {
  1271.     char *p;
  1272.     setenv("texgif_style","",1);
  1273.     setenv("texgif_tmpdir",tmp_dir,1);
  1274.     setenv("texgif_src",instex_src,1);
  1275.     setenv("texgif_outfile",instex_fname,1);
  1276.     unsetenv("w_instex_color");
  1277.     getwimstexsize=0; fix_tex_size(); getwimstexsize=1;
  1278.     for(p=instex_fname;*p;p++) if(*p=='\n') *p=' ';
  1279.     wrapexec=0; call_ssh("%s/%s >%s/ins.Out 2>%s/ins.Err",
  1280.                    bin_dir,instex_processor,
  1281.                    tmp_dir,tmp_dir);
  1282.     call_ssh("mv %s %s >/dev/null 2>/dev/null", instex_fname,s2_prefix);
  1283.     instex_src[0]=instex_fname[0]=0; instex_cnt=0;
  1284. }
  1285.  
  1286. /* put last.phtml */
  1287. void putlastout(void)
  1288. {
  1289.     int t;
  1290.     if(instex_cnt>0) instex_flush();
  1291.     t=catfile(stdout,"%s/%s",s2_prefix,lastout);
  1292.     if(t==0) printf("Content-type: text/plain\r\n\r\n");
  1293. }
  1294.  
  1295. struct sockaddr_un sun;
  1296.  
  1297. /* returns >=0 if OK. */
  1298.  
  1299. int kerneld(char *p, int bufsize)
  1300. {
  1301.     int sock, s, t, t1, l, *ip;
  1302.     struct timeval tv;
  1303.     fd_set rset;
  1304.     sock=socket(PF_UNIX,SOCK_STREAM,0);
  1305.     s=connect(sock,(const struct sockaddr *)&sun,sizeof(sun));
  1306.     if(s) {bad: close(sock); return -1;}
  1307.     ip=(int *) p;
  1308.     l=strlen(p+sizeof(int)); *ip=l;
  1309.     s=write(sock,p,l+sizeof(int)); if(s!=l+sizeof(int)) goto bad;
  1310.     for(t=0, l=bufsize-1; t<l+sizeof(int);) {
  1311.       tv.tv_sec=2; tv.tv_usec=0;
  1312.       FD_ZERO(&rset); FD_SET(sock,&rset);
  1313.       if(select(sock+1,&rset,NULL,NULL,&tv)<=0) goto bad;
  1314.       t1=read(sock,p+t,l+sizeof(int)-t);
  1315.       if(t1+t<sizeof(int)) goto bad;
  1316.       if (t1 < 0) goto bad;
  1317.       l=*ip; if(l<=0) goto bad;
  1318.       if(l>=bufsize-sizeof(int)-4) user_error("cmd_output_too_long");
  1319.       t+=t1;
  1320.     }
  1321.     p[l+sizeof(int)]=0;
  1322.     close(sock);
  1323.     return l+sizeof(int);
  1324. }
  1325.  
  1326. void _daemoncmd(char *p)
  1327. {
  1328.     char buf[MAX_LINELEN+1+sizeof(int)];
  1329.     char *p1, *p2, *p3;
  1330.     mystrncpy(buf+sizeof(int),p,sizeof(buf)-sizeof(int));
  1331.     if(kerneld(buf,sizeof(buf))<0)
  1332.       internal_error("Daemon communication error.");
  1333.     p1=find_word_start(buf+sizeof(int));
  1334.     p2=find_word_end(p1); if(*p2) *p2++=0;
  1335.     if(strcmp(p1,"OK")==0) {
  1336.       mystrncpy(p,p2,MAX_LINELEN); return;
  1337.     }
  1338.     p1=find_word_start(p2); p2=find_word_end(p1); if(*p2) *p2++=0;
  1339.     p2=find_word_start(p2); p3=find_word_end(p2);
  1340.     if(*p3) {
  1341.       *p3++=0; p3=find_word_start(p3); strip_trailing_spaces(p3);
  1342.       setvar("wims_error_data",p3);
  1343.     }
  1344.     switch(*p1) {
  1345.       case '1': user_error(p2);
  1346.       case '2': module_error(p2);
  1347.       case '3':
  1348.       default: internal_error(p2);
  1349.     }
  1350.     *p=0;
  1351. }
  1352.  
  1353.