Subversion Repositories wimsdev

Rev

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