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