new upstream release (3.3.0); modify package compatibility for Stretch
[ossec-hids.git] / src / shared / wait_op.c
1 /* Copyright (C) 2009 Trend Micro Inc.
2  * All rights reserved.
3  *
4  * This program is a free software; you can redistribute it
5  * and/or modify it under the terms of the GNU General Public
6  * License (version 2) as published by the FSF - Free Software
7  * Foundation
8  */
9
10 #include "shared.h"
11
12 #define LOCK_LOOP   5
13
14 static int __wait_lock = 0;
15
16
17 /* Create global lock */
18 void os_setwait()
19 {
20     FILE *fp = NULL;
21
22     /* For same threads */
23     __wait_lock = 1;
24
25     if (isChroot()) {
26         fp = fopen(WAIT_FILE, "w");
27     } else {
28         fp = fopen(WAIT_FILE_PATH, "w");
29     }
30
31     if (fp) {
32         fprintf(fp, "l");
33         fclose(fp);
34     }
35
36     return;
37 }
38
39 /* Remove global lock */
40 void os_delwait()
41 {
42     __wait_lock = 0;
43
44     if (isChroot()) {
45         unlink(WAIT_FILE);
46     } else {
47         unlink(WAIT_FILE_PATH);
48     }
49     return;
50 }
51
52 /* Check for the wait file. If present, wait.
53  * Works as a simple inter process lock (only the main
54  * process is allowed to lock).
55  */
56 #ifdef WIN32
57 void os_wait()
58 {
59     if (!__wait_lock) {
60         return;
61     }
62
63     /* Wait until the lock is gone */
64     verbose(WAITING_MSG, __local_name);
65     while (1) {
66         if (!__wait_lock) {
67             break;
68         }
69
70         /* Sleep LOCK_LOOP seconds and check if lock is gone */
71         sleep(LOCK_LOOP);
72     }
73
74     verbose(WAITING_FREE, __local_name);
75     return;
76
77 }
78
79 #else /* !WIN32 */
80
81 void os_wait()
82 {
83     struct stat file_status;
84
85     /* If the wait file is not present, keep going */
86     if (isChroot()) {
87         if (stat(WAIT_FILE, &file_status) == -1) {
88             return;
89         }
90     } else {
91         if (stat(WAIT_FILE_PATH, &file_status) == -1) {
92             return;
93         }
94     }
95
96     /* Wait until the lock is gone */
97     verbose(WAITING_MSG, __local_name);
98     while (1) {
99         if (isChroot()) {
100             if (stat(WAIT_FILE, &file_status) == -1) {
101                 break;
102             }
103         } else {
104             if (stat(WAIT_FILE_PATH, &file_status) == -1) {
105                 break;
106             }
107         }
108
109         /* Sleep LOCK_LOOP seconds and check if lock is gone */
110         sleep(LOCK_LOOP);
111     }
112
113     verbose(WAITING_FREE, __local_name);
114     return;
115 }
116
117 #endif /* !WIN32 */
118