Subversion Repositories wimsdev

Rev

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