-
Notifications
You must be signed in to change notification settings - Fork 3
/
MakoMain.c
1387 lines (1245 loc) · 35.1 KB
/
MakoMain.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ____ _________ __ _
* / __ \___ ____ _/ /_ __(_)___ ___ ___ / / ____ ____ _(_)____
* / /_/ / _ \/ __ `/ / / / / / __ `__ \/ _ \/ / / __ \/ __ `/ / ___/
* / _, _/ __/ /_/ / / / / / / / / / / / __/ /___/ /_/ / /_/ / / /__
* /_/ |_|\___/\__,_/_/ /_/ /_/_/ /_/ /_/\___/_____/\____/\__, /_/\___/
* /____/
*
* Mako Server
****************************************************************************
* PROGRAM MODULE
*
* $Id: MakoMain.c 3786 2015-11-06 22:54:28Z wini $
*
* COPYRIGHT: Real Time Logic LLC, 2012 - 2015
*
* This software is copyrighted by and is the sole property of Real
* Time Logic LLC. All rights, title, ownership, or other interests in
* the software remain the property of Real Time Logic LLC. This
* software may only be used in accordance with the terms and
* conditions stipulated in the corresponding license agreement under
* which the software has been supplied. Any unauthorized use,
* duplication, transmission, distribution, or disclosure of this
* software is expressly forbidden.
*
* This Copyright notice may not be removed or modified without prior
* written consent of Real Time Logic LLC.
*
* Real Time Logic LLC. reserves the right to modify this software
* without notice.
*
* http://realtimelogic.com
****************************************************************************
*
*/
#include "mako.h"
/* Version info */
#include "MakoVer.h"
#define MAKOEXNAME ""
#ifndef MAKO_VNAME
#define MAKO_VNAME "Mako Server" MAKOEXNAME ". Version " MAKO_VER
#endif
#ifndef MAKO_CPR
#define MAKO_CPR "Copyright (c) 2015 Real Time Logic. All rights reserved."
#endif
/* The Mako Server can optionally use an embedded version of
* mako.zip. The embedded ZIP file is a smaller version of mako.zip
* and includes just enough code to open the server listening ports
* and start LSP apps from command line params. This ZIP file is built
* and converted to a C code array by the "BuildInternalZip.sh"
* script. Note: The Mako Server will abort at startup if this macro
* is not defined and if it is unable to open the external mako.zip.
*/
#define USE_EMBEDDED_ZIP
/* The Mako Server uses a few operating system depended functions for
* Linux,Mac, QNX, and Windows. Defining this macro
* makes it possible to compile the Mako Server for other
* platforms. If you enable this macro, search below for CUSTOM_PLAT
* and implement the missing functions.
*/
/* #define CUSTOM_PLAT */
/* Use the forkpty library on Linux. */
#if !defined(CUSTOM_PLAT) && !defined(NO_FORKPTY) && !defined(_WIN32)
#define USE_FORKPTY
#endif
/* If not using: https://realtimelogic.info/amalgamator/ */
#ifndef USE_AMALGAMATED_BAS
#include "../../../xrc/lua/lxrc.h"
#include <DiskIo.h>
#include <ZipIo.h>
#include "../../../xrc/misc/NetIo.h"
#include <BaTimer.h>
#include <balua.h>
#include <HttpTrace.h>
#include <HttpCmdThreadPool.h>
#include <HttpResRdr.h>
#include <IoIntfZipReader.h>
#include <lualib.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#ifdef CUSTOM_PLAT
/* Include custom header files */
#else
#ifdef _WIN32
#pragma warning(disable : 4996)
#include "Windows/servutil.h"
#include <direct.h>
#define xgetcwd _getcwd
#else
#include <pwd.h>
#include <syslog.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#define xgetcwd getcwd
#endif
#endif
typedef struct
{
U32 trackerNodes,maxlogin;
BaTime bantime;
} ConfigParams;
ConfigParams* cfgParams;
int daemonMode=FALSE;
#ifdef USE_EMBEDDED_ZIP
extern ZipReader* getLspZipReader(void); /* ../obj/debug|release/LspZip.c */
#endif
/* xrc/sql/ */
#ifdef MAKOEX
#define luaopen_SQL luaopen_luasql_ittiadb
extern int luaopen_luasql_ittiadb(lua_State *L);
#else
#define luaopen_SQL luaopen_luasql_sqlite3
extern int luaopen_luasql_sqlite3(lua_State *L);
#endif
#ifdef BAS_LOADED
void luaopen_ba_redirector(lua_State *L);
#endif
/* Global pointer to dispatcher declared on 'main' stack */
static SoDisp* dispatcher;
static lua_State* L; /* pointer to the Lua virtual machine */
static IoIntfZipReader* makoZipReader; /* When using the ZIP file */
static FILE* logFp; /* Log file */
/* Change log file location/name */
static int lSetLogFile(lua_State *L)
{
const char* name = luaL_checkstring(L,1);
FILE* fp = fopen(name, "wb");
if(fp)
{
if(logFp) fclose(logFp);
logFp=fp;
lua_pushboolean(L, TRUE);
}
else
lua_pushboolean(L, FALSE);
return 1;
}
#ifndef va_copy
#define va_copy(d,s) ((d) = (s))
#endif
void
makovprintf(int isErr,const char* fmt, va_list argList)
{
va_list xList;
if(daemonMode || logFp)
{
#if !defined(_WIN32) && !defined(CUSTOM_PLAT)
if(isErr)
{
va_copy(xList, argList);
vsyslog(LOG_CRIT, fmt, xList);
va_end(xList);
}
#endif
if(!logFp)
{
logFp=fopen("mako.log","wb+");
if(!logFp)
{
char* tmp=getenv("TMP");
if(!tmp)
tmp=getenv("TEMP");
if(tmp)
{
char* ptr=malloc(strlen(tmp)+10);
if(ptr)
{
sprintf(ptr,"%s/mako.log",tmp);
logFp=fopen(ptr,"wb+");
free(ptr);
}
}
}
if(!logFp) return;
}
if( ! daemonMode )
{
va_copy(xList, argList);
vfprintf(logFp,fmt,xList);
va_end(xList);
vfprintf(stderr,fmt,argList);
}
else
vfprintf(logFp,fmt,argList);
fflush(logFp);
}
else
vfprintf(stderr,fmt,argList);
}
void
makoprintf(int isErr,const char* fmt, ...)
{
va_list varg;
va_start(varg, fmt);
makovprintf(isErr, fmt, varg);
va_end(varg);
}
void
errQuit(const char* fmt, ...)
{
va_list varg;
va_start(varg, fmt);
makovprintf(TRUE, fmt, varg);
va_end(varg);
HttpTrace_flush();
if(logFp) fclose(logFp);
exit(1);
}
static void
serverErrHandler(BaFatalErrorCodes ecode1,
unsigned int ecode2,
const char* file,
int line)
{
sendFatalError("FE",ecode1,ecode2,file,line);
errQuit("Fatal err: %d:%d, %s %d\n",ecode1,ecode2,file,line);
}
static void
writeHttpTrace(char* buf, int bufLen)
{
buf[bufLen]=0; /* Safe. See documentation. */
makoprintf(FALSE,"%s",buf);
}
void
setDispExit(void)
{
SoDisp_setExit(dispatcher);
}
static int
findFlag(int argc, char** argv, const char flag, const char** data)
{
int i;
for(i = 1; i < argc ; i++)
{
char* ptr = argv[i];
if(*ptr == '-' && ptr[1] == flag && !ptr[2])
{
if(data)
*data = ((i+1) < argc) ? argv[i+1] : NULL;
return TRUE;
}
}
if(data)
*data = NULL;
return FALSE;
}
#ifdef CUSTOM_PLAT
/* The "get current directory" function is used when searching for the
* Mako config file. This function is not required and can return NULL.
*
* In addition to the optional command line parameter "-c", the Mako
* Server also looks for the config file in the directory returned
* by function findExecPath.
*/
static char*
xgetcwd(char *buf, size_t size)
{
return 0;
}
/* This function should return the path to the directory where
* mako.zip is stored. The buffer must be dynamically allocated since
* the caller frees the memory by calling baFree. This function must
* be implemented if the macro USE_EMBEDDED_ZIP is undefined.
*/
static char*
findExecPath(const char* argv0)
{
/* The following example code shows how you could potentially use
* xgetcwd to return the path, assuming that the home directory is
* where the Mako ZIP file is stored.
*/
char* buf=baMalloc(1000);
if(buf)
return xgetcwd(buf,1000);
return 0;
}
/* The following functions are not required and are defined to do nothing. */
/* Enter Linux daemon mode */
#define setLinuxDaemonMode()
#define disableSignals()
/* Set Linux user */
#define setUser(argc, argv)
/* Install a CTRL-C handler */
#define setCtrlCHandler()
#else /* CUSTOM_PLAT */
/******************************** WIN32 **********************************/
#ifdef _WIN32
#define BA_WIN32
static int
pxexit(int status, int pause)
{
if(pause)
{
fprintf(stderr,"\nPress <Enter> to continue.\n");
getchar();
}
exit(status);
}
static char*
findExecPath(const char* argv0)
{
char buf[2048];
(void)argv0;
if(GetModuleFileName(NULL, buf, sizeof(buf)))
{
char* ptr=strrchr(buf,'\\');
if(ptr)
ptr[0]=0;
else
buf[0]=0;
return baStrdup(buf);
}
return NULL;
}
static BOOL WINAPI
sigTerm(DWORD x)
{
makoprintf(FALSE,"\nExiting...\n");
setDispExit();
while(dispatcher) Sleep(100); /* Ref-wait */
return FALSE;
}
static void
setCtrlCHandler(void)
{
SetConsoleCtrlHandler(sigTerm, TRUE);
}
#define setLinuxDaemonMode()
#define disableSignals()
#define setUser(argc, argv)
/******************************** LINUX **********************************/
#else /* #ifdef _WIN32 */
#ifdef _OSX_
#include <mach-o/dyld.h>
static char*
findExecPath(const char* argv0)
{
char path[2048];
uint32_t size = sizeof(path);
(void)argv0;
if ( ! _NSGetExecutablePath(path, &size) )
{
char* ptr=strrchr(path,'/');
if(ptr)
ptr[0]=0;
else
path[0]=0;
ptr=baStrdup(path);
if(ptr && realpath(ptr, path))
{
free(ptr);
return baStrdup(path);
}
return ptr;
}
return NULL;
}
#else
static char*
findExecPath(const char* argv0)
{
char* ptr;
char buf[2048];
ssize_t size = readlink("/proc/self/exe", buf, sizeof(buf));
if(size < 0)
{
if( (size = readlink("/proc/curproc/file", buf, sizeof(buf))) < 0)
{
if( (size = readlink("/proc/self/path/a.out", buf, sizeof(buf))) < 0)
{
struct stat statBuf;
if(argv0 && ! stat(argv0, &statBuf) && S_ISREG(statBuf.st_mode) &&
xgetcwd(buf, sizeof(buf)))
{
strcat(buf,"/");
strcat(buf,argv0);
size=1;
}
else
{
char* name;
char* path=getenv("PATH");
while(path)
{
int len;
ptr=strchr(path,':');
if(!ptr)
ptr=path+strlen(path);
len = ptr-path;
name=malloc(len+10);
if(!name)
return 0;
strncpy(name, path, len);
name[len]=0;
if(name[len-1] != '/')
strcat(name,"/");
strcat(name,"mako.zip");
if( ! stat(name, &statBuf) )
{
ptr=strrchr(name,'/');
*ptr=0;
return name;
}
path=ptr+1;
if( ! *path )
return 0;
}
}
}
}
}
if(size > 0)
{
buf[size]=0;
ptr=strrchr(buf,'/');
if(ptr)
ptr[0]=0;
else
buf[0]=0;
return baStrdup(buf);
}
return 0;
}
#endif
static void
sigTerm(int x)
{
(void)x;
static int oneshot=FALSE;
if(oneshot)
{
makoprintf(FALSE,"\nGot SIGTERM again; aborting...\n");
HttpTrace_flush();
if(logFp) fclose(logFp);
abort();
}
oneshot=TRUE;
makoprintf(FALSE,"\nGot SIGTERM; exiting...\n");
setDispExit();
}
static void
setCtrlCHandler(void)
{
signal(SIGINT, sigTerm);
signal(SIGTERM, sigTerm);
}
static void
cfignoreSignal(int sig, const char* signame)
{
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(sig, &sa, NULL) < 0)
errQuit("can't ignore %s.\n", signame);
}
#define ignoreSignal(x) cfignoreSignal((int)(x), #x)
static void
cfblockSignal(int sig, const char* signame)
{
sigset_t set;
sigemptyset(&set);
sigaddset(&set, sig);
if (sigprocmask(SIG_BLOCK, (const sigset_t*) &set, NULL) < 0)
errQuit("can't block %s - %s.\n", signame,strerror(errno));
}
#define blockSignal(x) cfblockSignal((int)(x), #x)
static void
disableSignals(void)
{
ignoreSignal(SIGPIPE);
}
static void
setLinuxDaemonMode(void)
{
int fd0, fd1, fd2;
pid_t pid;
/*
* Clear file creation mask.
*/
umask(0);
/*
* Become a session leader to lose controlling TTY.
*/
if((pid = fork()) < 0)
errQuit("%s: can't fork\n", APPNAME);
else if(pid != 0) /* parent */
exit(0);
setsid();
if((pid = fork()) < 0)
errQuit("%s: can't fork\n", APPNAME);
else if (pid != 0) /* parent */
exit(0);
ignoreSignal(SIGHUP);
ignoreSignal(SIGTTOU);
ignoreSignal(SIGTTIN);
ignoreSignal(SIGTSTP);
ignoreSignal(SIGPIPE);
ignoreSignal(SIGXFSZ);
ignoreSignal(SIGXCPU); /*Prevent server from terminating after a few days*/
ignoreSignal(SIGXFSZ);
blockSignal(SIGUSR1);
blockSignal(SIGUSR2);
/*
** Attach file descriptors 0, 1, and 2 to /dev/null.
** Note that these do not have cloexec set.
** The idea is that both parent and child processes that write to
** stdout/stderr will gracefully do nothing.
**/
close(0);
close(1);
close(2);
fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
/*
* Initialize the log file.
*/
openlog(APPNAME, LOG_CONS|LOG_PID, LOG_DAEMON);
if (fd0 != 0 || fd1 != 1 || fd2 != 2)
{
errQuit("unexpected file descriptors %d %d %d\n",fd0, fd1, fd2);
}
syslog(LOG_INFO, "%s: daemon started...", APPNAME);
}
static void
setUser(int argc, char** argv)
{
const char* userName;
findFlag(argc, argv, 'u', &userName);
if(userName)
{
if(getuid()==0 && getgid()==0)
{
struct passwd* pwd;
makoprintf(FALSE,"Setting user to '%s'\n", userName);
pwd = getpwnam(userName);
if(pwd)
{
if(setgid(pwd->pw_gid) || setuid(pwd->pw_uid))
{
errQuit("Cannot set user and/or group ID to %s.\n",userName);
}
else
return; /* success */
}
else
errQuit("Cannot find user %s.\n",userName);
}
else
{
makoprintf(TRUE,
"Cannot use command line option: -u %s. "
"You are not root.\n", userName);
}
}
}
#endif /* #ifdef _WIN32 */
/***************************** END WIN/LINUX *******************************/
#endif /* #ifdef CUSTOM_PLAT */
/* Run the Lua 'onunload' handlers for all loaded apps when mako exits.
onunload is an optional function applications loaded by mako can
use if the applications require graceful termination such as
sending a socket close message to peers.
*/
static void
onunload(void)
{
/* Run the 'onunload' function in the .config Lua script, which in
* turn runs the optional onunload for all loaded apps.
*/
lua_getglobal(L,"onunload");
if(lua_isfunction(L, -1))
{
if(lua_pcall(L, 0, 1, 0))
{
makoprintf(TRUE,"Error in 'onunload': %s\n",
lua_isstring(L,-1) ? lua_tostring(L, -1) : "?");
}
}
}
static int
loadConfigData(lua_State* L)
{
U16 val;
HttpServerConfig* cfg = (HttpServerConfig*)lua_touserdata(L,1);
int status = luaL_loadfile(L, (const char*)lua_touserdata(L,2));
const char** paramPtr = lua_touserdata(L,3);
if (status != 0 && status != LUA_ERRFILE)
lua_error(L);
else
lua_call(L,0,0);
*paramPtr="commandcnt";
lua_getglobal(L, *paramPtr);
HttpServerConfig_setNoOfHttpCommands(cfg,(U16)luaL_optinteger(L,-1,3));
*paramPtr="sessioncnt";
lua_getglobal(L, *paramPtr);
HttpServerConfig_setMaxSessions(cfg,(U16)luaL_optinteger(L,-1,50));
*paramPtr="conncnt";
lua_getglobal(L, *paramPtr);
HttpServerConfig_setNoOfHttpConnections(cfg,(U16)luaL_optinteger(L,-1,50));
*paramPtr="rspsz";
lua_getglobal(L, *paramPtr);
HttpServerConfig_setResponseData(cfg,(U16)luaL_optinteger(L,-1,8*1024));
*paramPtr="reqminsz";
lua_getglobal(L, *paramPtr);
val=(U16)luaL_optinteger(L,-1,4*1024);
*paramPtr="reqmaxsz";
lua_getglobal(L, *paramPtr);
HttpServerConfig_setRequest(cfg,val,(U16)luaL_optinteger(L,-1,8*1024));
*paramPtr="tracker_nodes";
lua_getglobal(L, *paramPtr);
cfgParams->trackerNodes=(int)luaL_optinteger(L,-1,100);
*paramPtr="tracker_maxlogin";
lua_getglobal(L, *paramPtr);
cfgParams->maxlogin=(int)luaL_optinteger(L,-1,4);
*paramPtr="tracker_bantime";
lua_getglobal(L, *paramPtr);
cfgParams->bantime=(int)luaL_optinteger(L,-1,10*60);
return 0;
}
static char*
openAndLoadConf(const char* path, HttpServerConfig* scfg, int isdir)
{
char* name=0;
char* abspath=0;
if(path)
{
if(*LUA_DIRSEP == '/' ? (path[0] != '/') : (path[1] != ':'))
{
char cwd[1024];
if(xgetcwd(cwd, sizeof(cwd)))
{
abspath=baMalloc(strlen(cwd)+strlen(path)+5);
basprintf(abspath,"%s%s%s",cwd,LUA_DIRSEP,path);
baElideDotDot(abspath);
path=abspath;
}
}
name=malloc(strlen(path)+15);
if(name)
{
struct stat statBuf;
if(isdir)
basprintf(name,"%s%smako.conf",path,LUA_DIRSEP);
else
basprintf(name,"%s",path);
if( ! stat(name, &statBuf) )
{
const char* param=0;
lua_State* L = luaL_newstate();
luaopen_base(L);
lua_pushcfunction(L,loadConfigData);
lua_pushlightuserdata(L, scfg);
lua_pushlightuserdata(L, name);
lua_pushlightuserdata(L, (void*)¶m);
makoprintf(FALSE,"Loading %s.\n",name);
if(lua_pcall(L,3,0,0))
{
const char* msg=lua_tostring(L,-1);
if (!msg) msg="(error with no message)";
if(param)
{
const char* ptr=strchr(msg, '(');
makoprintf(TRUE,"Invalid value for paramater '%s': %s\n",
param, ptr ? ptr : msg);
}
else
makoprintf(TRUE,"%s\n",msg);
exit(1);
}
lua_close(L);
}
else
{
free(name);
name=NULL;
}
}
}
if(abspath)
baFree(abspath);
return name;
}
static char*
openAndLoadConfUsingExecPath(
HttpServerConfig* cfg, const char* argv0, char** execpath)
{
*execpath=findExecPath(argv0);
if(*execpath)
{
char* cfgfname=openAndLoadConf(*execpath,cfg,TRUE);
return cfgfname;
}
return NULL;
}
/* Initialize the HttpServer object by calling HttpServer_constructor.
The HttpServerConfig object is only needed during initialization.
*/
static char*
createServer(HttpServer* server,int argc, char** argv, char** execpath)
{
HttpServerConfig scfg;
const char* ccfgfname;
char* cfgfname=0;
*execpath=0;
HttpServerConfig_constructor(&scfg);
if(findFlag(argc, argv, 'c', &ccfgfname))
{
if( ! (cfgfname=openAndLoadConf(ccfgfname,&scfg,FALSE)) )
{
errQuit("Error: cannot load configuration file %s.\n",ccfgfname);
}
}
else if( ! (cfgfname=openAndLoadConfUsingExecPath(
&scfg,argc>0?argv[0]:0,execpath)) &&
! (cfgfname=openAndLoadConf("mako.conf",&scfg,FALSE)))
{
if( ! (cfgfname=openAndLoadConf(getenv("HOME"),&scfg,TRUE)) )
{
#ifdef BA_WIN32
if( ! (cfgfname=openAndLoadConf(getenv("USERPROFILE"),&scfg,TRUE)) )
cfgfname=openAndLoadConf(getenv("HOMEPATH"),&scfg,TRUE);
#endif
}
}
if(!cfgfname)
{
HttpServerConfig_setNoOfHttpCommands(&scfg,3);
HttpServerConfig_setNoOfHttpConnections(&scfg,50);
HttpServerConfig_setMaxSessions(&scfg,50);
HttpServerConfig_setResponseData(&scfg,8*1024);
HttpServerConfig_setRequest(&scfg,4*1024,8*1024);
}
/* Create and init the server, by using the above HttpServerConfig.
*/
HttpServer_constructor(server, dispatcher, &scfg);
return cfgfname;
}
/* Create Lua global variables "argv" for the command line arguments and
* "env" for the system environment variables.
*/
static void
createLuaGlobals(
int argc, char** argv, char** envp, char* cfgfname, const char* execpath)
{
int i;
char* ptr;
static const luaL_Reg funcs[] = {
{"logfile", lSetLogFile},
{NULL, NULL}
};
lua_newtable(L);
lua_pushstring(L, MAKO_VER);
lua_setfield(L, -2, "version");
lua_pushstring(L, __DATE__);
lua_setfield(L, -2, "date");
#ifdef BASLIB_VER
lua_pushstring(L, BASLIB_VER);
lua_setfield(L, -2, "BAS");
#endif
lua_newtable(L);
for(i=1 ; i < argc; i++)
{
lua_pushstring(L, argv[i]);
lua_rawseti(L, -2, i);
}
lua_setfield(L, -2, "argv");
if(envp)
{
lua_newtable(L);
for(ptr=*envp ; ptr; ptr=*++envp)
{
char* v = strchr(ptr, '=');
if(v)
{
lua_pushlstring(L, ptr, v-ptr);
lua_pushstring(L, v+1);
lua_rawset(L, -3);
}
}
lua_setfield(L, -2, "env");
}
if(cfgfname)
{
lua_pushstring(L, cfgfname);
lua_setfield(L, -2, "cfgfname");
free(cfgfname);
}
if(execpath)
{
lua_pushstring(L, execpath);
lua_setfield(L, -2, "execpath");
}
lua_pushboolean(L, daemonMode);
lua_setfield(L, -2, "daemon");
luaL_setfuncs(L, funcs, 0);
lua_setglobal(L, "mako");
};
static void
printUsage()
{
static const char usage[]={
"Usage: " APPNAME " [options]\n"
"\nOptions:\n"
" -l[name]:[priority]:app - Load one or multiple applications\n"
" -c configfile - Load configuration file\n"
" -? -h - print this help message\n"
#ifdef BA_WIN32
" -install - Installs the service\n"
" -installauto - Installs the service for autostart\n"
" -remove - Removes the service\n"
" -start - Starts the service\n"
" -stop - Stops the service\n"
" -restart - Stops and starts the service\n"
" -autostart - Changes the service to automatic start\n"
" -manual - Changes the service to manual start\n"
" -state - Print the service state\n"
#else
" -d - Run in daemon mode\n"
" -u username - Username to run as\n"
#endif
};
fprintf(stderr,"%s",usage);
exit(1);
}
static IoIntf*
checkMakoIo(IoIntf* io, const char* name)
{
IoStat sb;
if( ! io->statFp(io, ".config", &sb) &&
! io->statFp(io, ".openports", &sb))
{
makoprintf(FALSE,"Mounting %s\n",name);
return io;
}
makoprintf(
TRUE,"%s is missing .config or .openports\n",name);
return 0;
}
static IoIntf*
createAndCheckMakoZipIo(ZipReader* zipReader, const char* name)
{
if(CspReader_isValid((CspReader*)zipReader))
{
ZipIo* vmIo=(ZipIo*)baMalloc(sizeof(ZipIo));
ZipIo_constructor(vmIo, zipReader, 2048, 0);
if(ZipIo_getECode(vmIo) == ZipErr_NoError)
{
if(checkMakoIo((IoIntf*)vmIo,name))
return (IoIntf*)vmIo;
}
ZipIo_destructor(vmIo);
baFree(vmIo);
}
return 0;
}
static IoIntf*
openMakoZip(IoIntf* rootIo, const char* path)
{
IoStat st;
IoIntf* io=0;
int plen=strlen(path);
char* buf=(char*)baMalloc(plen+12);
basprintf(buf,"%s%smako.zip",
path, path[plen-1] == *LUA_DIRSEP ? "" : LUA_DIRSEP);
if(*LUA_DIRSEP == '\\')
{
char* ptr=buf;
while(*ptr)
{
if(*ptr == '\\')
*ptr='/';
ptr++;
}
if(buf[1]==':')
{
buf[1] = buf[0];
buf[0]='/';
}
}
baElideDotDot(buf);
if( ! rootIo->statFp(rootIo, buf, &st) )
{
makoZipReader = baMalloc(sizeof(IoIntfZipReader));
IoIntfZipReader_constructor(makoZipReader, rootIo, buf);
io=createAndCheckMakoZipIo((ZipReader*)makoZipReader, buf);
if(!io)
{
IoIntfZipReader_destructor(makoZipReader);
baFree(makoZipReader);
makoZipReader=0;
}
}
baFree(buf);