diff options
Diffstat (limited to 'src/zabbix_agent_win32')
33 files changed, 0 insertions, 7996 deletions
diff --git a/src/zabbix_agent_win32/Debug/ZabbixW32.exe b/src/zabbix_agent_win32/Debug/ZabbixW32.exe Binary files differdeleted file mode 100755 index 13ebe08f..00000000 --- a/src/zabbix_agent_win32/Debug/ZabbixW32.exe +++ /dev/null diff --git a/src/zabbix_agent_win32/Release/ZabbixW32.exe b/src/zabbix_agent_win32/Release/ZabbixW32.exe Binary files differdeleted file mode 100755 index 13b99883..00000000 --- a/src/zabbix_agent_win32/Release/ZabbixW32.exe +++ /dev/null diff --git a/src/zabbix_agent_win32/ZabbixW32.dsp b/src/zabbix_agent_win32/ZabbixW32.dsp deleted file mode 100644 index 24a174af..00000000 --- a/src/zabbix_agent_win32/ZabbixW32.dsp +++ /dev/null @@ -1,247 +0,0 @@ -# Microsoft Developer Studio Project File - Name="ZabbixW32" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=ZabbixW32 - Win32 Debug -!MESSAGE This is not a valid makefile. To build this project using NMAKE, -!MESSAGE use the Export Makefile command and run -!MESSAGE -!MESSAGE NMAKE /f "ZabbixW32.mak". -!MESSAGE -!MESSAGE You can specify a configuration when running NMAKE -!MESSAGE by defining the macro CFG on the command line. For example: -!MESSAGE -!MESSAGE NMAKE /f "ZabbixW32.mak" CFG="ZabbixW32 - Win32 Debug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "ZabbixW32 - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "ZabbixW32 - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "ZabbixW32 - Win32 Release" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "Release" -# PROP BASE Intermediate_Dir "Release" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "Release" -# PROP Intermediate_Dir "Release" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /MT /W3 /GX /O2 /I "../../include/" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "HAVE_ASSERT_H" /FR /YX /FD /c -# ADD BASE RSC /l 0x409 /d "NDEBUG" -# ADD RSC /l 0x409 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 -# ADD LINK32 ws2_32.lib pdh.lib psapi.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386 - -!ELSEIF "$(CFG)" == "ZabbixW32 - Win32 Debug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "Debug" -# PROP BASE Intermediate_Dir "Debug" -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "Debug" -# PROP Intermediate_Dir "Debug" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /MTd /W4 /Gm /GX /ZI /Od /I "../../include/" /D "_DEBUG" /D "HAVE_ASSERT_H" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /FR /YX /FD /GZ /c -# ADD BASE RSC /l 0x409 /d "_DEBUG" -# ADD RSC /l 0x409 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept -# ADD LINK32 ws2_32.lib pdh.lib psapi.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept - -!ENDIF - -# Begin Target - -# Name "ZabbixW32 - Win32 Release" -# Name "ZabbixW32 - Win32 Debug" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\active.cpp -# End Source File -# Begin Source File - -SOURCE=.\alias.cpp -# End Source File -# Begin Source File - -SOURCE=.\base64.cpp -# End Source File -# Begin Source File - -SOURCE=.\collect.cpp -# End Source File -# Begin Source File - -SOURCE=.\comm.cpp -# End Source File -# Begin Source File - -SOURCE=.\config.cpp -# End Source File -# Begin Source File - -SOURCE=.\eventlog.cpp -# End Source File -# Begin Source File - -SOURCE=.\execute.cpp -# End Source File -# Begin Source File - -SOURCE=.\log.cpp -# End Source File -# Begin Source File - -SOURCE=.\logfiles.cpp -# End Source File -# Begin Source File - -SOURCE=.\main.cpp -# End Source File -# Begin Source File - -SOURCE=.\md5.cpp -# End Source File -# Begin Source File - -SOURCE=.\network.cpp -# End Source File -# Begin Source File - -SOURCE=.\procinfo.cpp -# End Source File -# Begin Source File - -SOURCE=.\service.cpp -# End Source File -# Begin Source File - -SOURCE=.\sysinfo.cpp -# End Source File -# Begin Source File - -SOURCE=.\util.cpp -# End Source File -# Begin Source File - -SOURCE=.\xml.cpp -# End Source File -# Begin Source File - -SOURCE=.\xml_comms.cpp -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=..\..\include\common.h -# End Source File -# Begin Source File - -SOURCE=.\md5.h -# End Source File -# Begin Source File - -SOURCE=.\zabbixw32.h -# End Source File -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# Begin Source File - -SOURCE=.\icon1.ico -# End Source File -# Begin Source File - -SOURCE=.\zabbixw32.rc -# End Source File -# End Group -# Begin Group "Message Files" - -# PROP Default_Filter ".mc" -# Begin Source File - -SOURCE=.\messages.mc - -!IF "$(CFG)" == "ZabbixW32 - Win32 Release" - -# Begin Custom Build - Message Compiler -ProjDir=. -InputPath=.\messages.mc -InputName=messages - -BuildCmds= \ - mc -s -U -h $(ProjDir) -r $(ProjDir) $(InputName) \ - del $(ProjDir)\$(InputName).rc \ - - -"$(InputName).h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - $(BuildCmds) - -"Msg00001.bin" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - $(BuildCmds) -# End Custom Build - -!ELSEIF "$(CFG)" == "ZabbixW32 - Win32 Debug" - -# Begin Custom Build - Message Compiler -ProjDir=. -InputPath=.\messages.mc -InputName=messages - -BuildCmds= \ - mc -s -U -h $(ProjDir) -r $(ProjDir) $(InputName) \ - del $(ProjDir)\$(InputName).rc \ - - -"$(InputName).h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - $(BuildCmds) - -"Msg00001.bin" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" - $(BuildCmds) -# End Custom Build - -!ENDIF - -# End Source File -# End Group -# Begin Source File - -SOURCE=..\..\..\tmp\EventLog.asp -# End Source File -# End Target -# End Project diff --git a/src/zabbix_agent_win32/ZabbixW32.dsw b/src/zabbix_agent_win32/ZabbixW32.dsw deleted file mode 100644 index 42daf3fa..00000000 --- a/src/zabbix_agent_win32/ZabbixW32.dsw +++ /dev/null @@ -1,29 +0,0 @@ -Microsoft Developer Studio Workspace File, Format Version 6.00 -# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE! - -############################################################################### - -Project: "ZabbixW32"=.\ZabbixW32.dsp - Package Owner=<4> - -Package=<5> -{{{ -}}} - -Package=<4> -{{{ -}}} - -############################################################################### - -Global: - -Package=<5> -{{{ -}}} - -Package=<3> -{{{ -}}} - -############################################################################### - diff --git a/src/zabbix_agent_win32/active.cpp b/src/zabbix_agent_win32/active.cpp deleted file mode 100644 index 08bbaabe..00000000 --- a/src/zabbix_agent_win32/active.cpp +++ /dev/null @@ -1,774 +0,0 @@ -/* -** ZABBIX -** Copyright (C) 2000-2005 SIA Zabbix -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -**/ - -//#include "config.h" - -/*#include <netdb.h> - -#include <stdlib.h> -#include <stdio.h> - -#include <unistd.h> -#include <signal.h> - -#include <time.h> - -#include <errno.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <arpa/inet.h>*/ - -/* No warning for bzero */ -#include <string.h> -#include <time.h> - -/*#include <sys/types.h> -#include <sys/stat.h> -#include <fcntl.h>*/ - -/* For setpriority */ -/*#include <sys/time.h> -#include <sys/resource.h> -*/ - -/* Required for getpwuid */ -/*#include <pwd.h> - -#include "common.h" -#include "sysinfo.h" - -#include "pid.h" -#include "log.h" -#include "cfg.h" -#include "stats.h" -#include "active.h" -#include "logfiles.h" -*/ - -#include "zabbixw32.h" - -#define MAX_LINES_PER_SECOND 10 - -#define METRIC struct metric_type -METRIC -{ - char *key; - int refresh; - int nextcheck; - int status; - int lastlogsize; -}; - -METRIC *metrics=NULL; - -static void InitMetrics() -{ -LOG_FUNC_CALL("In InitMetrics()"); - if(metrics==NULL) - { - metrics=(METRIC *)malloc(sizeof(METRIC)); - metrics[0].key=NULL; - } -LOG_FUNC_CALL("End of InitMetrics()"); -} - -static void FreeMetrics(void) -{ - int i; -LOG_FUNC_CALL("In FreeMetrics()"); - for(i=0;;i++) - { - if(metrics[i].key == NULL) break; - free(metrics[i].key); - metrics[i].status = ITEM_STATUS_NOTSUPPORTED; - } - free(metrics); -LOG_FUNC_CALL("End of FreeMetrics()"); -} - -void disable_all_metrics() -{ - int i; -LOG_FUNC_CALL("In disable_all_metrics()"); -INIT_CHECK_MEMORY(main); - for(i=0;;i++) - { - if(metrics[i].key == NULL) break; - - metrics[i].status = ITEM_STATUS_NOTSUPPORTED; - } -CHECK_MEMORY(main,"disable_all_metrics","end"); -LOG_FUNC_CALL("End of disable_all_metrics()"); -} - -int get_min_nextcheck() -{ - int i; - int min=-1; - int nodata=0; - -LOG_FUNC_CALL("In get_min_nextcheck()"); -INIT_CHECK_MEMORY(main); - - for(i=0;;i++) - { - if(metrics[i].key == NULL) break; - - if( (metrics[i].status == ITEM_STATUS_ACTIVE) && - ((metrics[i].nextcheck < min) || (min == -1))) - { - nodata=1; - min=metrics[i].nextcheck; - } - } - - if(nodata==0) - { - min = FAIL; - } - -CHECK_MEMORY(main,"add_check","end"); -LOG_FUNC_CALL("End of get_min_nextcheck()"); - return min; -} - -void add_check(char *key, int refresh, int lastlogsize) -{ - int i; - -LOG_FUNC_CALL("In add_check()"); - - for(i=0;;i++) - { - if(metrics[i].key == NULL) - { - metrics[i].key=strdup(key); - metrics[i].refresh=refresh; - metrics[i].nextcheck=0; - metrics[i].status=ITEM_STATUS_ACTIVE; - metrics[i].lastlogsize=lastlogsize; - - metrics=(METRIC *)realloc(metrics,(i+2)*sizeof(METRIC)); - metrics[i+1].key=NULL; - break; - } - else if(strcmp(metrics[i].key,key)==0) - { - if(metrics[i].refresh!=refresh) - { - metrics[i].nextcheck=0; - } - metrics[i].refresh=refresh; - metrics[i].lastlogsize=lastlogsize; - metrics[i].status=ITEM_STATUS_ACTIVE; - break; - } - } -LOG_FUNC_CALL("End of add_check()"); -} - -// Return position of Nth delimiter from right size, 0 - otherwise -int strnrchr(char *str, int num, char delim) -{ - int i=0; - int n=0; - -LOG_FUNC_CALL("In strnrchr()"); -INIT_CHECK_MEMORY(main); - - for(i=strlen(str)-1;i>=0;i--) - { - if(str[i]==delim) n++; - if(n==num) break; - } - if(i==-1) i=0; -CHECK_MEMORY(main,"strnrchr","end"); -LOG_FUNC_CALL("End of strnrchr()"); - return i; -} - -/* Parse list of active checks received from server */ -int parse_list_of_checks(char *str) -{ - char line[MAX_BUF_LEN]; - char - key[MAX_STRING_LEN], - refresh[MAX_STRING_LEN], - lastlogsize[MAX_STRING_LEN]; - //char *s1, *s2; - char *pos; - char *str_copy; - int p1,p2; - -LOG_FUNC_CALL("In parse_list_of_checks()"); - disable_all_metrics(); - - str_copy=str; - - pos=strchr(str_copy,'\n'); - //line=(char *)strtok(str,"\n"); - - while(pos!=NULL) - { - memset(line,0,sizeof(line)); - strncpy(line,str_copy,pos-str_copy); - - if(strcmp(line,"ZBX_EOF")==0) break; - -// sscanf(line,"%s:%d:%d",key,&r,&l); - - p2=strnrchr(line,1,':'); - p1=strnrchr(line,2,':'); - - memset(key,0,sizeof(key)); - memset(refresh,0,sizeof(refresh)); - memset(lastlogsize,0,sizeof(lastlogsize)); - - strcpy(lastlogsize,line+p2+1); -// WriteLog(MSG_SOCKET_ERROR,EVENTLOG_ERROR_TYPE,"s",lastlogsize); - - strncpy(key,line,p1); -// WriteLog(MSG_SOCKET_ERROR,EVENTLOG_ERROR_TYPE,"s",key); - - strncpy(refresh,line+p1+1,p2-p1-1); -// WriteLog(MSG_SOCKET_ERROR,EVENTLOG_ERROR_TYPE,"s",refresh); - -// key=(char *)strtok(line,":"); -// refresh=(char *)strtok(NULL,":"); -// lastlogsize=(char *)strtok(NULL,":"); - - add_check(key, atoi(refresh), atoi(lastlogsize)); -// add_check(key, r, l); - -// line=(char *)strtok(NULL,"\n"); - str_copy=pos+1; - pos=strchr(str_copy,'\n'); - } - -LOG_FUNC_CALL("End of parse_list_of_checks()"); - return SUCCEED; -} - -int get_active_checks(char *server, int port, char *error, int max_error_len) -{ -// int s; - SOCKET s; - int len,amount_read; - char c[MAX_BUF_LEN]; - - struct hostent *hp; - - struct sockaddr_in servaddr_in; - -LOG_FUNC_CALL("In get_active_checks()"); -// zabbix_log( LOG_LEVEL_DEBUG, "get_active_checks: host[%s] port[%d]", server, port); - - servaddr_in.sin_family=AF_INET; - hp=gethostbyname(server); - - if(hp==NULL) - { -// zabbix_log( LOG_LEVEL_WARNING, "gethostbyname() failed [%s]", hstrerror(h_errno)); -// _snprintf(error, max_error_len,"gethostbyname() failed [%s]", hstrerror(h_errno)); - return NETWORK_ERROR; - } - - servaddr_in.sin_addr.s_addr=((struct in_addr *)(hp->h_addr))->s_addr; - - servaddr_in.sin_port=htons((unsigned short)port); - - s=socket(AF_INET,SOCK_STREAM,0); - - if(s == -1) - { -// zabbix_log(LOG_LEVEL_WARNING, "Cannot create socket [%s]", -// strerror(errno)); - return FAIL; - } - - if( connect(s,(struct sockaddr *)&servaddr_in,sizeof(struct sockaddr_in)) == -1 ) - { - switch (errno) - { - case WSAETIMEDOUT: -// zabbix_log( LOG_LEVEL_WARNING, "Timeout while connecting to [%s:%d]",server,port); - _snprintf(error, max_error_len, "Timeout while connecting to [%s:%d]",server,port); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",error); - break; - case WSAEHOSTUNREACH: -// zabbix_log( LOG_LEVEL_WARNING, "No route to host [%s:%d]",server,port); - _snprintf(error, max_error_len,"No route to host [%s:%d]",server,port); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",error); - break; - default: -// zabbix_log( LOG_LEVEL_WARNING, "Cannot connect to [%s:%d] [%s]",server,port,strerror(errno)); - _snprintf(error, max_error_len,"Cannot connect to [%s:%d] [%s]",server,port,strerror(errno)); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",error); - } - closesocket(s); - return NETWORK_ERROR; - } - - sprintf(c,"%s\n%s\n","ZBX_GET_ACTIVE_CHECKS",confHostname); -// zabbix_log(LOG_LEVEL_DEBUG, "Sending [%s]", c); - - if( sendto(s,c,strlen(c),0,(struct sockaddr *)&servaddr_in,sizeof(struct sockaddr_in)) == -1 ) -// if( write(s,c,strlen(c)) == -1 ) - { - switch (errno) - { - case WSAETIMEDOUT: -// zabbix_log( LOG_LEVEL_WARNING, "Timeout while sending data to [%s:%d]",server,port); - _snprintf(error, max_error_len,"Timeout while sending data to [%s:%d]",server,port); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",error); - - break; - default: -// zabbix_log( LOG_LEVEL_WARNING, "Error while sending data to [%s:%d] [%s]",server,port,strerror(errno)); - _snprintf(error, max_error_len,"Error while sending data to [%s:%d] [%s]",server,port,strerror(errno)); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",error); - } - closesocket(s); - return FAIL; - } - - memset(c,0,MAX_BUF_LEN); - - //zabbix_log(LOG_LEVEL_DEBUG, "Before read"); - - amount_read = 0; - - do - { - len=sizeof(struct sockaddr_in); - len=recvfrom(s,c+amount_read,MAX_BUF_LEN-1-amount_read,0,(struct sockaddr *)&servaddr_in,(int *)&len); - -// len=read(s,c+amount_read,(MAX_BUF_LEN-1)-amount_read); - if (len > 0) - { - amount_read += len; - } - if(len == -1) - { - switch (errno) - { - case WSAETIMEDOUT: -// zabbix_log( LOG_LEVEL_WARNING, "Timeout while receiving data from [%s:%d]",server,port); - _snprintf(error, max_error_len,"Timeout while receiving data from [%s:%d]",server,port); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",error); - break; - case WSAECONNRESET: -// zabbix_log( LOG_LEVEL_WARNING, "Connection reset by peer."); - _snprintf(error, max_error_len,"Connection reset by peer."); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",error); - closesocket(s); - return NETWORK_ERROR; - default: -// zabbix_log( LOG_LEVEL_WARNING, "Error while receiving data from [%s:%d] [%s]",server,port,strerror(errno)); - _snprintf(error, max_error_len,"Error while receiving data from [%s:%d] [%s]",server,port,strerror(errno)); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",error); - } - closesocket(s); - return FAIL; - } - } - while (len > 0); - -/* while((len=read(s,tmp,MAX_BUF_LEN-1))>0) - { - if(len == -1) - { - switch (errno) - { - case WSAETIMEDOUT: - zabbix_log( LOG_LEVEL_WARNING, "Timeout while receiving data from [%s:%d]",server,port); - zbx_snprintf(error,max_error_len,"Timeout while receiving data from [%s:%d]",server,port); - break; - case ECONNRESET: - zabbix_log( LOG_LEVEL_WARNING, "Connection reset by peer."); - zbx_snprintf(error,max_error_len,"Connection reset by peer."); - close(s); - return NETWORK_ERROR; - default: - zabbix_log( LOG_LEVEL_WARNING, "Error while receiving data from [%s:%d] [%s]",server,port,strerror(errno)); - zbx_snprintf(error,max_error_len,"Error while receiving data from [%s:%d] [%s]",server,port,strerror(errno)); - } - close(s); - return FAIL; - } - strncat(c,tmp,len); - } - zabbix_log(LOG_LEVEL_DEBUG, "Read [%s]", c);*/ - - parse_list_of_checks(c); - - if( closesocket(s)!=0 ) - { -// zabbix_log(LOG_LEVEL_WARNING, "Problem with close [%s]", strerror(errno)); - } - -// LOG_DEBUG_INFO("s","get_active_checks: end"); -LOG_FUNC_CALL("End of get_active_checks()"); - return SUCCEED; -} - -int send_value(char *server,int port,char *host, char *key,char *value,char *lastlogsize, - char *timestamp, char *source, char *severity) -{ - int i,s; - char tosend[4*MAX_STRING_LEN]; - char result[1024]; - char tmp[1024]; - struct hostent *hp; - struct sockaddr_in myaddr_in; - struct sockaddr_in servaddr_in; - int ret = SUCCEED; - -LOG_FUNC_CALL("In send_value()"); -INIT_CHECK_MEMORY(main); - -//LOG_DEBUG_INFO("s","send_value: start"); -//LOG_DEBUG_INFO("s","send_value: key"); -//LOG_DEBUG_INFO("s",key); -//LOG_DEBUG_INFO("s","send_value: value"); -//LOG_DEBUG_INFO("s",value); - - - servaddr_in.sin_family=AF_INET; - hp=gethostbyname(server); - - if(hp==NULL) - { - sprintf(tmp,"gethostbyname() failed"); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",tmp); - ret = FAIL; - goto lbl_End; - } - - servaddr_in.sin_addr.s_addr=((struct in_addr *)(hp->h_addr))->s_addr; - - servaddr_in.sin_port=htons((unsigned short)port); - - s=socket(AF_INET,SOCK_STREAM,0); - if(s == -1) - { -// zabbix_log( LOG_LEVEL_WARNING, "Error in socket() [%s:%d] [%s]",server,port, strerror(errno)); - sprintf(tmp,"Error in socket()"); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",tmp); - ret = FAIL; - goto lbl_End; - } - -/* ling.l_onoff=1;*/ -/* ling.l_linger=0;*/ -/* if(setsockopt(s,SOL_SOCKET,SO_LINGER,&ling,sizeof(ling))==-1)*/ -/* {*/ -/* Ignore */ -/* }*/ - - myaddr_in.sin_family = AF_INET; - myaddr_in.sin_port=0; - myaddr_in.sin_addr.s_addr=INADDR_ANY; - - if( connect(s,(struct sockaddr *)&servaddr_in,sizeof(struct sockaddr_in)) == -1 ) - { -// zabbix_log( LOG_LEVEL_WARNING, "Error in connect() [%s:%d] [%s]",server, port, strerror(errno)); - sprintf(tmp,"Error in connect()"); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",tmp); - closesocket(s); - ret = FAIL; - goto lbl_End; - } -// LOG_DEBUG_INFO("s","send_value: 1"); - comms_create_request(host,key,value,lastlogsize,timestamp,source,severity,tosend,sizeof(tosend)-1); - -// i=strlen(tosend); -// LOG_DEBUG_INFO("d",i); - -// LOG_DEBUG_INFO("s",tosend); - -// LOG_DEBUG_INFO("s","send_value: 2"); -// sprintf(tosend,"%s:%s\n",shortname,value); - -// LOG_DEBUG_INFO("s",tosend); - - if( sendto(s,tosend,strlen(tosend),0,(struct sockaddr *)&servaddr_in,sizeof(struct sockaddr_in)) == -1 ) - { -// zabbix_log( LOG_LEVEL_WARNING, "Error in sendto() [%s:%d] [%s]",server, port, strerror(errno)); -sprintf(tmp,"Error in sendto()"); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",tmp); - - closesocket(s); - ret = FAIL; - goto lbl_End; - } -// LOG_DEBUG_INFO("s","send_value: 3"); - i=sizeof(struct sockaddr_in); -/* i=recvfrom(s,result,1023,0,(struct sockaddr *)&servaddr_in,(size_t *)&i);*/ - i=recvfrom(s,result,1023,0,(struct sockaddr *)&servaddr_in,(int *)&i); -// LOG_DEBUG_INFO("s","send_value: 4"); - if(s==-1) - { -// zabbix_log( LOG_LEVEL_WARNING, "Error in recvfrom() [%s:%d] [%s]",server,port, strerror(errno)); - sprintf(tmp,"Error in recvfrom()"); - WriteLog(MSG_ACTIVE_CHECKS,EVENTLOG_ERROR_TYPE,"s",tmp); - - closesocket(s); - ret = FAIL; - goto lbl_End; - } - -// LOG_DEBUG_INFO("s","send_value: 5"); - result[i-1]=0; -// LOG_DEBUG_INFO("s","send_value: 6"); - - if(strcmp(result,"OK") == 0) - { -// zabbix_log( LOG_LEVEL_DEBUG, "OK"); -// LOG_DEBUG_INFO("s","send result = OK"); - } - else - { -// zabbix_log( LOG_LEVEL_DEBUG, "NOT OK [%s]", shortname); -// LOG_DEBUG_INFO("s","send result = NOT OK"); - } - - if( closesocket(s)!=0 ) - { -// zabbix_log( LOG_LEVEL_WARNING, "Error in close() [%s] [%s]",server, strerror(errno)); - } - -// LOG_DEBUG_INFO("s","send_value: end"); - -lbl_End: - -CHECK_MEMORY(main, "send_value", "end"); -LOG_FUNC_CALL("End of send_value()"); - return ret; -} - -int process_active_checks(char *server, int port) -{ - REQUEST rq; - char value[MAX_STRING_LEN]; - char lastlogsize[MAX_STRING_LEN]; - char timestamp[MAX_STRING_LEN]; - char source[MAX_STRING_LEN]; - char severity[MAX_STRING_LEN]; - - int i, now, count; - int ret = SUCCEED; - - char c[MAX_STRING_LEN]; - char *filename; - -LOG_FUNC_CALL("In process_active_checks()"); -INIT_CHECK_MEMORY(main); - - now=time(NULL); - for(i=0;;i++) - { - if(metrics[i].key == NULL) break; - if(metrics[i].nextcheck>now) continue; - if(metrics[i].status!=ITEM_STATUS_ACTIVE) continue; - -// LOG_DEBUG_INFO("s",metrics[i].key); - /* Special processing for log files */ - if(strncmp(metrics[i].key,"log[",4) == 0) - { - timestamp[0]=0; - source[0]=0; - severity[0]=0; - strscpy(c,metrics[i].key); - filename=strtok(c,"[]"); - filename=strtok(NULL,"[]"); - - count=0; - while(process_log(filename,&metrics[i].lastlogsize,value) == 0) - { -//LOG_DEBUG_INFO("s","Active check: log[*]"); -//LOG_DEBUG_INFO("s",filename); -//LOG_DEBUG_INFO("s","Active check: value"); -//LOG_DEBUG_INFO("s",value); - sprintf(lastlogsize,"%d",metrics[i].lastlogsize); - if(send_value(server,port,confHostname,metrics[i].key, value, lastlogsize,timestamp,source,severity) == FAIL) - { - ret = FAIL; -// zabbix_log( LOG_LEVEL_WARNING, "Can't send value to server for active check [%s]", metrics[i].key); - break; - } - if(strcmp(value,"ZBX_NOTSUPPORTED\n")==0) - { - metrics[i].status=ITEM_STATUS_NOTSUPPORTED; -// zabbix_log( LOG_LEVEL_WARNING, "Active check [%s] is not supported. Disabled.", metrics[i].key); - break; - } - count++; - /* Do not flood ZABBIX server if file grows too fast */ - if(count >= MAX_LINES_PER_SECOND*metrics[i].refresh) break; - } - } - /* Special processing for log files */ - else if(strncmp(metrics[i].key,"eventlog[",9) == 0) - { - strscpy(c,metrics[i].key); - filename=strtok(c,"[]"); - filename=strtok(NULL,"[]"); - - count=0; - while(process_eventlog(filename,&metrics[i].lastlogsize, timestamp, source, severity, value) == 0) - { -// sprintf(shortname, "%s:%s",confHostname,metrics[i].key); -// zabbix_log( LOG_LEVEL_DEBUG, "%s",shortname); - -// LOG_DEBUG_INFO("s","pac:in loop()"); -// LOG_DEBUG_INFO("s","pac: metrics[i].key"); -// LOG_DEBUG_INFO("s",metrics[i].key); -// LOG_DEBUG_INFO("s","pac: value"); -// LOG_DEBUG_INFO("s",value); - -// LOG_DEBUG_INFO("s","pac:3"); - sprintf(lastlogsize,"%d",metrics[i].lastlogsize); - if(send_value(server,port,confHostname,metrics[i].key,value,lastlogsize,timestamp,source,severity) == FAIL) - { - ret = FAIL; - break; - } - if(strcmp(value,"ZBX_NOTSUPPORTED\n")==0) - { - metrics[i].status=ITEM_STATUS_NOTSUPPORTED; -// zabbix_log( LOG_LEVEL_WARNING, "Active check [%s] is not supported. Disabled.", metrics[i].key); - break; - } - count++; - /* Do not flood ZABBIX server if file grows too fast */ - if(count >= MAX_LINES_PER_SECOND*metrics[i].refresh) break; - } - } - else - { - timestamp[0]=0; - lastlogsize[0]=0; - source[0]=0; - severity[0]=0; - - // Init REQUEST - memset(&rq, 0, sizeof(REQUEST)); - strcpy(rq.cmd,metrics[i].key); - - ProcessCommand(rq.cmd,rq.result); - - ret = send_value(server,port,confHostname,metrics[i].key,rq.result,lastlogsize,timestamp,source,severity) ; - - if(strcmp(value,"ZBX_NOTSUPPORTED\n")==0) - { - metrics[i].status=ITEM_STATUS_NOTSUPPORTED; -LOG_DEBUG_INFO("s","Active check is not supported. Disabled"); - } - } - - metrics[i].nextcheck=time(NULL)+metrics[i].refresh; - } -CHECK_MEMORY(main, "process_active_checks", "end"); -LOG_FUNC_CALL("End of process_active_checks()"); - return ret; -} - -void refresh_metrics(char *server, int port, char *error, int max_error_len) -{ -LOG_FUNC_CALL("In refresh_metrics()"); - while(get_active_checks(server, port, error, max_error_len) != SUCCEED) - { -LOG_DEBUG_INFO("s","Getting list of active checks failed. Will retry after 60 seconds"); - - zbx_setproctitle("poller [sleeping for %d seconds]", 60*1000); - - Sleep(60*1000); - } -LOG_DEBUG_INFO("s","Out of refresh_metrics()"); -} - -void ActiveChecksThread(void *) -{ - char error[MAX_STRING_LEN]; - int sleeptime, nextcheck; - int nextrefresh; - -LOG_FUNC_CALL("In ActiveChecksThread()"); -INIT_CHECK_MEMORY(main); - - InitMetrics(); - - refresh_metrics(confServer, confServerPort, error, MAX_STRING_LEN); - nextrefresh=time(NULL)+300; - - for(;;) - { -INIT_CHECK_MEMORY(for); - if(process_active_checks(confServer, confServerPort) == FAIL) - { - Sleep(60*1000); -LOG_DEBUG_INFO("s","ActiveChecksThread - sleep 60000 (!!!)"); - continue; - } - - nextcheck = get_min_nextcheck(); - if(nextcheck == FAIL) - { - sleeptime=60; -LOG_DEBUG_INFO("s","ActiveChecksThread - sleep 60 (1)"); - } - else - { - sleeptime = nextcheck-time(NULL); - if(sleeptime<0) - { - sleeptime=0; -LOG_DEBUG_INFO("s","ActiveChecksThread - sleep 0 (1)"); - } - } - if(sleeptime>0) - { - if(sleeptime > 60) - { - sleeptime = 60; -LOG_DEBUG_INFO("s","ActiveChecksThread - sleep 60 (2)"); - } - - Sleep( sleeptime*1000 ); - } - else - { -// zabbix_log( LOG_LEVEL_DEBUG, "No sleeping" ); - } - - if(time(NULL)>=nextrefresh) - { - refresh_metrics(confServer, confServerPort, error, sizeof(error)); - nextrefresh=time(NULL)+300; - } - } -/**/ - FreeMetrics(); - -CHECK_MEMORY(main, "ActiveChecksThread", "end"); -LOG_FUNC_CALL("End of ActiveChecksThread()"); - - _endthread(); -} diff --git a/src/zabbix_agent_win32/active.h b/src/zabbix_agent_win32/active.h deleted file mode 100644 index 39e33dcf..00000000 --- a/src/zabbix_agent_win32/active.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -** ZABBIX -** Copyright (C) 2000-2005 SIA Zabbix -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -**/ - -#ifndef ZABBIX_ACTIVE_H -#define ZABBIX_ACTIVE_H - -extern char *CONFIG_HOSTNAME; -extern int CONFIG_REFRESH_ACTIVE_CHECKS; - -#define MAX_LINES_PER_SECOND 10 - -#define METRIC struct metric_type -METRIC -{ - char *key; - int refresh; - int nextcheck; - int status; - int lastlogsize; -}; - -pid_t child_active_make(int i,char *server, int port); - -#endif diff --git a/src/zabbix_agent_win32/alias.cpp b/src/zabbix_agent_win32/alias.cpp deleted file mode 100644 index f7bc3a26..00000000 --- a/src/zabbix_agent_win32/alias.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: alias.cpp -** -**/ - -#include "zabbixw32.h" - - -// -// Static data -// - -static ALIAS *aliasList=NULL; - - -// -// Add alias to the list -// Returns TRUE on success or FALSE if alias with that name already exist -// - -BOOL AddAlias(char *name,char *value) -{ -/* - ALIAS *alias; - BOOL ret = FALSE; - - // Find alias in the list - for(alias=aliasList;alias!=NULL;alias=alias->next) - if (!strcmp(alias->name,name)) - { - ret = FALSE; - break; - } - - if(ret == TRUE) - { - // Create new structure and add it to the list - alias=(ALIAS *)malloc(sizeof(ALIAS)); - if (alias==NULL) - { - memset(alias,0,sizeof(ALIAS)); - strncpy(alias->name,name,MAX_ALIAS_NAME-1); - alias->value=(char *)malloc(strlen(value)+1); - strcpy(alias->value,value); - alias->next=aliasList; - aliasList=alias; - } - else - { - ret = FALSE; - } - } - - return ret; -/**/ - - ALIAS *alias; - BOOL ret = FALSE; - - for(alias=aliasList; ; alias=alias->next) - { - /* Add new parameters */ - if(alias == NULL) - { - alias=(ALIAS *)malloc(sizeof(ALIAS)); - if (alias!=NULL) - { - memset(alias,0,sizeof(ALIAS)); - strncpy(alias->name, name, MAX_ALIAS_NAME-1); - alias->value = (char *)malloc(strlen(value)+1); - strcpy(alias->value,value); - alias->next=aliasList; - aliasList=alias; - - ret = TRUE; - } - break; - } - - /* Replace existing parameters */ - if (strcmp(alias->name, name) == 0) - { - if(alias->value) - free(alias->value); - - memset(alias, 0, sizeof(ALIAS)); - - strncpy(alias->name, name, MAX_ALIAS_NAME-1); - - alias->value = (char *)malloc(strlen(value)+1); - strcpy(alias->value, value); - - alias->next = aliasList; - aliasList = alias; - - ret = TRUE; - break; - } - } - return ret; -} - -void FreeAliasList(void) -{ - ALIAS *curr; - ALIAS *next; - - next = aliasList; - while(next!=NULL) - { - curr = next; - next = curr->next; - free(curr->value); - free(curr); - } -} - -// -// Checks parameter and expands it if aliased -// - -void ExpandAlias(char *orig,char *expanded) -{ - ALIAS *alias; - int ret = 1; - -INIT_CHECK_MEMORY(main); - - for(alias=aliasList;alias!=NULL;alias=alias->next) - if (!strcmp(alias->name,orig)) - { - strcpy(expanded,alias->value); - ret = 0; - break; - } - - if(ret == 1) - { - strcpy(expanded,orig); - } - -CHECK_MEMORY(main, "ExpandAlias","end"); -} diff --git a/src/zabbix_agent_win32/base64.cpp b/src/zabbix_agent_win32/base64.cpp deleted file mode 100644 index f11d7a7b..00000000 --- a/src/zabbix_agent_win32/base64.cpp +++ /dev/null @@ -1,256 +0,0 @@ -#include "zabbixw32.h" - -#define MAX_B64_SIZE 16*1024 - -static char base64_set [] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -void str_base64_encode(char *p_str, char *p_b64str, int in_size); -void str_base64_decode(char *p_b64str, char *p_str, int *p_out_size); -static char char_base64_encode(unsigned char uc); -static unsigned char char_base64_decode(char c); -static int is_base64 (char c); - -/*------------------------------------------------------------------------ - * - * Function : is_base64 - * - * Purpose : Is the character passed in a base64 character ? - * - * Parameters : - * - * Returns : - * - * Comments : - * - *----------------------------------------------------------------------*/ -static int is_base64 (char c) -{ - if ( (c >= '0' && c <= '9') - || (c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || c == '/' - || c == '+' - || c == '=' ) - - { - return 1; - } - - return 0; -} -/*------------------------------------------------------------------------ - * - * Function : char_base64_encode - * - * Purpose : Encode a byte into a base64 character - * - * Parameters : - * - * Returns : - * - * Comments : - * - *----------------------------------------------------------------------*/ -static char char_base64_encode(unsigned char uc) -{ - return base64_set[uc]; -} - -/*------------------------------------------------------------------------ - * - * Function : char_base64_decode - * - * Purpose : Decode a base64 character into a byte - * - * Parameters : - * - * Returns : - * - * Comments : - * - *----------------------------------------------------------------------*/ -static unsigned char char_base64_decode(char c) -{ - if (c >= 'A' && c <= 'Z') - { - return (unsigned char)(c - 'A'); - } - - if (c >= 'a' && c <= 'z') - { - return (unsigned char)(c - 'a' + 26); - } - - if (c >= '0' && c <= '9') - { - return (unsigned char)(c - '0' + 52); - } - - if (c == '+') - { - return (unsigned char)(62); - } - - return (unsigned char)(63); -} -/*------------------------------------------------------------------------ - * - * Function : str_base64_encode - * - * Purpose : Encode a string into a base64 string - * - * Parameters : p_str (in) - the string to encode - * p_b64str (out) - the encoded str to return - * in_size (in) - size (length) of input str - * Returns : - * - * Comments : - * - *----------------------------------------------------------------------*/ -void str_base64_encode(char *p_str, char *p_b64str, int in_size) -{ - int i; - unsigned char from1=0,from2=0,from3=0; - unsigned char to1=0,to2=0,to3=0,to4=0; - - if ( 0 == in_size ) - { - return; - }; - - for ( i = 0; i < in_size ; i += 3 ) - { - from1 = from2 = from3 = 0; - from1 = p_str[i]; - if (i+1 < in_size) - { - from2 = p_str[i+1]; - } - if (i+2 < in_size) - { - from3 = p_str[i+2]; - } - - to1 = to2 = to3 = to4 = 0; - to1 = (unsigned char)((from1>>2) & 0x3f); - to2 = (unsigned char)(((from1&0x3)<<4)|(from2>>4)); - to3 = (unsigned char)(((from2&0xf)<<2)|(from3>>6)); - to4 = (unsigned char)(from3&0x3f); - - *(p_b64str++) = char_base64_encode(to1); - *(p_b64str++) = char_base64_encode(to2); - - if (i+1 < in_size) - { - *(p_b64str++) = char_base64_encode(to3); - } - else - { - *(p_b64str++) = '='; /* Padding */ - } - if (i+2 < in_size) - { - *(p_b64str++) = char_base64_encode(to4); - } - else - { - *(p_b64str++) = '='; /* Padding */ - }; - -/* if ( i % (76/4*3) == 0) - { - *(p_b64str++) = '\r'; - *(p_b64str++) = '\n'; - }*/ - }; - - return; -} -/*------------------------------------------------------------------------ - * - * Function : str_base64_decode - * - * Purpose : Decode a base64 string into a string - * - * Parameters : p_b64str (in) - the base64 string to decode - * p_str (out) - the encoded str to return - * p_out_size (out) - the size (len) of the str decoded - * - * Returns : - * - * Comments : - * - *----------------------------------------------------------------------*/ -void str_base64_decode(char *p_b64str, char *p_str, int *p_out_size) -{ - int i; - int j = 0; - int in_size; - char from1='A',from2='A',from3='A',from4='A'; - unsigned char to1=0,to2=0,to3=0,to4=0; - char str_clean[MAX_B64_SIZE];/* str_clean is the string - * after removing the non-base64 - * characters - */ - - in_size = strlen(p_b64str); - memset(str_clean, 0, sizeof(str_clean)); - *p_out_size = 0; - - /* Clean-up input string */ - for ( i=0; i < in_size; i++ ) - { - if (is_base64(p_b64str[i])) - { - str_clean[j++] = p_b64str[i]; - } - } - - /* Re-define in_size after clean-up */ - in_size = strlen(str_clean); - - if ( 0 == in_size ) - { - return; - } - - for ( i=0; i < in_size ;i+=4) - { - from1 = from2 = from3 = from4 = 'A'; - from1 = str_clean[i]; - if ( i+1 < in_size ) - { - from2 = str_clean[i+1]; - } - if ( i+2 < in_size ) - { - from3 = str_clean[i+2]; - } - if ( i+3 < in_size ) - { - from4 = str_clean[i+3]; - }; - - to1 = to2 = to3 = to4 = 0; - to1 = char_base64_decode(from1); - to2 = char_base64_decode(from2); - to3 = char_base64_decode(from3); - to4 = char_base64_decode(from4); - - *(p_str++) = (char)((to1<<2)|(to2>>4)); - (*p_out_size)++; - if (from3 != '=') - { - *(p_str++) = (char)(((to2&0xf)<<4)|(to3>>2)); - (*p_out_size)++; - } - if (from4 != '=') - { - *(p_str++) = (char)(((to3&0x3)<<6)|to4); - (*p_out_size)++; - } - } - - return; -} diff --git a/src/zabbix_agent_win32/collect.cpp b/src/zabbix_agent_win32/collect.cpp deleted file mode 100644 index 43abac5b..00000000 --- a/src/zabbix_agent_win32/collect.cpp +++ /dev/null @@ -1,322 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** Support for non-English Windows versions (C) 2003 Harald Holzer -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: collect.cpp -** -**/ - -#include "zabbixw32.h" - - -// -// Global variables -// - -USER_COUNTER *userCounterList=NULL; -double statProcUtilization[MAX_CPU+1]; -double statProcUtilization5[MAX_CPU+1]; -double statProcUtilization15[MAX_CPU+1]; -double statProcLoad=0; -double statProcLoad5=0; -double statProcLoad15=0; -double statAvgCollectorTime=0; -double statMaxCollectorTime=0; - - -// -// Static variables -// - -static LONG cpuUsageHistory[MAX_CPU+1][900]; -static LONG cpuQueueHistory[900]; -static DWORD collectorTimesHistory[60]; - - -// -// Data collection thread -// - -void CollectorThread(void *) -{ - HQUERY query; - PDH_FMT_COUNTERVALUE value; - PDH_RAW_COUNTER rawCounter; // Generic raw counter for various parameters - PDH_STATUS status; - SYSTEM_INFO sysInfo; - USER_COUNTER *cptr = NULL; - PDH_STATISTICS statData; - char counterPath[MAX_COUNTER_PATH * 2 + 50]; - - PDH_HCOUNTER - cntCpuUsage[MAX_CPU+1], - cntCpuQueue=NULL; - - PDH_RAW_COUNTER - rawCpuUsage1[MAX_CPU+1], - rawCpuUsage2[MAX_CPU+1]; - - DWORD - i = 0, - cpuHistoryIdx = 0, - cpuQueueHistoryIdx = 0, - collectorTimesIdx = 0, - dwSleepTime = 0; - - -INIT_CHECK_MEMORY(main); -LOG_DEBUG_INFO("s", "CollectorThread start"); - - GetSystemInfo(&sysInfo); - - memset(collectorTimesHistory,0,sizeof(DWORD)*60); - collectorTimesIdx=0; - - // Prepare for CPU utilization collection - memset(cpuUsageHistory,0,sizeof(LONG)*(MAX_CPU+1)*900); - memset(statProcUtilization,0,sizeof(double)*(MAX_CPU+1)); - memset(statProcUtilization5,0,sizeof(double)*(MAX_CPU+1)); - memset(statProcUtilization15,0,sizeof(double)*(MAX_CPU+1)); - - if (PdhOpenQuery(NULL,0,&query)!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_OPEN_QUERY_FAILED,EVENTLOG_ERROR_TYPE,"e",GetLastError()); - goto lbl_End; - } - - - sprintf(counterPath,"\\%s(_Total)\\%s",GetCounterName(PCI_PROCESSOR),GetCounterName(PCI_PROCESSOR_TIME)); - -LOG_DEBUG_INFO("s","counterPath1"); -LOG_DEBUG_INFO("s",counterPath); - - if ((status=PdhAddCounter(query,counterPath, 0, &cntCpuUsage[0]))!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_ADD_COUNTER_FAILED,EVENTLOG_ERROR_TYPE,"ss", - (char *) &counterPath, GetPdhErrorText(status)); - goto lbl_CloseQuery; - } - - for(i=0;i<sysInfo.dwNumberOfProcessors;i++) - { - sprintf(counterPath,"\\%s(%d)\\%s", GetCounterName(PCI_PROCESSOR), i, GetCounterName(PCI_PROCESSOR_TIME)); - -LOG_DEBUG_INFO("s","counterPath2"); -LOG_DEBUG_INFO("s",counterPath); - - if ((status=PdhAddCounter(query,counterPath,0,&cntCpuUsage[i+1]))!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_ADD_COUNTER_FAILED,EVENTLOG_ERROR_TYPE,"ss", - counterPath,GetPdhErrorText(status)); - goto lbl_FreeCounters; - } - } - - if ((status=PdhCollectQueryData(query))!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_COLLECT_QUERY_DATA_FAILED,EVENTLOG_ERROR_TYPE,"s", - GetPdhErrorText(status)); - goto lbl_FreeCounters; - } - - for(i=0;i<sysInfo.dwNumberOfProcessors;i++) - PdhGetRawCounterValue(cntCpuUsage[i],NULL,&rawCpuUsage2[i]); - - cpuHistoryIdx=0; - - sprintf((char *) &counterPath, "\\%s\\%s", GetCounterName(PCI_SYSTEM), GetCounterName(PCI_PROCESSOR_QUEUE_LENGTH)); - -LOG_DEBUG_INFO("s","counterPath3"); -LOG_DEBUG_INFO("s",counterPath); - - // Prepare for CPU execution queue usage collection - if ((status=PdhAddCounter(query,(char *) &counterPath,0,&cntCpuQueue))!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_ADD_COUNTER_FAILED,EVENTLOG_ERROR_TYPE,"ss", - (char *) &counterPath,GetPdhErrorText(status)); - goto lbl_FreeCounters; - } - - memset(cpuQueueHistory,0,sizeof(LONG)*900); - cpuQueueHistoryIdx=0; - - // Add user counters to query - for(cptr=userCounterList;cptr!=NULL;cptr=cptr->next) - { - -LOG_DEBUG_INFO("s","counterPath4"); -LOG_DEBUG_INFO("s",counterPath); - - if ((status=PdhAddCounter(query,cptr->counterPath,0,&cptr->handle))!=ERROR_SUCCESS) - { - cptr->interval=-1; // Flag for unsupported counters - cptr->lastValue=NOTSUPPORTED; - WriteLog(MSG_USERDEF_COUNTER_FAILED,EVENTLOG_ERROR_TYPE,"sss", - cptr->name,cptr->counterPath,GetPdhErrorText(status)); - } - } - - // Data collection loop - WriteLog(MSG_COLLECTOR_INIT_OK,EVENTLOG_INFORMATION_TYPE,NULL); - SetEvent(eventCollectorStarted); - - do - { - LONG sum; - int j,n; - DWORD dwTicksStart,dwTicksElapsed; - -INIT_CHECK_MEMORY(do); - - dwTicksStart=GetTickCount(); - if ((status=PdhCollectQueryData(query))!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_COLLECT_QUERY_DATA_FAILED,EVENTLOG_ERROR_TYPE,"s", - GetPdhErrorText(status)); - } - - // Process CPU utilization data - for(i=0;i<=sysInfo.dwNumberOfProcessors;i++) - { - - PdhGetRawCounterValue(cntCpuUsage[i],NULL,&rawCpuUsage1[i]); - PdhCalculateCounterFromRawValue(cntCpuUsage[i],PDH_FMT_LONG, - &rawCpuUsage1[i],&rawCpuUsage2[i],&value); - cpuUsageHistory[i][cpuHistoryIdx]=value.longValue; - rawCpuUsage2[i]=rawCpuUsage1[i]; - - // Calculate average cpu usage for last minute - for(n=cpuHistoryIdx,j=0,sum=0;j<60;j++) - { - sum+=cpuUsageHistory[i][n--]; - if (n==-1) - n=899; - } - statProcUtilization[i]=((double)sum)/(double)60; - - // Calculate average cpu usage for last five minutes - for(n=cpuHistoryIdx,j=0,sum=0;j<300;j++) - { - sum+=cpuUsageHistory[i][n--]; - if (n==-1) - n=899; - } - statProcUtilization5[i]=((double)sum)/(double)300; - - // Calculate average cpu usage for last fifteen minutes - for(j=0,sum=0;j<900;j++) - sum+=cpuUsageHistory[i][j]; - statProcUtilization15[i]=((double)sum)/(double)900; - } - cpuHistoryIdx++; - if (cpuHistoryIdx==900) - cpuHistoryIdx=0; - - // Process CPU queue length data - PdhGetRawCounterValue(cntCpuQueue,NULL,&rawCounter); - PdhCalculateCounterFromRawValue(cntCpuQueue,PDH_FMT_LONG, - &rawCounter,NULL,&value); - cpuQueueHistory[cpuQueueHistoryIdx]=value.longValue; - - // Calculate average processor(s) load for last minute - for(n=cpuQueueHistoryIdx,j=0,sum=0;j<60;j++) - { - sum+=cpuQueueHistory[n--]; - if (n==-1) - n=899; - } - statProcLoad=((double)sum)/(double)60; - - // Calculate average processor(s) load for last five minutes - for(n=cpuQueueHistoryIdx,j=0,sum=0;j<300;j++) - { - sum+=cpuQueueHistory[n--]; - if (n==-1) - n=899; - } - statProcLoad5=((double)sum)/(double)300; - - // Calculate average processor(s) load for last fifteen minutes - for(j=0,sum=0;j<900;j++) - sum+=cpuQueueHistory[j]; - statProcLoad15=((double)sum)/(double)900; - - cpuQueueHistoryIdx++; - if (cpuQueueHistoryIdx==900) - cpuQueueHistoryIdx=0; - - // Process user-defined counters - for(cptr=userCounterList;cptr!=NULL;cptr=cptr->next) - if (cptr->interval>0) // Active counter? - { - PdhGetRawCounterValue(cptr->handle,NULL,&cptr->rawValueArray[cptr->currPos++]); - if (cptr->currPos==cptr->interval) - cptr->currPos=0; - PdhComputeCounterStatistics(cptr->handle,PDH_FMT_DOUBLE,cptr->currPos, - cptr->interval,cptr->rawValueArray,&statData); - cptr->lastValue=statData.mean.doubleValue; - } - - // Calculate time spent on sample processing and issue warning if it exceeds threshold - dwTicksElapsed=GetTickCount()-dwTicksStart; - if (dwTicksElapsed>confMaxProcTime) - { - LOG_DEBUG_INFO("s","Processing took too many time."); - LOG_DEBUG_INFO("d",dwTicksElapsed); - } - - // Save processing time to history buffer - collectorTimesHistory[collectorTimesIdx++]=dwTicksElapsed; - if (collectorTimesIdx==60) - collectorTimesIdx=0; - - // Calculate average cpu usage for last minute - for(i=0,sum=0;i<60;i++) - sum+=collectorTimesHistory[i]; - statAvgCollectorTime=((double)sum)/(double)60; - - // Change maximum processing time if needed - if ((double)dwTicksElapsed>statMaxCollectorTime) - statMaxCollectorTime=(double)dwTicksElapsed; - // Calculate sleeping time. We will sleep not less than 500 milliseconds even - // if processing takes more than 500 milliseconds - dwSleepTime=(dwTicksElapsed>500) ? 500 : (1000-dwTicksElapsed); - -CHECK_MEMORY(do, "CollectorThread","end do"); - } while(WaitForSingleObject(eventShutdown,dwSleepTime)==WAIT_TIMEOUT); - -lbl_FreeCounters: - PdhRemoveCounter(cntCpuQueue); - - if(cptr) - PdhRemoveCounter(cptr->handle); - - for(i=0; i<(MAX_CPU+1); i++) - PdhRemoveCounter(cntCpuUsage[i]); - - -lbl_CloseQuery: - PdhCloseQuery(query); - -lbl_End: - -LOG_DEBUG_INFO("s", "CollectorThread end"); -CHECK_MEMORY(main, "CollectorThread","end"); - - _endthread(); -} diff --git a/src/zabbix_agent_win32/comm.cpp b/src/zabbix_agent_win32/comm.cpp deleted file mode 100644 index 34f9fa8d..00000000 --- a/src/zabbix_agent_win32/comm.cpp +++ /dev/null @@ -1,244 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: comm.cpp -** -**/ - -#include "zabbixw32.h" - -// -// Global data -// - -double statAcceptedRequests=0; -double statRejectedRequests=0; -double statTimedOutRequests=0; -double statAcceptErrors=0; - - -// -// Validates server's address -// - -static BOOL IsValidServerAddr(DWORD addr) -{ - DWORD i; - BOOL ret= FALSE; - -INIT_CHECK_MEMORY(main); - for(i=0;i<confServerCount;i++) - if (addr==confServerAddr[i]) - ret = TRUE; - -CHECK_MEMORY(main, "IsValidServerAddr", "end"); - return ret; -} - - -// -// Client communication -// - -void Communicate(SOCKET sock) -{ - TIMEVAL timeout = {0,0}; - FD_SET rdfs; - REQUEST rq; - - int rc = 0; - -LOG_FUNC_CALL("In Communicate()"); -INIT_CHECK_MEMORY(main); - - // Wait for command from server - FD_ZERO(&rdfs); - FD_SET(sock,&rdfs); // ignore WARNING '...whle(0)' - - timeout.tv_sec = COMMAND_TIMEOUT; - timeout.tv_usec = 0; - rc = select(sock+1, &rdfs, (fd_set *)NULL, (fd_set *)NULL, &timeout); - if (rc == SOCKET_ERROR) - { - WriteLog(MSG_SELECT_ERROR,EVENTLOG_ERROR_TYPE,"e",WSAGetLastError()); - goto end_session; - } - if(rc == 0) - { - WriteLog(MSG_COMMAND_TIMEOUT,EVENTLOG_WARNING_TYPE,NULL); - goto end_session; - } - - // Init REQUEST - memset(&rq, 0, sizeof(REQUEST)); - rc = recv(sock,rq.cmd,MAX_ZABBIX_CMD_LEN-1,0); - - if(rc <= 0) - { - WriteLog(MSG_RECV_ERROR,EVENTLOG_ERROR_TYPE,"s",strerror(errno)); - goto end_session; - } - rq.cmd[rc-1]=0; - - ProcessCommand(rq.cmd,rq.result); - goto send_result; - -end_session: - sprintf(rq.result,"ERROR\n"); - -send_result: - send(sock,rq.result,strlen(rq.result),0); - -CHECK_MEMORY(main, "Communicate", "end"); -LOG_FUNC_CALL("End of Communicate()"); -} - -// -// Client connector thread -// - -unsigned int __stdcall AcceptThread(void *arg) -{ - SOCKET sock = (SOCKET)arg; - struct sockaddr_in servAddr; - int iSize=0,errorCount=0; - - LOG_DEBUG_INFO("s", "In AcceptThread()"); - INIT_CHECK_MEMORY(main); - - // Wait for connection requests - for(;;) - { - INIT_CHECK_MEMORY(while); - SOCKET sockClient; - - iSize = sizeof(struct sockaddr_in); - if ((sockClient=accept(sock,(struct sockaddr *)&servAddr,&iSize)) < 0) - { - int error = WSAGetLastError(); - - if (error!=WSAEINTR) - WriteLog(MSG_ACCEPT_ERROR,EVENTLOG_ERROR_TYPE,"e",error); - - errorCount++; - statAcceptErrors++; - if (errorCount>1000) - { - WriteLog(MSG_TOO_MANY_ERRORS,EVENTLOG_WARNING_TYPE,NULL); - errorCount=0; - } - Sleep(500); - continue; - } - - errorCount=0; /* Reset consecutive errors counter */ - - if (IsValidServerAddr(servAddr.sin_addr.S_un.S_addr)) - { - statAcceptedRequests++; - Communicate(sockClient); - } else { - statRejectedRequests++; - } - - shutdown(sockClient,2); - closesocket(sockClient); - - CHECK_MEMORY(while, "AcceptThread", "while"); - } - CHECK_MEMORY(main, "AcceptThread", "end"); - LOG_DEBUG_INFO("s", "End of AcceptThread()"); - - _endthreadex(0); - return 0; -} - - -// -// TCP/IP Listener -// - -void ListenerThread(void *) -{ -#define MAX_LISTENERS_COUNT 10 - - HANDLE hThread[MAX_LISTENERS_COUNT]; - unsigned int tid[MAX_LISTENERS_COUNT]; - - SOCKET sock; - struct sockaddr_in servAddr; - //int iSize=0, errorCount=0; - - int i=0; - - LOG_DEBUG_INFO("s", "In ListenerThread()"); - INIT_CHECK_MEMORY(main); - - // Create socket - if ((sock=socket(AF_INET,SOCK_STREAM,0)) == INVALID_SOCKET) - { - WriteLog(MSG_SOCKET_ERROR,EVENTLOG_ERROR_TYPE,"e",WSAGetLastError()); - LOG_DEBUG_INFO("s", "End of ListenerThread() Error: 1"); - _endthread(); - exit(1); - } - - // Fill in local address structure - memset(&servAddr,0,sizeof(struct sockaddr_in)); - servAddr.sin_family = AF_INET; - servAddr.sin_addr.s_addr = htonl(INADDR_ANY); - servAddr.sin_port = htons(confListenPort); - - // Bind socket - if (bind(sock,(struct sockaddr *)&servAddr,sizeof(struct sockaddr_in)) == SOCKET_ERROR) - { - WriteLog(MSG_BIND_ERROR,EVENTLOG_ERROR_TYPE,"e",WSAGetLastError()); - LOG_DEBUG_INFO("s", "End of ListenerThread() Error: 2"); - _endthread(); - exit(1); - } - - // Set up queue - if(listen(sock,SOMAXCONN) == SOCKET_ERROR) - { - WriteLog(MSG_LISTEN_ERROR,EVENTLOG_ERROR_TYPE,"e",WSAGetLastError()); - LOG_DEBUG_INFO("s", "End of ListenerThread() Error: 2"); - _endthread(); - exit(1); - } - - for(i = 0; i < MAX_LISTENERS_COUNT; i++) - { - hThread[i] = (HANDLE)_beginthreadex(NULL,0,AcceptThread,(void *)sock,0,&(tid[i])); - if(hThread[i] >=0 ) - WriteLog(MSG_INFORMATION,EVENTLOG_INFORMATION_TYPE,"ds", tid[i], ": Listen thread is Started."); - } - - for(i = 0; i < MAX_LISTENERS_COUNT; i++) - { - if(WaitForSingleObject(hThread[i], INFINITE) == WAIT_OBJECT_0) - WriteLog(MSG_INFORMATION,EVENTLOG_INFORMATION_TYPE,"ds", tid[i], ": Listen thread is Terminated."); - - CloseHandle( hThread ); - } - - CHECK_MEMORY(main, "ListenerThread", "end"); - - LOG_DEBUG_INFO("s", "End of ListenerThread()"); - _endthread(); -} diff --git a/src/zabbix_agent_win32/config.cpp b/src/zabbix_agent_win32/config.cpp deleted file mode 100644 index 2653b963..00000000 --- a/src/zabbix_agent_win32/config.cpp +++ /dev/null @@ -1,487 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: config.cpp -** -**/ - -#include "zabbixw32.h" - - -// -// Static data -// - -static int numSubAgents; - - -// -// Parse UserParameter=... parameter -// Argument is a parameter name and command line separated by comma -// - -static BOOL AddUserParameter(char *args,int sourceLine) -{ - char *cmdLine; - char *buffer; - BOOL ret = TRUE; - -INIT_CHECK_MEMORY(main); - - cmdLine=strchr(args,','); - if (cmdLine==NULL) - { - if (IsStandalone()) - printf("Error in configuration file, line %d: missing command line in UserParameter\n",sourceLine); - ret = FALSE; - } - else - { - *cmdLine=0; - cmdLine++; - - buffer=(char *)malloc(strlen(cmdLine)+32); - sprintf(buffer,"__exec{%s}",cmdLine); - AddAlias(args,buffer); - free(buffer); - ret = TRUE; - } - -CHECK_MEMORY(main, "AddUserParameter", "end"); - - return ret; -} - - -// -// Parse SubAgent=... parameter -// Argument is a module name and command line separated by comma -// - -static BOOL AddSubAgent(char *args) -{ - char *cmdLine; - -INIT_CHECK_MEMORY(main); - - cmdLine=strchr(args,','); - if (cmdLine!=NULL) - { - *cmdLine=0; - cmdLine++; - } - - subagentNameList=(SUBAGENT_NAME *)realloc(subagentNameList,sizeof(SUBAGENT_NAME)*(numSubAgents+2)); - subagentNameList[numSubAgents].name=strdup(args); - subagentNameList[numSubAgents].cmdLine=cmdLine==NULL ? NULL : strdup(cmdLine); - numSubAgents++; - subagentNameList[numSubAgents].name=NULL; - -CHECK_MEMORY(main, "AddSubAgent", "end"); - - return TRUE; -} - -void FreeSubagentNameList(void) -{ - int i =0; - if (subagentNameList!=NULL) - { - for(i=0; subagentNameList[i].name!=NULL; i++) - { - free(subagentNameList[i].name); - if (subagentNameList[i].cmdLine!=NULL) - free(subagentNameList[i].cmdLine); - } - free(subagentNameList); - } -} - -// -// Parse PerfCounter=... parameter and add new performance counter -// Argument is a config file parameter value which should have the following syntax: -// <key>,"<counter path>",<time interval> -// Returns TRUE on success and FALSE otherwise -// - -static BOOL AddPerformanceCounter(char *args) -{ - char - *ptr1=NULL, - *ptr2=NULL, - *eptr,buffer[MAX_ALIAS_NAME]; - USER_COUNTER *counter; - int i=0; - BOOL ret = FALSE; - -INIT_CHECK_MEMORY(main); - - ptr1=strchr(args,','); - if (ptr1!=NULL) // Invalid syntax - ret = TRUE; - - if(ret == TRUE) - { - *ptr1=0; - ptr1++; - StrStrip(args); - StrStrip(ptr1); - if (*ptr1!='"') - ret = FALSE; // Invalid syntax - } - - if(ret == TRUE) - { - ptr1++; - ptr2=strchr(ptr1,'"'); - if (ptr2==NULL) - ret = FALSE; // Invalid syntax - } - - if(ret == TRUE) - { - *ptr2=0; - ptr2++; - StrStrip(ptr2); - if (*ptr2!=',') - ret = FALSE; // Invalid syntax - } - - if(ret == TRUE) - { - ptr2++; - StrStrip(ptr2); - - i=strtol(ptr2,&eptr,10); - if ((*eptr!=0)|| // Not a decimal number - (i<1)||(i>1800)) // Interval value out of range - ret = FALSE; // Invalid syntax - } - - if(ret == TRUE) - { - // Add internal alias - sprintf(buffer,"__usercnt{%s}",args); - if (!AddAlias(args,buffer)) - ret = FALSE; - } - - if(ret == TRUE) - { - counter=(USER_COUNTER *)malloc(sizeof(USER_COUNTER)); - memset(counter,0,sizeof(USER_COUNTER)); - - strncpy(counter->name,args,MAX_COUNTER_NAME-1); - strncpy(counter->counterPath,ptr1,MAX_PATH-1); - counter->interval=i; - counter->rawValueArray=(PDH_RAW_COUNTER *)malloc(sizeof(PDH_RAW_COUNTER)*counter->interval); - - // Add to the list - counter->next=userCounterList; - userCounterList=counter; - } - -CHECK_MEMORY(main, "AddPerformanceCounter", "end"); - return ret; -} - -void FreeUserCounterList(void) -{ - USER_COUNTER *curr; - USER_COUNTER *next; - - next = userCounterList; - while(next!=NULL) - { - curr = next; - next = curr->next; - free(curr->rawValueArray); - free(curr); - } -} - -// -// Parse Server=... parameter -// - -static int ParseServerList(char *args,int sourceLine) -{ - char *sptr,*eptr; - int errors=0; - -INIT_CHECK_MEMORY(main); - - for(sptr=args;(sptr!=(char *)1)&&(confServerCount<MAX_SERVERS);sptr=eptr+1) - { - eptr=strchr(sptr,','); - if (eptr!=NULL) - *eptr=0; - - if(confServerCount==0) - { - strcpy(confServer,sptr); - } - confServerAddr[confServerCount]=inet_addr(sptr); - if (confServerAddr[confServerCount]==INADDR_NONE) - { - errors++; - if (IsStandalone()) - printf("Error in configuration file, line %d: invalid server's IP address (%s)\n",sourceLine,sptr); - } - else - { - confServerCount++; - } - } - -CHECK_MEMORY(main, "ParseServerList", "end"); - - return errors; -} - - -// -// Read configuration -// - -BOOL ReadConfig(void) -{ - FILE *cfg; - char *ptr,buffer[4096]; - int sourceLine=0,errors=0; - -INIT_CHECK_MEMORY(main); - - if (IsStandalone()) - printf("Using configuration file \"%s\"\n",confFile); - - cfg=fopen(confFile,"r"); - if (cfg==NULL) - { - if (IsStandalone()) - { - printf("Unable to open configuration file: %s\n",strerror(errno)); - if(test_cmd) - return TRUE; - } - -CHECK_MEMORY(main, "ReadConfig", "fopen==NULL"); - return FALSE; - } - - numSubAgents=0; - - while(!feof(cfg)) - { - buffer[0]=0; - fgets(buffer,4095,cfg); - sourceLine++; - ptr=strchr(buffer,'\n'); - if (ptr!=NULL) - *ptr=0; - ptr=strchr(buffer,'#'); - if (ptr!=NULL) - *ptr=0; - - StrStrip(buffer); - if (buffer[0]==0) - continue; - - ptr=strchr(buffer,'='); - if (ptr==NULL) - { - errors++; - if (IsStandalone()) - printf("Syntax error in configuration file, line %d\n",sourceLine); - continue; - } - *ptr=0; - ptr++; - StrStrip(buffer); - StrStrip(ptr); - - if (!stricmp(buffer,"LogFile")) - { - if (!stricmp(ptr,"{EventLog}")) - { - dwFlags|=AF_USE_EVENT_LOG; - } - else - { - dwFlags&=~AF_USE_EVENT_LOG; - memset(logFile,0,MAX_PATH); - strncpy(logFile,ptr,MAX_PATH-1); - } - } - else if (!stricmp(buffer,"Hostname")) - { - memset(confHostname,0,MAX_PATH); - strncpy(confHostname,ptr,MAX_PATH-1); - } - else if (!stricmp(buffer,"Server")) - { - int rc; - - if ((rc=ParseServerList(ptr,sourceLine))>0) - errors+=rc; - } - else if (!stricmp(buffer,"ListenPort")) - { - int n; - - n=atoi(ptr); - if ((n<1)||(n>65535)) - { - confListenPort=10050; - errors++; - if (IsStandalone()) - printf("Error in configuration file, line %d: invalid port number (%s)\n",sourceLine,ptr); - } - else - { - confListenPort=(WORD)n; - } - } - else if (!stricmp(buffer,"ServerPort")) - { - int n; - - n=atoi(ptr); - if ((n<1)||(n>65535)) - { - confServerPort=10051; - errors++; - if (IsStandalone()) - printf("Error in configuration file, line %d: invalid port number (%s)\n",sourceLine,ptr); - } - else - { - confServerPort=(WORD)n; - } - } - else if (!stricmp(buffer,"Alias")) - { - char *sep; - - sep=strchr(ptr,':'); - if (sep==NULL) - { - errors++; - if (IsStandalone()) - printf("Error in configuration file, line %d: invalid alias syntax\n",sourceLine); - } - else - { - *sep=0; - sep++; - StrStrip(ptr); - StrStrip(sep); - AddAlias(ptr,sep); - } - } - else if (!stricmp(buffer,"Timeout")) - { - int tm; - - tm=atoi(ptr); - if ((tm>0)&&(tm<=30)) - { - confTimeout=tm*1000; // Convert to milliseconds - } - else - { - errors++; - if (IsStandalone()) - printf("Error in configuration file, line %d: invalid timeout value (%d seconds)\n", - sourceLine,tm); - } - } - else if (!stricmp(buffer,"LogLevel")) - { - g_dwLogLevel = strtoul(ptr, NULL, 0); - } - else if (!stricmp(buffer,"EnableRemoteCommands")) - { - confEnableRemoteCommands = strtoul(ptr, NULL, 0); - } - else if (!stricmp(buffer,"PerfCounter")) - { - if (!AddPerformanceCounter(ptr)) - { - errors++; - if (IsStandalone()) - printf("Error in configuration file, line %d: invalid performance counter specification\n", - sourceLine); - } - } - else if (!stricmp(buffer,"MaxCollectorProcessingTime")) - { - int tm; - - tm=atoi(ptr); - if ((tm>0)&&(tm<=500)) - { - confMaxProcTime=tm; - } - else - { - errors++; - if (IsStandalone()) - printf("Error in configuration file, line %d: invalid collector sample processing time value (%d milliseconds)\n", - sourceLine,tm); - } - } - else if (!stricmp(buffer,"LogUnresolvedSymbols")) - { - if ((!stricmp(ptr,"1"))||(!stricmp(ptr,"yes"))||(!stricmp(ptr,"true"))) - dwFlags|=AF_LOG_UNRESOLVED_SYMBOLS; - else - dwFlags&=~AF_LOG_UNRESOLVED_SYMBOLS; - } - else if (!stricmp(buffer,"SubAgent")) - { - if (!AddSubAgent(ptr)) - errors++; - } - else if (!stricmp(buffer,"UserParameter")) - { - if (!AddUserParameter(ptr,sourceLine)) - errors++; - } - else if ((!stricmp(buffer,"PidFile"))||(!stricmp(buffer,"NoTimeWait"))|| - (!stricmp(buffer,"StartAgents"))||(!stricmp(buffer,"DebugLevel"))) - { - // Ignore these parameters, they are for compatibility with UNIX agent only - } - else - { - errors++; - if (dwFlags & AF_STANDALONE) - printf("Error in configuration file, line %d: unknown option \"%s\"\n",sourceLine,buffer); - } - } - - if ((IsStandalone())&&(!errors)) - printf("Configuration file OK\n"); - - fclose(cfg); - -CHECK_MEMORY(main, "ReadConfig", "end"); - - return TRUE; -} diff --git a/src/zabbix_agent_win32/doc/ChangeLog b/src/zabbix_agent_win32/doc/ChangeLog deleted file mode 100644 index aa22018d..00000000 --- a/src/zabbix_agent_win32/doc/ChangeLog +++ /dev/null @@ -1,94 +0,0 @@ -1.0.1 - -* Added configuration parameter LogLevel - - -1.0.0-beta15 - -* Fixed bug with memory[xxx] counters on systems with more than 2GB of memory - - -1.0.0-beta11 - -* Fixed bug in GetCounterName() function which causes agent crash on - Windows Server 2003 -* system[uname] now return correct information on Windows Server 2003 - - -1.0.0-beta10 - -* Added support for non-english Windows versions - thanks to Harald Holzer -* Added diskused[*] parameter - - -1.0.0-beta9 - -* Added API for subagents -* Disk free space and total size now returned in bytes -* Added support for external program execution (UserParameter) -* Added support for check_port[] parameter - - -1.0.0-beta8 - -* Added support for multiple servers -* Changes in communication protocol: on errors now returned special - text strings instead of negative integers -* Added proc_info[*] parameter -* Added memory[cached] parameter (supported only on Windows XP) -* Added logging to system Event Log -* PDH-related error messages are now more specific -* Listener thread now will not exit on any accept() error -* Added some parameters for agent statistics monitoring: number of accepted - and rejected connections, processing errors, etc. -* Fixed bug in calculation of md5_hash[] and cksum[] parameters for - zero-length files -* md5_hash[] and cksum[] now returns ZBX_UNSUPPORTED for files larger than - 64MB (due to high performance impact caused by checksum computing for - large files). - - -1.0.0-beta7 - -* Added parameters for monitoring average and maximum processing time for - Zabbix agent's collector thread -* Location of configuration file now can be specified in service mode -* Fixed bug which doesn't allow to use space characters in service - executable path - - -1.0.0-alpha5 - -* Added filesize[*] parameter -* Added system[uptime] parameter -* Added system[uname] parameter -* Service installation ("zabbixw32.exe install" command) now creates service - with automatic startup, not manual - - -1.0.0-alpha4 - -* Added md5_hash[*] parameter for computing MD5 hashes of files -* Added cksum[*] parameter -* Internal representation of all numeric parameters was converted to double -* Added "MaxCollectorProcessingTime" configuration file parameter - - -1.0.0-alpha3 - -* Added parameter aliases -* Added request processing timeout (controlled by "Timeout" parameter - in configuration file) -* Added support for user-specified performance counters - - -1.0.0-alpha2 - -* Added service_state[*] parameter for system services monitoring -* Added perf_counter[*] parameter which allow to retrieve any performance - counter -* Program now exits if no configuration file found -* Added check-config command line option which allow to check configuration - file syntax without actually starting agent -* Some configuration file options, which are standard for UNIX agent, are - now silently ignored (without error messages) diff --git a/src/zabbix_agent_win32/doc/ReadMe.txt b/src/zabbix_agent_win32/doc/ReadMe.txt deleted file mode 100644 index 424bfc90..00000000 --- a/src/zabbix_agent_win32/doc/ReadMe.txt +++ /dev/null @@ -1,295 +0,0 @@ - - ZabbixW32 version 1.0.1 - -****************************************************************************** - - -About ------ - -ZabbixW32 is Zabbix agent for Win32 systems. It will work on Windows NT 4.0, -Windows 2000, Windows XP and Windows Server 2003. ZabbixW32 doesn't supposed -to work on other Windows platforms. - - -Installation ------------- - -Installation is very simple and includes 3 steps: - -1. Unpack ZabbixW32.exe -2. Create configuration file c:\zabbix_agentd.conf (it has the same syntax as - for UNIX agent). -3. Run command "ZabbixW32.exe install" to install Zabbix agent as service. - If you wish to use configuration file other that c:\zabbix_agentd.conf, - you should use the following command for service installation: - "ZabbixW32.exe --config <your_configuration_file> install". Full path to - configuration file should be specified. - -Now you can use Control Panel to start agent's service or run -"ZabbixW32.exe start". - -Windows NT 4.0 Note: -ZabbixW32 uses PDH (Performance Data Helper) API to gather various system -information, so PDH.DLL is needed. This DLL is not supplied with Windows NT 4.0 -by default, so you need to download and install it by yourself. Microsoft -Knowledge Base article number 284996 describes this in detail and contains a -download link. You can find this article at -http://support.microsoft.com/default.aspx?scid=kb;en-us;284996 - - -Command line syntax -------------------- - -Usage: zabbixw32 [options] [command] - -Where possible commands are: - check-config : Check configuration file and exit - standalone : Run in standalone mode - start : Start Zabbix Win32 Agent service - stop : Stop Zabbix Win32 Agent service - install : Install Zabbix Win32 Agent as service - remove : Remove previously installed Zabbix Win32 Agent service - install-events : Install Zabbix Win32 Agent as event source for Event Log - This is done automatically when service is being installed - remove-events : Remove Zabbix Win32 Agent event source - This is done automatically when service is being removed - help : Display help information - version : Display version information - -And possible options are: - --config <file> : Specify alternate configuration file - (default is C:\zabbix_agentd.conf) - - -Configuration file ------------------- - -Zabbix Win32 agent suports the following configuration parameters: - -Server = <ip_address>[,<ip_address>[,<ip_address> ...]] - Sets IP address(es) of Zabbix server(s). Agent will accept connections only - from this address(es). To specify multiple servers, you can either write - their addresses in one line separated by commans, or create multiple - "Server = ..." lines. - -ListenPort = <port_number> - Sets TCP port number for incoming connections. - -LogFile = <path> - Sets the agent's log file. If this parameter is omitted, Event Log will - be used. You can also specify Event Log as a target for logging implicitly - by setting <path> to "{EventLog}" (without quotes). - -LogLevel = <mask> - Sets log level. It's an or'ed value of the following flags: - 0x01 - Log critical messages - 0x02 - Log warning messages - 0x04 - Log informational messages - Default value is 0x07, which means "log all messages". Value can be either - in decimal or hexadecimal form. - -Timeout = <number> - Sets the request processing timeout (in seconds). If server request will - not be processed within specified timeout, appropriate error code will be - returned to server. Default is 3 seconds. - -MaxCollectorProcessingTime = <number> - Sets maximum acceptable processing time of one data sample by collector - thread (in milliseconds). If processing time will exceed specified value, - warning message will be written to log file. Default value is 100 - milliseconds. - -Alias = <alias_name>:<parameter_name> - Sets the alias for parameter. It can be useful to substitute long and - complex parameter name with a smaller and simplies one. For example, if - you wish to retrieve paging file usage in percents from the server, you - can use parameter "perf_counter[\Paging File(_Total)\% Usage]", or you - can define an alias by adding the following line to configuration file: - - Alias = pg_usage:perf_counter[\Paging File(_Total)\% Usage] - - After that you can use parameter name "pg_usage" to retrieve the same - information. You can specify as many "Alias" records as you wish. - Please note tht aliases can not be used for parameters defined in - "PerfCounter" configuration file records. - -PerfCounter = <parameter_name>,"<perf_counter_path>",<period> - Defines new parameter <parameter_name> which is an average value for - system performance counter <perf_counter_path> for the specified time - period <period> (in seconds). For example, if you wish to receive average - number of processor interrupts per second for last minute, you can define - new parameter "interrupts" as following: - - PerfCounter = interrupts,"\Processor(0)\Interrupts/sec",60 - - Please note double quotes around performance counter path. Samples for - calculating average value will be taken every second. - -LogUnresolvedSymbols = (yes | no) - Controls logging of unresolved symbols during agent startup. Values can be - strings "yes" or "no" (without quotes). - -UserParameter = <parameter_name>,<executable_path> - Defines new parameter <parameter_name> which is an output of executable - file specified by <executable_path>. Executable file should be console - executable and send it's output to STDOUT. - -The following parameters can be presented in configuration file for -compatibility with UNIX agents but has no effect: - - StartAgents - DebugLevel - PidFile - NoTimeWait - - -Parameters supported by Zabbix Win32 Agent ------------------------------------------- - -I. Zabbix standard parameters - -check_port[<port>] -check_port[<host>,<port>] -cksum[<path>] <path> can be normal Windows path, like C:\, or UNC. - Agent will return UNSUPPORTED if file is larger than - 64MB. -diskfree[<path>] <path> can be normal Windows path, like C:\, or UNC -disktotal[<path>] <path> can be normal Windows path, like C:\, or UNC -filesize[<path>] <path> can be normal Windows path, like C:\, or UNC -memory[free] -memory[total] -memory[cached] Only on Windows XP and Windows Server 2003 -ping -proc_cnt[<process_name>] -swap[free] -swap[total] -system[hostname] -system[proccount] -system[procload] -system[procload5] -system[procload15] -system[uname] -system[uptime] -version[zabbix_agent] - - -II. Win32-specific parameters - -agent[avg_collector_time] -Average time spent by collector thread on each sample processing for -last minute (in milliseconds) - -agent[max_collector_time] -Maximum time spent by collector thread on sample processing (in milliseconds) - -agent[accepted_requests] -Total number of requests accepted by agent for processing. - -agent[rejected_requests] -Total number of requests rejected by agent because they was coming from -unallowed source. - -agent[timed_out_requests] -Total number of requests timed out in processing. - -agent[accept_errors] -Total number of accept() syscall errors. - -agent[processed_requests] -Total number of requests successfully processed by agent. - -agent[failed_requests] -Total number of requests with errors in processing (requests generated -ZBX_ERROR return code). - -agent[unsupported_requests] -Total number of requests for unsupported parameters (requests generated -ZBX_UNSUPPORTED return code). - -cpu_util -Average CPU(s) utilization (in percents) for last minute - -cpu_util5 -Average CPU(s) utilization (in percents) for last 5 minutes - -cpu_util15 -Average CPU(s) utilization (in percents) for last 15 minutes - -cpu_util[<instance>] -Average specific CPU utilization (in percents) for last minute, where -<instance> is zero-based CPU number - -cpu_util5[<instance>] -Average specific CPU utilization (in percents) for last 5 minutes, where -<instance> is zero-based CPU number - -cpu_util15[<instance>] -Average specific CPU utilization (in percents) for last 15 minutes, where -<instance> is zero-based CPU number - -diskused[<instance>] -Number of used bytes on specific drive. - -md5_hash[<file name>] -MD5 hash of specified file (returned as string). Agent will return UNSUPPORTED -if file is larger than 64MB. - -perf_counter[<path>] -Value of any performance counter, where <path> is the counter path (you can use -Performance Monitor to obtain list of available counters). Please note that -this parameter will return correct value only for counters which requires just -one sample (like "\System\Threads"). It will not work as expected for counters -that requires more than one sample - like CPU utilization. - -proc_info[<process>:<attribute>:<type>] -Different information about specific process(es). - <process> - process name (same as in proc_cnt[] parameter) - <attribute> - requested process attribute. The following attributes are - currenty supported: - vmsize - Size of process virtual memory in Kbytes - wkset - Size of process working set (amount of physical memory - used by process) in Kbytes - pf - Number of page faults - ktime - Process kernel time in milliseconds - utime - Process user time in milliseconds - io_read_b - Number of bytes read by process during I/O operations - io_read_op - Number of read operation performed by process - io_write_b - Number of bytes written by process during I/O operations - io_write_op - Number of write operation performed by process - io_other_b - Number of bytes transferred by process during operations - other than read and write operations - io_other_op - Number of I/O operations performed by process, other - than read and write operations - gdiobj - Number of GDI objects used by process - userobj - Number of USER objects used by process - <type> - representation type (meaningful when more than one process - with the same name exists). Valid values are: - min - minimal value among all processes named <process> - max - maximal value among all processes named <process> - avg - average value for all processes named <process> - sum - sum of values for all processes named <process> -Examples: -1. To get amount of physical memory taken by all Internet Explorer processes, -use the following parameter: - proc_info[iexplore.exe:wkset:sum] -2. To get average number of page faults for Internet Explorer processes, -use the following parameter: - proc_info[iexplore.exe:pf:avg] -Notes: -1. All io_xxx,gdiobj and userobj attributes available only on Windows 2000 - and later versions of Windows, not on Windows NT 4.0. - -service_state[<srv>] -State of service <srv>. The following states can be returned: - 0 - Running - 1 - Paused - 2 - Start pending - 3 - Pause pending - 4 - Continue pending - 5 - Stop pending - 6 - Stopped - 7 - Unknown - 255 - SCM communication error -Please note that <srv> should be real service name (as it seen in service -properties under "Name:"), not service display name! diff --git a/src/zabbix_agent_win32/doc/TODO.txt b/src/zabbix_agent_win32/doc/TODO.txt deleted file mode 100644 index 482f98a2..00000000 --- a/src/zabbix_agent_win32/doc/TODO.txt +++ /dev/null @@ -1,4 +0,0 @@ -* Support for check_service[*] parameter -* Installation program -* Possibility to store configuration in registry -* Configuration tool (may be through MMC) diff --git a/src/zabbix_agent_win32/eventlog.cpp b/src/zabbix_agent_win32/eventlog.cpp deleted file mode 100644 index 7cf066ba..00000000 --- a/src/zabbix_agent_win32/eventlog.cpp +++ /dev/null @@ -1,282 +0,0 @@ -#include "zabbixw32.h" - -#define DllExport __declspec( dllexport ) -#define MAX_INSERT_STRS 64 -#define MAX_MSG_LENGTH 1024 - -DllExport long MyOpenEventLog(char *pAppName,HANDLE -*pEventHandle,long *pNumRecords,long *pLatestRecord); -DllExport long MyCloseEventLog(HANDLE hAppLog); -DllExport long MyClearEventLog(HANDLE hAppLog); -DllExport long MyGetAEventLog(char *pAppName,HANDLE hAppLog,long -which,double *pTime,char *pSource,char *pMessage,DWORD *pType,WORD -*pCategory, DWORD *timestamp); - -int process_eventlog( - char *source, - int *lastlogsize, - char *timestamp, - char *src, - char *severity, - char *message) -{ - - HANDLE hAppLog; - long FirstID; - long LastID; - long i; - double time; - DWORD t,type; - WORD category; - int ret = 1; - -LOG_FUNC_CALL("In process_eventlog()"); -INIT_CHECK_MEMORY(main); - - if (!MyOpenEventLog(source,&hAppLog,&LastID,&FirstID)) - { - LastID += FirstID; - FirstID = ((*lastlogsize) >= FirstID) ? (*lastlogsize)+1 : FirstID; - - for (i = FirstID; i < LastID; i++) - { - if(MyGetAEventLog(source,hAppLog,i,&time,src,message,&type,&category,&t) == 0) - { - sprintf(timestamp,"%ld",t); - - if(type==EVENTLOG_ERROR_TYPE) type=4; - else if(type==EVENTLOG_AUDIT_FAILURE) type=7; - else if(type==EVENTLOG_AUDIT_SUCCESS) type=8; - else if(type==EVENTLOG_INFORMATION_TYPE) type=1; - else if(type==EVENTLOG_WARNING_TYPE) type=2; - sprintf(severity,"%d",type); - *lastlogsize = i; - ret = 0; - break; - } - } - MyCloseEventLog(hAppLog); - } - -CHECK_MEMORY(main, "process_eventlog","end"); -LOG_FUNC_CALL("End of process_eventlog()"); - - return ret; -} - -// open event logger and return number of records -DllExport long MyOpenEventLog( - char *pAppName, - HANDLE *pEventHandle, - long *pNumRecords, - long *pLatestRecord) -{ - HANDLE hAppLog; /* handle to the application log */ - -LOG_FUNC_CALL("In MyOpenEventLog()"); -INIT_CHECK_MEMORY(main); - - *pEventHandle = 0; - *pNumRecords = 0; - hAppLog = OpenEventLog(NULL,pAppName); // open log file - if (!hAppLog) - { - LOG_DEBUG_INFO("s","MyOpenEventLog: 1"); - return(GetLastError()); - } - GetNumberOfEventLogRecords(hAppLog,(unsigned long*)pNumRecords);// get number of records - GetOldestEventLogRecord(hAppLog,(unsigned long*)pLatestRecord); - *pEventHandle = hAppLog; - -CHECK_MEMORY(main, "MyOpenEventLog", "end"); -LOG_FUNC_CALL("End of MyOpenEventLog()"); - return(0); - -} - -// close event logger -DllExport long MyCloseEventLog( - HANDLE hAppLog - ) -{ -LOG_FUNC_CALL("In MyCloseEventLog()"); -INIT_CHECK_MEMORY(main); - - if (hAppLog) CloseEventLog(hAppLog); - -CHECK_MEMORY(main, "MyCloseEventLog", "end"); -LOG_FUNC_CALL("End of MyCloseEventLog()"); - return(0); -} - -// clear event log -DllExport long MyClearEventLog( - HANDLE hAppLog - ) -{ -LOG_FUNC_CALL("In MyClearEventLog()"); -INIT_CHECK_MEMORY(main); - - if (!(ClearEventLog(hAppLog,0))) - { -LOG_DEBUG_INFO("s","MyClearEventLog: error exit"); - return(GetLastError()); - } - -CHECK_MEMORY(main, "MyClearEventLog", "end"); -LOG_FUNC_CALL("End of MyClearEventLog()"); - return(0); - -} - -// get Nth error from event log. 1 is the first. -DllExport long MyGetAEventLog( - char *pAppName, - HANDLE hAppLog, - long which, - double *pTime, - char *pSource, - char *pMessage, - DWORD *pType, - WORD *pCategory, - DWORD *timestamp - ) -{ - EVENTLOGRECORD *pELR = NULL; - BYTE bBuffer[1024]; /* hold the event log record raw data */ - DWORD dwRead, dwNeeded; - char temp[MAX_PATH]; - char MsgDll[MAX_PATH]; /* the name of the message DLL */ - HKEY hk = NULL; - DWORD Data; - DWORD Type; - HINSTANCE hLib = NULL; /* handle to the messagetable DLL */ - char *pCh = NULL, *pFile = NULL, *pNextFile = NULL; - char *aInsertStrs[MAX_INSERT_STRS]; // array of pointers to insert - long i; - LPTSTR msgBuf = NULL; // hold text of the error message that we - long err = 0; - -LOG_FUNC_CALL("In MyGetAEventLog()"); -INIT_CHECK_MEMORY(main); - - if (!hAppLog) return(0); - - pMessage[0] = '\0'; - - if(!ReadEventLog(hAppLog, /* event-log handle */ - EVENTLOG_SEEK_READ | /* read forward */ - EVENTLOG_FORWARDS_READ, /* sequential read */ - which, /* which record to read 1 is first */ - bBuffer, /* address of buffer */ - sizeof(bBuffer), /* size of buffer */ - &dwRead, /* count of bytes read */ - &dwNeeded)) /* bytes in next record */ - { - return GetLastError(); - } - pELR = (EVENTLOGRECORD*)bBuffer; // point to data - - *pTime = (double)pELR->TimeGenerated; // return double timestamp - *pType = pELR->EventType; // return event type - *pCategory = pELR->EventCategory; // return category - *timestamp = pELR->TimeGenerated; // return timestamp - - strcpy(pSource,((char*)pELR + sizeof(EVENTLOGRECORD)));// copy source name - -// Get path to message dll - strcpy(temp,"SYSTEM\\CurrentControlSet\\Services\\EventLog\\"); - strcat(temp,pAppName); - strcat(temp,"\\"); - strcat(temp,((char*)pELR + sizeof(EVENTLOGRECORD))); - - pFile = NULL; - if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, temp, 0, KEY_READ, &hk) == ERROR_SUCCESS) - { - pFile = temp; - Data = MAX_PATH; - err = RegQueryValueEx( - hk, /* handle of key to query */ - "EventMessageFile", /* value name */ - NULL, /* must be NULL */ - &Type, /* address of type value */ - (UCHAR*)pFile, /* address of value data */ - &Data); /* length of value data */ - RegCloseKey(hk); - - if(err != ERROR_SUCCESS) - pFile = NULL; - } - - err = 1; - while(pFile) - { - pNextFile = strchr(pFile,';'); - if(pNextFile) - { - *pNextFile = '\0'; - pNextFile++; - } - - if (ExpandEnvironmentStrings(pFile, MsgDll, MAX_PATH)) - { - hLib = LoadLibraryEx(MsgDll, NULL, LOAD_LIBRARY_AS_DATAFILE); - if(hLib) - { - /* prepare the array of insert strings for FormatMessage - the - insert strings are in the log entry. */ - for ( - i = 0, pCh = (char *)((LPBYTE)pELR + pELR->StringOffset); - i < pELR->NumStrings && i < MAX_INSERT_STRS; - i++, pCh += strlen(pCh) + 1) /* point to next string */ - { - aInsertStrs[i] = pCh; - } - - /* Format the message from the message DLL with the insert strings */ - FormatMessage( - FORMAT_MESSAGE_FROM_HMODULE | - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_ARGUMENT_ARRAY | - FORMAT_MESSAGE_FROM_SYSTEM, - hLib, /* the messagetable DLL handle */ - pELR->EventID, /* message ID */ - MAKELANGID(LANG_NEUTRAL, SUBLANG_ENGLISH_US), /* language ID */ - (LPTSTR) &msgBuf, /* address of pointer to buffer for message */ - MAX_MSG_LENGTH, /* maximum size of the message buffer */ - aInsertStrs); /* array of insert strings for the message */ - - if(msgBuf) - { - strcpy(pMessage,msgBuf); // copy message - err = 0; - - /* Free the buffer that FormatMessage allocated for us. */ - LocalFree((HLOCAL) msgBuf); - } - FreeLibrary(hLib); - } - } - - if(err == 0) break; - - pFile = pNextFile; - } - - if(err) - { - for ( - i = 0, pCh = (char *)((LPBYTE)pELR + pELR->StringOffset); - i < pELR->NumStrings && i < MAX_INSERT_STRS; - i++, pCh += strlen(pCh) + 1) /* point to next string */ - { - if(i > 0) strcat(pMessage,","); - strcat(pMessage,pCh); - } - } - -CHECK_MEMORY(main, "MyGetAEventLog", "end"); -LOG_FUNC_CALL("End of MyGetAEventLog()"); - return 0; - -}
\ No newline at end of file diff --git a/src/zabbix_agent_win32/execute.cpp b/src/zabbix_agent_win32/execute.cpp deleted file mode 100644 index 7c4324e3..00000000 --- a/src/zabbix_agent_win32/execute.cpp +++ /dev/null @@ -1,167 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002,2003 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: execute.cpp -** -**/ - -#include "zabbixw32.h" - -LONG H_Execute(char *cmd,char *arg,char **value) -{ - char *ptr1,*ptr2; - STARTUPINFO si = {0}; - PROCESS_INFORMATION pi = {0}; - SECURITY_ATTRIBUTES sa; - HANDLE hOutput; - char szTempPath[MAX_PATH],szTempFile[MAX_PATH]; - DWORD dwBytes=0; - - // Extract command line - ptr1=strchr(cmd,'{'); - ptr2=strchr(cmd,'}'); - ptr1++; - *ptr2=0; - - // Create temporary file to hold process output - GetTempPath(MAX_PATH-1,szTempPath); - GetTempFileName(szTempPath,"zbx",0,szTempFile); - sa.nLength=sizeof(SECURITY_ATTRIBUTES); - sa.lpSecurityDescriptor=NULL; - sa.bInheritHandle=TRUE; - hOutput=CreateFile(szTempFile,GENERIC_READ | GENERIC_WRITE,0,&sa,CREATE_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL); - if (hOutput==INVALID_HANDLE_VALUE) - { - WriteLog(MSG_CREATE_TMP_FILE_FAILED,EVENTLOG_ERROR_TYPE,"e",GetLastError()); - return SYSINFO_RC_ERROR; - } - - // Fill in process startup info structure - memset(&si,0,sizeof(STARTUPINFO)); - si.cb=sizeof(STARTUPINFO); - si.dwFlags=STARTF_USESTDHANDLES; - si.hStdInput=GetStdHandle(STD_INPUT_HANDLE); - si.hStdOutput=hOutput; - si.hStdError=GetStdHandle(STD_ERROR_HANDLE); - - // Create new process - if (!CreateProcess(NULL,ptr1,NULL,NULL,TRUE,0,NULL,NULL,&si,&pi)) - { - WriteLog(MSG_CREATE_PROCESS_FAILED,EVENTLOG_ERROR_TYPE,"se",ptr1,GetLastError()); - return SYSINFO_RC_NOTSUPPORTED; - } - - // Wait for process termination and close all handles - WaitForSingleObject(pi.hProcess,INFINITE); - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - - // Rewind temporary file for reading - SetFilePointer(hOutput,0,NULL,FILE_BEGIN); - - *value=(char *)malloc(MAX_STRING_LEN); // Called and freed in function "ProcessCommand", pointer "strResult" - - // Read process output - ReadFile(hOutput,*value,MAX_STRING_LEN-1,&dwBytes,NULL); - (*value)[dwBytes]=0; - - ptr1=strchr(*value,'\r'); - if (ptr1!=NULL) - *ptr1=0; - ptr1=strchr(*value,'\n'); - if (ptr1!=NULL) - *ptr1=0; - - // Remove temporary file - CloseHandle(hOutput); - DeleteFile(szTempFile); - - return SYSINFO_RC_SUCCESS; -} - -LONG H_RunCommand(char *cmd,char *arg,char **value) -{ - STARTUPINFO si; - PROCESS_INFORMATION pi; - char *ptr1,*ptr2; - char command[MAX_ZABBIX_CMD_LEN]; - double result = 0; - - if(confEnableRemoteCommands != 1) - { - (*value) = NULL; - return SYSINFO_RC_NOTSUPPORTED; - } - - ZeroMemory(&si, sizeof(si) ); - si.cb = sizeof(si); - ZeroMemory(&pi, sizeof(pi) ); - - // Extract command line - ptr1=strchr(cmd,'['); - ptr2=strchr(cmd,']'); - ptr1++; - *ptr2=0; - - if((ptr2 = strrchr(ptr1,','))) - { - *ptr2=0; - ptr2++; - } - - if(!ptr2 || (ptr2 && strcmp(ptr2,"wait") == 0)) - { - sprintf(command,"__exec{%s}",ptr1); - return H_Execute(command, arg, value); - } - - sprintf(command,"cmd /C \"%s\"",ptr1); - -LOG_DEBUG_INFO("s","H_RunCommand"); -LOG_DEBUG_INFO("s",command); - - GetStartupInfo(&si); - - result = (double)CreateProcess( - NULL, // No module name (use command line) - command,// Name of app to launch - NULL, // Default process security attributes - NULL, // Default thread security attributes - FALSE, // Don't inherit handles from the parent - 0, // Normal priority - NULL, // Use the same environment as the parent - NULL, // Launch in the current directory - &si, // Startup Information - &pi); // Process information stored upon return - - if(!result) - { -LOG_DEBUG_INFO("s","ERROR"); -LOG_DEBUG_INFO("e",GetLastError()); - *value = strdup("1"); - } - else - { -LOG_DEBUG_INFO("s","H_RunCommand"); - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); - *value = strdup("0"); - } - - return SYSINFO_RC_SUCCESS; -} diff --git a/src/zabbix_agent_win32/log.cpp b/src/zabbix_agent_win32/log.cpp deleted file mode 100644 index 5b948c38..00000000 --- a/src/zabbix_agent_win32/log.cpp +++ /dev/null @@ -1,242 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: log.cpp -** -**/ - -#include "zabbixw32.h" -#include <time.h> -#include <stdarg.h> - - -// -// Static data -// - -static HANDLE mutexLogAccess; -static HANDLE hLog=INVALID_HANDLE_VALUE; - -// -// Write record to log file -// -static void WriteLogToFile(char *message) -{ - char buffer[64]; - char logFile_old[MAX_STRING_LEN+5]; - DWORD size; - time_t t; - struct tm *loc; - - if (mutexLogAccess!=INVALID_HANDLE_VALUE) - WaitForSingleObject(mutexLogAccess,INFINITE); - - hLog = CreateFile(logFile,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL,NULL); - if (hLog==INVALID_HANDLE_VALUE) - return; - - SetFilePointer(hLog,0,NULL,FILE_END); - - t=time(NULL); - loc=localtime(&t); - strftime(buffer,32,"[%d-%b-%Y %H:%M:%S] ",loc); - - // Prevent simultaneous write to log file - - WriteFile(hLog,buffer,strlen(buffer),&size,NULL); - if (IsStandalone()) - printf("%s",buffer); - - WriteFile(hLog,message,strlen(message),&size,NULL); - - FlushFileBuffers(hLog); - - size = GetFileSize(hLog, NULL); - - if (hLog!=INVALID_HANDLE_VALUE) - { - CloseHandle(hLog); - hLog = INVALID_HANDLE_VALUE; - } - - if(size > MAX_LOG_FILE_LEN) - { - strscpy(logFile_old, logFile); - strncat(logFile_old, ".old", MAX_STRING_LEN); - if(MoveFileEx(logFile, logFile_old, MOVEFILE_REPLACE_EXISTING)!=0) - { -/* exit(1);*/ - } - } - - if (mutexLogAccess!=INVALID_HANDLE_VALUE) - ReleaseMutex(mutexLogAccess); - - if (IsStandalone()) - printf("%s",message); - -} - -// -// Initialize log -// - -void InitLog(void) -{ - if (dwFlags & AF_USE_EVENT_LOG) - { - hLog=RegisterEventSource(NULL,ZABBIX_EVENT_SOURCE); - } - else - { - char buffer[256]; - - mutexLogAccess=CreateMutex(NULL,FALSE,NULL); - - sprintf(buffer,"*************** Log file opened ****************\r\n"); - WriteLogToFile(buffer); - } -} - - -// -// Close log -// - -void CloseLog(void) -{ - if (dwFlags & AF_USE_EVENT_LOG) - { - DeregisterEventSource(hLog); - } - else - { - if (mutexLogAccess!=INVALID_HANDLE_VALUE) - CloseHandle(mutexLogAccess); - } -} - -// -// Write log record -// Parameters: -// msg - Message ID -// wType - Message type (see ReportEvent() for details) -// format - Parameter format string, each parameter represented by one character. -// The following format characters can be used: -// s - String -// d - Decimal integer -// x - Hex integer -// e - System error code (will appear in log as textual description) -// - -void WriteLog(DWORD msg,WORD wType,char *format...) -{ - va_list args; - char *strings[16],*msgBuf; - char *ptmp; - int numStrings=0; - DWORD error; - - if (!((DWORD)wType & g_dwLogLevel)) - return; - - memset(strings,0,sizeof(char *)*16); - - if (format!=NULL) - { - va_start(args,format); - - for(numStrings=0; (format[numStrings]!=0)&&(numStrings<16); numStrings++) - { - switch(format[numStrings]) - { - case 's': - ptmp = va_arg(args,char *); - if(ptmp) - strings[numStrings] = strdup(ptmp); - else - strings[numStrings] = 0; - break; - case 'd': - strings[numStrings]=(char *)malloc(16); - sprintf(strings[numStrings],"%d",va_arg(args,LONG)); - break; - case 'x': - strings[numStrings]=(char *)malloc(16); - sprintf(strings[numStrings],"0x%08X",va_arg(args,DWORD)); - break; - case 'e': - error=va_arg(args,DWORD); - if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL,error, - MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Default language - (LPSTR)&msgBuf,0,NULL)>0) - { - msgBuf[strcspn(msgBuf,"\r\n")]=0; - strings[numStrings]=(char *)malloc(strlen(msgBuf)+1); - strcpy(strings[numStrings],msgBuf); - LocalFree(msgBuf); - } - else - { - strings[numStrings]=(char *)malloc(64); - sprintf(strings[numStrings],"1. MSG 0x%08X - Unable to find message text",error); - } - break; - default: - strings[numStrings]=(char *)malloc(32); - sprintf(strings[numStrings],"BAD FORMAT [%c] (0x%08X)", format[numStrings], va_arg(args,DWORD)); - break; - } - } - va_end(args); - } - - if (dwFlags & AF_USE_EVENT_LOG) - { - - ReportEvent(hLog,wType,0,msg,NULL,(unsigned short)(numStrings),0,(const char **)strings,NULL); - } - else - { - LPVOID lpMsgBuf; - - if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_ARGUMENT_ARRAY, - NULL,msg,0,(LPTSTR)&lpMsgBuf,0,strings)>0) - { - WriteLogToFile((char *)lpMsgBuf); - LocalFree(lpMsgBuf); - } - else - { - - char message[64]; - - sprintf(message,"2. MSG 0x%08X - Unable to find message text [0x%X]\r\n",msg , GetLastError()); - - WriteLogToFile(message); - } - } - - while(--numStrings>=0) - if(strings[numStrings]) - free(strings[numStrings]); -} diff --git a/src/zabbix_agent_win32/logfiles.cpp b/src/zabbix_agent_win32/logfiles.cpp deleted file mode 100644 index f9698a2d..00000000 --- a/src/zabbix_agent_win32/logfiles.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* -** ZABBIX -** Copyright (C) 2000-2005 SIA Zabbix -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -**/ - -/* -#include <errno.h> -#include <stdio.h> -#include <string.h> -*/ -#include <io.h> - -/* -#include <unistd.h> - -#include "common.h" - -#include "log.h" -#include "logfiles.h" - */ - -#include "zabbixw32.h" - -int process_log(char *filename,int *lastlogsize, char *value) -{ - FILE *f; - -LOG_FUNC_CALL("In process_log()"); -INIT_CHECK_MEMORY(main); - - f=fopen(filename,"r"); - if(NULL == f) - { -// zabbix_log( LOG_LEVEL_WARNING, "Cannot open [%s] [%s]", filename, strerror(errno)); - sprintf(value,"%s","ZBX_NOTSUPPORTED\n"); -CHECK_MEMORY(main, "process_log", "fopen"); - return 1; - } - - if(_filelength(_fileno(f)) < *lastlogsize) - { - *lastlogsize=0; - } - - if(-1 == fseek(f,*lastlogsize,SEEK_SET)) - { -// zabbix_log( LOG_LEVEL_WARNING, "Cannot set postition to [%d] for [%s] [%s]", *lastlogsize, filename, strerror(errno)); - sprintf(value,"%s","ZBX_NOTSUPPORTED\n"); - fclose(f); -CHECK_MEMORY(main, "process_log", "fseek"); - return 1; - } - - if(NULL == fgets(value, MAX_STRING_LEN-1, f)) - { - /* EOF */ - fclose(f); -CHECK_MEMORY(main, "process_log", "fgets"); - return 1; - } - fclose(f); - - *lastlogsize+=strlen(value); - -CHECK_MEMORY(main, "process_log", "end"); -LOG_FUNC_CALL("End of process_log()"); - return 0; -} diff --git a/src/zabbix_agent_win32/main.cpp b/src/zabbix_agent_win32/main.cpp deleted file mode 100644 index 6783cae0..00000000 --- a/src/zabbix_agent_win32/main.cpp +++ /dev/null @@ -1,351 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: main.cpp -** -**/ - -#include "zabbixw32.h" -#include <conio.h> - - -// -// Global variables -// - -HANDLE eventShutdown; -HANDLE eventCollectorStarted; - -DWORD dwFlags=AF_USE_EVENT_LOG; -char confFile[MAX_PATH]="C:\\zabbix_agentd.conf"; -char logFile[MAX_PATH]="{EventLog}"; -char confHostname[MAX_PATH]="0.0.0.0"; -char confServer[MAX_PATH]="0.0.0.0"; - -WORD confListenPort=10050; // Alexei: New defailt port 10000 -> 10050 -WORD confServerPort=10051; -DWORD confServerAddr[MAX_SERVERS]; -DWORD confServerCount=0; -DWORD confTimeout=3000; // 3 seconds default timeout -DWORD confMaxProcTime=1000; // 1000 milliseconds is default acceptable collector sample processing time -DWORD confEnableRemoteCommands=0; // by default disabled -DWORD g_dwLogLevel = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; - -SUBAGENT *subagentList; // List of loaded subagents -SUBAGENT_NAME *subagentNameList=NULL; -PERFCOUNTER *perfCounterList=NULL; - -DWORD (__stdcall *imp_GetGuiResources)(HANDLE,DWORD); -BOOL (__stdcall *imp_GetProcessIoCounters)(HANDLE,PIO_COUNTERS); -BOOL (__stdcall *imp_GetPerformanceInfo)(PPERFORMANCE_INFORMATION,DWORD); -BOOL (__stdcall *imp_GlobalMemoryStatusEx)(LPMEMORYSTATUSEX); - - -// -// Get proc address and write log file -// - -static FARPROC GetProcAddressAndLog(HMODULE hModule,LPCSTR procName) -{ - FARPROC ptr; - - ptr=GetProcAddress(hModule,procName); - if ((ptr==NULL)&&(dwFlags & AF_LOG_UNRESOLVED_SYMBOLS)) - WriteLog(MSG_NO_FUNCTION,EVENTLOG_WARNING_TYPE,"s",procName); - return ptr; -} - - -// -// Import symbols -// - -static void ImportSymbols(void) -{ - HMODULE hModule; - -INIT_CHECK_MEMORY(main); - - hModule=GetModuleHandle("USER32.DLL"); - if (hModule!=NULL) - { - imp_GetGuiResources=(DWORD (__stdcall *)(HANDLE,DWORD))GetProcAddressAndLog(hModule,"GetGuiResources"); - } - else - { - WriteLog(MSG_NO_DLL,EVENTLOG_WARNING_TYPE,"s","USER32.DLL"); - } - - hModule=GetModuleHandle("KERNEL32.DLL"); - if (hModule!=NULL) - { - imp_GetProcessIoCounters=(BOOL (__stdcall *)(HANDLE,PIO_COUNTERS))GetProcAddressAndLog(hModule,"GetProcessIoCounters"); - imp_GlobalMemoryStatusEx=(BOOL (__stdcall *)(LPMEMORYSTATUSEX))GetProcAddressAndLog(hModule,"GlobalMemoryStatusEx"); - } - else - { - WriteLog(MSG_NO_DLL,EVENTLOG_WARNING_TYPE,"s","KERNEL32.DLL"); - } - - hModule=GetModuleHandle("PSAPI.DLL"); - if (hModule!=NULL) - { - imp_GetPerformanceInfo=(BOOL (__stdcall *)(PPERFORMANCE_INFORMATION,DWORD))GetProcAddressAndLog(hModule,"GetPerformanceInfo"); - } - else - { - WriteLog(MSG_NO_DLL,EVENTLOG_WARNING_TYPE,"s","PSAPI.DLL"); - } -CHECK_MEMORY(main, "ImportSymbols", "end"); -} - - -// -// Load subagent -// - -static BOOL LoadSubAgent(char *name,char *cmdLine) -{ - SUBAGENT *sbi; - BOOL ret = TRUE; - - int rc; - - sbi=(SUBAGENT *)malloc(sizeof(SUBAGENT)); - - sbi->hModule=LoadLibrary(name); - if (sbi->hModule==NULL) - { - WriteLog(MSG_LOAD_FAILED,EVENTLOG_ERROR_TYPE,"se",name,GetLastError()); - ret = FALSE; - goto lbl_FreeSbi; - } - - sbi->init =(int (__zabbix_api *)(char *,SUBAGENT_COMMAND **))GetProcAddress(sbi->hModule,"zabbix_subagent_init"); - sbi->shutdown=(void (__zabbix_api *)(void))GetProcAddress(sbi->hModule,"zabbix_subagent_shutdown"); - if ((sbi->init==NULL) || (sbi->shutdown==NULL)) - { - WriteLog(MSG_NO_ENTRY_POINTS,EVENTLOG_ERROR_TYPE,"s",name); - ret = FALSE; - goto lbl_CloseLibrary; - } - - if ((rc=sbi->init(cmdLine, &sbi->cmdList))!=0) - { - WriteLog(MSG_SUBAGENT_INIT_FAILED, EVENTLOG_ERROR_TYPE, "sd", name, rc); - ret = FALSE; - goto lbl_CloseLibrary; - } - - // Add new subagent to chain - sbi->next = subagentList; - subagentList = sbi; - - FreeLibrary(sbi->hModule); - - WriteLog(MSG_SUBAGENT_LOADED,EVENTLOG_INFORMATION_TYPE,"s",name); - -lbl_CloseLibrary: - FreeLibrary(sbi->hModule); - -lbl_FreeSbi: - if(ret == FALSE) - free(sbi); - - return ret; -} - -static void FreeSubagentList(void) -{ - SUBAGENT *curr; - SUBAGENT *next; - - next = subagentList; - while(next!=NULL) - { - curr = next; - next = curr->next; - free(curr); - } -} - -// -// Initialization routine -// - -BOOL Initialize(void) -{ - WSAData sockInfo; - int i; - char counterPath[MAX_COUNTER_PATH * 2 + 50]; - - // Initialize Windows Sockets API - WSAStartup(0x0002,&sockInfo); - - // Dynamically import functions that may not be presented in all Windows versions - ImportSymbols(); - - // Load subagents - if (subagentNameList!=NULL) - { - for(i=0; subagentNameList[i].name!=NULL; i++) - LoadSubAgent(subagentNameList[i].name,subagentNameList[i].cmdLine); - - FreeSubagentNameList(); - } - - // Create synchronization stuff - eventShutdown=CreateEvent(NULL,TRUE,FALSE,NULL); - eventCollectorStarted=CreateEvent(NULL,TRUE,FALSE,NULL); - - // Internal command aliases - sprintf(counterPath,"perf_counter[\\%s\\%s]",GetCounterName(PCI_SYSTEM),GetCounterName(PCI_SYSTEM_UP_TIME)); - if(AddAlias("system.uptime",counterPath)) - { -LOG_DEBUG_INFO("s","AddAlias == OK"); - } - else - { -LOG_DEBUG_INFO("s","AddAlias == FAIL"); - } - - // Start TCP/IP listener and collector threads - - _beginthread(CollectorThread,0,NULL); - WaitForSingleObject(eventCollectorStarted,INFINITE); // Allow collector thread to initialize - - _beginthread(ListenerThread,0,NULL); - - _beginthread(ActiveChecksThread,0,NULL); - - CloseHandle(eventCollectorStarted); - - return TRUE; -} - - -// -// Shutdown routine -// - -void Shutdown(void) -{ - SetEvent(eventShutdown); - Sleep(2000); // Allow other threads to terminate - WriteLog(MSG_AGENT_SHUTDOWN,EVENTLOG_INFORMATION_TYPE,NULL); -} - - -// -// Common Main() -// - -void Main(void) -{ - WriteLog(MSG_AGENT_STARTED,EVENTLOG_INFORMATION_TYPE,NULL); - - if (IsStandalone()) - { - int ch; - - printf("\n*** Zabbix Win32 agent operational. Press ESC to terminate. ***\n"); - for(;;) - { - ch=getch(); - if (ch==0) - ch=-getch(); - - if (ch==27) - break; - } - - Shutdown(); - } - else - { - WaitForSingleObject(eventShutdown,INFINITE); - } -} - - -// -// Entry point -// - -int main(int argc,char *argv[]) -{ - int ret = 0; - -INIT_CHECK_MEMORY(main); - - if (!ParseCommandLine(argc,argv)) - { - ret = 1; - goto lbl_End; - } - - if (!ReadConfig()) - { - ret = 1; - goto lbl_End; - } - - InitLog(); - - if (!IsStandalone()) - { - InitService(); - } - else - { - if (!Initialize()) - { - printf("Zabbix Win32 agent initialization failed\n"); - ret = 1; - goto lbl_End; - } - if(test_cmd) - { - TestCommand(); - } - else - { - Main(); - } - } - -lbl_End: - CloseHandle(eventShutdown); - - FreeSubagentList(); - FreeSubagentNameList(); - FreeCounterList(); - FreeUserCounterList(); - FreeAliasList(); - -CHECK_MEMORY(main, "main","end") -#if defined(ENABLE_CHECK_MEMOTY) - else LOG_DEBUG_INFO("s", "main: Memory OK!"); -#else - ; -#endif //_DEBUG - - CloseLog(); - - return ret; -} diff --git a/src/zabbix_agent_win32/md5.cpp b/src/zabbix_agent_win32/md5.cpp deleted file mode 100644 index 2c9c2fcd..00000000 --- a/src/zabbix_agent_win32/md5.cpp +++ /dev/null @@ -1,381 +0,0 @@ -/* - Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ -/* $Id$ */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - - The original and principal author of md5.c is L. Peter Deutsch - <ghost@aladdin.com>. Other authors are noted in the change history - that follows (in reverse chronological order): - - 2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order - either statically or dynamically; added missing #include <string.h> - in library. - 2002-03-11 lpd Corrected argument list for main(), and added int return - type, in test program and T value program. - 2002-02-21 lpd Added missing #include <stdio.h> in test program. - 2000-07-03 lpd Patched to eliminate warnings about "constant is - unsigned in ANSI C, signed in traditional"; made test program - self-checking. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). - 1999-05-03 lpd Original version. - */ - -#include "md5.h" -#include <string.h> - -#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ -#ifdef ARCH_IS_BIG_ENDIAN -# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1) -#else -# define BYTE_ORDER 0 -#endif - -#define T_MASK ((md5_word_t)~0) -#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) -#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) -#define T3 0x242070db -#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) -#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) -#define T6 0x4787c62a -#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) -#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) -#define T9 0x698098d8 -#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) -#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) -#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) -#define T13 0x6b901122 -#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) -#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) -#define T16 0x49b40821 -#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) -#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) -#define T19 0x265e5a51 -#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) -#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) -#define T22 0x02441453 -#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) -#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) -#define T25 0x21e1cde6 -#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) -#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) -#define T28 0x455a14ed -#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) -#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) -#define T31 0x676f02d9 -#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) -#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) -#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) -#define T35 0x6d9d6122 -#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) -#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) -#define T38 0x4bdecfa9 -#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) -#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) -#define T41 0x289b7ec6 -#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) -#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) -#define T44 0x04881d05 -#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) -#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) -#define T47 0x1fa27cf8 -#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) -#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) -#define T50 0x432aff97 -#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) -#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) -#define T53 0x655b59c3 -#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) -#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) -#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) -#define T57 0x6fa87e4f -#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) -#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) -#define T60 0x4e0811a1 -#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) -#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) -#define T63 0x2ad7d2bb -#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) - - -static void -md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) -{ - md5_word_t - a = pms->abcd[0], b = pms->abcd[1], - c = pms->abcd[2], d = pms->abcd[3]; - md5_word_t t; -#if BYTE_ORDER > 0 - /* Define storage only for big-endian CPUs. */ - md5_word_t X[16]; -#else - /* Define storage for little-endian or both types of CPUs. */ - md5_word_t xbuf[16]; - const md5_word_t *X; -#endif - - { -#if BYTE_ORDER == 0 - /* - * Determine dynamically whether this is a big-endian or - * little-endian machine, since we can use a more efficient - * algorithm on the latter. - */ - static const int w = 1; - - if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ -#endif -#if BYTE_ORDER <= 0 /* little-endian */ - { - /* - * On little-endian machines, we can process properly aligned - * data without copying it. - */ - if (!((data - (const md5_byte_t *)0) & 3)) { - /* data are properly aligned */ - X = (const md5_word_t *)data; - } else { - /* not aligned */ - memcpy(xbuf, data, 64); - X = xbuf; - } - } -#endif -#if BYTE_ORDER == 0 - else /* dynamic big-endian */ -#endif -#if BYTE_ORDER >= 0 /* big-endian */ - { - /* - * On big-endian machines, we must arrange the bytes in the - * right order. - */ - const md5_byte_t *xp = data; - int i; - -# if BYTE_ORDER == 0 - X = xbuf; /* (dynamic only) */ -# else -# define xbuf X /* (static only) */ -# endif - for (i = 0; i < 16; ++i, xp += 4) - xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); - } -#endif - } - -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) - - /* Round 1. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ -#define F(x, y, z) (((x) & (y)) | (~(x) & (z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + F(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 7, T1); - SET(d, a, b, c, 1, 12, T2); - SET(c, d, a, b, 2, 17, T3); - SET(b, c, d, a, 3, 22, T4); - SET(a, b, c, d, 4, 7, T5); - SET(d, a, b, c, 5, 12, T6); - SET(c, d, a, b, 6, 17, T7); - SET(b, c, d, a, 7, 22, T8); - SET(a, b, c, d, 8, 7, T9); - SET(d, a, b, c, 9, 12, T10); - SET(c, d, a, b, 10, 17, T11); - SET(b, c, d, a, 11, 22, T12); - SET(a, b, c, d, 12, 7, T13); - SET(d, a, b, c, 13, 12, T14); - SET(c, d, a, b, 14, 17, T15); - SET(b, c, d, a, 15, 22, T16); -#undef SET - - /* Round 2. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ -#define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + G(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 1, 5, T17); - SET(d, a, b, c, 6, 9, T18); - SET(c, d, a, b, 11, 14, T19); - SET(b, c, d, a, 0, 20, T20); - SET(a, b, c, d, 5, 5, T21); - SET(d, a, b, c, 10, 9, T22); - SET(c, d, a, b, 15, 14, T23); - SET(b, c, d, a, 4, 20, T24); - SET(a, b, c, d, 9, 5, T25); - SET(d, a, b, c, 14, 9, T26); - SET(c, d, a, b, 3, 14, T27); - SET(b, c, d, a, 8, 20, T28); - SET(a, b, c, d, 13, 5, T29); - SET(d, a, b, c, 2, 9, T30); - SET(c, d, a, b, 7, 14, T31); - SET(b, c, d, a, 12, 20, T32); -#undef SET - - /* Round 3. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ -#define H(x, y, z) ((x) ^ (y) ^ (z)) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + H(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 5, 4, T33); - SET(d, a, b, c, 8, 11, T34); - SET(c, d, a, b, 11, 16, T35); - SET(b, c, d, a, 14, 23, T36); - SET(a, b, c, d, 1, 4, T37); - SET(d, a, b, c, 4, 11, T38); - SET(c, d, a, b, 7, 16, T39); - SET(b, c, d, a, 10, 23, T40); - SET(a, b, c, d, 13, 4, T41); - SET(d, a, b, c, 0, 11, T42); - SET(c, d, a, b, 3, 16, T43); - SET(b, c, d, a, 6, 23, T44); - SET(a, b, c, d, 9, 4, T45); - SET(d, a, b, c, 12, 11, T46); - SET(c, d, a, b, 15, 16, T47); - SET(b, c, d, a, 2, 23, T48); -#undef SET - - /* Round 4. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ -#define I(x, y, z) ((y) ^ ((x) | ~(z))) -#define SET(a, b, c, d, k, s, Ti)\ - t = a + I(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 6, T49); - SET(d, a, b, c, 7, 10, T50); - SET(c, d, a, b, 14, 15, T51); - SET(b, c, d, a, 5, 21, T52); - SET(a, b, c, d, 12, 6, T53); - SET(d, a, b, c, 3, 10, T54); - SET(c, d, a, b, 10, 15, T55); - SET(b, c, d, a, 1, 21, T56); - SET(a, b, c, d, 8, 6, T57); - SET(d, a, b, c, 15, 10, T58); - SET(c, d, a, b, 6, 15, T59); - SET(b, c, d, a, 13, 21, T60); - SET(a, b, c, d, 4, 6, T61); - SET(d, a, b, c, 11, 10, T62); - SET(c, d, a, b, 2, 15, T63); - SET(b, c, d, a, 9, 21, T64); -#undef SET - - /* Then perform the following additions. (That is increment each - of the four registers by the value it had before this block - was started.) */ - pms->abcd[0] += a; - pms->abcd[1] += b; - pms->abcd[2] += c; - pms->abcd[3] += d; -} - -void -md5_init(md5_state_t *pms) -{ - pms->count[0] = pms->count[1] = 0; - pms->abcd[0] = 0x67452301; - pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; - pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; - pms->abcd[3] = 0x10325476; -} - -void -md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) -{ - const md5_byte_t *p = data; - int left = nbytes; - int offset = (pms->count[0] >> 3) & 63; - md5_word_t nbits = (md5_word_t)(nbytes << 3); - - if (nbytes <= 0) - return; - - /* Update the message length. */ - pms->count[1] += nbytes >> 29; - pms->count[0] += nbits; - if (pms->count[0] < nbits) - pms->count[1]++; - - /* Process an initial partial block. */ - if (offset) { - int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); - - memcpy(pms->buf + offset, p, copy); - if (offset + copy < 64) - return; - p += copy; - left -= copy; - md5_process(pms, pms->buf); - } - - /* Process full blocks. */ - for (; left >= 64; p += 64, left -= 64) - md5_process(pms, p); - - /* Process a final partial block. */ - if (left) - memcpy(pms->buf, p, left); -} - -void -md5_finish(md5_state_t *pms, md5_byte_t digest[16]) -{ - static const md5_byte_t pad[64] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - md5_byte_t data[8]; - int i; - - /* Save the length before padding. */ - for (i = 0; i < 8; ++i) - data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); - /* Pad to 56 bytes mod 64. */ - md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); - /* Append the length. */ - md5_append(pms, data, 8); - for (i = 0; i < 16; ++i) - digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); -} diff --git a/src/zabbix_agent_win32/md5.h b/src/zabbix_agent_win32/md5.h deleted file mode 100644 index 37855ebb..00000000 --- a/src/zabbix_agent_win32/md5.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ -/* $Id$ */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - - The original and principal author of md5.h is L. Peter Deutsch - <ghost@aladdin.com>. Other authors are noted in the change history - that follows (in reverse chronological order): - - 2002-04-13 lpd Removed support for non-ANSI compilers; removed - references to Ghostscript; clarified derivation from RFC 1321; - now handles byte order either statically or dynamically. - 1999-11-04 lpd Edited comments slightly for automatic TOC extraction. - 1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); - added conditionalization for C++ compilation from Martin - Purschke <purschke@bnl.gov>. - 1999-05-03 lpd Original version. - */ - -#ifndef md5_INCLUDED -# define md5_INCLUDED - -/* - * This package supports both compile-time and run-time determination of CPU - * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be - * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is - * defined as non-zero, the code will be compiled to run only on big-endian - * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to - * run on either big- or little-endian CPUs, but will run slightly less - * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined. - */ - -#define MD5_DIGEST_SIZE 16 - -typedef unsigned char md5_byte_t; /* 8-bit byte */ -typedef unsigned int md5_word_t; /* 32-bit word */ - -/* Define the state of the MD5 Algorithm. */ -typedef struct md5_state_s { - md5_word_t count[2]; /* message length in bits, lsw first */ - md5_word_t abcd[4]; /* digest buffer */ - md5_byte_t buf[64]; /* accumulate block */ -} md5_state_t; - -#ifdef __cplusplus -extern "C" -{ -#endif - -/* Initialize the algorithm. */ -void md5_init(md5_state_t *pms); - -/* Append a string to the message. */ -void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes); - -/* Finish the message and return the digest. */ -void md5_finish(md5_state_t *pms, md5_byte_t digest[16]); - -#ifdef __cplusplus -} /* end extern "C" */ -#endif - -#endif /* md5_INCLUDED */ diff --git a/src/zabbix_agent_win32/messages.mc b/src/zabbix_agent_win32/messages.mc deleted file mode 100644 index c61f59f8..00000000 --- a/src/zabbix_agent_win32/messages.mc +++ /dev/null @@ -1,239 +0,0 @@ -;/**************************************************************************** -; Messages for Zabbix Win32 Agent -;****************************************************************************/ -; -;#ifndef _messages_h_ -;#define _messages_h_ -; - -MessageIdTypedef=DWORD - -MessageId=1 -SymbolicName=MSG_AGENT_STARTED -Language=English -Zabbix Win32 Agent started -. - -MessageId= -SymbolicName=MSG_AGENT_SHUTDOWN -Language=English -Zabbix Win32 Agent stopped -. - -MessageId= -SymbolicName=MSG_PDH_OPEN_QUERY_FAILED -Language=English -Call to PdhOpenQuery() failed: %1 -. - -MessageId= -SymbolicName=MSG_PDH_ADD_COUNTER_FAILED -Language=English -Unable to add performance counter "%1" to query: %2 -. - -MessageId= -SymbolicName=MSG_PDH_COLLECT_QUERY_DATA_FAILED -Language=English -Call to PdhCollectQueryData() failed: %1 -. - -MessageId= -SymbolicName=MSG_USERDEF_COUNTER_FAILED -Language=English -Unable to add user-defined counter "%1" (expanded to "%2") to query: %3 -. - -MessageId= -SymbolicName=MSG_COLLECTOR_INIT_OK -Language=English -Collector thread initialized successfully -. - -MessageId= -SymbolicName=MSG_BIG_PROCESSING_TIME -Language=English -Processing took more then %1 milliseconds (%2 milliseconds) -. - -MessageId= -SymbolicName=MSG_COMMAND_TIMEOUT -Language=English -Timeout occured waiting for server command -. - -MessageId= -SymbolicName=MSG_RECV_ERROR -Language=English -Error receiving data from socket: %1 -. - -MessageId= -SymbolicName=MSG_REQUEST_TIMEOUT -Language=English -Timed out while processing request. Requested parameter is "%1" -. - -MessageId= -SymbolicName=MSG_SOCKET_ERROR -Language=English -Unable to open socket: %1 -. - -MessageId= -SymbolicName=MSG_BIND_ERROR -Language=English -Unable to bind socket: %1 -. - -MessageId= -SymbolicName=MSG_LISTEN_ERROR -Language=English -Error listening on socket: %1 -. - -MessageId= -SymbolicName=MSG_SELECT_ERROR -Language=English -Unable to select socket: %1 -. - -MessageId= -SymbolicName=MSG_ACCEPT_ERROR -Language=English -Unable to accept incoming connection: %1 -. - -MessageId= -SymbolicName=MSG_NO_FUNCTION -Language=English -Unable to resolve symbol "%1" -. - -MessageId= -SymbolicName=MSG_NO_DLL -Language=English -Unable to get handle to "%1" -. - -MessageId= -SymbolicName=MSG_UNEXPECTED_ATTRIBUTE -Language=English -Internal error: unexpected process attribute code %1 in GetProcessAttribute() -. - -MessageId= -SymbolicName=MSG_UNEXPECTED_TYPE -Language=English -Internal error: unexpected type code %1 in GetProcessAttribute() -. - -MessageId= -SymbolicName=MSG_SERVICE_STOPPED -Language=English -Service stoppped -. - -MessageId= -SymbolicName=MSG_FILE_MAP_FAILED -Language=English -Unable to create mapping for file "%1": %2 -. - -MessageId= -SymbolicName=MSG_MAP_VIEW_FAILED -Language=English -MapViewOfFile("%1") failed: %2 -. - -MessageId= -SymbolicName=MSG_UNEXPECTED_IRC -Language=English -Internal error: unexpected iRC=%1 in ProcessCommand("%2") -. - -MessageId= -SymbolicName=MSG_TOO_MANY_ERRORS -Language=English -Too many consecutive errors on accept() call -. - -MessageId= -SymbolicName=MSG_LOAD_FAILED -Language=English -Failed to load subagent module "%1": %2 -. - -MessageId= -SymbolicName=MSG_NO_ENTRY_POINTS -Language=English -Unable to find all required exportable functions in subagent module "%1" -. - -MessageId= -SymbolicName=MSG_SUBAGENT_INIT_FAILED -Language=English -Subagent "%1" initialization failed (initialization function return code %2) -. - -MessageId= -SymbolicName=MSG_SUBAGENT_LOADED -Language=English -Subagent "%1" loaded successfully -. - -MessageId= -SymbolicName=MSG_CREATE_PROCESS_FAILED -Language=English -Unable to create process "%1": %2 -. - -MessageId= -SymbolicName=MSG_CREATE_TMP_FILE_FAILED -Language=English -Unable to create temporary file: %1 -. - -MessageId= -SymbolicName=MSG_OPEN_TMP_FILE_FAILED -Language=English -Unable to open existing temporary file: %1 -. - -MessageId= -SymbolicName=MSG_DNS_LOOKUP_FAILED -Language=English -DNS lookup failed for host %1 -. - -MessageId= -SymbolicName=MSG_ACTIVE_CHECKS -Language=English -Active checks [%1] -. - -MessageId= -SymbolicName=MSG_GET_COMPUTER_NAME_FAILED -Language=English -GetComputerName failed: %1 -. - -MessageId= -SymbolicName=MSG_LOOKUP_FAILED -Language=English -PdhLookupPerfNameByIndex failed: %1 -. - -MessageId= -SymbolicName=MSG_DEBUG_INFO -Language=English -%1 Debug Info: %2 -. - -MessageId= -SymbolicName=MSG_INFORMATION -Language=English -Information: %1 %2 -. - -;#endif diff --git a/src/zabbix_agent_win32/network.cpp b/src/zabbix_agent_win32/network.cpp deleted file mode 100644 index 4ac75272..00000000 --- a/src/zabbix_agent_win32/network.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002,2003 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: network.cpp -** -**/ - -#include "zabbixw32.h" - - -// -// Check if TCP port accepts connections -// Parameter has two forms: -// check_port[nnn] - check port nnn on localhost (127.0.0.1) -// check_port[xxxx,nnn] - check port nnn on host xxxx -// - -LONG H_CheckTcpPort(char *cmd,char *arg,double *value) -{ - SOCKET sock; - struct sockaddr_in sa; - struct hostent *hs; - char - param[MAX_STRING_LEN], - host[MAX_STRING_LEN], - str_port[15]; - int port; - - // Parse arguments - GetParameterInstance(cmd,param,256); - - if(num_param(param) != 2) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 1, host, MAX_STRING_LEN) != 0) - { - return SYSINFO_RC_NOTSUPPORTED; - } - if(host[0] == '\0') - { - /* default parameter */ - sprintf(host, "127.0.0.1"); - } - - if(get_param(param, 2, str_port, 15) != 0) - { - str_port[0] = '\0'; - } - if(str_port[0] == '\0') - { - return SYSINFO_RC_NOTSUPPORTED; - } - - port=atoi(str_port); - if ((port<1)||(port>655535)) - return SYSINFO_RC_NOTSUPPORTED; - - // Fill in server address structure - memset(&sa,0,sizeof(sa)); - sa.sin_family=AF_INET; - sa.sin_port=htons((unsigned short)port); - - // Get host address - hs=gethostbyname(host); - if (hs==NULL) - { - sa.sin_addr.s_addr=inet_addr(host); - if (sa.sin_addr.s_addr==INADDR_NONE) - { - WriteLog(MSG_DNS_LOOKUP_FAILED,EVENTLOG_ERROR_TYPE,"s",host); - return SYSINFO_RC_NOTSUPPORTED; - } - } - else - { - memcpy(&sa.sin_addr,hs->h_addr,hs->h_length); - } - - // Create socket - sock=socket(AF_INET,SOCK_STREAM,0); - if (sock==-1) - { -printf("error1 %e\n",WSAGetLastError()); - WriteLog(MSG_SOCKET_ERROR,EVENTLOG_ERROR_TYPE,"e",WSAGetLastError()); - return SYSINFO_RC_ERROR; - } - - // Establish connection - if (connect(sock,(struct sockaddr *)&sa,sizeof(sa))!=0) - { - DWORD dwError=WSAGetLastError(); - - closesocket(sock); - - if ((dwError==WSAECONNREFUSED)||(dwError==WSAENETUNREACH)||(dwError==WSAETIMEDOUT)) - { - *value=0; // Port unreacheable - return SYSINFO_RC_SUCCESS; - } -printf("error2\n"); - return SYSINFO_RC_ERROR; - } - - closesocket(sock); - *value=1; // Connection successful - - return SYSINFO_RC_SUCCESS; -} diff --git a/src/zabbix_agent_win32/procinfo.cpp b/src/zabbix_agent_win32/procinfo.cpp deleted file mode 100644 index ac4d296c..00000000 --- a/src/zabbix_agent_win32/procinfo.cpp +++ /dev/null @@ -1,288 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: sysinfo.cpp -** -**/ - -#include "zabbixw32.h" - - -// -// Convert process time from FILETIME structure (100-nanosecond units) to double (milliseconds) -// - -static double ConvertProcessTime(FILETIME *lpft) -{ - __int64 i; - - memcpy(&i,lpft,sizeof(__int64)); - i/=10000; // Convert 100-nanosecond units to milliseconds - return (double)i; -} - - -// -// Check if attribute supported or not -// - -static BOOL IsAttributeSupported(int attr) -{ - switch(attr) - { - case 5: // gdiobj - case 6: // userobj - if (imp_GetGuiResources==NULL) - return FALSE; // No appropriate function available, probably we are running on NT4 - break; - case 7: // io_read_b - case 8: // io_read_op - case 9: // io_write_b - case 10: // io_write_op - case 11: // io_other_b - case 12: // io_other_op - if (imp_GetProcessIoCounters==NULL) - return FALSE; // No appropriate function available, probably we are running on NT4 - break; - default: - break; - } - - return TRUE; -} - - -// -// Get specific process attribute -// - -static double GetProcessAttribute(HANDLE hProcess,int attr,int type,int count,double lastValue) -{ - double value; - PROCESS_MEMORY_COUNTERS mc; - IO_COUNTERS ioCounters; - FILETIME ftCreate,ftExit,ftKernel,ftUser; - - // Get value for current process instance - switch(attr) - { - case 0: // vmsize - GetProcessMemoryInfo(hProcess,&mc,sizeof(PROCESS_MEMORY_COUNTERS)); - value=(double)mc.PagefileUsage/1024; // Convert to Kbytes - break; - case 1: // wkset - GetProcessMemoryInfo(hProcess,&mc,sizeof(PROCESS_MEMORY_COUNTERS)); - value=(double)mc.WorkingSetSize/1024; // Convert to Kbytes - break; - case 2: // pf - GetProcessMemoryInfo(hProcess,&mc,sizeof(PROCESS_MEMORY_COUNTERS)); - value=(double)mc.PageFaultCount; - break; - case 3: // ktime - case 4: // utime - GetProcessTimes(hProcess,&ftCreate,&ftExit,&ftKernel,&ftUser); - value=ConvertProcessTime(attr==3 ? &ftKernel : &ftUser); - break; - case 5: // gdiobj - case 6: // userobj - value=(double)imp_GetGuiResources(hProcess,attr==5 ? 0 : 1); - break; - case 7: // io_read_b - imp_GetProcessIoCounters(hProcess,&ioCounters); - value=(double)((__int64)ioCounters.ReadTransferCount); - break; - case 8: // io_read_op - imp_GetProcessIoCounters(hProcess,&ioCounters); - value=(double)((__int64)ioCounters.ReadOperationCount); - break; - case 9: // io_write_b - imp_GetProcessIoCounters(hProcess,&ioCounters); - value=(double)((__int64)ioCounters.WriteTransferCount); - break; - case 10: // io_write_op - imp_GetProcessIoCounters(hProcess,&ioCounters); - value=(double)((__int64)ioCounters.WriteOperationCount); - break; - case 11: // io_other_b - imp_GetProcessIoCounters(hProcess,&ioCounters); - value=(double)((__int64)ioCounters.OtherTransferCount); - break; - case 12: // io_other_op - imp_GetProcessIoCounters(hProcess,&ioCounters); - value=(double)((__int64)ioCounters.OtherOperationCount); - break; - default: // Unknown attribute - WriteLog(MSG_UNEXPECTED_ATTRIBUTE,EVENTLOG_ERROR_TYPE,"x",attr); - value=0; - } - - // Recalculate final value according to selected type - if (count==1) // First instance - { - return value; - } - - switch(type) - { - case 0: // min - return min(lastValue,value); - case 1: // max - return max(lastValue,value); - case 2: // avg - return (lastValue*(count-1)+value)/count; - case 3: // sum - return lastValue+value; - default: - WriteLog(MSG_UNEXPECTED_TYPE,EVENTLOG_ERROR_TYPE,"x",type); - return 0; - } -} - - -// -// Get process-specific information -// Parameter has the following syntax: -// proc_info[<process>:<attribute>:<type>] -// where -// <process> - process name (same as in proc_cnt[] parameter) -// <attribute> - requested process attribute (see documentation for list of valid attributes) -// <type> - representation type (meaningful when more than one process with the same -// name exists). Valid values are: -// min - minimal value among all processes named <process> -// max - maximal value among all processes named <process> -// avg - average value for all processes named <process> -// sum - sum of values for all processes named <process> -// - -LONG H_ProcInfo(char *cmd,char *arg,double *value) -{ - char buffer[256]; - char *ptr1,*ptr2; - int attr,type,i,procCount,counter; - DWORD *procList,dwSize; - HMODULE *modList; - static char *attrList[]= - { - "vmsize", - "wkset", - "pf", - "ktime", - "utime", - "gdiobj", - "userobj", - "io_read_b", - "io_read_op", - "io_write_b", - "io_write_op", - "io_other_b", - "io_other_op", - NULL - }; - static char *typeList[]={ "min","max","avg","sum" }; - -INIT_CHECK_MEMORY(main); - - // Get parameter arguments - GetParameterInstance(cmd,buffer,255); - if (!MatchString("*:*:*",buffer)) - { - -CHECK_MEMORY(main,"H_ProcInfo","end"); - - return SYSINFO_RC_NOTSUPPORTED; // Invalid parameter syntax - } - - // Parse arguments - ptr1=strchr(buffer,':'); - *ptr1=0; - ptr1++; - ptr2=strchr(ptr1,':'); - *ptr2=0; - ptr2++; // Now ptr1 points to attribute and ptr2 points to type - - // Get attribute code from string - for(attr=0;attrList[attr]!=NULL;attr++) - if (!strcmp(attrList[attr],ptr1)) - break; - if (attrList[attr]==NULL) - { -CHECK_MEMORY(main,"H_ProcInfo","typeList"); - - return SYSINFO_RC_NOTSUPPORTED; // Unsupported attribute - } - - if (!IsAttributeSupported(attr)) - { - -CHECK_MEMORY(main,"H_ProcInfo","IsAttributeSupported"); - - return SYSINFO_RC_NOTSUPPORTED; // Unsupported attribute - } - - // Get type code from string - for(type=0;typeList[type]!=NULL;type++) - if (!strcmp(typeList[type],ptr2)) - break; - if (typeList[type]==NULL) - { - -CHECK_MEMORY(main,"H_ProcInfo","typeList"); - - - return SYSINFO_RC_NOTSUPPORTED; // Unsupported type - } - - // Gather information - *value=0; // Initialize to zero - procList=(DWORD *)malloc(MAX_PROCESSES*sizeof(DWORD)); - modList=(HMODULE *)malloc(MAX_MODULES*sizeof(HMODULE)); - EnumProcesses(procList,sizeof(DWORD)*MAX_PROCESSES,&dwSize); - procCount=dwSize/sizeof(DWORD); - for(i=0,counter=0;i<procCount;i++) - { - HANDLE hProcess; - - hProcess=OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,FALSE,procList[i]); - if (hProcess!=NULL) - { - if (EnumProcessModules(hProcess,modList,sizeof(HMODULE)*MAX_MODULES,&dwSize)) - { - if (dwSize>=sizeof(HMODULE)) // At least one module exist - { - char baseName[MAX_PATH]; - - GetModuleBaseName(hProcess,modList[0],baseName,sizeof(baseName)); - if (!stricmp(baseName,buffer)) - { - counter++; // Number of processes with specific name - *value=GetProcessAttribute(hProcess,attr,type,counter,*value); - } - } - } - CloseHandle(hProcess); - } - } - - // Cleanup - free(procList); - free(modList); - -CHECK_MEMORY(main,"H_ProcInfo","end"); - - return SYSINFO_RC_SUCCESS; -} diff --git a/src/zabbix_agent_win32/resource.h b/src/zabbix_agent_win32/resource.h deleted file mode 100644 index c02c661a..00000000 --- a/src/zabbix_agent_win32/resource.h +++ /dev/null @@ -1,15 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by ZabbixW32.rc -// - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 104 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/src/zabbix_agent_win32/service.cpp b/src/zabbix_agent_win32/service.cpp deleted file mode 100644 index 0e19b10a..00000000 --- a/src/zabbix_agent_win32/service.cpp +++ /dev/null @@ -1,376 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: service.cpp -** -**/ - -#include "zabbixw32.h" - -// -// Static data -// - -static SERVICE_STATUS_HANDLE serviceHandle; - - -// -// Service control handler -// - -static VOID WINAPI ServiceCtrlHandler(DWORD ctrlCode) -{ - SERVICE_STATUS status; - -INIT_CHECK_MEMORY(main); - - status.dwServiceType=SERVICE_WIN32_OWN_PROCESS; - status.dwCurrentState=SERVICE_RUNNING; - status.dwControlsAccepted=SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; - status.dwWin32ExitCode=0; - status.dwServiceSpecificExitCode=0; - status.dwCheckPoint=0; - status.dwWaitHint=0; - - switch(ctrlCode) - { - case SERVICE_CONTROL_STOP: - case SERVICE_CONTROL_SHUTDOWN: - status.dwCurrentState=SERVICE_STOP_PENDING; - status.dwWaitHint=4000; - SetServiceStatus(serviceHandle,&status); - -// WriteLog(MSG_SERVICE_STOPPPED,EVENTLOG_INFORMATION_TYPE,NULL); - Shutdown(); - - status.dwCurrentState=SERVICE_STOPPED; - status.dwWaitHint=0; - break; - default: - break; - } - - SetServiceStatus(serviceHandle,&status); -CHECK_MEMORY(main,"ServiceCtrlHandler","end"); -} - - -// -// Service main -// - -static VOID WINAPI ZabbixServiceMain(DWORD argc,LPTSTR *argv) -{ - SERVICE_STATUS status; - -INIT_CHECK_MEMORY(main); - - serviceHandle=RegisterServiceCtrlHandler(ZABBIX_SERVICE_NAME,ServiceCtrlHandler); - - // Now we start service initialization - status.dwServiceType=SERVICE_WIN32_OWN_PROCESS; - status.dwCurrentState=SERVICE_START_PENDING; - status.dwControlsAccepted=SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; - status.dwWin32ExitCode=0; - status.dwServiceSpecificExitCode=0; - status.dwCheckPoint=0; - status.dwWaitHint=2000; - SetServiceStatus(serviceHandle,&status); - - // Actual initialization - if (!Initialize()) - { - // Now service is stopped - status.dwCurrentState=SERVICE_STOPPED; - status.dwWaitHint=0; - SetServiceStatus(serviceHandle,&status); - } else { - // Now service is running - status.dwCurrentState=SERVICE_RUNNING; - status.dwWaitHint=0; - SetServiceStatus(serviceHandle,&status); - - Main(); - } -CHECK_MEMORY(main,"ZabbixServiceMain","end"); -} - - -// -// Initialize service -// - -void InitService(void) -{ - static SERVICE_TABLE_ENTRY serviceTable[2]={ { ZABBIX_SERVICE_NAME,ZabbixServiceMain },{ NULL,NULL } }; - -INIT_CHECK_MEMORY(main); - - if (!StartServiceCtrlDispatcher(serviceTable)) - printf("StartServiceCtrlDispatcher() failed: %s\n",GetSystemErrorText(GetLastError())); - -CHECK_MEMORY(main,"InitService","end"); -} - - -// -// Create service -// - -int ZabbixCreateService(char *execName) -{ - SC_HANDLE mgr,service; - char cmdLine[MAX_PATH*2]; - int ret = 0; - -INIT_CHECK_MEMORY(main); - - mgr=OpenSCManager(NULL,NULL,GENERIC_WRITE); - if (mgr==NULL) - { - printf("ERROR: Cannot connect to Service Manager (%s)\n",GetSystemErrorText(GetLastError())); - return 1; - } - - sprintf(cmdLine,"\"%s\" --config \"%s\"",execName,confFile); - service=CreateService(mgr,ZABBIX_SERVICE_NAME,"Zabbix Win32 Agent",GENERIC_READ,SERVICE_WIN32_OWN_PROCESS, - SERVICE_AUTO_START,SERVICE_ERROR_NORMAL,cmdLine,NULL,NULL,NULL,NULL,NULL); - if (service==NULL) - { - DWORD code=GetLastError(); - - if (code==ERROR_SERVICE_EXISTS) - printf("ERROR: Service named '" ZABBIX_SERVICE_NAME "' already exist\n"); - else - printf("ERROR: Cannot create service (%s)\n",GetSystemErrorText(code)); - ret = 1; - } - else - { - printf("Zabbix Win32 Agent service created successfully\n"); - CloseServiceHandle(service); - } - - CloseServiceHandle(mgr); - - if(ret == 0) - ret = ZabbixInstallEventSource(execName); - -CHECK_MEMORY(main,"ZabbixCreateService","end"); - return ret; -} - - -// -// Remove service -// - -int ZabbixRemoveService(void) -{ - SC_HANDLE mgr,service; - int ret = 0; - -INIT_CHECK_MEMORY(main); - - mgr=OpenSCManager(NULL,NULL,GENERIC_WRITE); - if (mgr==NULL) - { - printf("ERROR: Cannot connect to Service Manager (%s)\n",GetSystemErrorText(GetLastError())); -CHECK_MEMORY(main,"ZabbixCreateService","OpenSCManager"); - return 1; - } - - service=OpenService(mgr,ZABBIX_SERVICE_NAME,DELETE); - if (service==NULL) - { - printf("ERROR: Cannot open service named '" ZABBIX_SERVICE_NAME "' (%s)\n", - GetSystemErrorText(GetLastError())); - ret = 1; - } - else - { - if (DeleteService(service)) - printf("Zabbix Win32 Agent service deleted successfully\n"); - else - { - printf("ERROR: Cannot remove service named '" ZABBIX_SERVICE_NAME "' (%s)\n", - GetSystemErrorText(GetLastError())); - ret = 1; - } - - CloseServiceHandle(service); - } - - CloseServiceHandle(mgr); - - if(ret == 0) - ret = ZabbixRemoveEventSource(); - -CHECK_MEMORY(main,"ZabbixCreateService","end"); - return ret; -} - - -// -// Start service -// - -int ZabbixStartService(void) -{ - SC_HANDLE mgr,service; - int ret = 0; - -INIT_CHECK_MEMORY(main); - - mgr=OpenSCManager(NULL,NULL,GENERIC_WRITE); - if (mgr==NULL) - { - printf("ERROR: Cannot connect to Service Manager (%s)\n",GetSystemErrorText(GetLastError())); -CHECK_MEMORY(main,"ZabbixStartService","OpenSCManager"); - return 1; - } - - service=OpenService(mgr,ZABBIX_SERVICE_NAME,SERVICE_START); - if (service==NULL) - { - printf("ERROR: Cannot open service named '" ZABBIX_SERVICE_NAME "' (%s)\n", - GetSystemErrorText(GetLastError())); - ret=1; - } - else - { - if (StartService(service,0,NULL)) - printf("Zabbix Win32 Agent service started successfully\n"); - else - { - printf("ERROR: Cannot start service named '" ZABBIX_SERVICE_NAME "' (%s)\n", - GetSystemErrorText(GetLastError())); - ret = 1; - } - - CloseServiceHandle(service); - } - - CloseServiceHandle(mgr); -CHECK_MEMORY(main,"ZabbixStartService","end"); - return ret; -} - - -// -// Stop service -// - -int ZabbixStopService(void) -{ - SC_HANDLE mgr,service; - int ret = 0; - -INIT_CHECK_MEMORY(main); - - mgr=OpenSCManager(NULL,NULL,GENERIC_WRITE); - if (mgr==NULL) - { - printf("ERROR: Cannot connect to Service Manager (%s)\n",GetSystemErrorText(GetLastError())); -CHECK_MEMORY(main,"ZabbixStopService","OpenSCManager"); - return 1; - } - - service=OpenService(mgr,ZABBIX_SERVICE_NAME,SERVICE_STOP); - if (service==NULL) - { - printf("ERROR: Cannot open service named '" ZABBIX_SERVICE_NAME "' (%s)\n", - GetSystemErrorText(GetLastError())); - ret = 1; - } - else - { - SERVICE_STATUS status; - - if (ControlService(service,SERVICE_CONTROL_STOP,&status)) - printf("Zabbix Win32 Agent service stopped successfully\n"); - else - { - printf("ERROR: Cannot stop service named '" ZABBIX_SERVICE_NAME "' (%s)\n", - GetSystemErrorText(GetLastError())); - ret = 1; - } - - CloseServiceHandle(service); - } - - CloseServiceHandle(mgr); -CHECK_MEMORY(main,"ZabbixStopService","end"); - return ret; -} - - -// -// Install event source -// - -int ZabbixInstallEventSource(char *path) -{ - HKEY hKey; - DWORD dwTypes=EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; - -INIT_CHECK_MEMORY(main); - - if (ERROR_SUCCESS!=RegCreateKeyEx(HKEY_LOCAL_MACHINE, - "System\\CurrentControlSet\\Services\\EventLog\\System\\" ZABBIX_EVENT_SOURCE, - 0,NULL,REG_OPTION_NON_VOLATILE,KEY_SET_VALUE,NULL,&hKey,NULL)) - { - printf("Unable to create registry key: %s\n",GetSystemErrorText(GetLastError())); -CHECK_MEMORY(main,"ZabbixInstallEventSource","RegCreateKeyEx"); - return 1; - } - - RegSetValueEx(hKey,"TypesSupported",0,REG_DWORD,(BYTE *)&dwTypes,sizeof(DWORD)); - RegSetValueEx(hKey,"EventMessageFile",0,REG_EXPAND_SZ,(BYTE *)path,strlen(path)+1); - - RegCloseKey(hKey); - printf("Event source \"" ZABBIX_EVENT_SOURCE "\" installed successfully\n"); - -CHECK_MEMORY(main,"ZabbixInstallEventSource","end"); - return 0; -} - - -// -// Remove event source -// - -int ZabbixRemoveEventSource(void) -{ - -INIT_CHECK_MEMORY(main); - - if (ERROR_SUCCESS==RegDeleteKey(HKEY_LOCAL_MACHINE, - "System\\CurrentControlSet\\Services\\EventLog\\System\\" ZABBIX_EVENT_SOURCE)) - { - printf("Event source \"" ZABBIX_EVENT_SOURCE "\" uninstalled successfully\n"); - } - else - { - printf("Unable to uninstall event source \"" ZABBIX_EVENT_SOURCE "\": %s\n", - GetSystemErrorText(GetLastError())); - return 1; - } -CHECK_MEMORY(main,"ZabbixRemoveEventSource","end"); - return 0; -} diff --git a/src/zabbix_agent_win32/sysinfo.cpp b/src/zabbix_agent_win32/sysinfo.cpp deleted file mode 100644 index 129413dd..00000000 --- a/src/zabbix_agent_win32/sysinfo.cpp +++ /dev/null @@ -1,1235 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002,2003 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: sysinfo.cpp -** -**/ - -#include "zabbixw32.h" - - -// -// Externals -// - -LONG H_ProcInfo(char *cmd,char *arg,double *value); -LONG H_RunCommand(char *cmd,char *arg,char **value); -LONG H_Execute(char *cmd,char *arg,char **value); -LONG H_CheckTcpPort(char *cmd,char *arg,double *value); - - -// -// Static data -// - -static DWORD procList[MAX_PROCESSES]; - -static double statProcessedRequests=0; -static double statFailedRequests=0; -static double statUnsupportedRequests=0; - - -// -// Get instance for parameters like name[instance] -// - -void GetParameterInstance(char *param,char *instance,int maxSize) -{ - char *ptr1,*ptr2; - -INIT_CHECK_MEMORY(main); - - instance[0]=0; // Default is empty string - ptr1=strchr(param,'['); - ptr2=strchr(ptr1,']'); - if ((ptr1==NULL)||(ptr2==NULL)) - return; - - ptr1++; - memcpy(instance,ptr1,min(ptr2-ptr1,maxSize-1)); - instance[min(ptr2-ptr1,maxSize-1)]=0; -CHECK_MEMORY(main,"GetParameterInstance","end"); -} - - -// -// Handler for parameters which always returns numeric constant (like ping) -// - -static LONG H_NumericConstant(char *cmd,char *arg,double *value) -{ - *value=(double)((long)arg); - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for parameters which always returns string constant (like version[zabbix_agent]) -// - -static LONG H_StringConstant(char *cmd,char *arg,char **value) -{ - *value=strdup(arg ? arg : "(null)\n"); - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for parameters which returns numeric value from specific variable -// - -static LONG H_NumericPtr(char *cmd,char *arg,double *value) -{ - *value=*((double *)arg); - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for system.cpu.util[] -// - -static LONG H_CpuUtil(char *cmd,char *arg,double *value) -{ - char cpuname[20]; - char type[MAX_STRING_LEN]; - char mode[MAX_STRING_LEN]; - - char param[MAX_STRING_LEN]; - - int procnum; - - GetParameterInstance(cmd,param,20-1); - - if(num_param(param) > 3) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 1, cpuname, MAX_STRING_LEN) != 0) - { - cpuname[0] = '\0'; - } - if(cpuname[0] == '\0') - { - /* default parameter */ - sprintf(cpuname, "all"); - } - - if(get_param(param, 2, type, MAX_STRING_LEN) != 0) - { - type[0] = '\0'; - } - if(type[0] == '\0') - { - /* default parameter */ - sprintf(type, "system"); - } - if(strncmp(type, "system", MAX_STRING_LEN)) - { /* only 'system' parameter supported */ - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 3, mode, MAX_STRING_LEN) != 0) - { - mode[0] = '\0'; - } - - if(mode[0] == '\0') - { - /* default parameter */ - sprintf(mode, "avg1"); - } - - if(strcmp(cpuname,"all") == 0) - { - procnum = 0; - } - else - { - procnum = atoi(cpuname)+1; - if ((procnum < 1)||(procnum > MAX_CPU)) - return SYSINFO_RC_NOTSUPPORTED; - } - - if(strcmp(type,"system")) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(strcmp(mode,"avg1") == 0) - *value=statProcUtilization[procnum]; - else if(strcmp(mode,"avg5") == 0) - *value=statProcUtilization5[procnum]; - else if(strcmp(mode,"avg15") == 0) - *value=statProcUtilization15[procnum]; - else - return SYSINFO_RC_NOTSUPPORTED; - - return SYSINFO_RC_SUCCESS; -} - -static LONG H_CpuLoad(char *cmd,char *arg,double *value) -{ - char - param[28], - cpuname[10], - mode[10]; - - int procnum; - - GetParameterInstance(cmd,param,28-1); - - if(num_param(param) > 2) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 1, cpuname, 10) != 0) - { - cpuname[0] = '\0'; - } - if(cpuname[0] == '\0') - { - /* default parameter */ - sprintf(cpuname, "all"); - } - - - if(get_param(param, 2, mode, 10) != 0) - { - mode[0] = '\0'; - } - - if(mode[0] == '\0') - { - /* default parameter */ - sprintf(mode, "avg1"); - } - - if(strcmp(cpuname,"all") == 0) - { - procnum = 0; - } - else - { - procnum=atoi(cpuname)+1; - if ((procnum<1)||(procnum>MAX_CPU)) - return SYSINFO_RC_NOTSUPPORTED; - } - - if(strcmp(mode,"avg1") == 0) - *value=statProcLoad; - else if(strcmp(mode,"avg5") == 0) - *value=statProcLoad5; - else if(strcmp(mode,"avg15") == 0) - *value=statProcLoad15; - else - return SYSINFO_RC_NOTSUPPORTED; - - return SYSINFO_RC_SUCCESS; -} - -static int GetProcessUsername(HANDLE hProcess, char *userName, int userNameLen) { - HANDLE tok = 0; - TOKEN_USER *ptu; - - DWORD - nlen, - dlen; - - char - name[300], - dom[300], - tubuf[300]; - - int iUse; - - assert(userName); - - //clean result; - *userName = '\0'; - - //open the processes token - if (!OpenProcessToken(hProcess,TOKEN_QUERY,&tok)) goto lbl_err;; - - //get the SID of the token - ptu = (TOKEN_USER*)tubuf; - if (!GetTokenInformation(tok,(TOKEN_INFORMATION_CLASS)1,ptu,300,&nlen)) goto lbl_err; - - //get the account/domain name of the SID - dlen = 300; nlen = 300; - if (!LookupAccountSid(0, ptu->User.Sid, name, &nlen, dom, &dlen, (PSID_NAME_USE)&iUse)) goto lbl_err; - - nlen = min(userNameLen-1,(int)nlen); - - strncpy(userName, name, nlen); - userName[nlen] = 0; - - return 1; - -lbl_err: - if (tok) CloseHandle(tok); - return 0; -} - -// -// Handler for proc.num[*] -// -static LONG H_ProcNum(char *cmd,char *arg,double *value) -{ - HANDLE hProcess; - HMODULE hMod; - - DWORD dwSize=0; - - int - i = 0, - counter = 0, - procCount = 0, - proc_ok = 0, - user_ok = 0; - - char - param[MAX_STRING_LEN], - procName[MAX_PATH], - userName[300], - baseName[MAX_PATH], - uname[300]; - - GetParameterInstance(cmd,param,MAX_PATH-1); - - if(num_param(param) > 2) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 1, procName, MAX_PATH) != 0) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 2, userName, 300) != 0) - { - userName[0] = '\0'; - } - - - EnumProcesses(procList,sizeof(DWORD)*MAX_PROCESSES,&dwSize); - - for(i=0,counter=0,procCount=dwSize/sizeof(DWORD); i < procCount; i++) - { - proc_ok = 0; - user_ok = 0; - - hProcess=OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,FALSE,procList[i]); - if (hProcess!=NULL) - { - if (procName[0] != 0) - { - if (EnumProcessModules(hProcess,&hMod,sizeof(hMod),&dwSize)) - { - GetModuleBaseName(hProcess,hMod,baseName,sizeof(baseName)); - if (stricmp(baseName,procName) == 0) - { - proc_ok = 1; - } - } - } else { - proc_ok = 1; - } - - if(userName[0] != '\0') - { - if(GetProcessUsername(hProcess, uname, 300)) - { - if (stricmp(uname,userName) == 0) - user_ok = 1; - } - } else { - user_ok = 1; - } - - if(user_ok && proc_ok) counter++; - - CloseHandle(hProcess); - } - } - - *value=(double)counter; - - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for vm.memory.size[*] parameters -// - -static LONG H_MemorySize(char *cmd,char *arg,double *value) -{ - char - mode[10], - param[15]; - - GetParameterInstance(cmd,param,15-1); - - if(num_param(param) > 1) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 1, mode, 10) != 0) - { - mode[0] = '\0'; - } - if(mode[0] == '\0') - { - /* default parameter */ - sprintf(mode, "total"); - } - - - if (strcmp(mode,"cached") == 0) - { - PERFORMANCE_INFORMATION pfi; - - if (imp_GetPerformanceInfo==NULL) - return SYSINFO_RC_NOTSUPPORTED; - - imp_GetPerformanceInfo(&pfi,sizeof(PERFORMANCE_INFORMATION)); - *value=(double)pfi.SystemCache*(double)pfi.PageSize; - } - else - { - if (imp_GlobalMemoryStatusEx!=NULL) - { - MEMORYSTATUSEX ms; - - ms.dwLength = sizeof(MEMORYSTATUSEX); - imp_GlobalMemoryStatusEx(&ms); - if (strcmp(mode, "total") == 0) - *value = (double)((__int64)ms.ullTotalPhys); - else if (strcmp(mode, "free") == 0) - *value = (double)((__int64)ms.ullAvailPhys); - else - return SYSINFO_RC_NOTSUPPORTED; - } - else - { - MEMORYSTATUS ms; - - GlobalMemoryStatus(&ms); - - if (strcmp(mode,"total") == 0) - *value=(double)ms.dwTotalPhys; - else if (strcmp(mode,"free") == 0) - *value=(double)ms.dwAvailPhys; - else - return SYSINFO_RC_NOTSUPPORTED; - } - } - - return SYSINFO_RC_SUCCESS; -} - -static LONG H_SwapSize(char *cmd,char *arg,double *value) -{ - char param[25]; - char swapdev[10]; - char mode[10]; - - GetParameterInstance(cmd,param,25-1); - - if(num_param(param) > 2) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 1, swapdev, 10) != 0) - { - swapdev[0] = '\0'; - } - if(swapdev[0] == '\0') - { - /* default parameter */ - sprintf(swapdev, "all"); - } - if(strncmp(swapdev, "all", MAX_STRING_LEN)) - { /* only 'all' parameter supported */ - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 2, mode, 10) != 0) - { - mode[0] = '\0'; - } - if(mode[0] == '\0') - { - /* default parameter */ - sprintf(mode, "total"); - } - - if (imp_GlobalMemoryStatusEx!=NULL) - { - MEMORYSTATUSEX ms; - - ms.dwLength = sizeof(MEMORYSTATUSEX); - imp_GlobalMemoryStatusEx(&ms); - - if (strcmp(mode, "total") == 0) - *value = (double)((__int64)ms.ullTotalPageFile); - else if (strcmp(mode, "free") == 0) - *value = (double)((__int64)ms.ullAvailPageFile); - else - return SYSINFO_RC_NOTSUPPORTED; - } - else - { - MEMORYSTATUS ms; - - GlobalMemoryStatus(&ms); - - if (strcmp(mode,"total") == 0) - *value=(double)ms.dwTotalPageFile; - else if (strcmp(mode,"free") == 0) - *value=(double)ms.dwAvailPageFile; - else - return SYSINFO_RC_NOTSUPPORTED; - } - - return SYSINFO_RC_SUCCESS; -} - -// -// Handler for system[hostname] parameter -// - -static LONG H_HostName(char *cmd,char *arg,char **value) -{ - DWORD dwSize; - char buffer[MAX_COMPUTERNAME_LENGTH+1]; - - - dwSize=MAX_COMPUTERNAME_LENGTH+1; - GetComputerName(buffer,&dwSize); - *value=strdup(buffer); - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for vfs.fs.size[*] parameters -// - -static LONG H_DiskInfo(char *cmd,char *arg,double *value) -{ - - char - param[MAX_STRING_LEN], - path[MAX_PATH], - mode[20]; - - ULARGE_INTEGER freeBytes,totalBytes; - - GetParameterInstance(cmd,param,MAX_STRING_LEN-1); - - if(num_param(param) > 2) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 1, path, MAX_PATH) != 0) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - if(get_param(param, 2, mode, 20) != 0) - { - mode[0] = '\0'; - } - if(mode[0] == '\0') - { - /* default parameter */ - sprintf(mode, "total"); - } - - if (!GetDiskFreeSpaceEx(path,&freeBytes,&totalBytes,NULL)) - return SYSINFO_RC_NOTSUPPORTED; - - if (strcmp(mode,"free") == 0) - *value = (double)((__int64)freeBytes.QuadPart); - else if (strcmp(mode,"used") == 0) - *value = (double)((__int64)totalBytes.QuadPart-(__int64)freeBytes.QuadPart); - else if (strcmp(mode,"total") == 0) - *value = (double)((__int64)totalBytes.QuadPart); - else - return SYSINFO_RC_NOTSUPPORTED; - - return SYSINFO_RC_SUCCESS; -} - -// -// Handler for service_state[*] parameter -// - -static LONG H_ServiceState(char *cmd,char *arg,double *value) -{ - SC_HANDLE mgr,service; - char serviceName[MAX_PATH]; - - - GetParameterInstance(cmd,serviceName,MAX_PATH-1); - - mgr=OpenSCManager(NULL,NULL,GENERIC_READ); - if (mgr==NULL) - { - *value=255; // Unable to retrieve information - return SYSINFO_RC_SUCCESS; - } - - service=OpenService(mgr,serviceName,SERVICE_QUERY_STATUS); - if (service==NULL) - { - *value=SYSINFO_RC_NOTSUPPORTED; - } - else - { - SERVICE_STATUS status; - - if (QueryServiceStatus(service,&status)) - { - int i; - static DWORD states[7]={ SERVICE_RUNNING,SERVICE_PAUSED,SERVICE_START_PENDING, - SERVICE_PAUSE_PENDING,SERVICE_CONTINUE_PENDING, - SERVICE_STOP_PENDING,SERVICE_STOPPED }; - - for(i=0;i<7;i++) - if (status.dwCurrentState==states[i]) - break; - *value=(double)i; - } - else - { - *value=255; // Unable to retrieve information - } - - CloseServiceHandle(service); - } - - CloseServiceHandle(mgr); - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for perf_counter[*] parameter -// - -static LONG H_PerfCounter(char *cmd,char *arg,double *value) -{ - HQUERY query; - HCOUNTER counter; - PDH_RAW_COUNTER rawData; - PDH_FMT_COUNTERVALUE counterValue; - PDH_STATUS status; - char counterName[MAX_PATH]; - - - GetParameterInstance(cmd,counterName,MAX_PATH-1); - -LOG_DEBUG_INFO("s","H_PerfCounter: start"); -LOG_DEBUG_INFO("s", counterName); - - if (PdhOpenQuery(NULL,0,&query)!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_OPEN_QUERY_FAILED,EVENTLOG_ERROR_TYPE,"s", - GetSystemErrorText(GetLastError())); - return SYSINFO_RC_ERROR; - } - - if ((status=PdhAddCounter(query,counterName,0,&counter))!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_ADD_COUNTER_FAILED,EVENTLOG_ERROR_TYPE,"ss", - counterName,GetPdhErrorText(status)); - PdhCloseQuery(query); - return SYSINFO_RC_NOTSUPPORTED; - } - - if (PdhCollectQueryData(query)!=ERROR_SUCCESS) - { - WriteLog(MSG_PDH_COLLECT_QUERY_DATA_FAILED,EVENTLOG_ERROR_TYPE,"s", - GetSystemErrorText(GetLastError())); - PdhRemoveCounter(&counter); - PdhCloseQuery(query); - return SYSINFO_RC_ERROR; - } - - PdhGetRawCounterValue(counter,NULL,&rawData); - PdhCalculateCounterFromRawValue(counter,PDH_FMT_DOUBLE, - &rawData,NULL,&counterValue); - PdhRemoveCounter(&counter); - - PdhCloseQuery(query); - *value=counterValue.doubleValue; -LOG_DEBUG_INFO("s","H_PerfCounter: value"); -LOG_DEBUG_INFO("d",*value); -LOG_DEBUG_INFO("s","H_PerfCounter: end"); - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for user counters -// - -static LONG H_UserCounter(char *cmd,char *arg,double *value) -{ - USER_COUNTER *counter; - char *ptr1,*ptr2; - - - ptr1=strchr(cmd,'{'); - ptr2=strchr(cmd,'}'); - ptr1++; - *ptr2=0; - for(counter=userCounterList;counter!=NULL;counter=counter->next) - if (!strcmp(counter->name,ptr1)) - { - *value=counter->lastValue; - return SYSINFO_RC_SUCCESS; - } - - return SYSINFO_RC_NOTSUPPORTED; -} - - -// -// Calculate MD5 hash for file -// - -static LONG H_MD5Hash(char *cmd,char *arg,char **value) -{ - char - *fileName, - param[MAX_PATH], - hashText[MD5_DIGEST_SIZE*2+1]; - - unsigned char - *data=NULL, - hash[MD5_DIGEST_SIZE]; - - HANDLE - hFile=NULL, - hFileMapping=NULL; - - DWORD - dwSize=0, - dwSizeHigh=0; - - int i=0; - - - - // Get file name from parameter name and open it - GetParameterInstance(cmd,param,MAX_PATH-1); - - if(num_param(param) != 1) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - fileName = param; - - - hFile=CreateFile(fileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL); - if (hFile==INVALID_HANDLE_VALUE) - return SYSINFO_RC_NOTSUPPORTED; - - // Get file size - dwSize=GetFileSize(hFile,&dwSizeHigh); - if (dwSizeHigh>0 || dwSize>0x4000000) - return SYSINFO_RC_NOTSUPPORTED; // We will not work with files larger than 64MB - - if (dwSize>0) // We will not create mapping for zero-length files - { - // Create file mapping object - hFileMapping=CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL); - if (hFileMapping==NULL) - { - WriteLog(MSG_FILE_MAP_FAILED,EVENTLOG_ERROR_TYPE,"se", - fileName,GetLastError()); - CloseHandle(hFile); - return SYSINFO_RC_ERROR; - } - - // Map entire file to process's address space - data=(unsigned char *)MapViewOfFile(hFileMapping,FILE_MAP_READ,0,0,0); - if (data==NULL) - { - WriteLog(MSG_MAP_VIEW_FAILED,EVENTLOG_ERROR_TYPE,"se", - fileName,GetLastError()); - CloseHandle(hFileMapping); - CloseHandle(hFile); - return SYSINFO_RC_ERROR; - } - } - - - CalculateMD5Hash(data,dwSize,hash); - - // Unmap and close file - if (dwSize>0) - { - UnmapViewOfFile(data); - CloseHandle(hFileMapping); - } - CloseHandle(hFile); - - // Convert MD5 hash to text form - for(i=0;i<MD5_DIGEST_SIZE;i++) - sprintf(&hashText[i<<1],"%02x",hash[i]); - - *value=strdup(hashText); - return SYSINFO_RC_SUCCESS; -} - - -// -// Calculate CRC32 for file -// - -static LONG H_CRC32(char *cmd,char *arg,double *value) -{ - char - *fileName, - param[MAX_PATH]; - - HANDLE - hFile = NULL, - hFileMapping = NULL; - - DWORD - dwSize, - dwSizeHigh, - crc; - - unsigned char *data = NULL; - -INIT_CHECK_MEMORY(main); - - // Get file name from parameter name and open it - GetParameterInstance(cmd,param,MAX_PATH-1); - - if(num_param(param) != 1) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - fileName = param; - - hFile=CreateFile(fileName,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,0,NULL); - if (hFile==INVALID_HANDLE_VALUE) - return SYSINFO_RC_NOTSUPPORTED; - - // Get file size - dwSize=GetFileSize(hFile,&dwSizeHigh); - if (dwSizeHigh>0 || dwSize>0x4000000) - return SYSINFO_RC_NOTSUPPORTED; // We will not work with files larger than 64MB - - if (dwSize>0) // We will not create mapping for zero-length files - { - // Create file mapping object - hFileMapping=CreateFileMapping(hFile,NULL,PAGE_READONLY,0,0,NULL); - if (hFileMapping==NULL) - { - WriteLog(MSG_FILE_MAP_FAILED,EVENTLOG_ERROR_TYPE,"ss", - fileName,GetSystemErrorText(GetLastError())); - CloseHandle(hFile); - return SYSINFO_RC_ERROR; - } - - // Map entire file to process's address space - data=(unsigned char *)MapViewOfFile(hFileMapping,FILE_MAP_READ,0,0,0); - if (data==NULL) - { - WriteLog(MSG_MAP_VIEW_FAILED,EVENTLOG_ERROR_TYPE,"ss", - fileName,GetSystemErrorText(GetLastError())); - CloseHandle(hFileMapping); - CloseHandle(hFile); - - return SYSINFO_RC_ERROR; - } - } - - crc=CalculateCRC32(data,dwSize); - - // Unmap and close file - if (dwSize>0) - { - UnmapViewOfFile(data); - CloseHandle(hFileMapping); - } - CloseHandle(hFile); - - *value=(double)crc; - -CHECK_MEMORY(main, "H_FileSize","end"); - - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for filesize[*] parameter -// - -static LONG H_FileSize(char *cmd,char *arg,double *value) -{ - char - param[MAX_PATH], - *fileName; - HANDLE hFind; - WIN32_FIND_DATA findData; - -INIT_CHECK_MEMORY(main); - - GetParameterInstance(cmd,param,MAX_PATH-1); - - if(num_param(param) != 1) - { - return SYSINFO_RC_NOTSUPPORTED; - } - - fileName = param; - - hFind=FindFirstFile(fileName,&findData); - if (hFind==INVALID_HANDLE_VALUE) - { -CHECK_MEMORY(main, "H_FileSize","INVALID_HANDLE_VALUE"); - return SYSINFO_RC_ERROR; - } - FindClose(hFind); - - *value=(double)findData.nFileSizeLow+(double)(((__int64)findData.nFileSizeHigh) << 32); - -CHECK_MEMORY(main, "H_FileSize","end"); - - return SYSINFO_RC_SUCCESS; -} - - -// -// Handler for system[uname] parameter -// - -static LONG H_SystemUname(char *cmd,char *arg,char **value) -{ - DWORD dwSize; - char *cpuType,computerName[MAX_COMPUTERNAME_LENGTH+1],osVersion[256],buffer[1024]; - SYSTEM_INFO sysInfo; - OSVERSIONINFO versionInfo; - -LOG_FUNC_CALL("In H_SystemUname()"); -INIT_CHECK_MEMORY(main); - - dwSize=MAX_COMPUTERNAME_LENGTH+1; - GetComputerName(computerName,&dwSize); - - versionInfo.dwOSVersionInfoSize=sizeof(OSVERSIONINFO); - GetVersionEx(&versionInfo); - GetSystemInfo(&sysInfo); - - switch(versionInfo.dwPlatformId) - { - case VER_PLATFORM_WIN32_WINDOWS: - sprintf(osVersion,"Windows %s-%s",versionInfo.dwMinorVersion==0 ? "95" : - (versionInfo.dwMinorVersion==10 ? "98" : - (versionInfo.dwMinorVersion==90 ? "Me" : "Unknown")),versionInfo.szCSDVersion); - break; - case VER_PLATFORM_WIN32_NT: - if (versionInfo.dwMajorVersion!=5) - sprintf(osVersion,"Windows NT %d.%d %s",versionInfo.dwMajorVersion, - versionInfo.dwMinorVersion,versionInfo.szCSDVersion); - else // Windows 2000, Windows XP or Windows Server 2003 - sprintf(osVersion,"Windows %s%s%s",versionInfo.dwMinorVersion==0 ? "2000" : - (versionInfo.dwMinorVersion==1 ? "XP" : "Server 2003"), - versionInfo.szCSDVersion[0]==0 ? "" : " ",versionInfo.szCSDVersion); - break; - default: - strcpy(osVersion,"Windows [Unknown Version]"); - break; - } - - switch(sysInfo.wProcessorArchitecture) - { - case PROCESSOR_ARCHITECTURE_INTEL: - cpuType="Intel IA-32"; - break; - case PROCESSOR_ARCHITECTURE_MIPS: - cpuType="MIPS"; - break; - case PROCESSOR_ARCHITECTURE_ALPHA: - cpuType="Alpha"; - break; - case PROCESSOR_ARCHITECTURE_PPC: - cpuType="PowerPC"; - break; - case PROCESSOR_ARCHITECTURE_IA64: - cpuType="Intel IA-64"; - break; - case PROCESSOR_ARCHITECTURE_IA32_ON_WIN64: - cpuType="IA-32 on IA-64"; - break; - case PROCESSOR_ARCHITECTURE_AMD64: - cpuType="AMD-64"; - break; - default: - cpuType="unknown"; - break; - } - - sprintf(buffer,"Windows %s %d.%d.%d %s %s",computerName,versionInfo.dwMajorVersion, - versionInfo.dwMinorVersion,versionInfo.dwBuildNumber,osVersion,cpuType); - *value=strdup(buffer); - -CHECK_MEMORY(main, "H_SystemUname","end"); -LOG_FUNC_CALL("End of H_SystemUname()"); - - return SYSINFO_RC_SUCCESS; -} - - -// -// Parameters and handlers -// - -static AGENT_COMMAND commands[]= -{ /* name handler_float handler_string arg */ - { "__exec{*}", NULL, H_Execute, NULL }, - { "__usercnt{*}", H_UserCounter, NULL, NULL }, - { "system.run[*]", NULL, H_RunCommand, NULL }, - - { "agent.stat[avg_collector_time]", H_NumericPtr, NULL, (char *)&statAvgCollectorTime }, - { "agent.stat[max_collector_time]", H_NumericPtr, NULL, (char *)&statMaxCollectorTime }, - { "agent.stat[accepted_requests]", H_NumericPtr, NULL, (char *)&statAcceptedRequests }, - { "agent.stat[rejected_requests]", H_NumericPtr, NULL, (char *)&statRejectedRequests }, - { "agent.stat[timed_out_requests]", H_NumericPtr, NULL, (char *)&statTimedOutRequests }, - { "agent.stat[accept_errors]", H_NumericPtr, NULL, (char *)&statAcceptErrors }, - { "agent.stat[processed_requests]", H_NumericPtr, NULL, (char *)&statProcessedRequests }, - { "agent.stat[failed_requests]", H_NumericPtr, NULL, (char *)&statFailedRequests }, - { "agent.stat[unsupported_requests]", H_NumericPtr, NULL, (char *)&statUnsupportedRequests }, - - { "proc_info[*]", H_ProcInfo, NULL, NULL }, // TODO 'new realization and naming' - { "perf_counter[*]", H_PerfCounter, NULL, NULL }, // TODO 'new naming' - { "service_state[*]", H_ServiceState, NULL, NULL }, // TODO 'new naming' - -// { "check_port[*]", H_CheckTcpPort, NULL, NULL }, - { "net.tcp.port[*]", H_CheckTcpPort, NULL, NULL }, - -// { "cpu_util", H_ProcUtil, NULL, (char *)0x00 }, -// { "cpu_util5", H_ProcUtil, NULL, (char *)0x01 }, -// { "cpu_util15", H_ProcUtil, NULL, (char *)0x02 }, -// { "cpu_util[*]", H_ProcUtil, NULL, (char *)0x80 }, -// { "cpu_util5[*]", H_ProcUtil, NULL, (char *)0x81 }, -// { "cpu_util15[*]", H_ProcUtil, NULL, (char *)0x82 }, - { "system.cpu.util[*]", H_CpuUtil, NULL, NULL}, - -// { "diskfree[*]", H_DiskInfo, NULL, NULL }, -// { "disktotal[*]", H_DiskInfo, NULL, NULL }, -// { "diskused[*]", H_DiskInfo, NULL, NULL }, - { "vfs.fs.size[*]", H_DiskInfo, NULL, NULL }, - -// { "filesize[*]", H_FileSize, NULL, NULL }, - { "vfs.file.size[*]", H_FileSize, NULL, NULL }, - -// { "cksum[*]", H_CRC32, NULL, NULL }, - { "vfs.file.cksum[*]", H_CRC32, NULL, NULL }, - -// { "md5_hash[*]", NULL, H_MD5Hash, NULL }, - { "vfs.file.md5sum[*]", NULL, H_MD5Hash, NULL }, - -// { "swap[*]", H_MemoryInfo, NULL, NULL }, - { "system.swap.size[*]", H_SwapSize, NULL, NULL }, - -// { "memory[*]", H_MemoryInfo, NULL, NULL }, - { "vm.memory.size[*]", H_MemorySize, NULL, NULL }, - -// { "ping", H_NumericConstant, NULL, (char *)1 }, - { "agent.ping", H_NumericConstant, NULL, (char *)1 }, - -// { "proc_cnt[*]", H_ProcCountSpecific,NULL, NULL }, -// { "system[proccount]", H_ProcCount, NULL, NULL }, - { "proc.num[*]", H_ProcNum, NULL, NULL }, - -// { "system[procload]", H_NumericPtr, NULL, (char *)&statProcLoad }, -// { "system[procload5]", H_NumericPtr, NULL, (char *)&statProcLoad5 }, -// { "system[procload15]", H_NumericPtr, NULL, (char *)&statProcLoad15 }, - { "system.cpu.load[*]", H_CpuLoad, NULL, NULL}, - -// { "system[uname]", NULL, H_SystemUname, NULL }, - { "system.uname", NULL, H_SystemUname, NULL }, - -// { "system[hostname]", NULL, H_HostName, NULL }, - { "system.hostname", NULL, H_HostName, NULL }, - -// { "version[zabbix_agent]", NULL, H_StringConstant, AGENT_VERSION }, - { "agent.version", NULL, H_StringConstant, AGENT_VERSION }, - - { "",NULL,NULL,NULL } -}; - - -// -// Command processing function -// - -void ProcessCommand(char *received_cmd,char *result) -{ - int i; - double fResult=NOTSUPPORTED; - char *strResult=NULL,cmd[MAX_ZABBIX_CMD_LEN]; - LONG iRC=SYSINFO_RC_NOTSUPPORTED; - SUBAGENT *sbi; - BOOL isSubagentCommand=FALSE; - -assert(received_cmd); -assert(result); - -LOG_FUNC_CALL("In ProcessCommand()"); -INIT_CHECK_MEMORY(main); - - for(i=0; received_cmd[i]!='\0'; i++) - { - if(received_cmd[i] == '\r' || received_cmd[i] == '\n') - { - received_cmd[i] = '\0'; - break; - } - } - - ExpandAlias(received_cmd,cmd); - - // Find match for command in subagents - for(sbi=subagentList; sbi!=NULL; sbi=sbi->next) - { - for(i=0;;i++) - { - if (sbi->cmdList[i].name[0]==0) - break; - - if (MatchString(sbi->cmdList[i].name,cmd)) - { - if (sbi->cmdList[i].handler_float!=NULL) - { - iRC=sbi->cmdList[i].handler_float(cmd,&fResult); - } - else if (sbi->cmdList[i].handler_string!=NULL) - { - iRC=sbi->cmdList[i].handler_string(cmd,&strResult); - } - isSubagentCommand=TRUE; - goto finish_cmd_processing; - } - } - } - - // Find match for command in internal command list - for(i=0; commands[i].name[0]!='\0'; i++) - { - if (MatchString(commands[i].name,cmd)) - { - if (commands[i].handler_float!=NULL) - { - iRC=commands[i].handler_float(cmd,commands[i].arg,&fResult); - } - else if (commands[i].handler_string!=NULL) - { - iRC=commands[i].handler_string(cmd,commands[i].arg,&strResult); - } - break; - } - } - -finish_cmd_processing:; - - switch(iRC) - { - case SYSINFO_RC_SUCCESS: - if (strResult==NULL) - { - sprintf(result,"%f",fResult); - } - else - { - strncpy(result,strResult,MAX_STRING_LEN-1); - strcat(result,"\n"); - } - statProcessedRequests++; - break; - case SYSINFO_RC_NOTSUPPORTED: - strcpy(result,"ZBX_NOTSUPPORTED\n"); - statUnsupportedRequests++; - break; - case SYSINFO_RC_ERROR: - strcpy(result,"ZBX_ERROR\n"); - statFailedRequests++; - break; - default: - strcpy(result,"ZBX_ERROR\n"); - WriteLog(MSG_UNEXPECTED_IRC,EVENTLOG_ERROR_TYPE,"ds",iRC,received_cmd); - statFailedRequests++; - break; - } - - if(strResult) - { - if (isSubagentCommand) - zfree(strResult); - else - free(strResult); - } - -CHECK_MEMORY(main, "ProcessCommand","end"); -LOG_FUNC_CALL("End of ProcessCommand()"); -} - -char *test_cmd = NULL; - -int TestCommand() -{ - char result[MAX_STRING_LEN]; - int i = 0; - -LOG_FUNC_CALL("In TestCommand()"); - result[0] = 0; - ProcessCommand(test_cmd, result); - - for(i=0; result[i]!='\0'; i++) - { - if(result[i] == '\r' || result[i] == '\n') - { - result[i] = '\0'; - break; - } - } - - printf("%-35s [%s]\n",test_cmd, result); -LOG_FUNC_CALL("End of TestCommand()"); - return 0; -}
\ No newline at end of file diff --git a/src/zabbix_agent_win32/util.cpp b/src/zabbix_agent_win32/util.cpp deleted file mode 100644 index bbb8b4e6..00000000 --- a/src/zabbix_agent_win32/util.cpp +++ /dev/null @@ -1,597 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: util.cpp -** -**/ - -#include "zabbixw32.h" - - -// -// Display help -// - -static void Help(void) -{ - printf("Usage: zabbixw32 [options] [command]\n\n" - "Where possible commands are:\n" - " check-config : Check configuration file and exit\n" - " standalone : Run in standalone mode\n" - " start : Start Zabbix Win32 Agent service\n" - " stop : Stop Zabbix Win32 Agent service\n" - " install : Install Zabbix Win32 Agent as service\n" - " remove : Remove previously installed Zabbix Win32 Agent service\n" - " install-events : Install Zabbix Win32 Agent as event source for Event Log\n" - " This is done automatically when service is being installed\n" - " remove-events : Remove Zabbix Win32 Agent event source\n" - " This is done automatically when service is being removed\n" - " help : Display help information\n" - " version : Display version information\n" - " test <metric> : Test specified metric and exit\n\n" - "And possible options are:\n" - " --config <file> : Specify alternate configuration file\n" - " (default is %s)\n\n", confFile); -} - - -// -// Parse command line -// Return value: -// TRUE if program execution should be continued -// FALSE otherwise -// - -int ParseCommandLine(int argc,char *argv[]) -{ - int i; - int ret = TRUE; - char path[MAX_PATH]; - -INIT_CHECK_MEMORY(main); - - for(i=1;i<argc;i++) - { - if (!strcmp(argv[i],"help")) // Display help and exit - { - Help(); - exit(0); - goto lbl_end; - } - else if (!strcmp(argv[i],"version")) // Display version and exit - { - printf("Zabbix Win32 Agent Version " AGENT_VERSION " Build of " __DATE__ "\n"); - exit(0); - goto lbl_end; - } - else if (!strcmp(argv[i],"--config")) // Config file - { - i++; - strcpy(confFile,argv[i]); // Next word should contain name of the config file - ret = TRUE; - } - else if (!strcmp(argv[i],"standalone")) // Run in standalone mode - { - dwFlags|=AF_STANDALONE; - ret = TRUE; - } - else if ((!strcmp(argv[i],"install"))|| - (!strcmp(argv[i],"install-events"))) - { - _fullpath(path,argv[0],MAX_PATH); - - if (!strcmp(argv[i],"install")) - ret = ZabbixCreateService(path); - else - ret = ZabbixInstallEventSource(path); - exit(ret); - goto lbl_end; - } - else if (!strcmp(argv[i],"remove")) - { - ret = ZabbixRemoveService(); - exit(ret); - goto lbl_end; - } - else if (!strcmp(argv[i],"remove-events")) - { - ret = ZabbixRemoveEventSource(); - exit(ret); - goto lbl_end; - } - else if (!strcmp(argv[i],"start")) - { - ret = ZabbixStartService(); - exit(ret); - goto lbl_end; - } - else if (!strcmp(argv[i],"stop")) - { - ret = ZabbixStopService(); - exit(ret); - goto lbl_end; - } - else if (!strcmp(argv[i],"test")) - { - i++; - test_cmd = argv[i]; - dwFlags|=AF_STANDALONE; - ret = TRUE; - } - else if (!strcmp(argv[i],"check-config")) - { - dwFlags|=AF_STANDALONE; - printf("Checking configuration file:\n\n"); - ret = ReadConfig(); - exit(ret); - goto lbl_end; - } - else - { - printf("ERROR: Invalid command line argument\n\n"); - Help(); - exit(1); - goto lbl_end; - } - } -lbl_end: -CHECK_MEMORY(main,"GetSystemErrorText","end"); - - return ret; -} - - -// -// Get system error string by call to FormatMessage -// - -char *GetSystemErrorText(DWORD error) -{ - char *msgBuf; - static char staticBuffer[1024]; - -INIT_CHECK_MEMORY(main); - - if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL,error, - MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Default language - (LPSTR)&msgBuf,0,NULL)>0) - { - msgBuf[strcspn(msgBuf,"\r\n")]=0; - strncpy(staticBuffer,msgBuf,1023); - LocalFree(msgBuf); - } - else - { - sprintf(staticBuffer,"3. MSG 0x%08X - Unable to find message text [0x%X]", error , GetLastError()); - } - -CHECK_MEMORY(main,"GetSystemErrorText","end"); - - return staticBuffer; -} - - -// -// Extract word from line. Extracted word will be placed in buffer. -// Returns pointer to the next word or to the null character if end -// of line reached. -// - -char *ExtractWord(char *line,char *buffer) -{ - char *ptr,*bptr; - -INIT_CHECK_MEMORY(main); - - for(ptr=line;(*ptr==' ')||(*ptr=='\t');ptr++); // Skip initial spaces - // Copy word to buffer - for(bptr=buffer;(*ptr!=' ')&&(*ptr!='\t')&&(*ptr!=0);ptr++,bptr++) - *bptr=*ptr; - *bptr=0; - - CHECK_MEMORY(main,"MatchString","end"); - return ptr; -} - - -// -// Match string against pattern with * and ? metasymbols -// - -BOOL MatchString(char *pattern,char *string) -{ - char *SPtr,*MPtr,*BPtr; - - SPtr=string; - MPtr=pattern; - -INIT_CHECK_MEMORY(main); - - while(*MPtr!=0) - { - switch(*MPtr) - { - case '?': - if (*SPtr!=0) - { - SPtr++; - MPtr++; - } - else - return FALSE; - break; - case '*': - while(*MPtr=='*') - MPtr++; - if (*MPtr==0) - return TRUE; - if (*MPtr=='?') // Handle "*?" case - { - if (*SPtr!=0) - SPtr++; - else - return FALSE; - break; - } - BPtr=MPtr; // Text block begins here - while((*MPtr!=0)&&(*MPtr!='?')&&(*MPtr!='*')) - MPtr++; // Find the end of text block - for(;;) - { - while((*SPtr!=0)&&(*SPtr!=*BPtr)) - SPtr++; - if (strlen(SPtr)<(size_t)(MPtr-BPtr)) - return FALSE; // Length of remained text less than remaining pattern - if (!memcmp(BPtr,SPtr,MPtr-BPtr)) - break; - SPtr++; - } - SPtr+=(MPtr-BPtr); // Increment SPtr because we alredy match current fragment - break; - default: - if (*MPtr==*SPtr) - { - SPtr++; - MPtr++; - } - else - return FALSE; - break; - } - } - -CHECK_MEMORY(main,"MatchString","end"); - return *SPtr==0 ? TRUE : FALSE; -} - - -// -// Strip whitespaces and tabs off the string -// - -void StrStrip(char *str) -{ - int i; - -INIT_CHECK_MEMORY(main); - - for(i=0;(str[i]!=0)&&((str[i]==' ')||(str[i]=='\t'));i++); - if (i>0) - memmove(str,&str[i],strlen(&str[i])+1); - for(i=strlen(str)-1;(i>=0)&&((str[i]==' ')||(str[i]=='\t'));i--); - str[i+1]=0; - -CHECK_MEMORY(main,"StrStrip","end"); -} - - -// -// Calculate MD5 hash for array of bytes -// - -void CalculateMD5Hash(const unsigned char *data,int nbytes,unsigned char *hash) -{ - md5_state_t state; - -INIT_CHECK_MEMORY(main); - - md5_init(&state); - md5_append(&state,(const md5_byte_t *)data,nbytes); - md5_finish(&state,(md5_byte_t *)hash); - -CHECK_MEMORY(main,"CalculateMD5Hash","end"); -} - - -// -// Table for CRC calculation -// - -static DWORD crctab[256]= -{ - 0x0, - 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, - 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, - 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, - 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, - 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, - 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, - 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, - 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, - 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, - 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, - 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, - 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, - 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, - 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, - 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, - 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, - 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, - 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, - 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, - 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, - 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, - 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, - 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, - 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, - 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, - 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, - 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, - 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, - 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, - 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, - 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, - 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, - 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, - 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, - 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, - 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, - 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, - 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, - 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, - 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, - 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, - 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, - 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, - 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, - 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, - 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, - 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, - 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, - 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, - 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, - 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 -}; - - -// -// Calculate CRC32 for buffer of specified length -// - -DWORD CalculateCRC32(const unsigned char *data,DWORD nbytes) -{ - register DWORD crc,len; - register const unsigned char *ptr; - -INIT_CHECK_MEMORY(main); - - crc=0; - for(len=nbytes,ptr=data;len>0;ptr++,len--) - crc=(crc << 8)^crctab[(crc >> 24)^(*ptr)]; - - // Include the length of the data block - for (len=nbytes;len!=0;len>>=8) - crc=(crc << 8)^crctab[(crc >> 24)^(len & 0xFF)]; - -CHECK_MEMORY(main,"GetPdhErrorText","end2"); - - return ~crc; -} - - -// -// Get error text for PDH functions -// - -char *GetPdhErrorText(DWORD error) -{ - char *msgBuf; - static char staticBuffer[1024]; - -INIT_CHECK_MEMORY(main); - - if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_HMODULE | - FORMAT_MESSAGE_IGNORE_INSERTS, - GetModuleHandle("PDH.DLL"),error, - MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), // Default language - (LPSTR)&msgBuf,0,NULL)>0) - { - msgBuf[strcspn(msgBuf,"\r\n")]=0; - strncpy(staticBuffer,msgBuf,1023); - LocalFree(msgBuf); -CHECK_MEMORY(main,"GetPdhErrorText","end1"); - return staticBuffer; - } - else - { -CHECK_MEMORY(main,"GetPdhErrorText","end2"); - return GetSystemErrorText(error); - } -} - - -// -// Get performance counter name by index -// - -char *GetCounterName(DWORD index) -{ - PERFCOUNTER *counterName; - DWORD dwSize; - char hostname[MAX_COMPUTERNAME_LENGTH+3]; - - counterName=perfCounterList; - while(counterName!=NULL) - { - if (counterName->pdhIndex == index) - break; - counterName = counterName->next; - } - if (counterName == NULL) - { - counterName = (PERFCOUNTER *)malloc(sizeof(PERFCOUNTER)); - memset(counterName, 0, sizeof(PERFCOUNTER)); - counterName->pdhIndex = index; - counterName->next = perfCounterList; - - sprintf(hostname, "\\\\"); - dwSize = MAX_COMPUTERNAME_LENGTH+1; - if(GetComputerName((char *) &hostname + 2, &dwSize)==0) - { - WriteLog(MSG_GET_COMPUTER_NAME_FAILED,EVENTLOG_ERROR_TYPE, - "s",GetSystemErrorText(GetLastError())); - } - - dwSize = MAX_COUNTER_NAME; - if (PdhLookupPerfNameByIndex((char *)&hostname, index, (char *)&counterName->name, &dwSize)==ERROR_SUCCESS) - { - perfCounterList = counterName; - } - else - { - WriteLog(MSG_LOOKUP_FAILED,EVENTLOG_ERROR_TYPE, - "s", GetSystemErrorText(GetLastError())); - free(counterName); - return "UnknownPerformanceCounter"; - } - } - - return (char *)&counterName->name; -} - -void FreeCounterList(void) -{ - PERFCOUNTER *curr; - PERFCOUNTER *next; - - next = perfCounterList; - while(next!=NULL) - { - curr = next; - next = curr->next; - free(curr); - } -} - -/****************************************************************************** - * * - * Function: get_param * - * * - * Purpose: return parameter by index (num) from parameter list (param) * - * * - * Parameters: * - * param - parameter list * - * num - requested parameter index * - * buf - pointer og output buffer * - * maxlem - size of output buffer * - * * - * Return value: 1 - on error * - * * - * Author: Eugene Grigorjev * - * * - * Comments: delimeter vor parameters is ',' * - * * - ******************************************************************************/ -int get_param(const char *param, int num, char *buf, int maxlen) -{ - char tmp[MAX_STRING_LEN]; - char *s; - int ret = 1; - int i = 0; - int idx = 0; - - strscpy(tmp,param); - - s = &tmp[0]; - - for(i=0; tmp[i] != '\0'; i++) - { - if(tmp[i] == ',') - { - idx++; - if(idx == num) - { - tmp[i]='\0'; - strncpy(buf, s, maxlen); - tmp[i]=','; /* restore source string */ - ret = 0; - break; - - } - s = &tmp[i+1]; - } - } - - if(ret != 0) - { - idx++; - if(idx == num) - { - strncpy(buf, s, maxlen); - ret = 0; - } - } - - return ret; -} - -/****************************************************************************** - * * - * Function: num_param * - * * - * Purpose: calculate count of parameters from parameter list (param) * - * * - * Parameters: * - * param - parameter list * - * * - * Return value: count of parameters * - * * - * Author: Eugene Grigorjev * - * * - * Comments: delimeter vor parameters is ',' * - * * - ******************************************************************************/ -int num_param(const char *param) -{ - int i; - int ret = 1; - - if(param == NULL) - return 0; - - for(i=0;param[i]!=0;i++) - { - if(param[i]==',') ret++; - } - - return ret; -} diff --git a/src/zabbix_agent_win32/xml.cpp b/src/zabbix_agent_win32/xml.cpp deleted file mode 100644 index 53abe3c0..00000000 --- a/src/zabbix_agent_win32/xml.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "zabbixw32.h" - -#include <string.h> - -/* Get DATA from <tag>DATA</tag> */ -int xml_get_data(char *xml,char *tag, char *data, int maxlen) -{ - int ret = SUCCEED; - char *start, *end; - char tag_open[MAX_STRING_LEN]; - char tag_close[MAX_STRING_LEN]; - int len; - -INIT_CHECK_MEMORY(main); - - sprintf(tag_open,"<%s>",tag); - sprintf(tag_close,"</%s>",tag); - - if(NULL==(start=strstr(xml,tag_open))) - { - ret = FAIL; - } - - if(NULL==(end=strstr(xml,tag_close))) - { - ret = FAIL; - } - - if(ret == SUCCEED) - { - if(end<start) - { - ret = FAIL; - } - } - - if(ret == SUCCEED) - { - len=end-(start+strlen(tag_open)); - - if(len>maxlen) len=maxlen; - - strncpy(data, start+strlen(tag_open),len); - } - -CHECK_MEMORY(main,"xml_get_data","end"); - - return ret; -} diff --git a/src/zabbix_agent_win32/xml_comms.cpp b/src/zabbix_agent_win32/xml_comms.cpp deleted file mode 100644 index e79895b7..00000000 --- a/src/zabbix_agent_win32/xml_comms.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "zabbixw32.h" - -int comms_create_request(char *host, char *key, char *data, char *lastlogsize, - char *timestamp, char *source, char *severity, char *request,int maxlen) -{ - int ret = SUCCEED; - char host_b64[MAX_STRING_LEN]; - char key_b64[MAX_STRING_LEN]; - char data_b64[MAX_STRING_LEN]; - char lastlogsize_b64[MAX_STRING_LEN]; - char timestamp_b64[MAX_STRING_LEN]; - char source_b64[MAX_STRING_LEN]; - char severity_b64[MAX_STRING_LEN]; - -INIT_CHECK_MEMORY(main); - - memset(host_b64,0,sizeof(host_b64)); - memset(key_b64,0,sizeof(key_b64)); - memset(data_b64,0,sizeof(data_b64)); - memset(lastlogsize_b64,0,sizeof(lastlogsize_b64)); - memset(timestamp_b64,0,sizeof(timestamp_b64)); - memset(source_b64,0,sizeof(source_b64)); - memset(severity_b64,0,sizeof(severity_b64)); - - str_base64_encode(host, host_b64, strlen(host)); - str_base64_encode(key, key_b64, strlen(key)); - str_base64_encode(data, data_b64, strlen(data)); - str_base64_encode(lastlogsize, lastlogsize_b64, strlen(lastlogsize)); - str_base64_encode(timestamp, timestamp_b64, strlen(timestamp)); - str_base64_encode(source, source_b64, strlen(source)); - str_base64_encode(severity, severity_b64, strlen(severity)); - - if(lastlogsize[0]==0) - { - sprintf(request,"<req><host>%s</host><key>%s</key><data>%s</data></req>", - host_b64,key_b64,data_b64); - } - else - { - if(timestamp[0] == 0) - { - sprintf(request,"<req><host>%s</host><key>%s</key><data>%s</data><lastlogsize>%s</lastlogsize></req>", - host_b64,key_b64,data_b64,lastlogsize_b64); - } - else - { - sprintf(request,"<req><host>%s</host><key>%s</key><data>%s</data><lastlogsize>%s</lastlogsize><timestamp>%s</timestamp><source>%s</source><severity>%s</severity></req>", - host_b64,key_b64,data_b64,lastlogsize_b64,timestamp_b64,source_b64,severity_b64); - } - } - -CHECK_MEMORY(main,"comms_create_request","end"); - return ret; -} - -int comms_parse_response(char *xml,char *host,char *key, char *data, char *lastlogsize, int maxlen) -{ - int ret = SUCCEED; - int i; - - char host_b64[MAX_STRING_LEN]; - char key_b64[MAX_STRING_LEN]; - char data_b64[MAX_STRING_LEN]; - char lastlogsize_b64[MAX_STRING_LEN]; - -INIT_CHECK_MEMORY(main); - - memset(host_b64,0,sizeof(host_b64)); - memset(key_b64,0,sizeof(key_b64)); - memset(data_b64,0,sizeof(data_b64)); - memset(lastlogsize_b64,0,sizeof(lastlogsize_b64)); - - xml_get_data(xml, "host", host_b64, sizeof(host_b64)-1); - xml_get_data(xml, "key", key_b64, sizeof(key_b64)-1); - xml_get_data(xml, "data", data_b64, sizeof(data_b64)-1); - xml_get_data(xml, "lastlogsize", lastlogsize_b64, sizeof(lastlogsize_b64)-1); - - memset(key,0,maxlen); - memset(host,0,maxlen); - memset(data,0,maxlen); - memset(lastlogsize,0,maxlen); - - str_base64_decode(host_b64, host, &i); - str_base64_decode(key_b64, key, &i); - str_base64_decode(data_b64, data, &i); - str_base64_decode(lastlogsize_b64, lastlogsize, &i); - -CHECK_MEMORY(main,"comms_parse_response","end"); - - return ret; -} diff --git a/src/zabbix_agent_win32/zabbix_subagent.h b/src/zabbix_agent_win32/zabbix_subagent.h deleted file mode 100644 index f86ecbc4..00000000 --- a/src/zabbix_agent_win32/zabbix_subagent.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -** Zabbix Subagent API -** Copyright (C) 2003 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -**/ - -#ifndef _zabbix_subagent_h_ -#define _zabbix_subagent_h_ - -/* -** Subagent exportables call specs -*/ - -#ifdef _WIN32 -#define __zabbix_api __cdecl -#else -#define __zabbix_api -#endif - - -#define MAX_CMDNAME 256 - - -/* -** Subagent command definition structure -*/ - -typedef struct -{ - char name[MAX_CMDNAME]; - int (__zabbix_api * handler_float)(char *,double *); /* Handler if return value is floating point numeric */ - int (__zabbix_api * handler_string)(char *,char **); /* Handler if return value is string */ -} SUBAGENT_COMMAND; - - -/* -** Return codes for command handlers -*/ - -#define SYSINFO_RC_SUCCESS 0 -#define SYSINFO_RC_NOTSUPPORTED 1 -#define SYSINFO_RC_ERROR 2 - - -/* -** Wrappers for memory allocation functions -*/ - -#ifdef _WIN32 -#define zmalloc(x) HeapAlloc(GetProcessHeap(),0,x) -#define zrealloc(x,y) HeapReAlloc(GetProcessHeap(),0,x,y) -#define zfree(x) HeapFree(GetProcessHeap(),0,x) -#define zstrdup(x) strcpy((char *)HeapAlloc(GetProcessHeap(),0,strlen(x)+1),x) -#else -#define zmalloc(x) malloc(x) -#define zrealloc(x,y) realloc(x,y) -#define zfree(x) free(x) -#define zstrdup(x) strdup(x) -#endif - - -#endif diff --git a/src/zabbix_agent_win32/zabbixw32.h b/src/zabbix_agent_win32/zabbixw32.h deleted file mode 100644 index 271660c2..00000000 --- a/src/zabbix_agent_win32/zabbixw32.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -** ZabbixW32 - Win32 agent for Zabbix -** Copyright (C) 2002 Victor Kirhenshtein -** -** This program is free software; you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation; either version 2 of the License, or -** (at your option) any later version. -** -** This program is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have received a copy of the GNU General Public License -** along with this program; if not, write to the Free Software -** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -** -** $module: zabbixw32.h -** -**/ - -#ifndef _zabbixw32_h_ -#define _zabbixw32_h_ - -#include <windows.h> -#include <process.h> -#include <stdio.h> -#include <pdh.h> -#include <psapi.h> -#include "common.h" -#include "md5.h" -#include "messages.h" -#include "zabbix_subagent.h" - - -// -// Common constants -// - -#ifdef _DEBUG -#define DEBUG_SUFFIX "-debug" -#else -#define DEBUG_SUFFIX -#endif -#define AGENT_VERSION "1.1" DEBUG_SUFFIX - -#define ZABBIX_SERVICE_NAME "ZabbixAgentdW32" -#define ZABBIX_EVENT_SOURCE "Zabbix Win32 Agent" - -#define COMMAND_TIMEOUT 5 - -#define MAX_SERVERS 32 -#define MAX_ZABBIX_CMD_LEN MAX_STRING_LEN -#define MAX_CPU 16 -#define MAX_PARAM_NAME 64 -#define MAX_PROCESSES 4096 -#define MAX_MODULES 512 -#define MAX_ALIAS_NAME 120 -#define MAX_COUNTER_NAME (MAX_ALIAS_NAME-12) - - -// -// Performance Counter Indexes -// - -#define PCI_SYSTEM 2 -#define PCI_PROCESSOR 238 -#define PCI_PROCESSOR_TIME 6 -#define PCI_PROCESSOR_QUEUE_LENGTH 44 -#define PCI_SYSTEM_UP_TIME 674 - - -// -// Application flags -// - -#define AF_STANDALONE 0x0001 -#define AF_USE_EVENT_LOG 0x0002 -#define AF_LOG_UNRESOLVED_SYMBOLS 0x0004 - -#define IsStandalone() (dwFlags & AF_STANDALONE) - -// -// Parameter definition structure -// - -struct AGENT_COMMAND -{ - char name[MAX_PARAM_NAME]; // Command's name - LONG (* handler_float)(char *,char *,double *); // Handler if return value is floating point numeric - LONG (* handler_string)(char *,char *,char **); // Handler if return value is string - char *arg; // Optional command argument -}; - - -// -// Alias information structure -// - -struct ALIAS -{ - ALIAS *next; - char name[MAX_ALIAS_NAME]; - char *value; -}; - - -// -// User-defined performance counter structure -// - -struct USER_COUNTER -{ - USER_COUNTER *next; // Pointer to next counter in chain - char name[MAX_PARAM_NAME]; - char counterPath[MAX_PATH]; - LONG interval; // Time interval used in calculations - LONG currPos; // Current position in buffer - HCOUNTER handle; // Counter handle (set by collector thread) - PDH_RAW_COUNTER *rawValueArray; - double lastValue; // Last computed average value -}; - - -// -// Performance Countername structure -// - -struct PERFCOUNTER -{ - PERFCOUNTER *next; - DWORD pdhIndex; - char name[MAX_COUNTER_NAME + 1]; -}; - - -// -// Subagent information structure -// - -struct SUBAGENT -{ - SUBAGENT *next; // Pointer to next element in a chain - HMODULE hModule; // DLL module handle - int (__zabbix_api * init)(char *,SUBAGENT_COMMAND **); - void (__zabbix_api * shutdown)(void); - SUBAGENT_COMMAND *cmdList; // List of subagent's commands -}; - - -// -// Subagent names list -// - -struct SUBAGENT_NAME -{ - char *name; - char *cmdLine; -}; - -struct REQUEST -{ - char cmd[MAX_ZABBIX_CMD_LEN]; - char result[MAX_STRING_LEN]; -}; - - -// -// Functions -// - -BOOL ParseCommandLine(int argc,char *argv[]); -char *GetSystemErrorText(DWORD error); -char *GetPdhErrorText(DWORD error); -BOOL MatchString(char *pattern,char *string); -void StrStrip(char *string); -void GetParameterInstance(char *param,char *instance,int maxSize); - -void CalculateMD5Hash(const unsigned char *data,int nbytes,unsigned char *hash); -DWORD CalculateCRC32(const unsigned char *data,DWORD nbytes); - -void InitService(void); -int ZabbixCreateService(char *execName); -int ZabbixRemoveService(void); -int ZabbixStartService(void); -int ZabbixStopService(void); - -int ZabbixInstallEventSource(char *path); -int ZabbixRemoveEventSource(void); - -char *GetCounterName(DWORD index); - -void InitLog(void); -void CloseLog(void); -void WriteLog(DWORD msg,WORD wType,char *format...); - -BOOL Initialize(void); -void Shutdown(void); -void Main(void); - -void ListenerThread(void *); -void CollectorThread(void *); -void ActiveChecksThread(void *); - -void ProcessCommand(char *cmd,char *result); - -extern char *test_cmd; -int TestCommand(void); - -BOOL ReadConfig(void); - -BOOL AddAlias(char *name,char *value); -void ExpandAlias(char *orig,char *expanded); - -unsigned int __stdcall ProcessingThread(void *arg); -int process_log(char *filename,int *lastlogsize, char *value); -int process_eventlog(char *source,int *lastlogsize, char *timestamp, char *src, char *severity, char *message); - -void str_base64_encode(char *p_str, char *p_b64str, int in_size); -void str_base64_decode(char *p_b64str, char *p_str, int *p_out_size); - -int comms_create_request(char *host, char *key, char *data, char *lastlogsize, - char *timestamp, char *source, char *severity, char *request,int maxlen); - - -int xml_get_data(char *xml,char *tag, char *data, int maxlen); - -int num_param(const char *param); -int get_param(const char *param, int num, char *buf, int maxlen); - -// -// Global variables -// - -extern HANDLE eventShutdown; -extern HANDLE eventCollectorStarted; - -extern DWORD dwFlags; -extern DWORD g_dwLogLevel; - -extern char confFile[]; -extern char logFile[]; -extern char confHostname[]; -extern char confServer[]; -extern DWORD confServerAddr[]; -extern DWORD confServerCount; -extern WORD confListenPort; -extern WORD confServerPort; -extern DWORD confTimeout; -extern DWORD confMaxProcTime; -extern DWORD confEnableRemoteCommands; - -extern USER_COUNTER *userCounterList; -void FreeUserCounterList(void); - -extern SUBAGENT *subagentList; - -extern SUBAGENT_NAME *subagentNameList; -void FreeSubagentNameList(void); - -extern PERFCOUNTER *perfCounterList; -void FreeCounterList(void); - -void FreeAliasList(void); - -extern double statProcUtilization[]; -extern double statProcUtilization5[]; -extern double statProcUtilization15[]; -extern double statProcLoad; -extern double statProcLoad5; -extern double statProcLoad15; -extern double statAvgCollectorTime; -extern double statMaxCollectorTime; -extern double statAcceptedRequests; -extern double statRejectedRequests; -extern double statTimedOutRequests; -extern double statAcceptErrors; - -extern DWORD (__stdcall *imp_GetGuiResources)(HANDLE,DWORD); -extern BOOL (__stdcall *imp_GetProcessIoCounters)(HANDLE,PIO_COUNTERS); -extern BOOL (__stdcall *imp_GetPerformanceInfo)(PPERFORMANCE_INFORMATION,DWORD); -extern BOOL (__stdcall *imp_GlobalMemoryStatusEx)(LPMEMORYSTATUSEX); - -#endif diff --git a/src/zabbix_agent_win32/zabbixw32.rc b/src/zabbix_agent_win32/zabbixw32.rc deleted file mode 100644 index 6c2bc674..00000000 --- a/src/zabbix_agent_win32/zabbixw32.rc +++ /dev/null @@ -1,70 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// 11 -// - -1 11 DISCARDABLE "Msg00001.bin" -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - |