Subversion Repositories wimsdev

Rev

Rev 14873 | Rev 16647 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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