Imported Upstream version 2.7
[ossec-hids.git] / src / logcollector / read_command.c
1 /* @(#) $Id: ./src/logcollector/read_command.c, 2011/09/08 dcid Exp $
2  */
3
4 /* Copyright (C) 2009 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_command(int pos, int *rc, int drop_it)
23 {
24     int cmd_size = 0;
25     char *p;
26     char str[OS_MAXSTR+1];
27
28     FILE *cmd_output;
29
30     str[OS_MAXSTR]= '\0';
31     *rc = 0;
32
33
34     debug2("%s: DEBUG: Running command '%s'", ARGV0, logff[pos].command);
35
36
37     cmd_output = popen(logff[pos].command, "r");
38     if(!cmd_output)
39     {
40         merror("%s: ERROR: Unable to execute command: '%s'.",
41                ARGV0, logff[pos].command);
42
43         logff[pos].command = NULL;
44     }
45
46
47     snprintf(str, 256, "ossec: output: '%s': ",
48              (NULL != logff[pos].alias)
49              ? logff[pos].alias
50              : logff[pos].command);
51     cmd_size = strlen(str);
52
53
54     while(fgets(str + cmd_size, OS_MAXSTR - OS_LOG_HEADER - 256, cmd_output) != NULL)
55     {
56         /* Getting the last occurence of \n */
57         if ((p = strrchr(str, '\n')) != NULL)
58         {
59             *p = '\0';
60         }
61
62         /* Removing empty lines. */
63         #ifdef WIN32
64         if(str[0] == '\r' && str[1] == '\0')
65         {
66             continue;
67         }
68         #endif
69         if(str[0] == '\0')
70         {
71             continue;
72         }
73
74
75         debug2("%s: DEBUG: Reading command message: '%s'", ARGV0, str);
76
77
78         /* Sending message to queue */
79         if(drop_it == 0)
80         {
81             if(SendMSG(logr_queue,str,
82                         (NULL != logff[pos].alias) ? logff[pos].alias : logff[pos].command,
83                         LOCALFILE_MQ) < 0)
84             {
85                 merror(QUEUE_SEND, ARGV0);
86                 if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0)
87                 {
88                     ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH);
89                 }
90             }
91         }
92
93         continue;
94     }
95
96     pclose(cmd_output);
97
98     return(NULL);
99 }
100
101 /* EOF */