]> git.stg.codes - stg.git/blob - projects/stargazer/main.cpp
Fix types
[stg.git] / projects / stargazer / main.cpp
1 /*
2  *    This program is free software; you can redistribute it and/or modify
3  *    it under the terms of the GNU General Public License as published by
4  *    the Free Software Foundation; either version 2 of the License, or
5  *    (at your option) any later version.
6  *
7  *    This program is distributed in the hope that it will be useful,
8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  *    GNU General Public License for more details.
11  *
12  *    You should have received a copy of the GNU General Public License
13  *    along with this program; if not, write to the Free Software
14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
15  */
16
17 /*
18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19  */
20
21  /*
22  $Revision: 1.124 $
23  $Date: 2010/10/04 20:19:12 $
24  $Author: faust $
25  */
26
27 //#include <stdio.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <arpa/inet.h>
32 #include <unistd.h>
33 #include <sys/ipc.h>
34 #include <sys/msg.h>
35 #include <sys/stat.h>
36 #include <sys/wait.h>
37 #include <dlfcn.h>
38 #include <fcntl.h>
39
40 #include <csignal>
41 #include <cerrno>
42 #include <fstream>
43 #include <vector>
44 #include <set>
45 #include <list>
46
47 #include "settings.h"
48 #include "user.h"
49 #include "users_impl.h"
50 #include "admins_impl.h"
51 #include "tariffs_impl.h"
52 #include "common.h"
53 #include "traffcounter.h"
54 #include "plugin.h"
55 #include "stg_logger.h"
56 #include "stg_timer.h"
57 #include "plugin_runner.h"
58 #include "script_executer.h"
59 #include "conffiles.h"
60 #include "version.h"
61 #include "store_loader.h"
62 #include "pidfile.h"
63 #include "eventloop.h"
64
65 using namespace std;
66 uint32_t        eip;
67
68 #ifdef DEBUG
69     #define MAIN_DEBUG (1)
70     #define NO_DAEMON  (1)
71 #endif
72
73 #define START_FILE "/._ST_ART_ED_"
74
75 static bool needRulesReloading = false;
76 static bool childExited = false;
77 //static pid_t executerPid;
78 set<pid_t> executersPid;
79 static pid_t stgChildPid;
80
81 #include "pinger.h"
82
83 //-----------------------------------------------------------------------------
84 bool StartModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
85 {
86 return lhs.GetStartPosition() < rhs.GetStartPosition();
87 }
88 //-----------------------------------------------------------------------------
89 bool StopModCmp(const PLUGIN_RUNNER & lhs, const PLUGIN_RUNNER & rhs)
90 {
91 return lhs.GetStopPosition() > rhs.GetStopPosition();
92 }
93 //-----------------------------------------------------------------------------
94 class STG_STOPPER
95 {
96 public:
97     STG_STOPPER() { nonstop = true; }
98     bool    GetStatus() const { return nonstop; };
99     #ifdef NO_DAEMON
100     void    Stop(const char * __file__, int __line__)
101     #else
102     void    Stop(const char *, int)
103     #endif
104         {
105         #ifdef NO_DAEMON
106         printfd(__FILE__, "Stg stopped at %s:%d\n", __file__, __line__);
107         #endif
108         nonstop = false;
109         }
110 private:
111     bool nonstop;
112 };
113 //-----------------------------------------------------------------------------
114 STG_STOPPER nonstop;
115 //-----------------------------------------------------------------------------
116 static void StartTimer()
117 {
118 STG_LOGGER & WriteServLog = GetStgLogger();
119
120 if (RunStgTimer())
121     {
122     WriteServLog("Cannot start timer. Fatal.");
123     //printfd(__FILE__, "Cannot start timer. Fatal.\n");
124     exit(1);
125     }
126 else
127     {
128     WriteServLog("Timer thread started successfully.");
129     //printfd(__FILE__, "Timer thread started successfully.\n");
130     }
131 }
132 //-----------------------------------------------------------------------------
133 void CatchUSR1(int)
134 {
135
136 }
137 //-----------------------------------------------------------------------------
138 void CatchTERM(int sig)
139 {
140 /*
141  *Function Name:CatchINT
142  *Parameters: sig_num - ÎÏÍÅÒ ÓÉÇÎÁÌÁ
143  *Description: ïÂÒÁÂÏÔÞÉË ÓÉÇÎÁÌÁ INT
144  *Returns: îÉÞÅÇÏ
145  */
146 STG_LOGGER & WriteServLog = GetStgLogger();
147 WriteServLog("Shutting down... %d", sig);
148
149 //nonstop = false;
150 nonstop.Stop(__FILE__, __LINE__);
151
152 struct sigaction newsa, oldsa;
153 sigset_t sigmask;
154
155 sigemptyset(&sigmask);
156 sigaddset(&sigmask, SIGTERM);
157 newsa.sa_handler = SIG_IGN;
158 newsa.sa_mask = sigmask;
159 newsa.sa_flags = 0;
160 sigaction(SIGTERM, &newsa, &oldsa);
161
162 sigemptyset(&sigmask);
163 sigaddset(&sigmask, SIGINT);
164 newsa.sa_handler = SIG_IGN;
165 newsa.sa_mask = sigmask;
166 newsa.sa_flags = 0;
167 sigaction(SIGINT, &newsa, &oldsa);
168 }
169 //-----------------------------------------------------------------------------
170 void CatchPIPE(int)
171 {
172 STG_LOGGER & WriteServLog = GetStgLogger();
173 WriteServLog("Broken pipe!");
174 }
175 //-----------------------------------------------------------------------------
176 void CatchHUP(int)
177 {
178 needRulesReloading = true;
179 }
180 //-----------------------------------------------------------------------------
181 void CatchCHLD(int)
182 {
183 int status;
184 pid_t childPid;
185 childPid = waitpid(-1, &status, WNOHANG);
186
187 set<pid_t>::iterator pid;
188 pid = executersPid.find(childPid);
189 if (pid != executersPid.end())
190     {
191     executersPid.erase(pid);
192     if (executersPid.empty() && nonstop.GetStatus())
193         {
194         nonstop.Stop(__FILE__, __LINE__);
195         }
196     }
197 if (childPid == stgChildPid)
198     {
199     childExited = true;
200     }
201 }
202 /*//-----------------------------------------------------------------------------
203 void CatchSEGV(int, siginfo_t *, void *)
204 {
205 char fileName[50];
206 sprintf(fileName, "/tmp/stg_segv.%d", getpid());
207 FILE * f = fopen(fileName, "wt");
208 if (f)
209     {
210     fprintf(f, "\nSignal info:\n~~~~~~~~~~~~\n");
211     fprintf(f, "numb:\t %d (%d)\n", sinfo->si_signo, sig);
212     fprintf(f, "errn:\t %d\n", sinfo->si_errno);
213     fprintf(f, "code:\t %d ", sinfo->si_code);
214
215     switch (sinfo->si_code)
216         {
217         case SEGV_MAPERR:
218             fprintf(f, "(SEGV_MAPERR - address not mapped to object)\n");
219             break;
220
221         case SEGV_ACCERR:
222             fprintf(f, "(SEGV_ACCERR - invalid permissions for mapped object)\n");
223             break;
224
225         default:
226             fprintf(f, "???\n");
227         }
228
229     fprintf(f, "addr:\t 0x%.8X\n",
230         (unsigned int)sinfo->si_addr);
231
232     Dl_info dlinfo;
233     //asm("movl %eip, eip");
234     if (dladdr((void*)CatchCHLD, &dlinfo))
235         {
236         fprintf(f, "SEGV point: %s %s\n", dlinfo.dli_fname, dlinfo.dli_sname);
237         }
238     else
239         {
240         fprintf(f, "Cannot find SEGV point\n");
241         }
242
243     fclose(f);
244     }
245
246 struct sigaction segv_action, segv_action_old;
247
248 segv_action.sa_handler = SIG_DFL;
249 segv_action.sa_sigaction = NULL;
250 segv_action.sa_flags = SA_SIGINFO;
251 segv_action.sa_restorer = NULL;
252
253 sigaction(SIGSEGV, &segv_action, &segv_action_old);
254 }*/
255 //-----------------------------------------------------------------------------
256 static void SetSignalHandlers()
257 {
258 struct sigaction newsa, oldsa;
259 sigset_t sigmask;
260 ///////
261 sigemptyset(&sigmask);
262 sigaddset(&sigmask, SIGTERM);
263 newsa.sa_handler = CatchTERM;
264 newsa.sa_mask = sigmask;
265 newsa.sa_flags = 0;
266 sigaction(SIGTERM, &newsa, &oldsa);
267 ///////
268 sigemptyset(&sigmask);
269 sigaddset(&sigmask, SIGUSR1);
270 newsa.sa_handler = CatchUSR1;
271 newsa.sa_mask = sigmask;
272 newsa.sa_flags = 0;
273 sigaction(SIGUSR1, &newsa, &oldsa);
274 ///////
275 sigemptyset(&sigmask);
276 sigaddset(&sigmask, SIGINT);
277 newsa.sa_handler = CatchTERM;
278 newsa.sa_mask = sigmask;
279 newsa.sa_flags = 0;
280 sigaction(SIGINT, &newsa, &oldsa);
281 //////
282 sigemptyset(&sigmask);
283 sigaddset(&sigmask, SIGPIPE);
284 newsa.sa_handler = CatchPIPE;
285 newsa.sa_mask = sigmask;
286 newsa.sa_flags = 0;
287 sigaction(SIGPIPE, &newsa, &oldsa);
288 //////
289 sigemptyset(&sigmask);
290 sigaddset(&sigmask, SIGHUP);
291 newsa.sa_handler = CatchHUP;
292 newsa.sa_mask = sigmask;
293 newsa.sa_flags = 0;
294 sigaction(SIGHUP, &newsa, &oldsa);
295 //////
296 sigemptyset(&sigmask);
297 sigaddset(&sigmask, SIGCHLD);
298 newsa.sa_handler = CatchCHLD;
299 newsa.sa_mask = sigmask;
300 newsa.sa_flags = 0;
301 sigaction(SIGCHLD, &newsa, &oldsa);
302
303 /*newsa.sa_handler = NULL;
304 newsa.sa_sigaction = CatchSEGV;
305 newsa.sa_flags = SA_SIGINFO;
306 newsa.sa_restorer = NULL;
307 sigaction(SIGSEGV, &newsa, &oldsa);*/
308
309 return;
310 }
311 //-----------------------------------------------------------------------------
312 int StartScriptExecuter(char * procName, int msgKey, int * msgID, SETTINGS * settings)
313 {
314 STG_LOGGER & WriteServLog = GetStgLogger();
315
316 if (*msgID == -11)   // If msgID == -11 - first call. Create queue
317     {
318     for (int i = 0; i < 2; i++)
319         {
320         //WriteServLog("Creating queue with key=%d ...", msgKey);
321         *msgID = msgget(msgKey, IPC_CREAT | IPC_EXCL | 0600);
322
323         if (*msgID == -1)
324             {
325             *msgID = msgget(msgKey, 0);
326             if (*msgID == -1)
327                 {
328                 WriteServLog("Message queue not created.");
329                 return -1;
330                 }
331             else
332                 {
333                 msgctl(*msgID, IPC_RMID, NULL);
334                 //printfd(__FILE__, "Queue removed!");
335                 }
336             }
337         else
338             {
339             WriteServLog("Message queue created successfully. msgKey=%d msgID=%d", msgKey, *msgID);
340             break;
341             }
342         }
343     }
344
345 pid_t executerPid = fork();
346
347 switch (executerPid)
348     {
349     case -1:    // ìÁÖÁ
350         WriteServLog("Fork error!");
351         return -1;
352
353     case 0:     // ðÏÔÏÍÏË
354         //close(0);
355         //close(1);
356         //close(2);
357         //setsid();
358         delete settings;
359         Executer(msgKey, *msgID, executerPid, procName);
360         return 1;
361
362     default:    // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
363         if (executersPid.empty()) {
364             Executer(msgKey, *msgID, executerPid, NULL);
365         }
366         executersPid.insert(executerPid);
367     }
368 return 0;
369 }
370 //-----------------------------------------------------------------------------
371 #ifndef NO_DAEMON
372 int ForkAndWait(const string & confDir)
373 #else
374 int ForkAndWait(const string &)
375 #endif
376 {
377 #ifndef NO_DAEMON
378 stgChildPid = fork();
379 string startFile = confDir + START_FILE;
380 unlink(startFile.c_str());
381
382 switch (stgChildPid)
383     {
384     case -1:    // ìÁÖÁ
385         return -1;
386         break;
387
388     case 0:     // ðÏÔÏÍÏË
389         //close(0);
390         close(1);
391         close(2);
392         setsid();
393         break;
394
395     default:    // ïÓÎÏ×ÎÏÊ ÐÒÏÃÅÓÓ
396         for (int i = 0; i < 120 * 5; i++)
397             {
398             if (access(startFile.c_str(), F_OK) == 0)
399                 {
400                 //printf("Fork successfull. Exit.\n");
401                 unlink(startFile.c_str());
402                 exit(0);
403                 }
404
405             if (childExited)
406                 {
407                 unlink(startFile.c_str());
408                 exit(1);
409                 }
410             usleep(200000);
411             }
412         unlink(startFile.c_str());
413         exit(1);
414         break;
415     }
416 #endif
417 return 0;
418 }
419 //-----------------------------------------------------------------------------
420 void KillExecuters()
421 {
422 set<pid_t>::iterator pid;
423 pid = executersPid.begin();
424 while (pid != executersPid.end())
425     {
426     printfd(__FILE__, "KillExecuters pid=%d\n", *pid);
427     kill(*pid, SIGUSR1);
428     ++pid;
429     }
430 }
431 //-----------------------------------------------------------------------------
432 int main(int argc, char * argv[])
433 {
434
435 /*
436   Initialization order:
437   - Logger
438   - Stg timer
439   - Settings
440   - Plugins
441   - Plugins settings
442   - Read Admins
443   - Read Tariffs
444   - Read Users
445   - Start Users
446   - Start Traffcounter
447   - Start Plugins
448   - Start pinger
449   - Set signal nandlers
450   - Fork and exit
451  * */
452
453 SETTINGS * settings = NULL;
454 STORE * dataStore = NULL;
455 TARIFFS_IMPL * tariffs = NULL;
456 ADMINS_IMPL * admins = NULL;
457 USERS_IMPL * users = NULL;
458 TRAFFCOUNTER * traffCnt = NULL;
459 int msgID = -11;
460
461     {
462     STG_LOGGER & WriteServLog = GetStgLogger();
463     WriteServLog.SetLogFileName("/var/log/stargazer.log");
464     }
465
466 vector<MODULE_SETTINGS> modSettings;
467 list<PLUGIN_RUNNER> modules;
468
469 list<PLUGIN_RUNNER>::iterator modIter;
470
471 if (getuid())
472     {
473     printf("You must be root. Exit.\n");
474     exit(1);
475     }
476
477 if (argc == 2)
478     settings = new SETTINGS(argv[1]);
479 else
480     settings = new SETTINGS();
481
482 if (settings->ReadSettings())
483     {
484     //printfd(__FILE__, "ReadSettings error.\n");
485     STG_LOGGER & WriteServLog = GetStgLogger();
486
487     if (settings->GetLogFileName() != "")
488         WriteServLog.SetLogFileName(settings->GetLogFileName());
489
490     WriteServLog("ReadSettings error. %s", settings->GetStrError().c_str());
491     exit(1);
492     }
493
494 #ifndef NO_DAEMON
495 string startFile(settings->GetConfDir() + START_FILE);
496 #endif
497
498 if (ForkAndWait(settings->GetConfDir()) < 0)
499     {
500     STG_LOGGER & WriteServLog = GetStgLogger();
501     WriteServLog("Fork error!");
502     exit(1);
503     }
504
505 STG_LOGGER & WriteServLog = GetStgLogger();
506 WriteServLog.SetLogFileName(settings->GetLogFileName());
507 WriteServLog("Stg v. %s", SERVER_VERSION);
508
509 for (size_t i = 0; i < settings->GetExecutersNum(); i++)
510     {
511     int ret = StartScriptExecuter(argv[0], settings->GetExecMsgKey(), &msgID, settings);
512     if (ret < 0)
513         {
514         STG_LOGGER & WriteServLog = GetStgLogger();
515         WriteServLog("Start Script Executer error!");
516         return 1;
517         }
518     if (ret == 1)
519         {
520         // Stopping child
521         return 0;
522         }
523     }
524
525 PIDFile pidFile(settings->GetPIDFileName());
526
527 StartTimer();
528 WaitTimer();
529 if (!IsStgTimerRunning())
530     {
531     printfd(__FILE__, "Timer thread not started in 1 sec!\n");
532     WriteServLog("Timer thread not started in 1 sec!");
533     }
534
535 EVENT_LOOP & loop(EVENT_LOOP_SINGLETON::GetInstance());
536
537 STORE_LOADER storeLoader(*settings);
538 if (storeLoader.Load())
539     {
540     WriteServLog("Storage plugin: '%s'", storeLoader.GetStrError().c_str());
541     goto exitLblNotStarted;
542     }
543
544 if (loop.Start())
545     {
546     WriteServLog("Event loop not started.");
547     goto exitLblNotStarted;
548     }
549
550 dataStore = storeLoader.GetStore();
551 WriteServLog("Storage plugin: %s. Loading successfull.", dataStore->GetVersion().c_str());
552
553 tariffs = new TARIFFS_IMPL(dataStore);
554 admins = new ADMINS_IMPL(dataStore);
555 users = new USERS_IMPL(settings, dataStore, tariffs, admins->GetSysAdmin());
556 traffCnt = new TRAFFCOUNTER(users, tariffs, settings->GetRulesFileName());
557 traffCnt->SetMonitorDir(settings->GetMonitorDir());
558
559 modSettings = settings->GetModulesSettings();
560
561 for (unsigned i = 0; i < modSettings.size(); i++)
562     {
563     string modulePath = settings->GetModulesPath();
564     modulePath += "/mod_";
565     modulePath += modSettings[i].moduleName;
566     modulePath += ".so";
567     printfd(__FILE__, "Module: %s\n", modulePath.c_str());
568     modules.push_back(
569         PLUGIN_RUNNER(modulePath,
570                       modSettings[i],
571                       admins,
572                       tariffs,
573                       users,
574                       traffCnt,
575                       dataStore,
576                       settings)
577         );
578     }
579
580 modIter = modules.begin();
581
582 while (modIter != modules.end())
583     {
584     //Loading modules
585     if (modIter->Load())
586         {
587         WriteServLog("Error: %s",
588                      modIter->GetStrError().c_str());
589         goto exitLblNotStarted;
590         }
591     ++modIter;
592     }
593
594 //Start section
595 if (users->Start())
596     {
597     goto exitLblNotStarted;
598     }
599 WriteServLog("Users started successfully.");
600
601 if (traffCnt->Start())
602     {
603     goto exitLblNotStarted;
604     }
605 WriteServLog("Traffcounter started successfully.");
606
607 //Sort by start order
608 modules.sort(StartModCmp);
609 modIter = modules.begin();
610
611 while (modIter != modules.end())
612     {
613     if (modIter->Start())
614         {
615         WriteServLog("Error: %s",
616                      modIter->GetStrError().c_str());
617         //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
618         goto exitLbl;
619         }
620     WriteServLog("Module: \'%s\'. Start successfull. %d", modIter->GetPlugin()->GetVersion().c_str(),
621         modIter->GetPlugin()->GetStartPosition());
622     ++modIter;
623     }
624 SetSignalHandlers();
625
626 srandom(stgTime);
627
628 /*
629  * Note that an implementation in which nice returns the new nice value
630  * can legitimately return -1.   To  reliably  detect  an  error,  set
631  * errno to 0 before the call, and check its value when nice returns -1.
632  *
633  *
634  * (c) man 2 nice
635  */
636 errno = 0;
637 if (nice(-19) && errno) {
638     printfd(__FILE__, "nice failed: '%s'\n", strerror(errno));
639     WriteServLog("nice failed: '%s'", strerror(errno));
640 }
641
642 WriteServLog("Stg started successfully.");
643 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
644
645 #ifndef NO_DAEMON
646 creat(startFile.c_str(), S_IRUSR);
647 #endif
648
649 while (nonstop.GetStatus())
650     {
651     if (needRulesReloading)
652         {
653         needRulesReloading = false;
654         traffCnt->Reload();
655
656         modIter = modules.begin();
657         for (; modIter != modules.end(); ++modIter)
658             {
659             if (modIter->Reload())
660                 {
661                 WriteServLog("Error reloading %s ('%s')", modIter->GetPlugin()->GetVersion().c_str(),
662                                                           modIter->GetStrError().c_str());
663                 printfd(__FILE__, "Error reloading %s ('%s')\n", modIter->GetPlugin()->GetVersion().c_str(),
664                                                                  modIter->GetStrError().c_str());
665                 }
666             }
667         }
668     stgUsleep(100000);
669     }
670
671 exitLbl:
672
673 WriteServLog("+++++++++++++++++++++++++++++++++++++++++++++");
674
675 //Sort by start order
676 modules.sort(StopModCmp);
677 modIter = modules.begin();
678 while (modIter != modules.end())
679     {
680     std::string name = modIter->GetFileName();
681     printfd(__FILE__, "Stopping module '%s'\n", name.c_str());
682     if (modIter->Stop())
683         {
684         WriteServLog("Module \'%s\': Error: %s",
685                      modIter->GetPlugin()->GetVersion().c_str(),
686                      modIter->GetStrError().c_str());
687         printfd(__FILE__, "Failed to stop module '%s'\n", name.c_str());
688         //printfd(__FILE__, "Error: %s\n", capRunner.GetStrError().c_str());
689         //goto exitLbl;
690         }
691     WriteServLog("Module: \'%s\'. Stop successfull.", modIter->GetPlugin()->GetVersion().c_str());
692     ++modIter;
693     }
694
695 if (loop.Stop())
696     {
697     WriteServLog("Event loop not stopped.");
698     }
699
700 exitLblNotStarted:
701
702 modIter = modules.begin();
703 while (modIter != modules.end())
704     {
705     std::string name = modIter->GetFileName();
706     printfd(__FILE__, "Unloading module '%s'\n", name.c_str());
707     if (modIter->Unload())
708         {
709         WriteServLog("Module \'%s\': Error: %s",
710                      name.c_str(),
711                      modIter->GetStrError().c_str());
712         printfd(__FILE__, "Failed to unload module '%s'\n", name.c_str());
713         }
714     ++modIter;
715     }
716
717 if (traffCnt)
718     {
719     traffCnt->Stop();
720     WriteServLog("Traffcounter: Stop successfull.");
721     }
722
723 if (users)
724     {
725     users->Stop();
726     WriteServLog("Users: Stop successfull.");
727     }
728
729 sleep(1);
730 int res = msgctl(msgID, IPC_RMID, NULL);
731 if (res)
732     WriteServLog("Queue was not removed. id=%d", msgID);
733 else
734     WriteServLog("Queue removed successfully.");
735
736 /*struct sigaction newsa, oldsa;
737 sigset_t sigmask;
738 sigemptyset(&sigmask);
739 sigaddset(&sigmask, SIGCHLD);
740 newsa.sa_handler = SIG_IGN;
741 newsa.sa_mask = sigmask;
742 newsa.sa_flags = 0;
743 sigaction(SIGCHLD, &newsa, &oldsa);*/
744
745 KillExecuters();
746
747 StopStgTimer();
748 WriteServLog("StgTimer: Stop successfull.");
749
750 WriteServLog("Stg stopped successfully.");
751 sleep(1);
752 WriteServLog("---------------------------------------------");
753
754 delete traffCnt;
755 delete users;
756 delete admins;
757 delete tariffs;
758 delete settings;
759
760 return 0;
761 }
762 //-----------------------------------------------------------------------------