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