Subversion Repositories wimsdev

Rev

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