1 /*
2  * Copyright (C) Tildeslash Ltd. All rights reserved.
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Affero General Public License version 3.
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 Affero General Public License
13  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
14  *
15  * In addition, as a special exception, the copyright holders give
16  * permission to link the code of portions of this program with the
17  * OpenSSL library under certain conditions as described in each
18  * individual source file, and distribute linked combinations
19  * including the two.
20  *
21  * You must obey the GNU Affero General Public License in all respects
22  * for all of the code used other than OpenSSL.
23  */
24 
25 
26 #ifndef MONIT_H
27 #define MONIT_H
28 
29 #include "config.h"
30 #include <assert.h>
31 
32 #ifdef HAVE_KINFO_H
33 #include <kinfo.h>
34 #endif
35 
36 #ifdef HAVE_SYS_TYPES_H
37 #include <sys/types.h>
38 #endif
39 
40 #ifdef HAVE_SYS_STAT_H
41 #include <sys/stat.h>
42 #endif
43 
44 #ifdef HAVE_SIGNAL_H
45 #include <signal.h>
46 #endif
47 
48 #ifdef HAVE_PTHREAD_H
49 #include <pthread.h>
50 #endif
51 
52 #ifdef HAVE_STDARG_H
53 #include <stdarg.h>
54 #endif
55 
56 #ifdef HAVE_STDIO_H
57 #include <stdio.h>
58 #endif
59 
60 #ifdef HAVE_STDLIB_H
61 #include <stdlib.h>
62 #endif
63 
64 #ifdef HAVE_REGEX_H
65 #include <regex.h>
66 #endif
67 
68 #ifdef HAVE_SYSLOG_H
69 #include <syslog.h>
70 #endif
71 
72 #ifdef HAVE_LIMITS_H
73 #include <limits.h>
74 #endif
75 
76 #ifdef HAVE_SYS_UTSNAME_H
77 #include <sys/utsname.h>
78 #endif
79 
80 #ifdef HAVE_ERRNO_H
81 #include <errno.h>
82 #endif
83 
84 #ifdef HAVE_NETDB_H
85 #include <netdb.h>
86 #endif
87 
88 #ifdef HAVE_SYS_SOCKET_H
89 #include <sys/socket.h>
90 #endif
91 
92 #ifdef HAVE_UVM_UVM_PARAM_H
93 #include <uvm/uvm_param.h>
94 #endif
95 #ifdef HAVE_VM_VM_H
96 #include <vm/vm.h>
97 #endif
98 
99 #include <stdbool.h>
100 
101 
102 #include "Ssl.h"
103 #include "Address.h"
104 #include "statistics/Statistics.h"
105 #include "net/socket.h"
106 #include "net/Link.h"
107 
108 // libmonit
109 #include "system/Command.h"
110 #include "system/Process.h"
111 #include "util/Str.h"
112 #include "util/StringBuffer.h"
113 #include "thread/Thread.h"
114 
115 
116 #define MONITRC            "monitrc"
117 #define TIMEFORMAT         "%FT%T%z"
118 #define STRERROR            strerror(errno)
119 #define STRLEN             256
120 #ifndef USEC_PER_SEC
121 #define USEC_PER_SEC       1000000L
122 #endif
123 #define USEC_PER_MSEC      1000L
124 
125 #define ARGMAX             64
126 #define MYPIDDIR           PIDDIR
127 #define MYPIDFILE          "monit.pid"
128 #define MYSTATEFILE        "monit.state"
129 #define MYIDFILE           "monit.id"
130 #define MYEVENTLISTBASE    "/var/monit"
131 
132 #define LOCALHOST          "localhost"
133 
134 #define PORT_SMTP          25
135 #define PORT_SMTPS         465
136 #define PORT_HTTP          80
137 #define PORT_HTTPS         443
138 
139 #define SSL_TIMEOUT        15000
140 #define SMTP_TIMEOUT       30000
141 
142 
143 //FIXME: refactor Run_Flags to bit field
144 typedef enum {
145         Run_Once                 = 0x1,                   /**< Run Monit only once */
146         Run_Foreground           = 0x2,                 /**< Don't daemonize Monit */ //FIXME: cleanup: Run_Foreground and Run_Daemon are mutually exclusive => no need for 2 flags
147         Run_Daemon               = 0x4,                       /**< Daemonize Monit */ //FIXME: cleanup: Run_Foreground and Run_Daemon are mutually exclusive => no need for 2 flags
148         Run_Log                  = 0x8,                           /**< Log enabled */
149         Run_UseSyslog            = 0x10,                           /**< Use syslog */ //FIXME: cleanup: no need for standalone flag ... if syslog is enabled, don't set Run.files.log, then (Run.flags&Run_Log && ! Run.files.log => syslog)
150         Run_FipsEnabled          = 0x20,                 /** FIPS-140 mode enabled */
151         Run_HandlerInit          = 0x40,    /**< The handlers queue initialization */
152         Run_ProcessEngineEnabled = 0x80,    /**< Process monitoring engine enabled */
153         Run_ActionPending        = 0x100,              /**< Service action pending */
154         Run_MmonitCredentials    = 0x200,      /**< Should set M/Monit credentials */
155         Run_Stopped              = 0x400,                          /**< Stop Monit */
156         Run_DoReload             = 0x800,                        /**< Reload Monit */
157         Run_DoWakeup             = 0x1000,                       /**< Wakeup Monit */
158         Run_Batch                = 0x2000                      /**< CLI batch mode */
159 } __attribute__((__packed__)) Run_Flags;
160 
161 
162 typedef enum {
163         ProcessEngine_None               = 0x0,
164         ProcessEngine_CollectCommandLine = 0x1
165 } __attribute__((__packed__)) ProcessEngine_Flags;
166 
167 
168 typedef enum {
169         Httpd_Start = 1,
170         Httpd_Stop
171 } __attribute__((__packed__)) Httpd_Action;
172 
173 
174 typedef enum {
175         Every_Initializing = 0,
176         Every_Cycle,
177         Every_SkipCycles,
178         Every_Cron,
179         Every_NotInCron
180 } __attribute__((__packed__)) Every_Type;
181 
182 
183 typedef enum {
184         State_Succeeded  = 0x0,
185         State_Failed     = 0x1,
186         State_Changed    = 0x2,
187         State_ChangedNot = 0x4,
188         State_Init       = 0x8,
189         State_None       = State_Init // Alias
190 } __attribute__((__packed__)) State_Type;
191 
192 
193 typedef enum {
194         Operator_Less = 0,
195         Operator_LessOrEqual,
196         Operator_Greater,
197         Operator_GreaterOrEqual,
198         Operator_Equal,
199         Operator_NotEqual,
200         Operator_Changed
201 } __attribute__((__packed__)) Operator_Type;
202 
203 
204 typedef enum {
205         Timestamp_Default = 0,
206         Timestamp_Access,
207         Timestamp_Change,
208         Timestamp_Modification
209 } __attribute__((__packed__)) Timestamp_Type;
210 
211 
212 typedef enum {
213         Httpd_Disabled                    = 0x0,
214         Httpd_Net                         = 0x1,  // IP
215         Httpd_Unix                        = 0x2,  // Unix socket
216         Httpd_UnixUid                     = 0x4,  // Unix socket: override UID
217         Httpd_UnixGid                     = 0x8,  // Unix socket: override GID
218         Httpd_UnixPermission              = 0x10, // Unix socket: override permissions
219         Httpd_Signature                   = 0x20  // Server Signature enabled
220 } __attribute__((__packed__)) Httpd_Flags;
221 
222 
223 typedef enum {
224         Http_Head = 1,
225         Http_Get
226 } __attribute__((__packed__)) Http_Method;
227 
228 
229 typedef enum {
230         Time_Second = 1,
231         Time_Minute = 60,
232         Time_Hour   = 3600,
233         Time_Day    = 86400,
234         Time_Month  = 2678400
235 } __attribute__((__packed__)) Time_Type;
236 
237 
238 typedef enum {
239         Action_Ignored = 0,
240         Action_Alert,
241         Action_Restart,
242         Action_Stop,
243         Action_Exec,
244         Action_Unmonitor,
245         Action_Start,
246         Action_Monitor
247 } __attribute__((__packed__)) Action_Type;
248 
249 
250 typedef enum {
251         Monitor_Active = 0,
252         Monitor_Passive
253 } __attribute__((__packed__)) Monitor_Mode;
254 
255 
256 typedef enum {
257         Onreboot_Start = 0,
258         Onreboot_Nostart,
259         Onreboot_Laststate
260 } __attribute__((__packed__)) Onreboot_Type;
261 
262 
263 typedef enum {
264         Monitor_Not     = 0x0,
265         Monitor_Yes     = 0x1,
266         Monitor_Init    = 0x2,
267         Monitor_Waiting = 0x4
268 } __attribute__((__packed__)) Monitor_State;
269 
270 
271 typedef enum {
272         Connection_Failed = 0,
273         Connection_Ok,
274         Connection_Init
275 } __attribute__((__packed__)) Connection_State;
276 
277 
278 typedef enum {
279         Service_Filesystem = 0,
280         Service_Directory,
281         Service_File,
282         Service_Process,
283         Service_Host,
284         Service_System,
285         Service_Fifo,
286         Service_Program,
287         Service_Net,
288         Service_Last = Service_Net
289 } __attribute__((__packed__)) Service_Type;
290 
291 
292 typedef enum {
293         Resource_CpuPercent = 1,
294         Resource_MemoryPercent,
295         Resource_MemoryKbyte,
296         Resource_LoadAverage1m,
297         Resource_LoadAverage5m,
298         Resource_LoadAverage15m,
299         Resource_Children,
300         Resource_MemoryKbyteTotal,
301         Resource_MemoryPercentTotal,
302         Resource_Inode,
303         Resource_InodeFree,
304         Resource_Space,
305         Resource_SpaceFree,
306         Resource_CpuUser,
307         Resource_CpuSystem,
308         Resource_CpuWait,
309         Resource_CpuNice,
310         Resource_CpuHardIRQ,
311         Resource_CpuSoftIRQ,
312         Resource_CpuSteal,
313         Resource_CpuGuest,
314         Resource_CpuGuestNice,
315         Resource_CpuPercentTotal,
316         Resource_SwapPercent,
317         Resource_SwapKbyte,
318         Resource_Threads,
319         Resource_ReadBytes,
320         Resource_ReadBytesPhysical,
321         Resource_ReadOperations,
322         Resource_WriteBytes,
323         Resource_WriteBytesPhysical,
324         Resource_WriteOperations,
325         Resource_ServiceTime,
326         Resource_LoadAveragePerCore1m,
327         Resource_LoadAveragePerCore5m,
328         Resource_LoadAveragePerCore15m
329 } __attribute__((__packed__)) Resource_Type;
330 
331 
332 
333 typedef enum {
334         Digest_Cleartext = 1,
335         Digest_Crypt,
336         Digest_Md5,
337         Digest_Pam
338 } __attribute__((__packed__)) Digest_Type;
339 
340 
341 typedef enum {
342         Unit_Byte     = 1,
343         Unit_Kilobyte = 1024,
344         Unit_Megabyte = 1048576,
345         Unit_Gigabyte = 1073741824
346 } __attribute__((__packed__)) Unit_Type;
347 
348 
349 typedef enum {
350         Hash_Unknown = 0,
351         Hash_Md5,
352         Hash_Sha1,
353         Hash_Default = Hash_Md5
354 } __attribute__((__packed__)) Hash_Type;
355 
356 
357 typedef enum {
358         Handler_Succeeded = 0x0,
359         Handler_Alert     = 0x1,
360         Handler_Mmonit    = 0x2,
361         Handler_Max       = Handler_Mmonit
362 } __attribute__((__packed__)) Handler_Type;
363 
364 
365 typedef enum {
366         MmonitCompress_Init = 0,
367         MmonitCompress_No,
368         MmonitCompress_Yes
369 } __attribute__((__packed__)) MmonitCompress_Type;
370 
371 
372 typedef enum {
373         Statistics_CpuUser                      = 0x1,
374         Statistics_CpuNice                      = 0x2,
375         Statistics_CpuSystem                    = 0x4,
376         Statistics_CpuIOWait                    = 0x8,
377         Statistics_CpuHardIRQ                   = 0x10,
378         Statistics_CpuSoftIRQ                   = 0x20,
379         Statistics_CpuSteal                     = 0x40,
380         Statistics_CpuGuest                     = 0x80,
381         Statistics_CpuGuestNice                 = 0x100,
382         Statistics_FiledescriptorsPerSystem     = 0x200,
383         Statistics_FiledescriptorsPerProcess    = 0x400,
384         Statistics_FiledescriptorsPerProcessMax = 0x800
385 } __attribute__((__packed__)) Statistics_Flags;
386 
387 
388 /* Length of the longest message digest in bytes */
389 #define MD_SIZE 65
390 
391 
392 #define ICMP_SIZE 64
393 #define ICMP_MAXSIZE 1500
394 #define ICMP_ATTEMPT_COUNT 3
395 
396 
397 /* Default limits */
398 #define LIMIT_SENDEXPECTBUFFER  256
399 #define LIMIT_FILECONTENTBUFFER 512
400 #define LIMIT_PROGRAMOUTPUT     512
401 #define LIMIT_HTTPCONTENTBUFFER 1048576
402 #define LIMIT_NETWORKTIMEOUT    5000
403 #define LIMIT_PROGRAMTIMEOUT    300000
404 #define LIMIT_STOPTIMEOUT       30000
405 #define LIMIT_STARTTIMEOUT      30000
406 #define LIMIT_RESTARTTIMEOUT    30000
407 
408 
409 
410 /** ------------------------------------------------- Special purpose macros */
411 
412 
413 /* Replace the standard signal function with a more reliable using
414  * sigaction. Taken from Stevens APUE book. */
415 typedef void Sigfunc(int);
416 Sigfunc *signal(int signo, Sigfunc * func);
417 #if defined(SIG_IGN) && !defined(SIG_ERR)
418 #define SIG_ERR ((Sigfunc *)-1)
419 #endif
420 
421 
422 /** ------------------------------------------------- General purpose macros */
423 
424 
425 #undef MAX
426 #define MAX(x,y) ((x) > (y) ? (x) : (y))
427 #undef MIN
428 #define MIN(x,y) ((x) < (y) ? (x) : (y))
429 #define IS(a,b)  ((a && b) ? Str_isEqual(a, b) : false)
430 #define DEBUG Log_debug
431 #define FLAG(x, y) (x & y) == y
432 #define NVLSTR(x) (x ? x : "")
433 
434 
435 /** ------------------------------------------ Simple Assert Exception macro */
436 
437 
438 #define ASSERT(e) do { if (!(e)) { Log_critical("AssertException: " #e \
439 " at %s:%d\naborting..\n", __FILE__, __LINE__); abort(); } } while (0)
440 
441 
442 /* --------------------------------------------------------- Data structures */
443 
444 
445 /** Message Digest type with size for the longest digest we will compute */
446 typedef char MD_T[MD_SIZE];
447 
448 
449 /** Defines monit limits object */
450 typedef struct Limits_T {
451         int      programOutput;           /**< Program output truncate limit [B] */
452         size_t   fileContentBuffer;  /**< Maximum tested file content length [B] */
453         uint32_t sendExpectBuffer;  /**< Maximum send/expect response length [B] */
454         uint32_t httpContentBuffer;  /**< Maximum tested HTTP content length [B] */
455         uint32_t networkTimeout;               /**< Default network timeout [ms] */
456         uint32_t programTimeout;               /**< Default program timeout [ms] */
457         uint32_t stopTimeout;                     /**< Default stop timeout [ms] */
458         uint32_t startTimeout;                   /**< Default start timeout [ms] */
459         uint32_t restartTimeout;               /**< Default restart timeout [ms] */
460 } Limits_T;
461 
462 
463 /**
464  * Defines a Command with ARGMAX optional arguments. The arguments
465  * array must be NULL terminated and the first entry is the program
466  * itself. In addition, a user and group may be set for the Command
467  * which means that the Command should run as a certain user and with
468  * certain group. To avoid name collision with Command_T in libmonit
469  * this structure uses lower case.
470  */
471 typedef struct command_t {
472         char *arg[ARGMAX];                             /**< Program with arguments */
473         short length;                       /**< The length of the arguments array */
474         bool has_uid;      /**< true if a new uid is defined for this Command */
475         bool has_gid;      /**< true if a new gid is defined for this Command */
476         uid_t uid;         /**< The user id to switch to when running this Command */
477         gid_t gid;        /**< The group id to switch to when running this Command */
478         unsigned int timeout;     /**< Max seconds which we wait for method to execute */
479 } *command_t;
480 
481 
482 /** Defines an event action object */
483 typedef struct Action_T {
484         Action_Type id;                                   /**< Action to be done */
485         int count;                 /**< Event count needed to trigger the action */
486         int cycles;          /**< Cycles during which count limit can be reached */
487         int repeat;                             /*< Repeat action each Xth cycle */
488         command_t exec;                     /**< Optional command to be executed */
489 } *Action_T;
490 
491 
492 /** Defines event's up and down actions */
493 typedef struct EventAction_T {
494         Action_T  failed;                  /**< Action in the case of failure down */
495         Action_T  succeeded;                    /**< Action in the case of failure up */
496 } *EventAction_T;
497 
498 
499 /** Defines an url object */
500 typedef struct URL_T {
501         char *url;                                                  /**< Full URL */
502         char *protocol;                                    /**< URL protocol type */
503         char *user;                                        /**< URL user     part */
504         char *password;                                    /**< URL password part */
505         char *hostname;                                    /**< URL hostname part */
506         char *path;                                        /**< URL path     part */
507         char *query;                                       /**< URL query    part */
508         int   port;                                        /**< URL port     part */
509         bool ipv6;
510 } *URL_T;
511 
512 
513 /** Defines a HTTP client request object */
514 typedef struct Request_T {
515         URL_T url;                                               /**< URL request */
516         Operator_Type operator;         /**< Response content comparison operator */
517         regex_t *regex;                   /* regex used to test the response body */
518 } *Request_T;
519 
520 
521 /** Defines an event notification and status receiver object */
522 typedef struct Mmonit_T {
523         URL_T url;                                             /**< URL definition */
524         struct SslOptions_T ssl;                               /**< SSL definition */
525         int timeout;                /**< The timeout to wait for connection or i/o */
526         MmonitCompress_Type compress;                        /**< Compression flag */
527 
528         /** For internal use */
529         struct Mmonit_T *next;                         /**< next receiver in chain */
530 } *Mmonit_T;
531 
532 
533 /** Defines a mailinglist object */
534 typedef struct Mail_T {
535         char *to;                         /**< Mail address for alert notification */
536         Address_T from;                                 /**< The mail from address */
537         Address_T replyto;                          /**< Optional reply-to address */
538         char *subject;                                       /**< The mail subject */
539         char *message;                                       /**< The mail message */
540         char *host;                                             /**< FQDN hostname */
541         unsigned int events;  /*< Events for which this mail object should be sent */
542         unsigned int reminder;              /*< Send error reminder each Xth cycle */
543 
544         /** For internal use */
545         struct Mail_T *next;                          /**< next recipient in chain */
546 } *Mail_T;
547 
548 
549 /** Defines a mail server address */
550 typedef struct MailServer_T {
551         char *host;     /**< Server host address, may be a IP or a hostname string */
552         int   port;                                               /**< Server port */
553         char *username;                               /** < Username for SMTP_AUTH */
554         char *password;                               /** < Password for SMTP_AUTH */
555         struct SslOptions_T ssl;                               /**< SSL definition */
556         Socket_T socket;                                     /**< Connected socket */
557 
558         /** For internal use */
559         struct MailServer_T *next;        /**< Next server to try on connect error */
560 } *MailServer_T;
561 
562 
563 typedef struct Auth_T {
564         char *uname;                  /**< User allowed to connect to monit httpd */
565         char *passwd;                                /**< The users password data */
566         char *groupname;                                      /**< PAM group name */
567         Digest_Type digesttype;                /**< How did we store the password */
568         bool is_readonly; /**< true if this is a read-only authenticated user*/
569         struct Auth_T *next;                 /**< Next credential or NULL if last */
570 } *Auth_T;
571 
572 
573 /** Defines data for systemwide statistic */
574 typedef struct SystemInfo_T {
575         Statistics_Flags statisticsAvailable; /**< List of statistics that are available on this system */
576         struct {
577                 int count;                                      /**< Number of CPUs */
578                 struct {
579                         float user;       /**< Time in user space [%] */
580                         float nice;       /**< Time in user space with low priority [%] */
581                         float system;     /**< Time in kernel space [%] */
582                         float iowait;     /**< Idle time while waiting for I/O [%] */
583                         float hardirq;    /**< Time servicing hardware interrupts [%] */
584                         float softirq;    /**< Time servicing software interrupts [%] */
585                         float steal;      /**< Stolen time, which is the time spent in other operating systems when running in a virtualized environment [%] */
586                         float guest;      /**< Time spent running a virtual CPU for guest operating systems under the control of the kernel [%] */
587                         float guest_nice; /**< Time spent running a niced guest (virtual CPU for guest operating systems under the control of the kernel) [%] */
588                         float idle;       /**< Idle time [%] */
589                 } usage;
590         } cpu;
591         struct {
592                 unsigned long long size;                      /**< Maximal system real memory */
593                 struct {
594                         float percent;  /**< Total real memory in use in the system */
595                         unsigned long long bytes; /**< Total real memory in use in the system */
596                 } usage;
597         } memory;
598         struct {
599                 unsigned long long size;                                       /**< Swap size */
600                 struct {
601                         float percent;         /**< Total swap in use in the system */
602                         unsigned long long bytes;        /**< Total swap in use in the system */
603                 } usage;
604         } swap;
605         struct {
606                 long long allocated;        /**< Number of allocated filedescriptors */
607                 long long unused;              /**< Number of unused filedescriptors */
608                 long long maximum;                        /**< Filedescriptors limit */
609         } filedescriptors;
610         size_t argmax;                                                   /**< Program arguments maximum [B] */
611         double loadavg[3];                                                         /**< Load average triple */
612         struct utsname uname;                                 /**< Platform information provided by uname() */
613         struct timeval collected;                                             /**< When were data collected */
614         unsigned long long booted; /**< System boot time (seconds since UNIX epoch, using platform-agnostic unsigned long long) */
615         double time;                                                                      /**< 1/10 seconds */
616         double time_prev;                                                                 /**< 1/10 seconds */
617 } SystemInfo_T;
618 
619 
620 /** Defines a protocol object with protocol functions */
621 typedef struct Protocol_T {
622         const char *name;                                       /**< Protocol name */
623         void (*check)(Socket_T);          /**< Protocol verification function */
624 } *Protocol_T;
625 
626 
627 /** Defines a send/expect object used for generic protocol tests */
628 typedef struct Generic_T {
629         char *send;                           /* string to send, or NULL if expect */
630         regex_t *expect;                  /* regex code to expect, or NULL if send */
631         /** For internal use */
632         struct Generic_T *next;
633 } *Generic_T;
634 
635 
636 typedef struct Outgoing_T {
637         char *ip;                                         /**< Outgoing IP address */
638         struct sockaddr_storage addr;
639         socklen_t addrlen;
640 } Outgoing_T;
641 
642 
643 typedef struct ResponseTime_T {
644         Operator_Type operator;
645         double current;                            /**< Current response time [ms] */
646         double limit;                                /**< Response time limit [ms] */
647 } ResponseTime_T;
648 
649 
650 /** Defines a port object */
651 typedef struct Port_T {
652         char *hostname;                                     /**< Hostname to check */
653         union {
654                 struct {
655                         char *pathname;                  /**< Unix socket pathname */
656                 } unix;
657                 struct {
658                         int port;                                 /**< Port number */
659                         struct {
660                                 struct SslOptions_T options;
661                                 struct {
662                                         int validDays;
663                                         int minimumDays;
664                                 } certificate;
665                         } ssl;
666                 } net;
667         } target;
668         Outgoing_T outgoing;                                 /**< Outgoing address */
669         bool check_invers;           /**< Whether to alert on a connection success */
670         int timeout;      /**< The timeout in [ms] to wait for connect or read i/o */
671         int retry;       /**< Number of connection retry before reporting an error */
672         volatile int socket;                       /**< Socket used for connection */
673         struct ResponseTime_T responsetime;               /**< Response time limit */
674         Socket_Type type;           /**< Socket type used for connection (UDP/TCP) */
675         Socket_Family family;    /**< Socket family used for connection (NET/UNIX) */
676         Connection_State is_available;               /**< Server/port availability */
677         EventAction_T action; /**< Description of the action upon event occurrence */
678         /** Protocol specific parameters */
679         union {
680                 struct {
681                         char *username;
682                         char *password;
683                         char *path;                                              /**< status path */
684                         short loglimit;                  /**< Max percentage of logging processes */
685                         short closelimit;             /**< Max percentage of closinging processes */
686                         short dnslimit;         /**< Max percentage of processes doing DNS lookup */
687                         short keepalivelimit;          /**< Max percentage of keepalive processes */
688                         short replylimit;               /**< Max percentage of replying processes */
689                         short requestlimit;     /**< Max percentage of processes reading requests */
690                         short startlimit;            /**< Max percentage of processes starting up */
691                         short waitlimit;  /**< Min percentage of processes waiting for connection */
692                         short gracefullimit;/**< Max percentage of processes gracefully finishing */
693                         short cleanuplimit;      /**< Max percentage of processes in idle cleanup */
694                         Operator_Type loglimitOP;                          /**< loglimit operator */
695                         Operator_Type closelimitOP;                      /**< closelimit operator */
696                         Operator_Type dnslimitOP;                          /**< dnslimit operator */
697                         Operator_Type keepalivelimitOP;              /**< keepalivelimit operator */
698                         Operator_Type replylimitOP;                      /**< replylimit operator */
699                         Operator_Type requestlimitOP;                  /**< requestlimit operator */
700                         Operator_Type startlimitOP;                      /**< startlimit operator */
701                         Operator_Type waitlimitOP;                        /**< waitlimit operator */
702                         Operator_Type gracefullimitOP;                /**< gracefullimit operator */
703                         Operator_Type cleanuplimitOP;                  /**< cleanuplimit operator */
704                 } apachestatus;
705                 struct {
706                         Generic_T sendexpect;
707                 } generic;
708                 struct {
709                         Hash_Type hashtype;           /**< Type of hash for a checksum (optional) */
710                         bool hasStatus;                    /**< Is explicit HTTP status set? */
711                         Operator_Type operator;                         /**< HTTP status operator */
712                         Http_Method method;
713                         int status;                                              /**< HTTP status */
714                         char *username;
715                         char *password;
716                         char *request;                                          /**< HTTP request */
717                         char *checksum;                         /**< Document checksum (optional) */
718                         List_T headers;      /**< List of headers to send with request (optional) */
719                 } http;
720                 struct {
721                         char *username;
722                         char *password;
723                 } mqtt;
724                 struct {
725                         char *username;
726                         char *password;
727                         char *rsaChecksum;
728                         Hash_Type rsaChecksumType;
729                 } mysql;
730                 struct {
731                         char *username;
732                         char *password;
733                         char *database;
734                 } postgresql;
735                 struct {
736                         char *secret;
737                 } radius;
738                 struct {
739                         int maxforward;
740                         char *target;
741                 } sip;
742                 struct {
743                         char *username;
744                         char *password;
745                 } smtp;
746                 struct {
747                         int version;
748                         char *host;
749                         char *origin;
750                         char *request;
751                 } websocket;
752         } parameters;
753         Protocol_T protocol;     /**< Protocol object for testing a port's service */
754         Request_T url_request;             /**< Optional url client request object */
755 
756         /** For internal use */
757         struct Port_T *next;                               /**< next port in chain */
758 } *Port_T;
759 
760 
761 /** Defines a ICMP/Ping object */
762 typedef struct Icmp_T {
763         int type;                                              /**< ICMP type used */
764         int size;                                     /**< ICMP echo requests size */
765         int count;                                   /**< ICMP echo requests count */
766         int timeout;         /**< The timeout in milliseconds to wait for response */
767         bool check_invers;           /**< Whether to alert on a connection success */
768         Connection_State is_available;    /**< Flag for the server is availability */
769         Socket_Family family;                 /**< ICMP family used for connection */
770         struct ResponseTime_T responsetime;               /**< Response time limit */
771         Outgoing_T outgoing;                                 /**< Outgoing address */
772         EventAction_T action; /**< Description of the action upon event occurrence */
773 
774         /** For internal use */
775         struct Icmp_T *next;                               /**< next icmp in chain */
776 } *Icmp_T;
777 
778 
779 typedef struct Dependant_T {
780         char *dependant;                            /**< name of dependant service */
781         char *dependant_urlescaped;     /**< URL escaped name of dependant service */
782         StringBuffer_T dependant_htmlescaped; /**< HTML escaped name of dependant service */
783 
784         /** For internal use */
785         struct Dependant_T *next;             /**< next dependant service in chain */
786 } *Dependant_T;
787 
788 
789 /** Defines resource data */
790 typedef struct Resource_T {
791         Resource_Type resource_id;                     /**< Which value is checked */
792         Operator_Type operator;                           /**< Comparison operator */
793         double limit;                                   /**< Limit of the resource */
794         EventAction_T action; /**< Description of the action upon event occurrence */
795 
796         /** For internal use */
797         struct Resource_T *next;                       /**< next resource in chain */
798 } *Resource_T;
799 
800 
801 /** Defines timestamp object */
802 typedef struct Timestamp_T {
803         bool initialized;              /**< true if timestamp was initialized */
804         bool test_changes;       /**< true if we only should test for changes */
805         Timestamp_Type type;
806         Operator_Type operator;                           /**< Comparison operator */
807         unsigned long long time;                                    /**< Timestamp watermark */
808         time_t lastTimestamp;        /**< Last timestamp (context depends on type) */
809         EventAction_T action; /**< Description of the action upon event occurrence */
810 
811         /** For internal use */
812         struct Timestamp_T *next;                     /**< next timestamp in chain */
813 } *Timestamp_T;
814 
815 
816 /** Defines action rate object */
817 typedef struct ActionRate_T {
818         int  count;                                            /**< Action counter */
819         int  cycle;                                             /**< Cycle counter */
820         EventAction_T action;    /**< Description of the action upon matching rate */
821 
822         /** For internal use */
823         struct ActionRate_T *next;                   /**< next actionrate in chain */
824 } *ActionRate_T;
825 
826 
827 /** Defines when to run a check for a service. This type supports both the old
828  cycle based every statement and the new cron-format version */
829 typedef struct Every_T {
830         Every_Type type;
831         time_t last_run;
832         union {
833                 struct {
834                         int number; /**< Check this program at a given cycles */
835                         int counter; /**< Counter for number. When counter == number, check */
836                 } cycle; /**< Old cycle based every check */
837                 char *cron; /* A crontab format string */
838         } spec;
839 } Every_T;
840 
841 
842 typedef struct Status_T {
843         bool initialized;                 /**< true if status was initialized */
844         Operator_Type operator;                           /**< Comparison operator */
845         int return_value;                /**< Return value of the program to check */
846         EventAction_T action; /**< Description of the action upon event occurrence */
847 
848         /** For internal use */
849         struct Status_T *next;                       /**< next exit value in chain */
850 } *Status_T;
851 
852 
853 typedef struct Program_T {
854         Process_T P;          /**< A Process_T object representing the sub-process */
855         Command_T C;          /**< A Command_T object for creating the sub-process */
856         command_t args;                                     /**< Program arguments */
857         time_t started;                      /**< When the sub-process was started */
858         int timeout;           /**< Seconds the program may run until it is killed */
859         int exitStatus;                 /**< Sub-process exit status for reporting */
860         StringBuffer_T lastOutput;                        /**< Last program output */
861         StringBuffer_T inprogressOutput; /**< Output of the pending program instance */
862 } *Program_T;
863 
864 
865 /** Defines size object */
866 typedef struct Size_T {
867         bool initialized;                   /**< true if size was initialized */
868         bool test_changes;       /**< true if we only should test for changes */
869         Operator_Type operator;                           /**< Comparison operator */
870         unsigned long long size;                               /**< Size watermark */
871         EventAction_T action; /**< Description of the action upon event occurrence */
872 
873         /** For internal use */
874         struct Size_T *next;                               /**< next size in chain */
875 } *Size_T;
876 
877 
878 /** Defines uptime object */
879 typedef struct Uptime_T {
880         Operator_Type operator;                           /**< Comparison operator */
881         unsigned long long uptime;                           /**< Uptime watermark */
882         EventAction_T action; /**< Description of the action upon event occurrence */
883 
884         /** For internal use */
885         struct Uptime_T *next;                           /**< next uptime in chain */
886 } *Uptime_T;
887 
888 
889 typedef struct LinkStatus_T {
890         bool check_invers;                      /**< Whether to alert on a link up */
891         EventAction_T action; /**< Description of the action upon event occurrence */
892 
893         /** For internal use */
894         struct LinkStatus_T *next;                      /**< next link in chain */
895 } *LinkStatus_T;
896 
897 
898 typedef struct LinkSpeed_T {
899         int duplex;                                        /**< Last duplex status */
900         long long speed;                                     /**< Last speed [bps] */
901         EventAction_T action; /**< Description of the action upon event occurrence */
902 
903         /** For internal use */
904         struct LinkSpeed_T *next;                       /**< next link in chain */
905 } *LinkSpeed_T;
906 
907 
908 typedef struct LinkSaturation_T {
909         Operator_Type operator;                           /**< Comparison operator */
910         float limit;                                     /**< Saturation limit [%] */
911         EventAction_T action; /**< Description of the action upon event occurrence */
912 
913         /** For internal use */
914         struct LinkSaturation_T *next;                  /**< next link in chain */
915 } *LinkSaturation_T;
916 
917 
918 typedef struct Bandwidth_T {
919         Operator_Type operator;                           /**< Comparison operator */
920         Time_Type range;                            /**< Time range to watch: unit */
921         int rangecount;                            /**< Time range to watch: count */
922         unsigned long long limit;                              /**< Data watermark */
923         EventAction_T action; /**< Description of the action upon event occurrence */
924 
925         /** For internal use */
926         struct Bandwidth_T *next;                     /**< next bandwidth in chain */
927 } *Bandwidth_T;
928 
929 
930 /** Defines checksum object */
931 typedef struct Checksum_T {
932         bool initialized;                    /**< true if checksum was initialized */
933         bool test_changes;            /**< true if we only should test for changes */
934         Hash_Type type;                   /**< The type of hash (e.g. md5 or sha1) */
935         int   length;                                      /**< Length of the hash */
936         char  hash[MD_SIZE + 1];        /**< A checksum hash computed for the path */
937         EventAction_T action; /**< Description of the action upon event occurrence */
938 } *Checksum_T;
939 
940 
941 /** Defines permission object */
942 typedef struct Perm_T {
943         bool test_changes;       /**< true if we only should test for changes */
944         int perm;                                           /**< Access permission */
945         EventAction_T action; /**< Description of the action upon event occurrence */
946 } *Perm_T;
947 
948 /** Defines match object */
949 typedef struct Match_T {
950         bool ignore;                                        /**< Ignore match */
951         bool not;                                           /**< Invert match */
952         char    *match_string;                                   /**< Match string */ //FIXME: union?
953         char    *match_path;                         /**< File with matching rules */ //FIXME: union?
954         regex_t *regex_comp;                                    /**< Match compile */
955         StringBuffer_T log;   /**< The temporary buffer used to record the matches */
956         EventAction_T action; /**< Description of the action upon event occurrence */
957 
958         /** For internal use */
959         struct Match_T *next;                             /**< next match in chain */
960 } *Match_T;
961 
962 
963 /** Defines uid object */
964 typedef struct Uid_T {
965         uid_t     uid;                                            /**< Owner's uid */
966         EventAction_T action; /**< Description of the action upon event occurrence */
967 } *Uid_T;
968 
969 
970 /** Defines gid object */
971 typedef struct Gid_T {
972         gid_t     gid;                                            /**< Owner's gid */
973         EventAction_T action; /**< Description of the action upon event occurrence */
974 } *Gid_T;
975 
976 
977 typedef struct SecurityAttribute_T {
978         char *attribute;                                   /**< Security attribute */
979         EventAction_T action; /**< Description of the action upon event occurrence */
980 
981         /** For internal use */
982         struct SecurityAttribute_T *next;
983 } *SecurityAttribute_T;
984 
985 typedef struct Filedescriptors_T {
986         bool total;             /**<Whether to include filedescriptors of children */
987         long long limit_absolute;                      /**<  Filedescriptors limit */
988         float limit_percent;                            /**< Filedescriptors limit */
989         Operator_Type operator;                           /**< Comparison operator */
990         EventAction_T action; /**< Description of the action upon event occurrence */
991 
992         /** For internal use */
993         struct Filedescriptors_T *next;
994 } *Filedescriptors_T;
995 
996 /** Defines pid object */
997 typedef struct Pid_T {
998         EventAction_T action; /**< Description of the action upon event occurrence */
999 
1000         /** For internal use */
1001         struct Pid_T *next;                                 /**< next pid in chain */
1002 } *Pid_T;
1003 
1004 
1005 typedef struct FsFlag_T {
1006         EventAction_T action; /**< Description of the action upon event occurrence */
1007 
1008         /** For internal use */
1009         struct FsFlag_T *next;
1010 } *FsFlag_T;
1011 
1012 
1013 typedef struct NonExist_T {
1014         EventAction_T action; /**< Description of the action upon event occurrence */
1015 
1016         /** For internal use */
1017         struct NonExist_T *next;
1018 } *NonExist_T;
1019 
1020 
1021 typedef struct Exist_T {
1022         EventAction_T action; /**< Description of the action upon event occurrence */
1023 
1024         /** For internal use */
1025         struct Exist_T *next;
1026 } *Exist_T;
1027 
1028 
1029 /** Defines filesystem configuration */
1030 typedef struct FileSystem_T {
1031         Resource_Type resource;               /**< Whether to check inode or space */
1032         Operator_Type operator;                           /**< Comparison operator */
1033         //FIXME: union
1034         long long limit_absolute;                          /**< Watermark - blocks */
1035         float limit_percent;                              /**< Watermark - percent */
1036         EventAction_T action; /**< Description of the action upon event occurrence */
1037 
1038         /** For internal use */
1039         struct FileSystem_T *next;                   /**< next filesystem in chain */
1040 } *FileSystem_T;
1041 
1042 
1043 typedef struct IOStatistics_T {
1044         struct Statistics_T operations;                                         /**< Number of operations completed */
1045         struct Statistics_T bytes;          /**< Number of bytes handled by operations (total including cached I/O) */
1046         struct Statistics_T bytesPhysical;           /**< Number of bytes handled by operations (physical I/O only) */
1047 } *IOStatistics_T;
1048 
1049 
1050 typedef struct Device_T {
1051         bool mounted;
1052         int generation;
1053         int instance;
1054         struct {
1055                 int major;
1056                 int minor;
1057         } number;
1058         char partition;
1059         char device[PATH_MAX];
1060         char mountpoint[PATH_MAX];
1061         char key[PATH_MAX];
1062         char module[256];
1063         char type[64];
1064         unsigned long long flags;
1065         bool (*getDiskUsage)(void *);
1066         bool (*getDiskActivity)(void *);
1067 } *Device_T;
1068 
1069 
1070 typedef struct TimestampInfo_T {
1071         unsigned long long access;
1072         unsigned long long change;
1073         unsigned long long modify;
1074 } *TimestampInfo_T;
1075 
1076 
1077 typedef struct FilesystemFlags_T {
1078         char value[2][STRLEN];
1079         char *current;
1080         char *previous;
1081 } *FilesystemFlags_T;
1082 
1083 
1084 typedef struct FileSystemInfo_T {
1085         long long  f_blocks;              /**< Total data blocks in filesystem */
1086         long long  f_blocksfree;   /**< Free blocks available to non-superuser */
1087         long long  f_blocksfreetotal;           /**< Free blocks in filesystem */
1088         long long  f_blocksused;                  /**< Used space total blocks */
1089         long long  f_files;                /**< Total file nodes in filesystem */
1090         long long  f_filesfree;             /**< Free file nodes in filesystem */
1091         long long  f_filesused;                  /**< Used inode total objects */
1092         float inode_percent;                        /**< Used inode percentage */
1093         float space_percent;                        /**< Used space percentage */
1094         int f_bsize;                                  /**< Transfer block size */
1095         int uid;                                              /**< Owner's uid */
1096         int gid;                                              /**< Owner's gid */
1097         int mode;                                              /**< Permission */
1098         struct FilesystemFlags_T flags;                  /**< Filesystem flags */
1099         struct IOStatistics_T read;                       /**< Read statistics */
1100         struct IOStatistics_T write;                     /**< Write statistics */
1101         struct {
1102                 struct Statistics_T read;         /**< Time spend by read [ms] */
1103                 struct Statistics_T write;       /**< Time spend by write [ms] */
1104                 struct Statistics_T wait;   /**< Time spend in wait queue [ms] */
1105                 struct Statistics_T run;     /**< Time spend in run queue [ms] */
1106         } time;
1107         struct Device_T object;                             /**< Device object */
1108 } *FileSystemInfo_T;
1109 
1110 
1111 typedef struct FileInfo_T {
1112         struct TimestampInfo_T timestamp;
1113         int mode;                                              /**< Permission */
1114         int uid;                                              /**< Owner's uid */
1115         int gid;                                              /**< Owner's gid */
1116         off_t size;                                                  /**< Size */
1117         off_t readpos;                        /**< Position for regex matching */
1118         ino_t inode;                                                /**< Inode */
1119         ino_t inode_prev;               /**< Previous inode for regex matching */
1120         MD_T  cs_sum;                                            /**< Checksum */ //FIXME: allocate dynamically only when necessary
1121 } *FileInfo_T;
1122 
1123 
1124 typedef struct DirectoryInfo_T {
1125         struct TimestampInfo_T timestamp;
1126         int mode;                                              /**< Permission */
1127         int uid;                                              /**< Owner's uid */
1128         int gid;                                              /**< Owner's gid */
1129 } *DirectoryInfo_T;
1130 
1131 
1132 typedef struct FifoInfo_T {
1133         struct TimestampInfo_T timestamp;
1134         int mode;                                              /**< Permission */
1135         int uid;                                              /**< Owner's uid */
1136         int gid;                                              /**< Owner's gid */
1137 } *FifoInfo_T;
1138 
1139 
1140 typedef struct ProcessInfo_T {
1141         bool zombie;
1142         pid_t _pid;                           /**< Process PID from last cycle */
1143         pid_t _ppid;                   /**< Process parent PID from last cycle */
1144         pid_t pid;                          /**< Process PID from actual cycle */
1145         pid_t ppid;                  /**< Process parent PID from actual cycle */
1146         int uid;                                              /**< Process UID */
1147         int euid;                                   /**< Effective Process UID */
1148         int gid;                                              /**< Process GID */
1149         int threads;
1150         int children;
1151         unsigned long long mem;
1152         unsigned long long total_mem;
1153         float mem_percent;                                     /**< percentage */
1154         float total_mem_percent;                               /**< percentage */
1155         float cpu_percent;                                     /**< percentage */
1156         float total_cpu_percent;                               /**< percentage */
1157         time_t uptime;                                     /**< Process uptime */
1158         struct IOStatistics_T read;                       /**< Read statistics */
1159         struct IOStatistics_T write;                     /**< Write statistics */
1160         char secattr[STRLEN];                         /**< Security attributes */
1161         struct {
1162                 long long open;                        /**< number of opened files */
1163                 long long openTotal;             /**< number of total opened files */
1164                 struct {
1165                         long long soft;                 /**< Filedescriptors soft limit */
1166                         long long hard;                 /**< Filedescriptors hard limit */
1167                 } limit;
1168         } filedescriptors;
1169 } *ProcessInfo_T;
1170 
1171 
1172 typedef struct NetInfo_T {
1173         Link_T stats;
1174 } *NetInfo_T;
1175 
1176 
1177 /** Defines service data */
1178 typedef union Info_T {
1179         //FIXME: move global SystemInfo_T systeminfo here (for System service context)
1180         DirectoryInfo_T  directory;
1181         FifoInfo_T       fifo;
1182         FileInfo_T       file;
1183         FileSystemInfo_T filesystem;
1184         NetInfo_T        net;
1185         ProcessInfo_T    process;
1186 } *Info_T;
1187 
1188 
1189 /** Defines service data */
1190 //FIXME: use union for type-specific rules
1191 typedef struct Service_T {
1192 
1193         /** Common parameters */
1194         char *name;                                  /**< Service descriptive name */
1195         char *name_urlescaped;                       /**< Service name URL escaped */
1196         StringBuffer_T name_htmlescaped;            /**< Service name HTML escaped */
1197         State_Type (*check)(struct Service_T *);/**< Service verification function */
1198         bool onrebootRestored;
1199         bool visited; /**< Service visited flag, set if dependencies are used */
1200         bool inverseStatus;
1201         Service_Type type;                             /**< Monitored service type */
1202         Monitor_State monitor;                             /**< Monitor state flag */
1203         Monitor_Mode mode;                    /**< Monitoring mode for the service */
1204         Onreboot_Type onreboot;                                /**< On reboot mode */
1205         Action_Type doaction;                 /**< Action scheduled by http thread */
1206         int  ncycle;                          /**< The number of the current cycle */
1207         int  nstart;           /**< The number of current starts with this service */
1208         Every_T every;              /**< Timespec for when to run check of service */
1209         command_t start;                    /**< The start command for the service */
1210         command_t stop;                      /**< The stop command for the service */
1211         command_t restart;                /**< The restart command for the service */
1212         Program_T program;                            /**< Program execution check */
1213 
1214         Dependant_T dependantlist;                     /**< Dependant service list */
1215         Mail_T maillist;                       /**< Alert notification mailinglist */
1216 
1217         /** Test rules and event handlers */
1218         ActionRate_T actionratelist;                    /**< ActionRate check list */
1219         Checksum_T  checksum;                                  /**< Checksum check */
1220         FileSystem_T filesystemlist;                    /**< Filesystem check list */
1221         Icmp_T      icmplist;                                 /**< ICMP check list */
1222         Perm_T      perm;                                    /**< Permission check */
1223         Port_T      portlist;                            /**< Portnumbers to check */
1224         Port_T      socketlist;                         /**< Unix sockets to check */
1225         Resource_T  resourcelist;                         /**< Resource check list */
1226         Size_T      sizelist;                                 /**< Size check list */
1227         Uptime_T    uptimelist;                             /**< Uptime check list */
1228         Match_T     matchlist;                             /**< Content Match list */
1229         Match_T     matchignorelist;                /**< Content Match ignore list */
1230         Timestamp_T timestamplist;                       /**< Timestamp check list */
1231         Pid_T       pidlist;                                   /**< Pid check list */
1232         Pid_T       ppidlist;                                 /**< PPid check list */
1233         Status_T    statuslist;           /**< Program execution status check list */
1234         FsFlag_T    fsflaglist;           /**< Action upon filesystem flags change */
1235         NonExist_T  nonexistlist;      /**< Actions if test subject does not exist */
1236         Exist_T     existlist;                  /**< Actions if test subject exist */
1237         Uid_T       uid;                                            /**< Uid check */
1238         Uid_T       euid;                                 /**< Effective Uid check */
1239         Gid_T       gid;                                            /**< Gid check */
1240         SecurityAttribute_T secattrlist;             /**< Security attributes list */
1241         Filedescriptors_T filedescriptorslist;                   /**< Filedescriptors list */
1242         LinkStatus_T linkstatuslist;                 /**< Network link status list */
1243         LinkSpeed_T linkspeedlist;                    /**< Network link speed list */
1244         LinkSaturation_T linksaturationlist;     /**< Network link saturation list */
1245         Bandwidth_T uploadbyteslist;                  /**< Upload bytes check list */
1246         Bandwidth_T uploadpacketslist;              /**< Upload packets check list */
1247         Bandwidth_T downloadbyteslist;              /**< Download bytes check list */
1248         Bandwidth_T downloadpacketslist;          /**< Download packets check list */
1249 
1250         /** General event handlers */
1251         EventAction_T action_DATA;       /**< Description of the action upon event */
1252         EventAction_T action_EXEC;       /**< Description of the action upon event */
1253         EventAction_T action_INVALID;    /**< Description of the action upon event */
1254 
1255         /** Internal monit events */
1256         EventAction_T action_MONIT_START;  /**< Monit instance start/reload action */
1257         EventAction_T action_MONIT_STOP;           /**< Monit instance stop action */
1258         EventAction_T action_ACTION;           /**< Action requested by CLI or GUI */
1259 
1260         /** Runtime parameters */
1261         int                error;                          /**< Error flags bitmap */
1262         int                error_hint;   /**< Failed/Changed hint for error bitmap */
1263         union Info_T       inf;                          /**< Service check result */
1264         struct timeval     collected;                /**< When were data collected */ //FIXME: replace with unsigned long long? (all places where timeval is used) ... Time_milli()?
1265 
1266         /** Events */
1267         struct myevent {
1268                 #define           EVENT_VERSION  4      /**< The event structure version */
1269                 long              id;                      /**< The event identification */
1270                 struct timeval    collected;                /**< When the event occurred */
1271                 struct Service_T *source;                              /**< Event source */
1272                 Monitor_Mode      mode;             /**< Monitoring mode for the service */
1273                 Service_Type      type;                      /**< Monitored service type */
1274                 State_Type        state;                                 /**< Test state */
1275                 bool         state_changed;              /**< true if state changed */
1276                 Handler_Type      flag;                     /**< The handlers state flag */
1277                 long long         state_map;           /**< Event bitmap for last cycles */
1278                 unsigned int      count;                             /**< The event rate */
1279                 char             *message;    /**< Optional message describing the event */
1280                 EventAction_T     action;           /**< Description of the event action */
1281                 /** For internal use */
1282                 struct myevent   *next;                         /**< next event in chain */
1283         } *eventlist;                                     /**< Pending events list */
1284 
1285         /** Context specific parameters */
1286         char *path;  /**< Path to the filesys, file, directory or process pid file */
1287 
1288         /** For internal use */
1289         Mutex_T mutex;                  /**< Mutex used for action synchronization */
1290         struct Service_T *next;                         /**< next service in chain */
1291         struct Service_T *next_conf;      /**< next service according to conf file */
1292         struct Service_T *next_depend;           /**< next depend service in chain */
1293 } *Service_T;
1294 
1295 
1296 typedef struct myevent *Event_T;
1297 
1298 
1299 typedef struct ServiceGroup_T {
1300         char *name;                                     /**< name of service group */
1301         List_T members;                                 /**< Service group members */
1302 
1303         /** For internal use */
1304         struct ServiceGroup_T *next;              /**< next service group in chain */
1305 } *ServiceGroup_T;
1306 
1307 
1308 /** Data for application runtime */
1309 struct Run_T {
1310         uint8_t debug;                                            /**< Debug level */
1311         volatile Run_Flags flags;
1312         Handler_Type handler_flag;                    /**< The handlers state flag */
1313         Onreboot_Type onreboot;
1314         struct {
1315                 char *control;            /**< The file to read configuration from */
1316                 char *log;                     /**< The file to write logdata into */
1317                 char *pid;                              /**< This programs pidfile */
1318                 char *id;                       /**< The file with unique monit id */
1319                 char *state;            /**< The file with the saved runtime state */
1320         } files;
1321         char *mygroup;                              /**< Group Name of the Service */
1322         MD_T id;                                              /**< Unique monit id */
1323         Limits_T limits;                                       /**< Default limits */
1324         struct SslOptions_T ssl;                          /**< Default SSL options */
1325         int  polltime;        /**< In daemon mode, the sleeptime (sec) between run */
1326         int  startdelay;  /**< the sleeptime [s] on first start after machine boot */
1327         int  facility;              /** The facility to use when running openlog() */
1328         int  eventlist_slots;          /**< The event queue size - number of slots */
1329         int mailserver_timeout; /**< Connect and read timeout ms for a SMTP server */
1330         time_t incarnation;              /**< Unique ID for running monit instance */
1331         int  handler_queue[Handler_Max + 1];       /**< The handlers queue counter */
1332         Service_T system;                          /**< The general system service */
1333         char *eventlist_dir;                   /**< The event queue base directory */
1334 
1335         /** An object holding Monit HTTP interface setup */
1336         struct {
1337                 Httpd_Flags flags;
1338                 struct {
1339                         struct {
1340                                 int  port;
1341                                 char *address;
1342                                 struct SslOptions_T ssl;
1343                         } net;
1344                         struct {
1345                                 int uid;
1346                                 int gid;
1347                                 int permission;
1348                                 char *path;
1349                         } unix;
1350                 } socket;
1351                 Auth_T credentials;
1352         } httpd;
1353 
1354         /** An object holding program relevant "environment" data, see: env.c */
1355         struct myenvironment {
1356                 char *user;             /**< The the effective user running this program */
1357                 char *home;                                    /**< Users home directory */
1358                 char *cwd;                                /**< Current working directory */
1359         } Env;
1360 
1361         char *mail_hostname;    /**< Used in HELO/EHLO/MessageID when sending mail */
1362         Mail_T maillist;                /**< Global alert notification mailinglist */
1363         MailServer_T mailservers;    /**< List of MTAs used for alert notification */
1364         Mmonit_T mmonits;        /**< Event notification and status receivers list */
1365         Auth_T mmonitcredentials;     /**< Pointer to selected credentials or NULL */
1366         /** User selected standard mail format */
1367         struct myformat {
1368                 Address_T from;                      /**< The standard mail from address */
1369                 Address_T replyto;                         /**< Optional reply-to header */
1370                 char *subject;                            /**< The standard mail subject */
1371                 char *message;                            /**< The standard mail message */
1372         } MailFormat;
1373 
1374         Mutex_T mutex;            /**< Mutex used for service data synchronization */
1375 };
1376 
1377 
1378 /* -------------------------------------------------------- Global variables */
1379 
1380 
1381 extern const char    *prog;
1382 extern struct Run_T   Run;
1383 extern Service_T      servicelist;
1384 extern Service_T      servicelist_conf;
1385 extern ServiceGroup_T servicegrouplist;
1386 extern SystemInfo_T   systeminfo;
1387 
1388 extern const char *actionnames[];
1389 extern const char *modenames[];
1390 extern const char *onrebootnames[];
1391 extern const char *checksumnames[];
1392 extern const char *operatornames[];
1393 extern const char *operatorshortnames[];
1394 extern const char *servicetypes[];
1395 extern const char *pathnames[];
1396 extern const char *icmpnames[];
1397 extern const char *socketnames[];
1398 extern const char *timestampnames[];
1399 extern const char *httpmethod[];
1400 
1401 
1402 /* ------------------------------------------------------- Public prototypes */
1403 
1404 #include "util.h"
1405 #include "file.h"
1406 
1407 // libmonit
1408 #include "system/Mem.h"
1409 
1410 
1411 /* FIXME: move remaining prototypes into separate header-files */
1412 
1413 bool parse(char *);
1414 bool control_service(const char *, Action_Type);
1415 bool control_service_string(List_T, const char *);
1416 void spawn(Service_T, command_t, Event_T);
1417 bool Log_init(void);
1418 void Log_emergency(const char *, ...) __attribute__((format (printf, 1, 2)));
1419 void Log_alert(const char *, ...) __attribute__((format (printf, 1, 2)));
1420 void Log_critical(const char *, ...) __attribute__((format (printf, 1, 2)));
1421 void Log_error(const char *, ...) __attribute__((format (printf, 1, 2)));
1422 void Log_warning(const char *, ...) __attribute__((format (printf, 1, 2)));
1423 void Log_notice(const char *, ...) __attribute__((format (printf, 1, 2)));
1424 void Log_info(const char *, ...) __attribute__((format (printf, 1, 2)));
1425 void Log_debug(const char *, ...) __attribute__((format (printf, 1, 2)));
1426 void Log_vemergency(const char *, va_list ap) __attribute__((format (printf, 1, 0)));
1427 void Log_valert(const char *, va_list ap) __attribute__((format (printf, 1, 0)));
1428 void Log_vcritical(const char *, va_list ap) __attribute__((format (printf, 1, 0)));
1429 void Log_verror(const char *, va_list ap) __attribute__((format (printf, 1, 0)));
1430 void Log_vwarning(const char *,va_list ap) __attribute__((format (printf, 1, 0)));
1431 void Log_vnotice(const char *, va_list ap) __attribute__((format (printf, 1, 0)));
1432 void Log_vinfo(const char *, va_list ap) __attribute__((format (printf, 1, 0)));
1433 void Log_vdebug(const char *, va_list ap) __attribute__((format (printf, 1, 0)));
1434 void Log_abort_handler(const char *s, va_list ap) __attribute__((format (printf, 1, 0))) __attribute__((noreturn));
1435 void Log_close(void);
1436 int   validate(void);
1437 void  daemonize(void);
1438 void  gc(void);
1439 void  gc_mail_list(Mail_T *);
1440 void  gccmd(command_t *);
1441 void  gc_event(Event_T *e);
1442 bool kill_daemon(int);
1443 int   exist_daemon(void);
1444 bool sendmail(Mail_T);
1445 void  init_env(void);
1446 void  monit_http(Httpd_Action);
1447 bool can_http(void);
1448 void set_signal_block(void);
1449 State_Type check_process(Service_T);
1450 State_Type check_filesystem(Service_T);
1451 State_Type check_file(Service_T);
1452 State_Type check_directory(Service_T);
1453 State_Type check_remote_host(Service_T);
1454 State_Type check_system(Service_T);
1455 State_Type check_fifo(Service_T);
1456 State_Type check_program(Service_T);
1457 State_Type check_net(Service_T);
1458 int  check_URL(Service_T s);
1459 void status_xml(StringBuffer_T, Event_T, int, const char *);
1460 bool  do_wakeupcall(void);
1461 bool interrupt(void);
1462 
1463 #endif
1464