Subversion Repositories wimsdev

Rev

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

  1. /*    Copyright (C) 1998-2003 XIAO, Gang of Universite de Nice - Sophia Antipolis
  2.  *
  3.  *  This program is free software; you can redistribute it and/or modify
  4.  *  it under the terms of the GNU General Public License as published by
  5.  *  the Free Software Foundation; either version 2 of the License, or
  6.  *  (at your option) any later version.
  7.  *
  8.  *  This program is distributed in the hope that it will be useful,
  9.  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.  *  GNU General Public License for more details.
  12.  *
  13.  *  You should have received a copy of the GNU General Public License
  14.  *  along with this program; if not, write to the Free Software
  15.  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  16.  */
  17.  
  18. /* Web exerciser */
  19.  
  20. #include "wims.h"
  21.  
  22. struct {
  23.     char *name;
  24.     char *font;
  25. } charname[]={
  26.     {"en","iso-8859-1"},
  27.       {"fr","iso-8859-1"},
  28.       {"es","iso-8859-1"},
  29.       {"cn","gb2312"},
  30.       {"de","iso-8859-1"},
  31.       {"it","iso-8859-1"},
  32.       {"nl","iso-8859-1"},
  33.       {"si","iso-8859-2"},
  34.       {"ar","iso-8859-6"},
  35.       {"tw","big5"},
  36.       {"pt","iso-8859-1"},
  37.       {"ca","iso-8859-1"},
  38.       {"pt","iso-8859-1"},
  39.       {"ru","iso-8859-5"},
  40.       {"ty","iso-8859-13"}
  41. };
  42.  
  43. #define charname_no (sizeof(charname)/sizeof(charname[0]))
  44.  
  45. /* left to right or right to left writing */
  46. struct {
  47.     char *name;
  48.     char *dirn;
  49. } dirnname[]={
  50.     {"en","ltr"},
  51.       {"fr","ltr"},
  52.       {"es","ltr"},
  53.       {"cn","ltr"},
  54.       {"de","ltr"},
  55.       {"it","ltr"},
  56.       {"nl","ltr"},
  57.       {"si","ltr"},
  58.       {"ar","rtl"},
  59.       {"tw","ltr"},
  60.       {"pt","ltr"},
  61.       {"ca","ltr"},
  62.       {"pt","ltr"},
  63.       {"ru","ltr"},
  64.       {"ty","ltr"}
  65.  
  66. };
  67.  
  68. #define dirnname_no (sizeof(dirnname)/sizeof(dirnname[0]))
  69.  
  70.  
  71. #define evalue strevalue
  72. char *robot_session="../tmp/robot";
  73. int robot_access=0,human_access=0;
  74. int user_error_nolog=0;
  75. char *good_agent[]={
  76.       "Mozilla","Netscape","Opera","WIMS",
  77.       "MSIE","Konqueror","Java"
  78. };
  79. #define good_agent_no (sizeof(good_agent)/sizeof(good_agent[0]))
  80.  
  81. char *bad_agent[]={ /* These are really bad agents: prohibited. */
  82.       "HTTrack","MemoWeb","Teleport","Offline","Wget","eCatch",
  83.       "Powermarks","EmailSiphon", "WebCopier"
  84. };
  85. #define bad_agent_no (sizeof(bad_agent)/sizeof(bad_agent[0]))
  86.  
  87. /* used for debugging */
  88. int debug=0;
  89.  
  90. char class_dir[MAX_FNAME+1]; /* directory name of this class */
  91.  
  92. struct user_variable user_variable[MAX_VAR_NUM];
  93. int user_var_no;
  94.  
  95. struct VAR_DEF var_def[MAX_VAR_NUM];
  96. int defined_var_total;
  97.  
  98. /* Destinated to module error messages */
  99. WORKING_FILE m_file,svar_file,mcache[MAX_MCACHE];
  100. int mcachecnt;
  101.  
  102. /* Limit for any data working files. */
  103. int WORKFILE_LIMIT=2048*1024;
  104.  
  105. /* whether the user has defined language */
  106. int user_lang=0;
  107.  
  108. /* for instex grouping */
  109. int instex_cnt=0, getwimstexsize=1;
  110. char instex_src[MAX_LINELEN+1], instex_fname[MAX_LINELEN+1];
  111. char *instex_processor="tex..gif";
  112.  
  113. /* Cookie management */
  114. char cookiegot[256], cookieset[256], cookieheader[64]="WIMSUSER=";
  115.  
  116. /* multipart boundary */
  117. char mpboundary[1024];
  118. int  deplen=0; /* length of deposit */
  119.  
  120. int confset=0; /* set to 1 if setvar for config */
  121.  
  122. /* Operating mode: default, popup, raw, etc. */
  123.  
  124. int mode=mode_default;
  125.  
  126. /* Switch; notice subroutines wherether we are outputing. */
  127. int outputing;
  128.  
  129. char *home_module="home"; /* name of home module */
  130. extern char **environ;      /* table of environment variables */
  131. int module_defined=0;
  132.  
  133.         /* directory prefix buffers */
  134. char session_prefix[MAX_FNAME+1], s2_prefix[MAX_FNAME+1], module_prefix[MAX_FNAME+1];
  135.  
  136. char *stdinbuf;
  137. int sesrandomtab[MAX_SESRANDOM]; /* session random values */
  138. char multiexec_random[64];
  139. int executed_gotos; /* number of goto's executed. to check with GOTO_LIMIT. */
  140. int insert_no; /* number of instex, insplot, insPLOT. */
  141. int output_length; /* length of the output. */
  142. int isexam=0; /* non-zero if request is exam */
  143. int simuxam=0; /* exam is simulation */
  144. int is_multiexec=0; /* for execredirected */
  145. int multiexec_index;
  146. int direct_datafile=0;
  147. int exec_is_module=0;
  148.   /* root directory of modules */
  149. char *module_dir="modules";
  150. int new_session=0; /* =1 if new session created */
  151. int good_httpd=0; /* Whether the http server is intelligent */
  152. /* int internal_sql=0; */ /* for internal sql use */
  153. int direct_exec=0; /* calc routine is exected by exec if 1 */
  154. int print_precision=8; /* precision when printing real numbers */
  155. int session_serial; /* request serial for session control */
  156. int form_access=0; /* identifies form access, for robot identification */
  157. int lastout_file=-1; /* file to hold last output */
  158. char *instex_style=""; /* "": text "$": math "$$": displaymath */
  159. int instex_usedynamic=0; /* always dynamic if 1 */
  160. int wrapexec=0; /* if set to 1, change uid (nobody) to euid (wims).
  161.                  * if set to -1, change euid to uid when exec(). */
  162. int parm_restore=0; /* Restoring saved parameters? */
  163. int exec_wait=1; /* whether to wait for fork return */
  164. int execnt=0; /* count executions */
  165. int readnest; /* nested read count */
  166. int mfilecnt=0; /* count working files */
  167. int forceresume=0; /* force user to resume old request */
  168. int manageable=0; /* whether the connection may be site manager
  169.                    * 0: no; 1: maybe; 2: sure */
  170. int ismhelp=0;  /* 1 if session is in mhelp. */
  171. int getvar_len; /* length of the last-got variable. */
  172. int noout=0; /* if set to 1 then output is skipped */
  173. char tmp_dir[MAX_FNAME+1]; /* temporary directory */
  174. char *bin_dir="bin"; /* directory containing executable scripts and programs. */
  175. char cwdbuf[MAX_FNAME+1]; /* store current working directory */
  176. char var_hacking=0; /* Trying to hack a variable? */
  177. char *tmp_debug="no";
  178. char *tmp_debug_var="";
  179. char ins_alt[MAX_LINELEN+1]; /* dynamic insertion alternative text */
  180. char *devel_modules="close"; /* whether to open devel modules */
  181. int isclassmodule=0; /* 1 if the module is class module */
  182. int isdevelmodule=0; /* development module? */
  183. int setcookie=0; /* 1 if need to set cookie */
  184. int killpid=0; /* pid of process to kill by alarm */
  185. char *mathalign_sup1, *mathalign_sup2; /* see mathalign_base */
  186. int substnest=0; /* nesting level of substit() */
  187. int exodepOK=1;
  188. long int startmtime; /* start time in milliseconds */
  189. long int startmtime2; /* start time in microseconds */
  190. int backslash_insmath=0; /* \(...) substitution? */
  191. char examlogf[MAX_FNAME+1]; /* examlog file name */
  192. char examlogd[MAX_FNAME+1]; /* examlog file name */
  193. char exam_sheetexo[32]; /* sheet data of an exam */
  194. char loadavg[64];
  195. /* user file variable access control. */
  196. char *var_readable, *var_writable, *var_nr, *var_nw, *var_pfx;
  197. int hostcquota;
  198. int var_noexport; /* do not export variable */
  199.  
  200. char tmplbuf[MAX_LINELEN+1]; /* for temporary uses not thru subroutines. */
  201.  
  202. struct tm *now, Now; /* time of request */
  203. time_t nowtime, limtime, limtimex;
  204. char nowstr[32];
  205.  
  206. /* Resource limits. Capital names are reserved by system. */
  207. int rlimit_cpu=20;  /* cpu time in seconds */
  208. int rlimit_fsize=8388608;/* file size */
  209. int rlimit_as=614457600;/* virtual memory size */
  210. int rlimit_data=204857600;/* data segment size; maxima requires a lot (must be lower than rlimit_as)*/
  211. int rlimit_stack=2097152;/* stack size */
  212. int rlimit_core=0; /* core dump size */
  213. int rlimit_rss=16777216; /* resident size */
  214. int rlimit_nproc=1024; /* number of processes */
  215. int rlimit_nofile=512; /* number of open files */
  216. int rlimit_memlock=2097152;/* locked-in-memory address space */
  217.  
  218. char *var_str; /* malloc'ed buffer to hold translated query_string */
  219.  
  220. /* buffer to hold module's variable definition file, malloc'ed. */
  221. char *var_def_buf;
  222.  
  223. /* job_identifier is even a reserved variable name */
  224. char job_identifier[32];
  225.  
  226. /* site manager definition IPv4 IPv6*/
  227. char *manager_site="127.0.0.1 ::1";
  228. int   manager_https=0;
  229.  
  230. /* sheet and exercise information */
  231. int wims_sheet=0,wims_exo=0;
  232.  
  233. /* Form method: get or post */
  234. char *default_form_method="post";
  235.  
  236. /* Je suis maintenant oblige de passer a l'anglais
  237.  * pour la langue de defaut.
  238.  */
  239. char lang[16]="en";
  240. char available_lang[MAX_LANGUAGES][4]={"en","fr"};
  241. int available_lang_no=2;
  242. char pre_language[4]="";
  243. FILE *trace_file;
  244. int trace_indent=0;
  245. char *protocol="http"; /* http or https */
  246.  
  247. /* check for coordinate input. This will mean that
  248.  * the request is manual, but not robot.
  249.  */
  250. int coord_input=0;
  251.  
  252. /* These are readonly environment variable names
  253.  * special parm used for special cmds (getins, etc).
  254.  */
  255. char *ro_name[]={
  256.       "cmd" ,
  257.       "empty",
  258.       "lang" ,
  259.       "module" ,
  260.       "session" ,
  261.       "special_parm",
  262.       "special_parm2",
  263.       "special_parm3",
  264.       "special_parm4",
  265.       "useropts" ,
  266.       "wims_session",
  267.       "wims_subsession",
  268.       "wims_window",
  269.       "worksheet"
  270. };
  271.  
  272. int RO_NAME_NO=(sizeof(ro_name)/sizeof(ro_name[0]));
  273.  
  274. int cmd_type;
  275. char *commands[]={
  276.     "intro" , "new" , "renew" , "reply" , "config" , "hint" , "help" ,
  277.       "resume", "next", "getins", "getframe", "getfile", "close", "ref"
  278. };
  279.  
  280. int CMD_NO=(sizeof(commands)/sizeof(commands[0]));
  281.  
  282. /* stat=0: saved variables
  283.  * all names starting with wims_priv_ are also internal.
  284.  */
  285. struct internal_name internal_name[]={
  286.       {"accessright", 1}, /* right to access commercial resources */
  287.       {"caller", 1}, /* caller session */
  288.       {"check", 1}, /* for exam check use */
  289.       {"class", 1},
  290.       {"class_examlog", 1},
  291.       {"class_exolog", 1},
  292.       {"class_limit", 1},
  293.       {"class_quota", 1},
  294.       {"class_regpass", 1},
  295.       {"class_user_limit", 1},
  296.       {"classdir", 1},
  297.       {"classname", 1},
  298.       {"devel_modules", 1},
  299.       {"developer", 1},
  300.       {"doc_quota", 1},
  301.       {"doc_regpass", 1},
  302.       {"email", 1},
  303.       {"exo", 0}, /* exercise number */
  304.       {"exoption", 1}, /* exercise option */
  305.       {"firstname", 1},
  306.       {"forum_limit", 1},
  307.       {"home", 1},
  308.       {"institutionname", 1},
  309.       {"isexam", 0}, /* whether the sheet is an exam sheet */
  310.       {"ismanager", 0},
  311.       {"lastname", 1},
  312.       {"mode", 0}, /* operating mode */
  313.       {"module_start_time", 0},
  314.       {"now", 1}, /* date and time, yyyymmdd.hh:mm:ss */
  315.       {"nowseconds", 1}, /* date and time, seconds since EPOCH */
  316.       {"nr", 1}, /* non-readable variables in user file, words */
  317.       {"nw", 1}, /* non-writable variables in user file, words */
  318.       {"otherclass", 1}, /* Remember other logins */
  319.       {"participate", 1}, /* superclass definition */
  320.       {"prefix", 1}, /* user file prefix */
  321.       {"protocol", 0}, /* http protocol */
  322.       {"rafale", 0}, /* rapidfire request information */
  323.       {"readable", 1}, /* readable variables in user file, words */
  324.       {"realuser", 1}, /* real user for supervisor in gateway */
  325.       {"req_time", 0}, /* time of the request */
  326.       {"sclassdir", 1},
  327.       {"scorereg", 0}, /* score registration flag */
  328.       {"sequence", 0}, /*sequence number */
  329.       {"sescookie", 1}, /* session cookie */
  330.       {"sesdir", 1},
  331.       {"session_serial", 0}, /* request serial in the session */
  332.       {"session_start_time", 0},
  333.       {"sheet", 0}, /* sheet number */
  334.       {"sup_secure", 1}, /* secure level of supervisor */
  335.       {"superclass", 1}, /* superclass code */
  336.       {"superclass_quota", 1},
  337.       {"supertype", 1}, /* superclass type */
  338.       {"supervise", 1}, /* superclass definition */
  339.       {"supervisor", 1}, /* real name of the supervisor */
  340.       {"supervisormail",1}, /* email of supervisor */
  341.       {"trustfile", 1}, /* trusted files in special adm modules */
  342.       {"useropts", 1}, /* user options */
  343.       {"writable", 1}, /* writable variables in user file, words */
  344. };
  345. int INTERNAL_NAME_NO=(sizeof(internal_name)/sizeof(internal_name[0]));
  346.  
  347. char *httpd_vars[]={
  348.       "HTTP_ACCEPT",
  349.       "HTTP_ACCEPT_CHARSET",
  350.       "HTTP_ACCEPT_LANGUAGE",
  351.       "HTTP_COOKIE",
  352.       "HTTP_HOST",
  353.       "HTTP_USER_AGENT",
  354.       "HTTPS",
  355.       "QUERY_STRING",
  356.       "REMOTE_HOST",
  357.       "REMOTE_ADDR",
  358.       "REMOTE_PORT",
  359.       "REQUEST_METHOD",
  360.       "SCRIPT_NAME",
  361.       "SERVER_NAME",
  362.       "SERVER_SOFTWARE",
  363.       "SERVER_PROTOCOL"
  364. };
  365. #define HTTPD_VAR_NO (sizeof(httpd_vars)/sizeof(httpd_vars[0]))
  366.  
  367. /* security: these variables will not be visible to child processes */
  368. char *unsetvars[]={
  369.  "DOCUMENT_ROOT","SERVER_SIGNATURE","SERVER_SOFTWARE",
  370.       "UNIQUE_ID","HTTP_KEEP_ALIVE","SSL_SESSION_ID"
  371. };
  372. #define unsetvarcnt (sizeof(unsetvars)/sizeof(unsetvars[0]))
  373.  
  374. int httpd_type=httpd_apache;
  375.  
  376. char *remote_addr=""; /* storing for performance */
  377. char *remote_host="";
  378.  
  379. char ref_name[2048], ref_base[2048];
  380.  
  381. void put_special_page(char *pname);
  382. void useropts(void);
  383.  
  384. /* Make certain httpd variables readable by modules */
  385. void take_httpd_vars(void)
  386. {
  387.     int i;
  388.     char *p, buf[MAX_NAMELEN+1];
  389.     var_noexport=1;
  390.     for(i=0;i<HTTPD_VAR_NO;i++) {
  391.      snprintf(buf,sizeof(buf),"httpd_%s",httpd_vars[i]);
  392.      if((p=getenv(httpd_vars[i]))!=NULL) setvar(buf,p);
  393.     }
  394.     var_noexport=0;
  395.  
  396.     for(i=0;i<unsetvarcnt;i++) unsetenv(unsetvars[i]);
  397.      /* IPv4 IPv6*/
  398.     p=getenv("REMOTE_ADDR");if(p!=NULL && (strcmp(p,"127.0.0.1")==0 || strcmp(p,"::1")==0)) human_access=1;
  399.     p=getenv("HTTP_REFERER"); if(p!=NULL && *p!=0) setvar("wims_referer",p);
  400. }
  401.  
  402. void cookie2session(void)
  403. {
  404.     char cksession[64], psession[32], *ckey, *p;
  405.     char nbuf[MAX_FNAME+1];
  406.  
  407.     if(mode==mode_popup) return;
  408.     if(cookiegot[0]==0) {
  409.      ckset: cookiegot[0]=0; setcookie=1; return;
  410.     }
  411.     p=getvar("special_parm");
  412.     if(p!=NULL && strcmp(p,"ignorecookie")==0) return;
  413.     mystrncpy(cksession,cookiegot,sizeof(cksession));
  414.     ckey=strchr(cksession,'-');
  415.     if(ckey==NULL) goto ckset; else *ckey++=0;
  416.     p=getvar("wims_session"); if(p==NULL) p="";
  417.     if(strstr(p,"new")!=NULL) goto ckset;
  418.     mystrncpy(psession,p,sizeof(psession));
  419.     p=strchr(psession,'_'); if(p!=NULL) *p=0;
  420.     if(psession[0]!=0) {
  421.       if(strcmp(psession,cksession)==0) return;
  422.       if(session_exists(psession)) goto ckset;
  423.       if(session_exists(cksession)) goto change;
  424.     }
  425.     else {
  426.       if(!session_exists(cksession)) return;
  427.       change:
  428.       p=getenv("HTTPS");
  429.       if(p!=NULL && strcasecmp(p,"on")==0) goto ckset;
  430.       mkfname(nbuf,"%s/%s/var",session_dir,cksession);
  431.       getdef(nbuf,"w_wims_ismanager",tmplbuf);
  432.       if(tmplbuf[0]!=0 && tmplbuf[0]!='0') goto ckset;
  433.       getdef(nbuf,"w_wims_protocol",tmplbuf);
  434.       if(strcasecmp(tmplbuf,"https")==0) goto ckset;
  435.       mkfname(nbuf,"%s/%s/var.stat",session_dir,cksession);
  436.       getdef(nbuf,"wims_user",tmplbuf);
  437.       if(tmplbuf[0]!=0) goto ckset;
  438.       force_setvar(ro_name[ro_session],cksession);
  439.       setsesdir(cksession);
  440.       force_setvar("wims_subsession","");
  441.       session_serial=0;
  442.     }
  443. }
  444.  
  445. void determine_font(char *l)
  446. {
  447.     int i;
  448.  
  449.     if(l==NULL || *l==0) return;
  450.     for(i=0;i<charname_no && memcmp(charname[i].name,l,2);i++);
  451.     if(i<charname_no) setvar("wims_main_font",charname[i].font);
  452. }
  453.  
  454. void determine_dirn(char *l)
  455. {
  456.     int i;
  457.  
  458.     if(l==NULL || *l==0) return;
  459.     for(i=0;i<dirnname_no && memcmp(dirnname[i].name,l,2);i++);
  460.     if(i<dirnname_no) setvar("wims_main_dirn",dirnname[i].dirn);
  461. }
  462.  
  463. void predetermine_language(void)
  464. {
  465.     char *p;
  466.     int i,n;
  467.  
  468.     if(pre_language[0]!=0) p=pre_language;
  469.     else p=getenv("HTTP_ACCEPT_LANGUAGE");
  470.     if(p!=NULL && strlen(p)>=2) {
  471.       for(i=0;i<available_lang_no && memcmp(p,available_lang[i],2)!=0;i++);
  472.       if(i<available_lang_no) goto lend;
  473.     }
  474.     p=getenv("HTTP_USER_AGENT");
  475.     if(p!=NULL && strlen(p)>=5) {
  476.       char *q;
  477.       if((q=strchr(p,'['))!=NULL && islower(*(q+1)) && islower(*(q+2)) && *(q+3)==']') {
  478.           char bb[4];
  479.           bb[0]=*(q+1);bb[1]=*(q+2);bb[2]=0;
  480.           for(i=0;i<available_lang_no && memcmp(bb,available_lang[i],2)!=0;i++);
  481.           if(i<available_lang_no) {
  482.             memmove(lang,bb,2); lang[2]=0;
  483.             goto lend2;
  484.           }
  485.       }
  486.     }
  487.     p=getenv("HTTP_HOST"); if(p==NULL) goto lend2;
  488.     n=strlen(p); if(n<=3 || *(p+n-3)!='.') goto lend2;
  489.     p=p+n-2;
  490.     for(i=0;i<available_lang_no && memcmp(p,available_lang[i],2)!=0;i++);
  491.     if(i<available_lang_no) {
  492.       lend: memmove(lang,p,2); lang[2]=0;
  493.       lend2: determine_font(lang);determine_dirn(lang);
  494.     }
  495. }
  496.  
  497. /* print a special page */
  498. void put_special_page(char *pname)
  499. {
  500.     determine_font(lang);
  501.     determine_dirn(lang);
  502.     phtml_put_base(mkfname(NULL,"%s.phtml.%s",pname,lang),0);
  503.     write_logs();free(var_str);
  504. }
  505.  
  506. /* check whether the connection is a site manager. */
  507. void manager_check(void)
  508. {
  509.     char *p, *pp, buf[16];
  510.     struct stat confstat;
  511.     int i;
  512.  
  513.     manageable=0;
  514.     if(robot_access || *manager_site==0 || checkhost(manager_site)<1)
  515.       goto mend;
  516.     if(manager_https) {
  517.       p=getenv("HTTPS");
  518.       if(p==NULL || strcmp(p,"on")!=0) goto mend;
  519.     }
  520. /* IPv4 IPv6*/
  521.     if(strcmp(remote_addr,"127.0.0.1")==0 || strcmp(remote_addr,"::1")==0) {
  522.       int port, port2;
  523.       char tester[128];
  524.       p=getenv("REMOTE_PORT"); if(p==NULL) goto mend;
  525.       port=atoi(p); if(port<1024 || port>65535) goto mend;
  526.       p=getenv("SERVER_PORT"); if(p==NULL) goto mend;
  527.       port2=atoi(p); if(port2>=10000 || port2<=0) goto mend;
  528. /* this is very non-portable */
  529.       manageable=1;
  530.       accessfile(tmplbuf,"r","/proc/net/tcp");
  531.       snprintf(tester,sizeof(tester)," 0100007F:%04X 0100007F:%04X ",
  532.              port,port2);
  533.       p=strstr(tmplbuf,tester);
  534.       if(p!=NULL) {
  535.           pp=strchr(p,'\n'); if(pp!=NULL) *pp=0;
  536.           if(strlen(p)>=75) {
  537.             p=find_word_start(p+70); *find_word_end(p)=0;
  538.             if(atoi(p)==geteuid()) manageable=2;
  539.           }
  540.       }
  541.     }
  542.     else manageable=1;
  543.     i=stat(config_file,&confstat);
  544.     if(i==0 && manageable>0 && (confstat.st_mode&(S_IRWXO|S_IRWXG))!=0) manageable=-1;
  545.     if(manageable>0 && !trusted_module()) manageable=0;
  546.     if(manageable==1) {
  547.       accessfile(tmplbuf,"r","%s/.manager",session_prefix);
  548.       if(strstr(tmplbuf,"yes")!=NULL) manageable=2;
  549.     }
  550.     if(manageable==1) {
  551.       p=getvar(ro_name[ro_module]);
  552.       if(p!=NULL && strncmp(p,"adm/manage",strlen("adm/manage"))==0) {
  553.           struct stat pstat;
  554.           if(stat("../log/.wimspass",&pstat)==0) {
  555.             if((S_IFMT&pstat.st_mode)!=S_IFREG ||
  556.                ((S_IRWXO|S_IRWXG)&pstat.st_mode)!=0)
  557.               manageable=-2;
  558.           }
  559.       }
  560.     }
  561.     mend:
  562.     mystrncpy(buf,int2str(manageable),sizeof(buf));
  563.     force_setvar("wims_ismanager",buf);
  564.     if(manageable>=2) {
  565.       struct rlimit rlim;
  566.       rlimit_cpu*=10;
  567.       rlim.rlim_cur=rlim.rlim_max=rlimit_cpu;
  568.       setrlimit(RLIMIT_CPU,&rlim);
  569.       mystrncpy(buf,int2str(rlimit_cpu),sizeof(buf));
  570.       setvar("wims_cpu_limit",buf);
  571.       initalarm();
  572.     }
  573. }
  574.  
  575. /* check for robot access */
  576. void robot_check(void)
  577. {
  578.     char *ua, *p, *ses, *c, *mod;
  579.     int i;
  580.  
  581.     if(human_access) return;
  582.     mod=getvar(ro_name[ro_module]);
  583.     if(mod!=NULL && strcmp(mod,"adm/raw")==0) return;
  584.     ses=getvar(ro_name[ro_session]);
  585. /* user has valid session; OK */
  586.     if(ses!=NULL && strncmp(ses,robot_session,strlen(robot_session))!=0
  587.        && strchr(ses,'/')==NULL
  588.        && ftest(mkfname(NULL,"%s/%s",s2_dir,ses))==is_dir)
  589.       return;
  590.     ua=getenv("HTTP_USER_AGENT"); if(ua==NULL) ua="";
  591.     ua=find_word_start(ua);
  592.     if(strncasecmp(ua,"Mozilla",strlen("Mozilla"))==0 &&
  593.        (p=strstr(ua,"compatible"))!=NULL)
  594.       ua=find_word_start(find_word_end(p));
  595.     if(*ua) {
  596.       for(i=0;i<good_agent_no
  597.           && strncasecmp(ua,good_agent[i],strlen(good_agent[i]));i++);
  598.       if(i<good_agent_no) return;
  599.       for(i=0;i<bad_agent_no
  600.           && strstr(ua,bad_agent[i])==NULL;i++);
  601.       if(i<bad_agent_no) user_error("trapped");
  602.     }
  603.     force_setvar(ro_name[ro_session],robot_session);
  604.     setsesdir(robot_session);
  605.     c=getvar(ro_name[ro_cmd]);
  606.     robot_access=1;
  607.     if(c!=NULL && strcmp(c,"new") && strcmp(c,"intro")) {
  608.       force_setvar(ro_name[ro_cmd],"robot_error");
  609.       nph_header(450); put_special_page("robot");
  610.       flushoutput(); flushlog(); exit(0);
  611.     }
  612. }
  613.  
  614. /* type=0: ordinary; type=1: multipart/form-data */
  615. void parse_query_string(int len, int type)
  616. {
  617.     int i,j,l,v,cmd_defined;
  618.     int parenth=-1, ll, lb, dlen;
  619.     char *start, *p, *p1, *pt, *b1="";
  620.  
  621.     cmd_defined=0;
  622.     setvar("wims_subsession","");
  623.     ll=lb=0;
  624.     if(type) {
  625.       ll=strlen(mpboundary);
  626.       start=strstr(var_str,mpboundary);
  627.       if(start==NULL) start=var_str+strlen(var_str);
  628.       if(strstr(var_str,"\r\n\r\n")!=NULL) b1="\r\n\r\n";
  629.       else b1="\n\n";
  630.       lb=strlen(b1);
  631.     }
  632.     else start=var_str;
  633.     for(v=0, p1=start;p1<var_str+len;p1+=l) {
  634.       if(type) {
  635.           char *p2, *p3, *p4, *p5;
  636.           p2=p1+ll; p3=memstr(p2,mpboundary,var_str+len-p2); l=p3-p1;
  637.           p=memstr(p2,b1,var_str+len-p2); if(p>=p3) continue;
  638.           p+=lb; if(p3<var_str+len) {
  639.             while(*p3!='\n' && p3>p2) p3--;
  640.             *p3=0;
  641.             p3--; if(*p3=='\r') *p3=0;
  642.           }
  643.           dlen=p3-p;
  644.           p2=memstr(p2,"name=",p3-p2); if(p2>=p3) continue;
  645.           p2+=strlen("name="); if(*p2=='"') p2++;
  646.           for(p3=p2; myisalnum(*p3) || strchr("._",*p3)!=NULL; p3++);
  647.           if(p3==p2) continue;
  648.           if(p3-p2==strlen("wims_deposit") &&
  649.              strncmp(p2,"wims_deposit",p3-p2)==0) {
  650.             p4=memstr(p1,"filename=",p-p1); if(p4<p) {
  651.                 p4+=strlen("filename="); if(*p4=='"') {
  652.                   p4++; p5=strchr(p4,'"');
  653.                   if(p5==NULL || p5-p4>=MAX_FNAME) goto emptyquote;
  654.                 }
  655.                 else {
  656.                   emptyquote:
  657.                   for(p5=p4; p5<p && !isspace(*p5) &&
  658.                       strchr(";\"~#*?=,'",*p5)==NULL; p5++);
  659.                 }
  660.                 if(p5>p4) {
  661.                   *p5=0;
  662.                   for(p5--;
  663.                       p5>=p4 && !isspace(*p5) && strchr("/\\:",*p5)==NULL;
  664.                       p5--);
  665.                   if(p5>=p4) p4=p5+1;
  666.                   if(*p4==0) goto noname;
  667.                   if(strstr(p4,"..")!=NULL || *p4=='.')
  668.                     p4="noname.file";
  669.                   setvar("wims_deposit",p4);
  670.                 }
  671.                 else {
  672.                   noname: setvar("wims_deposit","noname.file");
  673.                 }
  674.             }
  675.             deplen=dlen;
  676.           }
  677.           *p3=0; l-=p2-p1; p1=p2;
  678.       }
  679.       else {
  680.           p1=find_word_start(p1);
  681.           l=strlen(p1)+1; p=strchr(p1,'=');
  682.           if(p==NULL) p=p1+strlen(p1);
  683.           if(*p==0 && l>1) {
  684.             user_variable[v].name="no_name";
  685.             user_variable[v].value=p1;
  686.             coord_input=1;
  687.             goto nnext;
  688.           }
  689.           *p++=0;
  690.       }
  691. /* empty name or empty value: ignore */
  692.         if(*p1==0 || *p==0) continue;
  693. /* We do not treat names containing '.' */
  694.       for(pt=strchr(p1,'.'); pt; pt=strchr(++pt,'.')) *pt='_';
  695. /* Restrictions on variable names */
  696.       for(pt=p1; myisalnum(*pt) || *pt=='_'; pt++);
  697.       if(*pt) continue;
  698.       if(strcmp(p1,"wims_deposit")!=0) _tolinux(p);
  699. /* This is a restriction:
  700.  * Every parameter must have matching parentheses.
  701.  */
  702.       if(parenth==-1 && strncmp(p1,"freepar_",strlen("freepar_"))!=0
  703.          && strcmp(p1,"wims_deposit")!=0
  704.          && check_parentheses(p,1)) parenth=v;
  705.       if(strcmp(p1,"special_parm")==0 && strcmp(p,"wims")==0)
  706.         human_access=1;
  707.       j=search_list(ro_name,RO_NAME_NO,sizeof(ro_name[0]),p1);
  708.       if(j>=0) {
  709.           if(j==ro_session) {
  710.             p=find_word_start(p); *find_word_end(p)=0;
  711.             if(strlen(p)>MAX_SESSIONLEN) continue;
  712.             if(strcmp(p,robot_session)==0) p="";
  713.             if(strcasecmp(p,"popup")==0) {
  714.                 mode=mode_popup;
  715.                 force_setvar("wims_mode","popup");
  716.                 force_setvar("session","");
  717.                 continue;
  718.             }
  719.           }
  720.           if(j==ro_module) module_defined=1;
  721.           if(j==ro_cmd) {
  722.             p=find_word_start(p); *find_word_end(p)=0;
  723.             if(strlen(p)>16) continue;
  724.             cmd_defined=1;
  725.           }
  726.           if(j==ro_lang) {
  727.             if(strlen(p)!=2) continue;
  728.             for(i=0;i<available_lang_no && strcmp(available_lang[i],p)!=0;i++);
  729.             if(i<available_lang_no) {user_lang=1; ovlstrcpy(lang,p);}
  730.             else continue;
  731.           }
  732. /* strip leading and trailing '/'s in module name */
  733.           if(j==ro_module) {
  734.             p=find_word_start(p); *find_word_end(p)=0;
  735.             while(*p=='/') p++;
  736.             while(*p!=0 && *(p+strlen(p)-1)=='/') *(p+strlen(p)-1)=0;
  737.             if(strlen(p)>MAX_MODULELEN) continue;
  738.           }
  739.           setvar(p1,p);
  740.           if(j==ro_session && mode!=mode_popup) {
  741.             char *pp, *pr;
  742.             char buf[1024];
  743.             mystrncpy(buf,p,sizeof(buf));
  744.             if((pp=strchr(buf,'.'))!=NULL) {
  745.                 *pp++=0; session_serial=atoi(pp);
  746.                 if(pp<0) pp=0;
  747.             }
  748.             else session_serial=0;
  749.             pp=strchr(buf,'_');
  750.             if(pp!=NULL && (pr=strstr(pp,"_mhelp"))!=NULL) {
  751.                 *pr=0; ismhelp=1; lastout_file=-1;
  752.                 setvar("wims_inssub","mh");
  753.             }
  754.             force_setvar("wims_session",buf);
  755.             if(pp!=NULL) force_setvar("wims_subsession",pp);
  756.           }
  757.           continue;
  758.       }
  759.       user_variable[v].name=p1;
  760.       user_variable[v].value=p;
  761. nnext:v++; if(v>=MAX_VAR_NUM) user_error("too_many_variables");
  762.     }
  763.     user_var_no=v;
  764.     if(parenth>=0) {
  765.       char buf[16];
  766.       mystrncpy(buf,int2str(user_var_no),sizeof(buf));
  767.       setvar("user_var_no",buf);
  768.       for(i=0;i<user_var_no;i++) {
  769.           snprintf(buf,sizeof(buf),"name%d",i);
  770.           setvar(buf,user_variable[i].name);
  771.           snprintf(buf,sizeof(buf),"value%d",i);
  772.           setvar(buf,user_variable[i].value);
  773.       }
  774.       mystrncpy(buf,int2str(parenth),sizeof(buf));
  775.       setvar("bad_parentheses",buf);
  776.       user_error("unmatched_parentheses");
  777.     }
  778.     p=getenv("SCRIPT_NAME");
  779.     if(p!=NULL && (p=strstr(p,"/getfile/"))!=NULL) {
  780.       p+=strlen("/getfile/");
  781.       force_setvar(ro_name[ro_cmd],commands[cmd_getfile]);
  782.       force_setvar("special_parm",p);
  783.       cmd_defined=1;
  784.     }
  785.     if(module_defined && !cmd_defined) setvar(ro_name[ro_cmd],commands[cmd_intro]);
  786.     robot_check(); cookie2session();
  787. }
  788.  
  789. /* parse special commands */
  790. void special_cmds(void)
  791. {
  792.     char *c, *p;
  793.     int i;
  794.     long int l=-1;
  795.  
  796.     c=getvar(ro_name[ro_cmd]);
  797.     if(c==NULL || *c==0) {  /* no module name nor command */
  798.       setvar(ro_name[ro_module],home_module);
  799.       setvar(ro_name[ro_cmd],commands[cmd_new]);
  800.       return;
  801.     }
  802.     for(i=0;i<CMD_NO && strcmp(commands[i],c)!=0; i++);
  803.     switch(i) {
  804.       case cmd_intro: {
  805.           set_module_prefix();
  806.           default_form_method="get";
  807.           if(ftest(mkfname(NULL,"%s/%s",module_prefix,intro_file))<0) {
  808.             force_setvar(ro_name[ro_cmd],commands[cmd_new]);
  809.             return;
  810.           }
  811.           p=getvar("wims_session");
  812.           if(p!=NULL && *p!=0) {
  813.             if(set_session_prefix()==0) check_session();
  814.             else {
  815.                 trap_check(p);
  816.                 if(strchr(p,'_')!=NULL && strchr(p,'/')==NULL) {
  817.                   get_static_session_var();
  818.                 }
  819.             }
  820.           }
  821. /* determine http protocol name. How to detect? */
  822.           p=getenv("HTTPS"); if(p!=NULL && strcmp(p,"on")==0) {
  823.             protocol="https"; set_protocol();
  824.           }
  825.           force_setvar("wims_protocol",protocol);
  826.           determine_font(lang);
  827.           determine_dirn(lang);
  828.           main_phtml_put(intro_file); debug_output();
  829.           introend: write_logs();free(var_str);
  830.           delete_pid(); exit(0);
  831.       }
  832.       case cmd_ref: {
  833.           set_module_prefix();
  834.           default_form_method="get";
  835.           p=getvar("wims_session");
  836.           if(p!=NULL && *p!=0) {
  837.             if(set_session_prefix()==0) check_session();
  838.             else trap_check(p);
  839.           }
  840.           determine_font(lang);
  841.           determine_dirn(lang);
  842.           main_phtml_put(ref_file); goto introend;
  843.       }
  844.       case cmd_getins: {
  845.           c=getvar(ro_name[ro_special_parm]);
  846.           if(c==NULL || *c==0) {
  847.             user_error_nolog=1; user_error("no_insnum");
  848.           }
  849.           if(*c=='/' || strstr(c,"..")!=NULL) goto badins;
  850.           set_session_prefix();
  851.           if(strstr(session_prefix,"robot")!=NULL) exit(0);
  852.           l=filelength("%s/%s",s2_prefix,c);
  853.           if(l<0) {
  854.             badins: user_error_nolog=1; user_error("bad_insnum");
  855.           }
  856.           {
  857.             char *fmt;
  858.             fmt=strchr(c,'.');
  859.             if(fmt==NULL) {
  860.                 user_error_nolog=1; user_error("bad_insnum");
  861.             }
  862.             else fmt++;
  863.  
  864.             nph_header(200);
  865. /* insert format problem; bricolage */
  866.             printf("Content-type: image/%s\r\n\
  867. Content-length: %ld\r\n\r\n",fmt,l);
  868.             catfile(stdout,"%s/%s",s2_prefix,c); exit(0);
  869.           }
  870.       }
  871.       case cmd_getfile: {
  872.           char fname[MAX_FNAME+1];
  873.           c=getvar(ro_name[ro_special_parm]);
  874.           if(c==NULL || *c==0) {
  875.             user_error_nolog=1; user_error("no_insnum");
  876.           }
  877.           if(*c=='/' || strstr(c,"..")!=NULL) goto badfile;
  878.  
  879.           set_session_prefix();
  880.           if(strstr(session_prefix,"robot")!=NULL) exit(0);
  881.           mkfname(fname,"%s/getfile/%s",session_prefix,c);
  882.           l=filelength("%s",fname);
  883.           if(l<0 && strchr(session_prefix,'_')!=NULL) {
  884.             char *pt;
  885.             mystrncpy(fname,session_prefix,sizeof(fname));
  886.             pt=strrchr(fname,'_'); if(pt) *pt=0;
  887.             snprintf(fname+(pt-fname),sizeof(fname)-(pt-fname),
  888.                   "/getfile/%s",c);
  889.             l=filelength("%s",fname);
  890.           }
  891.           if(l<0) {
  892.             badfile: user_error_nolog=1; user_error("bad_insnum");
  893.           }
  894.           if(l>512*1024) {
  895.             struct rlimit rlim;
  896.             rlimit_cpu*=l/(10*1024);
  897.             rlim.rlim_cur=rlim.rlim_max=rlimit_cpu;
  898.             initalarm();
  899.           }
  900.           {
  901.             char *p1;
  902.             char mime[MAX_LINELEN+1];
  903.             for(p1=c+strlen(c);p1>c && isalpha(*(p1-1)); p1--);
  904.             ovlstrcpy(mime,"application/octet-stream");
  905.             if(p1>c && *(p1-1)=='.') {
  906.                 setvar("translator_unknown",mime);
  907.                 setvar("dictionary","bases/sys/mime");
  908.                 snprintf(mime,sizeof(mime),"translator %s",p1);
  909.                 calc_exec(mime);
  910.             }
  911.             nph_header(200);
  912.             printf("Content-type: %s\r\n\
  913. Content-length: %ld\r\n\r\n",mime,l);
  914.             catfile(stdout,"%s",fname); exit(0);
  915.           }
  916.       }
  917.       case cmd_close: {
  918.           char *p, b2[32]; int w;
  919.           char nbuf[MAX_FNAME+1], vbuf[MAX_LINELEN+1];
  920.           p=getvar(ro_name[ro_session]);
  921.           if(p==NULL || strlen(p)<10 ||
  922.              strchr(p,'/')!=NULL) return;
  923.           mystrncpy(b2,p,sizeof(b2));
  924.           p=strchr(b2,'.'); if(p!=NULL) *p=0;
  925.           mkfname(nbuf,"%s/%s/var.stat",session_dir,b2);
  926.           getdef(nbuf,"wims_caller",vbuf);
  927.           if(vbuf[0]!=0) force_setvar(ro_name[ro_session],vbuf);
  928.           w=wrapexec; wrapexec=1;
  929.           call_sh("rm -Rf %s/%s* %s/%s* >/dev/null 2>&1",session_dir,b2,s2_dir,b2);
  930.           wrapexec=w; cookiegot[0]=0;
  931.           force_setvar(ro_name[ro_cmd],"new");
  932.       }
  933.       default: return;
  934.     }
  935. }
  936.  
  937. /* This is run only when manually invoking the program.
  938.  * Verifies the orderedness of various list tables.
  939.  */
  940. int verify_tables(void)
  941. {
  942.     if(verify_order(calc_routine,CALC_FN_NO,sizeof(calc_routine[0]))) return -1;
  943.     if(verify_order(exec_routine,EXEC_FN_NO,sizeof(exec_routine[0]))) return -1;
  944.     if(verify_order(main_config,MAIN_CONFIG_NO,sizeof(main_config[0]))) return -1;
  945.     if(verify_order(mathname,mathname_no,sizeof(mathname[0]))) return -1;
  946.     if(verify_order(hmname,hmname_no,sizeof(hmname[0]))) return -1;
  947.     if(verify_order(ro_name,RO_NAME_NO,sizeof(ro_name[0]))) return -1;
  948.     if(verify_order(distr_cmd,distr_cmd_no,sizeof(distr_cmd[0]))) return -1;
  949.     if(verify_order(internal_name,INTERNAL_NAME_NO,
  950.                 sizeof(internal_name[0]))) return -1;
  951.     if(verify_order(tmathfn,tmathfn_no,sizeof(tmathfn[0]))) return -1;
  952.     if(verify_order(tmathvar,tmathvar_no,sizeof(tmathvar[0]))) return -1;
  953.     if(verify_order(modindex,MODINDEX_NO,sizeof(modindex[0]))) return -1;
  954.     if(verify_order(exportvars,exportvarcnt,sizeof(exportvars[0]))) return -1;
  955.     if(evaltab_verify()) return -1;
  956.     if(textab_verify()) return -1;
  957.     return 0;
  958. }
  959.  
  960. void config_defaults(void)
  961. {
  962.     int i;
  963.     for(i=0;i<MAIN_CONFIG_NO;i++) {
  964.       if((1&main_config[i].is_integer)==1) {
  965.           int *pi = (int*)main_config[i].address;
  966.           printf("DF_%s=%d\n",main_config[i].name, *pi);
  967.         }
  968.       else {
  969.             char **ps = (char**)main_config[i].address;
  970.           printf("DF_%s=%s\n",main_config[i].name,*ps);
  971.         }
  972.     }
  973. }
  974.  
  975. /* get and set useroptions */
  976. void useropts(void)
  977. {
  978.     char *p;
  979.     setvar("lang",lang);
  980.     p=getvar("useropts");
  981.     if(p==NULL || *p==0) p=getvar("wims_useropts");
  982.     if(p!=NULL && *p!=0) {
  983.       if(myisdigit(p[0])) {
  984.         usertexsize=p[0]-'0';
  985.         /* fourth digit is for special fonts*/
  986.         if(p[1]!=0) { mathalign_base=p[1]-'0'; }
  987.       }
  988.       if(myisdigit(p[3]) && p[3]!=0){ spec_font=p[3]-'0';}
  989.     }
  990.     if(mathalign_base==1) {
  991.         mathalign_sup1="<sup>"; mathalign_sup2="</sup>";
  992.     } else mathalign_sup1=mathalign_sup2="";
  993. }
  994.  
  995. /* popup module help */
  996. void mhelp(void)
  997. {
  998.     char *p, buf[MAX_LINELEN+1];
  999.     main_phtml_put(""); buf[0]=0;
  1000.     if(cmd_type!=cmd_help) {
  1001.       phtml_put_base("closemhelp.phtml",0);
  1002.     }
  1003.     else {
  1004.       phtml_put_base("mhelpheader.phtml",0);
  1005.       p=getvar("special_parm");
  1006.       if(p!=NULL && strcmp(p,"about")==0)
  1007.         phtml_put("about.phtml",0);
  1008.       else phtml_put("help.phtml",0);
  1009.       phtml_put_base("mhelptail.phtml",0);
  1010.       exec_tail(buf);
  1011.     }
  1012. }
  1013.  
  1014. #define READSTDIN_WINDOW 4096
  1015.  
  1016. void readstdin(int len)
  1017. {
  1018.     int ll, l1, lt, lr;
  1019.     int cpulim;
  1020.  
  1021.     cpulim=rlimit_cpu; rlimit_cpu=3;
  1022.     lr=len; l1=0;
  1023.     while(lr>0) {
  1024.       nowtime=time(0); initalarm();
  1025.       ll=lr; if(ll>READSTDIN_WINDOW) ll=READSTDIN_WINDOW;
  1026.       lt=fread(stdinbuf+l1,1,ll,stdin);
  1027.       if(lt!=ll) user_error("parm_too_long");
  1028.       lr-=ll; l1+=ll;
  1029.     }
  1030.     if(l1!=len) user_error("parm_too_long");
  1031.     stdinbuf[len]=0; rlimit_cpu=cpulim;
  1032. }
  1033.  
  1034. /* input: p=QUERY_STRING. output: parameter length. */
  1035. /* Netscape puts form content into /tmp. */
  1036. int formdata(char *p)
  1037. {
  1038.     char *pp;
  1039.     int inlen;
  1040.     char *ctype;
  1041.     inlen=0; ctype=getenv("CONTENT_TYPE");
  1042.     if(ctype==NULL || strstr(ctype,"multipart/form-data")==NULL
  1043.        || (p=strstr(ctype,"boundary="))==NULL) {
  1044.       bad: stdinbuf=""; return 0;
  1045.     }
  1046.     pp=getenv("CONTENT_LENGTH");
  1047.     if(pp==NULL) goto bad;
  1048.     inlen=atoi(pp); if(inlen<=10) goto bad;
  1049.     if(inlen>=MAX_DEPOSITLEN) user_error("parm_too_long");
  1050.     stdinbuf=xmalloc(inlen+1); readstdin(inlen);
  1051.     p+=strlen("boundary=");
  1052.     for(pp=p;myisalnum(*pp) || *pp=='-'; pp++);
  1053.     if(pp-p<sizeof(mpboundary)-2) {
  1054.       memmove(mpboundary,p,pp-p); mpboundary[pp-p]=0;
  1055.     }
  1056. /* empty data */
  1057.     if(strstr(stdinbuf,mpboundary)==NULL || strstr(stdinbuf,"name=")==NULL) {
  1058.       free(stdinbuf); goto bad;
  1059.     }
  1060.     form_access=1; post_log();
  1061.     return inlen;
  1062. }
  1063.  
  1064. /* get the content of POST */
  1065. void getpost(void)
  1066. {
  1067.     int ll;
  1068.     char *pp;
  1069.     pp=getenv("CONTENT_LENGTH");
  1070.     if(pp==NULL || (ll=atoi(pp))<=0) {
  1071.       stdinbuf=xmalloc(16); stdinbuf[0]=0;
  1072.     }
  1073.     else {
  1074.       if(ll>QUERY_STRING_LIMIT) user_error("parm_too_long");
  1075.       stdinbuf=xmalloc(ll+16); readstdin(ll);
  1076.       if(ll>0) {
  1077.           setenv("QUERY_STRING",stdinbuf,1);
  1078.           form_access=1; post_log();
  1079.       }
  1080.     }
  1081. }
  1082.  
  1083. void buffer_init(void)
  1084. {
  1085.     struct timeval tv;
  1086.  
  1087.     mcachecnt=readnest=0;
  1088.     mpboundary[0]=cookiegot[0]=cookieset[0]=cwdbuf[0]=0;
  1089.     rscore_class[0]=rscore_user[0]=multiexec_random[0]=0;
  1090.     lastftest[0]=0;
  1091.     lastdatafile[0]=0; lastdata=xmalloc(WORKFILE_LIMIT);
  1092.     outptr=outbuf;
  1093.     instex_src[0]=instex_fname[0]=module_prefix[0]=0;
  1094.     examlogf[0]=examlogd[0]=exam_sheetexo[0]=0;
  1095.     stdinbuf=NULL;
  1096.     mkfname(tmp_dir,"../tmp/forall");
  1097.     mkfname(session_dir,"../%s",SESSION_BASE);
  1098.     mkfname(s2_dir,"../%s",S2_BASE);
  1099.     if(gettimeofday(&tv,NULL)) startmtime=startmtime2=0;
  1100.     else {
  1101.       startmtime=((tv.tv_sec%10000)*1000+tv.tv_usec/1000);
  1102.       startmtime2=(tv.tv_sec%1000)*1000000+tv.tv_usec;
  1103.     }
  1104. }
  1105.  
  1106. /**
  1107.  * runs the test suite, to check whether the documented commands of modtool
  1108.  * behave properly.
  1109.  * @param prefix path to the proc file to process
  1110.  * @param p      name of the proc file to proceed
  1111.  * @param vars a list of var names to print.
  1112.  **/
  1113. void test_suite(char *prefix, char *p, char *vars){
  1114.   char *v, *nextv;
  1115.   mystrncpy(module_prefix, prefix, sizeof(module_prefix));
  1116.   exec_read(p);
  1117.   nextv=vars;
  1118.   while (*nextv!='\0'){
  1119.     v=find_word_start(nextv);
  1120.     nextv=find_word_end(v);
  1121.     if (*nextv != '\0'){
  1122.       *nextv++='\0';
  1123.     }
  1124.     v=getvar(v);
  1125.     if(v) puts(v); else putchar('\n');
  1126.   }
  1127. }
  1128.  
  1129. int main(int argc, char *argv[], char *envp[])
  1130. {
  1131.     char *p, homebuf[MAX_FNAME+1], lbuf[32];
  1132.     int inlen=0;
  1133. /*    int mfd; */
  1134.  
  1135.     class_dir[0]=0;
  1136.     substitute=substit; buffer_init(); var_init();
  1137. /* WIMS internal locale is always C. */
  1138.     setenv("LANG","C",1); umask(022);
  1139.     setenv("LANGUAGE","us",1);
  1140.     setenv("LC_ALL","C",1);
  1141.     if(argc>1) {
  1142.       if(strcasecmp(argv[1],"table")==0) {
  1143.           if(verify_tables()) internal_error("Table disorder.");
  1144.           else printf("Table orders OK.\n");
  1145.           return 0;
  1146.       }
  1147.       if(strcasecmp(argv[1],"version")==0) {
  1148.           printf("%s",wims_version); return 0;
  1149.       }
  1150.       if(strcasecmp(argv[1],"defaults")==0) {
  1151.           config_defaults(); return 0;
  1152.       }
  1153.       if(strcasecmp(argv[1],"test")==0) {
  1154. /* launches a test suite */
  1155.          if (argc < 5) {
  1156.            printf("Not enough arguments to launch a test; usage:\n");
  1157.            printf("wims test path_to_file name_of_proc_file 'var1 var2 ...'\n\n");
  1158.            printf("the file at path_to_file/name_of_proc_file will be evaluated by wims for\nexec commands, then the values of var1, var2, ... will be printed\nin the standard output, one per line.\n");
  1159.            return 1;
  1160.          }
  1161.          test_suite(argv[2], argv[3], argv[4]);
  1162.          return 0;
  1163.        }
  1164.     }
  1165.     p=getenv("SERVER_SOFTWARE"); if(p!=NULL && strcasecmp(p,"WIMS")==0)
  1166.       httpd_type=httpd_wims;
  1167.     p=getenv("REMOTE_ADDR"); if(p!=NULL) remote_addr=p;
  1168.     p=getenv("REMOTE_HOST"); if(p!=NULL) remote_host=p;
  1169.     nowtime=time(0); now=localtime(&nowtime);
  1170. /* nowtime contains the seconds elapsed from EPOCH (1970)
  1171.    but tm_year is set to current year-1900.
  1172.  */
  1173.     memmove(&Now, now, sizeof(Now)); now=&Now;
  1174.     snprintf(nowstr,sizeof(nowstr),"%04d%02d%02d.%02d:%02d:%02d",
  1175.            (now->tm_year)+1900,(now->tm_mon)+1,now->tm_mday,
  1176.            now->tm_hour,now->tm_min,now->tm_sec);
  1177.     p=getenv("QUERY_STRING");
  1178.     if(p==NULL || *p==0) getpost();
  1179.     else if(strncmp(p,"form-data",9)==0) inlen=formdata(p);
  1180.  
  1181.     force_setvar("wims_now",nowstr);
  1182.     snprintf(lbuf,sizeof(lbuf),"%lu",nowtime);
  1183.     force_setvar("wims_nowseconds",lbuf);
  1184.     nowtime=time(0);
  1185.     initalarm();
  1186.  
  1187.     executed_gotos=insert_no=output_length=0; ins_alt[0]=0;
  1188.     setvar("empty","");       /* lock this variable */
  1189.     setvar("wims_version",wims_version);
  1190.     setvar("wims_version_date",wims_version_date);
  1191.     setvar("wims_main_font","utf-8");
  1192.     take_httpd_vars();
  1193.  
  1194.     main_configure();
  1195.     checklogd();
  1196. /* mfd=shm_open(SHM_NAME,O_RDONLY,-1);
  1197.  * if(mfd==-1) internal_error("Unable to find shared memory.");
  1198.  * shmptr=mmap(0,SHM_SIZE,PROT_READ,MAP_SHARED,mfd,0);
  1199.  * if(shmptr==MAP_FAILED) internal_error("Shared memory failure.");
  1200.  */
  1201.     getppid(); /* this is the first sysmask trigger, must be after checklogd() */
  1202.     predetermine_language();
  1203.     /* modify a few rlimits for 64-bit processors */
  1204.     if (sizeof(long) == 8) {
  1205.       rlimit_as*=2;    /* virtual memory size */
  1206.       rlimit_data*=2;  /* data segment size; maxima requires a lot */
  1207.       rlimit_stack*=2; /* stack size */
  1208.     }
  1209.     set_rlimits();
  1210.     init_random();
  1211.     module_configure();
  1212.     set_job_ident();
  1213.     m_file.name[0]=0;m_file.linecnt=m_file.linepointer=0;
  1214.     p=getenv("QUERY_STRING");
  1215.     if(p==NULL || strlen(p)==0) {
  1216.       setvar("lang",lang);
  1217.       snprintf(homebuf,sizeof(homebuf),"module=%s",home_module);
  1218.       p=homebuf;
  1219.     }
  1220.     if(strlen(p)>=QUERY_STRING_LIMIT) user_error("parm_too_long");
  1221.     if(mpboundary[0]==0) {
  1222.       var_str=xmalloc(strlen(p)+2);
  1223.       parse_query_string(http2env(var_str,p),0);
  1224.     }
  1225.     else {
  1226.       var_str=stdinbuf;
  1227.       parse_query_string(inlen,1);
  1228.     }
  1229.     if(ismhelp) {
  1230.       p=getvar(ro_name[ro_cmd]);
  1231.       if(p==NULL || (strcmp(p,"help")!=0 && strcmp(p,"getins")!=0)) {
  1232.           mhelp(); goto outgo;
  1233.       }
  1234.     }
  1235.     check_exam();
  1236.     useropts();
  1237.     special_cmds();
  1238.     parse_ro_names();
  1239.     manager_check();
  1240.     access_check(0);
  1241. /* it is really for developing in wims, so no use in general */
  1242.    if (1==1) {
  1243.     if(strstr(tmp_debug,"yes")!=NULL && checkhost(manager_site)>=1)
  1244.        trace_file = fopen(mkfname(NULL,"%s/%s",tmp_dir,"trace.txt"),"a");
  1245.    }
  1246.     set_variables();
  1247.     determine_font(getvar("module_language"));
  1248.     determine_dirn(getvar("module_language"));
  1249.     if(!robot_access && session_prefix[0]!=0 && cmd_type!=cmd_help && !ismhelp)
  1250.       lastout_file=creat(mkfname(NULL,"%s/%s",s2_prefix,lastout),
  1251.                    S_IRUSR|S_IWUSR);
  1252.     p=getvar("module_category");
  1253.     if(p==NULL || strstr(p,"tool")==NULL) default_form_method="get";
  1254.     if(noout) {
  1255.       write_logs(); save_session_vars();
  1256.       goto outgo;
  1257.     }
  1258.     if(ismhelp) {
  1259.       mhelp();
  1260.     }
  1261.     else {
  1262.       main_phtml_put(html_file);
  1263.       if(lastout_file!=-1) {
  1264.           flushoutput(); close(lastout_file); putlastout();
  1265.       }
  1266.       write_logs(); save_session_vars();
  1267.     }
  1268.     outgo:
  1269.     debug_output();
  1270.     if (trace_file)  { fclose(trace_file); trace_file=NULL; }
  1271.     if(var_str!=stdinbuf) free(var_str);
  1272.     delete_pid();
  1273.     if(mode!=mode_popup && trusted_module()) {
  1274.       p=getvar("wims_mode");
  1275.       if(p!=NULL && strcmp(p,"popup")==0) mode=mode_popup;
  1276.     }
  1277.     if(mode==mode_popup && insert_no==0) {
  1278.       p=getvar("wims_mode");
  1279.       if(p!=NULL && strcmp(p,"popup")==0) {
  1280.           remove_tree(session_prefix);
  1281.  
  1282.           remove_tree(s2_prefix);
  1283.       }
  1284.     }
  1285.     return 0;
  1286. }
  1287.