forked from fumiyas/hyperestraier-encore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
estmaster.c
6484 lines (6300 loc) · 253 KB
/
estmaster.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
/*************************************************************************************************
* The master of node servers
* Copyright (C) 2004-2007 Mikio Hirabayashi
* This file is part of Hyper Estraier.
* Hyper Estraier is free software; you can redistribute it and/or modify it under the terms of
* the GNU Lesser General Public License as published by the Free Software Foundation; either
* version 2.1 of the License or any later version. Hyper Estraier is distributed in the hope
* that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
* You should have received a copy of the GNU Lesser General Public License along with Hyper
* Estraier; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA.
*************************************************************************************************/
#include "mastermod.h"
#include "myimage.dat"
#define SERVNAME "estmaster" /* name of the server */
#define IOBUFSIZ 8192 /* size of a buffer for I/O */
#define SPCACHEMNUM 131072 /* max number of the special cache */
#define IREFRESHSEC 3 /* wait time for refreshing and charging */
#define ICHARGENUM 16 /* number of keys per charging */
#define IFLUSHNUM 32768 /* number of keys per flushing */
#define LINKMASKMAX 31 /* maximum number of link masks */
#define LCSRCHRESMIN 31 /* minimum number of result to get from local */
#define RMSRCHRESMIN 16 /* minimum number of result to get from local */
#define FCLOSECONNNUM 10 /* number of over connections for forced closing */
#define FCLOSEWAITMAX 10 /* wait time for forced closing */
#define FTERMWAITMAX 60 /* wait time for forced termination */
#define HELPERTRYNUM 3 /* number of trys of helper command */
#define UICACHELIFE 1800 /* maximum age of image cache data */
#define IMGCACHELIFE (3600 * 24) /* maximum age of image cache data */
#define MASTERLOC "/master" /* location of the URL of the master */
#define NODEPREFIX "/node/" /* prefix of URLs of nodes */
#define MASTERUILOC "/master_ui" /* location of administration user intarfaces */
#define FAVICONLOC "/favicon.ico" /* location of the favorite icon */
#define IMAGEPREFIX "/image/" /* prefix of URLs of images */
#define SEARCHUICMD "search_ui" /* name of search user interface */
#define SEARCHATOMCMD "search_atom" /* name of Atom feed interface */
#define SEARCHRSSCMD "search_rss" /* name of RSS feed interface */
#define OPENSEARCHCMD "opensearch" /* name of OpenSearch Description */
#define BIGICONNAME "bigicon.png" /* name of the big icon */
#define CANVASNAME "canvas.png" /* name of the backgroud pattern */
#define DELIMSTR "{{!}}" /* delimiter string */
#define UIMIMETYPE "text/html; charset=UTF-8" /* media type of search_ui */
#define ATOMMIMETYPE "application/atom+xml" /* media type of search_atom */
#define RSSMIMETYPE "application/rdf+xml" /* media type of search_rss */
#define OSRCHMIMETYPE "application/opensearchdescription+xml" /* media type of opensearch */
#define DIRMIMETYPE "text/html" /* media type of directory index */
#define MENUMIMETYPE "text/html" /* media type of the menu page */
#define DEFMIMETYPE "application/octet-stream" /* media type by default */
typedef struct { /* type of structure for a communication */
int clsock; /* socket between client */
char claddr[ADDRBUFSIZ]; /* address of the client */
int clport; /* port number of the client */
} TARGCOMM;
enum { /* enumeration for HTTP method */
HM_HEAD, /* HEAD */
HM_GET, /* GET */
HM_POST, /* POST */
HM_OPTIONS, /* OPTIONS */
HM_UNKNOWN /* unknown */
};
typedef struct { /* type of structure for a request */
const char *claddr; /* address of the client */
int clport; /* port number of the client */
char prefix[HOSTBUFSIZ]; /* prefix of the server */
int method; /* method */
char *target; /* target path */
char *name; /* user name */
char *passwd; /* password */
time_t ims; /* if-modified-since header */
int gzip; /* whether to accept gzip encoding */
int deflate; /* whether to accept deflate encoding */
char *ctype; /* content-type header */
char *referer; /* referer header */
char *estvia; /* x-estraier-via header */
char *body; /* entity body */
CBMAP *params; /* parameters */
time_t now; /* current time */
int reload; /* whether to be reloaded */
} REQUEST;
typedef struct { /* type of structure for a local search */
REQUEST *req; /* request object */
int alive; /* whether to be alive */
ESTCOND *cond; /* search condition */
CBMAP *hints; /* hints about result */
int max; /* max number of retrieved documents */
NODE *node; /* self node object */
RESMAP *resmap; /* documents in result */
CBLIST *words; /* words in the search phrase */
int hnum; /* number of hits */
int mhnum; /* number of mishits */
double itime; /* index elapsed time */
double etime; /* total elapsed time */
} TARGLCSRCH;
typedef struct { /* type of structure for a remote search */
REQUEST *req; /* request object */
int alive; /* whether to be alive */
const char *myurl; /* url of the local node */
ESTCOND *cond; /* search condition */
CBMAP *hints; /* hints about result */
int max; /* max number of retrieved documents */
NODE *node; /* self node object */
RESMAP *resmap; /* documents in result */
const char *url; /* URL of the link */
int credit; /* credit of the link */
char *label; /* label of the link */
int depth; /* depth of meta search */
int wwidth; /* while width of a snippet */
int hwidth; /* top width of a snippet */
int awidth; /* around width of a snippet */
int hnum; /* number of hits */
int dnum; /* number of documents */
int wnum; /* number of words */
double etime; /* elapsed time */
double size; /* size of the database */
time_t mtime; /* modification time */
} TARGRMSRCH;
enum { /* enumeration for UI operations */
UI_VIEWMASTER, /* view master operations */
UI_SHUTDOWN, /* shutdown the master server */
UI_SYNCNODES, /* synchronize all nodes */
UI_BACKUPDB, /* backup the database */
UI_VIEWUSERS, /* view user operations */
UI_NEWUSER, /* create a user */
UI_DELUSER, /* delete a user */
UI_VIEWNODES, /* view node operations */
UI_NEWNODE, /* create a node */
UI_DELENODE, /* delete a node */
UI_EDITNODE, /* edit a node */
UI_STATNODE, /* view search history of a node */
UI_NONE /* none */
};
/* global variables */
const char *g_progname; /* program name */
int g_sigterm = FALSE; /* flag for termination signal */
int g_sigrestart = FALSE; /* flag for restarting signal */
int g_sigsync = FALSE; /* flag for synchronus signal */
int g_sigback = FALSE; /* flag for backup signal */
const char *g_rootdir = NULL; /* path of the root directory */
const char *g_bindaddr = NULL; /* binding address of TCP */
int g_portnum = 0; /* port number of TCP */
const char *g_publicurl = NULL; /* public URL */
int g_runmode = 0; /* runnning mode */
int g_authmode = 0; /* authorization mode */
int g_recvmax = 0; /* maximum length of data to receive */
int g_maxconn = 0; /* maximum number of connections */
int g_idleflush = 0; /* idle time to start flushing */
int g_idlesync = 0; /* idle time to start synchronizing */
int g_sessiontimeout = 0; /* timeout of a session, in seconds */
int g_searchtimeout = 0; /* timeout of search, in seconds */
int g_searchmax = 0; /* maximum number of documents to send */
int g_searchdepth = 0; /* depth of meta search */
int g_rateuri = FALSE; /* whether to rate URI for scoring */
int g_mergemethod = 0; /* merge method */
const char *g_proxyhost = NULL; /* host name of the proxy */
int g_proxyport = 0; /* port number of the proxy */
const char *g_logfile = NULL; /* path of the log file */
int g_loglevel = 0; /* logging level */
const char *g_backupcmd = NULL; /* path of the backup command */
int g_scalepred = 0; /* scale prediction */
int g_scoreexpr = 0; /* score expression */
CBLIST *g_attrindexes = NULL; /* expressions of attribute indexes */
const char *g_docroot = NULL; /* path of the document root directory */
const char *g_indexfile = NULL; /* name of the directory index file */
CBMAP *g_trustednodes = NULL; /* addresses of trusted nodes */
int g_denyuntrusted = FALSE; /* whether to deny untrusted nodes */
double g_cachesize = 0.0; /* maximum size of the index cache */
int g_cacheanum = 0; /* max of cached records for document attributes */
int g_cachetnum = 0; /* max of cached records for document texts */
int g_cachernum = 0; /* max of cached records for occurrence results */
const char *g_specialcache = NULL; /* name of the attribute of special cache */
double g_helpershift = 0.0; /* lower limit of cache usage size to use the helper */
int g_wildmax = -1; /* maximum number of extension of wild cards */
int g_limittextsize = 0; /* text size limitation */
int g_snipwwidth = 0; /* whole width of the snippet */
int g_sniphwidth = 0; /* width of beginning of the text */
int g_snipawidth = 0; /* width around each highlighted word */
int g_scancheck = FALSE; /* whether to check documents by scanning */
int g_smlrvnum = 0; /* number of keywords for similarity search */
int g_extdelay = 0; /* number of documents for delay of extraction */
const char *g_adminemail = NULL; /* e-mail address of the administrator */
CBLIST *g_uireplaces = NULL; /* expressions to replace the URI of each document */
CBLIST *g_uiextattrs = NULL; /* extra attributes to be shown */
int g_uiphraseform = 0; /* mode of phrase form */
const char *g_uismlrtune = NULL; /* tuning parameters for similarity search */
int g_bgmode = FALSE; /* whether to be foreground mode */
int g_romode = FALSE; /* whether to be read only mode */
int g_stmode = FALSE; /* whether to be single thread mode */
char g_hostname[HOSTBUFSIZ]; /* host name of the server */
DEPOT *g_metadb = NULL; /* meta database */
DEPOT *g_dfdb = NULL; /* document frequency database */
UMGR *g_umgr = NULL; /* user manager */
NMGR *g_nmgr = NULL; /* node manager */
RWLOCK *g_runlock = NULL; /* read-write lock for running threads */
RWLOCK *g_mgrlock = NULL; /* read-write lock for handling managers */
pthread_mutex_t g_backlock = PTHREAD_MUTEX_INITIALIZER; /* mutex for background tasks */
const char *g_bordstr = NULL; /* border string */
int g_svsock = -1; /* server socket */
int g_accesscount = 0; /* count of all access */
time_t g_startdate = 0; /* start date of the server */
double g_cacheratio = 0.0; /* worst usage ratio of the index cache */
/* function prototypes */
int main(int argc, char **argv);
static int realmain(int argc, char **argv);
static void setsignals(void);
static void sigtermhandler(int num);
static void usage(void);
static int runinit(int argc, char **argv);
static int runstart(int argc, char **argv);
static int runstop(int argc, char **argv);
static int rununittest(int argc, char **argv);
static int runcrypt(int argc, char **argv);
static void die(const char *format, ...);
static void startup(void);
static const char *skiplabel(const char *str);
static void cleanup(void);
static int procinit(const char *rootdir, int ex);
static int procstart(const char *rootdir);
static int procstop(const char *rootdir);
static int procunittest(const char *rootdir);
static int proccrypt(const char *key, const char *hash);
static void dispatch(void);
static void *refreshnode(void *targ);
static void *flushnode(void *targ);
static void *syncnodes(void *targ);
static void backupdb(void);
static void *communicate(void *targ);
static void setparams(CBMAP *params, const char *src);
static void addservinfo(CBDATUM *datum, time_t now, int ccage);
static void senderror(int clsock, REQUEST *req, int code, const char *message);
static void sendautherror(int clsock, REQUEST *req, const char *realm);
static void sendnotmoderror(int clsock, REQUEST *req);
static void sendheadonly(int clsock, REQUEST *req, const char *type);
static int isbanned(USER *user);
static int ismasteradmin(REQUEST *req, USER *user);
static int isnodeadmin(NODE *node, REQUEST *req, USER *user);
static int isnodeuser(NODE *node, REQUEST *req, USER *user);
static int getnodeoptions(void);
static void sendoptions(int clsock, REQUEST *req, USER *user);
static void sendmasterdata(int clsock, REQUEST *req, USER *user);
static void sendnodedata(int clsock, REQUEST *req, USER *user, const char *path);
static void setdocorigin(ESTDOC *doc, REQUEST *req, NODE *node, int score);
static void mergehints(CBMAP *total, CBMAP *local);
static int islooproute(const char *url, REQUEST *req);
static void *searchlocal(void *targ);
static void *searchremote(void *targ);
static void setsimilarphrase(ESTCOND *cond, const char *url, int id);
static void catdocdata(CBDATUM *datum, NODE *node, RESDOC *resdoc, CBLIST *words,
int wwidth, int hwidth, int awidth);
static void catdocdataui(CBDATUM *datum, int num, RESDOC *resdoc, CBLIST *words,
REQUEST *req, NODE *node, const char *condstr, const char *simcondstr);
static void catdocdataatom(CBDATUM *datum, RESDOC *resdoc, CBLIST *words, NODE *node);
static void catdocdatarss(CBDATUM *datum, RESDOC *resdoc, CBLIST *words, NODE *node);
static char *makeshownuri(const char *uri);
static void sendnodecmdinform(int clsock, REQUEST *req, NODE *node);
static int sendnodecmdinformhelper(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdcacheusage(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdsearch(int clsock, REQUEST *req, NODE *node);
static int sendnodecmdsearchhelper(int clsock, REQUEST *req, NODE *node, const char *myurl);
static void sendnodecmdlist(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdgetdoc(int clsock, REQUEST *req, NODE *node);
static int sendnodecmdgetdochelper(int clsock, REQUEST *req, NODE *node,
int id, const char *uri, int options);
static void sendnodecmdgetdocattr(int clsock, REQUEST *req, NODE *node);
static int sendnodecmdgetdocattrhelper(int clsock, REQUEST *req, NODE *node,
int id, const char *uri, const char *attr);
static void sendnodecmdetchdoc(int clsock, REQUEST *req, NODE *node);
static int sendnodecmdetchdochelper(int clsock, REQUEST *req, NODE *node,
int id, const char *uri);
static void sendnodecmduritoid(int clsock, REQUEST *req, NODE *node);
static int sendnodecmduritoidhelper(int clsock, REQUEST *req, NODE *node, const char *uri);
static void sendnodecmdputdoc(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdoutdoc(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdeditdoc(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdsync(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdoptimize(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdsetuser(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdsetlink(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdsearchui(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdsearchatom(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdsearchrss(int clsock, REQUEST *req, NODE *node);
static void sendnodecmdopensearch(int clsock, REQUEST *req, NODE *node);
static void sendmasteruidata(int clsock, REQUEST *req, USER *user);
static void sendfavicondata(int clsock, REQUEST *req);
static void sendimagedata(int clsock, REQUEST *req, const char *name);
static void sendfiledata(int clsock, REQUEST *req);
static char *makelocalpath(const char *target);
static void sendmenudata(int clsock, REQUEST *req);
/* for windows service */
#if defined(MYWINSERV)
SERVICE_STATUS_HANDLE g_svstat = 0;
static void svmain(int argc, char **argv);
static int sendstatus(int curstate, int exitcode, int svexitcode, int check, int hint);
static void svfinish(int code);
static void svhandle(int code);
static void svmain(int argc, char **argv){
if(!(g_svstat = RegisterServiceCtrlHandler(SERVNAME, (LPHANDLER_FUNCTION)svhandle))){
svfinish(GetLastError());
return;
}
if(!sendstatus(SERVICE_START_PENDING, 0, 0, 1, 5000)){
svfinish(GetLastError());
return;
}
est_init_net_env();
startup();
if(!sendstatus(SERVICE_RUNNING, 0, 0, 0, 0)){
svfinish(GetLastError());
return;
}
dispatch();
cleanup();
svfinish(0);
}
static int sendstatus(int curstate, int exitcode, int svexitcode, int check, int hint){
SERVICE_STATUS st;
st.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
st.dwCurrentState = curstate;
if(curstate == SERVICE_START_PENDING){
st.dwControlsAccepted = 0;
} else {
st.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
}
if(svexitcode == 0){
st.dwWin32ExitCode = exitcode;
} else {
st.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
}
st.dwServiceSpecificExitCode = svexitcode;
st.dwCheckPoint = check;
st.dwWaitHint = hint;
if(!SetServiceStatus(g_svstat, &st)){
g_sigterm = TRUE;
return FALSE;
}
return TRUE;
}
static void svfinish(int code){
if(g_svstat) sendstatus(SERVICE_STOPPED, code, 0, 0, 0);
}
static void svhandle(int code){
switch(code){
case SERVICE_CONTROL_STOP:
case SERVICE_CONTROL_SHUTDOWN:
sendstatus(SERVICE_STOP_PENDING, 0, 0, 1, 5000);
g_sigterm = TRUE;
break;
case SERVICE_CONTROL_INTERROGATE:
sendstatus(0, 0, 0, 0, 0);
break;
}
}
#endif
/* main routine */
int main(int argc, char **argv){
#if defined(MYWINSERV)
SERVICE_TABLE_ENTRY table[] = {
{ SERVNAME, (LPSERVICE_MAIN_FUNCTION)svmain }, { NULL, NULL }
};
est_proc_env_reset();
g_progname = argv[0];
g_sigterm = FALSE;
g_rootdir = argc >= 2 ? argv[1] : "casket";
if(!StartServiceCtrlDispatcher(table)) die("not called by service controll manager");
return 0;
#else
return realmain(argc, argv);
#endif
}
/* real main routine */
static int realmain(int argc, char **argv){
const char *tmp;
int rv;
if((tmp = getenv("ESTDBGFD")) != NULL) dpdbgfd = atoi(tmp);
est_proc_env_reset();
g_progname = argv[0];
g_sigterm = FALSE;
if(argc < 2) usage();
rv = 0;
if(!strcmp(argv[1], "init")){
rv = runinit(argc, argv);
} else if(!strcmp(argv[1], "start")){
rv = runstart(argc, argv);
} else if(!strcmp(argv[1], "stop")){
rv = runstop(argc, argv);
} else if(!strcmp(argv[1], "unittest")){
rv = rununittest(argc, argv);
} else if(!strcmp(argv[1], "crypt")){
rv = runcrypt(argc, argv);
} else {
usage();
}
return rv;
}
/* set signal handlers */
static void setsignals(void){
est_signal(1, sigtermhandler);
est_signal(2, sigtermhandler);
est_signal(3, sigtermhandler);
est_signal(13, SIG_IGN);
est_signal(14, SIG_IGN);
est_signal(15, sigtermhandler);
g_sigterm = FALSE;
g_sigrestart = FALSE;
g_sigsync = FALSE;
g_sigback = FALSE;
}
/* handler of termination signal */
static void sigtermhandler(int num){
g_sigterm = TRUE;
if(num == 1 && g_bgmode) g_sigrestart = TRUE;
}
/* print the usage and exit */
static void usage(void){
fprintf(stderr, "%s: the master of node servers\n", g_progname);
fprintf(stderr, "\n");
fprintf(stderr, "usage:\n");
fprintf(stderr, " %s init [-ex] rootdir\n", g_progname);
fprintf(stderr, " %s start [-bg] [-ro] [-st] rootdir\n", g_progname);
fprintf(stderr, " %s stop rootdir\n", g_progname);
fprintf(stderr, " %s unittest rootdir\n", g_progname);
fprintf(stderr, " %s crypt key [hash]\n", g_progname);
fprintf(stderr, "\n");
exit(1);
}
/* parse arguments of the init command */
static int runinit(int argc, char **argv){
char *rootdir;
int i, ex, rv;
rootdir = NULL;
ex = FALSE;
for(i = 2; i < argc; i++){
if(!rootdir && argv[i][0] == '-'){
if(!strcmp(argv[i], "-ex")){
ex = TRUE;
} else {
usage();
}
} else if(!rootdir){
rootdir = argv[i];
} else {
usage();
}
}
if(!rootdir) usage();
rv = procinit(rootdir, ex);
return rv;
}
/* parse arguments of the start command */
static int runstart(int argc, char **argv){
char *rootdir;
int i, rv;
rootdir = NULL;
for(i = 2; i < argc; i++){
if(!rootdir && argv[i][0] == '-'){
if(!strcmp(argv[i], "-bg")){
g_bgmode = TRUE;
} else if(!strcmp(argv[i], "-ro")){
g_romode = TRUE;
} else if(!strcmp(argv[i], "-st")){
g_stmode = TRUE;
} else if(!strcmp(argv[i], "--no-log-timestamp")){
log_timestamp = FALSE;
} else {
usage();
}
} else if(!rootdir){
rootdir = argv[i];
} else {
usage();
}
}
if(!rootdir) usage();
rv = procstart(rootdir);
return rv;
}
/* parse arguments of the stop command */
static int runstop(int argc, char **argv){
char *rootdir;
int i, rv;
rootdir = NULL;
for(i = 2; i < argc; i++){
if(!rootdir && argv[i][0] == '-'){
usage();
} else if(!rootdir){
rootdir = argv[i];
} else {
usage();
}
}
if(!rootdir) usage();
rv = procstop(rootdir);
return rv;
}
/* parse arguments of the unittest command */
static int rununittest(int argc, char **argv){
char *rootdir;
int i, rv;
rootdir = NULL;
for(i = 2; i < argc; i++){
if(!rootdir && argv[i][0] == '-'){
usage();
} else if(!rootdir){
rootdir = argv[i];
} else {
usage();
}
}
if(!rootdir) usage();
rv = procunittest(rootdir);
return rv;
}
/* parse arguments of the crypt command */
static int runcrypt(int argc, char **argv){
char *key, *hash;
int i, rv;
key = NULL;
hash = NULL;
for(i = 2; i < argc; i++){
if(!key && argv[i][0] == '-'){
usage();
} else if(!key){
key = argv[i];
} else if(!hash){
hash = argv[i];
} else {
usage();
}
}
if(!key) usage();
rv = proccrypt(key, hash);
return rv;
}
/* print formatted error string and exit */
static void die(const char *format, ...){
va_list ap;
char msgbuf[URIBUFSIZ];
va_start(ap, format);
vsprintf(msgbuf, format, ap);
if(log_open(g_rootdir, g_logfile ? g_logfile : LOGFILE, LL_INFO, FALSE)){
log_print(LL_ERROR, "startup failed: %s", msgbuf);
} else {
fprintf(stderr, "%s: %s\n", g_progname, msgbuf);
fflush(stderr);
}
va_end(ap);
exit(1);
}
/* initialize the global variables */
static void startup(void){
NODE *node;
ESTMTDB *db;
CBLIST *lines, *elems;
struct stat sbuf;
const char *rp, *name;
char path[URIBUFSIZ], numbuf[NUMBUFSIZ];
int i, ecode, pid, omode;
if(stat(g_rootdir, &sbuf) == -1)
die("the server root directory (%s) could not open", g_rootdir);
sprintf(path, "%s%c%s", g_rootdir, ESTPATHCHR, CONFFILE);
if(!(lines = cbreadlines(path))) die("the configuration file (%s) could not open", path);
cbglobalgc(lines, (void (*)(void *))cblistclose);
g_attrindexes = cblistopen();
cbglobalgc(g_attrindexes, (void (*)(void *))cblistclose);
g_trustednodes = cbmapopenex(MINIBNUM);
cbglobalgc(g_trustednodes, (void (*)(void *))cbmapclose);
g_uireplaces = cblistopen();
cbglobalgc(g_uireplaces, (void (*)(void *))cblistclose);
g_uiextattrs = cblistopen();
cbglobalgc(g_uiextattrs, (void (*)(void *))cblistclose);
for(i = 0; i < cblistnum(lines); i++){
rp = cblistval(lines, i, NULL);
if(cbstrfwimatch(rp, "bindaddr:")){
g_bindaddr = skiplabel(rp);
} else if(cbstrfwimatch(rp, "portnum:")){
g_portnum = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "publicurl:")){
g_publicurl = skiplabel(rp);
} else if(cbstrfwimatch(rp, "runmode:")){
g_runmode = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "authmode:")){
g_authmode = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "recvmax:")){
g_recvmax = atoi(skiplabel(rp)) * 1024;
} else if(cbstrfwimatch(rp, "maxconn:")){
g_maxconn = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "idleflush:")){
g_idleflush = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "idlesync:")){
g_idlesync = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "sessiontimeout:")){
g_sessiontimeout = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "searchtimeout:")){
g_searchtimeout = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "searchmax:")){
g_searchmax = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "searchdepth:")){
g_searchdepth = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "rateuri:")){
g_rateuri = atoi(skiplabel(rp)) > 0;
} else if(cbstrfwimatch(rp, "mergemethod:")){
g_mergemethod = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "proxyhost:")){
g_proxyhost = skiplabel(rp);
} else if(cbstrfwimatch(rp, "proxyport:")){
g_proxyport = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "logfile:")){
g_logfile = skiplabel(rp);
} else if(cbstrfwimatch(rp, "loglevel:")){
g_loglevel = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "backupcmd:")){
g_backupcmd = skiplabel(rp);
} else if(cbstrfwimatch(rp, "scalepred:")){
g_scalepred = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "scoreexpr:")){
g_scoreexpr = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "attrindex:")){
cblistpush(g_attrindexes, skiplabel(rp), -1);
} else if(cbstrfwimatch(rp, "docroot:")){
g_docroot = skiplabel(rp);
} else if(cbstrfwimatch(rp, "indexfile:")){
g_indexfile = skiplabel(rp);
} else if(cbstrfwimatch(rp, "trustednode:")){
cbmapput(g_trustednodes, skiplabel(rp), -1, "", 0, TRUE);
} else if(cbstrfwimatch(rp, "denyuntrusted:")){
g_denyuntrusted = atoi(skiplabel(rp)) > 0;
} else if(cbstrfwimatch(rp, "cachesize:")){
g_cachesize = strtod(skiplabel(rp), NULL) * 1024 * 1024;
} else if(cbstrfwimatch(rp, "cacheanum:")){
g_cacheanum = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "cachetnum:")){
g_cachetnum = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "cachernum:")){
g_cachernum = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "specialcache:")){
g_specialcache = skiplabel(rp);
} else if(cbstrfwimatch(rp, "helpershift:")){
g_helpershift = strtod(skiplabel(rp), NULL);
} else if(cbstrfwimatch(rp, "wildmax:")){
g_wildmax = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "limittextsize:")){
g_limittextsize = atoi(skiplabel(rp)) * 1024;
} else if(cbstrfwimatch(rp, "snipwwidth:")){
g_snipwwidth = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "sniphwidth:")){
g_sniphwidth = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "snipawidth:")){
g_snipawidth = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "scancheck:")){
g_scancheck = atoi(skiplabel(rp)) > 0;
} else if(cbstrfwimatch(rp, "smlrvnum:")){
g_smlrvnum = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "extdelay:")){
g_extdelay = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "adminemail:")){
g_adminemail = skiplabel(rp);
} else if(cbstrfwimatch(rp, "uireplace:")){
cblistpush(g_uireplaces, skiplabel(rp), -1);
} else if(cbstrfwimatch(rp, "uiextattr:")){
cblistpush(g_uiextattrs, skiplabel(rp), -1);
} else if(cbstrfwimatch(rp, "uiphraseform:")){
g_uiphraseform = atoi(skiplabel(rp));
} else if(cbstrfwimatch(rp, "uismlrtune:")){
g_uismlrtune = skiplabel(rp);
}
}
if(!g_bindaddr) die("bindaddr is undefined");
if(g_portnum < 1) die("portnum is undefined");
if(!g_publicurl) die("publicurl is undefined");
if(g_runmode < RM_NORMAL || g_runmode > RM_RDONLY) die("runmode is undefined");
if(g_authmode < AM_NONE || g_authmode > AM_ALL) die("authmode is undefined");
if(g_recvmax < 1) die("recvmax is undefined");
if(g_maxconn < 1) die("maxconn is undefined");
if(g_idleflush < 1) die("idleflush is undefined");
if(g_idlesync < 1) die("idlesync is undefined");
if(g_sessiontimeout < 1) die("sessiontimeout is undefined");
if(g_searchtimeout < 1) die("searchtimeout is undefined");
if(g_searchmax < 1) die("searchmax is undefined");
if(g_searchdepth < 0) die("searchdepth is undefined");
if(g_mergemethod < MM_SCORE || g_mergemethod > MM_RANK) die("mergemethod is undefined");
if(!g_proxyhost) die("proxyhost is undefined");
if(g_proxyhost[0] != '\0' && g_proxyport < 1) die("proxyport is undefined");
if(!g_logfile) die("logfile is undefined");
if(g_loglevel < LL_DEBUG || g_loglevel > LL_NONE) die("loglevel is undefined");
if(!g_docroot) die("docroot is undefined");
if(!g_indexfile) die("indexfile is undefined");
if(!g_backupcmd) die("backupcmd is undefined");
if(g_scalepred < SP_SMALL || g_scalepred > SP_HUGE) die("scalepred is undefined");
if(g_scoreexpr < SE_VOID || g_scoreexpr > SE_ASIS) die("scoreexpr is undefined");
if(g_cachesize < 0.0) die("cachesize is undefined");
if(g_cacheanum < 0) die("cacheanum is undefined");
if(g_cachetnum < 0) die("cachetnum is undefined");
if(g_cachernum < 0) die("cachernum is undefined");
if(!g_specialcache) die("indexfile is undefined");
if(g_helpershift < 0) die("helpershift is undefined");
if(g_wildmax < 0) die("wildmax is undefined");
if(g_limittextsize < 1) die("limittextsize is undefined");
if(g_snipwwidth < 0) die("snipwwidth is undefined");
if(g_sniphwidth < 0) die("sniphwidth is undefined");
if(g_snipawidth < 0) die("snipawidth is undefined");
if(g_smlrvnum < 0) die("smlrvnum is undefined");
if(!g_adminemail) die("adminemail is undefined");
if(g_uiphraseform < 1) die("uiphraseform is undefined");
if(!g_uismlrtune) die("uismlrtune is undefined");
if(g_romode) g_runmode = RM_RDONLY;
if((pid = lockerpid(g_rootdir)) > 0)
die("another process (pid:%d) has opened the database", pid);
if(!log_open(g_rootdir, g_logfile, LL_CHECK, FALSE))
die("the log file (%s) could not open", g_logfile);
sprintf(path, "%s%c%s", g_rootdir, ESTPATHCHR, METAFILE);
if(!(g_metadb = dpopen(path, DP_OREADER, -1))){
if(dpecode == DP_ELOCK){
die("other process (pid:%d) has opened the database", lockerpid(g_rootdir));
} else {
die("the meta database file (%s) could not open", path);
}
}
sprintf(path, "%s%c%s", g_rootdir, ESTPATHCHR, NODEDIR);
if(!(elems = cbdirlist(path))){
dpclose(g_metadb);
die("the node directory (%s) could not open", path);
}
for(i = 0; i < cblistnum(elems); i++){
name = cblistval(elems, i, NULL);
if(!strcmp(name, ESTCDIRSTR) || !strcmp(name, ESTPDIRSTR)) continue;
sprintf(path, "%s%c%s%c%s", g_rootdir, ESTPATHCHR, NODEDIR, ESTPATHCHR, name);
if((db = est_mtdb_open(path, ESTDBREADER, &ecode)) != NULL){
if(!est_mtdb_close(db, &ecode)){
cblistclose(elems);
dpclose(g_metadb);
die("the database (%s) could not close", path);
}
} else {
cblistclose(elems);
dpclose(g_metadb);
die("the database (%s) could not open", path);
}
}
cblistclose(elems);
dpclose(g_metadb);
if(g_bgmode && !be_daemon(g_rootdir)) die("the process could not be a daemon");
sprintf(g_hostname, "%s", est_get_host_name());
sprintf(path, "%s%c%s", g_rootdir, ESTPATHCHR, METAFILE);
omode = (g_runmode == RM_RDONLY ? DP_OREADER : DP_OWRITER) | DP_OLCKNB;
if(!(g_metadb = dpopen(path, omode, -1))){
if(dpecode == DP_ELOCK){
die("other process (pid:%d) has opened the database", lockerpid(g_rootdir));
} else {
die("the meta database file (%s) could not open", path);
}
}
pid = (int)getpid();
sprintf(path, "%s%c%s", g_rootdir, ESTPATHCHR, PIDFILE);
sprintf(numbuf, "%d\n", pid);
cbwritefile(path, numbuf, -1);
if(!log_open(g_rootdir, g_logfile, g_loglevel, FALSE)){
unlink(path);
dpclose(g_metadb);
die("starting logging failed");
}
log_print(LL_INFO, "starting the master process (pid:%d)", pid);
g_umgr = umgr_new(g_rootdir);
g_nmgr = nmgr_new(g_rootdir);
if(!umgr_load(g_umgr) || !nmgr_load(g_nmgr, g_runmode != RM_RDONLY)){
unlink(path);
nmgr_delete(g_nmgr);
umgr_delete(g_umgr);
dpclose(g_metadb);
log_print(LL_ERROR, "loading users and nodes failed");
die("loading users and nodes failed");
}
for(i = 0; i < cblistnum(g_attrindexes); i++){
name = cblistval(g_attrindexes, i, NULL);
if(!(rp = strstr(name, "{{!}}"))) continue;
memcpy(path, name, rp - name);
path[rp-name] = '\0';
nmgr_add_aidx(g_nmgr, path, rp + 5);
}
g_runlock = rwlock_new();
g_mgrlock = rwlock_new();
if((g_svsock = est_get_server_sock(g_bindaddr, g_portnum)) == -1){
unlink(path);
rwlock_delete(g_mgrlock);
rwlock_delete(g_runlock);
nmgr_delete(g_nmgr);
umgr_delete(g_umgr);
dpclose(g_metadb);
log_print(LL_ERROR, "initializing network failed");
die("initializing network failed");
}
g_accesscount = 0;
g_startdate = time(NULL);
if(g_docroot[0] != '\0'){
if(stat(g_docroot, &sbuf) == 0){
log_print(LL_INFO, "letting the directory (%s) be public", g_docroot);
} else {
log_print(LL_WARN, "missing the directory (%s)", g_docroot);
}
}
sprintf(path, "%s%c%s", g_rootdir, ESTPATHCHR, DFDBFILE);
g_dfdb = dpopen(path, DP_OREADER, -1);
g_bordstr = est_border_str();
elems = nmgr_names(g_nmgr);
for(i = 0; i < cblistnum(elems); i++){
if(!(name = cblistval(elems, i, NULL)) || !(node = nmgr_get(g_nmgr, name))) continue;
est_mtdb_set_cache_size(node->db, g_cachesize, g_cacheanum, g_cachetnum, g_cachernum);
if(g_specialcache[0] != '\0')
est_mtdb_set_special_cache(node->db, g_specialcache, SPCACHEMNUM);
est_mtdb_set_wildmax(node->db, g_wildmax);
if(g_dfdb) est_mtdb_set_dfdb(node->db, g_dfdb);
}
cblistclose(elems);
}
/* skip the label of a line */
static const char *skiplabel(const char *str){
if(!(str = strchr(str, ':'))) return "";
str++;
while(*str != '\0' && (*str == ' ' || *str == '\t')){
str++;
}
return str;
}
/* clean up resources */
static void cleanup(void){
char path[URIBUFSIZ];
if(g_svsock != -1) est_sock_down(g_svsock);
rwlock_delete(g_mgrlock);
rwlock_delete(g_runlock);
nmgr_delete(g_nmgr);
umgr_delete(g_umgr);
sprintf(path, "%s%c%s", g_rootdir, ESTPATHCHR, STOPFILE);
unlink(path);
sprintf(path, "%s%c%s", g_rootdir, ESTPATHCHR, PIDFILE);
unlink(path);
dpclose(g_metadb);
if(g_dfdb) dpclose(g_dfdb);
log_print(LL_INFO, "the master process finished");
}
/* perform the init command */
static int procinit(const char *rootdir, int ex){
UMGR *umgr;
NMGR *nmgr;
NODE *node;
ESTDOC *doc;
char *tmp;
int err;
setsignals();
if(!master_init(rootdir)){
log_print(LL_ERROR, "initializing the root directory failed");
return 1;
}
log_open(rootdir, LOGFILE, LL_INFO, FALSE);
log_print(LL_INFO, "the root directory created");
umgr = umgr_new(rootdir);
tmp = est_make_crypt("admin");
umgr_put(umgr, "admin", tmp, "s", "Carolus Magnus", "Administrator");
free(tmp);
if(ex){
tmp = est_make_crypt("john");
umgr_put(umgr, "john", tmp, "", "John Doe", "Normal User");
free(tmp);
tmp = est_make_crypt("dick");
umgr_put(umgr, "dick", tmp, "", "Richard Roe", "Normal User");
free(tmp);
tmp = est_make_crypt("lupin");
umgr_put(umgr, "lupin", tmp, "b", "Arsene Lupin", "Banned User");
free(tmp);
}
err = FALSE;
if(!umgr_delete(umgr)) err = TRUE;
nmgr = nmgr_new(rootdir);
if(ex){
nmgr_put(nmgr, "sample1", TRUE, 0);
if((node = nmgr_get(nmgr, "sample1")) != NULL){
free(node->label);
node->label = cbmemdup("Sample Node One", -1);
cbmapput(node->admins, "john", -1, "", 0, TRUE);
cbmapput(node->users, "john", -1, "", 0, TRUE);
cbmapput(node->users, "dick", -1, "", 0, TRUE);
cbmapput(node->users, "lupin", -1, "", 0, TRUE);
node_set_link(node, "http://localhost:1978/node/sample2",
"Sample-Node-Two", 4000);
doc = est_doc_new();
est_doc_add_attr(doc, ESTDATTRURI, "http://localhost/foo.html");
est_doc_add_text(doc, "You may my glories and my state dispose,");
est_doc_add_text(doc, "But not my griefs; still am I king of those.");
est_doc_add_text(doc, "(Give it up, Yo! Give it up, Yo!)");
est_mtdb_put_doc(node->db, doc, 0);
est_doc_delete(doc);
doc = est_doc_new();
est_doc_add_attr(doc, ESTDATTRURI, "http://localhost/bar.html");
est_doc_add_text(doc, "The faster I go, the behinder I get.");
est_doc_add_text(doc, "(Give it up, Yo! Give it up, Yo!)");
est_mtdb_put_doc(node->db, doc, 0);
est_doc_delete(doc);
} else {
err = TRUE;
}
nmgr_put(nmgr, "sample2", TRUE, 0);
if((node = nmgr_get(nmgr, "sample2")) != NULL){
free(node->label);
node->label = cbmemdup("Sample Node Two", -1);
cbmapput(node->users, "john", -1, "", 0, TRUE);
node_set_link(node, "http://localhost:1978/node/sample1",
"Sample-Node-One", 8000);
doc = est_doc_new();
est_doc_add_attr(doc, ESTDATTRURI, "http://localhost/foo.html");
est_doc_add_text(doc, "He that is giddy thinks the world turns round.");
est_doc_add_text(doc, "(Give it up, Yo! Give it up, Yo!)");
est_mtdb_put_doc(node->db, doc, 0);
est_doc_delete(doc);
} else {
err = TRUE;
}
}
if(!nmgr_delete(nmgr)) err = TRUE;
return err ? 1 : 0;
}
/* perform the start command */
static int procstart(const char *rootdir){
char *path;
path = est_realpath(rootdir);
cbglobalgc(path, free);
g_rootdir = path;
if(!est_init_net_env()) die("could not initialize network environment");
atexit(est_free_net_env);
do {
setsignals();
startup();
dispatch();
cleanup();
} while(g_sigrestart);
return 0;
}
/* perform the stop command */
static int procstop(const char *rootdir){
struct stat sbuf;
char path[URIBUFSIZ], *buf;
int pid;
sprintf(path, "%s%c%s", rootdir, ESTPATHCHR, PIDFILE);
if(!(buf = cbreadfile(path, NULL))) die("not running");
pid = atoi(buf);
free(buf);
if(pid < 1) die("not running");
if(est_kill(pid, 15)){
do {
est_usleep(1000 * 500);
if(!est_kill(pid, 13) && errno == ESRCH) break;