-
Notifications
You must be signed in to change notification settings - Fork 0
/
configuration-manager.c
79 lines (74 loc) · 2.42 KB
/
configuration-manager.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/* jnm 20140809 */
/* Make sure to use absolute paths only! */
const char configtest[] = "/usr/sbin/apache2ctl configtest";
const char graceful[] = "/usr/sbin/apache2ctl graceful";
const char maintenance_conf[] = "/opt/maintenance/maintenance.conf";
const char normal_conf[] = "/opt/maintenance/normal.conf";
const char active_conf[] = "/opt/maintenance/active.conf";
const char address_marker[] = "{address}";
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <regex.h>
int main(int argc, char* argv[])
{
const char* source_path;
char* address = NULL;
if(argc == 2 && strcmp(argv[1], "normal") == 0)
source_path = normal_conf;
else if(argc == 3 && strcmp(argv[1], "maintenance") == 0)
{
regex_t regex;
address = argv[2];
regcomp(®ex, "^\\([0-9]\\{1,3\\}\\.\\)\\{3\\}[0-9]\\{1,3\\}$", 0);
if(regexec(®ex, address, 0, NULL, 0) == REG_NOMATCH)
{
fprintf(stderr, "Invalid address.\n");
return 1;
}
source_path = maintenance_conf;
}
else
{
fprintf(stderr, "Usage: %s maintenance|normal [address]\n", argv[0]);
return 1;
}
FILE* source = fopen(source_path, "r");
if(source == NULL)
{
fprintf(stderr, "Failed to open source configuration file.\n");
return 1;
}
FILE* destination = fopen(active_conf, "w");
if(destination == NULL)
{
fprintf(stderr, "Failed to open destination configuration file.\n");
fclose(source);
return 1;
}
char* line = NULL;
size_t line_size = 0;
ssize_t read_length;
char* marker_location = NULL;
while((read_length = getline(&line, &line_size, source)) != -1)
{
if(address != NULL && (marker_location = strstr(line, address_marker)) != NULL)
{
/* Write the part of the line preceeding the marker */
fwrite(line, sizeof(char), marker_location - line, destination);
/* Write the address */
fprintf(destination, "%s", address);
/* Write the part of the line following the marker */
fprintf(destination, "%s", marker_location + strlen(address_marker));
}
else
fwrite(line, sizeof(char), read_length, destination);
}
if(line)
free(line);
fclose(source);
fclose(destination);
if(system(configtest) == 0)
return system(graceful);
return 1;
}