-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon.c
398 lines (337 loc) · 10.2 KB
/
daemon.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*
* Author: Peter Nagy
*
* File: daemon.c
* Project: Simple linux daemon
* Description: Simple linux daemon communicating over network using TCP protocol
* Date: 13.6.2017
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <syslog.h>
/* Macro for unused variables */
#define UNUSED(x) (void)(x)
/* Error codes */
#define ERR_OK 0
#define ERR_MEM 1
#define ERR_INTERNAL 2
#define ERR_ARG 3
#define ERR_COMM 4
#define PORT_NUM 5001
#define BUFFER_SIZE 512
#define TOK_DELIM " \t\r\n\a"
/* Global variables */
int listenfd = 0, connfd = 0;
/* CPU usage info - parsed from /proc/stat */
struct sys_cpu_info {
long long user;
long long nice;
long long system;
long long idle;
long long iowait;
long long irq;
long long softirq;
long long steal;
long long guest;
long long guest_nice;
};
/* Prev version of measured CPU times */
long long prev_cpu_idle_time = 0;
long long prev_cpu_non_idle_time = 0;
/* Memory info - parsed from /proc/meminfo */
struct sys_mem_info {
unsigned long mem_total;
unsigned long mem_free;
unsigned long mem_available;
unsigned long mem_buffered;
unsigned long mem_cached;
};
/**
* @brief Gets the total CPU usage percentage computed from /proc/stat file
* @return The total CPU usage
*/
char *get_cpu_usage()
{
char *result;
struct sys_cpu_info cpuinfo;
/* Open /proc/stat file */
FILE *cpu_f = fopen("/proc/stat", "r");
if (cpu_f == NULL) {
syslog(LOG_ERR, "Could not open /proc/stat file");
return NULL;
}
/* Read first line of the file */
char buffer[1024];
char *ret = fgets(buffer, sizeof(buffer) - 1, cpu_f);
if (ret == NULL) {
syslog(LOG_ERR, "Could not read /proc/stat file");
fclose(cpu_f);
return NULL;
}
fclose(cpu_f);
/* Parse first line of /proc/stat file */
sscanf(buffer,
"cpu %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld",
&cpuinfo.user, &cpuinfo.nice, &cpuinfo.system, &cpuinfo.idle, &cpuinfo.iowait,
&cpuinfo.irq, &cpuinfo.softirq, &cpuinfo.steal, &cpuinfo.guest, &cpuinfo.guest_nice);
/* Compute actual CPU time */
long long cpu_idle_time = cpuinfo.idle + cpuinfo.iowait;
long long cpu_non_idle_time = cpuinfo.user + cpuinfo.nice + cpuinfo.system + cpuinfo.idle
+ cpuinfo.iowait + cpuinfo.irq + cpuinfo.softirq + cpuinfo.steal;
/* CPU usage */
long long cpu_usage_time = cpu_non_idle_time + cpu_idle_time;
long long prev_cpu_usage_time = prev_cpu_non_idle_time + prev_cpu_idle_time;
/* Total usage */
long long cpu_totald = cpu_usage_time - prev_cpu_usage_time;
long long cpu_idled = cpu_idle_time - prev_cpu_idle_time;
double cpu_percentage = (double)(cpu_totald - cpu_idled) / (double)cpu_totald * 100.0;
asprintf(&result, "%.0lf%%\n", cpu_percentage);
/* Save actual cpu time to prev */
prev_cpu_idle_time = cpu_idle_time;
prev_cpu_non_idle_time = cpu_non_idle_time;
return result;
}
/**
* @brief Gets the memory usage number from a line in kB
* @param line The line from /proc/meminfo file
* @return One item from memory usage as number
*/
int get_mem_usage_num(char *line)
{
char *token;
int position = 0;
int result = 0;
token = strtok(line, TOK_DELIM);
while (token != NULL) {
/* Number is in second column in /proc/meminfo */
if (position == 1) {
result = atoi(token);
}
position++;
token = strtok(NULL, TOK_DELIM);
}
return result;
}
/**
* @brief Gets the memory usage
* @return The memory usage or NULL in case of error
*/
char *get_memory_usage()
{
FILE *mem_f;
char *line = NULL;
size_t len = 0;
struct sys_mem_info meminfo;
int mem_used;
char *result;
/* Open /proc/meminfo file */
if ((mem_f = fopen("/proc/meminfo", "r")) == NULL) {
syslog(LOG_ERR, "Could not open /proc/meminfo file");
return NULL;
}
/* Parsing only the first five lines of /proc/meminfo */
for (int i = 0; i < 5; ++i) {
if (getline(&line, &len, mem_f) == -1) {
syslog(LOG_ERR, "Could not read /proc/meminfo file");
fclose(mem_f);
return NULL;
}
switch(i) {
case 0:
meminfo.mem_total = get_mem_usage_num(line);
break;
case 1:
meminfo.mem_free = get_mem_usage_num(line);
break;
case 2:
meminfo.mem_available = get_mem_usage_num(line);
break;
case 3:
meminfo.mem_buffered = get_mem_usage_num(line);
break;
case 4:
meminfo.mem_cached = get_mem_usage_num(line);
break;
}
}
/* Compute memory usage */
mem_used = meminfo.mem_total - meminfo.mem_free - meminfo.mem_buffered - meminfo.mem_cached;
asprintf(&result, "%d kB\n", mem_used);
fclose(mem_f);
return result;
}
/**
* @brief Parse and execute received command
* @param buffer Buffer containing received buffer
* @return CPU or memory usage or NULL in case of error
*/
char *par_exec_command(char *buffer)
{
if (strncmp(buffer, "cpu\r", 4) == 0) {
return get_cpu_usage();
} else if (strncmp(buffer, "mem\r", 4) == 0) {
return get_memory_usage();
}
return NULL;
}
/**
* @brief Thread running the server
*/
void *server_run()
{
int socket_id = connfd;
char recv_buffer[BUFFER_SIZE];
memset(recv_buffer, '\0', sizeof(recv_buffer));
/* Read message from client */
if (read(socket_id, recv_buffer, sizeof(recv_buffer)) < 0) {
syslog(LOG_ERR, "Error reading socket");
return NULL;
}
/* Parse and execute received command */
char *send_buffer = par_exec_command(recv_buffer);
if (send_buffer == NULL) {
asprintf(&send_buffer, "Invalid command received!\n");
}
/* Send a reply to a client */
if ( write(socket_id, send_buffer, strlen(send_buffer) * sizeof(char) ) < 0 ) {
syslog(LOG_ERR, "Error writing to socket");
free(send_buffer);
return NULL;
}
free(send_buffer);
/* close connection, clean up socket */
if (close(socket_id) < 0) {
syslog(LOG_ERR, "Error closing socket");
return NULL;
}
return NULL;
}
/**
* @brief Deamonize the running program
*/
static void daemonize()
{
pid_t pid;
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* On success - terminate parent */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* On success - The child process becomes session leader */
if (setsid() < 0) {
exit(EXIT_FAILURE);
}
/* Catch, ignore and handle signals */
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
/* Fork for the second time */
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* On success - Let the parent terminate */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* Close all open file descriptors */
for (int x = sysconf(_SC_OPEN_MAX); x >= 0; x--) {
close (x);
}
/* Open the log file */
openlog("simple_linux_daemon", LOG_PID, LOG_DAEMON);
}
/**
* @brief Handles a TCP connection properties
* @param[in] port_num The port number
* @param sin The sine
* @param listenfd The listenfd
* @return Returns ERR_OK or error code in case of error
*/
int create_connection(const int port_num, struct sockaddr_in *sin, int *listenfd)
{
// Create socket
if ( (*listenfd = socket(PF_INET, SOCK_STREAM, 0 ) ) < 0) {
syslog(LOG_ERR, "Error creating socket");
return ERR_COMM;
}
sin->sin_family = PF_INET; /* set protocol family to Internet */
sin->sin_port = htons(port_num); /* set port no. */
sin->sin_addr.s_addr = INADDR_ANY; /* set IP addr to any interface */
// Bind socket
if (bind(*listenfd, (struct sockaddr *)sin, sizeof(*sin) ) < 0 ) {
syslog(LOG_ERR, "Error on bind");
return ERR_COMM;
}
// Pasive open - listen
if (listen(*listenfd, 5)) {
syslog(LOG_ERR, "Error on listen");
return ERR_COMM;
}
return ERR_OK;
}
/**
* @brief Main function
* @param[in] argc The number of problem agruments
* @param argv Program arguments
* @return Returns ERR_OK or error code in case of error
*/
int main(int argc, char const *argv[])
{
unsigned int sinlen;
struct sockaddr_in sin;
/* Thread variables */
pthread_t thread_id;
int status;
int res;
pthread_attr_t attr;
/* Parse arguments - no agruments needed or alowed */
if (argc > 1) {
syslog(LOG_ERR, "No arguments allowed! Run without arguments.");
return ERR_ARG;
}
UNUSED(argv);
/* Daemonize process */
daemonize();
/* Create and bind socket */
if (create_connection(PORT_NUM, &sin, &listenfd) != ERR_OK) {
return ERR_COMM;
}
sinlen = sizeof(sin);
/* Creating implicit attribute */
if ((res = pthread_attr_init(&attr)) != 0) {
syslog(LOG_ERR, "pthread_attr_init() err %d\n", res);
return ERR_INTERNAL;
}
/* Type of thread in atributes */
if ((res = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) != 0) {
syslog(LOG_ERR, "pthread_attr_setdetachstate() err %d\n", res);
return ERR_INTERNAL;
}
/* Server infinite loop */
while(1) {
/* accepting new connection request from client,
socket id for the new connection is returned in connfd */
if ((connfd = accept(listenfd, (struct sockaddr *) &sin, &sinlen)) < 0) {
fprintf(stderr, "Error on accept\n");
return ERR_COMM;
}
/* Create a new thread */
status = pthread_create(&thread_id, &attr, &server_run, NULL);
if (status != 0) {
return ERR_MEM;
}
}
closelog();
return ERR_OK;
}