new upstream release (3.3.0); modify package compatibility for Stretch
[ossec-hids.git] / src / logcollector / read_command.c
1 /* Copyright (C) 2009 Trend Micro Inc.
2  * All right 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 #include "logcollector.h"
12
13
14 /* Read Output of commands */
15 void *read_command(int pos, int *rc, int drop_it)
16 {
17     size_t cmd_size = 0;
18     char *p;
19     char str[OS_MAXSTR + 1];
20     FILE *cmd_output;
21
22     str[OS_MAXSTR] = '\0';
23     *rc = 0;
24
25     debug2("%s: DEBUG: Running command '%s'", ARGV0, logff[pos].command);
26
27     cmd_output = popen(logff[pos].command, "r");
28     if (!cmd_output) {
29         merror("%s: ERROR: Unable to execute command: '%s'.",
30                ARGV0, logff[pos].command);
31
32         logff[pos].command = NULL;
33         return (NULL);
34     }
35
36     snprintf(str, 256, "ossec: output: '%s': ",
37              (NULL != logff[pos].alias)
38              ? logff[pos].alias
39              : logff[pos].command);
40     cmd_size = strlen(str);
41
42     while (fgets(str + cmd_size, OS_MAXSTR - OS_LOG_HEADER - 256, cmd_output) != NULL) {
43         /* Get the last occurrence of \n */
44         if ((p = strrchr(str, '\n')) != NULL) {
45             *p = '\0';
46         }
47
48         /* Remove empty lines */
49 #ifdef WIN32
50         if (str[0] == '\r' && str[1] == '\0') {
51             continue;
52         }
53 #endif
54         if (str[0] == '\0') {
55             continue;
56         }
57
58         debug2("%s: DEBUG: Reading command message: '%s'", ARGV0, str);
59
60         /* Send message to queue */
61         if (drop_it == 0) {
62             if (SendMSG(logr_queue, str,
63                         (NULL != logff[pos].alias) ? logff[pos].alias : logff[pos].command,
64                         LOCALFILE_MQ) < 0) {
65                 merror(QUEUE_SEND, ARGV0);
66                 if ((logr_queue = StartMQ(DEFAULTQPATH, WRITE)) < 0) {
67                     ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH);
68                 }
69             }
70         }
71
72         continue;
73     }
74
75     pclose(cmd_output);
76
77     return (NULL);
78 }
79