Subversion Repositories wimsdev

Rev

Rev 8155 | Rev 8479 | 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. /* routines to process variables */
  18.  
  19. #include "wims.h"
  20.  
  21. char *computed_var_start; /* pointer to read-in var def file */
  22. int session_var_ready=0;
  23. char last_host[32]="";
  24. char *robotcheck="";
  25.  
  26. char *header_var_name[]={
  27.     "REMOTE_ADDR", "HTTP_REFERER", "QUERY_STRING", "HTTP_USER_AGENT",
  28.      "HTTP_COOKIE"
  29. };
  30. #define HEADER_VAR_NO (sizeof(header_var_name)/sizeof(header_var_name[0]))
  31.  
  32. char *var_allow[]={
  33.     "deny" , "init" , "config" ,
  34.       "reply", "any", "help"
  35. };
  36. enum {
  37.     var_allow_deny, var_allow_init, var_allow_config,
  38.       var_allow_reply, var_allow_any, var_allow_help
  39. } VAR_ALLOWS;
  40. #define VAR_ALLOW_NO (sizeof(var_allow)/sizeof(var_allow[0]))
  41.  
  42. /* install a temporary directory for the session */
  43. void mktmpdir(char *p)
  44. {
  45.     char *base;
  46.     if(p==NULL || *p==0 || strstr(p,"robot")!=NULL) return;
  47.     if(strstr(tmp_dir,"sessions")!=NULL) return;
  48.     if(ftest("../chroot/tmp/sessions/.chroot")==is_file) base="chroot/tmp";
  49.     else base="tmp";
  50.     mkfname(tmp_dir,"../%s/sessions/%s",base,p);
  51.     remove_tree(tmp_dir); mkdirs(tmp_dir);
  52.     chmod(tmp_dir,S_IRUSR|S_IWUSR|S_IXUSR
  53.        |S_IRGRP|S_IWGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH);
  54.     setenv("tmp_dir",tmp_dir,1); setenv("TMPDIR",tmp_dir,1);
  55. }
  56.  
  57. /* Open session variable file */
  58. FILE *fopen_session_var_file(char read_or_write[])
  59. {
  60.     char *nbuf; FILE *f;
  61.  
  62.     nbuf=mkfname(NULL,"%s/var",session_prefix);
  63.     if(read_or_write[0]=='r') {
  64.      if(open_working_file(&m_file,nbuf)!=0) return NULL;
  65.      mkfname(m_file.name,"session_var");
  66.      return stdin;
  67.     }
  68.     f=fopen(nbuf,read_or_write);
  69.     if(f==NULL) {
  70. /* expired_session */
  71.      internal_error("fopen_session_var_file(): unable to create session variable file.");
  72.     }
  73.     mkfname(m_file.name,"session_var");
  74.     m_file.l=0;
  75.     return f;
  76. }
  77.  
  78. /* Open a module file, read only, with name checking.
  79.  * returns NULL if error.
  80.  */
  81. int read_module_file(char *fname)
  82. {
  83.     char nbuf[MAX_FNAME+1];
  84.  
  85.     if(get_cached_file(fname)>=0) return 0;
  86.     if(find_module_file(fname,nbuf,0)) return -1;
  87.     if(open_working_file(&m_file,nbuf)!=0) return -1;
  88.     untrust|=(untrust>>8);
  89.     mystrncpy(m_file.name,fname,sizeof(m_file.name));
  90.     if(strncmp(module_prefix,module_dir,strlen(module_dir))!=0) m_file.nocache|=8;
  91.     return 0;
  92. }
  93.  
  94. int varget[]={ro_module,ro_lang,ro_useropts,ro_worksheet};
  95. #define varget_no (sizeof(varget)/sizeof(varget[0]))
  96.  
  97. /* set up ref strings according to protocol */
  98. void set_protocol(void)
  99. {
  100.     if(strcmp(protocol,"https")!=0) return;
  101.     if(strncmp(ref_name,"http:",5)==0) {
  102.      string_modify(ref_name,ref_name+4,ref_name+4,"s");
  103.      string_modify(ref_base,ref_base+4,ref_base+4,"s");
  104.      force_setvar("wims_ref_name",ref_name);
  105.     }
  106. }
  107.  
  108. /* verify class participant connection data */
  109. void classlock(void)
  110. {
  111.     int lvl;
  112.     char *p;
  113.  
  114.     p=getvar("wims_classlock"); if(p==NULL) lvl=0; else {
  115.      p=find_word_start(p);
  116.      lvl=*p-'0'; if(lvl<0 || lvl>7) lvl=0;
  117.     }
  118.     if(lvl==7) { /* closed */
  119.      p=getvar("wims_user");
  120.      if(p==NULL || strcmp(p,"supervisor")!=0) user_error("class_closed");
  121.     }
  122.     if(lvl==2 || lvl==4 || lvl==6) { /* https */
  123.      p=getenv("HTTPS");
  124.      if(p==NULL || strcasecmp(p,"on")!=0) user_error("need_https");
  125.     }
  126.     if(lvl==3 || lvl>=5) {
  127.      if(strcmp(last_host,remote_addr)!=0) user_error("bad_host");
  128.     }
  129.     if((lvl==1 || lvl>=4) && cookiegot[0]==0) { /* cookie */
  130.      setcookie=1;
  131.      setvar("cookie_module",getvar(ro_name[ro_module]));
  132.      setvar("cookie_cmd",getvar(ro_name[ro_cmd]));
  133.      force_setvar(ro_name[ro_module],home_module);
  134.      force_setvar(ro_name[ro_cmd],commands[cmd_new]);
  135.      setvar("wims_askcookie","yes");
  136.      return;
  137.     }
  138.     else setcookie=0;
  139. }
  140.  
  141. /* get static session variables */
  142. void get_static_session_var(void)
  143. {
  144.     char *p, *pe, *p2, *p3;
  145.     char sbuf[MAX_FNAME+1], tbuf[MAX_LINELEN+1];
  146.     mystrncpy(sbuf,session_prefix,sizeof(sbuf));
  147.     for(p=sbuf+strlen(sbuf);p>sbuf && *p!='_' && *p!='/'; p--);
  148.     if(p>sbuf && *p=='_') *p=0;
  149.     accessfile(tbuf,"r","%s/var.stat",sbuf);
  150.     p=strrchr(sbuf,'/'); if(p!=NULL) p++; else p=sbuf;
  151.     mktmpdir(p);
  152.     for(p=find_word_start(tbuf);*p;p=find_word_start(pe)) {
  153.      pe=strchr(p,'\n'); if(pe!=NULL) *pe++=0; else pe=p+strlen(p);
  154.      p2=strchr(p,'='); if(p2==NULL) continue;
  155.      *p2++=0; force_setvar(p,p2);
  156.     }
  157.     p=getvar("wims_class"); if(p==NULL || *p==0) return;
  158.     mkfname(class_dir,"%s/%s",class_base,p);
  159.     classlock();
  160.     p3=getvar("wims_class_refcolor"); if(p3!=NULL && *p3!=0)
  161.       force_setvar("wims_ref_bgcolor",p3);
  162.     p3=getvar("wims_class_ref_menucolor"); if(p3!=NULL && *p3!=0)
  163.       force_setvar("wims_ref_menucolor",p3);
  164.     p3=getvar("wims_class_ref_button_color"); if(p3!=NULL && *p3!=0)
  165.       force_setvar("wims_ref_button_color",p3);
  166.     p3=getvar("wims_class_ref_button_bgcolor"); if(p3!=NULL && *p3!=0)
  167.       force_setvar("wims_ref_button_bgcolor",p3);
  168.     p3=getvar("wims_class_ref_button_help_bgcolor"); if(p3!=NULL && *p3!=0)
  169.       force_setvar("wims_ref_button_help_bgcolor",p3);
  170.     p3=getvar("wims_class_ref_button_help_color"); if(p3!=NULL && *p3!=0)
  171.       force_setvar("wims_ref_button_help_color",p3);
  172.     p2=getvar(ro_name[ro_module]);
  173.     if(p2==NULL || strncmp(p2,"classes/",strlen("classes/"))!=0) return;
  174.     mkfname(sbuf,"classes/%s",lang);
  175.     if(strcmp(sbuf,p2)!=0) force_setvar(ro_name[ro_module],sbuf);
  176. }
  177.  
  178. /* set one static session variable */
  179. void set_static_session_var(char *name, char *val)
  180. {
  181.     char *p;
  182.     char sbuf[MAX_FNAME+1], tbuf[MAX_LINELEN+1];
  183.     mystrncpy(sbuf,session_prefix,sizeof(sbuf));
  184.     for(p=sbuf+strlen(sbuf);p>sbuf && *p!='_' && *p!='/'; p--);
  185.     if(p>sbuf && *p=='_') *p=0;
  186.     snprintf(sbuf+strlen(sbuf),sizeof(sbuf)-strlen(sbuf),"/var.stat");
  187.     snprintf(tbuf,sizeof(tbuf),"%s=%s",name,val);
  188.     setdef(sbuf,tbuf); setvar(name,val);
  189. }
  190.  
  191. /* The session is probably robot. */
  192. void robot_doubt(void)
  193. {
  194.     char *h, *p;
  195.  
  196.     p=getvar("special_parm"); h=getvar("module");
  197.     if(p==NULL || h==NULL) {
  198.      bad: user_error("robot_doubt"); return;
  199.     }
  200.     p=find_word_start(p); strip_trailing_spaces(p);
  201.     if(strcmp(p,"wims")!=0 || strcmp(h,home_module)!=0) goto bad;
  202.     set_static_session_var("wims_robotcheck","manual");
  203. }
  204.  
  205. /* User has changed module within an operation.
  206.  * Probably due to robot access.
  207.  */
  208. void bad_module(void)
  209. {
  210.     char *p;
  211.     p=getvar("wims_user"); if(p==NULL) p="";
  212.     if(*p==0 && strcmp(robotcheck,"manual")!=0) set_static_session_var("wims_robotcheck","robot");
  213.     else setvar("wims_human_access","yes");
  214.     user_error("module_change");
  215. }
  216.  
  217. /* returns 1 if session directory exists */
  218. int session_exists(char *s)
  219. {
  220.     if(ftest(mkfname(NULL,"../%s/%s/var",SESSION_BASE,s))==is_file) return 1;
  221.     else return 0;
  222. }
  223.  
  224. /* Check the validity of session number .
  225.  * returns 0 if OK, else -1.
  226.  */
  227. int check_session(void)
  228. {
  229.     char tbuf[MAX_LINELEN+1], vbuf[MAX_LINELEN+1];
  230.     char *p, *pp, *pr;
  231.     int i,m,n,pl,rapid,badmod;
  232.     struct stat st;
  233.  
  234.     rapid=badmod=0; pr="";
  235.     if(fopen_session_var_file("r")==NULL) return -1;
  236.     if(ftest(s2_prefix)!=is_dir) mkdirs(s2_prefix);
  237.     session_var_ready=1; memmove(&svar_file,&m_file,sizeof(WORKING_FILE));
  238. /* REMOTE_ADDR */
  239.     wgetline(vbuf,MAX_LINELEN,&m_file);
  240.     mystrncpy(last_host,vbuf+strlen("REMOTE_ADDR="),sizeof(last_host));
  241.     m_file.linepointer++; /* now it points to query_string */
  242.     pp=getenv("QUERY_STRING");
  243.     if(pp!=NULL && *pp!=0 && strlen(pp)<=MAX_LINELEN) {
  244. /* we compare the query string with the last one. */
  245.      char *p1, *p2;
  246.      wgetline(tbuf,MAX_LINELEN,&m_file);
  247.      p1=tbuf+strlen("QUERY_STRING=");
  248.      if(strncmp(tbuf,"QUERY_STRING=",strlen("QUERY_STRING="))==0 &&
  249.         strcmp(pp,p1)==0 && strstr(session_prefix,"_test")==NULL) {
  250. /* query string does not change */
  251.          if(ftest(mkfname(NULL,"%s/%s",s2_prefix,lastout))==is_file &&
  252.             ftest_size > 0) {
  253.           uselast:
  254.           putlastout(); delete_pid(); exit(0);
  255.          }
  256.          else {
  257.           if(cmd_type==cmd_new || cmd_type==cmd_renew ||
  258.              cmd_type==cmd_reply || cmd_type==cmd_next) {
  259.               cmd_type=cmd_resume;
  260.               force_setvar(ro_name[ro_cmd],"resume");
  261.               forceresume=1;
  262.           }
  263.          }
  264.      }
  265. /* stop rapidfire requests */
  266.      if((cmd_type==cmd_new || cmd_type==cmd_renew) &&
  267.         strncmp(p1,"session=",strlen("session="))==0 &&
  268.         strncmp(pp,"session=",strlen("session="))==0) {
  269.          p1=strchr(p1,'&'); if(p1==NULL) p1="";
  270.          p2=strchr(pp,'&'); if(p2==NULL) p2=""; pr=p2;
  271.          if(strcmp(p1,p2)==0) rapid=1;
  272.      }
  273.     }
  274.     m_file.linepointer=3;
  275.     wgetline(vbuf,MAX_LINELEN,&m_file); /* stored user_agent */
  276. /*    p=getenv("HTTP_USER_AGENT"); if(p==NULL) p="";
  277.     if(strcmp(vbuf+strlen("HTTP_USER_AGENT="),p)!=0) bad_ident(); */
  278.     m_file.linepointer=HEADER_VAR_NO;
  279.     pl=strlen(var_prefix);i=-1;
  280.     while(wgetline(tbuf,MAX_LINELEN,&m_file)!=EOF) {
  281.      if(tbuf[0]==0) break; /* blank line */
  282.      if(strncmp(tbuf,var_prefix,pl)!=0) break;
  283.      i++;if(i>=RO_NAME_NO) break;
  284.      for(n=0;n<varget_no && varget[n]!=i;n++);
  285.      if(n>=varget_no) continue;
  286.      m=pl+strlen(ro_name[i]);
  287.      if(tbuf[m]!='=' || tbuf[m+1]==0) continue;
  288.      if(i==ro_module && cmd_type!=cmd_new && cmd_type!=cmd_intro) {
  289.          char *pp;
  290.          pp=getvar(ro_name[i]);
  291.          if(pp!=NULL && *pp!=0 && strcmp(pp,tbuf+m+1)!=0) badmod=1;
  292.      }
  293.      if(i==ro_lang && !user_lang)
  294.        force_setvar(ro_name[i],tbuf+m+1);
  295.      else setvar(ro_name[i],tbuf+m+1);
  296.     }
  297. /* recover internal variables */
  298.     do {
  299.      char *v;
  300.      if(tbuf[0]==0) break;
  301.      v=strchr(tbuf,'=');
  302.      if(v==NULL) break; else *(v++)=0;
  303.      if(strncmp(tbuf,var_prefix,strlen(var_prefix))!=0) setenv(tbuf,v,1);
  304.      else if(tbuf[strlen(var_prefix)]) force_setvar(tbuf+strlen(var_prefix),v);
  305.     }
  306.     while(wgetline(tbuf,MAX_LINELEN,&m_file)!=EOF);
  307.     get_static_session_var();
  308.     robotcheck=getvar("wims_robotcheck"); if(robotcheck==NULL) robotcheck="";
  309. /* form access means manual access. Mark this. */
  310.     if(form_access && strcmp(robotcheck,"manual")!=0) {
  311.      robotcheck="manual";
  312.      set_static_session_var("wims_robotcheck","manual");
  313.     }
  314.     else if(strcmp(robotcheck,"robot")==0) robot_doubt();
  315.     if(badmod) bad_module();
  316.     if(cookiegot[0]!=0) {
  317.      p=getvar("wims_sescookie");
  318.      if(p!=NULL && *p!=0 && strcmp(cookiegot,p)!=0) bad_ident();
  319.     }
  320.     p=getvar("wims_sreferer");
  321.     if(p!=NULL && *p!=0) {
  322.      setenv("HTTP_REFERER",p,1); setvar("httpd_HTTP_REFERER",p);
  323.     }
  324.     if(rapid) {
  325.      int rapidfiredelay;
  326.      char *pw, fnbuf[MAX_FNAME+1];
  327. /* Delay: 10 seconds within worksheets, 1 second otherwise. */
  328.      pw=getvar("wims_developer");
  329.      if(pw!=NULL && *pw!=0) goto delcheckend;
  330.      pw=getvar("wims_user");
  331.      if(pw==NULL || *pw==0 || strcmp(pw,"supervisor")==0) rapidfiredelay=1;
  332.      else {
  333.          pw=strstr(pr,"&+worksheet=");
  334.          if(pw!=NULL && myisdigit(*(pw+strlen("&+worksheet=")))) rapidfiredelay=10;
  335.          else rapidfiredelay=2;
  336.      }
  337.      if(ftest(mkfname(fnbuf,"%s/%s",s2_prefix,lastout))==is_file
  338.         && ftest_size > 0
  339.         && stat(fnbuf,&st) == 0
  340.         && st.st_mtime > nowtime-rapidfiredelay && st.st_mtime <= nowtime)
  341.        goto uselast;
  342.     }
  343. /* set protocol string */
  344.     delcheckend: pp=getvar("wims_protocol");
  345.     if(pp!=NULL && strcmp(pp,"https")==0) {
  346.      protocol="https"; set_protocol();
  347.     }
  348.     useropts(); return 0;
  349. }
  350. /* check whether a session is trapped. */
  351. void trap_check(char *s)
  352. {
  353.     char buf[64];
  354.     char *p;
  355.     time_t t1;
  356.  
  357.     setvar("wims_session_expired",s);
  358.     accessfile(tmplbuf,"r","../tmp/log/trap.check");
  359.     if(tmplbuf[0]==0) return;
  360.     p=getenv("REMOTE_ADDR");if(p==NULL) return;
  361.     snprintf(buf,sizeof(buf),":%s,%s,",s,p);
  362.     p=strstr(tmplbuf,buf); if(p==NULL) return;
  363.     p+=strlen(buf);*find_word_end(p)=0;
  364.     t1=atoi(p);
  365.     if(t1>nowtime) user_error("trapped");
  366. }
  367.  
  368. char cars[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  369.  
  370. void set_cookie(void)
  371. {
  372.     #define keylen 20
  373.     char sesbuf[16], keybuf[keylen+8];
  374.     char *p;
  375.  
  376.     p=getvar(ro_name[ro_session]); if(p==NULL) return;
  377.     mystrncpy(sesbuf,p,sizeof(sesbuf));
  378.     if(strchr(sesbuf,'_')==NULL) { /* main session */
  379.      int i;
  380.      for(i=0;i<keylen;i++) keybuf[i]=cars[random()%36];
  381.      keybuf[keylen]=0; cookiegot[0]=0;
  382.      snprintf(cookieset,sizeof(cookieset),"%s-%s",sesbuf,keybuf);
  383.      set_static_session_var("wims_sescookie",cookieset);
  384.      setcookie=1;
  385.     }
  386.     else { /* subsession */
  387.      p=getvar("wims_sescookie"); if(p && *p)
  388.        mystrncpy(cookieset,p,sizeof(cookieset));
  389.     }
  390. }
  391.  
  392. /* create a session number */
  393. void create_session(void)
  394. {
  395.     long t; char session_str[64],*s;
  396.     char *p, ses_dir_buf[MAX_FNAME+1], sesrandbuf[MAX_LINELEN+1];
  397.     int i;
  398.  
  399. /* no session is created for robots */
  400.     if(robot_access) return;
  401.     sesrandbuf[0]=0;
  402. /* If session is given in request_string: use it. */
  403.     s=getvar(ro_name[ro_session]); if(s==NULL) goto creat;
  404.     mystrncpy(session_str,s,sizeof(session_str));
  405.     s=strchr(session_str,'.'); if(s!=NULL) *s=0;
  406.     s=session_str;
  407.     if(*s!=0) {
  408.      int i;
  409.      mkfname(ses_dir_buf,"%s/%s",session_dir,s);
  410.      i=ftest(ses_dir_buf);
  411.      if(i<0) {
  412.          trap_check(s);
  413. /* subsession */
  414.          if(strlen(s)>10 && strchr(s,'_')!=NULL) {
  415.           char *tt;
  416.           tt=strrchr(ses_dir_buf,'_'); if(tt!=NULL) *tt=0;
  417. /* parent session gone. */
  418.           if(ftest(ses_dir_buf)<0) goto creat;
  419.           goto creat2;
  420.          }
  421.          else goto creat;
  422.      }
  423.      if(i!=is_dir) {
  424.          trap_check(s);
  425.          remove_tree(ses_dir_buf); goto creat;
  426.      }
  427.      return;
  428.     }
  429.     creat:
  430.     t=create_job_ident();
  431.     for(i=0;i<MAX_SESRANDOM;i++)
  432.       snprintf(sesrandbuf+strlen(sesrandbuf),
  433.             sizeof(sesrandbuf)-strlen(sesrandbuf),
  434.             "%d,",sesrandomtab[i]);
  435.     sesrandbuf[strlen(sesrandbuf)-1]='\n';
  436.     snprintf(session_str,sizeof(session_str),"%c%c%08lX",
  437.           cars[random()%36],cars[random()%36],t);
  438.     creat2:
  439.     force_setvar(ro_name[ro_session],session_str);
  440.     setsesdir(session_str);
  441. /* check whether the environment is created. */
  442.     s=getvar(ro_name[ro_session]);
  443.     if(s==NULL || strcmp(s,session_str))
  444.       internal_error("cannot_create_session_number");
  445.     snprintf(ses_dir_buf,sizeof(ses_dir_buf)-100,"%s/%s",
  446.           session_dir,session_str);
  447.     if(mkdir(ses_dir_buf,S_IRWXU)==-1)
  448.       internal_error("cannot_create_session_directory");
  449.     mkfname(s2_prefix,"%s/%s",s2_dir,session_str);
  450.     if(mkdir(s2_prefix,S_IRWXU)==-1) mkdirs(s2_prefix);
  451.     mystrncpy(session_prefix,ses_dir_buf,sizeof(session_prefix)); create_pid();
  452.     if(strchr(session_str,'_')==NULL) {
  453.      if((s=getenv("HTTP_REFERER"))!=NULL && *s!=0 && strlen(s)<MAX_FNAME-20
  454.         && strstr(s,"wims")==NULL) {
  455.          char *tt;
  456.          tt=getenv("SERVER_NAME");
  457.          if(tt==NULL || *tt==0 || strstr(s,tt)==NULL)
  458.            set_static_session_var("wims_sreferer",s);
  459.      }
  460.      if(sesrandbuf[0]) set_static_session_var("wims_sesrandom",sesrandbuf);
  461.     }
  462. /* determine http protocol name. How to detect? */
  463.     p=getenv("HTTPS"); if(p!=NULL && strcmp(p,"on")==0) {
  464.       protocol="https"; set_protocol();
  465.     }
  466.     force_setvar("wims_protocol",protocol);
  467.     new_session=1; session_serial=0;
  468.     setvar("wims_new_session","yes");
  469.     if(strchr(session_str,'_')!=NULL) get_static_session_var();
  470.     set_cookie();
  471. }
  472.  
  473. /* Register time of the request. */
  474. void set_req_time(void)
  475. {
  476.     char tstr[64];
  477.  
  478.     snprintf(tstr,sizeof(tstr),"%04d-%02d-%02d.%02d:%02d:%02d=%lu",
  479.          (now->tm_year)+1900, (now->tm_mon)+1, now->tm_mday,
  480.          now->tm_hour, now->tm_min, now->tm_sec, nowtime);
  481.     force_setvar("wims_req_time",tstr);
  482.     if(cmd_type == cmd_new || cmd_type == cmd_renew)
  483.       force_setvar("wims_module_start_time",tstr);
  484.     if(new_session) force_setvar("wims_session_start_time",tstr);
  485. }
  486.  
  487. /* set up module_prefix. */
  488. void set_module_prefix(void)
  489. {
  490.     char tbuf[MAX_FNAME+1], mmbuf[MAX_FNAME+1], *p, *pp, *ps;
  491.     int t,ft;
  492.     struct stat st;
  493.  
  494.     isclassmodule=0;
  495.     p=getvar(ro_name[ro_module]);
  496.     if(p==NULL || *p==0) user_error("no_module_name");
  497. /* security measure: we should not allow users to go back to
  498.  * parent directories.
  499.  */
  500.     if(strstr(p,parent_dir_string)!=NULL) user_error("wrong_module");
  501.     if(strncmp(p,"classes/",strlen("classes/"))==0) isclassmodule=1;
  502.     if(strncmp(p,"devel/",strlen("devel/"))==0) isdevelmodule=1;
  503.     mkfname(module_prefix,"%s/%s",module_dir,p);
  504. /* Now no symbolic link should appear in the module path. */
  505.     mkfname(tbuf,"modules/%s",p);
  506.     for(t=0,ps=pp=strchr(tbuf+strlen("modules/"),'/'); pp;
  507.      *pp='/', ps=pp, pp=strchr(pp+1,'/'), t++) {
  508.      *pp=0; if(lstat(tbuf,&st)) user_error("wrong_module");
  509.      if(t>0 && S_ISLNK(st.st_mode)) {
  510.          if(strcmp(ps,"/local")!=0 ||
  511.             strncmp(tbuf,"modules/home",strlen("modules/home"))==0)
  512.            user_error("wrong_module");
  513.        }
  514.     }
  515. /* Check validity of the module. */
  516.     mkfname(tbuf,"%s/%s",module_prefix,html_file);
  517.     ft=stat(tbuf,&st);
  518.     if(ft!=0 && p[strlen(p)-3]!='.') {
  519.      int i,j;
  520.      char *l;
  521.      l=getvar(ro_name[ro_lang]);
  522.      j=available_lang_no;
  523.      for(i=-1;i<j && ft!=0;i++) {
  524.          if(i<0) mkfname(mmbuf,"%s.%s",p,l);
  525.          else mkfname(mmbuf,"%s.%s",p,available_lang[i]);
  526.          mkfname(module_prefix,"%s/%s",module_dir,mmbuf);
  527.          mkfname(tbuf,"%s/%s",module_prefix,html_file);
  528.          ft=stat(tbuf,&st);
  529.      }
  530.      if(ft==0) force_setvar(ro_name[ro_module],mmbuf);
  531.     }
  532.     if(ft!=0 && !isclassmodule) user_error("wrong_module");
  533.     setenv("module_dir",module_prefix,1); setvar("module_dir",module_prefix);
  534.     module_index();
  535. }
  536.  
  537. /* set up session_prefix. */
  538. int set_session_prefix(void)
  539. {
  540.     char *p, s[32];
  541.  
  542.     if(robot_access) {
  543.      mystrncpy(session_prefix,robot_session,sizeof(session_prefix));
  544.      mystrncpy(s2_prefix,robot_session,sizeof(session_prefix));
  545.      return 0;
  546.     }
  547.     p=getvar(ro_name[ro_session]);
  548.     if(p==NULL || *p==0) user_error("no_session");
  549. /* same reason as for modules */
  550.     if (strchr(p,'/')!=NULL || strstr(p,parent_dir_string)!=NULL
  551.      || *find_word_end(p)!=0) user_error("wrong_session");
  552.     mystrncpy(s,p,sizeof(s));
  553.     p=strchr(s,'.'); if(p!=NULL) *p=0;
  554.     mkfname(session_prefix,"%s/%s",session_dir,s);
  555.     p=strstr(session_prefix,"_mhelp"); if(p!=NULL) *p=0;
  556.     if(ftest(session_prefix)!=is_dir) return -1;
  557.     mkfname(s2_prefix,"%s/%s",s2_dir,s);
  558.     setenv("session_dir",session_prefix,1);
  559.     setenv("s2_dir",s2_prefix,1);
  560.     if(ftest(mkfname(NULL,"%s/.trap",s2_prefix))==is_file)
  561.       user_error("trapped");
  562.     return 0;
  563. }
  564.  
  565. /* check reserved name values in query_string */
  566. void parse_ro_names(void)
  567. {
  568.     int i;
  569.     char *cmd, *p;
  570.     char sesbuf[64];
  571.     create:
  572.     cmd=getvar(ro_name[ro_cmd]);
  573.     if(cmd==NULL || *cmd==0) user_error("no_command");
  574.     for(i=0;i<CMD_NO;i++) if(strcmp(cmd,commands[i])==0) break;
  575.     if(i>=CMD_NO) user_error("bad_command");
  576.     cmd_type=i;
  577.     if(cmd_type == cmd_new) {
  578.      create_session();
  579.      if(set_session_prefix()==0) {
  580.          check_session();
  581.          set_module_prefix();
  582.      }
  583.      else goto redo;
  584.     }
  585.     if (set_session_prefix()==-1 || (cmd_type != cmd_new && check_session())) {
  586.      redo:
  587.      force_setvar(ro_name[ro_cmd],commands[cmd_new]);
  588.      if(strcmp(ro_name[ro_module],home_module)!=0) user_var_no=0;
  589.      goto create;
  590.     }
  591.     if(!new_session) create_pid();
  592.     session_serial++;
  593.     if(robot_access) session_serial=1;
  594.     snprintf(sesbuf,sizeof(sesbuf),"%d",session_serial);
  595.     force_setvar("wims_session_serial",sesbuf);
  596.     p=getvar(ro_name[ro_session]);
  597.     if(p==NULL || *p==0) internal_error("parse_ro_names(): bad session.\n");
  598.     mystrncpy(sesbuf,p,sizeof(sesbuf));
  599.     p=strchr(sesbuf+5,'.'); if(p!=NULL) *p=0;
  600.     mktmpdir(sesbuf);
  601.     if(!robot_access) {
  602.      setsesdir(sesbuf);
  603.      p=strchr(sesbuf,'_');
  604.      if(p!=NULL) force_setvar("wims_subsession",p);
  605.     }
  606.     snprintf(sesbuf+strlen(sesbuf),sizeof(sesbuf)-strlen(sesbuf),
  607.           ".%d",session_serial);
  608.     force_setvar(ro_name[ro_session],sesbuf);
  609.     if(cmd_type != cmd_new) set_module_prefix();
  610.     set_req_time();
  611.     if(robot_access) check_load(0);
  612.     else {
  613.      if(new_session) auth();
  614.      else {
  615.          p=getvar("wims_user"); if(p==NULL || *p==0) check_load(2);
  616.      }
  617.     }
  618.     if(cmd_type==cmd_help && open_working_file(&m_file,module_about_file)==0)
  619.       var_proc(NULL,0);
  620. }
  621.  
  622.  
  623. /* returns positive or 0 if var_def found, otherwise returns -1. */
  624. int var_def_check(char *name)
  625. {
  626.     char *p, nbuf[MAX_NAMELEN+1];
  627.     int i,tt;
  628.  
  629.     tt=-1;
  630.     for(p=name+strlen(name);p>name && myisdigit(*(p-1));p--);
  631.     if(*p && *p!='0' && p>name) tt=atoi(p);
  632.     else p=name+strlen(name);
  633.     if(p>name+MAX_NAMELEN) p=name+MAX_NAMELEN;
  634.     memmove(nbuf,name,p-name); nbuf[p-name]=0;
  635.     i=search_list(var_def,defined_var_total,sizeof(var_def[0]),nbuf);
  636.     if(i<0) return -1;
  637.     while(i>0 && tt<var_def[i].beg && strcmp(nbuf,var_def[i-1].name)==0) i--;
  638.     while(i<defined_var_total-1 && tt>var_def[i].end &&
  639.            strcmp(nbuf,var_def[i+1].name)==0) i++;
  640.     if(tt<var_def[i].beg || tt>var_def[i].end) return -1;
  641.     return i;
  642. }
  643.  
  644. int var_def_name(char *n, int v)
  645. {
  646.     char *q, *r;
  647.     int j;
  648.     if(strlen(n)>=MAX_NAMELEN) module_error("defn_too_long");
  649.     var_def[v].name=n;
  650.     if((strncmp(n,wims_prefix,wpflen)==0 &&
  651.      (strncmp(n,"wims_priv_",strlen("wims_priv_"))==0 ||
  652.       search_list(internal_name,INTERNAL_NAME_NO,
  653.                sizeof(internal_name[0]),n+wpflen)>=0)) ||
  654.        search_list(ro_name,RO_NAME_NO,sizeof(ro_name[0]),n)>=0) {
  655.      setvar("wims_reserved_name",n);
  656.      module_error("name_is_reserved");
  657.     }
  658.     for(q=n;myisalnum(*q) || *q=='_'; q++);
  659.     if(q==n) {
  660.      illegal: setvar("wims_bad_name",n);
  661.      module_error("illegal_name");
  662.     }
  663.     if(*q=='[') {
  664.      *q++=0; r=find_matching(q,']');
  665.      if(r==NULL) goto illegal;
  666.      *r=0; j=atoi(q);
  667.      if(j<1) j=1; if(j>MAX_VAR_NUM) j=MAX_VAR_NUM;
  668.      var_def[v].beg=1; var_def[v].end=j;
  669.      return j;
  670.     }
  671.     if(*q) goto illegal;
  672.     for(r=q; r>n && myisdigit(*(r-1)); r--);
  673.     if(*r && *r!='0' && r>n) {
  674.      var_def[v].beg=var_def[v].end=atoi(r); *r=0;
  675.     }
  676.     else var_def[v].beg=var_def[v].end=-1;
  677.     return 1;
  678. }
  679.  
  680. int var_def_allow(char *p, int v)
  681. {
  682.     int i;
  683.     for(i=0;i<VAR_ALLOW_NO && strcasecmp(p,var_allow[i])!=0; i++);
  684.     if(i>=VAR_ALLOW_NO) module_error("bad_allow");
  685.     else var_def[v].allow=i;
  686.     return i;
  687. }
  688.  
  689. int varsort(const void *p1, const void *p2)
  690. {
  691.     int i; const struct VAR_DEF *pp1, *pp2;
  692.     pp1=p1; pp2=p2; i=strcmp(pp1->name,pp2->name);
  693.     if(i) return i; else return pp1->end - pp2->end;
  694. }
  695.  
  696.      /* parse module's variable definitions */
  697. void get_var_defs(void)
  698. {
  699.     int i, j, k, v, add;
  700.     char *p, *p1, *wlist[MAX_VAR_NUM];
  701.  
  702.     defined_var_total=0;
  703.     if(read_module_file(var_def_file)!=0) return;
  704.     var_def_buf=m_file.textbuf;
  705.     for(m_file.l=v=add=0;v<MAX_VAR_NUM && m_file.l<m_file.linecnt;m_file.l++) {
  706.      if(m_file.lines[m_file.l].isstart!=1) continue;
  707.      p=find_word_start(m_file.lines[m_file.l].address);
  708.      if(*p==0 || *p==comment_prefix_char) continue;  /* empty or comment lines */
  709.      items2words(p);
  710.      if((p1=strchr(p,':'))!=NULL) {  /* new format */
  711.          *p1=' '; i=cutwords(p,wlist,MAX_VAR_NUM); if(i<=1) continue;
  712.          k=var_def_allow(wlist[0],v);
  713.          for(j=1;j<i && v<MAX_VAR_NUM;j++) {
  714.           add+=var_def_name(wlist[j],v); var_def[v].allow=k;
  715.           v++;
  716.          }
  717.      }
  718.      else {
  719.          i=cutwords(p,wlist,3); if(i<2) module_error("too_few_columns");
  720.          add+=var_def_name(wlist[0],v); var_def_allow(wlist[1],v);
  721.          var_def[v].defined_in_parm=0;
  722.          v++;
  723.      }
  724.     }
  725.     if(v>=MAX_VAR_NUM) module_error("too_many_variables");
  726.     defined_var_total=v;
  727.     qsort(var_def,v,sizeof(var_def[0]),varsort);
  728.     p=getvar(ro_name[ro_module]);
  729.     if(p==NULL || strncmp(p,"devel/",6)!=0) return;
  730.     for(v=1;v<defined_var_total;v++) {
  731.      if(strcmp(var_def[v].name,var_def[v-1].name)==0 &&
  732.         var_def[v].beg<=var_def[v-1].end) {
  733.          setvar("wims_bad_name",var_def[v].name);
  734.          module_error("multiple_declaration");
  735.      }
  736.     }
  737. }
  738.  
  739. /* returns 1 if hacked, else 0. */
  740. int try_hack(char *var)
  741. {
  742.     int i, al;
  743.     char vbuf[16];
  744.     i=var_def_check(var);
  745.     if(i<0) return 0;
  746.     al=var_def[i].allow;
  747.     if(al != var_allow_any) switch(cmd_type) {
  748.      case cmd_new:
  749.      case cmd_renew: {
  750.          if (al != var_allow_init && al != var_allow_config) return 0;
  751.          else break;
  752.      }
  753.      case cmd_config: {
  754.          if(al != var_allow_config) return 0;
  755.          else break;
  756.      }
  757.      case cmd_reply: {
  758.          if(al != var_allow_reply) return 0;
  759.          else break;
  760.      }
  761.      case cmd_help: {
  762.          if(al != var_allow_help) return 0;
  763.          else break;
  764.      }
  765.      default: return 0;
  766.     }
  767.     snprintf(vbuf,sizeof(vbuf),"%d",(int) irand(21));
  768.     var_hacking=1; setvar(var,vbuf); var_hacking=0;
  769.     return 1;
  770. }
  771.  
  772. /* set environ variables from last session save
  773.  * The session var file starts with variables which should not
  774.  * be restored. Variables which are restored follow a blank line. */
  775. void set_vars_from_session(void)
  776. {
  777.     char lbuf[MAX_LINELEN+1];
  778.     int i;
  779.     char *p;
  780.  
  781.     if(session_var_ready) memmove(&m_file,&svar_file,sizeof(WORKING_FILE));
  782.     else fopen_session_var_file("r");
  783. /* look for the first blank line. */
  784.     for(i=0;i<m_file.linecnt && (m_file.lines[i].isstart==0 || m_file.lines[i].llen>0);i++);
  785.     for(i++;i<m_file.linecnt && m_file.lines[i].llen==0;i++);
  786.     if(i>=m_file.linecnt) return;
  787.     m_file.linepointer=i;
  788.     if(isdevelmodule && strstr(session_prefix,"_test")==NULL) isdevelmodule=0;
  789.     while(wgetline(lbuf,MAX_LINELEN, &m_file)!=EOF) {
  790.      p=strchr(lbuf,'=');
  791.      if(p==NULL || p<=lbuf || isspace(lbuf[0]) ) {
  792. /* this time it is corrupted var file */
  793.        call_ssh("cat %s/var >%s/corrupt.var.bak",session_prefix,log_dir);
  794.        internal_error("get_vars_from_session(): corrupt session variable file.");
  795.      }
  796.      *p=0;p++;
  797. /* Here we suppose that nobody can tamper session variable
  798.  * file, and do not check variable names against module's
  799.  * definition file. Policy under reserve. */
  800. /* We do not allow override though.
  801.  * Especially because reply variables should
  802.  * be preserved. */
  803.      if(strncmp(lbuf,var_prefix,strlen(var_prefix))!=0)
  804.        setenv(lbuf,p,0);
  805.      else if(lbuf[strlen(var_prefix)]!=0 && getvar(lbuf+strlen(var_prefix))==NULL) {
  806.          if(!isdevelmodule || !try_hack(lbuf+strlen(var_prefix))) {
  807.           setvar(lbuf+strlen(var_prefix),p);
  808.          }
  809.      }
  810.     }
  811.     close_working_file(&m_file,0);
  812. }
  813.  
  814. /* Initialize environment variables according to module's
  815.  * variable init or calculation file.
  816.  * init is only used when cmd=new or renew.
  817.  * Requires get_var_defs be run first. */
  818. void var_proc(char *fname,int cache)
  819. {
  820.     int  t;
  821.     char *p, tbuf[MAX_LINELEN+1];
  822.  
  823.     if(fname!=NULL && read_module_file(fname)) return;
  824.     if(untrust&6) get_var_privileges();
  825.     while(m_file.linepointer<m_file.linecnt) {
  826.      t=m_file.lines[m_file.linepointer].isstart;
  827.      if((t&~2)!=1 || m_file.lines[m_file.linepointer].llen==0) {
  828.          m_file.linepointer++; continue;
  829.      }
  830.      wgetline(tbuf,MAX_LINELEN,&m_file); substnest=0;
  831.      p=find_word_start(tbuf); if(*p==0) continue;
  832.      if((t&2)!=0) exec_main(p+1);
  833.      else exec_set(p);
  834.     }
  835.     close_working_file(&m_file,cache);
  836. }
  837.  
  838. /* Deposit the content of wims_deposit into a file */
  839. void var_deposit(char *p)
  840. {
  841.     char fn[MAX_FNAME+1];
  842.     int l,fd;
  843.     if(!trusted_module()) return;
  844.     if(deplen>0) l=deplen; else {
  845.      while(isspace(*p)) p++; l=strlen(p);
  846.     }
  847.     if(l<=0) return;
  848.     if(l>MAX_DEPOSITLEN) l=MAX_DEPOSITLEN; /* silent truncation, should not occur */
  849.     mkfname(fn,"%s/user-deposit",session_prefix);
  850.     fd=creat(fn,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if(fd==-1) return;
  851.     write(fd,p,l); close(fd);
  852.     snprintf(fn,sizeof(fn),"%u",l); setvar("wims_deposit_len",fn);
  853. }
  854.  
  855. /* Check and set variables passed in query_string */
  856. void set_vars_from_parm(void)
  857. {
  858.     int i,j,al;
  859.     char *s, vbuf[MAX_LINELEN+1];
  860.     if(forceresume) return;
  861.     for(i=0; i<user_var_no; i++) {
  862.      j=var_def_check(user_variable[i].name);
  863.      if(j<0) continue;
  864. /* check permissions */
  865.      al=var_def[j].allow;
  866.      if(al != var_allow_any) switch(cmd_type) {
  867.          case cmd_new:
  868.          case cmd_renew:
  869.              if (al != var_allow_init && al != var_allow_config) {
  870. violat:        /* setvar(error_data_string,user_variable[i].name);
  871.               user_error("allow_violation"); */
  872.               goto loopend;
  873.           }
  874.              break;
  875.  
  876.          case cmd_config:
  877.              if(al != var_allow_config) goto violat;
  878.              break;
  879.  
  880.          case cmd_reply:
  881.               if(al != var_allow_reply) goto violat;
  882.              break;
  883.  
  884.          case cmd_help:
  885.               if(al != var_allow_help) goto violat;
  886.               break;
  887.  
  888.          default: goto violat;
  889.      }
  890.      var_def[j].defined_in_parm=1;
  891.      if(strcmp(user_variable[i].name,"wims_deposit")==0) {
  892.          var_deposit(user_variable[i].value); continue;
  893.      }
  894.      mystrncpy(vbuf,user_variable[i].value,sizeof(vbuf));
  895.      if(strchr(vbuf,'$')!=NULL) {
  896.          char *p;
  897.          while((p=strchr(vbuf,'$'))!=NULL)
  898.            string_modify(vbuf,p,p+1,"&#36;");
  899.      }
  900.      s=getvar(user_variable[i].name);
  901.      if(s==NULL || *s==0) setvar(user_variable[i].name, vbuf);
  902.      else {  /* concatenate */
  903.          int k;
  904.          k=strlen(s)+strlen(vbuf);
  905.          if(k>=MAX_LINELEN-2) user_error("string_too_long");
  906.          snprintf(tmplbuf,sizeof(tmplbuf),"%s, %s",s,vbuf);
  907.          setvar(user_variable[i].name, tmplbuf);
  908.      }
  909.      loopend: ;
  910.     }
  911. }
  912.  
  913. /* parms to be eliminated from module_init_parm */
  914. /* char *init_elim[]={
  915.     "module","cmd","session","lang","worksheet","wims_access","useropts"
  916. };
  917. #define init_elim_no (sizeof(init_elim)/sizeof(init_elim[0]))
  918. */
  919.  
  920. void elim_parm(char *str, char *parm)
  921. {
  922.     char *p1, *p2;
  923.     for(p1=strstr(str,parm);p1!=NULL;p1=strstr(p1+1,parm)) {
  924.      if( (p1>str && *(p1-1)!='&') || *(p1+strlen(parm))!='=')
  925.        continue;
  926.      p2=strchr(p1,'&');
  927.      if(p2==NULL) {
  928.          if(p1>str) *(p1-1)=0; else *p1=0;
  929.          return;
  930.      }
  931.      ovlstrcpy(p1,p2+1); p1--;
  932.     }
  933. }
  934.  
  935. /* eliminate technical definitions form parameter string. */
  936. void prep_init_parm(char rqv[])
  937. {
  938.     int i;
  939.     char *p;
  940.  
  941.     for(p=strstr(rqv,"&+"); p!=NULL; p=strstr(++p,"&+"))
  942.       ovlstrcpy(p+1,p+2);
  943.     for(i=0;i<RO_NAME_NO;i++) elim_parm(rqv,ro_name[i]);
  944.     if(strlen(rqv)>=MAX_LINELEN) rqv[0]=0;
  945.     while(rqv[0]=='&') ovlstrcpy(rqv,rqv+1);
  946.     while(rqv[0]!=0 && rqv[strlen(rqv)-1]=='&') rqv[strlen(rqv)-1]=0;
  947. }
  948.  
  949. /* retain initializing parameters, for use in user references */
  950. void set_init_parm(void)
  951. {
  952.     char *rq, rqv[MAX_LINELEN*2+2], *u, *sh;
  953.     char *shname;
  954.     int public_sheet;
  955.  
  956.     if(isexam) return;
  957.     force_setvar("wims_sheet",""); force_setvar("wims_exo","");
  958.     rq=getenv("QUERY_STRING");
  959.     if(rq==NULL || *rq==0) {
  960.      empty:
  961.      setvar("module_init_parm",""); return;
  962.     }
  963.     if(strlen(rq)>=MAX_LINELEN*2) goto empty;
  964.     _http2env(rqv,rq); prep_init_parm(rqv);
  965.     setvar("module_init_parm",rqv); public_sheet=0;
  966. /* now determine the sheet number for user */
  967.     sh=getvar(ro_name[ro_worksheet]); if(sh==NULL) return;
  968.     if(*sh=='P') {public_sheet=1; sh++;}
  969.     shname="sheet";
  970.     u=getvar("wims_user"); if(u==NULL) u="";
  971.     if(sh!=NULL && *sh!=0) {
  972.      char buf[MAX_LINELEN+1],ubuf[32], nbuf[1024], *c, *m;
  973.      char *p1,*p2,*p3,*p4,*p5;
  974.      int i,j,sheet;
  975.      sheet=atoi(sh); if(sheet<=0 || sheet>256) return;
  976.      m=getvar(ro_name[ro_module]);
  977.      if(m==NULL) internal_error("set_init_parm(): module name disapears.");
  978.      if(*u==0) public_sheet=1;
  979.      if(!public_sheet) {
  980.          c=getvar("wims_class"); if(c==NULL) c="";
  981.          snprintf(nbuf,sizeof(nbuf),"%s/sheets/.%s%d",
  982.                class_dir,shname,sheet);
  983.      }
  984.      else {
  985.          char bf[MAX_LINELEN+1];
  986.          int i;
  987.          accessfile(bf,"r","%s/.sheets",session_prefix);
  988.          if(bf[0]==0) return;
  989.          for(i=1, p1=bf;i<sheet;i++,p1=p2) {
  990.           p2=strchr(p1,'\n');
  991.           if(p2!=NULL) *p2++=0; else p2=p1+strlen(p1);
  992.          }
  993.          p2=strchr(p1,'\n'); if(p2) *p2=0;
  994.          snprintf(nbuf,sizeof(nbuf),"bases/sheet/%s.def",p1);
  995.      }
  996.      if(readfile(nbuf,buf,sizeof(buf))==NULL) return;
  997.      for(p1=strstr(buf,"&+");p1!=NULL;p1=strstr(++p1,"&+"))
  998.          ovlstrcpy(p1+1,p1+2);
  999.      if(strncmp(m,"classes/",strlen("classes/"))==0) {
  1000.          m="classes/";
  1001.          for(p1=strstr(buf,":classes/");p1;p1=strstr(p1+1,":classes/")) {
  1002.           if(p1==buf || *(p1-1)=='\n') {
  1003.               p1+=strlen(":classes/");
  1004.               p2=find_word_end(p1); if(p2>p1 && *p2=='\n') ovlstrcpy(p1,p2);
  1005.           }
  1006.          }
  1007.      }
  1008.      snprintf(nbuf,sizeof(nbuf),":%s\n%s\n",m,rqv);
  1009.      p1=strstr(buf,nbuf);
  1010.      while(p1>buf && *(p1-1)!='\n') p1=strstr(p1+1,nbuf);
  1011.      if(p1!=NULL) {
  1012.          p2=strchr(buf,':');
  1013.          while(p2>buf && *(p2-1)!='\n') p2=strchr(p2+1,':');
  1014.          for(i=1;p2!=NULL && p2<p1;i++) {
  1015.           p2=strchr(p2+1,':');
  1016.           while(p2>buf && *(p2-1)!='\n') p2=strchr(p2+1,':');
  1017.          }
  1018.          if(p2==NULL) return; /* error which should not occur */
  1019.          snprintf(ubuf,sizeof(ubuf),"%d",i);
  1020. /* look for dependency information */
  1021.          for(j=0, p3=strchr(p1+strlen(nbuf),'\n');
  1022.           j<3 && p3 && *(p3+1)!=':';
  1023.           j++, p3=strchr(p3+1,'\n'));
  1024.          if(j>=3 && p3!=NULL && *(p3+1)!=':') {
  1025.           p3++; p4=strchr(p3,'\n');
  1026.           if(p4) {
  1027.               *p4++=0; if(*p4!=':') { /* options */
  1028.                p5=strchr(p4,'\n'); if(p5) *p5=0;
  1029.                force_setvar("wims_exoption",p4);
  1030.               }
  1031.           }
  1032.           p3=find_word_start(p3); strip_trailing_spaces(p3);
  1033. /* non-empty dependency information */
  1034.           if(*p3 && !public_sheet) {
  1035.               exodepOK=depcheck(sh,i,p3);
  1036.               if(!exodepOK) setvar("wims_exodep","pending");
  1037.           }
  1038.          }
  1039.          if(public_sheet) {
  1040.           char bf[32];
  1041.           snprintf(bf,16,"P%s",sh);
  1042.           force_setvar("wims_sheet",bf);
  1043.          }
  1044.          else force_setvar("wims_sheet",sh);
  1045.          force_setvar("wims_exo",ubuf);
  1046.          wims_sheet=sheet; wims_exo=i;
  1047.      }
  1048.     }
  1049. }
  1050.  
  1051. /* user with class: whether exercise is registered
  1052.  * Returns 1 if got, 0 otherwise. */
  1053. int get_parmreg(void)
  1054. {
  1055.     char *p, *cl, *u, nbuf[MAX_FNAME+1];
  1056.     struct stat st;
  1057.  
  1058.     u=getvar("wims_user"); cl=getvar("wims_class");
  1059.     if(u==NULL || cl==NULL || *u==0 || *cl==0 || strcmp(u,"supervisor")==0
  1060.        || wims_sheet<=0 || wims_exo<=0) return 0;
  1061.     mkfname(nbuf,"%s/.parmreg/%s.%d.%d", class_dir,u,wims_sheet,wims_exo);
  1062.     p=getvar("wims_scorereg"); if(p!=NULL && strcmp(p,"suspend")==0) {
  1063.      unlink(nbuf); return 0;
  1064.     }
  1065.     if(stat(nbuf,&st)) return 0;
  1066. /* latency is 10 min. */
  1067.     if(st.st_mtime<nowtime-600 || st.st_mtime > nowtime) {
  1068.      unlink(nbuf); return 0;
  1069.     }
  1070.     if(open_working_file(&m_file,nbuf)!=0) return 0;
  1071.     mkfname(m_file.name,"parmreg/%s.%d.%d",u,wims_sheet,wims_exo);
  1072.     while(wgetline(tmplbuf,MAX_LINELEN, &m_file)!=EOF) {
  1073.      p=strchr(tmplbuf,'=');
  1074.      if(p==NULL || p<=tmplbuf || isspace(tmplbuf[0]) )
  1075. /* this time it is corrupted var file */
  1076.        internal_error("get_parmreg(): corrupt parmreg file.");
  1077.      *p=0;p++;
  1078.      if(strncmp(tmplbuf,var_prefix,strlen(var_prefix))!=0) setenv(tmplbuf,p,1);
  1079.      else if(tmplbuf[strlen(var_prefix)]!=0) force_setvar(tmplbuf+strlen(var_prefix),p);
  1080.     }
  1081.     parm_restore=1;
  1082.     close_working_file(&m_file,0); return 1;
  1083. }
  1084.  
  1085. /* set environment variables */
  1086. void set_variables(void)
  1087. {
  1088.     outputing=0; readnest=0;
  1089.     get_var_defs();
  1090.     set_vars_from_parm();
  1091.     if(cmd_type != cmd_new && cmd_type != cmd_renew) set_vars_from_session();
  1092.     else {
  1093.      set_init_parm();
  1094.      if(wims_sheet>0 && get_parmreg()) {
  1095.          cmd_type=cmd_resume; force_setvar("cmd","resume");
  1096.          var_proc(main_var_proc_file,0); return;
  1097.      }
  1098.      checkrafale();
  1099.      var_proc(var_init_file,0);
  1100.     }
  1101.     /* check_var_bounds(); */
  1102.     var_proc(main_var_proc_file,0);
  1103. }
  1104.  
  1105. /* Output a phtml file. */
  1106. void phtml_put(char *fname,int cache)
  1107. {
  1108.     int t;
  1109.     char tbuf[MAX_LINELEN+1];
  1110.  
  1111.     outputing=1;
  1112.      /* File not found; we give empty output, but no error message. */
  1113.     if(fname!=NULL && read_module_file(fname)!=0) return;
  1114.     if(untrust&6) get_var_privileges();
  1115.     while(m_file.linepointer<m_file.linecnt) {
  1116.      t=m_file.lines[m_file.linepointer].isstart;
  1117.      if((t&~18)!=1) {m_file.linepointer++; continue;}
  1118.      wgetline(tbuf,MAX_LINELEN,&m_file); substnest=0;
  1119.      if((t&2)!=0) {exec_main(tbuf+1); continue;}
  1120.      substit(tbuf); output0(tbuf); _output_("\n");
  1121.     }
  1122.     close_working_file(&m_file,cache);
  1123. }
  1124.  
  1125. /* output a file in base html directory. Internal use only. */
  1126. void phtml_put_base(char *fname,int cache)
  1127. {
  1128.     WORKING_FILE save;
  1129.     char modsave[MAX_FNAME+1];
  1130.     memmove(&save,&m_file,sizeof(WORKING_FILE));
  1131.     mystrncpy(modsave,module_prefix,sizeof(modsave));
  1132.     ovlstrcpy(module_prefix,"html");
  1133.     phtml_put(fname,cache);
  1134.     mystrncpy(module_prefix,modsave,sizeof(module_prefix));
  1135.     memmove(&m_file,&save,sizeof(WORKING_FILE));
  1136. }
  1137.  
  1138. /* Read main.phtml, process it, and write to stdout. */
  1139. void main_phtml_put(char *mname)
  1140. {
  1141.     char *p, buf[1024], txbuf[256], dirnbuf[256], bgbuf[256], spfbuf[256];
  1142.     char *bcolor, *refcolor, *bg, *tx, *dirn, *vlink, *link, *spf ;
  1143.     define_html_header(); readnest=0;
  1144.     nph_header(200);
  1145.     p=getvar("wims_backslash_insmath");
  1146.     if(p!=NULL && strcasecmp(p,"yes")==0) backslash_insmath=1;
  1147.     p=getvar("wims_expire");
  1148.     if(p!=NULL) p=strstr(p,"no-cache");
  1149.     if(p!=NULL) _output_("Cache-Control: no-cache\r\nPragma: no-cache\r\n");
  1150.     output("Server: %s %s (%s)\n", SHORTSWNAME,wims_version,LONGSWNAME);
  1151.     if(!robot_access && strcasecmp(usecookie,"yes")==0 && setcookie
  1152.        && mode!=mode_popup) {
  1153.      if(cookieset[0]==0) {
  1154.          p=getvar("wims_sescookie");
  1155.          if(p!=NULL && *p!=0) mystrncpy(cookieset,p,sizeof(cookieset));
  1156.      }
  1157.      output("Set-Cookie: %s%s; path=/\r\n",cookieheader,cookieset);
  1158.     }
  1159.     p=getvar("wims_main_font");
  1160.     if(p!=NULL && *p!=0) output("Content-type: text/html; charset=%s\r\n\r\n",p);
  1161.     else _output_("Content-type: text/html\r\n\r\n");
  1162.     bcolor=getvar("wims_bgcolor");
  1163.     if(bcolor==NULL || *bcolor==0) bcolor=bgcolor;
  1164.     link=getvar("wims_link_color");
  1165.     if(link==NULL || *link==0) link="blue";
  1166.     vlink=getvar("wims_vlink_color");
  1167.     if(vlink==NULL || *vlink==0) vlink="blue";
  1168.     refcolor=getvar("wims_ref_bgcolor");
  1169.     if(refcolor==NULL || *refcolor==0) {
  1170.      setvar("wims_ref_bgcolor","white");
  1171.      refcolor="white";
  1172.     }
  1173.     bg=getvar("wims_bgimg"); bgbuf[0]=0;
  1174.     if(bg!=NULL && *bg!=0 && strchr(bg,'\"')==NULL) {
  1175.      if(strchr(bg,'/')==NULL)
  1176.        snprintf(bgbuf,sizeof(bgbuf),"background-image: url(\"gifs/bg/%s\");",bg);
  1177.      else
  1178.        snprintf(bgbuf,sizeof(bgbuf),"background-image: url(\"%s\");",bg);
  1179.     }
  1180.     setvar("wims_bodyimg",bgbuf);
  1181.     tx=getvar("wims_textcolor");
  1182.     if(tx!=NULL && *tx!=0 && strchr(tx,'\"')==NULL) {
  1183.      snprintf(txbuf,sizeof(txbuf),"color:%s;",tx);
  1184.     }
  1185.     else txbuf[0]=0;
  1186.    /* special fonts defined in special_font -should also take the value specialfont in wims.conf */
  1187.     if(spec_font==1){
  1188.         spf=getvar("wims_specialfont");
  1189.         if(spf!=NULL && *spf!=0) { snprintf(spfbuf,sizeof(spfbuf),"%s",spf);}
  1190.           else { snprintf(spfbuf,sizeof(spfbuf),"%s",special_font); }
  1191.         setvar("wims_special_font",spfbuf);
  1192.     }
  1193.     dirn=getvar("wims_main_dirn");     /* "rtl" for arabic writing ; on pourrait laisser vide pour les autres ? */
  1194.     if(dirn!=NULL && *dirn!=0 && strchr(dirn,'\"')==NULL) {
  1195.      snprintf(dirnbuf,sizeof(dirnbuf),"dir=\"%s\"",dirn);
  1196.     }
  1197.     else dirnbuf[0]=0;
  1198.     snprintf(buf,sizeof(buf),
  1199.           "class=\"main_body\" %s",dirnbuf);
  1200.     setvar("wims_htmlbody",buf);
  1201.     phtml_put(mname,0);
  1202. }
  1203.  
  1204. void _write_var(char *name, FILE *varf,int user,int skip)
  1205. {
  1206.     char *s, buf[MAX_NAMELEN+9], nbf[MAX_NAMELEN+9];
  1207.  
  1208.     if((user&2)!=0) {
  1209.      snprintf(nbf,sizeof(nbf),"%s%s",wims_prefix,name); name=nbf;
  1210.     }
  1211.     if((user&1)!=0) {
  1212.      snprintf(buf,sizeof(buf),"%s%s",var_prefix,name); s=_getvar(name);
  1213.     }
  1214.     else {
  1215.      mystrncpy(buf,name,sizeof(buf)); s=getenv(name);
  1216.     }
  1217.     if(s==NULL) s="";
  1218.     if(skip && *s==0) return;
  1219.     fprintf(varf,"%s=",buf);
  1220.     if(strchr(s,'\n')==NULL) fputs(s,varf);
  1221.     else while(*s) {
  1222.        if(*s=='\n') fputc('\\',varf);
  1223.        fputc(*s,varf); s++;
  1224.     }
  1225.     fputc('\n',varf);
  1226. }
  1227.  
  1228. void _write_vars(FILE *varf)
  1229. {
  1230.     int i,j,k;
  1231.     char nbuf[MAX_NAMELEN+1];
  1232.     for(i=0;i<defined_var_total;i++) {
  1233.      if(var_def[i].beg>=0) {
  1234.          if(var_def[i].end<=var_def[i].beg) {
  1235.           snprintf(nbuf,sizeof(nbuf),"%s%d",var_def[i].name,var_def[i].beg);
  1236.           _write_var(nbuf,varf,1,1);
  1237.          }
  1238.          else {
  1239.           char *pbuf[MAX_VAR_NUM];
  1240.           j=varsuite(var_def[i].name,var_def[i].beg,var_def[i].end,pbuf,MAX_VAR_NUM);
  1241.           for(k=0;k<j;k++) _write_var(pbuf[k],varf,1,1);
  1242.          }
  1243.      }
  1244.      else _write_var(var_def[i].name,varf,1,1);
  1245.     }
  1246. }
  1247.  
  1248. /* save exercise parm for registered users */
  1249. void save_parmreg(void)
  1250. {
  1251.     char *p, *u, *sh, *ex, nbuf[MAX_FNAME+1], dbuf[MAX_FNAME+1];
  1252.     int s;
  1253.     FILE *varf;
  1254.  
  1255.     if(cmd_type!=cmd_reply && cmd_type!=cmd_new && cmd_type!=cmd_renew)
  1256.       return;
  1257.     u=getvar("wims_user");
  1258.     if(class_dir[0]==0 || *u==0) return;
  1259.     sh=getvar("wims_sheet"); ex=getvar("wims_exo");
  1260.     if(sh==NULL || ex==NULL || *sh==0 || *ex==0) return;
  1261.     mkfname(nbuf,"%s/.parmreg/%s.%s.%s",
  1262.           class_dir,u,sh,ex);
  1263.     if(cmd_type==cmd_reply) {
  1264.      unlink(nbuf); return;
  1265.     }
  1266.     p=getvar("wims_scorereg");
  1267.     if(p!=NULL && strcmp(p,"suspend")==0) return;
  1268. /* these two lines must be before random factor
  1269.  * in order to set variable wims_scoring */
  1270.     s=atoi(sh); if(getscorestatus(getvar("wims_class"),s)==0) return;
  1271.     if(strcmp(u,"supervisor")==0) return;
  1272. /* 0.2 is random factor to trigger exercise parm register */
  1273. /*    return;
  1274. */    if((double) random()>(double) RAND_MAX*0.2) return;
  1275.     mkfname(dbuf,"%s/.parmreg",class_dir);
  1276.     mkdirs(dbuf); varf=fopen(nbuf,"w"); if(varf==NULL) return;
  1277.     _write_var("module_init_parm",varf,1,0);
  1278.     _write_var("wims_sheet",varf,1,1);
  1279.     _write_var("wims_exo",varf,1,1);
  1280.     _write_var("wims_scoring",varf,1,1);
  1281.     _write_vars(varf);
  1282.     fclose(varf);
  1283. }
  1284.  
  1285. void exolog(char *fname)
  1286. {
  1287.     FILE *varf, *varg;
  1288.     int c;
  1289.     char logftmp[MAX_FNAME+1], *sess;
  1290.  
  1291. /* add by FG to put w_module_score at the top of the file */
  1292.     if ((getenv("w_module_score"))!=NULL )
  1293.     {
  1294.      sess=getvar("wims_session");
  1295.      mkfname(logftmp,"%s/%s/.tmp%lu",s2_dir,sess,nowtime);
  1296.      rename(fname,logftmp);
  1297.      varf=fopen(fname,"a");
  1298.      if(varf!=NULL) {
  1299.          _write_var("module_score",varf,1,1);
  1300.          varg=fopen(logftmp, "r");
  1301.          if(varg!=NULL) {
  1302.           while ( (c=getc (varg)) != EOF)
  1303.           putc (c,varf);
  1304.           fclose(varg);
  1305.          }
  1306.          fclose(varf);
  1307.          remove(logftmp);
  1308.      }
  1309.     }
  1310. /* end of add */
  1311.     varf=fopen(fname,"a");
  1312.     if(varf!=NULL) {
  1313. /* The first 4 lines should not be modified */
  1314.      fprintf(varf,"\n:\n");
  1315.      _write_var("QUERY_STRING",varf,0,0);
  1316.      _write_var("module",varf,1,0);
  1317.      _write_var("cmd",varf,1,0);
  1318.      _write_var("module_init_parm",varf,1,0);
  1319.      _write_var("wims_scoring",varf,1,1);
  1320.      _write_var("module_score",varf,1,1);
  1321.      fprintf(varf,"w_wims_checktime1=%lu\n\
  1322. w_wims_checktime2=%s\n",nowtime,nowstr);
  1323.      _write_vars(varf);
  1324.      fclose(varf);
  1325.     }
  1326. }
  1327.  
  1328. /* save variables to session var file */
  1329. void save_session_vars(void)
  1330. {
  1331.     int i;
  1332.     char *mp, *sh, *ex, *ll;
  1333.     FILE *varf;
  1334. /* light pages don't need saved variables. ? */
  1335. /*    if(varchr(module_prefix,"light")!=NULL) return;*/
  1336.     if(robot_access) return;
  1337. /* no variable saving if cmd=help? */
  1338.     if(cmd_type==cmd_help) return;
  1339.     lastdatafile[0]=lastftest[0]=0;
  1340.     lessrafale();
  1341.     mp=getvar("wims_nextmodule"); if(mp!=NULL && *mp!=0) {
  1342.      mp=getvar("module"); if(strcmp(mp,home_module)==0)
  1343.        force_setvar("module",getvar("wims_nextmodule"));
  1344.     }
  1345.     varf=fopen_session_var_file("w");
  1346.     for(i=0;i<HEADER_VAR_NO;i++)
  1347.       _write_var(header_var_name[i],varf,0,0);
  1348.     for(i=0;i<RO_NAME_NO;i++)
  1349.       _write_var(ro_name[i],varf,1,0);
  1350.     for(i=0;i<INTERNAL_NAME_NO;i++) {
  1351.      if(internal_name[i].stat==0)
  1352.        _write_var(internal_name[i].name,varf,3,0);
  1353.     }
  1354.     _write_var("password",varf,0,1);
  1355.     save_parmreg();
  1356.     if(new_session) fprintf(varf,"wims_new_session=yes\n");
  1357.     fprintf(varf,"\n");
  1358.     _write_var("module_init_parm",varf,1,0);
  1359.     _write_var("wims_sheet",varf,1,1);
  1360.     _write_var("wims_exo",varf,1,1);
  1361.     _write_var("wims_scoring",varf,1,1);
  1362.     _write_vars(varf);
  1363.     fclose(varf);
  1364.     if(cmd_type==cmd_new || cmd_type==cmd_renew || cmd_type==cmd_reply || cmd_type==cmd_next) {
  1365.      ll=getvar("wims_class_examlog");
  1366.      if(ll!=NULL && *ll!=0) i=atoi(ll); else i=examlog_limit;
  1367.      if(strstr(session_prefix,"_exam")!=NULL && examlogf[0]!=0 &&
  1368.         simuxam==0 && i>0) {
  1369.          mkdirs(examlogd); exolog(examlogf);
  1370.      }
  1371.      else {
  1372.          ll=getvar("wims_class_exolog");
  1373.          sh=getvar("wims_sheet"); ex=getvar("wims_exo");
  1374.          if(ll!=NULL && atoi(ll)>0 &&
  1375.             sh!=NULL && *sh!=0 && ex!=NULL && *ex!=0) {
  1376.           char buf[MAX_FNAME+1];
  1377.           mkfname(buf,"%s/exolog.%s.%s",session_prefix,sh,ex);
  1378.           if(cmd_type==cmd_new || cmd_type==cmd_renew) unlink(buf);
  1379.           exolog(buf);
  1380.          }
  1381.      }
  1382.     }
  1383.     if(var_def_buf) free(var_def_buf);
  1384. }
  1385.  
  1386.