Subversion Repositories wimsdev

Rev

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