Subversion Repositories wimsdev

Rev

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

  1. /*    Copyright (C) 1998-2003 XIAO, Gang of Universite de Nice - Sophia Antipolis
  2.  *
  3.  *  This program is free software; you can redistribute it and/or modify
  4.  *  it under the terms of the GNU General Public License as published by
  5.  *  the Free Software Foundation; either version 2 of the License, or
  6.  *  (at your option) any later version.
  7.  *
  8.  *  This program is distributed in the hope that it will be useful,
  9.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.  *  GNU General Public License for more details.
  12.  *
  13.  *  You should have received a copy of the GNU General Public License
  14.  *  along with this program; if not, write to the Free Software
  15.  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16.  */
  17. /* 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; if(j>MAX_VAR_NUM) j=MAX_VAR_NUM;
  679.      var_def[v].beg=1; var_def[v].end=j;
  680.      return j;
  681.     }
  682.     if(*q) goto illegal;
  683.     for(r=q; r>n && myisdigit(*(r-1)); r--);
  684.     if(*r && *r!='0' && r>n) {
  685.      var_def[v].beg=var_def[v].end=atoi(r); *r=0;
  686.     }
  687.     else var_def[v].beg=var_def[v].end=-1;
  688.     return 1;
  689. }
  690.  
  691. int var_def_allow(char *p, int v)
  692. {
  693.     int i;
  694.     for(i=0;i<VAR_ALLOW_NO && strcasecmp(p,var_allow[i])!=0; i++);
  695.     if(i>=VAR_ALLOW_NO) module_error("bad_allow");
  696.     else var_def[v].allow=i;
  697.     return i;
  698. }
  699.  
  700. int varsort(const void *p1, const void *p2)
  701. {
  702.     int i; const struct VAR_DEF *pp1, *pp2;
  703.     pp1=p1; pp2=p2; i=strcmp(pp1->name,pp2->name);
  704.     if(i) return i; else return pp1->end - pp2->end;
  705. }
  706.  
  707.      /* parse module's variable definitions */
  708. void get_var_defs(void)
  709. {
  710.     int i, j, k, v, add;
  711.     char *p, *p1, *wlist[MAX_VAR_NUM];
  712.  
  713.     defined_var_total=0;
  714.     if(read_module_file(var_def_file)!=0) return;
  715.     var_def_buf=m_file.textbuf;
  716.     for(m_file.l=v=add=0;v<MAX_VAR_NUM && m_file.l<m_file.linecnt;m_file.l++) {
  717.      if(m_file.lines[m_file.l].isstart!=1) continue;
  718.      p=find_word_start(m_file.lines[m_file.l].address);
  719.      if(*p==0 || *p==comment_prefix_char) continue;  /* empty or comment lines */
  720.      items2words(p);
  721.      if((p1=strchr(p,':'))!=NULL) {  /* new format */
  722.          *p1=' '; i=cutwords(p,wlist,MAX_VAR_NUM); if(i<=1) continue;
  723.          k=var_def_allow(wlist[0],v);
  724.          for(j=1;j<i && v<MAX_VAR_NUM;j++) {
  725.           add+=var_def_name(wlist[j],v); var_def[v].allow=k;
  726.           v++;
  727.          }
  728.      }
  729.      else {
  730.          i=cutwords(p,wlist,3); if(i<2) module_error("too_few_columns");
  731.          add+=var_def_name(wlist[0],v); var_def_allow(wlist[1],v);
  732.          var_def[v].defined_in_parm=0;
  733.          v++;
  734.      }
  735.     }
  736.     if(v>=MAX_VAR_NUM) module_error("too_many_variables");
  737.     defined_var_total=v;
  738.     qsort(var_def,v,sizeof(var_def[0]),varsort);
  739.     p=getvar(ro_name[ro_module]);
  740.     if(p==NULL || strncmp(p,"devel/",6)!=0) return;
  741.     for(v=1;v<defined_var_total;v++) {
  742.      if(strcmp(var_def[v].name,var_def[v-1].name)==0 &&
  743.         var_def[v].beg<=var_def[v-1].end) {
  744.          setvar("wims_bad_name",var_def[v].name);
  745.          module_error("multiple_declaration");
  746.      }
  747.     }
  748. }
  749.  
  750. /* returns 1 if hacked, else 0. */
  751. int try_hack(char *var)
  752. {
  753.     int i, al;
  754.     char vbuf[16];
  755.     i=var_def_check(var);
  756.     if(i<0) return 0;
  757.     al=var_def[i].allow;
  758.     if(al != var_allow_any) switch(cmd_type) {
  759.      case cmd_new:
  760.      case cmd_renew: {
  761.          if (al != var_allow_init && al != var_allow_config) return 0;
  762.          else break;
  763.      }
  764.      case cmd_config: {
  765.          if(al != var_allow_config) return 0;
  766.          else break;
  767.      }
  768.      case cmd_reply: {
  769.          if(al != var_allow_reply) return 0;
  770.          else break;
  771.      }
  772.      case cmd_help: {
  773.          if(al != var_allow_help) return 0;
  774.          else break;
  775.      }
  776.      default: return 0;
  777.     }
  778.     snprintf(vbuf,sizeof(vbuf),"%d",(int) irand(21));
  779.     var_hacking=1; setvar(var,vbuf); var_hacking=0;
  780.     return 1;
  781. }
  782.  
  783. /* set environ variables from last session save
  784.  * The session var file starts with variables which should not
  785.  * be restored. Variables which are restored follow a blank line. */
  786. void set_vars_from_session(void)
  787. {
  788.     char lbuf[MAX_LINELEN+1];
  789.     int i;
  790.     char *p;
  791.  
  792.     if(session_var_ready) memmove(&m_file,&svar_file,sizeof(WORKING_FILE));
  793.     else fopen_session_var_file("r");
  794. /* look for the first blank line. */
  795.     for(i=0;i<m_file.linecnt && (m_file.lines[i].isstart==0 || m_file.lines[i].llen>0);i++);
  796.     for(i++;i<m_file.linecnt && m_file.lines[i].llen==0;i++);
  797.     if(i>=m_file.linecnt) return;
  798.     m_file.linepointer=i;
  799.     if(isdevelmodule && strstr(session_prefix,"_test")==NULL) isdevelmodule=0;
  800.     while(wgetline(lbuf,MAX_LINELEN, &m_file)!=EOF) {
  801.      p=strchr(lbuf,'=');
  802.      if(p==NULL || p<=lbuf || isspace(lbuf[0]) ) {
  803. /* this time it is corrupted var file */
  804.        call_ssh("cat %s/var >%s/corrupt.var.bak",session_prefix,log_dir);
  805.        internal_error("get_vars_from_session(): corrupt session variable file.");
  806.      }
  807.      *p=0;p++;
  808. /* Here we suppose that nobody can tamper session variable
  809.  * file, and do not check variable names against module's
  810.  * definition file. Policy under reserve. */
  811. /* We do not allow override though.
  812.  * Especially because reply variables should
  813.  * be preserved. */
  814.      if(strncmp(lbuf,var_prefix,strlen(var_prefix))!=0)
  815.        setenv(lbuf,p,0);
  816.      else if(lbuf[strlen(var_prefix)]!=0 && getvar(lbuf+strlen(var_prefix))==NULL) {
  817.          if(!isdevelmodule || !try_hack(lbuf+strlen(var_prefix))) {
  818.           setvar(lbuf+strlen(var_prefix),p);
  819.          }
  820.      }
  821.     }
  822.     close_working_file(&m_file,0);
  823. }
  824.  
  825. void start_tracefile(void)
  826. {
  827.   int i;
  828.   putc('\n',trace_file);
  829.   for(i=1; i<=2*trace_indent; i++) putc(' ',trace_file);
  830.   fprintf(trace_file,"%s:",m_file.filepath);
  831.   fflush(trace_file);
  832.   trace_indent++;
  833. }
  834.  
  835. void stop_tracefile(void)
  836. {
  837.   trace_indent--;
  838. }
  839.  
  840. /* Initialize environment variables according to module's
  841.  * variable init or calculation file.
  842.  * init is only used when cmd=new or renew.
  843.  * Requires get_var_defs be run first. */
  844. void var_proc(char *fname,int cache)
  845. {
  846.     int  t;
  847.     char *p, tbuf[MAX_LINELEN+1];
  848.  
  849.     if(fname!=NULL && read_module_file(fname)) return;
  850.     if(untrust&6) get_var_privileges();
  851.     if (trace_file) start_tracefile();
  852.     while(m_file.linepointer<m_file.linecnt) {
  853.      if (trace_file) {fprintf(trace_file," %d",m_file.linepointer+1);
  854.        fflush(trace_file); }
  855.      t=m_file.lines[m_file.linepointer].isstart;
  856.      if((t&~2)!=1 || m_file.lines[m_file.linepointer].llen==0) {
  857.          m_file.linepointer++; continue;
  858.      }
  859.      wgetline(tbuf,MAX_LINELEN,&m_file); substnest=0;
  860.      p=find_word_start(tbuf); if(*p==0) continue;
  861.      if((t&2)!=0) exec_main(p+1);
  862.      else exec_set(p);
  863.     }
  864.     if (trace_file) stop_tracefile();
  865.     close_working_file(&m_file,cache);
  866. }
  867.  
  868. /* Deposit the content of wims_deposit into a file */
  869. void var_deposit(char *p)
  870. {
  871.     char fn[MAX_FNAME+1];
  872.     int l,fd;
  873.     if(!trusted_module()) return;
  874.     if(deplen>0) l=deplen; else {
  875.      while(isspace(*p)) p++; l=strlen(p);
  876.     }
  877.     if(l<=0) return;
  878.     if(l>MAX_DEPOSITLEN) l=MAX_DEPOSITLEN; /* silent truncation, should not occur */
  879.     mkfname(fn,"%s/user-deposit",session_prefix);
  880.     fd=creat(fn,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if(fd==-1) return;
  881.     write(fd,p,l); close(fd);
  882.     snprintf(fn,sizeof(fn),"%u",l); setvar("wims_deposit_len",fn);
  883. }
  884.  
  885. /* Check and set variables passed in query_string */
  886. void set_vars_from_parm(void)
  887. {
  888.     int i,j,al;
  889.     char *s, vbuf[MAX_LINELEN+1];
  890.     if(forceresume) return;
  891.     for(i=0; i<user_var_no; i++) {
  892.      j=var_def_check(user_variable[i].name);
  893.      if(j<0) continue;
  894. /* check permissions */
  895.      al=var_def[j].allow;
  896.      if(al != var_allow_any) switch(cmd_type) {
  897.          case cmd_new:
  898.          case cmd_renew:
  899.              if (al != var_allow_init && al != var_allow_config) {
  900. violat:        /* setvar(error_data_string,user_variable[i].name);
  901.               user_error("allow_violation"); */
  902.               goto loopend;
  903.           }
  904.              break;
  905.  
  906.          case cmd_config:
  907.              if(al != var_allow_config) goto violat;
  908.              break;
  909.  
  910.          case cmd_reply:
  911.               if(al != var_allow_reply) goto violat;
  912.              break;
  913.  
  914.          case cmd_help:
  915.               if(al != var_allow_help) goto violat;
  916.               break;
  917.  
  918.          default: goto violat;
  919.      }
  920.      var_def[j].defined_in_parm=1;
  921.      if(strcmp(user_variable[i].name,"wims_deposit")==0) {
  922.          var_deposit(user_variable[i].value); continue;
  923.      }
  924.      mystrncpy(vbuf,user_variable[i].value,sizeof(vbuf));
  925.      if(strchr(vbuf,'$')!=NULL) {
  926.          char *p;
  927.          while((p=strchr(vbuf,'$'))!=NULL)
  928.            string_modify(vbuf,p,p+1,"&#36;");
  929.      }
  930.      s=getvar(user_variable[i].name);
  931.      if(s==NULL || *s==0) setvar(user_variable[i].name, vbuf);
  932.      else {  /* concatenate */
  933.          int k;
  934.          k=strlen(s)+strlen(vbuf);
  935.          if(k>=MAX_LINELEN-2) user_error("string_too_long");
  936.          snprintf(tmplbuf,sizeof(tmplbuf),"%s, %s",s,vbuf);
  937.          setvar(user_variable[i].name, tmplbuf);
  938.      }
  939.      loopend: ;
  940.     }
  941. }
  942.  
  943. /* parms to be eliminated from module_init_parm */
  944. /* char *init_elim[]={
  945.     "module","cmd","session","lang","worksheet","wims_access","useropts"
  946. };
  947. #define init_elim_no (sizeof(init_elim)/sizeof(init_elim[0]))
  948. */
  949.  
  950. void elim_parm(char *str, char *parm)
  951. {
  952.     char *p1, *p2;
  953.     for(p1=strstr(str,parm);p1!=NULL;p1=strstr(p1+1,parm)) {
  954.      if( (p1>str && *(p1-1)!='&') || *(p1+strlen(parm))!='=')
  955.        continue;
  956.      p2=strchr(p1,'&');
  957.      if(p2==NULL) {
  958.          if(p1>str) *(p1-1)=0; else *p1=0;
  959.          return;
  960.      }
  961.      ovlstrcpy(p1,p2+1); p1--;
  962.     }
  963. }
  964.  
  965. /* eliminate technical definitions form parameter string. */
  966. void prep_init_parm(char rqv[])
  967. {
  968.     int i;
  969.     char *p;
  970.  
  971.     for(p=strstr(rqv,"&+"); p!=NULL; p=strstr(++p,"&+"))
  972.       ovlstrcpy(p+1,p+2);
  973.     for(i=0;i<RO_NAME_NO;i++) elim_parm(rqv,ro_name[i]);
  974.     if(strlen(rqv)>=MAX_LINELEN) rqv[0]=0;
  975.     while(rqv[0]=='&') ovlstrcpy(rqv,rqv+1);
  976.     while(rqv[0]!=0 && rqv[strlen(rqv)-1]=='&') rqv[strlen(rqv)-1]=0;
  977. }
  978.  
  979. /* retain initializing parameters, for use in user references */
  980. void set_init_parm(void)
  981. {
  982.     char *rq, rqv[MAX_LINELEN*2+2], *u, *sh;
  983.     char *shname;
  984.     int public_sheet;
  985.  
  986.     if(isexam) return;
  987.     force_setvar("wims_sheet",""); force_setvar("wims_exo","");
  988.     rq=getenv("QUERY_STRING");
  989.     if(rq==NULL || *rq==0) {
  990.      empty:
  991.      setvar("module_init_parm",""); return;
  992.     }
  993.     if(strlen(rq)>=MAX_LINELEN*2) goto empty;
  994.     _http2env(rqv,rq); prep_init_parm(rqv);
  995.     setvar("module_init_parm",rqv); public_sheet=0;
  996. /* now determine the sheet number for user */
  997.     sh=getvar(ro_name[ro_worksheet]); if(sh==NULL) return;
  998.     if(*sh=='P') {public_sheet=1; sh++;}
  999.     shname="sheet";
  1000.     u=getvar("wims_user"); if(u==NULL) u="";
  1001.     if(sh!=NULL && *sh!=0) {
  1002.      char buf[MAX_LINELEN+1],ubuf[32], nbuf[1024], *c, *m;
  1003.      char *p1,*p2,*p3,*p4,*p5;
  1004.      int i,j,sheet;
  1005.      sheet=atoi(sh); if(sheet<=0 || sheet>256) return;
  1006.      m=getvar(ro_name[ro_module]);
  1007.      if(m==NULL) internal_error("set_init_parm(): module name disapears.");
  1008.      if(*u==0) public_sheet=1;
  1009.      if(!public_sheet) {
  1010.          c=getvar("wims_class"); if(c==NULL) c="";
  1011.          snprintf(nbuf,sizeof(nbuf),"%s/sheets/.%s%d",
  1012.                class_dir,shname,sheet);
  1013.      }
  1014.      else {
  1015.          char bf[MAX_LINELEN+1];
  1016.          int i;
  1017.          accessfile(bf,"r","%s/.sheets",session_prefix);
  1018.          if(bf[0]==0) return;
  1019.          for(i=1, p1=bf;i<sheet;i++,p1=p2) {
  1020.           p2=strchr(p1,'\n');
  1021.           if(p2!=NULL) *p2++=0; else p2=p1+strlen(p1);
  1022.          }
  1023.          p2=strchr(p1,'\n'); if(p2) *p2=0;
  1024.          snprintf(nbuf,sizeof(nbuf),"bases/sheet/%s.def",p1);
  1025.      }
  1026.      if(readfile(nbuf,buf,sizeof(buf))==NULL) return;
  1027.      for(p1=strstr(buf,"&+");p1!=NULL;p1=strstr(++p1,"&+"))
  1028.          ovlstrcpy(p1+1,p1+2);
  1029.      if(strncmp(m,"classes/",strlen("classes/"))==0) {
  1030.          m="classes/";
  1031.          for(p1=strstr(buf,":classes/");p1;p1=strstr(p1+1,":classes/")) {
  1032.           if(p1==buf || *(p1-1)=='\n') {
  1033.               p1+=strlen(":classes/");
  1034.               p2=find_word_end(p1); if(p2>p1 && *p2=='\n') ovlstrcpy(p1,p2);
  1035.           }
  1036.          }
  1037.      }
  1038.      snprintf(nbuf,sizeof(nbuf),":%s\n%s\n",m,rqv);
  1039.      p1=strstr(buf,nbuf);
  1040.      while(p1>buf && *(p1-1)!='\n') p1=strstr(p1+1,nbuf);
  1041.      if(p1!=NULL) {
  1042.          p2=strchr(buf,':');
  1043.          while(p2>buf && *(p2-1)!='\n') p2=strchr(p2+1,':');
  1044.          for(i=1;p2!=NULL && p2<p1;i++) {
  1045.           p2=strchr(p2+1,':');
  1046.           while(p2>buf && *(p2-1)!='\n') p2=strchr(p2+1,':');
  1047.          }
  1048.          if(p2==NULL) return; /* error which should not occur */
  1049.          snprintf(ubuf,sizeof(ubuf),"%d",i);
  1050. /* look for dependency information */
  1051.          for(j=0, p3=strchr(p1+strlen(nbuf),'\n');
  1052.           j<3 && p3 && *(p3+1)!=':';
  1053.           j++, p3=strchr(p3+1,'\n'));
  1054.          if(j>=3 && p3!=NULL && *(p3+1)!=':') {
  1055.           p3++; p4=strchr(p3,'\n');
  1056.           if(p4) {
  1057.               *p4++=0; if(*p4!=':') { /* options */
  1058.                p5=strchr(p4,'\n'); if(p5) *p5=0;
  1059.                force_setvar("wims_exoption",p4);
  1060.               }
  1061.           }
  1062.           p3=find_word_start(p3); strip_trailing_spaces(p3);
  1063. /* non-empty dependency information */
  1064.           if(*p3 && !public_sheet) {
  1065.               exodepOK=depcheck(sh,i,p3);
  1066.               if(!exodepOK) setvar("wims_exodep","pending");
  1067.           }
  1068.          }
  1069.          if(public_sheet) {
  1070.           char bf[32];
  1071.           snprintf(bf,16,"P%s",sh);
  1072.           force_setvar("wims_sheet",bf);
  1073.          }
  1074.          else force_setvar("wims_sheet",sh);
  1075.          force_setvar("wims_exo",ubuf);
  1076.          wims_sheet=sheet; wims_exo=i;
  1077.      }
  1078.     }
  1079. }
  1080.  
  1081. /* user with class: whether exercise is registered
  1082.  * Returns 1 if got, 0 otherwise. */
  1083. int get_parmreg(void)
  1084. {
  1085.     char *p, *cl, *u, nbuf[MAX_FNAME+1];
  1086.     struct stat st;
  1087.  
  1088.     u=getvar("wims_user"); cl=getvar("wims_class");
  1089.     if(u==NULL || cl==NULL || *u==0 || *cl==0 || strcmp(u,"supervisor")==0
  1090.        || wims_sheet<=0 || wims_exo<=0) return 0;
  1091.     mkfname(nbuf,"%s/.parmreg/%s.%d.%d", class_dir,u,wims_sheet,wims_exo);
  1092.     p=getvar("wims_scorereg"); if(p!=NULL && strcmp(p,"suspend")==0) {
  1093.      unlink(nbuf); return 0;
  1094.     }
  1095.     if(stat(nbuf,&st)) return 0;
  1096. /* latency is 10 min. */
  1097.     if(st.st_mtime<nowtime-600 || st.st_mtime > nowtime) {
  1098.      unlink(nbuf); return 0;
  1099.     }
  1100.     if(open_working_file(&m_file,nbuf)!=0) return 0;
  1101.     mkfname(m_file.name,"parmreg/%s.%d.%d",u,wims_sheet,wims_exo);
  1102.     while(wgetline(tmplbuf,MAX_LINELEN, &m_file)!=EOF) {
  1103.      p=strchr(tmplbuf,'=');
  1104.      if(p==NULL || p<=tmplbuf || isspace(tmplbuf[0]) )
  1105. /* this time it is corrupted var file */
  1106.        internal_error("get_parmreg(): corrupt parmreg file.");
  1107.      *p=0;p++;
  1108.      if(strncmp(tmplbuf,var_prefix,strlen(var_prefix))!=0) setenv(tmplbuf,p,1);
  1109.      else if(tmplbuf[strlen(var_prefix)]!=0) force_setvar(tmplbuf+strlen(var_prefix),p);
  1110.     }
  1111.     parm_restore=1;
  1112.     close_working_file(&m_file,0); return 1;
  1113. }
  1114.  
  1115. /* set environment variables */
  1116. void set_variables(void)
  1117. {
  1118.     outputing=0; readnest=0;
  1119.     get_var_defs();
  1120.     set_vars_from_parm();
  1121.     if(cmd_type != cmd_new && cmd_type != cmd_renew) set_vars_from_session();
  1122.     else {
  1123.      set_init_parm();
  1124.      if(wims_sheet>0 && get_parmreg()) {
  1125.          cmd_type=cmd_resume; force_setvar("cmd","resume");
  1126.          var_proc(main_var_proc_file,0); return;
  1127.      }
  1128.      checkrafale();
  1129.      var_proc(var_init_file,0);
  1130.     }
  1131.     /* check_var_bounds(); */
  1132.     var_proc(main_var_proc_file,0);
  1133. }
  1134.  
  1135. /* Output a phtml file. */
  1136. void phtml_put(char *fname,int cache)
  1137. {
  1138.     int t;
  1139.     char tbuf[MAX_LINELEN+1];
  1140.  
  1141.     outputing=1;
  1142.      /* File not found; we give empty output, but no error message. */
  1143.     if(fname!=NULL && read_module_file(fname)!=0) return;
  1144.     if(untrust&6) get_var_privileges();
  1145.     if (trace_file) start_tracefile();
  1146.     while(m_file.linepointer<m_file.linecnt) {
  1147.          if (trace_file) { fprintf(trace_file," %d",m_file.linepointer+1);
  1148.                            fflush(trace_file); }
  1149.      t=m_file.lines[m_file.linepointer].isstart;
  1150.      if((t&~18)!=1) {m_file.linepointer++; continue;}
  1151.      wgetline(tbuf,MAX_LINELEN,&m_file); substnest=0;
  1152.      if((t&2)!=0) {exec_main(tbuf+1); continue;}
  1153.      substit(tbuf); output0(tbuf); _output_("\n");
  1154.     }
  1155.     if (trace_file) stop_tracefile();
  1156.     close_working_file(&m_file,cache);
  1157. }
  1158.  
  1159. /* output a file in base html directory. Internal use only. */
  1160. void phtml_put_base(char *fname,int cache)
  1161. {
  1162.     WORKING_FILE save;
  1163.     char modsave[MAX_FNAME+1];
  1164.     memmove(&save,&m_file,sizeof(WORKING_FILE));
  1165.     mystrncpy(modsave,module_prefix,sizeof(modsave));
  1166.     ovlstrcpy(module_prefix,"html");
  1167.     phtml_put(fname,cache);
  1168.     mystrncpy(module_prefix,modsave,sizeof(module_prefix));
  1169.     memmove(&m_file,&save,sizeof(WORKING_FILE));
  1170. }
  1171.  
  1172. /* Read main.phtml, process it, and write to stdout. */
  1173. void main_phtml_put(char *mname)
  1174. {
  1175.     char *p, buf[1024], txbuf[256], dirnbuf[256], bgbuf[256], spfbuf[256];
  1176.     char *bcolor, *refcolor, *bg, *tx, *dirn, *vlink, *link, *spf ;
  1177.     define_html_header(); readnest=0;
  1178.     nph_header(200);
  1179.     p=getvar("wims_backslash_insmath");
  1180.     if(p!=NULL && strcasecmp(p,"yes")==0) backslash_insmath=1;
  1181.     p=getvar("wims_expire");
  1182.     if(p!=NULL) p=strstr(p,"no-cache");
  1183.     if(p!=NULL) _output_("Cache-Control: no-cache\r\nPragma: no-cache\r\n");
  1184.     output("Server: %s %s (%s)\n", SHORTSWNAME,wims_version,LONGSWNAME);
  1185.     if(!robot_access && strcasecmp(usecookie,"yes")==0 && setcookie
  1186.        && mode!=mode_popup) {
  1187.      if(cookieset[0]==0) {
  1188.          p=getvar("wims_sescookie");
  1189.          if(p!=NULL && *p!=0) mystrncpy(cookieset,p,sizeof(cookieset));
  1190.      }
  1191.      output("Set-Cookie: %s%s; path=/\r\n",cookieheader,cookieset);
  1192.     }
  1193.     p=getvar("wims_main_font");
  1194.     if(p!=NULL && *p!=0) output("Content-type: text/html; charset=%s\r\n\r\n",p);
  1195.     else _output_("Content-type: text/html\r\n\r\n");
  1196.     bcolor=getvar("wims_bgcolor");
  1197.     if(bcolor==NULL || *bcolor==0) bcolor=bgcolor;
  1198.     link=getvar("wims_link_color");
  1199.     if(link==NULL || *link==0) link="blue";
  1200.     vlink=getvar("wims_vlink_color");
  1201.     if(vlink==NULL || *vlink==0) vlink="blue";
  1202.     refcolor=getvar("wims_ref_bgcolor");
  1203.     if(refcolor==NULL || *refcolor==0) {
  1204.      setvar("wims_ref_bgcolor","white");
  1205.      refcolor="white";
  1206.     }
  1207.     bg=getvar("wims_bgimg"); bgbuf[0]=0;
  1208.     if(bg!=NULL && *bg!=0 && strchr(bg,'\"')==NULL) {
  1209.      if(strchr(bg,'/')==NULL)
  1210.        snprintf(bgbuf,sizeof(bgbuf),"background-image: url(\"gifs/bg/%s\");",bg);
  1211.      else
  1212.        snprintf(bgbuf,sizeof(bgbuf),"background-image: url(\"%s\");",bg);
  1213.     }
  1214.     setvar("wims_bodyimg",bgbuf);
  1215.     tx=getvar("wims_textcolor");
  1216.     if(tx!=NULL && *tx!=0 && strchr(tx,'\"')==NULL) {
  1217.      snprintf(txbuf,sizeof(txbuf),"color:%s;",tx);
  1218.     }
  1219.     else txbuf[0]=0;
  1220.    /* special fonts defined in special_font -should also take the value specialfont in wims.conf */
  1221.     if(spec_font==1){
  1222.         spf=getvar("wims_specialfont");
  1223.         if(spf!=NULL && *spf!=0) { snprintf(spfbuf,sizeof(spfbuf),"%s",spf);}
  1224.           else { snprintf(spfbuf,sizeof(spfbuf),"%s",special_font); }
  1225.         setvar("wims_special_font",spfbuf);
  1226.     }
  1227.     dirn=getvar("wims_main_dirn");     /* "rtl" for arabic writing ; on pourrait laisser vide pour les autres ? */
  1228.     if(dirn!=NULL && *dirn!=0 && strchr(dirn,'\"')==NULL) {
  1229.      snprintf(dirnbuf,sizeof(dirnbuf),"dir=\"%s\"",dirn);
  1230.     }
  1231.     else dirnbuf[0]=0;
  1232.     snprintf(buf,sizeof(buf),
  1233.           "class=\"main_body\" %s",dirnbuf);
  1234.     setvar("wims_htmlbody",buf);
  1235.     phtml_put(mname,0);
  1236. }
  1237.  
  1238. void _write_var(char *name, FILE *varf,int user,int skip)
  1239. {
  1240.     char *s, buf[MAX_NAMELEN+9], nbf[MAX_NAMELEN+9];
  1241.  
  1242.     if((user&2)!=0) {
  1243.      snprintf(nbf,sizeof(nbf),"%s%s",wims_prefix,name); name=nbf;
  1244.     }
  1245.     if((user&1)!=0) {
  1246.      snprintf(buf,sizeof(buf),"%s%s",var_prefix,name); s=_getvar(name);
  1247.     }
  1248.     else {
  1249.      mystrncpy(buf,name,sizeof(buf)); s=getenv(name);
  1250.     }
  1251.     if(s==NULL) s="";
  1252.     if(skip && *s==0) return;
  1253.     fprintf(varf,"%s=",buf);
  1254.     if(strchr(s,'\n')==NULL) fputs(s,varf);
  1255.     else while(*s) {
  1256.        if(*s=='\n') fputc('\\',varf);
  1257.        fputc(*s,varf); s++;
  1258.     }
  1259.     fputc('\n',varf);
  1260. }
  1261.  
  1262. void _write_vars(FILE *varf)
  1263. {
  1264.     int i,j,k;
  1265.     char nbuf[MAX_NAMELEN+1];
  1266.     for(i=0;i<defined_var_total;i++) {
  1267.      if(var_def[i].beg>=0) {
  1268.          if(var_def[i].end<=var_def[i].beg) {
  1269.           snprintf(nbuf,sizeof(nbuf),"%s%d",var_def[i].name,var_def[i].beg);
  1270.           _write_var(nbuf,varf,1,1);
  1271.          }
  1272.          else {
  1273.           char *pbuf[MAX_VAR_NUM];
  1274.           j=varsuite(var_def[i].name,var_def[i].beg,var_def[i].end,pbuf,MAX_VAR_NUM);
  1275.           for(k=0;k<j;k++) _write_var(pbuf[k],varf,1,1);
  1276.          }
  1277.      }
  1278.      else _write_var(var_def[i].name,varf,1,1);
  1279.     }
  1280. }
  1281.  
  1282. /* save exercise parm for registered users */
  1283. void save_parmreg(void)
  1284. {
  1285.     char *p, *u, *sh, *ex, nbuf[MAX_FNAME+1], dbuf[MAX_FNAME+1];
  1286.     int s;
  1287.     FILE *varf;
  1288.  
  1289.     if(cmd_type!=cmd_reply && cmd_type!=cmd_new && cmd_type!=cmd_renew)
  1290.       return;
  1291.     u=getvar("wims_user");
  1292.     if(class_dir[0]==0 || *u==0) return;
  1293.     sh=getvar("wims_sheet"); ex=getvar("wims_exo");
  1294.     if(sh==NULL || ex==NULL || *sh==0 || *ex==0) return;
  1295.     mkfname(nbuf,"%s/.parmreg/%s.%s.%s",
  1296.           class_dir,u,sh,ex);
  1297.     if(cmd_type==cmd_reply) {
  1298.      unlink(nbuf); return;
  1299.     }
  1300.     p=getvar("wims_scorereg");
  1301.     if(p!=NULL && strcmp(p,"suspend")==0) return;
  1302. /* these two lines must be before random factor
  1303.  * in order to set variable wims_scoring */
  1304.     s=atoi(sh); if(getscorestatus(getvar("wims_class"),s)==0) return;
  1305.     if(strcmp(u,"supervisor")==0) return;
  1306. /* 0.2 is random factor to trigger exercise parm register */
  1307. /*    return;*/
  1308.     if((double) random()>(double) RAND_MAX*0.2) return;
  1309.     mkfname(dbuf,"%s/.parmreg",class_dir);
  1310.     mkdirs(dbuf); varf=fopen(nbuf,"w"); if(varf==NULL) return;
  1311.     _write_var("module_init_parm",varf,1,0);
  1312.     _write_var("wims_sheet",varf,1,1);
  1313.     _write_var("wims_exo",varf,1,1);
  1314.     _write_var("wims_scoring",varf,1,1);
  1315.     _write_vars(varf);
  1316.     fclose(varf);
  1317. }
  1318.  
  1319. void exolog(char *fname)
  1320. {
  1321.     FILE *varf, *varg;
  1322.     int c;
  1323.     char logftmp[MAX_FNAME+1], *sess;
  1324.  
  1325. /* add by FG to put w_module_score at the top of the file */
  1326.     if ((getenv("w_module_score"))!=NULL )
  1327.     {
  1328.      sess=getvar("wims_session");
  1329.      mkfname(logftmp,"%s/%s/.tmp%lu",s2_dir,sess,nowtime);
  1330.      rename(fname,logftmp);
  1331.      varf=fopen(fname,"a");
  1332.      if(varf!=NULL) {
  1333.          _write_var("module_score",varf,1,1);
  1334.          varg=fopen(logftmp, "r");
  1335.          if(varg!=NULL) {
  1336.           while ( (c=getc (varg)) != EOF)
  1337.           putc (c,varf);
  1338.           fclose(varg);
  1339.          }
  1340.          fclose(varf);
  1341.          remove(logftmp);
  1342.      }
  1343.     }
  1344. /* end of add */
  1345.     varf=fopen(fname,"a");
  1346.     if(varf!=NULL) {
  1347. /* The first 4 lines should not be modified */
  1348.      fprintf(varf,"\n:\n");
  1349.      _write_var("QUERY_STRING",varf,0,0);
  1350.      _write_var("module",varf,1,0);
  1351.      _write_var("cmd",varf,1,0);
  1352.      _write_var("module_init_parm",varf,1,0);
  1353.      _write_var("wims_scoring",varf,1,1);
  1354.      _write_var("module_score",varf,1,1);
  1355.      fprintf(varf,"w_wims_checktime1=%lu\n\
  1356. w_wims_checktime2=%s\n",nowtime,nowstr);
  1357.      _write_vars(varf);
  1358.      fclose(varf);
  1359.     }
  1360. }
  1361.  
  1362. /* save variables to session var file */
  1363. void save_session_vars(void)
  1364. {
  1365.     int i;
  1366.     char *mp, *sh, *ex, *ll;
  1367.     FILE *varf;
  1368. /* light pages don't need saved variables. ? */
  1369. /*    if(varchr(module_prefix,"light")!=NULL) return;*/
  1370.     if(robot_access) return;
  1371. /* no variable saving if cmd=help? */
  1372.     if(cmd_type==cmd_help) return;
  1373.     lastdatafile[0]=lastftest[0]=0;
  1374.     lessrafale();
  1375.     mp=getvar("wims_nextmodule"); if(mp!=NULL && *mp!=0) {
  1376.      mp=getvar("module"); if(strcmp(mp,home_module)==0)
  1377.        force_setvar("module",getvar("wims_nextmodule"));
  1378.     }
  1379.     varf=fopen_session_var_file("w");
  1380.     for(i=0;i<HEADER_VAR_NO;i++)
  1381.       _write_var(header_var_name[i],varf,0,0);
  1382.     for(i=0;i<RO_NAME_NO;i++)
  1383.       _write_var(ro_name[i],varf,1,0);
  1384.     for(i=0;i<INTERNAL_NAME_NO;i++) {
  1385.      if(internal_name[i].stat==0)
  1386.        _write_var(internal_name[i].name,varf,3,0);
  1387.     }
  1388.     _write_var("password",varf,0,1);
  1389.     save_parmreg();
  1390.     if(new_session) fprintf(varf,"wims_new_session=yes\n");
  1391.     fprintf(varf,"\n");
  1392.     _write_var("module_init_parm",varf,1,0);
  1393.     _write_var("wims_sheet",varf,1,1);
  1394.     _write_var("wims_exo",varf,1,1);
  1395.     _write_var("wims_scoring",varf,1,1);
  1396.     _write_vars(varf);
  1397.     fclose(varf);
  1398.     if(cmd_type==cmd_new || cmd_type==cmd_renew || cmd_type==cmd_reply || cmd_type==cmd_next) {
  1399.      ll=getvar("wims_class_examlog");
  1400.      if(ll!=NULL && *ll!=0) i=atoi(ll); else i=examlog_limit;
  1401.      if(strstr(session_prefix,"_exam")!=NULL && examlogf[0]!=0 &&
  1402.         simuxam==0 && i>0) {
  1403.          mkdirs(examlogd); exolog(examlogf);
  1404.      }
  1405.      else {
  1406.          ll=getvar("wims_class_exolog");
  1407.          sh=getvar("wims_sheet"); ex=getvar("wims_exo");
  1408.          if(ll!=NULL && atoi(ll)>0) {
  1409.            char buf[MAX_FNAME+1];
  1410.            if(sh!=NULL && *sh!=0 && ex!=NULL && *ex!=0){
  1411.              mkfname(buf,"%s/exolog.%s.%s",session_prefix,sh,ex);
  1412.            }
  1413.            else { mkfname(buf,"%s/exolog",session_prefix);}
  1414.            if(cmd_type==cmd_new || cmd_type==cmd_renew) unlink(buf);
  1415.            exolog(buf);
  1416.          }
  1417.       }
  1418.     }
  1419.     if(var_def_buf) free(var_def_buf);
  1420. }
  1421.