Imported Upstream version 2.7
[ossec-hids.git] / src / logcollector / read_fullcommand.c
1 /* @(#) $Id: ./src/logcollector/read_fullcommand.c, 2011/09/08 dcid Exp $
2  */
3
4 /* Copyright (C) 2010 Trend Micro Inc.
5  * All right reserved.
6  *
7  * This program is a free software; you can redistribute it
8  * and/or modify it under the terms of the GNU General Public
9  * License (version 2) as published by the FSF - Free Software
10  * Foundation
11  */
12
13 /* Read the syslog */
14
15
16 #include "shared.h"
17 #include "logcollector.h"
18
19
20
21 /* Read Output of commands */
22 void *read_fullcommand(int pos, int *rc, int drop_it)
23 {
24     int n = 0;
25     int cmd_size = 0;
26     char *p;
27     char str[OS_MAXSTR+1];
28     char strfinal[OS_MAXSTR+1];
29
30     FILE *cmd_output;
31
32     str[OS_MAXSTR]= '\0';
33     strfinal[OS_MAXSTR]= '\0';
34     *rc = 0;
35
36
37     debug2("%s: DEBUG: Running full command '%s'", ARGV0, logff[pos].command);
38
39
40     cmd_output = popen(logff[pos].command, "r");
41     if(!cmd_output)
42     {
43         merror("%s: ERROR: Unable to execute command: '%s'.",
44                ARGV0, logff[pos].command);
45
46         logff[pos].command = NULL;
47     }
48
49
50     snprintf(str, 256, "ossec: output: '%s':\n",
51                 (NULL != logff[pos].alias)
52                 ? logff[pos].alias
53                 : logff[pos].command);
54     cmd_size = strlen(str);
55
56     n = fread(str + cmd_size, 1, OS_MAXSTR - OS_LOG_HEADER - 256, cmd_output);
57     if(n > 0)
58     {
59         str[cmd_size +n] = '\0';
60
61         /* Getting the last occurence of \n */
62         if ((p = strrchr(str, '\n')) != NULL)
63         {
64             *p = '\0';
65         }
66
67
68         debug2("%s: DEBUG: Reading command message: '%s'", ARGV0, str);
69
70         /* Removing empty lines. */
71         n = 0;
72         p = str;
73         while(*p != '\0')
74         {
75             if(p[0] == '\r')
76             {
77                 p++;
78                 continue;
79             }
80
81             if(p[0] == '\n' && p[1] == '\n')
82             {
83                 p++;
84             }
85             strfinal[n] = *p;
86             n++;
87             p++;
88         }
89         strfinal[n] = '\0';
90
91
92         /* Sending message to queue */
93         if(drop_it == 0)
94         {
95             if(SendMSG(logr_queue,strfinal,
96                         (NULL != logff[pos].alias) ? logff[pos].alias : logff[pos].command,
97                         LOCALFILE_MQ) < 0)
98             {
99                 merror(QUEUE_SEND, ARGV0);
100                 if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0)
101                 {
102                     ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH);
103                 }
104             }
105         }
106     }
107
108     pclose(cmd_output);
109
110     return(NULL);
111 }
112
113 /* EOF */