Debian Codegraph @

src/e2guardian.cpp

raw
1 // For all support, instructions and copyright go to:
2 // http://e2guardian.org/
3 // Released under the GPL v2, with the OpenSSL exception described in the README file.
4
5 // INCLUDES
6
7 #ifdef HAVE_CONFIG_H
8 #include "e2config.h"
9 #endif
10
11 #include "FatController.hpp"
12 #include "SysV.hpp"
13 #include "Queue.hpp"
14 #include "Logger.hpp"
15 #include "LoggerConfigurator.hpp"
16 #include "UdpSocket.hpp"
17
18 #include <cstdlib>
19 #include <iostream>
20 #include <cstdio>
21 #include <ctime>
22 #include <unistd.h>
23 #include <cerrno>
24 #include <pwd.h>
25 #include <grp.h>
26 #include <fstream>
27 #include <fcntl.h>
28 #include <locale.h>
29 #include <string>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <sys/times.h>
33 #include <sys/resource.h>
34
35 #ifdef __BENCHMARK
36 #include <sys/times.h>
37 #include "NaughtyFilter.hpp"
38 #endif
39
40 // GLOBALS
41
42 OptionContainer o;
43 thread_local std::string thread_id;
44 std::atomic<bool> g_is_starting;
45
46 LoggerConfigurator loggerConfig(&e2logger);
47
48 bool is_daemonised;
49 bool force_nodeamon = false;
50
51 // regexp used during URL decoding by HTTPHeader
52 // we want it compiled once, not every time it's used, so do so on startup
53 RegExp urldecode_re;
54
55 #ifdef HAVE_PCRE
56 // regexes used for embedded URL extraction by NaughtyFilter
57 RegExp absurl_re, relurl_re;
58 #endif
59
60 // DECLARATIONS
61 int readCommandlineOptions(int &ret, int argc, char *argv[]);
62
63 int startDaemon();
64
65 //int runBenchmarks();
66
67 bool check_enough_filedescriptors();
68
69 void prepareRegExp();
70
71 #define E2_LOAD 1
72 #define E2_EXIT 2
73
74 // IMPLEMENTATION
75
76 int main(int argc, char *argv[]) {
77 g_is_starting = true;
78 thread_id = "";
79 int ret = 0;
80
81 o.config.prog_name = PACKAGE;
82 o.config.configfile = __CONFFILE;
83
84 srand(time(NULL));
85
86 // Set current locale for proper character conversion
87 setlocale(LC_ALL, "");
88
89 e2logger.setSyslogName(o.config.prog_name);
90
91 // E2LOGGER_info("Start ", prog_name ); // No we are not starting here - we may be stopping, reloading etc
92
93 #ifdef DEBUG_LOW
94 e2logger.enable(LoggerSource::debug); // This is only for backward compatibilty with previous version
95 // setting all debug features should be done in e2guardian.conf with the debuglevel setting
96
97 // DEBUG_LOW mode is not suitable for production use so warn the user that is switched on
98 E2LOGGER_warning("Running in debug_low mode...");
99 #endif
100
101
102 #ifdef NOT_DEF // bespoke test code to be removed later - PIP
103 UdpSocket test_udp;
104 test_udp.connect("192.168.1.102", 33001);
105 std::string line = "this is a test of upd logging";
106 if(test_udp.writeString(line)) {
107 std::cerr << "upd write ok" << std::endl;
108 } else {
109 std::cerr << "upd write ok" << std::endl;
110 }
111 #endif
112
113 DEBUG_trace("read CommandLineOptions");
114 int rc = readCommandlineOptions(ret, argc, argv);
115 if (rc == E2_EXIT) return ret;
116
117
118 DEBUG_trace("read Configfile: ", o.config.configfile);
119 if (!o.read_config(o.config.configfile)) {
120 E2LOGGER_error("Error parsing the e2guardian.conf file or other e2guardian configuration files");
121 exit(1); // OptionContainer class had an error reading the conf or other files so exit with error
122 }
123
124 if(force_nodeamon)
125 o.proc.no_daemon = true;
126
127 if (o.config.total_block_list) {
128 if (o.readinStdin()) {
129 DEBUG_debug("Total block lists read OK from stdin.");
130 } else {
131 E2LOGGER_error("Error on reading total_block_list");
132 }
133 }
134
135 DEBUG_trace("create Lists");
136 if (!o.createLists(0)) {
137 E2LOGGER_error("Error reading filter group conf file(s).");
138 return 1;
139 }
140
141 prepareRegExp();
142
143 return startDaemon();
144
145 }
146
147
148 int readCommandlineOptions(int &ret, int argc, char *argv[]) // returns E2_EXIT or E2_LOAD
149 {
150 bool needreset = false;
151 std::string debugoptions;
152
153 DEBUG_trace("parse Options");
154 for (int i = 1; i < argc; i++) { // first check for config file
155 if (argv[i][0] == '-') {
156 for (unsigned int j = 1; j < strlen(argv[i]); j++) {
157 char option = argv[i][j];
158 bool dobreak = false;
159 switch (option) {
160 case 'c':
161 if ((i + 1) < argc) {
162 o.config.configfile = argv[i + 1];
163 i++;
164 dobreak = true;
165 } else {
166 std::cerr << "No config file specified!" << std::endl;
167 ret = 1;
168 return E2_EXIT;
169 }
170 break;
171 }
172 if (dobreak) break;
173 }
174 }
175 }
176
177 for (int i = 1; i < argc; i++) { // then rest of args
178 bool skip_next = false;
179 if (argv[i][0] == '-') {
180 for (unsigned int j = 1; j < strlen(argv[i]); j++) {
181 char option = argv[i][j];
182 bool dobreak = false;
183 switch (option) {
184 case 'q':
185 o.read_config(o.config.configfile, false);
186 ret = sysv_kill(o.proc.pid_filename, true);
187 return E2_EXIT;
188 case 'Q':
189 o.read_config(o.config.configfile, false);
190 sysv_kill(o.proc.pid_filename, false);
191 // give the old process time to die
192 while (sysv_amirunning(o.proc.pid_filename))
193 sleep(1);
194 unlink(o.proc.pid_filename.c_str());
195 // remember to reset config before continuing
196 needreset = true;
197 break;
198 case 's':
199 o.read_config(o.config.configfile, false);
200 ret = sysv_showpid(o.proc.pid_filename);
201 return E2_EXIT;
202 case 'r':
203 case 'g':
204 o.read_config(o.config.configfile, false);
205 ret = sysv_hup(o.proc.pid_filename);
206 return E2_EXIT;
207 case 't':
208 o.read_config(o.config.configfile, false);
209 ret = sysv_usr1(o.proc.pid_filename);
210 return E2_EXIT;
211 case 'v':
212 std::cout << "e2guardian " << PACKAGE_VERSION << std::endl
213 << std::endl
214 << "Built with: " << E2_CONFIGURE_OPTIONS << std::endl;
215 // temporary check code
216 //{
217 //unsigned int ilen = 0;
218 //ilen = ~ilen;
219 //std::cout << " max int is " << ilen << std::endl;
220 //}
221 ret = 0;
222 return E2_EXIT;
223 case 'N':
224 force_nodeamon = true;
225 break;
226 case 'c': // already processed this - so skip
227 skip_next = true;
228 break;
229 case 'i':
230 o.config.total_block_list = true;
231 break;
232 case 'd':
233 if ((i + 1) < argc) {
234 debugoptions = argv[i + 1];
235 i++;
236 dobreak = true;
237 };
238 break;
239
240 case 'h':
241 default:
242 std::cout << "Usage: " << argv[0]
243 << " [-c ConfigFileName|-v|-h|-N|-q|-Q|-s|-r|-g|-i] [-d debuglevel]" << std::endl;
244 std::cout << " -v gives the version number and build options." << std::endl;
245 std::cout << " -h gives this message." << std::endl;
246 std::cout << " -c allows you to specify a different configuration file location." << std::endl;
247 std::cout << " -N Do not go into the background." << std::endl;
248 std::cout << " -q causes e2guardian to kill any running copy." << std::endl;
249 std::cout << " -Q kill any running copy AND start a new one with current options."
250 << std::endl;
251 std::cout << " -s shows the parent process PID and exits." << std::endl;
252 std::cout << " -r reloads lists and group config files by issuing a HUP," << std::endl;
253 std::cout << " but this does not reset the httpworkers option (amongst others)."
254 << std::endl;
255 std::cout << " -g same as -r (Issues a HUP)" << std::endl;
256 std::cout << " -t rotate logs (Issues a USR1)" << std::endl;
257 std::cout << " -d allows you to specify a debuglevel" << std::endl;
258 std::cout << " -i read lists from stdin" << std::endl;
259 ret = 0;
260 return E2_EXIT;
261 }
262 if (dobreak)
263 break; // skip to the next argument
264 }
265 }
266 if (skip_next) i++;
267 }
268
269 if (needreset) {
270 DEBUG_trace("reset Options");
271 o.reset();
272 }
273
274 if (!debugoptions.empty()) {
275 loggerConfig.debuglevel(debugoptions);
276 }
277
278 return E2_LOAD;
279
280 }
281
282
283 int startDaemon() {
284 DEBUG_trace("prepare Start");
285 if (sysv_amirunning(o.proc.pid_filename)) {
286 E2LOGGER_error("I seem to be running already!");
287 return 1; // can't have two copies running!!
288 }
289
290 if (!check_enough_filedescriptors()) return 1;
291 if (!o.proc.find_user_ids()) return 1;
292 if (!o.proc.become_proxy_user()) return 1;
293
294 DEBUG_trace("Starting Main loop");
295 while (true) {
296 int rc = fc_controlit();
297 // its a little messy, but I wanted to split
298 // all the ground work and non-daemon stuff
299 // away from the daemon class
300 // However the line is not so fine.
301 // fc_controlit never returns 2 ??! KDG 2020-09-25
302 if (rc == 2) {
303
304 // In order to re-read the conf files
305 // we need to become root user again
306 if (!o.proc.become_root_user()) return 1;
307
308 DEBUG_trace("About to re-read conf file.");
309 o.reset();
310 if (!o.read_config(o.config.configfile, true)) {
311 // OptionContainer class had an error reading the conf or
312 // other files so exit with errora
313 E2LOGGER_error("Error re-parsing the e2guardian.conf file or other e2guardian configuration files");
314 return 1;
315 }
316 DEBUG_trace("conf file read.");
317
318 while (waitpid(-1, NULL, WNOHANG) > 0) {
319 } // mop up defunts
320
321 // become low priv again
322 if (!o.proc.become_proxy_user()) return 1;
323 continue;
324 }
325
326 if (o.proc.is_daemonised)
327 return 0; // exit without error
328 if (rc > 0) {
329 E2LOGGER_error("Exiting with error");
330 return rc; // exit returning the error number
331 }
332 return 0;
333
334 }
335
336 }
337
338 void prepareRegExp() {
339 urldecode_re.comp("%[0-9a-fA-F][0-9a-fA-F]"); // regexp for url decoding
340
341 #ifdef HAVE_PCRE
342 // todo: these only work with PCRE enabled (non-greedy matching).
343 // change them, or make them a feature for which you need PCRE?
344 absurl_re.comp("[\"'](http|ftp)://.*?[\"']"); // find absolute URLs in quotes
345 relurl_re.comp("(href|src)\\s*=\\s*[\"'].*?[\"']"); // find relative URLs in quotes
346 #endif
347
348 }
349
350 bool check_enough_filedescriptors() {
351 // calc the number of listening processes
352 int no_listen_fds;
353 no_listen_fds = o.net.filter_ports.size() * o.net.filter_ip.size();
354 if (!o.net.TLS_filter_ports.empty()) {
355 no_listen_fds += o.net.TLS_filter_ports.size() * o.net.filter_ip.size();
356 }
357 if (o.net.transparenthttps_port > 0)
358 no_listen_fds++;
359 if (o.net.icap_port > 0)
360 no_listen_fds++;
361
362 struct rlimit rlim;
363 if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
364 E2LOGGER_error("getrlimit call returned error: ", errno);
365 return false;
366 }
367
368 // enough fds needed for listening_fds + logger + ipcs + stdin/out/err
369 // in addition to two for each worker thread
370 int max_free_fds = rlim.rlim_cur - (no_listen_fds + 6);
371 int fd_needed = (o.proc.http_workers * 2) + no_listen_fds + 6;
372
373 if (((o.proc.http_workers * 2)) > max_free_fds) {
374 E2LOGGER_error("httpworkers option in e2guardian.conf has a value too high for current file id limit (",
375 rlim.rlim_cur, ")");
376 E2LOGGER_error("httpworkers ", o.proc.http_workers, " must not exceed 50% of ", max_free_fds);
377 E2LOGGER_error("in this configuration.");
378 E2LOGGER_error("Reduce httpworkers ");
379 E2LOGGER_error("Or increase the filedescriptors available with ulimit -n to at least=", fd_needed);
380 return false; // we can't have rampant proccesses can we?
381 }
382
383 return true;
384 }