ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/i-scream/projects/cms/source/ihost/ihost.c
Revision: 1.53
Committed: Sat Sep 24 13:30:40 2005 UTC (19 years, 2 months ago) by tdb
Content type: text/plain
Branch: MAIN
Changes since 1.52: +570 -96 lines
Log Message:
Add WIN32 support via MINGW. We'll need to add stuff to the README file
about what this requires to build.

All the hard work done by: skel

File Contents

# User Rev Content
1 tdb 1.11 /*
2     * i-scream central monitoring system
3 tdb 1.42 * http://www.i-scream.org
4 tdb 1.52 * Copyright (C) 2000-2004 i-scream
5 tdb 1.11 *
6     * This program is free software; you can redistribute it and/or
7     * modify it under the terms of the GNU General Public License
8     * as published by the Free Software Foundation; either version 2
9     * of the License, or (at your option) any later version.
10     *
11     * This program is distributed in the hope that it will be useful,
12     * but WITHOUT ANY WARRANTY; without even the implied warranty of
13     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14     * GNU General Public License for more details.
15     *
16     * You should have received a copy of the GNU General Public License
17     * along with this program; if not, write to the Free Software
18     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19     */
20    
21 tdb 1.26 #ifdef HAVE_CONFIG_H
22     #include "config.h"
23     #endif
24    
25 pajs 1.1 #include <stdio.h>
26     #include <stdlib.h>
27 pajs 1.28 #include <unistd.h>
28     #include <string.h>
29 pajs 1.18 #include <sys/types.h>
30 pajs 1.28 #include <stdarg.h>
31     #include <errno.h>
32 tdb 1.53 #ifndef WIN32
33     #include <sys/socket.h>
34 pajs 1.1 #include <netdb.h>
35 pajs 1.40 #include <netinet/in.h>
36 tdb 1.53 #else
37     #include <winsock2.h>
38     #include <getopt.h>
39     #endif
40 tdb 1.51 #include <time.h>
41 pajs 1.28
42 tdb 1.39 #include <ukcprog.h>
43     #include <statgrab.h>
44 pajs 1.1
45 pajs 1.28 #define LOG_CRIT 0
46     #define LOG_ERR 1
47 tdb 1.51 #define LOG_INFO 2
48 pajs 1.28 #define LOG_DEBUG 3
49    
50 tdb 1.53 #define SERVICENAME "ihost"
51    
52     /* Windows printf does not understand %lld, so we have to use %I64d */
53     #ifdef WIN32
54     #define LLD "%I64d"
55     #define OPTSTRING "vVn:i:s:p:w:h"
56     #define SLEEP 10000
57     #else
58     #define LLD "%lld"
59     #define OPTSTRING "vfVn:i:s:p:h"
60     #define SLEEP 10
61     #endif
62    
63     /* The "socket" */
64     #ifdef WIN32
65     #define IHOST_SOCKET SOCKET
66     #define CLOSESOCKET(socket) closesocket(socket)
67     #else
68     #define IHOST_SOCKET FILE *
69     #define CLOSESOCKET(socket) fclose(socket)
70     #endif
71    
72 pajs 1.1 typedef struct{
73 pajs 1.28 int filtermanager_port;
74     char *filtermanager_host;
75    
76     char *host_ip;
77     char *host_fqdn;
78 pajs 1.41 int preset_fqdn;
79     int preset_ip;
80 pajs 1.16
81 pajs 1.1 char *server_fqdn;
82     int server_udp_port;
83 tdb 1.51
84 pajs 1.28 /* Weird stuff iscream wants sent to it */
85 pajs 1.4 char *last_modified;
86 pajs 1.28 char *file_list;
87    
88 pajs 1.1 int udp_update_time;
89 pajs 1.28
90     time_t config_ttl;
91 pajs 1.1
92     }ihost_state_t;
93    
94 pajs 1.28 typedef struct{
95 tdb 1.51 int verbose;
96     int daemon;
97 pajs 1.28
98     FILE *log;
99 tdb 1.51 }ihost_config_t;
100 pajs 1.28
101     typedef struct{
102     struct sockaddr_in addr;
103     int sock;
104     }udp_sockinfo_t;
105    
106     ihost_config_t ihost_config;
107 tdb 1.53 ihost_state_t ihost_state;
108 pajs 1.28
109 pajs 1.33 extern int errno;
110    
111 tdb 1.53 #ifdef WIN32
112     int run_server = 1;
113     int run_as_service = 0;
114     SERVICE_STATUS service_status;
115     SERVICE_STATUS_HANDLE hstatus;
116     #endif
117    
118 tdb 1.34 /* Taken from the OpenSSH code. Its licence included in function.*/
119     #ifndef HAVE_STRLCAT
120 pajs 1.33
121     /*
122     * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
123     * All rights reserved.
124     *
125     * Redistribution and use in source and binary forms, with or without
126     * modification, are permitted provided that the following conditions
127     * are met:
128     * 1. Redistributions of source code must retain the above copyright
129     * notice, this list of conditions and the following disclaimer.
130     * 2. Redistributions in binary form must reproduce the above copyright
131     * notice, this list of conditions and the following disclaimer in the
132     * documentation and/or other materials provided with the distribution.
133     * 3. The name of the author may not be used to endorse or promote products
134     * derived from this software without specific prior written permission.
135     *
136     * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
137     * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
138     * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
139     * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
140     * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
141     * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
142     * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
143     * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
144     * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
145     * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
146     */
147 tdb 1.34
148 pajs 1.33 /*
149     * Appends src to string dst of size siz (unlike strncat, siz is the
150     * full size of dst, not space left). At most siz-1 characters
151     * will be copied. Always NUL terminates (unless siz <= strlen(dst)).
152     * Returns strlen(src) + MIN(siz, strlen(initial dst)).
153     * If retval >= siz, truncation occurred.
154     */
155     size_t
156     strlcat(dst, src, siz)
157 tdb 1.51 char *dst;
158     const char *src;
159     size_t siz;
160 pajs 1.33 {
161 tdb 1.51 register char *d = dst;
162     register const char *s = src;
163     register size_t n = siz;
164     size_t dlen;
165    
166     /* Find the end of dst and adjust bytes left but don't go past end */
167     while (n-- != 0 && *d != '\0')
168     d++;
169     dlen = d - dst;
170     n = siz - dlen;
171    
172     if (n == 0)
173     return(dlen + strlen(s));
174     while (*s != '\0') {
175     if (n != 1) {
176     *d++ = *s;
177     n--;
178     }
179     s++;
180     }
181     *d = '\0';
182 pajs 1.33
183 tdb 1.51 return(dlen + (s - src)); /* count does not include NUL */
184 pajs 1.33 }
185    
186 tdb 1.34 #endif
187     /* End strlcat function taken from OpenSSH */
188 pajs 1.33
189 pajs 1.28 void log_msg(int level, char *format, ...){
190     int cur_errno;
191     va_list ap;
192    
193     cur_errno=errno;
194    
195     if(level<=ihost_config.verbose){
196     va_start(ap, format);
197     vfprintf(ihost_config.log, format, ap);
198     va_end(ap);
199     if(level==LOG_CRIT){
200     fprintf(ihost_config.log, " (%s)\n", strerror(cur_errno));
201 pajs 1.18 }else{
202 pajs 1.28 fprintf(ihost_config.log, "\n");
203 pajs 1.18 }
204 pajs 1.37 fflush(ihost_config.log);
205 pajs 1.28 }
206 pajs 1.18 }
207    
208 pajs 1.28 int create_udp_sockinfo(udp_sockinfo_t *udp_sockinfo, char *hostname, int port){
209    
210     struct in_addr haddr;
211    
212     log_msg(LOG_DEBUG, "Resolving name for udp connection");
213     if(get_host_addr(hostname, &haddr) != 0){
214     log_msg(LOG_CRIT, "Failed to lookup name");
215     return 1;
216     }
217 pajs 1.1
218 pajs 1.28 if((udp_sockinfo->sock=socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0){
219     log_msg(LOG_CRIT, "Failed to create UDP socket");
220     return 1;
221 pajs 1.1 }
222    
223 pajs 1.28 memset(&(udp_sockinfo->addr), 0, sizeof(struct sockaddr_in));
224     udp_sockinfo->addr.sin_family=AF_INET;
225     memcpy((char *)&(udp_sockinfo->addr.sin_addr), &haddr, sizeof(haddr));
226     udp_sockinfo->addr.sin_port = htons(port);
227 pajs 1.1
228 pajs 1.28 log_msg(LOG_DEBUG, "Socket created");
229     return 0;
230     }
231    
232 tdb 1.53 IHOST_SOCKET create_tcp_connection(char *hostname, int port){
233     #ifdef WIN32
234     SOCKET sock;
235     #else
236 pajs 1.28 int sock;
237 tdb 1.53 #endif
238 pajs 1.28 struct sockaddr_in addr;
239     struct in_addr haddr;
240     FILE *f;
241    
242 tdb 1.51 log_msg(LOG_DEBUG, "Creating tcp socket");
243 pajs 1.28 if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP))<0){
244     log_msg(LOG_CRIT, "Failed to make TCP Socket");
245 tdb 1.53 goto out;
246 pajs 1.1 }
247    
248 pajs 1.28 if((get_host_addr(hostname, &haddr))!=0){
249     log_msg(LOG_CRIT, "Failed to lookup name for %s", hostname);
250 pajs 1.38 close(sock);
251 tdb 1.53 goto out;
252 pajs 1.2 }
253    
254 pajs 1.28 memset(&addr, 0, sizeof(addr));
255     addr.sin_family = AF_INET;
256     memcpy(&addr.sin_addr, &haddr, sizeof(haddr));
257     addr.sin_port = htons(port);
258    
259     log_msg(LOG_DEBUG, "Creating a tcp connection");
260     if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) !=0){
261     log_msg(LOG_CRIT, "Failed to connect to hostname %s on port %d", hostname, port);
262 pajs 1.38 close(sock);
263 tdb 1.53 goto out;
264 pajs 1.1 }
265 pajs 1.28
266 tdb 1.53 #ifndef WIN32
267     /* Windows does not treat sockets like this :( */
268 pajs 1.28 if((f=fdopen(sock, "r+"))==NULL){
269     log_msg(LOG_CRIT, "Failed to connect to open filedescriptor on tcp connection");
270     close(sock);
271     return NULL;
272 pajs 1.16 }
273 pajs 1.28
274     return f;
275 tdb 1.53 #else
276     return sock;
277     #endif
278    
279     out:
280     #ifdef WIN32
281     return 0;
282     #else
283     return NULL;
284     #endif
285 pajs 1.28 }
286    
287 tdb 1.53 #ifndef WIN32
288 pajs 1.28 int tcp_comm(FILE *f, char *send, char **response, char *expected){
289    
290     log_msg(LOG_DEBUG, "Sending %s", send);
291     fprintf(f, "%s\n", send);
292     fflush(f);
293     *response=fpgetline(f);
294     fseek(f, 0, SEEK_CUR);
295    
296 tdb 1.49 if(*response!=NULL) log_msg(LOG_DEBUG, "Received %s", *response);
297 pajs 1.28
298     if( (*response==NULL) || (strcmp(*response, "ERROR")==0) ) return -1;
299 tdb 1.51
300 pajs 1.28 if(expected==NULL) return 0;
301    
302     if((strcmp(expected, *response))==0) return 0;
303    
304     log_msg(LOG_DEBUG, "Did not get expected response");
305     return -1;
306     }
307 tdb 1.53 #else
308     int tcp_comm(SOCKET soc, char *sendstr, char **response, char *expected) {
309     static char *rec = NULL;
310     char sendbuf[128];
311     char recbuf[128];
312     int bytesRecv;
313     char *tmp;
314    
315     sprintf(sendbuf, "%s\n", sendstr);
316    
317     log_msg(LOG_DEBUG, "Sending %s", sendstr);
318     send(soc, sendbuf, strlen(sendbuf), 0);
319     bytesRecv = recv(soc, recbuf, 128, 0);
320    
321     if(bytesRecv != 0 && bytesRecv != SOCKET_ERROR) {
322     /* remove \n and copy to a string */
323     recbuf[bytesRecv-1] = '\0';
324     tmp = realloc(rec, bytesRecv);
325     if(tmp == NULL) {
326     free(rec);
327     rec = NULL;
328     log_msg(LOG_CRIT, "out of memory");
329     return -1;
330     }
331     rec = tmp;
332     rec = strcpy(rec, recbuf);
333     *response = rec;
334     log_msg(LOG_DEBUG, "Received %s", *response);
335     } else {
336     return -1;
337     }
338     if(strcmp(*response, "ERROR")==0) return -1;
339    
340     if(expected==NULL) return 0;
341    
342     if((strcmp(expected, *response))==0) return 0;
343    
344     log_msg(LOG_DEBUG, "Did not get expected response");
345     return -1;
346     }
347     #endif /* WIN32 */
348 pajs 1.28
349 tdb 1.53 int tcp_comm_strdup(IHOST_SOCKET f, char *send, char **response, char *expected)
350     {
351 tdb 1.51 if((tcp_comm(f, send, response, expected))!=0){
352 pajs 1.16 return -1;
353     }
354 pajs 1.25
355 pajs 1.28 *response=strdup(*response);
356     if (response==NULL) return -1;
357    
358     return 0;
359     }
360 tdb 1.51
361 pajs 1.28 int ihost_getconfig(ihost_state_t *ihost_state){
362 tdb 1.53 IHOST_SOCKET tcp_con;
363 pajs 1.28 char *response;
364     char *response_ptr;
365    
366     /* Keep these in case of a failure and so it can keep running on the old config */
367 tdb 1.51 char *file_list=NULL;
368 pajs 1.28 char *last_modified=NULL;
369     char *host_fqdn=NULL;
370     char *host_ip=NULL;
371     int udp_update_time=0;
372     char *server_fqdn=NULL;
373     int server_udp_port=0;
374     time_t config_ttl=0;
375    
376 tdb 1.53 if((tcp_con=create_tcp_connection(ihost_state->filtermanager_host, ihost_state->filtermanager_port))
377     #ifndef WIN32
378     ==NULL
379     #else
380     ==0
381     #endif
382     ) {
383 pajs 1.35 return -1;
384 pajs 1.30 }
385 pajs 1.28
386     if(ihost_state->file_list!=NULL || ihost_state->last_modified!=NULL){
387 tdb 1.53 #ifndef WIN32
388     if(tcp_con==NULL)
389     #else
390     if(tcp_con==0)
391     #endif
392     {
393 pajs 1.28 goto error;
394 tdb 1.51 }
395    
396 pajs 1.28 if((tcp_comm(tcp_con, "CHECKCONFIG", &response, "OK"))!=0){
397     goto error;
398     }
399 tdb 1.51
400 pajs 1.28 if((tcp_comm(tcp_con, ihost_state->file_list, &response, "OK"))!=0){
401     goto error;
402     }
403 tdb 1.51
404 pajs 1.28 if((tcp_comm(tcp_con, ihost_state->last_modified, &response, "OK"))==0){
405 pajs 1.32 if((tcp_comm(tcp_con, "END", &response, "OK"))!=0){
406 pajs 1.28 goto error;
407     }
408 tdb 1.53 CLOSESOCKET(tcp_con);
409 pajs 1.28 return 0;
410     }else{
411     if((strcmp(response, "EXPIRED"))!=0){
412     goto error;
413     }
414     }
415 pajs 1.1 }
416    
417 pajs 1.28 /* If we got to here, the config must of expired */
418 pajs 1.18
419 pajs 1.28 if((tcp_comm(tcp_con, "STARTCONFIG", &response, "OK"))!=0){
420     goto error;
421 pajs 1.1 }
422    
423 pajs 1.28 if((tcp_comm_strdup(tcp_con, "LASTMODIFIED", &response, NULL))!=0){
424     goto error;
425 pajs 1.1 }
426 pajs 1.28 last_modified=response;
427 tdb 1.51
428 pajs 1.28 if((tcp_comm_strdup(tcp_con, "FILELIST", &response, NULL))!=0){
429     goto error;
430 pajs 1.1 }
431 pajs 1.28 file_list=response;
432 pajs 1.1
433 pajs 1.28 if((tcp_comm_strdup(tcp_con, "FQDN", &response, NULL))!=0){
434     goto error;
435 pajs 1.1 }
436 pajs 1.28 host_fqdn=response;
437    
438     if((tcp_comm_strdup(tcp_con, "IP", &response, NULL))!=0){
439     goto error;
440 pajs 1.1 }
441 pajs 1.28 host_ip=response;
442    
443     if((tcp_comm(tcp_con, "UDPUpdateTime", &response, NULL))!=0){
444     goto error;
445 pajs 1.1 }
446 pajs 1.28 udp_update_time=atoi(response);
447    
448     if((tcp_comm(tcp_con, "ConfigTTL", &response, NULL))!=0){
449     goto error;
450 pajs 1.1 }
451 pajs 1.28 config_ttl=atoi(response);
452 pajs 1.1
453 pajs 1.28 if((tcp_comm(tcp_con, "ENDCONFIG", &response, NULL))!=0){
454     goto error;
455 pajs 1.1 }
456    
457 pajs 1.28 if((tcp_comm(tcp_con, "FILTER", &response, NULL))!=0){
458     goto error;
459     }else{
460     response_ptr=strchr(response,';');
461     if(response_ptr==NULL){
462     log_msg(LOG_ERR, "Incorrect data sent by server");
463     goto error;
464     }
465     *response_ptr='\0';
466     server_fqdn=strdup(response);
467     if(server_fqdn==NULL){
468     goto error;
469     }
470     response_ptr++;
471     if(response_ptr==NULL){
472 tdb 1.51 log_msg(LOG_ERR, "Incorrect data sent by server");
473     goto error;
474     }
475 pajs 1.28
476 tdb 1.51 server_udp_port=atoi(response_ptr);
477 pajs 1.28
478     if (server_udp_port==0){
479     log_msg(LOG_ERR, "Incorrect data sent by server");
480     goto error;
481     }
482 pajs 1.2 }
483 tdb 1.51
484 pajs 1.28 if((tcp_comm(tcp_con, "END", &response, "OK"))!=0){
485     goto error;
486 pajs 1.2 }
487 pajs 1.28
488 tdb 1.53 CLOSESOCKET(tcp_con);
489 pajs 1.28
490     /* We have the data we need, and its all been read correctly */
491    
492     /* Free the old data before pointing them to the new data. m_free copes should
493     * this already be NULL */
494 tdb 1.51 if(ihost_state->file_list!=NULL) free(ihost_state->file_list);
495     if(ihost_state->last_modified!=NULL) free(ihost_state->last_modified);
496     if(ihost_state->server_fqdn!=NULL) free(ihost_state->server_fqdn);
497 pajs 1.41
498     if(ihost_state->preset_fqdn){
499     if(host_fqdn != NULL) free(host_fqdn);
500     }else{
501 tdb 1.51 if(ihost_state->host_fqdn!=NULL) free(ihost_state->host_fqdn);
502 pajs 1.41 ihost_state->host_fqdn=host_fqdn;
503     }
504    
505     if(ihost_state->preset_ip){
506     if(host_ip != NULL) free(host_ip);
507     }else{
508     if(ihost_state->host_ip!=NULL) free(ihost_state->host_ip);
509     ihost_state->host_ip=host_ip;
510     }
511    
512 pajs 1.28
513     ihost_state->file_list=file_list;
514     ihost_state->last_modified=last_modified;
515     ihost_state->server_fqdn=server_fqdn;
516     ihost_state->server_udp_port=server_udp_port;
517     ihost_state->udp_update_time=udp_update_time;
518     ihost_state->config_ttl=config_ttl;
519    
520     log_msg(LOG_DEBUG, "UDP Update time %d", udp_update_time);
521     log_msg(LOG_DEBUG, "Configure ttl %d", config_ttl);
522    
523     return 0;
524    
525     error:
526    
527     if(file_list!=NULL) free(file_list);
528     if(last_modified!=NULL) free(last_modified);
529     if(host_fqdn!=NULL) free(host_fqdn);
530     if(server_fqdn!=NULL) free(server_fqdn);
531     if(host_ip!=NULL) free(host_ip);
532 tdb 1.53 CLOSESOCKET(tcp_con);
533 pajs 1.28
534     return -1;
535     }
536    
537     int get_system_stats(int seq_no, ihost_state_t *ihost_state, char *xml, int size){
538     char tmp[size];
539 tdb 1.51 sg_cpu_percents *cpu_percent;
540 tdb 1.50 sg_mem_stats *mem_stats;
541     sg_load_stats *load_stats;
542     sg_user_stats *user_stats;
543     sg_swap_stats *swap_stats;
544     sg_host_info *general_stats;
545     sg_fs_stats *disk_stats;
546     sg_disk_io_stats *diskio_stats;
547     sg_process_count *process_stats;
548     sg_network_io_stats *network_stats;
549     sg_page_stats *page_stats;
550 pajs 1.28 int disk_entries=0;
551     int diskio_entries=0;
552     int network_entries=0;
553    
554     int counter;
555     long long x;
556     long long y;
557    
558     /* Print start of the packet we want */
559     snprintf(xml, size, "<packet seq_no=\"%d\" machine_name=\"%s\" date=\"%ld\" type=\"data\" ip=\"%s\">", \
560 tdb 1.51 seq_no, ihost_state->host_fqdn, (long) time(NULL), ihost_state->host_ip);
561 pajs 1.28
562     /* Get cpu stats, check it is correct, then fill in its entry for the xml */
563 tdb 1.50 if((cpu_percent=sg_get_cpu_percents())==NULL){
564 tdb 1.51 log_msg(LOG_CRIT, "Failed to get cpu statistics: %s (%s)",
565     sg_str_error(sg_get_error()), sg_get_error_arg());
566 pajs 1.28 }else{
567     snprintf(tmp, size, \
568     "<cpu><user>%3.2f</user><kernel>%3.2f</kernel><idle>%3.2f</idle><iowait>%3.2f</iowait><swap>%3.2f</swap></cpu>", \
569     cpu_percent->user, \
570     cpu_percent->kernel, \
571     cpu_percent->idle, \
572     cpu_percent->iowait, \
573     cpu_percent->swap);
574    
575     if(strlcat(xml, tmp, size) >= size) goto too_big_error;
576 pajs 1.2 }
577 pajs 1.28
578 tdb 1.51
579     /*Get mem stats, and fill in xml */
580 tdb 1.53
581 tdb 1.50 if((mem_stats=sg_get_mem_stats())==NULL){
582 tdb 1.51 log_msg(LOG_CRIT, "Failed to get memory statistics: %s (%s)",
583     sg_str_error(sg_get_error()), sg_get_error_arg());
584 pajs 1.28 }else{
585     snprintf(tmp, size, \
586 tdb 1.53 "<memory><total>"LLD"</total><free>"LLD"</free><used>"LLD"</used><cache>"LLD"</cache></memory>", \
587 pajs 1.28 mem_stats->total, \
588     mem_stats->free, \
589     mem_stats->used, \
590     mem_stats->cache);
591 tdb 1.51
592 pajs 1.28 if(strlcat(xml, tmp, size) >= size) goto too_big_error;
593 pajs 1.2 }
594 pajs 1.28
595    
596 tdb 1.51 /* Get load stats */
597 tdb 1.53
598 tdb 1.50 if((load_stats=sg_get_load_stats())==NULL){
599 tdb 1.51 log_msg(LOG_CRIT, "Failed to get load statistics: %s (%s)",
600     sg_str_error(sg_get_error()), sg_get_error_arg());
601 pajs 1.28 }else{
602     snprintf(tmp, size, \
603     "<load><load1>%.2lf</load1><load5>%.2lf</load5><load15>%.2lf</load15></load>", \
604     load_stats->min1, \
605     load_stats->min5, \
606     load_stats->min15);
607     if(strlcat(xml, tmp, size) >= size) goto too_big_error;
608 pajs 1.2 }
609    
610 pajs 1.28
611     /* get user stats */
612 tdb 1.51
613 tdb 1.50 if((user_stats=sg_get_user_stats())==NULL){
614 tdb 1.51 log_msg(LOG_CRIT, "Failed to get user statistics: %s (%s)",
615     sg_str_error(sg_get_error()), sg_get_error_arg());
616 pajs 1.28 }else{
617    
618     snprintf(tmp, size, \
619     "<users><list>%s</list><count>%d</count></users>", \
620     user_stats->name_list, \
621     user_stats->num_entries);
622 tdb 1.51
623 pajs 1.28 if(strlcat(xml, tmp, size) >= size) goto too_big_error;
624 pajs 1.2 }
625 pajs 1.1
626 pajs 1.28
627     /* swap stats */
628 tdb 1.53
629 tdb 1.50 if((swap_stats=sg_get_swap_stats())==NULL){
630 tdb 1.51 log_msg(LOG_CRIT, "Failed to get swap statistics: %s (%s)",
631     sg_str_error(sg_get_error()), sg_get_error_arg());
632 pajs 1.28 }else{
633     snprintf(tmp, size, \
634 tdb 1.53 "<swap><total>"LLD"</total><used>"LLD"</used><free>"LLD"</free></swap>",\
635 pajs 1.28 swap_stats->total, \
636     swap_stats->used, \
637     swap_stats->free);
638 tdb 1.51
639 pajs 1.28 if(strlcat(xml, tmp, size) >= size) goto too_big_error;
640 pajs 1.2 }
641 pajs 1.28
642    
643     /* general stats */
644 tdb 1.51
645 tdb 1.50 if((general_stats=sg_get_host_info())==NULL){
646 tdb 1.51 log_msg(LOG_CRIT, "Failed to get host info statistics: %s (%s)",
647     sg_str_error(sg_get_error()), sg_get_error_arg());
648 pajs 1.28 }else{
649     snprintf(tmp, size, \
650     "<os><name>%s</name><release>%s</release><version>%s</version><sysname>%s</sysname><platform>%s</platform><uptime>%ld</uptime></os>", \
651     general_stats->os_name, \
652     general_stats->os_release, \
653     general_stats->os_version, \
654     general_stats->hostname, \
655     general_stats->platform, \
656     (long)general_stats->uptime);
657 tdb 1.51
658 pajs 1.28 if(strlcat(xml, tmp, size) >= size) goto too_big_error;
659 tdb 1.51
660 pajs 1.2 }
661 pajs 1.1
662 tdb 1.51
663 pajs 1.28 /* process stats */
664 tdb 1.53
665 tdb 1.51 if((process_stats=sg_get_process_count())==NULL){
666     log_msg(LOG_CRIT, "Failed to get process statistics: %s (%s)",
667     sg_str_error(sg_get_error()), sg_get_error_arg());
668 pajs 1.28 }else{
669     snprintf(tmp, size, \
670     "<processes><sleeping>%d</sleeping><cpu>%d</cpu><zombie>%d</zombie><stopped>%d</stopped><total>%d</total></processes>",\
671     process_stats->sleeping, \
672     process_stats->running, \
673     process_stats->zombie, \
674     process_stats->stopped, \
675     process_stats->total);
676    
677     if(strlcat(xml, tmp, size) >= size) goto too_big_error;
678 pajs 1.4
679 pajs 1.28 }
680 pajs 1.4
681    
682 pajs 1.28 /* Get paging stats */
683 tdb 1.53
684 tdb 1.50 if((page_stats=sg_get_page_stats_diff())==NULL){
685 tdb 1.51 log_msg(LOG_CRIT, "Failed to get paging statistics: %s (%s)",
686     sg_str_error(sg_get_error()), sg_get_error_arg());
687 pajs 1.28 }else{
688     if(page_stats->systime!=0){
689     x=page_stats->pages_pagein / page_stats->systime;
690     y=page_stats->pages_pageout / page_stats->systime;
691     }else{
692     x=page_stats->pages_pagein;
693     y=page_stats->pages_pageout;
694     }
695     snprintf(tmp, size, \
696 tdb 1.53 "<pages><pageins>"LLD"</pageins><pageouts>"LLD"</pageouts></pages>", \
697 pajs 1.28 x, \
698     y);
699 tdb 1.51
700 pajs 1.28 if(strlcat(xml, tmp, size) >= size) goto too_big_error;
701     }
702 pajs 1.4
703    
704 pajs 1.28 /* get diskio stats */
705 tdb 1.51
706 tdb 1.50 if((diskio_stats=sg_get_disk_io_stats_diff(&diskio_entries))==NULL){
707 tdb 1.51 log_msg(LOG_CRIT, "Failed to get disk io statistics: %s (%s)",
708     sg_str_error(sg_get_error()), sg_get_error_arg());
709 pajs 1.28 }else{
710     strlcat(xml, "<diskio>", size);
711     for(counter=0;counter<diskio_entries;counter++){
712 pajs 1.4
713 pajs 1.28 if(diskio_stats->systime!=0){
714     x=diskio_stats->read_bytes / diskio_stats->systime;
715     y=diskio_stats->write_bytes / diskio_stats->systime;
716     }else{
717     x=diskio_stats->read_bytes;
718 tdb 1.51 y=diskio_stats->write_bytes;
719 pajs 1.28 }
720 tdb 1.51
721 pajs 1.28 snprintf(tmp, size, \
722 tdb 1.53 "<p%d name=\"%s\" rbytes=\""LLD"\" wbytes=\""LLD"\"></p%d>", \
723 pajs 1.28 counter, \
724     diskio_stats->disk_name, \
725     x, \
726     y, \
727     counter);
728 pajs 1.9
729 pajs 1.28 strlcat(xml, tmp, size);
730     diskio_stats++;
731     }
732 pajs 1.4
733 pajs 1.28 if(strlcat(xml, "</diskio>", size) >= size) goto too_big_error;
734 pajs 1.4
735     }
736 pajs 1.18
737 tdb 1.51
738 pajs 1.28 /* get networks stats */
739 tdb 1.51
740 tdb 1.50 if((network_stats=sg_get_network_io_stats_diff(&network_entries))==NULL){
741 tdb 1.51 log_msg(LOG_CRIT, "Failed to get network io statistics: %s (%s)",
742     sg_str_error(sg_get_error()), sg_get_error_arg());
743 pajs 1.28 }else{
744     strlcat(xml, "<net>", size);
745     for(counter=0;counter<network_entries;counter++){
746     if(network_stats->systime!=0){
747     x=network_stats->rx / network_stats->systime;
748     y=network_stats->tx / network_stats->systime;
749     }else{
750     x=network_stats->rx;
751     y=network_stats->tx;
752     }
753 pajs 1.4
754 pajs 1.28 snprintf(tmp, size, \
755 tdb 1.53 "<p%d name=\"%s\" rx=\""LLD"\" tx=\""LLD"\"></p%d>", \
756 pajs 1.28 counter, \
757     network_stats->interface_name, \
758     x, \
759     y, \
760     counter);
761 pajs 1.4
762 pajs 1.28 strlcat(xml, tmp, size);
763     network_stats++;
764     }
765 pajs 1.10
766 pajs 1.28 if(strlcat(xml, "</net>", size) >= size) goto too_big_error;
767 pajs 1.6
768 pajs 1.28 }
769 pajs 1.4
770 pajs 1.18
771 pajs 1.28 /* get disk stats */
772 tdb 1.51
773 tdb 1.50 if((disk_stats=sg_get_fs_stats(&disk_entries))==NULL){
774 tdb 1.51 log_msg(LOG_CRIT, "Failed to get fs statistics: %s (%s)",
775     sg_str_error(sg_get_error()), sg_get_error_arg());
776 pajs 1.28 }else{
777     strlcat(xml, "<disk>", size);
778     for(counter=0;counter<disk_entries;counter++){
779     snprintf(tmp, size, \
780 tdb 1.53 "<p%d name=\"%s\" mount=\"%s\" fstype=\"%s\" total=\""LLD"\" used=\""LLD"\" avail=\""LLD"\" totalinodes=\""LLD"\" usedinodes=\""LLD"\" freeinodes=\""LLD"\"></p%d>", \
781 pajs 1.28 counter, \
782     disk_stats->device_name, \
783     disk_stats->mnt_point, \
784     disk_stats->fs_type, \
785     disk_stats->size, \
786     disk_stats->used, \
787     disk_stats->avail, \
788     disk_stats->total_inodes, \
789     disk_stats->used_inodes, \
790     disk_stats->free_inodes, \
791     counter);
792 pajs 1.18
793 pajs 1.28 strlcat(xml, tmp, size);
794 pajs 1.9
795 pajs 1.28 disk_stats++;
796     }
797 pajs 1.9
798 pajs 1.28 if(strlcat(xml, "</disk>", size) >= size) goto too_big_error;
799 pajs 1.9
800     }
801 tdb 1.51
802 pajs 1.9
803 pajs 1.28 if(strlcat(xml, "</packet>", size) >= size) goto too_big_error;
804 pajs 1.9
805 pajs 1.28 /*If we got to here, it should of all been filled in nicely now */
806     return 0;
807 pajs 1.10
808 pajs 1.28 too_big_error:
809     log_msg(LOG_ERR, "UDP Packet is too large. Throwing away the packet");
810     return -1;
811 pajs 1.9 }
812 pajs 1.1
813 pajs 1.28
814 tdb 1.51
815 tdb 1.53 /* WIN32 NT service stuff */
816     #ifdef WIN32
817     void service_stopped() {
818     if(run_as_service) {
819     service_status.dwCurrentState = SERVICE_STOPPED;
820     service_status.dwWin32ExitCode = errno;
821     service_status.dwServiceSpecificExitCode = 0;
822    
823     SetServiceStatus(hstatus, &service_status);
824     }
825     }
826    
827     void control_handler(DWORD request) {
828     switch(request) {
829     case SERVICE_CONTROL_STOP:
830     case SERVICE_CONTROL_SHUTDOWN:
831     service_status.dwWin32ExitCode = 0;
832     service_status.dwCurrentState = SERVICE_STOP_PENDING;
833     break;
834     default:
835     break;
836     }
837    
838     SetServiceStatus (hstatus, &service_status);
839     }
840    
841     /* attempt to tell service manager to start our service.
842     * return 0 on error, 1 on ok
843     */
844     int start_service() {
845     SC_HANDLE scm;
846     SC_HANDLE service;
847    
848     // Open SCM
849     if((scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT)) == NULL) {
850     log_msg(LOG_CRIT, "Failed to open Service Control Manager");
851     return 0;
852     }
853     // Locate the service
854     if((service = OpenService(scm, SERVICENAME, SERVICE_START)) == NULL) {
855     log_msg(LOG_CRIT, "Unable to open the service");
856     return 0;
857     }
858     // Start the service
859     if(StartService(service, 0, NULL) == 0) {
860     log_msg(LOG_CRIT, "Unable to start the service");
861     return 0;
862     }
863     return 1;
864     }
865    
866     int stop_service() {
867     SC_HANDLE scm;
868     SC_HANDLE service;
869     SERVICE_STATUS status;
870    
871     // Open SCM
872     if((scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT)) == NULL) {
873     log_msg(LOG_CRIT, "Failed to open Service Control Manager");
874     return 0;
875     }
876     // Locate service
877     if((service = OpenService(scm, SERVICENAME, SERVICE_STOP)) == NULL) {
878     log_msg(LOG_CRIT, "Unable to open the service");
879     return 0;
880     }
881     // Stop the service
882     if(!ControlService(service, SERVICE_CONTROL_STOP, &status)) {
883     log_msg(LOG_CRIT, "Unable to stop the service");
884     return 0;
885     }
886     return 1;
887     }
888    
889     int register_service(int argc, char **argv) {
890     char path[MAX_PATH];
891     int cmdline_len;
892     int i;
893     char *cmdline;
894     char *tmp;
895     SC_HANDLE scm;
896    
897     if(!GetModuleFileName(NULL, path, MAX_PATH)) {
898     log_msg(LOG_CRIT, "GetModuleFileName failed");
899     return 0;
900     }
901    
902     // Calculate command line length
903     // 14 = 10 for " -w service", 2x quote around path and ending \0
904     cmdline_len = strlen(path) + 14;
905     for (i=0; i<argc; i++) {
906     // +1 for space prefix
907     cmdline_len += strlen(argv[i]) +1;
908     }
909    
910     cmdline = malloc(cmdline_len);
911     if(cmdline == NULL) {
912     log_msg(LOG_CRIT, "out of memory");
913     return 0;
914     }
915     tmp = malloc(cmdline_len);
916     if(tmp == NULL) {
917     log_msg(LOG_CRIT, "out of memory");
918     free(cmdline);
919     return 0;
920     }
921    
922     // Compile up the final command line call
923     snprintf(cmdline, cmdline_len, "\"%s\" -w service", path);
924     for (i=0; i<argc; i++) {
925     snprintf(tmp, cmdline_len, " %s", argv[i]);
926     strcat(cmdline, tmp);
927     }
928     free(tmp);
929    
930     // Open SCM
931     if((scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) {
932     log_msg(LOG_CRIT, "Unable to open Service Control Manager");
933     return 0;
934     }
935    
936     // Add the service
937     if (CreateService(scm, SERVICENAME, SERVICENAME,
938     SC_MANAGER_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,
939     SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, cmdline, NULL,
940     NULL, NULL, NULL, NULL) == NULL) {
941     log_msg(LOG_CRIT, "Unable to create service");
942     return 0;
943     }
944    
945     return 1;
946     }
947    
948     int unregister_service() {
949     SC_HANDLE scm;
950     SC_HANDLE service;
951    
952     // Open the SCM
953     if((scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) ==NULL) {
954     log_msg(LOG_CRIT, "Unable to open Service Control Manager");
955     return 0;
956     }
957     // Get the service
958     if((service = OpenService(scm, SERVICENAME, SC_MANAGER_ALL_ACCESS)) == NULL) {
959     log_msg(LOG_CRIT, "Unable to locate the service");
960     return 0;
961     }
962     // Delete service
963     if(DeleteService(service) == 0) {
964     log_msg(LOG_CRIT, "Unable to remove the service");
965     return 0;
966     }
967     return 1;
968     }
969     #endif
970    
971    
972    
973 pajs 1.17 void usage(char *progname){
974 tdb 1.53 const char *usage;
975     #ifdef WIN32
976     usage = "Usage %s [-w option] [-v[v]] [-n name] [-i ip] [-s server] [-p port] [-V] [-h]\n\n";
977     #else
978     usage = "Usage %s [-v[v]] [-f] [-n name] [-i ip] [-s server] [-p port] [-V] [-h]\n\n";
979     #endif
980     fprintf(stderr, usage, progname);
981 tdb 1.51 fprintf(stderr, " -v Verbose mode, -vv would make even more verbose\n");
982 tdb 1.53 #ifndef WIN32
983 tdb 1.51 fprintf(stderr, " -f Foreground mode, print errors to stderr\n");
984 tdb 1.53 #else
985     fprintf(stderr, " -w Windows Service options:\n");
986     fprintf(stderr, " start - start the service\n");
987     fprintf(stderr, " stop - stop the service\n");
988     fprintf(stderr, " register - register the service\n");
989     fprintf(stderr, " unregister - unregister the service\n");
990     /* service - run as a service, only called by windows service */
991     #endif
992 tdb 1.43 fprintf(stderr, " -n Set the machine name to be reported as\n");
993     fprintf(stderr, " -i Set the IP to be reported as\n");
994     fprintf(stderr, " -s Specifies the i-scream server to connect to\n");
995 tdb 1.51 fprintf(stderr, " default: %s\n", DEF_SERVER_NAME);
996 tdb 1.43 fprintf(stderr, " -p Specifies the i-scream server port\n");
997 tdb 1.51 fprintf(stderr, " default: %d\n", DEF_SERVER_PORT);
998     fprintf(stderr, " -V Print version number\n");
999     fprintf(stderr, " -h Prints this help page\n");
1000 tdb 1.43 fprintf(stderr, "\nReport bugs to <%s>.\n", PACKAGE_BUGREPORT);
1001 tdb 1.51 exit(1);
1002 pajs 1.17 }
1003    
1004 tdb 1.53 int run_ihost(){
1005 pajs 1.28
1006     udp_sockinfo_t udp_sockinfo;
1007 tdb 1.51
1008 pajs 1.28 pid_t pid;
1009 pajs 1.19 FILE *f;
1010 pajs 1.28 int packet_num=0;
1011     int len;
1012 pajs 1.18
1013 pajs 1.28 char packet[MAX_UDP_PACKET_SIZE];
1014 pajs 1.18
1015 pajs 1.28 time_t cur_time, sleep_delay, udp_time=0, config_time=0;
1016 tdb 1.53 #ifdef WIN32
1017     int tries=0;
1018     WSADATA wsaData;
1019    
1020     if(WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) {
1021     log_msg(LOG_CRIT, "Failed to init a winsock");
1022     service_stopped();
1023     exit(1);
1024 tdb 1.51 }
1025 tdb 1.53 #endif
1026 pajs 1.28
1027     if(gethostbyname(ihost_state.filtermanager_host)==NULL){
1028 tdb 1.53 printf("%s\n", ihost_state.filtermanager_host);
1029 pajs 1.28 log_msg(LOG_CRIT, "Failed to lookup hostname. Please check settings");
1030 tdb 1.53 goto out;
1031 pajs 1.3 }
1032 pajs 1.28 if(ihost_state.filtermanager_port==0){
1033     log_msg(LOG_ERR, "Invalid port number");
1034 tdb 1.53 goto out;
1035 pajs 1.17 }
1036 pajs 1.18
1037 tdb 1.53 #ifndef WIN32
1038 pajs 1.28 if(ihost_config.daemon){
1039 pajs 1.18 pid=fork();
1040     if(pid==-1){
1041 pajs 1.28 log_msg(LOG_CRIT, "Failed to background exiting");
1042 tdb 1.51 exit(1);
1043 pajs 1.18 }else if(pid!=0){
1044 tdb 1.51 /* Parent process */
1045     return 0;
1046     }
1047     /* We should now be in the background*/
1048     if(setsid()==-1){
1049     log_msg(LOG_CRIT, "setsid failed");
1050     exit(1);
1051     }
1052    
1053 tdb 1.29 if((ihost_config.log=fopen(LOG_FILE, "a"))==NULL){
1054 pajs 1.28 ihost_config.log=stderr;
1055 tdb 1.29 log_msg(LOG_CRIT, "Failed to open Logfiles %s for writing", LOG_FILE);
1056 pajs 1.18 exit(1);
1057     }
1058 pajs 1.28
1059 tdb 1.51 fclose(stdin);
1060     fclose(stdout);
1061     fclose(stderr);
1062 pajs 1.28
1063 tdb 1.51 }
1064 tdb 1.53 #endif
1065 pajs 1.28
1066 tdb 1.43 log_msg(LOG_INFO, "Starting ihost...");
1067 pajs 1.44
1068 tdb 1.51 log_msg(LOG_DEBUG, "Running sg_init()");
1069     if(sg_init()){
1070     log_msg(LOG_CRIT, "sg_init failed: %s (%s)",
1071     sg_str_error(sg_get_error()), sg_get_error_arg());
1072 tdb 1.53 goto out;
1073     }
1074     if(sg_snapshot()) {
1075     log_msg(LOG_ERR, "sg_snapshot failed: %s (%s)",
1076     sg_str_error(sg_get_error()), sg_get_error_arg());
1077 pajs 1.44 }
1078 pajs 1.28
1079 tdb 1.53 #ifndef WIN32
1080 tdb 1.51 log_msg(LOG_DEBUG,"Writing PID FILE");
1081 pajs 1.28
1082 tdb 1.51 pid=getpid();
1083 pajs 1.44
1084 tdb 1.51 if((f=fopen(PID_FILE,"w")) == NULL){
1085     log_msg(LOG_CRIT, "Failed to write PID file");
1086     }else{
1087     if((fprintf(f,"%d",(int)pid)) <= 0 ){
1088     log_msg(LOG_CRIT, "Failed to write PID file");
1089     }
1090     if((fclose(f))!=0){
1091     log_msg(LOG_CRIT, "failed to close PID file");
1092     }
1093     }
1094 tdb 1.53 #endif
1095 tdb 1.51
1096     /* Get the initial config from the filter manager. Should this fail,
1097 pajs 1.28 * wait, and then try again. */
1098 tdb 1.53 /* Win32 - for a max of one minute */
1099 pajs 1.28
1100 tdb 1.51 sg_get_disk_io_stats_diff(&packet_num);
1101 pajs 1.28 packet_num=0;
1102    
1103 tdb 1.53 while(ihost_getconfig(&ihost_state)!=0
1104     #ifdef WIN32
1105     && (tries<6)
1106     #endif
1107     ){
1108 pajs 1.28 log_msg(LOG_ERR, "Failed to get ihost config");
1109 tdb 1.53 sleep(SLEEP);
1110     #ifdef WIN32
1111     tries++;
1112     #endif
1113     }
1114    
1115     #ifdef WIN32
1116     if (tries == 6) {
1117     log_msg(LOG_ERR, "Giving up");
1118     goto out;
1119 pajs 1.18 }
1120 tdb 1.53 tries = 0;
1121     #endif
1122 pajs 1.18
1123 tdb 1.53 while((create_udp_sockinfo(&udp_sockinfo, ihost_state.server_fqdn, ihost_state.server_udp_port))!=0
1124     #ifdef WIN32
1125     && (tries<6)
1126     #endif
1127     ){
1128 tdb 1.51 log_msg(LOG_ERR, "Failed to create udp socket");
1129 tdb 1.53 sleep(SLEEP);
1130     #ifdef WIN32
1131     tries++;
1132     #endif
1133     }
1134    
1135     #ifdef WIN32
1136     if (tries == 6) {
1137     log_msg(LOG_ERR, "Giving up");
1138     goto out;
1139 pajs 1.18 }
1140 tdb 1.53 #endif
1141 pajs 1.2
1142 pajs 1.28 config_time=time(NULL)+ihost_state.config_ttl;
1143 pajs 1.5
1144 tdb 1.53 #ifdef WIN32
1145     /* Finally, we have started successfully!
1146     * We set state to running even for non-service calls so the while
1147     * loop works. Bit of a hack ;)
1148     */
1149     service_status.dwCurrentState = SERVICE_RUNNING;
1150     if(run_as_service) {
1151     SetServiceStatus(hstatus, &service_status);
1152     }
1153     printf("started\n");
1154     #endif
1155    
1156 pajs 1.28 /* Now have config.. collect data and send as often as required */
1157 tdb 1.53 #ifdef WIN32
1158     while(service_status.dwCurrentState == SERVICE_RUNNING)
1159     #else
1160     for(;;)
1161     #endif
1162     {
1163 pajs 1.9 cur_time=time(NULL);
1164 pajs 1.28
1165     if(cur_time>=udp_time){
1166 tdb 1.53 if(sg_snapshot()) {
1167     log_msg(LOG_ERR, "sg_snapshot failed: %s (%s)",
1168     sg_str_error(sg_get_error()), sg_get_error_arg());
1169     continue; /* Could this get ugly? */
1170     }
1171 pajs 1.28 if((get_system_stats(packet_num++, &ihost_state, packet, MAX_UDP_PACKET_SIZE))!=0){
1172     log_msg(LOG_ERR, "Failed to get system stats");
1173     }
1174    
1175     len=strlen(packet);
1176     log_msg(LOG_DEBUG, "Packet size: %d\nPacket: %s\n", len, packet);
1177 tdb 1.51
1178 pajs 1.28 if((sendto(udp_sockinfo.sock, packet, len, 0, (struct sockaddr *) &udp_sockinfo.addr, sizeof(udp_sockinfo.addr)))!=len){
1179     log_msg(LOG_CRIT, "Failed to send packet");
1180 pajs 1.9 }
1181 pajs 1.28 udp_time=cur_time+ihost_state.udp_update_time;
1182     log_msg(LOG_DEBUG, "Next packet should be sent on %d", udp_time);
1183 pajs 1.9 }
1184 tdb 1.51
1185 pajs 1.28 if(cur_time>=config_time){
1186     if(ihost_getconfig(&ihost_state)!=0){
1187     /* If we can't get the config, try again 5 minutes time */
1188     log_msg(LOG_ERR, "Failed to get config, try again 5 minutes time");
1189     config_time=time(NULL)+300;
1190     }else{
1191     close(udp_sockinfo.sock);
1192    
1193 tdb 1.51 while((create_udp_sockinfo(&udp_sockinfo, ihost_state.server_fqdn, ihost_state.server_udp_port))!=0){
1194     log_msg(LOG_CRIT, "Failed to create udp socket");
1195 tdb 1.53 sleep(SLEEP);
1196 pajs 1.28 }
1197    
1198     config_time=time(NULL)+ihost_state.config_ttl;
1199 pajs 1.10
1200 pajs 1.28 log_msg(LOG_DEBUG, "Config expires on %d\n", ihost_state.config_ttl);
1201 pajs 1.9 }
1202     }
1203 pajs 1.10
1204 pajs 1.28 sleep_delay=udp_time-time(NULL);
1205     log_msg(LOG_DEBUG, "Sleeping for %d", sleep_delay);
1206 tdb 1.53 #ifdef WIN32
1207     /* convert to millisecs */
1208     sleep_delay *= 1000;
1209     #endif
1210 pajs 1.10 if(sleep_delay>0) sleep(sleep_delay);
1211 tdb 1.51 }
1212    
1213 tdb 1.53 if(sg_shutdown()) {
1214     log_msg(LOG_ERR, "sg_shutdown failed: %s (%s)",
1215     sg_str_error(sg_get_error()), sg_get_error_arg());
1216     }
1217    
1218     #ifdef WIN32
1219     WSACleanup();
1220     if(run_as_service) {
1221     service_status.dwWin32ExitCode = 0;
1222     service_status.dwCurrentState = SERVICE_STOPPED;
1223     SetServiceStatus(hstatus, &service_status);
1224     }
1225     #endif
1226     log_msg(LOG_ERR, "ihost shutdown successfully");
1227     fclose(ihost_config.log);
1228    
1229 pajs 1.28 return(0);
1230 tdb 1.53
1231     out:
1232     #ifdef WIN32
1233     WSACleanup();
1234     service_stopped();
1235     #endif
1236     exit(1);
1237     }
1238    
1239     #ifdef WIN32
1240     int service_main(int argc, char **argv) {
1241     int error;
1242    
1243     service_status.dwServiceType = SERVICE_WIN32;
1244     service_status.dwCurrentState = SERVICE_START_PENDING;
1245     service_status.dwControlsAccepted = SERVICE_ACCEPT_STOP |
1246     SERVICE_ACCEPT_SHUTDOWN;
1247     service_status.dwWin32ExitCode = 0;
1248     service_status.dwServiceSpecificExitCode = 0;
1249     service_status.dwCheckPoint = 0;
1250     service_status.dwWaitHint = 0;
1251    
1252     hstatus = RegisterServiceCtrlHandler(SERVICENAME,
1253     (LPHANDLER_FUNCTION)control_handler);
1254     if(hstatus == (SERVICE_STATUS_HANDLE)0) {
1255     log_msg(LOG_CRIT, "RegisterServiceCtrlHandle failed");
1256     return -1;
1257     }
1258    
1259     return run_ihost();
1260     }
1261    
1262    
1263     void parse_w(int argc, char **argv) {
1264     if (strcasecmp(optarg, "start") == 0) {
1265     log_msg(LOG_ERR, "Attempting to start service...");
1266     run_server = 0;
1267     if(start_service())
1268     log_msg(LOG_ERR, "Service started");
1269     } else if (strcasecmp(optarg, "stop") == 0) {
1270     log_msg(LOG_ERR, "Attempting to stop service...");
1271     run_server = 0;
1272     if(stop_service())
1273     log_msg(LOG_ERR, "Service stopped");
1274     } else if (strcasecmp(optarg, "service") == 0) {
1275     run_as_service = 1;
1276     } else if (strcasecmp(optarg, "register") == 0) {
1277     log_msg(LOG_ERR, "Attempting to register service...");
1278     run_server = 0;
1279     int i = optind;
1280     optind = argc;
1281     /* Grab the remaining arguments and use each time the service
1282     * is started */
1283     if (register_service(argc-i, &argv[i]))
1284     log_msg(LOG_ERR, "Registered service successfully");
1285     } else if (strcasecmp(optarg, "unregister") == 0) {
1286     log_msg(LOG_ERR, "Attempting to unregister service...");
1287     run_server = 0;
1288     if(unregister_service())
1289     log_msg(LOG_ERR, "Unregistered service successfully");
1290     } else {
1291     fprintf(stderr, "Unknown -w option\n");
1292     usage(argv[0]);
1293     exit(1);
1294     }
1295     }
1296     #endif
1297    
1298    
1299     int main(int argc, char **argv){
1300     int cmdopt;
1301     extern int optind;
1302    
1303     /* Set default settings */
1304     ihost_config.verbose=1;
1305     ihost_config.daemon=1;
1306     /* Set all errors to go down stderr until told otherwise */
1307     ihost_config.log=stderr;
1308    
1309     /* Blank ihost_state to default settings */
1310     ihost_state.filtermanager_host=DEF_SERVER_NAME;
1311     ihost_state.filtermanager_port=DEF_SERVER_PORT;
1312     ihost_state.host_fqdn=NULL;
1313     ihost_state.host_ip=NULL;
1314     ihost_state.preset_fqdn = 0;
1315     ihost_state.preset_ip = 0;
1316     ihost_state.server_fqdn=NULL;
1317     ihost_state.file_list=NULL;
1318     ihost_state.last_modified=NULL;
1319    
1320     while((cmdopt=getopt(argc, argv, OPTSTRING)) != -1){
1321     switch(cmdopt){
1322     case 'v':
1323     ihost_config.verbose++;
1324     break;
1325    
1326     #ifndef WIN32
1327     case 'f':
1328     /* Force syslog logging since stderr will be closed in this case */
1329     ihost_config.daemon=0;
1330     break;
1331     #endif
1332    
1333     case 'V':
1334     fprintf(stderr, "%s version %s\n", argv[0], VERSION);
1335     break;
1336     case 'n':
1337     ihost_state.preset_fqdn = 1;
1338     ihost_state.host_fqdn = strdup(optarg);
1339     if(ihost_state.host_fqdn == NULL){
1340     fprintf(stderr, "Missing hostname\n");
1341     usage(argv[0]);
1342     }
1343     break;
1344     case 'i':
1345     /* Hmm.. Someone could set any string to be the IP, and it will let it */
1346     ihost_state.preset_ip = 1;
1347     ihost_state.host_ip = strdup(optarg);
1348     if(ihost_state.host_ip == NULL){
1349     fprintf(stderr, "Missing ip\n");
1350     usage(argv[0]);
1351     }
1352     break;
1353    
1354     case 's':
1355     ihost_state.filtermanager_host=strdup(optarg);
1356     break;
1357    
1358     case 'p':
1359     ihost_state.filtermanager_port=atoi(optarg);
1360     break;
1361    
1362     #ifdef WIN32
1363     case 'w':
1364     parse_w(argc, argv);
1365     break;
1366     #endif
1367    
1368     case 'h':
1369     default:
1370     usage(argv[0]);
1371     exit(1);
1372     }
1373     }
1374    
1375     #ifdef WIN32
1376     if (run_server) {
1377     if(run_as_service) {
1378     if((ihost_config.log=fopen(LOG_FILE, "a"))==NULL){
1379     ihost_config.log=stderr;
1380     log_msg(LOG_CRIT, "Failed to open Logfiles %s for writing", LOG_FILE);
1381     exit(1);
1382     }
1383     log_msg(LOG_ERR, "Starting Service-Mode i-host");
1384     SERVICE_TABLE_ENTRY service_table[2];
1385     service_table[0].lpServiceName = SERVICENAME;
1386     service_table[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)service_main;
1387     service_table[1].lpServiceName = NULL;
1388     service_table[1].lpServiceProc = NULL;
1389     return StartServiceCtrlDispatcher(service_table);
1390     } else {
1391     log_msg(LOG_ERR, "Starting User-Mode i-host");
1392     return run_ihost();
1393     }
1394     }
1395     #else
1396     return run_ihost();
1397     #endif
1398 pajs 1.1 }