Icinga-core 1.4.0
next gen monitoring
cgi/cgiutils.c
Go to the documentation of this file.
00001 /***********************************************************************
00002  *
00003  * CGIUTILS.C - Common utilities for Icinga CGIs
00004  *
00005  * Copyright (c) 1999-2009 Ethan Galstad (egalstad@nagios.org)
00006  * Copyright (c) 2009-2011 Icinga Development Team (http://www.icinga.org)
00007  *
00008  * License:
00009  *
00010  * This program is free software; you can redistribute it and/or modify
00011  * it under the terms of the GNU General Public License version 2 as
00012  * published by the Free Software Foundation.
00013  *
00014  * This program is distributed in the hope that it will be useful,
00015  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00016  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00017  * GNU General Public License for more details.
00018  *
00019  * You should have received a copy of the GNU General Public License
00020  * along with this program; if not, write to the Free Software
00021  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
00022  ***********************************************************************/
00023 
00024 #include "../include/config.h"
00025 #include "../include/common.h"
00026 #include "../include/locations.h"
00027 #include "../include/objects.h"
00028 #include "../include/statusdata.h"
00029 
00030 #include "../include/cgiutils.h"
00031 
00032 char            main_config_file[MAX_FILENAME_LENGTH];
00033 char            command_file[MAX_FILENAME_LENGTH];
00034 
00035 char            physical_html_path[MAX_FILENAME_LENGTH];
00036 char            physical_images_path[MAX_FILENAME_LENGTH];
00037 char            physical_ssi_path[MAX_FILENAME_LENGTH];
00038 char            url_html_path[MAX_FILENAME_LENGTH];
00039 char            url_docs_path[MAX_FILENAME_LENGTH];
00040 char            url_context_help_path[MAX_FILENAME_LENGTH];
00041 char            url_images_path[MAX_FILENAME_LENGTH];
00042 char            url_logo_images_path[MAX_FILENAME_LENGTH];
00043 char            url_stylesheets_path[MAX_FILENAME_LENGTH];
00044 char            url_js_path[MAX_FILENAME_LENGTH];
00045 char            url_media_path[MAX_FILENAME_LENGTH];
00046 
00047 char            *service_critical_sound=NULL;
00048 char            *service_warning_sound=NULL;
00049 char            *service_unknown_sound=NULL;
00050 char            *host_down_sound=NULL;
00051 char            *host_unreachable_sound=NULL;
00052 char            *normal_sound=NULL;
00053 char            *statusmap_background_image=NULL;
00054 char            *statuswrl_include=NULL;
00055 
00056 char            *illegal_output_chars=NULL;
00057 
00058 char            *http_charset=NULL;
00059 
00060 char            *notes_url_target=NULL;
00061 char            *action_url_target=NULL;
00062 
00063 char            *ping_syntax=NULL;
00064 
00065 char            *csv_delimiter=CSV_DELIMITER;
00066 char            *csv_data_enclosure=CSV_DATA_ENCLOSURE;
00067 
00068 char            nagios_check_command[MAX_INPUT_BUFFER]="";
00069 char            nagios_process_info[MAX_INPUT_BUFFER]="";
00070 int             nagios_process_state=STATE_OK;
00071 
00072 int             enable_splunk_integration=FALSE;
00073 char            *splunk_url=NULL;
00074 int             lock_author_names=TRUE;
00075 
00076 extern time_t   program_start;
00077 extern int      nagios_pid;
00078 extern int      daemon_mode;
00079 extern int      enable_notifications;
00080 extern int      execute_service_checks;
00081 extern int      accept_passive_service_checks;
00082 extern int      enable_event_handlers;
00083 extern int      obsess_over_services;
00084 extern int      enable_failure_prediction;
00085 extern int      process_performance_data;
00086 extern time_t   last_command_check;
00087 extern time_t   last_log_rotation;
00088 
00090 int             log_rotation_method=LOG_ROTATION_NONE;
00091 extern time_t   this_scheduled_log_rotation;
00092 extern time_t   last_scheduled_log_rotation;
00093 extern time_t   next_scheduled_log_rotation;
00094 char            log_file[MAX_INPUT_BUFFER];
00095 char            log_archive_path[MAX_INPUT_BUFFER];
00096 
00097 
00098 int             check_external_commands=0;
00099 
00100 int             log_external_commands_user=FALSE;
00101 
00102 int             date_format=DATE_FORMAT_US;
00103 
00104 int             use_authentication=TRUE;
00105 
00106 int             interval_length=60;
00107 
00108 int             show_context_help=FALSE;
00109 int             show_all_services_host_is_authorized_for=TRUE;
00110 
00111 int             use_pending_states=TRUE;
00112 
00113 int             host_status_has_been_read=FALSE;
00114 int             service_status_has_been_read=FALSE;
00115 int             program_status_has_been_read=FALSE;
00116 
00117 int             refresh_rate=DEFAULT_REFRESH_RATE;
00118 
00119 int             escape_html_tags=FALSE;
00120 
00121 int             persistent_ack_comments=FALSE;
00122 
00123 int             use_ssl_authentication=FALSE;
00124 
00125 int             default_statusmap_layout_method=0;
00126 int             default_statuswrl_layout_method=0;
00127 
00128 int             color_transparency_index_r=255;
00129 int             color_transparency_index_g=255;
00130 int             color_transparency_index_b=255;
00131 
00132 int             status_show_long_plugin_output=FALSE;
00133 int             tac_show_only_hard_state=FALSE;
00134 int             show_tac_header=TRUE;
00135 int             showlog_initial_states=TRUE;
00136 int             showlog_current_states=TRUE;
00137 int             tab_friendly_titles=FALSE;
00138 int             add_notif_num_hard=0;
00139 int             add_notif_num_soft=0;
00140 int             enforce_comments_on_actions=FALSE;
00141 int             week_starts_on_monday=FALSE;
00142 
00143 extern hostgroup       *hostgroup_list;
00144 extern contactgroup    *contactgroup_list;
00145 extern command         *command_list;
00146 extern timeperiod      *timeperiod_list;
00147 extern contact         *contact_list;
00148 extern serviceescalation *serviceescalation_list;
00149 
00150 extern hoststatus      *hoststatus_list;
00151 extern servicestatus   *servicestatus_list;
00152 
00153 
00154 char encoded_url_string[2][MAX_INPUT_BUFFER]; // 2 to be able use url_encode twice
00155 char *encoded_html_string=NULL;
00156 
00157 #ifdef HAVE_TZNAME
00158 #ifdef CYGWIN
00159 extern char     *_tzname[2] __declspec(dllimport);
00160 #else
00161 extern char     *tzname[2];
00162 #endif
00163 #endif
00164 
00165 int content_type=HTML_CONTENT;
00166 int embedded=FALSE;
00167 int display_header=TRUE;
00168 int refresh=TRUE;
00169 int daemon_check=TRUE;
00170 int tac_header=FALSE;
00171 
00172 extern char alert_message;
00173 extern char *host_name;
00174 extern char *host_filter;
00175 extern char *hostgroup_name;
00176 extern char *service_desc;
00177 extern char *servicegroup_name;
00178 extern char *service_filter;
00179 extern int host_alert;
00180 extern int show_all_hosts;
00181 extern int show_all_hostgroups;
00182 extern int show_all_servicegroups;
00183 extern int display_type;
00184 extern int overview_columns;
00185 extern int max_grid_width;
00186 extern int group_style_type;
00187 extern int navbar_search;
00188 extern int CGI_ID;
00189 
00190 /* used for logging function */
00191 char            cgi_log_file[MAX_FILENAME_LENGTH]="";
00192 char            cgi_log_archive_path[MAX_FILENAME_LENGTH]="";
00193 int             use_logging=FALSE;
00194 int             cgi_log_rotation_method=LOG_ROTATION_NONE;
00195 
00196 /*
00197  * These function stubs allow us to compile a lot of the
00198  * source-files common to cgi's and daemon without adding
00199  * a whole bunch of #ifdef's everywhere. Note that we can't
00200  * have them as macros, since the goal is to compile the
00201  * source-files once. A decent linker will make the call
00202  * a no-op anyway, so it's not a big issue
00203  */
00204 void logit(int data_type, int display, const char *fmt, ...) { return; }
00205 int log_debug_info(int leve, int verbosity, const char *fmt, ...) { return 0; }
00206 
00207 /**********************************************************
00208  ***************** CLEANUP FUNCTIONS **********************
00209  **********************************************************/
00210 
00211 /* reset all variables used by the CGIs */
00212 void reset_cgi_vars(void){
00213 
00214         strcpy(main_config_file,"");
00215 
00216         strcpy(physical_html_path,"");
00217         strcpy(physical_images_path,"");
00218         strcpy(physical_ssi_path,"");
00219 
00220         strcpy(url_html_path,"");
00221         strcpy(url_docs_path,"");
00222         strcpy(url_context_help_path,"");
00223         strcpy(url_stylesheets_path,"");
00224         strcpy(url_js_path,"");
00225         strcpy(url_media_path,"");
00226         strcpy(url_images_path,"");
00227 
00228         strcpy(log_file,"");
00229         strcpy(log_archive_path,DEFAULT_LOG_ARCHIVE_PATH);
00230         if(log_archive_path[strlen(log_archive_path)-1]!='/' && strlen(log_archive_path)<sizeof(log_archive_path)-2)
00231                 strcat(log_archive_path,"/");
00232         strcpy(command_file,get_cmd_file_location());
00233 
00234         strcpy(nagios_check_command,"");
00235         strcpy(nagios_process_info,"");
00236         nagios_process_state=STATE_OK;
00237 
00238         log_rotation_method=LOG_ROTATION_NONE;
00239         cgi_log_rotation_method=LOG_ROTATION_NONE;
00240 
00241         use_authentication=TRUE;
00242 
00243         interval_length=60;
00244 
00245         refresh_rate=DEFAULT_REFRESH_RATE;
00246 
00247         default_statusmap_layout_method=0;
00248         default_statusmap_layout_method=0;
00249 
00250         service_critical_sound=NULL;
00251         service_warning_sound=NULL;
00252         service_unknown_sound=NULL;
00253         host_down_sound=NULL;
00254         host_unreachable_sound=NULL;
00255         normal_sound=NULL;
00256 
00257         my_free(http_charset);
00258         http_charset = strdup(DEFAULT_HTTP_CHARSET);
00259 
00260         statusmap_background_image=NULL;
00261         color_transparency_index_r=255;
00262         color_transparency_index_g=255;
00263         color_transparency_index_b=255;
00264         statuswrl_include=NULL;
00265 
00266         ping_syntax=NULL;
00267 
00268         return;
00269 }
00270 
00271 /* free all memory for object definitions */
00272 void free_memory(void){
00273 
00274         /* free memory for common object definitions */
00275         free_object_data();
00276 
00277         /* free memory for status data */
00278         free_status_data();
00279 
00280         /* free misc data */
00281         free(service_critical_sound);
00282         free(service_warning_sound);
00283         free(service_unknown_sound);
00284         free(host_down_sound);
00285         free(host_unreachable_sound);
00286         free(normal_sound);
00287         free(statusmap_background_image);
00288         free(statuswrl_include);
00289         free(ping_syntax);
00290 
00291         return;
00292 }
00293 
00294 
00295 /**********************************************************
00296  *************** CONFIG FILE FUNCTIONS ********************
00297  **********************************************************/
00298 
00299 /* read the CGI config file location from an environment variable */
00300 char * get_cgi_config_location(void){
00301         static char *cgiloc=NULL;
00302 
00303         if(!cgiloc){
00304                 cgiloc=getenv("ICINGA_CGI_CONFIG");
00305                 if(!cgiloc){
00306                         /* stay compatible */
00307                         cgiloc=getenv("NAGIOS_CGI_CONFIG");
00308                         if(!cgiloc){
00309                                 cgiloc=DEFAULT_CGI_CONFIG_FILE;
00310                         }
00311                 }
00312         }
00313 
00314         return cgiloc;
00315 }
00316 
00317 /* read the command file location from an environment variable */
00318 char * get_cmd_file_location(void){
00319         static char *cmdloc=NULL;
00320 
00321         if(!cmdloc){
00322                 cmdloc=getenv("ICINGA_COMMAND_FILE");
00323                 if(!cmdloc){
00324                         /* stay compatible */
00325                         cmdloc=getenv("NAGIOS_COMMAND_FILE");
00326                         if(!cmdloc){
00327                                 cmdloc=DEFAULT_COMMAND_FILE;
00328                         }
00329                 }
00330         }
00331         return cmdloc;
00332 }
00333 
00334 /*read the CGI configuration file */
00335 int read_cgi_config_file(char *filename){
00336         char *input=NULL;
00337         mmapfile *thefile;
00338         char *var=NULL;
00339         char *val=NULL;
00340 
00341 
00342         if((thefile=mmap_fopen(filename))==NULL)
00343                 return ERROR;
00344 
00345         while(1){
00346 
00347                 /* free memory */
00348                 free(input);
00349 
00350                 /* read the next line */
00351                 if((input=mmap_fgets_multiline(thefile))==NULL)
00352                         break;
00353 
00354                 strip(input);
00355 
00356                 var=strtok(input,"=");
00357                 val=strtok(NULL,"\n");
00358 
00359                 if(var==NULL || val==NULL)
00360                         continue;
00361 
00362                 if(!strcmp(var,"main_config_file")){
00363                         strncpy(main_config_file,val,sizeof(main_config_file));
00364                         main_config_file[sizeof(main_config_file)-1]='\x0';
00365                         strip(main_config_file);
00366                         }
00367 
00368                 else if(!strcmp(var,"show_context_help"))
00369                         show_context_help=(atoi(val)>0)?TRUE:FALSE;
00370 
00371                 else if(!strcmp(var,"show_all_services_host_is_authorized_for"))
00372                         show_all_services_host_is_authorized_for=(atoi(val)>0)?TRUE:FALSE;
00373 
00374                 else if(!strcmp(var,"use_pending_states"))
00375                         use_pending_states=(atoi(val)>0)?TRUE:FALSE;
00376 
00377                 else if(!strcmp(var,"use_authentication"))
00378                         use_authentication=(atoi(val)>0)?TRUE:FALSE;
00379 
00380                 else if(!strcmp(var,"nagios_check_command")){
00381                         strncpy(nagios_check_command,val,sizeof(nagios_check_command));
00382                         nagios_check_command[sizeof(nagios_check_command)-1]='\x0';
00383                         strip(nagios_check_command);
00384                         }
00385 
00386                 else if(!strcmp(var,"refresh_rate"))
00387                         refresh_rate=atoi(val);
00388 
00389                 else if(!strcmp(var,"physical_html_path")){
00390                         strncpy(physical_html_path,val,sizeof(physical_html_path));
00391                         physical_html_path[sizeof(physical_html_path)-1]='\x0';
00392                         strip(physical_html_path);
00393                         if(physical_html_path[strlen(physical_html_path)-1]!='/' && (strlen(physical_html_path) < sizeof(physical_html_path)-1))
00394                                 strcat(physical_html_path,"/");
00395 
00396                         snprintf(physical_images_path,sizeof(physical_images_path),"%simages/",physical_html_path);
00397                         physical_images_path[sizeof(physical_images_path)-1]='\x0';
00398 
00399                         snprintf(physical_ssi_path,sizeof(physical_images_path),"%sssi/",physical_html_path);
00400                         physical_ssi_path[sizeof(physical_ssi_path)-1]='\x0';
00401                         }
00402 
00403                 else if(!strcmp(var,"url_html_path")){
00404 
00405                         strncpy(url_html_path,val,sizeof(url_html_path));
00406                         url_html_path[sizeof(url_html_path)-1]='\x0';
00407 
00408                         strip(url_html_path);
00409                         if(url_html_path[strlen(url_html_path)-1]!='/' && (strlen(url_html_path) < sizeof(url_html_path)-1))
00410                                 strcat(url_html_path,"/");
00411 
00412                         snprintf(url_docs_path,sizeof(url_docs_path),"%sdocs/",url_html_path);
00413                         url_docs_path[sizeof(url_docs_path)-1]='\x0';
00414 
00415                         snprintf(url_context_help_path,sizeof(url_context_help_path),"%scontexthelp/",url_html_path);
00416                         url_context_help_path[sizeof(url_context_help_path)-1]='\x0';
00417 
00418                         snprintf(url_images_path,sizeof(url_images_path),"%simages/",url_html_path);
00419                         url_images_path[sizeof(url_images_path)-1]='\x0';
00420 
00421                         snprintf(url_logo_images_path,sizeof(url_logo_images_path),"%slogos/",url_images_path);
00422                         url_logo_images_path[sizeof(url_logo_images_path)-1]='\x0';
00423 
00424                         /*
00425                         snprintf(url_stylesheets_path,sizeof(url_stylesheets_path),"%sstylesheets/",url_html_path);
00426                         url_stylesheets_path[sizeof(url_stylesheets_path)-1]='\x0';
00427                         */
00428 
00429                         snprintf(url_js_path,sizeof(url_js_path),"%sjs/",url_html_path);
00430                         url_js_path[sizeof(url_js_path)-1]='\x0';
00431 
00432                         snprintf(url_media_path,sizeof(url_media_path),"%smedia/",url_html_path);
00433                         url_media_path[sizeof(url_media_path)-1]='\x0';
00434                         }
00435 
00436                 else if(!strcmp(var,"url_stylesheets_path")){
00437 
00438                         strncpy(url_stylesheets_path,val,sizeof(url_stylesheets_path));
00439                         url_stylesheets_path[sizeof(url_stylesheets_path)-1]='\x0';
00440 
00441                         strip(url_stylesheets_path);
00442                         if(url_stylesheets_path[strlen(url_stylesheets_path)-1]!='/' && (strlen(url_stylesheets_path) < sizeof(url_stylesheets_path)-1))
00443                                 strcat(url_stylesheets_path,"/");
00444 
00445                         }
00446                 else if(!strcmp(var,"cgi_log_archive_path")){
00447 
00448                         strncpy(cgi_log_archive_path,val,sizeof(cgi_log_archive_path));
00449                         cgi_log_archive_path[sizeof(cgi_log_archive_path)-1]='\x0';
00450 
00451                         strip(cgi_log_archive_path);
00452                         if(cgi_log_archive_path[strlen(cgi_log_archive_path)-1]!='/' && (strlen(cgi_log_archive_path) < sizeof(cgi_log_archive_path)-1))
00453                                 strcat(cgi_log_archive_path,"/");
00454 
00455                         }
00456                 else if(!strcmp(var,"cgi_log_file")){
00457 
00458                         strncpy(cgi_log_file,val,sizeof(cgi_log_file));
00459                         cgi_log_file[sizeof(cgi_log_file)-1]='\x0';
00460                         }
00461                 else if(!strcmp(var,"cgi_log_rotation_method")){
00462                         if(!strcmp(val,"h"))
00463                                 cgi_log_rotation_method=LOG_ROTATION_HOURLY;
00464                         else if(!strcmp(val,"d"))
00465                                 cgi_log_rotation_method=LOG_ROTATION_DAILY;
00466                         else if(!strcmp(val,"w"))
00467                                 cgi_log_rotation_method=LOG_ROTATION_WEEKLY;
00468                         else if(!strcmp(val,"m"))
00469                                 cgi_log_rotation_method=LOG_ROTATION_MONTHLY;
00470                         }
00471                 else if(!strcmp(var,"use_logging"))
00472                         use_logging=(atoi(val)>0)?TRUE:FALSE;
00473 
00474                 else if(!strcmp(var,"enforce_comments_on_actions"))
00475                         enforce_comments_on_actions=(atoi(val)>0)?TRUE:FALSE;
00476 
00477                 else if(!strcmp(var,"first_day_of_week"))
00478                         week_starts_on_monday=(atoi(val)>0)?TRUE:FALSE;
00479 
00480                 else if(!strcmp(var,"service_critical_sound"))
00481                         service_critical_sound=strdup(val);
00482 
00483                 else if(!strcmp(var,"service_warning_sound"))
00484                         service_warning_sound=strdup(val);
00485 
00486                 else if(!strcmp(var,"service_unknown_sound"))
00487                         service_unknown_sound=strdup(val);
00488 
00489                 else if(!strcmp(var,"host_down_sound"))
00490                         host_down_sound=strdup(val);
00491 
00492                 else if(!strcmp(var,"host_unreachable_sound"))
00493                         host_unreachable_sound=strdup(val);
00494 
00495                 else if(!strcmp(var,"normal_sound"))
00496                         normal_sound=strdup(val);
00497 
00498                 else if(!strcmp(var,"statusmap_background_image"))
00499                         statusmap_background_image=strdup(val);
00500 
00501                 else if(!strcmp(var,"color_transparency_index_r"))
00502                         color_transparency_index_r=atoi(val);
00503 
00504                 else if(!strcmp(var,"color_transparency_index_g"))
00505                         color_transparency_index_g=atoi(val);
00506 
00507                 else if(!strcmp(var,"color_transparency_index_b"))
00508                         color_transparency_index_b=atoi(val);
00509 
00510                 else if(!strcmp(var,"default_statusmap_layout"))
00511                         default_statusmap_layout_method=atoi(val);
00512 
00513                 else if(!strcmp(var,"default_statuswrl_layout"))
00514                         default_statuswrl_layout_method=atoi(val);
00515 
00516                 else if(!strcmp(var,"statuswrl_include"))
00517                         statuswrl_include=strdup(val);
00518 
00519                 else if(!strcmp(var,"ping_syntax"))
00520                         ping_syntax=strdup(val);
00521 
00522                 else if(!strcmp(var,"action_url_target"))
00523                         action_url_target=strdup(val);
00524 
00525                 else if(!strcmp(var,"illegal_macro_output_chars"))
00526                         illegal_output_chars=strdup(val);
00527 
00528                 else if(!strcmp(var,"http_charset"))
00529                         http_charset=strdup(val);
00530 
00531                 else if(!strcmp(var,"notes_url_target"))
00532                         notes_url_target=strdup(val);
00533 
00534                 else if(!strcmp(var,"enable_splunk_integration"))
00535                         enable_splunk_integration=(atoi(val)>0)?TRUE:FALSE;
00536 
00537                 else if(!strcmp(var,"splunk_url"))
00538                         splunk_url=strdup(val);
00539 
00540                 else if(!strcmp(var,"escape_html_tags"))
00541                         escape_html_tags=(atoi(val)>0)?TRUE:FALSE;
00542 
00543                 else if(!strcmp(var,"persistent_ack_comments"))
00544                         persistent_ack_comments=(atoi(val)>0)?TRUE:FALSE;
00545 
00546                 else if(!strcmp(var,"lock_author_names"))
00547                         lock_author_names=(atoi(val)>0)?TRUE:FALSE;
00548 
00549                 else if(!strcmp(var,"use_ssl_authentication"))
00550                         use_ssl_authentication=(atoi(val)>0)?TRUE:FALSE;
00551 
00552                 else if(!strcmp(var,"status_show_long_plugin_output"))
00553                         status_show_long_plugin_output=(atoi(val)>0)?TRUE:FALSE;
00554 
00555                 else if(!strcmp(var,"tac_show_only_hard_state"))
00556                         tac_show_only_hard_state=(atoi(val)>0)?TRUE:FALSE;
00557 
00558                 else if(!strcmp(var,"show_tac_header"))
00559                         show_tac_header=(atoi(val)>0)?TRUE:FALSE;
00560 
00561                 else if(!strcmp(var,"showlog_initial_state") || !strcmp(var,"showlog_initial_states"))
00562                         showlog_initial_states=(atoi(val)>0)?TRUE:FALSE;
00563 
00564                 else if(!strcmp(var,"showlog_current_state") || !strcmp(var,"showlog_current_states"))
00565                         showlog_current_states=(atoi(val)>0)?TRUE:FALSE;
00566 
00567                 else if(!strcmp(var,"tab_friendly_titles"))
00568                         tab_friendly_titles=(atoi(val)>0)?TRUE:FALSE;
00569 
00570                 else if(!strcmp(var,"add_notif_num_hard"))
00571                         add_notif_num_hard=atoi(val);
00572 
00573                 else if(!strcmp(var,"add_notif_num_soft"))
00574                         add_notif_num_soft=atoi(val);
00575 
00576                 else if(!strcmp(var,"csv_delimiter"))
00577                         csv_delimiter=strdup(val);
00578 
00579                 else if(!strcmp(var,"csv_data_enclosure"))
00580                         csv_data_enclosure=strdup(val);
00581 
00582                 }
00583 
00584         /* free memory and close the file */
00585         free(input);
00586         mmap_fclose(thefile);
00587 
00588         /* check if stylesheet path was set */
00589         if(!strcmp(url_stylesheets_path,"")){
00590                 snprintf(url_stylesheets_path,sizeof(url_stylesheets_path),"%sstylesheets/",url_html_path);
00591                 url_stylesheets_path[sizeof(url_stylesheets_path)-1]='\x0';
00592         }
00593 
00594         if(!strcmp(main_config_file,""))
00595                 return ERROR;
00596         else
00597                 return OK;
00598 }
00599 
00600 /* read the main configuration file */
00601 int read_main_config_file(char *filename){
00602         char *input=NULL;
00603         char *temp_buffer;
00604         mmapfile *thefile;
00605 
00606 
00607         if((thefile=mmap_fopen(filename))==NULL)
00608                 return ERROR;
00609 
00610         while(1){
00611 
00612                 /* free memory */
00613                 free(input);
00614 
00615                 /* read the next line */
00616                 if((input=mmap_fgets_multiline(thefile))==NULL)
00617                         break;
00618 
00619                 strip(input);
00620 
00621                 if(strstr(input,"interval_length=")==input){
00622                         temp_buffer=strtok(input,"=");
00623                         temp_buffer=strtok(NULL,"\x0");
00624                         interval_length=(temp_buffer==NULL)?60:atoi(temp_buffer);
00625                         }
00626 
00627                 else if(strstr(input,"log_file=")==input){
00628                         temp_buffer=strtok(input,"=");
00629                         temp_buffer=strtok(NULL,"\x0");
00630                         strncpy(log_file,(temp_buffer==NULL)?"":temp_buffer,sizeof(log_file));
00631                         log_file[sizeof(log_file)-1]='\x0';
00632                         strip(log_file);
00633                         }
00634 
00635                 else if(strstr(input,"log_archive_path=")==input){
00636                         temp_buffer=strtok(input,"=");
00637                         temp_buffer=strtok(NULL,"\n");
00638                         strncpy(log_archive_path,(temp_buffer==NULL)?"":temp_buffer,sizeof(log_archive_path));
00639                         log_archive_path[sizeof(log_archive_path)-1]='\x0';
00640                         strip(physical_html_path);
00641                         if(log_archive_path[strlen(log_archive_path)-1]!='/' && (strlen(log_archive_path) < sizeof(log_archive_path)-1))
00642                                 strcat(log_archive_path,"/");
00643                         }
00644 
00645                 else if(strstr(input,"log_rotation_method=")==input){
00646                         temp_buffer=strtok(input,"=");
00647                         temp_buffer=strtok(NULL,"\x0");
00648                         if(temp_buffer==NULL)
00649                                 log_rotation_method=LOG_ROTATION_NONE;
00650                         else if(!strcmp(temp_buffer,"h"))
00651                                 log_rotation_method=LOG_ROTATION_HOURLY;
00652                         else if(!strcmp(temp_buffer,"d"))
00653                                 log_rotation_method=LOG_ROTATION_DAILY;
00654                         else if(!strcmp(temp_buffer,"w"))
00655                                 log_rotation_method=LOG_ROTATION_WEEKLY;
00656                         else if(!strcmp(temp_buffer,"m"))
00657                                 log_rotation_method=LOG_ROTATION_MONTHLY;
00658                         }
00659 
00660                 else if(strstr(input,"command_file=")==input){
00661                         temp_buffer=strtok(input,"=");
00662                         temp_buffer=strtok(NULL,"\x0");
00663                         strncpy(command_file,(temp_buffer==NULL)?"":temp_buffer,sizeof(command_file));
00664                         command_file[sizeof(command_file)-1]='\x0';
00665                         strip(command_file);
00666                         }
00667 
00668                 else if(strstr(input,"check_external_commands=")==input){
00669                         temp_buffer=strtok(input,"=");
00670                         temp_buffer=strtok(NULL,"\x0");
00671                         check_external_commands=(temp_buffer==NULL)?0:atoi(temp_buffer);
00672                         }
00673 
00674                 else if(strstr(input,"log_external_commands_user=")==input){
00675                         temp_buffer=strtok(input,"=");
00676                         temp_buffer=strtok(NULL,"\x0");
00677                         log_external_commands_user=(temp_buffer==NULL)?0:atoi(temp_buffer);
00678                         }
00679 
00680                 else if(strstr(input,"date_format=")==input){
00681                         temp_buffer=strtok(input,"=");
00682                         temp_buffer=strtok(NULL,"\x0");
00683                         if(temp_buffer==NULL)
00684                                 date_format=DATE_FORMAT_US;
00685                         else if(!strcmp(temp_buffer,"euro"))
00686                                 date_format=DATE_FORMAT_EURO;
00687                         else if(!strcmp(temp_buffer,"iso8601"))
00688                                 date_format=DATE_FORMAT_ISO8601;
00689                         else if(!strcmp(temp_buffer,"strict-iso8601"))
00690                                 date_format=DATE_FORMAT_STRICT_ISO8601;
00691                         else
00692                                 date_format=DATE_FORMAT_US;
00693                 }
00694         }
00695 
00696         /* free memory and close the file */
00697         free(input);
00698         mmap_fclose(thefile);
00699 
00700         return OK;
00701 }
00702 
00703 /* read all object definitions */
00704 int read_all_object_configuration_data(char *config_file,int options){
00705         int result=OK;
00706 
00707         /* read in all external config data of the desired type(s) */
00708         result=read_object_config_data(config_file,options,FALSE,FALSE);
00709 
00710         return result;
00711 }
00712 
00713 /* read all status data */
00714 int read_all_status_data(char *config_file,int options){
00715         int result=OK;
00716 
00717         /* don't duplicate things we've already read in */
00718         if(program_status_has_been_read==TRUE && (options & READ_PROGRAM_STATUS))
00719                 options-=READ_PROGRAM_STATUS;
00720         if(host_status_has_been_read==TRUE && (options & READ_HOST_STATUS))
00721                 options-=READ_HOST_STATUS;
00722         if(service_status_has_been_read==TRUE && (options & READ_SERVICE_STATUS))
00723                 options-=READ_SERVICE_STATUS;
00724 
00725         /* bail out if we've already read what we need */
00726         if(options<=0)
00727                 return OK;
00728 
00729         /* read in all external status data */
00730         result=read_status_data(config_file,options);
00731 
00732         /* mark what items we've read in... */
00733         if(options & READ_PROGRAM_STATUS)
00734                 program_status_has_been_read=TRUE;
00735         if(options & READ_HOST_STATUS)
00736                 host_status_has_been_read=TRUE;
00737         if(options & READ_SERVICE_STATUS)
00738                 service_status_has_been_read=TRUE;
00739 
00740         return result;
00741 }
00742 
00743 
00744 /**********************************************************
00745  *************** COMMON HEADER AND FOOTER *****************
00746  **********************************************************/
00747 
00748 void document_header(int cgi_id, int use_stylesheet){
00749         char date_time[MAX_DATETIME_LENGTH];
00750         char *cgi_name=NULL;
00751         char *cgi_css=NULL;
00752         char *cgi_title=NULL;
00753         char *cgi_body_class=NULL;
00754         time_t expire_time;
00755         time_t current_time;
00756 
00757         switch(cgi_id) {
00758                 case STATUS_CGI_ID:
00759                         cgi_name        = STATUS_CGI;
00760                         cgi_css         = STATUS_CSS;
00761                         cgi_title       = "Current Network Status";
00762                         cgi_body_class  = "status";
00763                         break;
00764                 case AVAIL_CGI_ID:
00765                         cgi_name        = AVAIL_CGI;
00766                         cgi_css         = AVAIL_CSS;
00767                         cgi_title       = "Availability";
00768                         cgi_body_class  = "avail";
00769                         refresh         = FALSE;
00770                         break;
00771                 case CMD_CGI_ID:
00772                         cgi_name        = CMD_CGI;
00773                         cgi_css         = CMD_CSS;
00774                         cgi_title       = "External Command Interface";
00775                         cgi_body_class  = "cmd";
00776                         refresh         = FALSE;
00777                         break;
00778                 case CONFIG_CGI_ID:
00779                         cgi_name        = CONFIG_CGI;
00780                         cgi_css         = CONFIG_CSS;
00781                         cgi_title       = "Configuration";
00782                         cgi_body_class  = "config";
00783                         break;
00784                 case EXTINFO_CGI_ID:
00785                         cgi_name        = EXTINFO_CGI;
00786                         cgi_css         = EXTINFO_CSS;
00787                         cgi_title       = "Extended Information";
00788                         cgi_body_class  = "extinfo";
00789                         break;
00790                 case HISTOGRAM_CGI_ID:
00791                         cgi_name        = HISTOGRAM_CGI;
00792                         cgi_css         = HISTOGRAM_CSS;
00793                         cgi_title       = "Histogram";
00794                         cgi_body_class  = "histogram";
00795                         refresh         = FALSE;
00796                         break;
00797                 case HISTORY_CGI_ID:
00798                         cgi_name        = HISTORY_CGI;
00799                         cgi_css         = HISTORY_CSS;
00800                         cgi_title       = "History";
00801                         cgi_body_class  = "history";
00802                         refresh         = FALSE;
00803                         break;
00804                 case NOTIFICATIONS_CGI_ID:
00805                         cgi_name        = NOTIFICATIONS_CGI;
00806                         cgi_css         = NOTIFICATIONS_CSS;
00807                         cgi_title       = "Alert Notifications";
00808                         cgi_body_class  = "notifications";
00809                         break;
00810                 case OUTAGES_CGI_ID:
00811                         cgi_name        = OUTAGES_CGI;
00812                         cgi_css         = OUTAGES_CSS;
00813                         cgi_title       = "Network Outages";
00814                         cgi_body_class  = "outages";
00815                         break;
00816                 case SHOWLOG_CGI_ID:
00817                         cgi_name        = SHOWLOG_CGI;
00818                         cgi_css         = SHOWLOG_CSS;
00819                         cgi_title       = "Log File";
00820                         cgi_body_class  = "showlog";
00821                         refresh         = FALSE;
00822                         break;
00823                 case STATUSMAP_CGI_ID:
00824                         cgi_name        = STATUSMAP_CGI;
00825                         cgi_css         = STATUSMAP_CSS;
00826                         cgi_title       = "Network Map";
00827                         cgi_body_class  = "statusmap";
00828                         break;
00829                 case SUMMARY_CGI_ID:
00830                         cgi_name        = SUMMARY_CGI;
00831                         cgi_css         = SUMMARY_CSS;
00832                         cgi_title       = "Event Summary";
00833                         cgi_body_class  = "summary";
00834                         refresh         = FALSE;
00835                         break;
00836                 case TAC_CGI_ID:
00837                         cgi_name        = TAC_CGI;
00838                         cgi_css         = TAC_CSS;
00839                         cgi_title       = "Tactical Monitoring Overview";
00840                         cgi_body_class  = "tac";
00841                         if (tac_header==TRUE && show_tac_header==FALSE)
00842                                 refresh=FALSE;
00843                         break;
00844                 case TRENDS_CGI_ID:
00845                         cgi_name        = TRENDS_CGI;
00846                         cgi_css         = TRENDS_CSS;
00847                         cgi_title       = "Trends";
00848                         cgi_body_class  = "trends";
00849                         refresh         = FALSE;
00850                         break;
00851                 case ERROR_CGI_ID:
00852                         cgi_name        = "";
00853                         cgi_css         = CMD_CSS;
00854                         cgi_title       = "ERROR";
00855                         cgi_body_class  = "error";
00856                         break;
00857         }
00858 
00859 
00860         // don't refresh non html output
00861         if(content_type==JSON_CONTENT || content_type==CSV_CONTENT)
00862                 refresh=FALSE;
00863 
00864         if(content_type==WML_CONTENT){
00865                 /* used by cmd.cgi */
00866                 printf("Content-type: text/vnd.wap.wml; charset=\"%s\"\r\n\r\n", http_charset);
00867 
00868                 printf("<?xml version=\"1.0\"?>\n");
00869                 printf("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">\n");
00870 
00871                 printf("<wml>\n");
00872 
00873                 printf("<card id='card1' title='Command Results'>\n");
00874 
00875                 return;
00876         }
00877 
00878         if(cgi_id!=ERROR_CGI_ID){
00879                 printf("Cache-Control: no-store\r\n");
00880                 printf("Pragma: no-cache\r\n");
00881 
00882                 if(refresh==TRUE)
00883                         printf("Refresh: %d\r\n",refresh_rate);
00884 
00885                 get_time_string(&current_time,date_time,(int)sizeof(date_time),HTTP_DATE_TIME);
00886                 printf("Last-Modified: %s\r\n",date_time);
00887 
00888                 expire_time=(time_t)0L;
00889                 get_time_string(&expire_time,date_time,(int)sizeof(date_time),HTTP_DATE_TIME);
00890                 printf("Expires: %s\r\n",date_time);
00891         }
00892 
00893         if(cgi_id==STATUSWRL_CGI_ID) {
00894                 printf("Content-Type: x-world/x-vrml\r\n\r\n");
00895                 return;
00896         }
00897         if(cgi_id==STATUSWML_CGI_ID) {
00898 
00899                 printf("Content-type: text/vnd.wap.wml; charset=\"%s\"\r\n\r\n", http_charset);
00900 
00901                 printf("<?xml version=\"1.0\"?>\n");
00902                 printf("<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.1//EN\" \"http://www.wapforum.org/DTD/wml_1.1.xml\">\n");
00903 
00904                 printf("<wml>\n");
00905 
00906                 printf("<head>\n");
00907                 printf("<meta forua=\"true\" http-equiv=\"Cache-Control\" content=\"max-age=0\"/>\n");
00908                 printf("</head>\n");
00909 
00910                 return;
00911         }
00912         if(content_type==IMAGE_CONTENT) {
00913                 printf("Content-Type: image/png\r\n\r\n");
00914                 return;
00915         }
00916 
00917         if(content_type==CSV_CONTENT) {
00918                 printf("Content-type: text/plain; charset=\"%s\"\r\n\r\n", http_charset);
00919                 return;
00920         }
00921 
00922         if(content_type==JSON_CONTENT) {
00923                 printf("Content-type: text/json; charset=\"%s\"\r\n\r\n", http_charset);
00924                 printf("{ \"cgi_json_version\": \"%s\",\n",JSON_OUTPUT_VERSION);
00925                 printf("\"%s\": {\n",cgi_body_class);
00926                 return;
00927         }
00928 
00929 
00930         if(cgi_id!=ERROR_CGI_ID){
00931                 // send HTML CONTENT
00932                 printf("Content-type: text/html; charset=\"%s\"\r\n\r\n", http_charset);
00933         }
00934 
00935         /* is this tac.cgi?tac_header */
00936         if(cgi_id==TAC_CGI_ID && tac_header==TRUE) {
00937 
00938                 printf("<html>\n");
00939                 printf("<head>\n");
00940                 printf("<title>Icinga</title>\n");
00941                 printf("<meta name='robots' content='noindex, nofollow' />\n");
00942 
00943                 /* is show_tac_header=1 in cgi.cfg? */
00944                 if(show_tac_header==TRUE)
00945                         printf("<LINK REL='stylesheet' TYPE='text/css' HREF='%s%s'>\n",url_stylesheets_path,TAC_HEADER_CSS);
00946                 else //no? show the classic header as the default
00947                         printf("<LINK REL='stylesheet' TYPE='text/css' HREF='%sinterface/common.css'>\n",url_stylesheets_path);
00948 
00949                 printf("<link rel=\"shortcut icon\" href=\"%sfavicon.ico\" type=\"image/ico\">\n",url_images_path);
00950                 printf("</head>\n");
00951                 printf("<body>\n");
00952 
00953                 return; //safely return
00954         }
00955 
00956         if(embedded==TRUE)
00957                 return;
00958 
00959         printf("<html>\n");
00960         printf("<head>\n");
00961         printf("<link rel=\"shortcut icon\" href=\"%sfavicon.ico\" type=\"image/ico\">\n",url_images_path);
00962         printf("<META HTTP-EQUIV='Pragma' CONTENT='no-cache'>\n");
00963         printf("<title>\n");
00964 
00965         if(cgi_id == STATUS_CGI_ID){
00966                 if (tab_friendly_titles){
00967                         if ((display_type==DISPLAY_HOSTS)&&(!show_all_hosts)&&host_name&&(*host_name!='\0'))
00968                                 printf ("[%s]\n",html_encode(host_name,FALSE));
00969                         else if ((display_type==DISPLAY_HOSTGROUPS)&&(!show_all_hostgroups)&&hostgroup_name &&(*hostgroup_name!='\0'))
00970                                 printf ("{%s}\n",html_encode(hostgroup_name,FALSE));
00971                         else if ((display_type==DISPLAY_SERVICEGROUPS)&&(!show_all_servicegroups)&&servicegroup_name &&(*servicegroup_name!='\0'))
00972                                 printf ("(%s)\n",html_encode(servicegroup_name,FALSE));
00973                         else
00974                                 printf("%s\n",cgi_title);
00975                 }
00976                 else printf("%s\n",cgi_title);
00977         } else if(cgi_id == EXTINFO_CGI_ID){
00978                 if (tab_friendly_titles){
00979                         if ((display_type==DISPLAY_HOST_INFO)&&host_name&&(*host_name!='\0'))
00980                                 printf ("[%s]\n",html_encode(host_name,FALSE));
00981                         else if ((display_type==DISPLAY_SERVICE_INFO)&&service_desc&&(*service_desc!='\0')){
00982                                 printf ("%s\n",service_desc);
00983                                 if (host_name&&(*host_name!='\0'))
00984                                         printf ("@ %s\n",html_encode(host_name,FALSE));
00985                         }
00986                         else if ((display_type==DISPLAY_HOSTGROUP_INFO)&&hostgroup_name&&(*hostgroup_name!='\0'))
00987                                 printf ("{%s}\n",html_encode(hostgroup_name,FALSE));
00988                         else if ((display_type==DISPLAY_SERVICEGROUP_INFO)&&servicegroup_name &&(*servicegroup_name!='\0'))
00989                                 printf ("(%s)\n",html_encode(servicegroup_name,FALSE));
00990                         else
00991                                 printf("%s\n",cgi_title);
00992                 }
00993                 else printf("%s\n",cgi_title);
00994         } else {
00995                 printf("%s\n",cgi_title);
00996         }
00997         printf("</title>\n");
00998 
00999         if(use_stylesheet){
01000                 printf("<LINK REL='stylesheet' TYPE='text/css' HREF='%s%s'>\n",url_stylesheets_path,COMMON_CSS);
01001                 printf("<LINK REL='stylesheet' TYPE='text/css' HREF='%s%s'>\n",url_stylesheets_path,cgi_css);
01002         }
01003 
01004         if(cgi_id == STATUS_CGI_ID || cgi_id == EXTINFO_CGI_ID) {
01005                 /* JavaScript for dropdown menu WITH images */
01006                 printf("<script type='text/javascript' src='%s%s'></script>\n",url_js_path,JQUERY_MAIN_JS);
01007                 printf("<script type='text/javascript' src='%s%s'></script>\n",url_js_path,JQUERY_DD_JS);
01008 
01009                 /* This CSS IS needed for proper dropdown menu's (bypass the use_stylesheets above, who does without anyway?) */
01010                 printf("<link rel='stylesheet' type='text/css' href='%s%s'/>\n",url_stylesheets_path,JQUERY_DD_CSS);
01011 
01012                 /* functions to handle the checkboxes and dropdown menus */
01013                 printf("<script type='text/javascript' src='%s%s'></script>\n",url_js_path,CHECKBOX_FUNCTIONS_JS);
01014         }
01015 
01016         if(cgi_id==STATUSMAP_CGI_ID || cgi_id==TRENDS_CGI_ID) {
01017                 /* write JavaScript code for popup window */
01018                 write_popup_code(cgi_id);
01019         }
01020 
01021         printf("</head>\n");
01022 
01023         if(cgi_id==STATUSMAP_CGI_ID)
01024                 printf("<body CLASS='%s' name='mappage' id='mappage'>\n",cgi_body_class);
01025         else if(cgi_id==TAC_CGI_ID)
01026                 printf("<body CLASS='%s' marginwidth=2 marginheight=2 topmargin=0 leftmargin=0 rightmargin=0>\n",cgi_body_class);
01027         else
01028                 printf("<body CLASS='%s'>\n",cgi_body_class);
01029 
01030         /* include user SSI header */
01031         include_ssi_files(cgi_name,SSI_HEADER);
01032 
01033         /* this line was also in histogram.c, is this necessary??? */
01034         if(cgi_id==HISTOGRAM_CGI_ID || cgi_id==STATUSMAP_CGI_ID || cgi_id==TRENDS_CGI_ID)
01035                 printf("<div id=\"popup\" style=\"position:absolute; z-index:1; visibility: hidden\"></div>\n");
01036 
01037         if(cgi_id == STATUS_CGI_ID) {
01038                 /* Set everything in a form, so checkboxes can be searched after and checked. */
01039                 printf("<form name='tableform' id='tableform'>\n");
01040                 printf("<input type=hidden name=hiddenforcefield><input type=hidden name=hiddencmdfield><input type=hidden name=buttonValidChoice><input type=hidden name=buttonCheckboxChecked>\n");
01041 
01042                 /* Print out the activator for the dropdown (which must be between the body tags */
01043 /*              printf("<script language='javascript'>");
01044                 printf("$(document).ready(function(e) {");
01045                 printf("try {");
01046                 printf("$('body select').msDropDown();");
01047                 printf("} catch(e) {");
01048                 printf("alert(e.message);");
01049                 printf("}");
01050                 printf("});");
01051                 printf("</script>\n");
01052 */
01053                 /* Javascript lib to show tooltips */
01054         }
01055 
01056         if(cgi_id == STATUS_CGI_ID || cgi_id == CMD_CGI_ID) {
01057                 printf("\n<script type='text/javascript' src='%s%s'>\n<!-- SkinnyTip (c) Elliott Brueggeman -->\n</script>\n",url_js_path,SKINNYTIP_JS);
01058                 printf("<div id='tiplayer' style='position:absolute; visibility:hidden; z-index:1000;'></div>\n");
01059         }
01060 
01061         return;
01062 }
01063 
01064 
01065 void document_footer(int cgi_id){
01066         char *cgi_name=NULL;
01067 
01068         switch(cgi_id) {
01069                 case STATUS_CGI_ID:
01070                         cgi_name = STATUS_CGI;
01071                         break;
01072                 case AVAIL_CGI_ID:
01073                         cgi_name = AVAIL_CGI;
01074                         break;
01075                 case CMD_CGI_ID:
01076                         cgi_name = CMD_CGI;
01077                         break;
01078                 case CONFIG_CGI_ID:
01079                         cgi_name = CONFIG_CGI;
01080                         break;
01081                 case EXTINFO_CGI_ID:
01082                         cgi_name = EXTINFO_CGI;
01083                         break;
01084                 case HISTOGRAM_CGI_ID:
01085                         cgi_name = HISTOGRAM_CGI;
01086                         break;
01087                 case HISTORY_CGI_ID:
01088                         cgi_name = HISTORY_CGI;
01089                         break;
01090                 case NOTIFICATIONS_CGI_ID:
01091                         cgi_name = NOTIFICATIONS_CGI;
01092                         break;
01093                 case OUTAGES_CGI_ID:
01094                         cgi_name = OUTAGES_CGI;
01095                         break;
01096                 case SHOWLOG_CGI_ID:
01097                         cgi_name = SHOWLOG_CGI;
01098                         break;
01099                 case STATUSMAP_CGI_ID:
01100                         cgi_name = STATUSMAP_CGI;
01101                         break;
01102                 case SUMMARY_CGI_ID:
01103                         cgi_name = SUMMARY_CGI;
01104                         break;
01105                 case TAC_CGI_ID:
01106                         cgi_name = TAC_CGI;
01107                         break;
01108                 case TRENDS_CGI_ID:
01109                         cgi_name = TRENDS_CGI;
01110                         break;
01111         }
01112 
01113         if(content_type==WML_CONTENT){
01114                 /* used by cmd.cgi */
01115                 printf("</card>\n");
01116                 printf("</wml>\n");
01117                 return;
01118         }
01119 
01120         if(content_type==JSON_CONTENT){
01121                 printf("}\n}\n");
01122                 return;
01123         }
01124 
01125         /*
01126            top is embedded, so if this is top we don't want to return
01127            otherwise if embedded or HTML_CONTENT we do want to return
01128         */
01129         if((embedded || content_type!=HTML_CONTENT) && tac_header==FALSE)
01130                 return;
01131 
01132         if(cgi_id==STATUSWML_CGI_ID) {
01133                 printf("</wml>\n");
01134                 return;
01135         }
01136 
01137         if(cgi_id == STATUS_CGI_ID) {
01138                 /* Close the form */
01139                 printf("</form>\n");
01140         }
01141 
01142         /* include user SSI footer */
01143         include_ssi_files(cgi_name,SSI_FOOTER);
01144 
01145         printf("</body>\n");
01146         printf("</html>\n");
01147 
01148         return;
01149 }
01150 
01151 /* write JavaScript code an layer for popup window */
01152 void write_popup_code(int cgi_id){
01153         char *border_color="#000000";
01154         char *background_color="#ffffcc";
01155         int border=1;
01156         int padding=3;
01157         int x_offset=3;
01158         int y_offset=3;
01159 
01160         printf("<SCRIPT LANGUAGE='JavaScript'>\n");
01161         printf("<!--\n");
01162         printf("// JavaScript popup based on code originally found at http://www.helpmaster.com/htmlhelp/javascript/popjbpopup.htm\n");
01163         printf("function showPopup(text, eventObj){\n");
01164         printf("if(!document.all && document.getElementById)\n");
01165         printf("{ document.all=document.getElementsByTagName(\"*\")}\n");
01166         printf("ieLayer = 'document.all[\\'popup\\']';\n");
01167         printf("nnLayer = 'document.layers[\\'popup\\']';\n");
01168         printf("moLayer = 'document.getElementById(\\'popup\\')';\n");
01169 
01170         printf("if(!(document.all||document.layers||document.documentElement)) return;\n");
01171 
01172         printf("if(document.all) { document.popup=eval(ieLayer); }\n");
01173         printf("else {\n");
01174         printf("  if (document.documentElement) document.popup=eval(moLayer);\n");
01175         printf("  else document.popup=eval(nnLayer);\n");
01176         printf("}\n");
01177 
01178         printf("var table = \"\";\n");
01179 
01180         printf("if (document.all||document.documentElement){\n");
01181         printf("table += \"<table bgcolor='%s' border=%d cellpadding=%d cellspacing=0>\";\n",background_color,border,padding);
01182         printf("table += \"<tr><td>\";\n");
01183         printf("table += \"<table cellspacing=0 cellpadding=%d>\";\n",padding);
01184         printf("table += \"<tr><td bgcolor='%s' class='popupText'>\" + text + \"</td></tr>\";\n",background_color);
01185         printf("table += \"</table></td></tr></table>\"\n");
01186         printf("document.popup.innerHTML = table;\n");
01187         
01188         if (cgi_id==STATUSMAP_CGI_ID) {
01189                 printf("document.popup.style.left = document.body.scrollLeft + %d;\n",x_offset);
01190                 printf("document.popup.style.top = document.body.scrollTop + %d;\n",y_offset);
01191         } else if (cgi_id==TRENDS_CGI_ID){
01192                 printf("document.popup.style.left = (document.all ? eventObj.x : eventObj.layerX) + %d;\n",x_offset);
01193                 printf("document.popup.style.top  = (document.all ? eventObj.y : eventObj.layerY) + %d;\n",y_offset);
01194         }
01195 
01196         printf("document.popup.style.visibility = \"visible\";\n");
01197         printf("} \n");
01198 
01199 
01200         printf("else{\n");
01201         printf("table += \"<table cellpadding=%d border=%d cellspacing=0 bordercolor='%s'>\";\n",padding,border,border_color);
01202         printf("table += \"<tr><td bgcolor='%s' class='popupText'>\" + text + \"</td></tr></table>\";\n",background_color);
01203         printf("document.popup.document.open();\n");
01204         printf("document.popup.document.write(table);\n");
01205         printf("document.popup.document.close();\n");
01206 
01207         /* set x coordinate */
01208         printf("document.popup.left = eventObj.layerX + %d;\n",x_offset);
01209         
01210         /* make sure we don't overlap the right side of the screen */
01211         printf("if(document.popup.left + document.popup.document.width + %d > window.innerWidth) document.popup.left = window.innerWidth - document.popup.document.width - %d - 16;\n",x_offset,x_offset);
01212                 
01213         /* set y coordinate */
01214         printf("document.popup.top  = eventObj.layerY + %d;\n",y_offset);
01215         
01216         /* make sure we don't overlap the bottom edge of the screen */
01217         printf("if(document.popup.top + document.popup.document.height + %d > window.innerHeight) document.popup.top = window.innerHeight - document.popup.document.height - %d - 16;\n",y_offset,y_offset);
01218                 
01219         /* make the popup visible */
01220         printf("document.popup.visibility = \"visible\";\n");
01221         printf("}\n");
01222         printf("}\n");
01223 
01224         printf("function hidePopup(){ \n");
01225         printf("if (!(document.all || document.layers || document.documentElement)) return;\n");
01226         printf("if (document.popup == null){ }\n");
01227         printf("else if (document.all||document.documentElement) document.popup.style.visibility = \"hidden\";\n");
01228         printf("else document.popup.visibility = \"hidden\";\n");
01229         printf("document.popup = null;\n");
01230         printf("}\n");
01231         printf("//-->\n");
01232 
01233         printf("</SCRIPT>\n");
01234 
01235         return;
01236 }
01237 
01238 
01239 /**********************************************************
01240  *************** MISC UTILITY FUNCTIONS *******************
01241  **********************************************************/
01242 
01243 /* unescapes newlines in a string */
01244 char *unescape_newlines(char *rawbuf){
01245         register int x,y;
01246 
01247         for(x=0,y=0;rawbuf[x]!=(char)'\x0';x++){
01248 
01249                 if(rawbuf[x]=='\\'){
01250 
01251                         /* unescape newlines */
01252                         if(rawbuf[x+1]=='n'){
01253                                 rawbuf[y++]='\n';
01254                                 x++;
01255                                 }
01256 
01257                         /* unescape backslashes and other stuff */
01258                         if(rawbuf[x+1]!='\x0'){
01259                                 rawbuf[y++]=rawbuf[x+1];
01260                                 x++;
01261                                 }
01262 
01263                         }
01264                 else
01265                         rawbuf[y++]=rawbuf[x];
01266                 }
01267         rawbuf[y]='\x0';
01268 
01269         return rawbuf;
01270 }
01271 
01272 /* escapes newlines in a string */
01273 char *escape_newlines(char *rawbuf) {
01274         char *newbuf=NULL;
01275         register int x,y;
01276 
01277         if(rawbuf==NULL)
01278                 return NULL;
01279 
01280         /* allocate enough memory to escape all chars if necessary */
01281         if((newbuf=malloc((strlen(rawbuf)*2)+1))==NULL)
01282                 return NULL;
01283 
01284         for(x=0,y=0;rawbuf[x]!=(char)'\x0';x++){
01285 
01286                 /* escape backslashes */
01287                 if(rawbuf[x]=='\\'){
01288                         newbuf[y++]='\\';
01289                         newbuf[y++]='\\';
01290                         }
01291 
01292                 /* escape newlines */
01293                 else if(rawbuf[x]=='\n'){
01294                         newbuf[y++]='\\';
01295                         newbuf[y++]='n';
01296                         }
01297 
01298                 else
01299                         newbuf[y++]=rawbuf[x];
01300                 }
01301         newbuf[y]='\x0';
01302 
01303         return newbuf;
01304 }
01305 
01306 /* strips HTML and bad stuff from plugin output */
01307 void sanitize_plugin_output(char *buffer){
01308         int x=0;
01309         int y=0;
01310         int in_html=FALSE;
01311         char *new_buffer;
01312 
01313         if(buffer==NULL)
01314                 return;
01315 
01316         new_buffer=strdup(buffer);
01317         if(new_buffer==NULL)
01318                 return;
01319 
01320         /* check each character */
01321         for(x=0,y=0;buffer[x]!='\x0';x++){
01322 
01323                 /* we just started an HTML tag */
01324                 if(buffer[x]=='<'){
01325                         in_html=TRUE;
01326                         continue;
01327                         }
01328 
01329                 /* end of an HTML tag */
01330                 else if(buffer[x]=='>'){
01331                         in_html=FALSE;
01332                         continue;
01333                         }
01334 
01335                 /* skip everything inside HTML tags */
01336                 else if(in_html==TRUE)
01337                         continue;
01338 
01339                 /* strip single and double quotes */
01340                 else if(buffer[x]=='\'' || buffer[x]=='\"')
01341                         new_buffer[y++]=' ';
01342 
01343                 /* strip semicolons (replace with colons) */
01344                 else if(buffer[x]==';')
01345                         new_buffer[y++]=':';
01346 
01347                 /* strip pipe and ampersand */
01348                 else if(buffer[x]=='&' || buffer[x]=='|')
01349                         new_buffer[y++]=' ';
01350 
01351                 /* normal character */
01352                 else
01353                         new_buffer[y++]=buffer[x];
01354                 }
01355 
01356         /* terminate sanitized buffer */
01357         new_buffer[y++]='\x0';
01358 
01359         /* copy the sanitized buffer back to the original */
01360         strcpy(buffer,new_buffer);
01361 
01362         /* free memory allocated to the new buffer */
01363         free(new_buffer);
01364 
01365         return;
01366 }
01367 
01368 /* get date/time string */
01369 void get_time_string(time_t *raw_time,char *buffer,int buffer_length,int type){
01370         time_t t;
01371         struct tm *tm_ptr=NULL;
01372         int hour=0;
01373         int minute=0;
01374         int second=0;
01375         int month=0;
01376         int day=0;
01377         int year=0;
01378         char *weekdays[7]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
01379         char *months[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
01380         char *tzone="";
01381 
01382         if(raw_time==NULL)
01383                 time(&t);
01384         else
01385                 t=*raw_time;
01386 
01387         if(type==HTTP_DATE_TIME)
01388                 tm_ptr=gmtime(&t);
01389         else
01390                 tm_ptr=localtime(&t);
01391 
01392         hour=tm_ptr->tm_hour;
01393         minute=tm_ptr->tm_min;
01394         second=tm_ptr->tm_sec;
01395         month=tm_ptr->tm_mon+1;
01396         day=tm_ptr->tm_mday;
01397         year=tm_ptr->tm_year+1900;
01398 
01399 #ifdef HAVE_TM_ZONE
01400         tzone=(char *)tm_ptr->tm_zone;
01401 #else
01402         tzone=(tm_ptr->tm_isdst)?tzname[1]:tzname[0];
01403 #endif
01404 
01405         /* ctime() style */
01406         if(type==LONG_DATE_TIME)
01407                 snprintf(buffer,buffer_length,"%s %s %d %02d:%02d:%02d %s %d",weekdays[tm_ptr->tm_wday],months[tm_ptr->tm_mon],day,hour,minute,second,tzone,year);
01408 
01409         /* short style */
01410         else if(type==SHORT_DATE_TIME){
01411                 if(date_format==DATE_FORMAT_EURO)
01412                         snprintf(buffer,buffer_length,"%02d-%02d-%04d %02d:%02d:%02d",tm_ptr->tm_mday,tm_ptr->tm_mon+1,tm_ptr->tm_year+1900,tm_ptr->tm_hour,tm_ptr->tm_min,tm_ptr->tm_sec);
01413                 else if(date_format==DATE_FORMAT_ISO8601 || date_format==DATE_FORMAT_STRICT_ISO8601)
01414                         snprintf(buffer,buffer_length,"%04d-%02d-%02d%c%02d:%02d:%02d",tm_ptr->tm_year+1900,tm_ptr->tm_mon+1,tm_ptr->tm_mday,(date_format==DATE_FORMAT_STRICT_ISO8601)?'T':' ',tm_ptr->tm_hour,tm_ptr->tm_min,tm_ptr->tm_sec);
01415                 else
01416                         snprintf(buffer,buffer_length,"%02d-%02d-%04d %02d:%02d:%02d",tm_ptr->tm_mon+1,tm_ptr->tm_mday,tm_ptr->tm_year+1900,tm_ptr->tm_hour,tm_ptr->tm_min,tm_ptr->tm_sec);
01417                 }
01418 
01419         /* short date */
01420         else if(type==SHORT_DATE){
01421                 if(date_format==DATE_FORMAT_EURO)
01422                         snprintf(buffer,buffer_length,"%02d-%02d-%04d",day,month,year);
01423                 else if(date_format==DATE_FORMAT_ISO8601 || date_format==DATE_FORMAT_STRICT_ISO8601)
01424                         snprintf(buffer,buffer_length,"%04d-%02d-%02d",year,month,day);
01425                 else
01426                         snprintf(buffer,buffer_length,"%02d-%02d-%04d",month,day,year);
01427                 }
01428 
01429         /* expiration date/time for HTTP headers */
01430         else if(type==HTTP_DATE_TIME)
01431                 snprintf(buffer,buffer_length,"%s, %02d %s %d %02d:%02d:%02d GMT",weekdays[tm_ptr->tm_wday],day,months[tm_ptr->tm_mon],year,hour,minute,second);
01432 
01433         /* short time */
01434         else
01435                 snprintf(buffer,buffer_length,"%02d:%02d:%02d",hour,minute,second);
01436 
01437         buffer[buffer_length-1]='\x0';
01438 
01439         return;
01440 }
01441 
01442 /* get time string for an interval of time */
01443 void get_interval_time_string(double time_units,char *buffer,int buffer_length){
01444         unsigned long total_seconds;
01445         int hours=0;
01446         int minutes=0;
01447         int seconds=0;
01448 
01449         total_seconds=(unsigned long)(time_units*interval_length);
01450         hours=(int)total_seconds/3600;
01451         total_seconds%=3600;
01452         minutes=(int)total_seconds/60;
01453         total_seconds%=60;
01454         seconds=(int)total_seconds;
01455         snprintf(buffer,buffer_length,"%dh %dm %ds",hours,minutes,seconds);
01456         buffer[buffer_length-1]='\x0';
01457 
01458         return;
01459 }
01460 
01461 /* encodes a string in proper URL format */
01462 char * url_encode(char *input){
01463         int len,output_len;
01464         int x,y;
01465         char temp_expansion[4];
01466         static int i = 0;
01467         char* str = encoded_url_string[i];
01468 
01469         /* initialize return string */
01470         strcpy(str,"");
01471 
01472         if(input==NULL)
01473                 return str;
01474 
01475         len=(int)strlen(input);
01476         output_len=(int)sizeof(encoded_url_string[0]);
01477 
01478         str[0]='\x0';
01479 
01480         for(x=0,y=0;x<=len && y<output_len-1;x++){
01481 
01482                 /* end of string */
01483                 if((char)input[x]==(char)'\x0'){
01484                         str[y]='\x0';
01485                         break;
01486                         }
01487 
01488                 /* alpha-numeric characters and a few other characters don't get encoded */
01489                 else if(((char)input[x]>='0' && (char)input[x]<='9') || ((char)input[x]>='A' && (char)input[x]<='Z') || ((char)input[x]>=(char)'a' && (char)input[x]<=(char)'z') || (char)input[x]==(char)'.' || (char)input[x]==(char)'-' || (char)input[x]==(char)'_'){
01490                         str[y]=input[x];
01491                         y++;
01492                         }
01493 
01494                 /* high bit characters don't get encoded */
01495                 else if((unsigned char)input[x]>=0x7f){
01496                         str[y]=input[x];
01497                         y++;
01498                 }
01499 
01500                 /* spaces are pluses */
01501                 else if((char)input[x]==(char)' '){
01502                         str[y]='+';
01503                         y++;
01504                         }
01505 
01506                 /* anything else gets represented by its hex value */
01507                 else{
01508                         str[y]='\x0';
01509                         if((int)strlen(str)<(output_len-3)){
01510                                 sprintf(temp_expansion,"%%%02X",(unsigned int)input[x]);
01511                                 strcat(str,temp_expansion);
01512                                 y+=3;
01513                                 }
01514                         }
01515                 }
01516 
01517         str[sizeof(encoded_url_string[0])-1]='\x0';
01518 
01519         return str;
01520 }
01521 
01522 /* escapes a string used in HTML */
01523 char * html_encode(char *input, int escape_newlines){
01524         int len,output_len;
01525         int x,y;
01526         char temp_expansion[10];
01527 
01528         /* we need up to six times the space to do the conversion */
01529         len=(int)strlen(input);
01530         output_len=len*6;
01531         if((encoded_html_string=(char *)malloc(output_len+1))==NULL)
01532                 return "";
01533 
01534         strcpy(encoded_html_string,"");
01535 
01536         for(x=0,y=0;x<=len;x++){
01537 
01538                 /* end of string */
01539                 if((char)input[x]==(char)'\x0'){
01540                         encoded_html_string[y]='\x0';
01541                         break;
01542                 }
01543 
01544                 /* alpha-numeric characters and spaces don't get encoded */
01545                 else if(((char)input[x]==(char)' ') || ((char)input[x]>='0' && (char)input[x]<='9') || ((char)input[x]>='A' && (char)input[x]<='Z') || ((char)input[x]>=(char)'a' && (char)input[x]<=(char)'z'))
01546                         encoded_html_string[y++]=input[x];
01547 
01548                 /* newlines turn to <BR> tags */
01549                 else if(escape_newlines==TRUE && (char)input[x]==(char)'\n'){
01550                         strcpy(&encoded_html_string[y],"<BR>");
01551                         y+=4;
01552                         }
01553                 else if(escape_newlines==TRUE && (char)input[x]==(char)'\\' && (char)input[x+1]==(char)'n'){
01554                         strcpy(&encoded_html_string[y],"<BR>");
01555                         y+=4;
01556                         x++;
01557                         }
01558 
01559                 /* TODO - strip all but allowed HTML tags out... */
01560 
01561                 else if((char)input[x]==(char)'<'){
01562 
01563                         if(escape_html_tags==FALSE)
01564                                 encoded_html_string[y++]=input[x];
01565                         else{
01566                                 encoded_html_string[y]='\x0';
01567                                 if((int)strlen(encoded_html_string)<(output_len-4)){
01568                                         strcat(encoded_html_string,"&lt;");
01569                                         y+=4;
01570                                         }
01571                                 }
01572                         }
01573 
01574                 else if((char)input[x]==(char)'>'){
01575 
01576                         if(escape_html_tags==FALSE)
01577                                 encoded_html_string[y++]=input[x];
01578                         else{
01579                                 encoded_html_string[y]='\x0';
01580                                 if((int)strlen(encoded_html_string)<(output_len-4)){
01581                                         strcat(encoded_html_string,"&gt;");
01582                                         y+=4;
01583                                         }
01584                                 }
01585                         }
01586 
01587                 /* high bit chars don't get encoded, so we won't be breaking utf8 characters */
01588                 else if ((unsigned char)input[x] >= 0x7f)
01589                         encoded_html_string[y++]=input[x];
01590 
01591                 /* for simplicity, all other chars represented by their numeric value */
01592                 else{
01593                         if(escape_html_tags==FALSE)
01594                                 encoded_html_string[y++]=input[x];
01595                         else{
01596                                 encoded_html_string[y]='\x0';
01597                                 sprintf(temp_expansion,"&#%d;",(unsigned char)input[x]);
01598                                 if((int)strlen(encoded_html_string)<(output_len-strlen(temp_expansion))){
01599                                         strcat(encoded_html_string,temp_expansion);
01600                                         y+=strlen(temp_expansion);
01601                                         }
01602                                 }
01603                         }
01604                 }
01605 
01606         encoded_html_string[y++]='\x0';
01607 
01608         return encoded_html_string;
01609 }
01610 
01611 /* strip > and < from string */
01612 void strip_html_brackets(char *buffer){
01613         register int x;
01614         register int y;
01615         register int z;
01616 
01617         if(buffer==NULL || buffer[0]=='\x0')
01618                 return;
01619 
01620         /* remove all occurances in string */
01621         z=(int)strlen(buffer);
01622         for(x=0,y=0;x<z;x++){
01623                 if(buffer[x]=='<' || buffer[x]=='>')
01624                         continue;
01625                 buffer[y++]=buffer[x];
01626                 }
01627         buffer[y++]='\x0';
01628 
01629         return;
01630 }
01631 
01632 /* escape string for html form usage */
01633 char * escape_string(char *input){
01634         int len,output_len;
01635         int x,y;
01636         char temp_expansion[10];
01637 
01638         /* we need up to six times the space to do the conversion */
01639         len=(int)strlen(input);
01640         output_len=len*6;
01641         if((encoded_html_string=(char *)malloc(output_len+1))==NULL)
01642                 return "";
01643 
01644         strcpy(encoded_html_string,"");
01645 
01646         for(x=0,y=0;x<=len;x++){
01647 
01648                 /* end of string */
01649                 if((char)input[x]==(char)'\x0'){
01650                         encoded_html_string[y]='\x0';
01651                         break;
01652                         }
01653 
01654                 /* alpha-numeric characters don't get encoded */
01655                 else if(((char)input[x]>='0' && (char)input[x]<='9') || ((char)input[x]>='A' && (char)input[x]<='Z') || ((char)input[x]>=(char)'a' && (char)input[x]<=(char)'z'))
01656                         encoded_html_string[y++]=input[x];
01657 
01658                 /* spaces, hyphens, periods, underscores and colons don't get encoded */
01659                 else if(((char)input[x]==(char)' ') || ((char)input[x]==(char)'-') || ((char)input[x]==(char)'.') || ((char)input[x]==(char)'_') || ((char)input[x]==(char)':'))
01660                         encoded_html_string[y++]=input[x];
01661 
01662                 /* high bit characters don't get encoded */
01663                 else if((unsigned char)input[x]>=0x7f)
01664                         encoded_html_string[y++]=input[x];
01665 
01666                 /* for simplicity, all other chars represented by their numeric value */
01667                 else{
01668                         encoded_html_string[y]='\x0';
01669                         sprintf(temp_expansion,"&#%d;",(unsigned char)input[x]);
01670                         if((int)strlen(encoded_html_string)<(output_len-strlen(temp_expansion))){
01671                                 strcat(encoded_html_string,temp_expansion);
01672                                 y+=strlen(temp_expansion);
01673                                 }
01674                         }
01675                 }
01676 
01677         encoded_html_string[y++]='\x0';
01678 
01679         return encoded_html_string;
01680 }
01681 
01682 
01683 /**********************************************************
01684  *************** COMMON HTML FUNCTIONS ********************
01685  **********************************************************/
01686 
01687 void display_info_table(char *title,int refresh, authdata *current_authdata, int daemon_check){
01688         char date_time[MAX_DATETIME_LENGTH];
01689         char *dir_to_check=NULL;
01690         time_t current_time;
01691         int result;
01692         int x,last=0,dummy;
01693 
01694         /* read program status */
01695         result=read_all_status_data(get_cgi_config_location(),READ_PROGRAM_STATUS);
01696 
01697         printf("<TABLE CLASS='infoBox' BORDER=1 CELLSPACING=0 CELLPADDING=0>\n");
01698         printf("<TR><TD CLASS='infoBox'>\n");
01699         printf("<DIV CLASS='infoBoxTitle'>%s</DIV>\n",title);
01700 
01701         time(&current_time);
01702         get_time_string(&current_time,date_time,(int)sizeof(date_time),LONG_DATE_TIME);
01703 
01704         printf("Last Updated: %s<BR>\n",date_time);
01705 
01706         /* don't show in historical (long) listings */
01707         if(CGI_ID!=SHOWLOG_CGI_ID && CGI_ID!=TRENDS_CGI_ID && CGI_ID!=HISTOGRAM_CGI_ID && CGI_ID!=HISTORY_CGI_ID && CGI_ID!=AVAIL_CGI_ID){
01708                 /* decide if refresh is paused or not */
01709                 if(refresh==TRUE) {
01710                         /* if refresh, add paused query to url and set location.href */
01711                         printf("Updated every %d seconds <small>[<a href=\"javascript:window.location.href += ((window.location.toString().indexOf('?') != -1) ? '&' : '?') + 'paused'\">pause</a>]</small><br>\n",refresh_rate);
01712                 } else {
01713                         /* if no refresh, remove the paused query from url and set location.href */
01714                         printf("Update is paused <small>[<a href=\"javascript:window.location.href = window.location.href.replace(/[\?&]paused/,'')\">continue</a>]</small><br>\n");
01715                 }
01716         }
01717 
01718         printf("%s %s - <A HREF='http://www.icinga.org' TARGET='_new' CLASS='homepageURL'>www.icinga.org</A><BR>\n", PROGRAM_NAME, PROGRAM_VERSION);
01719 
01720         /* We shouldn't forget from where we come */
01721         printf("(Credits to: Nagios&reg; - <A HREF='http://www.nagios.org' TARGET='_new' CLASS='homepageURL'>www.nagios.org</A>)<BR>");
01722 
01723         if(current_authdata!=NULL)
01724                 printf("Logged in as <i>%s</i><BR>\n",(!strcmp(current_authdata->username,""))?"?":current_authdata->username);
01725 
01726         /* add here every cgi_id which uses logging, this should limit the testing of write access to the necessary amount */
01727         if(use_logging==TRUE && CGI_ID==CMD_CGI_ID) {
01728 
01729                 dummy=asprintf(&dir_to_check,"%s",cgi_log_file);
01730 
01731                 for(x=0;x<=(int)strlen(dir_to_check);x++){
01732                         /* end of string */
01733                         if((char)dir_to_check[x]==(char)'\x0'){
01734                                 break;
01735                         }
01736                         if ((char)dir_to_check[x]=='/')
01737                                 last=x;
01738                 }
01739                 dir_to_check[last]='\x0';
01740 
01741                 if(!strcmp(cgi_log_file,"")) {
01742                         printf("<DIV CLASS='infoBoxBadProcStatus'>Warning: Logging is activated but no logfile is configured</DIV>");
01743                 } else {
01744                         if (access(dir_to_check, W_OK) != 0)
01745                                 printf("<DIV CLASS='infoBoxBadProcStatus'>Warning: No permission to write logfile to %s</DIV>",dir_to_check);
01746                 }
01747                 if (cgi_log_rotation_method!=LOG_ROTATION_NONE) {
01748                         if(!strcmp(cgi_log_archive_path,""))
01749                                 printf("<DIV CLASS='infoBoxBadProcStatus'>Warning: Log rotation is configured but option \"cgi_log_archive_path\" isn't</DIV>");
01750                         else {
01751                                 if (access(cgi_log_archive_path, W_OK) != 0)
01752                                         printf("<DIV CLASS='infoBoxBadProcStatus'>Warning: No permission to write to \"cgi_log_archive_path\": %s</DIV>",cgi_log_archive_path);
01753                         }
01754                 }
01755                 free(dir_to_check);
01756         }
01757 
01758         if(nagios_process_state!=STATE_OK)
01759                 printf("<DIV CLASS='infoBoxBadProcStatus'>Warning: Monitoring process may not be running!<BR>Click <A HREF='%s?type=%d'>here</A> for more info.</DIV>",EXTINFO_CGI,DISPLAY_PROCESS_INFO);
01760 
01761         if(result==ERROR && daemon_check == TRUE)
01762                 printf("<DIV CLASS='infoBoxBadProcStatus'>Warning: Could not read program status information!</DIV>");
01763 
01764         else{
01765                 if(enable_notifications==FALSE)
01766                         printf("<DIV CLASS='infoBoxBadProcStatus'>- Notifications are disabled</DIV>");
01767 
01768                 if(execute_service_checks==FALSE)
01769                         printf("<DIV CLASS='infoBoxBadProcStatus'>- Service checks are disabled</DIV>");
01770         }
01771 
01772         printf("</TD></TR>\n");
01773         printf("</TABLE>\n");
01774 
01775         return;
01776 }
01777 
01778 void display_nav_table(char *url,int archive){
01779         char date_time[MAX_DATETIME_LENGTH];
01780         char archive_file[MAX_INPUT_BUFFER];
01781         char *archive_basename;
01782 
01783         if(log_rotation_method!=LOG_ROTATION_NONE){
01784                 printf("<table border=0 cellspacing=0 cellpadding=0 CLASS='navBox'>\n");
01785                 printf("<tr>\n");
01786                 printf("<td align=center valign=center CLASS='navBoxItem'>\n");
01787                 if(archive==0){
01788                         printf("Latest Archive<br>");
01789                         printf("<a href='%sarchive=1'><img src='%s%s' border=0 alt='Latest Archive' title='Latest Archive'></a>",url,url_images_path,LEFT_ARROW_ICON);
01790                         }
01791                 else{
01792                         printf("Earlier Archive<br>");
01793                         printf("<a href='%sarchive=%d'><img src='%s%s' border=0 alt='Earlier Archive' title='Earlier Archive'></a>",url,archive+1,url_images_path,LEFT_ARROW_ICON);
01794                         }
01795                 printf("</td>\n");
01796 
01797                 printf("<td width=15></td>\n");
01798 
01799                 printf("<td align=center CLASS='navBoxDate'>\n");
01800                 printf("<DIV CLASS='navBoxTitle'>Log File Navigation</DIV>\n");
01801                 get_time_string(&last_scheduled_log_rotation,date_time,(int)sizeof(date_time),LONG_DATE_TIME);
01802                 printf("%s",date_time);
01803                 printf("<br>to<br>");
01804                 if(archive==0)
01805                         printf("Present..");
01806                 else{
01807                         get_time_string(&this_scheduled_log_rotation,date_time,(int)sizeof(date_time),LONG_DATE_TIME);
01808                         printf("%s",date_time);
01809                         }
01810                 printf("</td>\n");
01811 
01812                 printf("<td width=15></td>\n");
01813                 if(archive!=0){
01814 
01815                         printf("<td align=center valign=center CLASS='navBoxItem'>\n");
01816                         if(archive==1){
01817                                 printf("Current Log<br>");
01818                                 printf("<a href='%s'><img src='%s%s' border=0 alt='Current Log' title='Current Log'></a>",url,url_images_path,RIGHT_ARROW_ICON);
01819                                 }
01820                         else{
01821                                 printf("More Recent Archive<br>");
01822                                 printf("<a href='%sarchive=%d'><img src='%s%s' border=0 alt='More Recent Archive' title='More Recent Archive'></a>",url,archive-1,url_images_path,RIGHT_ARROW_ICON);
01823                                 }
01824                         printf("</td>\n");
01825                         }
01826                 else
01827                         printf("<td><img src='%s%s' border=0 width=75 height=1></td>\n",url_images_path,EMPTY_ICON);
01828 
01829                 printf("</tr>\n");
01830 
01831                 printf("</table>\n");
01832                 }
01833 
01834         /* get archive to use */
01835         get_log_archive_to_use(archive,archive_file,sizeof(archive_file)-1);
01836 
01837         /* cut the pathname for security, and the remaining slash for clarity */
01838         archive_basename=(char *)&archive_file;
01839         if(strrchr((char *)&archive_basename,'/')!=NULL)
01840                 archive_basename=strrchr((char *)&archive_file,'/')+1;
01841 
01842         /* now it's safe to print the filename */
01843         printf("<BR><DIV CLASS='navBoxFile'>File: %s</DIV>\n",archive_basename);
01844 
01845         return;
01846 }
01847 
01848 /* prints the additional notes or action url for a hostgroup (with macros substituted) */
01849 void print_extra_hostgroup_url(char *group_name, char *url){
01850         char input_buffer[MAX_INPUT_BUFFER]="";
01851         char output_buffer[MAX_INPUT_BUFFER]="";
01852         char *temp_buffer;
01853         int in_macro=FALSE;
01854         hostgroup *temp_hostgroup=NULL;
01855 
01856         if(group_name==NULL || url==NULL)
01857                 return;
01858 
01859         temp_hostgroup=find_hostgroup(group_name);
01860         if(temp_hostgroup==NULL){
01861                 printf("%s",url);
01862                 return;
01863                 }
01864 
01865         strncpy(input_buffer,url,sizeof(input_buffer)-1);
01866         input_buffer[sizeof(input_buffer)-1]='\x0';
01867 
01868         for(temp_buffer=my_strtok(input_buffer,"$");temp_buffer!=NULL;temp_buffer=my_strtok(NULL,"$")){
01869 
01870                 if(in_macro==FALSE){
01871                         if(strlen(output_buffer)+strlen(temp_buffer)<sizeof(output_buffer)-1){
01872                                 strncat(output_buffer,temp_buffer,sizeof(output_buffer)-strlen(output_buffer)-1);
01873                                 output_buffer[sizeof(output_buffer)-1]='\x0';
01874                                 }
01875                         in_macro=TRUE;
01876                         }
01877                 else{
01878 
01879                         if(strlen(output_buffer)+strlen(temp_buffer) < sizeof(output_buffer)-1){
01880 
01881                                 if(!strcmp(temp_buffer,"HOSTGROUPNAME"))
01882                                         strncat(output_buffer,url_encode(temp_hostgroup->group_name),sizeof(output_buffer)-strlen(output_buffer)-1);
01883                                 }
01884 
01885                         in_macro=FALSE;
01886                         }
01887                 }
01888 
01889         printf("%s",output_buffer);
01890 
01891         return;
01892 }
01893 
01894 /* prints the additional notes or action url for a servicegroup (with macros substituted) */
01895 void print_extra_servicegroup_url(char *group_name, char *url){
01896         char input_buffer[MAX_INPUT_BUFFER]="";
01897         char output_buffer[MAX_INPUT_BUFFER]="";
01898         char *temp_buffer;
01899         int in_macro=FALSE;
01900         servicegroup *temp_servicegroup=NULL;
01901 
01902         if(group_name==NULL || url==NULL)
01903                 return;
01904 
01905         temp_servicegroup=find_servicegroup(group_name);
01906         if(temp_servicegroup==NULL){
01907                 printf("%s",url);
01908                 return;
01909                 }
01910 
01911         strncpy(input_buffer,url,sizeof(input_buffer)-1);
01912         input_buffer[sizeof(input_buffer)-1]='\x0';
01913 
01914         for(temp_buffer=my_strtok(input_buffer,"$");temp_buffer!=NULL;temp_buffer=my_strtok(NULL,"$")){
01915 
01916                 if(in_macro==FALSE){
01917                         if(strlen(output_buffer)+strlen(temp_buffer)<sizeof(output_buffer)-1){
01918                                 strncat(output_buffer,temp_buffer,sizeof(output_buffer)-strlen(output_buffer)-1);
01919                                 output_buffer[sizeof(output_buffer)-1]='\x0';
01920                                 }
01921                         in_macro=TRUE;
01922                         }
01923                 else{
01924 
01925                         if(strlen(output_buffer)+strlen(temp_buffer) < sizeof(output_buffer)-1){
01926 
01927                                 if(!strcmp(temp_buffer,"SERVICEGROUPNAME"))
01928                                         strncat(output_buffer,url_encode(temp_servicegroup->group_name),sizeof(output_buffer)-strlen(output_buffer)-1);
01929                                 }
01930 
01931                         in_macro=FALSE;
01932                         }
01933                 }
01934 
01935         printf("%s",output_buffer);
01936 
01937         return;
01938 }
01939 
01940 /* include user-defined SSI footers or headers */
01941 void include_ssi_files(char *cgi_name, int type){
01942         char common_ssi_file[MAX_INPUT_BUFFER];
01943         char cgi_ssi_file[MAX_INPUT_BUFFER];
01944         char raw_cgi_name[MAX_INPUT_BUFFER];
01945         char *stripped_cgi_name;
01946         int x;
01947 
01948         /* common header or footer */
01949         snprintf(common_ssi_file,sizeof(common_ssi_file)-1,"%scommon-%s.ssi",physical_ssi_path,(type==SSI_HEADER)?"header":"footer");
01950         common_ssi_file[sizeof(common_ssi_file)-1]='\x0';
01951 
01952         /* CGI-specific header or footer */
01953         strncpy(raw_cgi_name,cgi_name,sizeof(raw_cgi_name)-1);
01954         raw_cgi_name[sizeof(raw_cgi_name)-1]='\x0';
01955         stripped_cgi_name=strtok(raw_cgi_name,".");
01956         snprintf(cgi_ssi_file,sizeof(cgi_ssi_file)-1,"%s%s-%s.ssi",physical_ssi_path,(stripped_cgi_name==NULL)?"":stripped_cgi_name,(type==SSI_HEADER)?"header":"footer");
01957         cgi_ssi_file[sizeof(cgi_ssi_file)-1]='\x0';
01958         for(x=0;x<strlen(cgi_ssi_file);x++)
01959                 cgi_ssi_file[x]=tolower(cgi_ssi_file[x]);
01960 
01961         if(type==SSI_HEADER){
01962                 printf("\n<!-- Produced by %s (http://www.%s.org).\nCopyright (c) 1999-2009 Ethan Galstad (egalstad@nagios.org)\nCopyright (c) 2009-2011 Icinga Development Team -->\n", PROGRAM_NAME, PROGRAM_NAME_LC);
01963                 include_ssi_file(common_ssi_file);
01964                 include_ssi_file(cgi_ssi_file);
01965                 }
01966         else{
01967                 include_ssi_file(cgi_ssi_file);
01968                 include_ssi_file(common_ssi_file);
01969                 printf("\n<!-- Produced by %s (http://www.%s.org).\nCopyright (c) 1999-2009 Ethan Galstad (egalstad@nagios.org)\nCopyright (c) 2009-2011 Icinga Development Team -->\n", PROGRAM_NAME, PROGRAM_NAME_LC);
01970                 }
01971 
01972         return;
01973 }
01974 
01975 /* include user-defined SSI footer or header */
01976 void include_ssi_file(char *filename){
01977         char buffer[MAX_INPUT_BUFFER];
01978         FILE *fp;
01979         struct stat stat_result;
01980         int call_return;
01981 
01982         /* if file is executable, we want to run it rather than print it */
01983         call_return=stat(filename,&stat_result);
01984 
01985         /* file is executable */
01986         if(call_return==0 && (stat_result.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
01987 
01988                 /* must flush output stream first so that output
01989                    from script shows up in correct place. Other choice
01990                    is to open program under pipe and copy the data from
01991                    the program to our output stream.
01992                 */
01993                 fflush(stdout);
01994 
01995                 /* ignore return status from system call. */
01996                 call_return=system(filename);
01997 
01998                 return;
01999                 }
02000 
02001         /* an error occurred trying to stat() the file */
02002         else if(call_return!=0){
02003 
02004                 /* Handle error conditions. Assume that standard posix error codes and errno are available. If not, comment this section out. */
02005                 switch(errno){
02006                 case ENOTDIR: /* - A component of the path is not a directory. */
02007                 case ELOOP: /* Too many symbolic links encountered while traversing the path. */
02008                 case EFAULT: /* Bad address. */
02009                 case ENOMEM: /* Out of memory (i.e. kernel memory). */
02010                 case ENAMETOOLONG: /* File name too long. */
02011                         printf("<br /> A stat call returned %d while looking for the file %s.<br />", errno, filename);
02012                         return;
02013                 case EACCES: /* Permission denied. -- The file should be accessible by nagios. */
02014                         printf("<br /> A stat call returned a permissions error(%d) while looking for the file %s.<br />", errno, filename);
02015                         return;
02016                 case ENOENT: /* A component of the path file_name does not exist, or the path is an empty string. Just return if the file doesn't exist. */
02017                         return;
02018                 default:
02019                         return;
02020                         }
02021                 }
02022 
02023         fp=fopen(filename,"r");
02024         if(fp==NULL)
02025                 return;
02026 
02027         /* print all lines in the SSI file */
02028         while(fgets(buffer,(int)(sizeof(buffer)-1),fp)!=NULL)
02029                 printf("%s",buffer);
02030 
02031         fclose(fp);
02032 
02033         return;
02034 }
02035 
02036 /* displays an error if CGI config file could not be read */
02037 void cgi_config_file_error(char *config_file){
02038 
02039         printf("<H1>Whoops!</H1>\n");
02040 
02041         printf("<P><STRONG><FONT COLOR='RED'>Error: Could not open CGI config file '%s' for reading!</FONT></STRONG></P>\n",config_file);
02042 
02043         printf("<P>\n");
02044         printf("Here are some things you should check in order to resolve this error:\n");
02045         printf("</P>\n");
02046 
02047         printf("<P>\n");
02048         printf("<OL>\n");
02049 
02050         printf("<LI>Make sure you've installed a CGI config file in its proper location.  A sample CGI configuration file (named <b>cgi.cfg</b>) can be found in the <b>sample-config/</b> subdirectory of the %s source code distribution.\n", PROGRAM_NAME);
02051         printf("<LI>Make sure the user your web server is running as has permission to read the CGI config file.\n");
02052 
02053         printf("</OL>\n");
02054         printf("</P>\n");
02055 
02056         printf("<P>\n");
02057         printf("Make sure you read the documentation on installing and configuring %s thoroughly before continuing.  If everything else fails, try sending a message to one of the mailing lists.  More information can be found at <a href='http://www.icinga.org'>http://www.icinga.org</a>.\n", PROGRAM_NAME);
02058         printf("</P>\n");
02059 
02060         return;
02061 }
02062 
02063 /* displays an error if main config file could not be read */
02064 void main_config_file_error(char *config_file){
02065 
02066         printf("<H1>Whoops!</H1>\n");
02067 
02068         printf("<P><STRONG><FONT COLOR='RED'>Error: Could not open main config file '%s' for reading!</FONT></STRONG></P>\n",config_file);
02069 
02070         printf("<P>\n");
02071         printf("Here are some things you should check in order to resolve this error:\n");
02072         printf("</P>\n");
02073 
02074         printf("<P>\n");
02075         printf("<OL>\n");
02076 
02077         printf("<LI>Make sure you've installed a main config file in its proper location. A sample main configuration file (named <b>icinga.cfg</b>) can be found in the <b>sample-config/</b> subdirectory of the %s source code distribution.\n", PROGRAM_NAME);
02078         printf("<LI>Make sure the user your web server is running as has permission to read the main config file.\n");
02079 
02080         printf("</OL>\n");
02081         printf("</P>\n");
02082 
02083         printf("<P>\n");
02084         printf("Make sure you read the documentation on installing and configuring %s thoroughly before continuing.  If everything else fails, try sending a message to one of the mailing lists.  More information can be found at <a href='http://www.icinga.org'>http://www.icinga.org</a>.\n", PROGRAM_NAME);
02085         printf("</P>\n");
02086 
02087         return;
02088 }
02089 
02090 /* displays an error if object data could not be read */
02091 void object_data_error(void){
02092 
02093         printf("<H1>Whoops!</H1>\n");
02094 
02095         printf("<P><STRONG><FONT COLOR='RED'>Error: Could not read object configuration data!</FONT></STRONG></P>\n");
02096 
02097         printf("<P>\n");
02098         printf("Here are some things you should check in order to resolve this error:\n");
02099         printf("</P>\n");
02100 
02101         printf("<P>\n");
02102         printf("<OL>\n");
02103 
02104         printf("<LI>Verify configuration options using the <b>-v</b> command-line option to check for errors.\n");
02105         printf("<LI>Check the %s log file for messages relating to startup or status data errors.\n", PROGRAM_NAME);
02106 
02107         printf("</OL>\n");
02108         printf("</P>\n");
02109 
02110         printf("<P>\n");
02111         printf("Make sure you read the documentation on installing, configuring and running %s thoroughly before continuing.  If everything else fails, try sending a message to one of the mailing lists.  More information can be found at <a href='http://www.icinga.org'>http://www.icinga.org</a>.\n", PROGRAM_NAME);
02112         printf("</P>\n");
02113 
02114         return;
02115 }
02116 
02117 /* displays an error if status data could not be read */
02118 void status_data_error(void){
02119 
02120         printf("<H1>Whoops!</H1>\n");
02121 
02122         printf("<P><STRONG><FONT COLOR='RED'>Error: Could not read host and service status information!</FONT></STRONG></P>\n");
02123 
02124         printf("<P>\n");
02125         printf("It seems that %s is not running or has not yet finished the startup procedure and then creating the status data file. If %s is indeed not running, this is a normal error message.\n", PROGRAM_NAME, PROGRAM_NAME);
02126         printf("Please note that event broker modules and/or rdbms backends may slow down the overall (re)start and the cgis cannot retrieve any status information.");
02127         printf("</P>\n");
02128 
02129         printf("<P>\n");
02130         printf("Things to check in order to resolve this error include:\n");
02131         printf("</P>\n");
02132 
02133         printf("<P>\n");
02134         printf("<OL>\n");
02135 
02136         printf("<LI>Check the %s log file for messages relating to startup or status data errors.\n", PROGRAM_NAME);
02137         printf("<LI>Always verify configuration options using the <b>-v</b> command-line option before starting or restarting %s!\n", PROGRAM_NAME);
02138         printf("<LI>If using any event broker module for %s, look into their respective logs and/or on their behavior!\n", PROGRAM_NAME);
02139 
02140         printf("</OL>\n");
02141         printf("</P>\n");
02142 
02143         printf("<P>\n");
02144         printf("Make sure you read the documentation on installing, configuring and running %s thoroughly before continuing.  If everything else fails, try sending a message to one of the mailing lists.  More information can be found at <a href='http://www.icinga.org'>http://www.icinga.org</a>.\n", PROGRAM_NAME);
02145         printf("</P>\n");
02146 
02147         return;
02148 }
02149 
02151 void print_error(char *config_file, int error_type){
02152 
02153         /* if cgi.cfg is missing, we don't know which fancy style to use, take our own */
02154         if(error_type!=ERROR_CGI_CFG_FILE){
02155                 document_header(ERROR_CGI_ID,TRUE);
02156         }
02157 
02158          /* Giving credits to stop.png image source */
02159         printf("\n<!-- Image \"stop.png\" has been taken from \"http://fedoraproject.org/wiki/Template:Admon/caution\" -->\n\n");
02160 
02161         printf("<BR><DIV align='center'><DIV CLASS='errorBox'>\n");
02162         if(error_type==ERROR_CGI_CFG_FILE){
02163                 printf("<DIV style='font-family:  Helvetica, serif; background-color: #fff; color: #000; font-size: 8pt; text-align:left; font-weight: bold; margin:1em; border:1px red solid; background-color: #FFE5E5;' CLASS='errorMessage'><table cellspacing=0 cellpadding=0 border=0><tr><td width=55 valign=top></td>");
02164         } else {
02165                 printf("<DIV CLASS='errorMessage'><table cellspacing=0 cellpadding=0 border=0><tr><td width=55 valign=top><img src=\"%s%s\" border=0></td>",url_images_path,CMD_STOP_ICON);
02166         }
02167         printf("<td class='errorDescription'>");
02168 
02169         switch(error_type){
02170                 case ERROR_CGI_STATUS_DATA:
02171                         status_data_error();
02172                         break;
02173                 case ERROR_CGI_OBJECT_DATA:
02174                         object_data_error();
02175                         break;
02176                 case ERROR_CGI_CFG_FILE:
02177                         cgi_config_file_error(config_file);
02178                         break;
02179                 case ERROR_CGI_MAIN_CFG:
02180                         main_config_file_error(config_file);
02181                         break;
02182         }
02183 
02184         printf("</td></tr></table></DIV>\n");
02185         printf("</DIV>\n");
02186 
02187         return;
02188 }
02189 
02190 /* displays context-sensitive help window */
02191 void display_context_help(char *chid){
02192         char *icon=CONTEXT_HELP_ICON1;
02193 
02194         if(show_context_help==FALSE)
02195                 return;
02196 
02197         /* change icon if necessary */
02198         if(!strcmp(chid,CONTEXTHELP_TAC))
02199                 icon=CONTEXT_HELP_ICON2;
02200 
02201         printf("<a href='%s%s.html' target='cshw' onClick='javascript:window.open(\"%s%s.html\",\"cshw\",\"width=550,height=600,toolbar=0,location=0,status=0,resizable=1,scrollbars=1\");return true'><img src='%s%s' border=0 alt='Display context-sensitive help for this screen' title='Display context-sensitive help for this screen'></a>\n",url_context_help_path,chid,url_context_help_path,chid,url_images_path,icon);
02202 
02203         return;
02204 }
02205 
02206 void display_splunk_host_url(host *hst){
02207 
02208         if(enable_splunk_integration==FALSE)
02209                 return;
02210         if(hst==NULL)
02211                 return;
02212 
02213         printf("<a href='%s?q=search %s' target='_blank'><img src='%s%s' alt='Splunk It' title='Splunk It' border='0'></a>\n",splunk_url,url_encode(hst->name),url_images_path,SPLUNK_SMALL_WHITE_ICON);
02214 
02215         return;
02216 }
02217 
02218 void display_splunk_service_url(service *svc){
02219 
02220         if(enable_splunk_integration==FALSE)
02221                 return;
02222         if(svc==NULL)
02223                 return;
02224 
02225         printf("<a href='%s?q=search %s%%20",splunk_url,url_encode(svc->host_name));
02226         printf("%s' target='_blank'><img src='%s%s' alt='Splunk It' title='Splunk It' border='0'></a>\n",url_encode(svc->description),url_images_path,SPLUNK_SMALL_WHITE_ICON);
02227 
02228         return;
02229 }
02230 
02231 void display_splunk_generic_url(char *buf, int icon){
02232         char *newbuf=NULL;
02233 
02234         if(enable_splunk_integration==FALSE)
02235                 return;
02236         if(buf==NULL)
02237                 return;
02238 
02239         if((newbuf=(char *)strdup(buf))==NULL)
02240                 return;
02241 
02242         strip_splunk_query_terms(newbuf);
02243 
02244         printf("<a href='%s?q=search %s' target='_blank'>",splunk_url,url_encode(newbuf));
02245 
02246         if(icon>0)
02247                 printf("<img src='%s%s' alt='Splunk It' title='Splunk It' border='0'>",url_images_path,(icon==1)?SPLUNK_SMALL_WHITE_ICON:SPLUNK_SMALL_BLACK_ICON);
02248         printf("</a>\n");
02249 
02250         free(newbuf);
02251 
02252         return;
02253 }
02254 
02255 /* strip quotes and from string */
02256 void strip_splunk_query_terms(char *buffer){
02257         register int x;
02258         register int y;
02259         register int z;
02260 
02261         if(buffer==NULL || buffer[0]=='\x0')
02262                 return;
02263 
02264         /* remove all occurances in string */
02265         z=(int)strlen(buffer);
02266         for(x=0,y=0;x<z;x++){
02267                 if(buffer[x]=='\'' || buffer[x]=='\"' || buffer[x]==';' || buffer[x]==':' || buffer[x]==',' || buffer[x]=='-' || buffer[x]=='=')
02268                         buffer[y++]=' ';
02269                 else
02270                         buffer[y++]=buffer[x];
02271                 }
02272         buffer[y++]='\x0';
02273 
02274         return;
02275 }
02276 
02277 void print_generic_error_message(char *title, char *text, int returnlevels) {
02278 
02279         if(content_type==WML_CONTENT) {
02280                 printf("<p>");
02281 
02282                 if(title!=NULL && title[0]!='\x0')
02283                         printf("%s",title);
02284                 if(text!=NULL && text[0]!='\x0')
02285                         printf("<br>%s",text);
02286 
02287                 printf("</p>\n");
02288         } else if(content_type==CSV_CONTENT) {
02289                 if(title!=NULL && title[0]!='\x0')
02290                         printf("ERROR: %s\n",title);
02291                 if(text!=NULL && text[0]!='\x0')
02292                         printf("ERROR: %s\n",text);
02293         } else if(content_type==JSON_CONTENT) {
02294                 printf("\"error\": {\n\"title\": ");
02295                 if(title!=NULL && title[0]!='\x0')
02296                         printf("\"%s\",\n",title);
02297                 else
02298                         printf("null,\n");
02299                 printf("\"text\": ");
02300                 if(text!=NULL && text[0]!='\x0')
02301                         printf("\"%s\"\n}",text);
02302                 else
02303                         printf("null\n}");
02304         } else {
02305                 printf("<BR><DIV align='center'><DIV CLASS='errorBox'>\n");
02306                 printf("<DIV CLASS='errorMessage'><table cellspacing=0 cellpadding=0 border=0><tr><td width=55><img src=\"%s%s\" border=0></td>",url_images_path,CMD_STOP_ICON);
02307 
02308                 if(title!=NULL && title[0]!='\x0')
02309                         printf("<td CLASS='errorMessage'>%s</td></tr></table></DIV>\n",title);
02310 
02311                 if(text!=NULL && text[0]!='\x0')
02312                         printf("<DIV CLASS='errorDescription'>%s</DIV><br>",text);
02313 
02314                 printf("</DIV>\n");
02315 
02316                 if(returnlevels!=0)
02317                         printf("<BR><input type='submit' value='Get me out of here' onClick='window.history.go(-%d);' class='submitButton'>\n",returnlevels);
02318 
02319                 printf("</DIV>\n");
02320         }
02321 
02322         return;
02323 }
02324 
02325 /* function to make export csv link XSS save #1275 */
02326 char *get_export_csv_link(char *cgi) {
02327         char temp_buffer[MAX_INPUT_BUFFER]="";
02328         static char ret[MAX_INPUT_BUFFER]="";
02329 
02330         /* just do stuff if some options are requested */
02331         if(getenv("QUERY_STRING")!=NULL){
02332                 if(strcmp(getenv("QUERY_STRING"),"")) {
02333                         snprintf(temp_buffer,sizeof(temp_buffer)-1,"%s",getenv("QUERY_STRING"));
02334                         temp_buffer[sizeof(temp_buffer)-1]='\x0';
02335                         strip_html_brackets(temp_buffer);
02336                         snprintf(ret,sizeof(ret)-1,"%s?%s&csvoutput",cgi,temp_buffer);
02337                         ret[sizeof(ret)-1]='\x0';
02338                 } else
02339                         snprintf(ret,sizeof(ret)-1,"%s?csvoutput",cgi);
02340         } else
02341                 snprintf(ret,sizeof(ret)-1,"%s?csvoutput",cgi);
02342 
02343         ret[sizeof(ret)-1]='\x0';
02344 
02345         return ret;
02346 }
02347 
02352 int write_to_cgi_log(char *buffer) {
02353         FILE *fp;
02354         time_t log_time;
02355         int write_retries=10, i=0;
02356 
02357         /* we don't do anything if logging is deactivated or no logfile configured */
02358         if(use_logging==FALSE || !strcmp(cgi_log_file,""))
02359                 return OK;
02360 
02361         time(&log_time);
02362 
02363         // allways check if log file has to be rotated
02364         rotate_log_file();
02365 
02366         // open log file and try again if failed
02367         while((fp=fopen(cgi_log_file,"a+"))==NULL && i<write_retries) {
02368                 usleep(10);
02369                 i++;
02370         }
02371 
02372         if(i>=write_retries)
02373                 return ERROR;
02374 
02375         /* strip any newlines from the end of the buffer */
02376         strip(buffer);
02377 
02378         /* write the buffer to the log file */
02379         fprintf(fp,"[%lu] %s\n",log_time,buffer);
02380 
02381         fclose(fp);
02382 
02383         return OK;
02384 }
02385 
02386 /* rotates the cgi log file */
02387 int rotate_log_file(){
02388         char temp_buffer[MAX_INPUT_BUFFER]="";
02389         char method_string[16]="";
02390         char *log_archive=NULL;
02391         struct tm *ts;
02392         int rename_result=0;
02393         int stat_result=-1;
02394         struct stat log_file_stat;
02395         int dummy, sub=0, weekday;
02396         time_t current_time, rotate_ts;
02397 
02398         /* if there is no log arhive configured we don't do anything */
02399         if(!strcmp(cgi_log_archive_path,""))
02400                 return ERROR;
02401 
02402         /* get the current time */
02403         time(&current_time);
02404 
02405         ts=localtime(&current_time);
02406 
02407         ts->tm_sec=0;
02408         ts->tm_min=0;
02409         ts->tm_isdst=-1;
02410 
02411         weekday=ts->tm_wday;
02412         /* implement start of week (Sunday/Monday) as config option
02413         weekday=ts->tm_wday;
02414         weekday--;
02415         if (weekday==-1)
02416                 weekday=6;
02417         */
02418 
02419         if(cgi_log_rotation_method==LOG_ROTATION_NONE)
02420                 return OK;
02421         else if(cgi_log_rotation_method==LOG_ROTATION_HOURLY)
02422                 strcpy(method_string,"HOURLY");
02423         else if(cgi_log_rotation_method==LOG_ROTATION_DAILY) {
02424                 strcpy(method_string,"DAILY");
02425                 ts->tm_hour=0;
02426         }
02427         else if(cgi_log_rotation_method==LOG_ROTATION_WEEKLY) {
02428                 strcpy(method_string,"WEEKLY");
02429                 ts->tm_hour=0;
02430                 sub=(60*60*24*weekday);
02431         }
02432         else if(cgi_log_rotation_method==LOG_ROTATION_MONTHLY) {
02433                 strcpy(method_string,"MONTHLY");
02434                 ts->tm_hour=0;
02435                 ts->tm_mday=1;
02436         }
02437         else
02438                 return ERROR;
02439 
02440         // determine the timestamp for next rotation
02441         rotate_ts=(time_t)(mktime(ts)-sub);
02442 
02443         /* get stats of current log file */
02444         stat_result = stat(cgi_log_file, &log_file_stat);
02445 
02446         // timestamp for rotation hasn't passed. don't rotate log file
02447         if (rotate_ts<log_file_stat.st_atime)
02448                 return OK;
02449 
02450         // from here on file gets rotated.
02451 
02452         /* get the archived filename to use */
02453         dummy=asprintf(&log_archive,"%s/icinga-cgi-%02d-%02d-%d-%02d.log", cgi_log_archive_path, ts->tm_mon+1, ts->tm_mday, ts->tm_year+1900, ts->tm_hour);
02454 
02455         /* rotate the log file */
02456         rename_result=my_rename(cgi_log_file,log_archive);
02457 
02458         if(rename_result){
02459                 my_free(log_archive);
02460                 return ERROR;
02461         }
02462 
02463         /* record the log rotation after it has been done... */
02464         snprintf(temp_buffer,sizeof(temp_buffer)-1,"LOG ROTATION: %s\n",method_string);
02465         temp_buffer[sizeof(temp_buffer)-1]='\x0';
02466         write_to_cgi_log(temp_buffer);
02467 
02468         /* give a warning about use */
02469         write_to_cgi_log("This log is highly experimental and changes may occure without notice. Use at your own risk!!");
02470 
02471         if(stat_result==0){
02472                 chmod(cgi_log_file, log_file_stat.st_mode);
02473                 dummy=chown(cgi_log_file, log_file_stat.st_uid, log_file_stat.st_gid);
02474         }
02475 
02476         my_free(log_archive);
02477 
02478         return OK;
02479 }
02480 
02481 /* renames a file - works across filesystems (Mike Wiacek) */
02482 int my_rename(char *source, char *dest){
02483         int rename_result=0;
02484 
02485 
02486         /* make sure we have something */
02487         if(source==NULL || dest==NULL)
02488                 return -1;
02489 
02490         /* first see if we can rename file with standard function */
02491         rename_result=rename(source,dest);
02492 
02493         /* handle any errors... */
02494         if(rename_result==-1){
02495 
02496                 /* an error occurred because the source and dest files are on different filesystems */
02497                 if(errno==EXDEV){
02498 
02499                         /* try copying the file */
02500                         if(my_fcopy(source,dest)==ERROR){
02501                                 logit(NSLOG_RUNTIME_ERROR,TRUE,"Error: Unable to rename file '%s' to '%s': %s\n",source,dest,strerror(errno));
02502                                 return -1;
02503                         }
02504 
02505                         /* delete the original file */
02506                         unlink(source);
02507 
02508                         /* reset result since we successfully copied file */
02509                         rename_result=0;
02510                 }
02511 
02512                 /* some other error occurred */
02513                 else{
02514                         logit(NSLOG_RUNTIME_ERROR,TRUE,"Error: Unable to rename file '%s' to '%s': %s\n",source,dest,strerror(errno));
02515                         return rename_result;
02516                 }
02517         }
02518 
02519         return rename_result;
02520 }
02521 
02522 /* copies a file */
02523 int my_fcopy(char *source, char *dest){
02524         int dest_fd, result;
02525 
02526         /* make sure we have something */
02527         if(source==NULL || dest==NULL)
02528                 return ERROR;
02529 
02530         /* unlink destination file first (not doing so can cause problems on network file systems like CIFS) */
02531         unlink(dest);
02532 
02533         /* open destination file for writing */
02534         if((dest_fd=open(dest,O_WRONLY|O_TRUNC|O_CREAT|O_APPEND,0644)) < 0){
02535                 logit(NSLOG_RUNTIME_ERROR,TRUE,"Error: Unable to open file '%s' for writing: %s\n",dest,strerror(errno));
02536                 return ERROR;
02537         }
02538 
02539         result = my_fdcopy(source, dest, dest_fd);
02540         close(dest_fd);
02541         return result;
02542 }
02543 
02544 /*
02545  * copy a file from the path at source to the already opened
02546  * destination file dest.
02547  * This is handy when creating tempfiles with mkstemp()
02548  */
02549 int my_fdcopy(char *source, char *dest, int dest_fd){
02550         int source_fd, rd_result = 0, wr_result = 0;
02551         unsigned long tot_written = 0, tot_read = 0, buf_size = 0;
02552         struct stat st;
02553         char *buf;
02554 
02555         /* open source file for reading */
02556         if((source_fd=open(source,O_RDONLY,0644)) < 0){
02557                 logit(NSLOG_RUNTIME_ERROR,TRUE,"Error: Unable to open file '%s' for reading: %s\n",source,strerror(errno));
02558                 return ERROR;
02559         }
02560 
02561         /*
02562          * find out how large the source-file is so we can be sure
02563          * we've written all of it
02564          */
02565         if (fstat(source_fd, &st) < 0) {
02566                 logit(NSLOG_RUNTIME_ERROR,TRUE,"Error: Unable to stat source file '%s' for my_fcopy(): %s\n", source, strerror(errno));
02567                 close(source_fd);
02568                 return ERROR;
02569         }
02570 
02571         /*
02572          * If the file is huge, read it and write it in chunks.
02573          * This value (128K) is the result of "pick-one-at-random"
02574          * with some minimal testing and may not be optimal for all
02575          * hardware setups, but it should work ok for most. It's
02576          * faster than 1K buffers and 1M buffers, so change at your
02577          * own peril. Note that it's useful to make it fit in the L2
02578          * cache, so larger isn't necessarily better.
02579          */
02580         buf_size = st.st_size > 128 << 10 ? 128 << 10 : st.st_size;
02581         buf = malloc(buf_size);
02582         if (!buf) {
02583                 logit(NSLOG_RUNTIME_ERROR,TRUE,"Error: Unable to malloc(%lu) bytes: %s\n", buf_size, strerror(errno));
02584                 close(source_fd);
02585                 return ERROR;
02586         }
02587         /* most of the times, this loop will be gone through once */
02588         while (tot_written < st.st_size) {
02589                 int loop_wr = 0;
02590 
02591                 rd_result = read(source_fd, buf, buf_size);
02592                 if (rd_result < 0) {
02593                         if (errno == EAGAIN || errno == EINTR)
02594                                 continue;
02595                         logit(NSLOG_RUNTIME_ERROR,TRUE,"Error: my_fcopy() failed to read from '%s': %s\n", source, strerror(errno));
02596                         break;
02597                 }
02598                 tot_read += rd_result;
02599 
02600                 while (loop_wr < rd_result) {
02601                         wr_result = write(dest_fd, buf + loop_wr, rd_result - loop_wr);
02602 
02603                         if (wr_result < 0) {
02604                                 if (errno == EAGAIN || errno == EINTR)
02605                                         continue;
02606                                 logit(NSLOG_RUNTIME_ERROR,TRUE,"Error: my_fcopy() failed to write to '%s': %s\n", dest, strerror(errno));
02607                                 break;
02608                         }
02609                         loop_wr += wr_result;
02610                 }
02611                 if (wr_result < 0)
02612                         break;
02613                 tot_written += loop_wr;
02614         }
02615 
02616         /*
02617          * clean up irregardless of how things went. dest_fd comes from
02618          * our caller, so we mustn't close it.
02619          */
02620         close(source_fd);
02621         free(buf);
02622 
02623         if (rd_result < 0 || wr_result < 0) {
02624                 /* don't leave half-written files around */
02625                 unlink(dest);
02626                 return ERROR;
02627         }
02628 
02629         return OK;
02630 }
02631 
02632 /* Checks if the given time is in daylight time saving period */
02633 int is_dlst_time(time_t *time) {
02634         struct tm *bt = localtime(time);
02635         return bt->tm_isdst;
02636 }
02637 
02638 /* convert timeperiodes to timestamps */
02639 void convert_timeperiod_to_times(int type, time_t *ts_start, time_t *ts_end){
02640         time_t current_time;
02641         int weekday=0;
02642         struct tm *t;
02643 
02644         /* get the current time */
02645         time(&current_time);
02646 
02647         /* everything before start of unix time is invalid */
02648         if ((unsigned long int)ts_start>(unsigned long int)current_time)
02649                 *ts_start=0L;
02650 
02651         t=localtime(&current_time);
02652 
02653         t->tm_sec=0;
02654         t->tm_min=0;
02655         t->tm_hour=0;
02656         t->tm_isdst=-1;
02657 
02658         /* see if weeks starts on sunday or monday */
02659         weekday=t->tm_wday;
02660         if (week_starts_on_monday==TRUE) {
02661                 weekday--;
02662                 if (weekday==-1)
02663                         weekday=6;
02664         }
02665 
02666         switch(type){
02667                 case TIMEPERIOD_LAST24HOURS:
02668                         *ts_start=current_time-(60*60*24);
02669                         *ts_end=current_time;
02670                         break;
02671                 case TIMEPERIOD_TODAY:
02672                         *ts_start=mktime(t);
02673                         *ts_end=current_time;
02674                         break;
02675                 case TIMEPERIOD_SINGLE_DAY:
02676                         if (*ts_start==0L && *ts_end==0L) {
02677                                 *ts_start=mktime(t);
02678                                 *ts_end=current_time;
02679                         }
02680                         break;
02681                 case TIMEPERIOD_YESTERDAY:
02682                         *ts_start=(time_t)(mktime(t)-(60*60*24));
02683                         *ts_end=(time_t)mktime(t)-1;
02684                         break;
02685                 case TIMEPERIOD_THISWEEK:
02686                         *ts_start=(time_t)(mktime(t)-(60*60*24*weekday));
02687                         *ts_end=current_time;
02688                         break;
02689                 case TIMEPERIOD_LASTWEEK:
02690                         t->tm_wday--;
02691                         *ts_start=(time_t)(mktime(t)-(60*60*24*weekday)-(60*60*24*7));
02692                         *ts_end=(time_t)(mktime(t)-(60*60*24*weekday)-1);
02693                         break;
02694                 case TIMEPERIOD_THISMONTH:
02695                         t->tm_mday=1;
02696                         *ts_start=mktime(t);
02697                         *ts_end=current_time;
02698                         break;
02699                 case TIMEPERIOD_LASTMONTH:
02700                         t->tm_mday=1;
02701                         *ts_end=mktime(t)-1;
02702                         if(t->tm_mon==0){
02703                                 t->tm_mon=11;
02704                                 t->tm_year--;
02705                         } else
02706                                 t->tm_mon--;
02707                         *ts_start=mktime(t);
02708                         break;
02709                 case TIMEPERIOD_THISYEAR:
02710                         t->tm_mon=0;
02711                         t->tm_mday=1;
02712                         *ts_start=mktime(t);
02713                         *ts_end=current_time;
02714                         break;
02715                 case TIMEPERIOD_LASTYEAR:
02716                         t->tm_mon=0;
02717                         t->tm_mday=1;
02718                         *ts_end=mktime(t)-1;
02719                         t->tm_year--;
02720                         *ts_start=mktime(t);
02721                         break;
02722                 case TIMEPERIOD_LAST7DAYS:
02723                         *ts_start=(time_t)(mktime(t)-(60*60*24*7));
02724                         *ts_end=current_time;
02725                         break;
02726                 case TIMEPERIOD_LAST31DAYS:
02727                         *ts_start=(time_t)(mktime(t)-(60*60*24*31));
02728                         *ts_end=current_time;
02729                         break;
02730                 case TIMEPERIOD_THISQUARTER:
02731                         /* not implemented */
02732                         break;
02733                 case TIMEPERIOD_LASTQUARTER:
02734                         /* not implemented */
02735                         break;
02736                 case TIMEPERIOD_NEXTPROBLEM:
02737                         /* Time period will be defined later */
02738                         /* only used in trends.cgi */
02739                         break;
02740                 default:
02741                         break;
02742         }
02743 
02744         /* check if interval is across dlst change and adjust timestamps with compensation */
02745         if (is_dlst_time(ts_start) != is_dlst_time(ts_end)) {
02746                 t=localtime(&current_time);
02747                 /* in DST */
02748                 if (t->tm_isdst==1) {
02749                         /* if end is also in DST */
02750                         if (is_dlst_time(ts_end)==1)
02751                                 *ts_start=*ts_start+3600;
02752                 } else {
02753                         if (is_dlst_time(ts_end)==0)
02754                                 *ts_start=*ts_start-3600;
02755                 }
02756 
02757         }
02758 
02759         return;
02760 }
02761 
02762 /* converts a time string to a UNIX timestamp, respecting the date_format option */
02763 int string_to_time(char *buffer, time_t *t){
02764         struct tm lt;
02765         int ret=0;
02766 
02767         /* Initialize some variables just in case they don't get parsed
02768            by the sscanf() call.  A better solution is to also check the
02769            CGI input for validity, but this should suffice to prevent
02770            strange problems if the input is not valid.
02771            Jan 15 2003  Steve Bonds */
02772         lt.tm_mon=0;
02773         lt.tm_mday=1;
02774         lt.tm_year=1900;
02775         lt.tm_hour=0;
02776         lt.tm_min=0;
02777         lt.tm_sec=0;
02778         lt.tm_wday=0;
02779         lt.tm_yday=0;
02780 
02781 
02782         if(date_format==DATE_FORMAT_EURO)
02783                 ret=sscanf(buffer,"%02d-%02d-%04d %02d:%02d:%02d",&lt.tm_mday,&lt.tm_mon,&lt.tm_year,&lt.tm_hour,&lt.tm_min,&lt.tm_sec);
02784         else if(date_format==DATE_FORMAT_ISO8601 || date_format==DATE_FORMAT_STRICT_ISO8601)
02785                 ret=sscanf(buffer,"%04d-%02d-%02d%*[ T]%02d:%02d:%02d",&lt.tm_year,&lt.tm_mon,&lt.tm_mday,&lt.tm_hour,&lt.tm_min,&lt.tm_sec);
02786         else
02787                 ret=sscanf(buffer,"%02d-%02d-%04d %02d:%02d:%02d",&lt.tm_mon,&lt.tm_mday,&lt.tm_year,&lt.tm_hour,&lt.tm_min,&lt.tm_sec);
02788 
02789         if (ret!=6)
02790                 return ERROR;
02791 
02792         lt.tm_mon--;
02793         lt.tm_year-=1900;
02794 
02795         /* tell mktime() to try and compute DST automatically */
02796         lt.tm_isdst=-1;
02797 
02798         *t=mktime(&lt);
02799 
02800         return OK;
02801 }
02802 
02803 char *json_encode(char *input) {
02804         char *encoded_string;
02805         int len=0;
02806         int i,j;
02807 
02808         /* we need up to twice the space to do the conversion */
02809         len=(int)strlen(input);
02810         if((encoded_string=(char *)malloc(len*2+1))==NULL)
02811                 return "";
02812         
02813         for(i=0,j=0;i<len;i++) {
02814         
02815                 if((char)input[i]==(char)'"') {
02816                         encoded_string[j++]='\\';
02817                         encoded_string[j++]=input[i];
02818                 }else
02819                         encoded_string[j++]=input[i];
02820         }
02821 
02822         encoded_string[j]='\x0';
02823 
02824         return encoded_string;
02825 }
 All Data Structures Files Functions Variables Typedefs Defines