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