コード例 #1
0
ファイル: neo_cgi.c プロジェクト: HermannDppes/clearsilver
static PyObject * p_cgi_error (PyObject *self, PyObject *args)
{
  CGI *cgi = ((CGIObject *) self)->cgi;
  char *s;
  PyObject *rv;

  if (!PyArg_ParseTuple(args, "s:error(str)", &s))
    return NULL;

  cgi_error (cgi, "%s", s);
  rv = Py_None;
  Py_INCREF(rv);
  return rv;
}
コード例 #2
0
ファイル: ext_param.cpp プロジェクト: dblock/agnes
void ext_param::traverse_cline_internal(cgiOutStream& CGIStream, const CString& arg){
	if (arg == "equiv") output_current_equivs(CGIStream);
	else if (arg == "nocache") entry_manager::set_value("CACHED", "0");
	else if (arg == "admin") output_current_admins(CGIStream);
	else if (arg.StartsWith("access")) {
		CString passwd = arg.Copy(strlen("access"), arg.StrLength());
		if (check_root_access(passwd)) cgi_error(CGIStream, "access denied");
		output_current_access(CGIStream);
	} else if (arg == "version") {
		CGIStream << "(" << __DATE__ ") Daniel Doubrovkine - University of Geneva" << elf;
		CGIStream << "&copy; Vestris Inc. - 1994-1998 - All Rights Reserved" << elf;
	}
	else if (arg == "environ") {
#ifdef ANSI
		extern char **environ;
		char ** _environ = environ;
#endif
		int i=0; while (_environ[i]) CGIStream << _environ[i++]<<elf;
	}
}
コード例 #3
0
ファイル: useradm.c プロジェクト: osvaldsson/xymon
int parse_query(void)
{
	cgidata_t *cgidata, *cwalk;
	int returnval = ACT_NONE;

	cgidata = cgi_request();
	if (cgi_method != CGI_POST) return ACT_NONE;

	if (cgidata == NULL) errormsg(cgi_error());

	cwalk = cgidata;
	while (cwalk) {
		/*
		 * cwalk->name points to the name of the setting.
		 * cwalk->value points to the value (may be an empty string).
		 */

		if (strcmp(cwalk->name, "USERNAME") == 0) {
			adduser_name = cwalk->value;
		}
		else if (strcmp(cwalk->name, "PASSWORD") == 0) {
			adduser_password = cwalk->value;
		}
		else if (strcmp(cwalk->name, "USERLIST") == 0) {
			deluser_name = cwalk->value;
		}
		else if (strcmp(cwalk->name, "SendCreate") == 0) {
			returnval = ACT_CREATE;
		}
		else if (strcmp(cwalk->name, "SendDelete") == 0) {
			returnval = ACT_DELETE;
		}

		cwalk = cwalk->next;
	}

	return returnval;
}
コード例 #4
0
ファイル: ip-toplast.c プロジェクト: fm4dd/edacs
int cgiMain() {
#ifdef MYSQL_DB
  static MYSQL *dbh;              /* database connect handle */
  static MYSQL_RES *result;       /* database query results  */
  static MYSQL_ROW values;        /* query data returned     */
  unsigned int colcount    =0;    /* number of returned columns */
  int server_version;             /* returned server version */
#endif
#ifdef ORACLE_DB
  sqlo_db_handle_t dbh;           /* database handle */
  sqlo_stmt_handle_t sth1;        /* statement handle 1 */
  char server_version[1024]="";   /* string for returned server version */
  int stat                 =0;    /* status of sqlo calls */
  int handle               =0;    /* handle of the interrupt handler */
  //const char ** colnames;         /* column names */
  const char ** values;           /* values */
#endif
  char sqlquery_str[1024]  ="";   /* SQL query string */
  int allrows              =0;    /* number of returned rows */
  int rowcount             =0;    /* row iteration counter */
  div_t oddline_calc;             /* calculates even/odd row color */
  int top_count            =0;    /* how many top ip to display */
  char start_date[11]      ="";   /* selected start date */
  char start_time[6]       ="";   /* selected start time */
  char end_date[11]        ="";   /* selected end date */
  char end_time[6]         ="";   /* selected end time */
  char order_by[13]        ="";   /* sort list by column */
  char sort_order[5]       ="";   /* ascending or descending */
  char **form_data;               /* string array for query data */
  char title[256]          = "";  /* cgi title string */
  struct tm *tm_ptr;              /* containing time structure */
  time_t now, old;                /* containing timestamp */
  char err_str[2048]       = "";  /* use for combined error string */
  int period               = 0;   /* the period to display */
  char dataunit[255] = "0 Bytes"; /* holds the calculated KB/MB */

  _abort_flag     = 0;
#ifdef ORACLE_DB
  /* ------------------------------------------------------------------- * 
   * ORACLE_HOME is needed for OCI8 to find tnsnames.ora                 *
   * ------------------------------------------------------------------- */
  putenv(WEB_ORACLE_ENV);

  /* initialize the connection */
  if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100))
    cgi_error("Error: Failed to init libsqlora8.");

  /* register the interrupt handler */
  sqlo_register_int_handler(&handle, sigint_handler);

  /* login to the database */
  if (SQLO_SUCCESS != sqlo_connect(&dbh, WEB_TNS_STRING))
    cgi_error("Error: Cannot connect to database.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  if (SQLO_SUCCESS != sqlo_server_version(dbh, server_version,
                                        sizeof(server_version)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* enable autocommit, each statement is commited as a single transaction */
  stat = sqlo_set_autocommit(dbh, 1);
#endif
#ifdef MYSQL_DB
  /* initialize the connection */
  dbh = mysql_init(NULL);
  if(dbh == NULL) cgi_error("Error:  Failed to init MySQL DB.");

  /* login to the database */
  if (mysql_real_connect(dbh, MYSQLIP, EDACSADMIN, ADMIN_PASS, DB_NAME, DB_PORT, NULL, 0) == 0)
    cgi_error("Error: Cannot connect to database.");

  /* Get the database version */
  server_version = mysql_get_server_version(dbh);
#endif

  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    cgi_error("Error: Could not retrieve form data.");

  if(form_data[0] == NULL) {
    /* ------------------------------------------------------------------- * 
     * Start the HTML output to display the query selection                *
     * ------------------------------------------------------------------- */
    /* define the CGI title */
    snprintf(title, sizeof(title), "Top IP Address Session Activity");
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");

    fprintf(cgiOut, "<form action=\"ip-toplast.cgi\" method=\"get\">\n");
    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    /* 1st row, display headers */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">Number of IP</th>");
    fprintf(cgiOut, "<th class=\"inner\">Time Frame</th>");
    fprintf(cgiOut, "<th class=\"inner\">Top by</th>");
    fprintf(cgiOut, "<th class=\"inner\">Sort Order</th>");
    fprintf(cgiOut, "</tr>\n");
    /* 2nd row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"24\" checked name=\"start\">Last Day</td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 3rd row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"168\" name=\"start\">Last Week</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"desc\" checked name=\"sort_order\">");
    fprintf(cgiOut, "Top</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 4th row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><select name=\"top_count\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"5\">Top 5 IP</option>");
    fprintf(cgiOut, "<option selected value=\"10\">Top 10 IP</option>");
    fprintf(cgiOut, "<option value=\"20\">Top 20 IP</option>");
    fprintf(cgiOut, "<option value=\"50\">Top 50 IP</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio value=\"720\" name=\"start\">Last Month</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><select name=\"order_by\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"elapsed_mins\">Elapsed Time</option>");
    fprintf(cgiOut, "<option value=\"bytes_in\">Bytes In</option>");
    fprintf(cgiOut, "<option selected value=\"bytes_out\">Bytes Out</option>");
    fprintf(cgiOut, "<option value=\"packets_in\">Packets In</option>");
    fprintf(cgiOut, "<option value=\"packets_out\">Packets Out</option>");
    fprintf(cgiOut, "<option value=\"sessions\">Session Count</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner\"><input type=radio name=\"sort_order\" value=\"asc\">Bottom</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 5th row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"2160\" name=\"start\">Last 3 Months</td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 6th and last row, close the frame */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=4><input type=submit value=\"Run Query\"></td>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");

    fprintf(cgiOut, "<h3>Additional Information</h3>\n");
    fprintf(cgiOut, "<hr>\n");
    fprintf(cgiOut, "<p>\n");
    fprintf(cgiOut, "This query returns a list of top IP addresses of the \"Order By\" selection for the last time period choosen.");
    fprintf(cgiOut, " It will give you a quick view who is possibly missusing the service, i.e. transferring large amounts of data in or out.");
    fprintf(cgiOut, "<ul>");
    fprintf(cgiOut, "<li>Select the number of top IP to display (5, 10, 20, 50) from the drop down list.");
    fprintf(cgiOut, "<li>The time frame can be selected from the radio menu, time is counting back from now.");
    fprintf(cgiOut, "<li>The results list is grouped by the \"Order By\" list, and sorted \"Top\" down or \"Bottom\" up.");
    fprintf(cgiOut, "</ul>");
    fprintf(cgiOut, "</p>\n");
  } /* end if for displaying the query request */
  else {
  /* ------------------------------------------------------------------- *
   * check if we got all information to make the SQL query               *
   * --------------------------------------------------------------------*/
    if ( cgiFormIntegerBounded("top_count", &top_count, 1, 50, 10) 
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving IP top count.");
  
    if ( cgiFormIntegerBounded("start", &period, 1, 2160, 24) 
                                                     != cgiFormSuccess ) 
      cgi_error("Error retrieving start period information.");
  
    if ( cgiFormString("order_by", order_by, sizeof(order_by))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving order_by information.");
  
    if ( cgiFormString("sort_order", sort_order, sizeof(sort_order))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving sort_order information.");
  
    /* ------------------------------------------------------------------- * 
     * The calculate query start and end time from given period in hours   *
     * ------------------------------------------------------------------- */
    now = time(NULL);
    tm_ptr = localtime(&now);
    strftime(end_date, sizeof(end_date), "%d.%m.%Y", (tm_ptr));
    strftime(end_time, sizeof(end_time), "%H:%M", tm_ptr);
    old = time(NULL) - (period * 3600);
    tm_ptr = localtime(&old);
    strftime(start_date, sizeof(start_date), "%d.%m.%Y", tm_ptr);
    strftime(start_time, sizeof(start_time), "%H:%M", tm_ptr);
  
    /* ------------------------------------------------------------------- *
     * check we got all parts and can start doing the SQL query below      *
     * --------------------------------------------------------------------*/
#ifdef ORACLE_DB
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT IP_ADDR, TO_CHAR(SUM(BYTES_IN), '999,999,999,999') BYTES_IN, TO_CHAR(SUM(BYTES_OUT), '999,999,999,999') BYTES_OUT, TO_CHAR(SUM(PACKETS_IN), '999,999,999,999') PACKETS_IN, TO_CHAR(SUM(PACKETS_OUT), '999,999,999,999') PACKETS_OUT, TO_CHAR(SUM(ELAPSED_MINS), '99,999.99') ELAPSED_MINS, COUNT (IP_ADDR) AS SESSIONS FROM %s.V_EDACS WHERE BYTES_IN IS NOT NULL AND START_DATE BETWEEN TO_DATE('%s %s', 'dd.mm.yyyy hh24:mi') and TO_DATE ('%s %s', 'dd.mm.yyyy hh24:mi') GROUP BY IP_ADDR ORDER BY %s %s",
           EDACSADMIN, start_date, start_time, end_date,
           end_time, order_by, sort_order);

    /* initialize the statement handle */
    sth1 = SQLO_STH_INIT;
  
    /* opens a cursor for the query statement */
    if ( 0 > (sqlo_open2(&sth1, dbh, sqlquery_str, 0, NULL))) {
      if(DEBUG == 0) cgi_error(sqlo_geterror(dbh));
      else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
               sqlo_geterror(dbh), sqlquery_str);
      cgi_error(err_str);
    }
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
  
    /* get the output column names */
    //if (SQLO_SUCCESS != sqlo_ocol_names2(sth1, &colcount, &colnames))
    //  cgi_error("Error getting the DB columns with sqlo_ocol_names2()");
    // RETURN_ON_ABORT; /* finish if SIGINT was catched */
  #endif
#ifdef MYSQL_DB
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT ip_addr, SUM(bytes_in) bytes_in, SUM(BYTES_OUT) bytes_out, TRUNCATE((bytes_in+bytes_out)/SUM(TIME_TO_SEC(elapsed_mins)),2) throughput, FORMAT(SUM(packets_in), 0) packets_in, FORMAT(SUM(packets_out), 0) packet_out, SEC_TO_TIME(SUM(TIME_TO_SEC(elapsed_mins))) elapsed_mins, COUNT(ip_addr) AS SESSIONS FROM v_edacs WHERE bytes_in IS NOT NULL AND start_date BETWEEN STR_TO_DATE('%s %s', '%s') and STR_TO_DATE('%s %s', '%s') GROUP BY ip_addr ORDER BY %s %s",
           start_date, start_time, "%d.%m.%Y %H:%i",
           end_date, end_time, "%d.%m.%Y %H:%i",
           order_by, sort_order);

  /* Prepare and execute the SQL statement */
  if(mysql_query(dbh, sqlquery_str) != 0) {
    if(DEBUG == 0) cgi_error(mysql_error(dbh));
    else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
             mysql_error(dbh), sqlquery_str);
    cgi_error(err_str);
  }
 /* get query results set */
  result = mysql_store_result(dbh);
  if (result == NULL) {
    snprintf(err_str, sizeof(err_str), "No results for query: %s\n", sqlquery_str);
    cgi_error( err_str);
  }

  allrows = mysql_num_rows(result);
  colcount = mysql_num_fields(result);
#endif

  /* ------------------------------------------------------------------------ *
   * start the html output                                                    *
   * -------------------------------------------------------------------------*/
    snprintf(title, sizeof(title), "Top %d IP Address Activity by %s", top_count, order_by);
  
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");
    fprintf(cgiOut, "<p>\n");
    fprintf(cgiOut, "<b>Top:</b> %d <b>Selection:</b> %s <b>Timeperiod:</b> %s %s - %s %s <b>Data Records:</b> %d",
               top_count, order_by, start_date, start_time, end_date, end_time, allrows);
    fprintf(cgiOut, "</p>\n");

    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">#</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">IP Address</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Data In</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Data Out</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Throughput</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Packets In</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Packets Out</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Elapsed Time</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Sessions</th>\n");
    fprintf(cgiOut, "</tr>\n");
  
    /* fetch the data */
#ifdef ORACLE_DB
    while ( SQLO_SUCCESS == (stat = (sqlo_fetch(sth1, 1)))) {
       /* get one record */
       values = sqlo_values(sth1, NULL, 1);
#endif
#ifdef MYSQL_DB
     while((values = mysql_fetch_row(result)) != NULL) {
#endif
     rowcount++;

     /* check for even/odd rows */
     oddline_calc = div(rowcount, 2);
     if(oddline_calc.rem) fprintf(cgiOut, "<tr class=\"odd\">\n");
     else fprintf(cgiOut, "<tr class=\"even\">\n");

     fprintf(cgiOut, "<td>%d</td>\n", rowcount);
     fprintf(cgiOut, "<td>");
     fprintf(cgiOut, "<a href=ip-actlast.cgi?start=%d&sort_order=%s&ipaddr=%s&order_by=start_date>",
                         period, sort_order, values[0]);
     fprintf(cgiOut, "%s</a></td>", values[0]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", calc_units(values[1], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s</td>", calc_units(values[2], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s/s</td>", calc_units(values[3], dataunit));
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[4]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[5]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[6]);
     fprintf(cgiOut, "<td class=\"right\">%s</td>", values[7]);
     fprintf(cgiOut, "</tr>\n");

       if ( rowcount == top_count) break;
     } /* end while row */
#ifdef ORACLE_DB
    if (SQLO_SUCCESS != sqlo_close(sth1))
      cgi_error("Error Closing the SQL statment handle.");
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
   mysql_close(dbh);
#endif

     /* ----------------------------------------------------------------- *
      * IF there was no data for the selection, display a notification    *
      * ----------------------------------------------------------------- */
    if(rowcount == 0) {
      fprintf(cgiOut, "<tr>\n");
      fprintf(cgiOut, "<td colspan=9>");
      fprintf(cgiOut, "No data found for top %d IP by %s between %s %s and %s %s.",
              top_count, order_by, start_date, start_time, end_date, end_time);
      fprintf(cgiOut, "</td>\n");
      fprintf(cgiOut, "</tr>\n");
    } /* end if rowcount is zero */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=9>");
    fprintf(cgiOut, "&nbsp;");
    fprintf(cgiOut, "</th>\n");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
  } /* end else we were called with form data */

  pageside();
  pagefoot();
  return(0);
}
コード例 #5
0
ファイル: router-acttime.c プロジェクト: fm4dd/edacs
int cgiMain() {
#ifdef MYSQL_DB
  static MYSQL *dbh;              /* database connect handle */
  static MYSQL_RES *result;       /* database query results  */
  static MYSQL_ROW values;        /* query data returned     */
  unsigned int colcount    =0;    /* number of returned columns */
  int server_version;             /* returned server version */
#endif
#ifdef ORACLE_DB
  sqlo_db_handle_t dbh;           /* database handle */
  sqlo_stmt_handle_t sth1;        /* statement handle 1 */
  char server_version[1024]="";   /* string for returned server version */
  int stat                 =0;    /* status of sqlo calls */
  int handle               =0;    /* handle of the interrupt handler */
  const char ** values;           /* values */
#endif

  char sqlquery_str[1024]  ="";   /* SQL query string */
  int allrows              =0;    /* number of returned rows */
  int rowcount             =0;    /* row iteration counter */
  div_t oddline_calc;             /* calculates even/odd row color */
  char router[41]          ="";   /* selected router IP */
  char start_date[11]      ="";   /* selected start date */
  char start_time[6]       ="";   /* selected start time */
  char end_date[11]        ="";   /* selected end date */
  char end_time[6]         ="";   /* selected end time */
  char select_by[11]       ="";   /* select by start_date (def) | stop_date */
  char order_by[13]        ="";   /* sort list by column */
  char sort_order[5]       ="";   /* ascending or descending */
  char **form_data;               /* string array for query data */
  char title[256]          = "";  /* cgi title string */
  struct tm *tm_ptr;              /* containing time structure */
  time_t now, old;                /* containing timestamp */
  char err_str[2048]       = "";  /* use for combined error string */
  char dataunit[255] = "0 Bytes"; /* holds the calculated KB/MB */
  unsigned long long sum_bin = 0;
  unsigned long long sum_bout = 0;
  unsigned long long sum_ball = 0;
  char sum_buf[255]  = "0";

  _abort_flag     = 0;
#ifdef ORACLE_DB
  /* ------------------------------------------------------------------- * 
   * ORACLE_HOME is needed for OCI8 to find tnsnames.ora                 *
   * ------------------------------------------------------------------- */
  putenv(WEB_ORACLE_ENV);

  /* initialize the connection */
  if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100))
    cgi_error("Error: Failed to init libsqlora8.");

  /* register the interrupt handler */
  sqlo_register_int_handler(&handle, sigint_handler);

  /* login to the database */
  if (SQLO_SUCCESS != sqlo_connect(&dbh, WEB_TNS_STRING))
    cgi_error("Error: Cannot connect to database.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  if (SQLO_SUCCESS != sqlo_server_version(dbh, server_version,
                                        sizeof(server_version)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* enable autocommit, each statement is commited as a single transaction */
  stat = sqlo_set_autocommit(dbh, 1);


  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    cgi_error("Error: Could not retrieve form data.");

  /* ------------------------------------------------------------------- * 
   * If we are not called with arguments, we display the query selector  *
   * with a query to list the available routers from edacs_router.       *
   * ------------------------------------------------------------------- */
  if(form_data[0] == NULL) {

    /* define the SQL query */
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT ROUTER FROM %s.EDACS_ROUTER", EDACSADMIN);

    /* initialize the statement handle */
    sth1 = SQLO_STH_INIT;

    /* opens a cursor for the query statement */
    if ( 0 > (sqlo_open2(&sth1, dbh, sqlquery_str, 0, NULL)))
      cgi_error(sqlo_geterror(dbh));
    RETURN_ON_ABORT; /* finish if SIGINT was catched */

    /* get the output column names */
    //if (SQLO_SUCCESS != sqlo_ocol_names2(sth1, &colcount, &colnames))
    //  cgi_error("Error getting the DB columns with sqlo_ocol_names2()");
    //RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
  /* initialize the connection */
  dbh = mysql_init(NULL);
  if(dbh == NULL) cgi_error("Error:  Failed to init MySQL DB.");

  /* login to the database */
  if (mysql_real_connect(dbh, MYSQLIP, EDACSADMIN, ADMIN_PASS, DB_NAME, DB_PORT, NULL, 0) == 0)
    cgi_error("Error: Cannot connect to database.");

  /* Get the database version */
  server_version = mysql_get_server_version(dbh);

  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    cgi_error("Error: Could not retrieve form data.");

  /* ------------------------------------------------------------------- * 
   * If we are not called with arguments, we display the query selector  *
   * with a query to list the available routers from edacs_router.       *
   * ------------------------------------------------------------------- */
  if(form_data[0] == NULL) {

    /* create the SQL query string */
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT router FROM edacs_router");

    /* Prepare and execute the SQL statement */
    if(mysql_query(dbh, sqlquery_str) != 0) {
      if(DEBUG == 0) cgi_error(mysql_error(dbh));
      else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
             mysql_error(dbh), sqlquery_str);
      cgi_error(err_str);
    }
   /* get query results set */
    result = mysql_store_result(dbh);
    if (result == NULL) {
      snprintf(err_str, sizeof(err_str), "No results for query: %s\n", sqlquery_str);
      cgi_error( err_str);
    }

    colcount = mysql_num_fields(result);
#endif

    /* ------------------------------------------------------------------- * 
     * The timestamps are used for range pre-selection or show query time  *
     * ------------------------------------------------------------------- */
    now = time(NULL);
    tm_ptr = localtime(&now);
    strftime(end_date, sizeof(end_date), "%d.%m.%Y", (tm_ptr));
    strftime(end_time, sizeof(end_time), "%H:%M", tm_ptr);
    old = time(NULL) - 7200;
    tm_ptr = localtime(&old);
    strftime(start_date, sizeof(start_date), "%d.%m.%Y", tm_ptr);
    strftime(start_time, sizeof(start_time), "%H:%M", tm_ptr);

    /* ------------------------------------------------------------------- * 
     * Start the HTML output                                               *
     * ------------------------------------------------------------------- */
    /* define the CGI title */
    snprintf(title, sizeof(title), "Router Session Activity by Time");
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");

    fprintf(cgiOut, "<form action=\"router-acttime.cgi\" method=\"get\">\n");
    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    /* 1st row, display headers */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">Router</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Time Frame</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Order By</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Sort Order</th>\n");
    /* 2nd row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">From:</td>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 3rd row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<input type=text size=10 name=start_date value=\"%s\">",start_date);
    fprintf(cgiOut, "<input type=text size=5 name=start_time value=\"%s\">",start_time);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">(choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"asc\" checked name=\"sort_order\">");
    fprintf(cgiOut, "Ascending</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 4th row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<select name=\"router\" size=\"1\">");
    /* fetch the data */
#ifdef ORACLE_DB
    while ( SQLO_SUCCESS == (stat = (sqlo_fetch(sth1, 1)))) {
      /* get one record */
      values = sqlo_values(sth1, NULL, 1);
#endif
#ifdef MYSQL_DB
   while((values = mysql_fetch_row(result)) != NULL) {
#endif
      fprintf(cgiOut, "<option value=\"%s\">%s</option>",values[0],values[0]);
    }
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">To:</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<select name=\"order_by\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"username\">User Name</option>");
    fprintf(cgiOut, "<option value=\"service\">Service</option>");
    fprintf(cgiOut, "<option value=\"ip_or_phone\">IP or Phone</option>");
    fprintf(cgiOut, "<option selected value=\"start_date\">Start Date</option>");
    fprintf(cgiOut, "<option value=\"stop_date\">Stop Date</option>");
    fprintf(cgiOut, "<option value=\"elapsed_mins\">Elapsed Time</option>");
    fprintf(cgiOut, "<option value=\"tty\">TTY</option>");
    fprintf(cgiOut, "<option value=\"bytes_in\">Bytes In</option>");
    fprintf(cgiOut, "<option value=\"bytes_out\">Bytes Out</option>");
    fprintf(cgiOut, "<option value=\"packets_in\">Packets In</option>");
    fprintf(cgiOut, "<option value=\"packets_out\">Packets Out</option>");
    fprintf(cgiOut, "<option value=\"throughput\">Throughput</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio name=\"sort_order\" value=\"desc\">Descending</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 5th row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<input type=text size=10 name=\"end_date\" value=\"%s\">", end_date);
    fprintf(cgiOut, "<input type=text size=5 name=\"end_time\" value=\"%s\"><br>&nbsp;</td>", end_time);
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 6th and last row, close the frame */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=4><input type=submit value=\"Run Query\"></th>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
    fprintf(cgiOut, "</form>\n");

    fprintf(cgiOut, "<h3>Additional Information</h3>\n");
    fprintf(cgiOut, "<hr>\n");
    fprintf(cgiOut, "<p>");
    fprintf(cgiOut, "This query returns the list of user sessions on the selected router for a given time period.");
    fprintf(cgiOut, "<ul>");
    fprintf(cgiOut, "<li>Select the router from the drop down list. If unsure, see <a href=\"router-list.cgi\">List of Routers</a> for more information.");
    fprintf(cgiOut, "<li>The time frame can be adjusted by typing directly into it, using the DD.MM.YYYY HH:MM format.");
    fprintf(cgiOut, "<li>Choosing a large time frame can result in a long query and a very large result set (thousands of rows).");
    fprintf(cgiOut, "<li>The results list can be ordered using criteria from the \"Order By\" drop down list.");
    fprintf(cgiOut, "</ul>\n");
    fprintf(cgiOut, "</p>\n");

    pageside();
  } /* end if for displaying the query request */
  else {
    /* ------------------------------------------------------------------- *
     * check if we got all information to make the SQL query               *
     * --------------------------------------------------------------------*/
    if ( cgiFormString("router", router, sizeof(router)) != cgiFormSuccess )
コード例 #6
0
ファイル: cgi_access.cpp プロジェクト: dblock/agnes
CString cgi_access_manager::get_value(cgiOutStream& CGIStream, const CString& name, int fatal){
	CString result = entry_manager::get_value(name);
	if ((!result.StrLength())&&fatal) cgi_error(CGIStream, "equivalence access denied");
	return result;
}
コード例 #7
0
ファイル: cgi_access.cpp プロジェクト: dblock/agnes
void cgi_access_manager::check_access(cgiOutStream& CGIStream, const CString& pass, const CString& id){
	if (!pass.StrLength()) cgi_error(CGIStream, "access denied");
	if ((entry_manager::get_value(id)!=pass)&&(check_root_access(pass))) cgi_error(CGIStream, "access denied");
}
コード例 #8
0
ファイル: user-info.c プロジェクト: fm4dd/edacs
int cgiMain() {
#ifdef MYSQL_DB
  static MYSQL *dbh;              /* database connect handle */
  static MYSQL_RES *result;       /* database query results  */
  static MYSQL_ROW values;        /* query data returned     */
  unsigned int colcount    =0;    /* number of returned columns */
  int server_version;             /* returned server version */
#endif
#ifdef ORACLE_DB
  sqlo_db_handle_t dbh;           /* database handle */
  sqlo_stmt_handle_t sth1;        /* statement handle 1 */
  char server_version[1024]="";   /* string for returned server version */
  int stat                 =0;    /* status of sqlo calls */
  int handle               =0;    /* handle of the interrupt handler */
  //const char ** colnames;         /* column names */
  const char ** values;           /* values */
#endif
  char sqlquery_str[1024]  ="";   /* SQL query string */
  char **form_data;               /* string array for query data */
  char username[49]        ="";   /* selected username */
  char first_start_date[11]="";   /* first connect start date */
  char first_start_time[6] ="";   /* first connect start time */
  char first_end_date[11]  ="";   /* first connect end date */
  char first_end_time[6]   ="";   /* first connect end time */
  char last_start_date[11] ="";   /* last connect start date */
  char last_start_time[6]  ="";   /* last connect start time */
  char last_end_date[11]   ="";   /* last connect end date */
  char last_end_time[6]    ="";   /* last connect end time */
  char title[256]          = "";  /* cgi title string */
  int allrows              =0;    /* number of returned rows */
  int rowcount             =0;    /* row iteration counter */
  div_t oddline_calc;             /* calculates even/odd row color */
  char err_str[2048]       ="";   /* use for combined error string */
  _abort_flag     = 0;

  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
  /* ------------------------------------------------------------------- *
   * If we are not called with arguments, we display a error message.    *
   * ------------------------------------------------------------------- */
    cgi_error("Error: Could not retrieve form data.");

  /* ------------------------------------------------------------------- *
   * check if we got all information to make the SQL query               *
   * --------------------------------------------------------------------*/
  if ( cgiFormString("username", username, sizeof(username))
                                                     != cgiFormSuccess )
    cgi_error("Error retrieving the username.");

#ifdef ORACLE_DB
  /* ------------------------------------------------------------------- * 
   * ORACLE_HOME is needed for OCI8 to find tnsnames.ora                 *
   * ------------------------------------------------------------------- */
  putenv(WEB_ORACLE_ENV);

  /* initialize the connection */
  if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100))
    cgi_error("Error: Failed to init libsqlora8.");

  /* register the interrupt handler */
  sqlo_register_int_handler(&handle, sigint_handler);

  /* login to the database */
  if (SQLO_SUCCESS != sqlo_connect(&dbh, WEB_TNS_STRING))
    cgi_error("Error: Cannot connect to database.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  if (SQLO_SUCCESS != sqlo_server_version(dbh, server_version,
                                        sizeof(server_version)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* enable autocommit, each statement is commited as a single transaction */
  stat = sqlo_set_autocommit(dbh, 1);

  /* define the SQL query */
  snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s FROM %s.EDACS_REMOTE WHERE USERNAME='******' ORDER BY IP_OR_PHONE",
           "IP_OR_PHONE",                                              /* 00 */
           "TO_CHAR(FIRST_CONNECT, 'dd-mm-yyyy')",                     /* 01 */
           "TO_CHAR(FIRST_CONNECT, 'hh24:mi:ss')",                     /* 02 */
           "TO_CHAR(FIRST_CONNECT+INTERVAL '1' MINUTE, 'dd-mm-yyyy')", /* 03 */
           "TO_CHAR(FIRST_CONNECT+INTERVAL '1' MINUTE, 'hh24:mi')",    /* 04 */
           "TO_CHAR(LAST_CONNECT, 'dd-mm-yyyy')",                      /* 05 */
           "TO_CHAR(LAST_CONNECT, 'hh24:mi:ss')",                      /* 06 */
           "TO_CHAR(LAST_CONNECT+INTERVAL '1' MINUTE, 'dd-mm-yyyy')",  /* 07 */
           "TO_CHAR(LAST_CONNECT+INTERVAL '1' MINUTE, 'hh24:mi')",     /* 08 */
	   EDACSADMIN, username);
	   // cgi_error(sqlquery_str); /* DEBUG output of the SQL string */

  /* initialize the statement handle */
  sth1 = SQLO_STH_INIT;

  /* opens a cursor for the query statement */
  if ( 0 > (sqlo_open2(&sth1, dbh, sqlquery_str, 0, NULL)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* get the output column names */
  //if (SQLO_SUCCESS != sqlo_ocol_names2(sth1, &colcount, &colnames))
  //  cgi_error("Error getting the DB columns with sqlo_ocol_names2()");
  //RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
  /* initialize the connection */
  dbh = mysql_init(NULL);
  if(dbh == NULL) cgi_error("Error:  Failed to init MySQL DB.");

  /* login to the database */
  if (mysql_real_connect(dbh, MYSQLIP, EDACSADMIN, ADMIN_PASS, DB_NAME, DB_PORT, NULL, 0) == 0)
    cgi_error("Error: Cannot connect to database.");

  /* Get the database version */
  server_version = mysql_get_server_version(dbh);

  /* create the SQL query string */
  snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT %s, %s, %s, %s, %s, %s, %s, %s, %s FROM edacs_remote WHERE username='******' ORDER BY ip_or_phone",
           "ip_or_phone",                                                /* 00 */
           "DATE_FORMAT(first_connect, '%d-%m-%Y')",                     /* 01 */
           "DATE_FORMAT(first_connect, '%H:%i:%s')",                     /* 02 */
           "DATE_FORMAT(first_connect+INTERVAL '1' MINUTE, '%d-%m-%Y')", /* 03 */
           "DATE_FORMAT(first_connect+INTERVAL '1' MINUTE, '%H:%i')",    /* 04 */
           "DATE_FORMAT(last_connect, '%d-%m-%Y')",                      /* 05 */
           "DATE_FORMAT(last_connect, '%H:%i:%s')",                      /* 06 */
           "DATE_FORMAT(last_connect+INTERVAL '1' MINUTE, '%d-%m-%Y')",  /* 07 */
           "DATE_FORMAT(last_connect+INTERVAL '1' MINUTE, '%H:%i')",     /* 08 */
           username);
           // cgi_error(sqlquery_str); /* DEBUG output of the SQL string */

  /* Prepare and execute the SQL statement */
  if(mysql_query(dbh, sqlquery_str) != 0) {
    if(DEBUG == 0) cgi_error(mysql_error(dbh));
    else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
             mysql_error(dbh), sqlquery_str);
    cgi_error(err_str);
  }
 /* get query results set */
  result = mysql_store_result(dbh);
  if (result == NULL) {
    snprintf(err_str, sizeof(err_str), "No results for query: %s\n", sqlquery_str);
    cgi_error( err_str);
  }

  allrows = mysql_num_rows(result);
  colcount = mysql_num_fields(result);
#endif

/* -------------------------------------------------------------------------- *
 * start the html output                                                      *
 * ---------------------------------------------------------------------------*/

  /* define the CGI title */
  snprintf(title, sizeof(title), "User Information for '%s'", username);
  pagehead(title);
  fprintf(cgiOut, "<div id=\"content\">\n");

  fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th class=\"inner\">#</th>\n");
  fprintf(cgiOut, "<th class=\"inner\">Remote IP / Phone</th>\n");
  fprintf(cgiOut, "<th class=\"inner\">Active Since</th>\n");
  fprintf(cgiOut, "<th class=\"inner\">Last Update</th>\n");
  fprintf(cgiOut, "</tr>\n");

  /* fetch the data */
#ifdef ORACLE_DB
  while ( SQLO_SUCCESS == (stat = (sqlo_fetch(sth1, 1)))) {
    /* get one record */
    values = sqlo_values(sth1, NULL, 1);
#endif
#ifdef MYSQL_DB
   while((values = mysql_fetch_row(result)) != NULL) {
#endif
    rowcount++;

     /* check for even/odd rows */
     oddline_calc = div(rowcount, 2);
     if(oddline_calc.rem) fprintf(cgiOut, "<tr class=\"odd\">\n");
     else fprintf(cgiOut, "<tr class=\"even\">\n");

    /* calculate start and end times for link to session query */
    strncpy(first_start_date, values[1], sizeof(first_start_date)-1);
    first_start_date[2] = '.';
    first_start_date[5] = '.';
    first_start_date[10] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(first_start_time, values[2], sizeof(first_start_time)-1);
    first_start_time[5] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(first_end_date, values[3], sizeof(first_end_date)-1);
    first_end_date[2] = '.';
    first_end_date[5] = '.';
    first_end_date[10] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(first_end_time, values[4], sizeof(first_end_time)-1);
    first_end_time[5] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(last_start_date, values[5], sizeof(last_start_date)-1);
    last_start_date[2] = '.';
    last_start_date[5] = '.';
    last_start_date[10] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(last_start_time, values[6], sizeof(last_start_time)-1);
    last_start_time[5] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(last_end_date, values[7], sizeof(last_end_date)-1);
    last_end_date[2] = '.';
    last_end_date[5] = '.';
    last_end_date[10] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    strncpy(last_end_time, values[8], sizeof(last_end_time)-1);
    last_end_time[5] = '\0'; /* strncpy does not terminate the string, therefore we have to */

    fprintf(cgiOut, "<td>%d</td>\n", rowcount);
    fprintf(cgiOut, "<td>%s</td>", values[0]);
    fprintf(cgiOut, "<td>");
    fprintf(cgiOut, "<a href=user-acttime.cgi?start_date=%s&start_time=%s&end_date=%s&end_time=%s&sort_order=asc&username=%s&order_by=start_date>", first_start_date, first_start_time, first_end_date, first_end_time, username);
    fprintf(cgiOut, "%s %s</a></td>", values[1], values[2]);

    fprintf(cgiOut, "<td>");
    fprintf(cgiOut, "<a href=user-acttime.cgi?start_date=%s&start_time=%s&end_date=%s&end_time=%s&sort_order=asc&username=%s&order_by=start_date&select_by=stop_date>", last_start_date, last_start_time, last_end_date, last_end_time, username);
    fprintf(cgiOut, "%s %s</a></td>", values[5], values[6]);
    fprintf(cgiOut, "</tr>\n");
  }
#ifdef ORACLE_DB
  if (SQLO_SUCCESS != sqlo_close(sth1))
    cgi_error("Error Closing the SQL statment handle.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
   mysql_close(dbh);
#endif
  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th class=\"inner\" colspan=4>");
  fprintf(cgiOut, "&nbsp;");
  fprintf(cgiOut, "</th>\n");
  fprintf(cgiOut, "</tr>\n");
  fprintf(cgiOut, "</table>\n");

  fprintf(cgiOut, "<h3>Additional Information</h3>\n");
  fprintf(cgiOut, "<hr>\n");
  fprintf(cgiOut, "<p>");
  fprintf(cgiOut, "This list represents all remote IP addresses or telephone numbers this user connected from.");
  fprintf(cgiOut, "<ul>");
  fprintf(cgiOut, "<li>The \"Remote IP / Phone\" is the remote ISP IP address of a user in case of a VPN connection, or his telephone number reported when connecting via dial-up. If the value is unknown, the connection came from a line that has caller-ID supression or is a plain old analog modem line.");
  fprintf(cgiOut, "<li>The \"Active Since\" is the first time session information was received. The time links to the first recorded session for this user, coming from this particular remote IP or phone.");
  fprintf(cgiOut, "<li>The \"Last Update\" time shows when the latest session record was received. The link tries to find the latest session. Sometimes the session is still in progress and incomplete or no data is returned.");
  fprintf(cgiOut, "</ul>");
  fprintf(cgiOut, "</p>\n");

  pageside();
  pagefoot();
  return(0);
}
コード例 #9
0
ファイル: main.c プロジェクト: c4125442/enterprise-search
int main(int argc, char **argv, char **envp)
{
	int postsize;
	char *xmldata, *data;
	xmlDocPtr doc;
        xmlNodePtr cur, anode;
	int bbdnsock;
	int bbdnport;
	char *status = NULL;
	struct config_t maincfg;


	/* Read in config file */
	maincfg = maincfgopen();
	bbdnport = maincfg_get_int(&maincfg, "BLDPORT");
	maincfgclose(&maincfg);
	key_get(systemkey);
	char *request_method;

	if (!bbdn_conect(&bbdnsock, "", bbdnport))
		cgi_error(500, bstrerror());


	request_method = getenv("HTTP_REQUEST_METHOD")!=NULL ? strdup(getenv("HTTP_REQUEST_METHOD")) : strdup(getenv("REQUEST_METHOD"));
	// We will handel the post stuf our self. Set REQUEST_METHOD to GET so cgi-util ignores it.
	setenv("REQUEST_METHOD", "GET", 1);

	if (cgi_init() != CGIERR_NONE) {
		cgi_error(500, "Can't init cgi-util");		
	}


	/*
	 * Either called from command line, and then we want a file.
	 * or a http get/put
	 * Or we are handling a web request, and getting the data from stdin.
	 */
	if ((cgi_getentrystr("method") != NULL) && (strcmp(cgi_getentrystr("method"),"rest") == 0)) {

		char api[100], coll[100], url[512];
		char *requrle;

		if (getenv("REQUEST_URI") == NULL) {
			cgi_error(500, "Can't read REQUEST_URI");
		}

		requrle = strdup(getenv("REQUEST_URI"));
		unescape_url(requrle);
		sscanf(requrle,"/%[a-z]/%[a-zA-Z0-9_-]/%[^?]", api, coll, url);

		#ifdef DEBUG
			fprintf(stderr, "api: \"%s\"\n",api);
			fprintf(stderr, "coll: \"%s\"\n",coll);
			fprintf(stderr, "url: \"%s\"\n",url);
			fprintf(stderr, "request_method: \"%s\"\n",request_method);
			fprintf(stderr, "reques url \"%s\"\n",getenv("REQUEST_URI"));
			fprintf(stderr, "reques url unescaped \"%s\"\n",requrle);
		#endif

		free(requrle);

		if (strcmp(request_method,"POST") == 0 || strcmp(request_method,"ADDDELAYED") == 0 || strcmp(request_method,"PUT") == 0) {

			if (getenv("CONTENT_LENGTH") == NULL) {
				cgi_error(500, "Can't read CONTENT_LENGTH");
			}

			
	               // Get data length
	                postsize = atoi(getenv("CONTENT_LENGTH"));
	                data = malloc(postsize + 1);
			if (data == NULL) {
				cgi_error(500, "Can't allocate data.");
			}
	                // Read data
	                fread(data, 1, postsize, stdin);
	                data[postsize] = '\0';

			// add in to repo
	        	if (bbdn_docadd(bbdnsock, 
					coll, 											// collection name
					url, 											// url
					cgi_getentrystr("documenttype"), 							// document type
					data,											// data
					postsize, 										// data size
					0, 											// lastmodified
					cgi_getentrystr("acl_allow")!=NULL ? cgi_getentrystr("acl_allow") : "Everyone", 	// acl allow
					cgi_getentrystr("acl_denied"), 								// acl denied
					cgi_getentrystr("title"), 								// title
					cgi_getentrystr("documentformat"), 							// document format
					cgi_getentrystr("attributes"),								// attributes
					NULL,											// image
					0											// image size
				) != 1) {
				cgi_error(500, "bbdn_docadd() failed. Can't add document.");
			}

			
			if (strcmp(request_method,"ADDDELAYED") != 0) {
	                	// close it
	                	sd_close(bbdnsock, coll);
			}

			asprintf(&status,"Added %s to %s\n",url,coll);

		}
		else if (strcmp(request_method,"DELETE") == 0) {

			if (url[0] == '\0') {

				if (sd_deletecollection(bbdnsock, coll) != 1) {
					cgi_error(500, "Can't delete collection");
				}

				asprintf(&status,"Deleted collection %s\n",coll);
			}
			else {
				if (bbdn_deleteuri(bbdnsock, coll, url) != 1) {
					cgi_error(500, "Can't delete document");
				}

				asprintf(&status,"Deleted url %s in %s\n",url,coll);
			}

		}
		else if (strcmp(request_method,"CLOSE") == 0) {
			sd_close(bbdnsock, coll);

			asprintf(&status,"Closed %s\n",coll);

		}
		else {
			cgi_error(500, "Unknown request method \"%s\"", request_method );
		}

		#ifdef DEBUG
			// Print the envirement so we can better see what is going on.
	                char** env;
	                for (env = envp; *env != 0; env++) {
	                    char* thisEnv = *env;
	                    fprintf(stderr, "%s\n", thisEnv);
	                }
		#endif


	}
	else if ((cgi_getentrystr("do") != NULL) && (strcmp(cgi_getentrystr("do"),"add") == 0)) {

		char *data;
		int datasize;
		int n;

		const char *url = getenv("HTTP_X_FILENAME") ? getenv("HTTP_X_FILENAME") : cgi_getentrystr("url");
		const char *coll = cgi_getentrystr("collection");

		if (url == NULL) {
			cgi_error(500, "No url specified. Either set http header HTTP_X_FILENAME or get parameter 'url'.\n");
		}
		if (coll == NULL) {
			cgi_error(500, "No collection specified\n");
		}


		char *tmpname;
		FILE *fh;
		asprintf(&tmpname,"/tmp/%s",url);
	
		fh = fopen(tmpname,"wb");
		if (fh == NULL) {
			cgi_error(500, "Can't open file %s",tmpname);
		}

		if ((data = malloc( atoi(getenv("CONTENT_LENGTH")) )) == NULL) {
			cgi_error(500, "Can't malloc data");
		}

		datasize = 0;
		while ((n = fread ((unsigned char *)(data + datasize),1,1024,stdin)) > 0) {
			datasize += n;
		}

		fwrite(data,1,datasize,fh);

		fclose(fh);
		free(tmpname);


		//        bbdn_docadd(bbdnsock, xmldoc.collection, uri, xmldoc.documenttype, xmldoc.body, xmldoc.bodysize,
		//            xmldoc.lastmodified, xmldoc.aclallow, xmldoc.acldeny, xmldoc.title, xmldoc.documentformat, xmldoc.attributes, image, image_size);
        	bbdn_docadd(bbdnsock, coll, url, "", data, datasize,
      		    0, "Everyone", "", "omp1", "", "", NULL, 0);


		// close it
		sd_close(bbdnsock, coll);
	}
	else if ((cgi_getentrystr("do") != NULL) && (strcmp(cgi_getentrystr("do"),"delete") == 0)) {


		const char *url = getenv("HTTP_X_FILENAME") ? getenv("HTTP_X_FILENAME") : cgi_getentrystr("url");
		const char *coll = cgi_getentrystr("collection");

		if (url == NULL) {
			cgi_error(500, "No url specified. Either set http header HTTP_X_FILENAME or get parameter 'url'.\n");
		}
		if (coll == NULL) {
			cgi_error(500, "No collection specified\n");
		}

		bbdn_deleteuri(bbdnsock, coll, url);

		asprintf(&status,"%s deleted.\n", url);
	}
	else if (getenv("CONTENT_LENGTH") != NULL) {
		// Get data length
		postsize = atoi(getenv("CONTENT_LENGTH"));
		xmldata = malloc(postsize + 1);	
		// Read data
		fread(xmldata, 1, postsize, stdin);
		xmldata[postsize] = '\0';


		//fprintf(stderr, "Received %i bytes.\n", postsize);
		//fprintf(stderr, "Got document:\n%s\n", xmldata);

		//parsing xml
        	doc = xmlParseDoc((xmlChar*)xmldata);

        	if (doc == NULL)
		cgi_error(500, "Unable to parse document");

        	cur = xmlDocGetRootElement(doc);

        	if (cur == NULL) {
        	        xmlFreeDoc(doc);
        	        cgi_error(500, "empty document");
        	}

		// Some document checking
        	if (xmlStrcmp(cur->name, (const xmlChar *)ROOT_NODE_NAME)) {
        	        xmlFreeDoc(doc);
        	        cgi_error(500, "document of the wrong type, root node != %s, but %s\n", ROOT_NODE_NAME, cur->name);
        	}

		if ((anode = xml_find_child(cur, "key")) != NULL) {
			char *p;
		
			p = (char *)xmlNodeListGetString(doc, anode->xmlChildrenNode, 1);
			if (p == NULL)
				cgi_error(500, "No key data");

			if ((systemkey[0] != '\0') && (!key_equal(systemkey, p))) {
				cgi_error(500, "Keys does not match:  Got \"%s\" but wanted \"%s\"\n",p,systemkey);
			}
		} else {
			cgi_error(500, "Did not receive a key");
		}
		if ((anode = xml_find_child(cur, "version")) != NULL) {
			xmlChar *p;

			p = xmlNodeListGetString(doc, anode->xmlChildrenNode, 1);
			version = atoi((char*)p);

			xmlFree(p);
		} else {
			cgi_error(500, "Did not receive a version number");
		}

		for (cur = cur->xmlChildrenNode; cur != NULL; cur = cur->next) {
			if ((!xmlStrcmp(cur->name, (const xmlChar *) "key"))){
				// Ignore
			} else if ((!xmlStrcmp(cur->name, (const xmlChar *) "version"))){
				// Ignore
			} else if ((!xmlStrcmp(cur->name, (const xmlChar *) "add"))){
				xml_add(bbdnsock, doc, cur);
			} else if ((!xmlStrcmp(cur->name, (const xmlChar *) "delete"))){
				xml_delete(bbdnsock, doc, cur);
			} else if ((!xmlStrcmp(cur->name, (const xmlChar *) "close"))) {
				xml_close(bbdnsock, doc, cur);
			} else if ((!xmlStrcmp(cur->name, (const xmlChar *) "create"))) {
				xml_create(bbdnsock, doc, cur);
			} else if ((!xmlStrcmp(cur->name, (const xmlChar *) "users"))) {
				xml_users(doc, cur);
			} else if ((!xmlStrcmp(cur->name, (const xmlChar *) "gcwhispers"))) {
				xml_gcwhispers(bbdnsock, doc, cur);
			} else if ((!xmlStrcmp(cur->name, (const xmlChar *) "error"))) {
				xml_errormsg(bbdnsock, doc, cur);
			} else if ((!xmlStrcmp(cur->name, (xmlChar*)"text"))) {
				//fprintf(stderr, "Got text: %s\n", xmlNodeListGetString(doc, cur, 1));
				// Ignore for now
			} else {
				warnx("Unknown xml node '%s'", cur->name);
			}
		}

	} else {
		cgi_error(500, "Didn't receive any command or data.");
	}

	if (status != NULL) {
		printf("Content-type: text/plain\n\n");
		printf(status);
	}
	else {
		cgi_error(500, "Reached end of program without status.");
	}

	return 0;
}
コード例 #10
0
ファイル: enadis.c プロジェクト: Kotty666/xymon
void parse_cgi(void)
{
	cgidata_t *postdata, *pwalk;
	struct tm schedtm;
	struct tm endtm;
	struct tm nowtm;

	memset(&schedtm, 0, sizeof(schedtm));
	memset(&endtm, 0, sizeof(endtm));

	postdata = cgi_request();
	if (cgi_method == CGI_GET) return;


	/* We only want to accept posts from certain pages: svcstatus (for info), and ourselves */
	/* At some point in the future, moving info lookups to their own page would be a good idea */
	{
		char cgisource[1024]; char *p;
		p = csp_header("enadis"); if (p) fprintf(stdout, "%s", p);
		snprintf(cgisource, sizeof(cgisource), "%s/%s", xgetenv("SECURECGIBINURL"), "enadis");
		if (!cgi_refererok(cgisource)) {
			snprintf(cgisource, sizeof(cgisource), "%s/%s", xgetenv("CGIBINURL"), "svcstatus");
			if (!cgi_refererok(cgisource)) {
				dbgprintf("Not coming from self or svcstatus; abort\n");
				return;	/* Just display, don't do anything */
			}
		}
	}


	if (!postdata) {
		errormsg(cgi_error());
	}

	pwalk = postdata;
	while (pwalk) {
		/*
		 * When handling the "go", the "Disable now" and "Schedule disable"
		 * radio buttons mess things up. So ignore the "go" if we have seen a
		 * "filter" request already.
		 */
		if ((strcmp(pwalk->name, "go") == 0) && (action != ACT_FILTER)) {
			if      (strcasecmp(pwalk->value, "enable") == 0)           action = ACT_ENABLE;
			else if (strcasecmp(pwalk->value, "disable now") == 0)      action = ACT_DISABLE;
			else if (strcasecmp(pwalk->value, "schedule disable") == 0) action = ACT_SCHED_DISABLE;
			else if (strcasecmp(pwalk->value, "cancel") == 0)           action = ACT_SCHED_CANCEL;
			else if (strcasecmp(pwalk->value, "apply filters") == 0)    action = ACT_FILTER;
		}
		else if ((strcmp(pwalk->name, "go2") == 0) && (action != ACT_FILTER)) { 
			if (strcasecmp(pwalk->value, "Disable until") == 0) disableend = DISABLE_UNTIL;
		}
		else if (strcmp(pwalk->name, "duration") == 0) {
			duration = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "untilok") == 0) {
			if (strcasecmp(pwalk->value, "on") == 0) {
				duration = -1;
				scale = 1;
			}
		}
		else if (strcmp(pwalk->name, "scale") == 0) {
			scale = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "cause") == 0) {
			disablemsg = strdup(pwalk->value);
		}
		else if (strcmp(pwalk->name, "hostname") == 0) {
			if (hostnames == NULL) {
				hostnames = (char **)malloc(2 * sizeof(char *));
				hostnames[0] = strdup(pwalk->value);
				hostnames[1] = NULL;
				hostcount = 1;
			}
			else {
				hostnames = (char **)realloc(hostnames, (hostcount + 2) * sizeof(char *));
				hostnames[hostcount] = strdup(pwalk->value);
				hostnames[hostcount+1] = NULL;
				hostcount++;
			}
		}
		else if (strcmp(pwalk->name, "enabletest") == 0) {
			char *val = pwalk->value;

			if (strcmp(val, "ALL") == 0) val = "*";

			if (enabletest == NULL) {
				enabletest = (char **)malloc(2 * sizeof(char *));
				enabletest[0] = strdup(val);
				enabletest[1] = NULL;
				enablecount = 1;
			}
			else {
				enabletest = (char **)realloc(enabletest, (enablecount + 2) * sizeof(char *));
				enabletest[enablecount] = strdup(val);
				enabletest[enablecount+1] = NULL;
				enablecount++;
			}
		}
		else if (strcmp(pwalk->name, "disabletest") == 0) {
			char *val = pwalk->value;

			if (strcmp(val, "ALL") == 0) val = "*";

			if (disabletest == NULL) {
				disabletest = (char **)malloc(2 * sizeof(char *));
				disabletest[0] = strdup(val);
				disabletest[1] = NULL;
				disablecount = 1;
			}
			else {
				disabletest = (char **)realloc(disabletest, (disablecount + 2) * sizeof(char *));
				disabletest[disablecount] = strdup(val);
				disabletest[disablecount+1] = NULL;
				disablecount++;
			}
		}
		else if (strcmp(pwalk->name, "year") == 0) {
			schedtm.tm_year = atoi(pwalk->value) - 1900;
		}
		else if (strcmp(pwalk->name, "month") == 0) {
			schedtm.tm_mon = atoi(pwalk->value) - 1;
		}
		else if (strcmp(pwalk->name, "day") == 0) {
			schedtm.tm_mday = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "hour") == 0) {
			schedtm.tm_hour = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "minute") == 0) {
			schedtm.tm_min = atoi(pwalk->value);
		}

		/* Until start */
		else if (strcmp(pwalk->name, "endyear") == 0) {
			endtm.tm_year = atoi(pwalk->value) - 1900;
		}
		else if (strcmp(pwalk->name, "endmonth") == 0) {
			endtm.tm_mon = atoi(pwalk->value) - 1;
		}
		else if (strcmp(pwalk->name, "endday") == 0) {
			endtm.tm_mday = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "endhour") == 0) {
			endtm.tm_hour = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "endminute") == 0) {
			endtm.tm_min = atoi(pwalk->value);
		}
		/* Until end */

		else if (strcmp(pwalk->name, "canceljob") == 0) {
			cancelid = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "preview") == 0) {
			preview = (strcasecmp(pwalk->value, "on") == 0);
		}
		else if ((strcmp(pwalk->name, "hostpattern") == 0) && pwalk->value && strlen(pwalk->value)) {
			hostpattern = strdup(pwalk->value);
		}
		else if ((strcmp(pwalk->name, "pagepattern") == 0) && pwalk->value && strlen(pwalk->value)) {
			pagepattern = strdup(pwalk->value);
		}
		else if ((strcmp(pwalk->name, "ippattern") == 0)   && pwalk->value && strlen(pwalk->value)) {
			ippattern = strdup(pwalk->value);
		}
		else if ((strcmp(pwalk->name, "classpattern") == 0)   && pwalk->value && strlen(pwalk->value)) {
			classpattern = strdup(pwalk->value);
		}

		pwalk = pwalk->next;
	}

	schedtm.tm_isdst = -1;
	schedtime = mktime(&schedtm);
	endtm.tm_isdst = -1;
	endtime = mktime(&endtm);
}
コード例 #11
0
ファイル: ip-actlast.c プロジェクト: fm4dd/edacs
int cgiMain() {
#ifdef MYSQL_DB
  static MYSQL *dbh;              /* database connect handle */
  static MYSQL_RES *result;       /* database query results  */
  static MYSQL_ROW values;        /* query data returned     */
  unsigned int colcount    =0;    /* number of returned columns */
  int server_version;             /* returned server version */
#endif
#ifdef ORACLE_DB
  sqlo_db_handle_t dbh;           /* database handle */
  sqlo_stmt_handle_t sth1;        /* statement handle 1 */
  char server_version[1024]="";   /* string for returned server version */
  int stat                 =0;    /* status of sqlo calls */
  int handle               =0;    /* handle of the interrupt handler */
  const char ** values;           /* values */
#endif
  char sqlquery_str[1024]  ="";   /* SQL query string */
  int allrows              =0;    /* number of returned rows */
  int rowcount             =0;    /* row iteration counter */
  div_t oddline_calc;             /* calculates even/odd row color */
  char ipaddr[16]          ="";   /* selected IP address */
  char start_date[11]      ="";   /* selected start date */
  char start_time[6]       ="";   /* selected start time */
  char end_date[11]        ="";   /* selected end date */
  char end_time[6]         ="";   /* selected end time */
  char order_by[13]        ="";   /* sort list by column */
  char sort_order[5]       ="";   /* ascending or descending */
  char **form_data;               /* string array for query data */
  char title[256]          ="";   /* cgi title string */
  struct tm *tm_ptr;              /* containing time structure */
  time_t now, old;                /* containing timestamp */
  char err_str[2048]       ="";   /* use for combined error string */
  int period               = 0;   /* the period to display */
  char dataunit[255] = "0 Bytes"; /* holds the calculated KB/MB */
  unsigned long long sum_bin = 0;  /* summary of all bytes in */
  unsigned long long sum_bout = 0; /* summary of all bytes out */
  unsigned long long sum_ball = 0; /* summary of all bytes total */
  char sum_buf[255]  = "0";        /* summary string buffer */

  _abort_flag     = 0;
#ifdef ORACLE_DB
  /* ------------------------------------------------------------------- * 
   * ORACLE_HOME is needed for OCI8 to find tnsnames.ora                 *
   * ------------------------------------------------------------------- */
  putenv(WEB_ORACLE_ENV);

  /* initialize the connection */
  if (SQLO_SUCCESS != sqlo_init(SQLO_OFF, 1, 100))
    cgi_error("Error: Failed to init libsqlora8.");

  /* register the interrupt handler */
  sqlo_register_int_handler(&handle, sigint_handler);

  /* login to the database */
  if (SQLO_SUCCESS != sqlo_connect(&dbh, WEB_TNS_STRING))
    cgi_error("Error: Cannot connect to database.");
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  if (SQLO_SUCCESS != sqlo_server_version(dbh, server_version,
                                        sizeof(server_version)))
    cgi_error(sqlo_geterror(dbh));
  RETURN_ON_ABORT; /* finish if SIGINT was catched */

  /* enable autocommit, each statement is commited as a single transaction */
  stat = sqlo_set_autocommit(dbh, 1);
#endif
#ifdef MYSQL_DB
  /* initialize the connection */
  dbh = mysql_init(NULL);
  if(dbh == NULL) cgi_error("Error:  Failed to init MySQL DB.");

  /* login to the database */
  if (mysql_real_connect(dbh, MYSQLIP, EDACSADMIN, ADMIN_PASS, DB_NAME, DB_PORT, NULL, 0) == 0)
    cgi_error("Error: Cannot connect to database.");

  /* Get the database version */
  server_version = mysql_get_server_version(dbh);
#endif

  /* we load the cgi form values into form_data */
  if (cgiFormEntries(&form_data) != cgiFormSuccess)
    cgi_error("Error: Could not retrieve form data.");

  if(form_data[0] == NULL) {
    /* ------------------------------------------------------------------- * 
     * Start the HTML output to display the query selection                *
     * ------------------------------------------------------------------- */
    /* define the CGI title */
    snprintf(title, sizeof(title), "Latest IP Address Session Activity");
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content\">\n");

    fprintf(cgiOut, "<form action=\"ip-actlast.cgi\" method=\"get\">\n");
    fprintf(cgiOut, "<table class=\"inner\">\n");
    /* 1st row, display headers */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" width=150>");
    fprintf(cgiOut, "IP Address</th>");
    fprintf(cgiOut, "<th class=\"inner\" width=150>");
    fprintf(cgiOut, "Time Frame</th>");
    fprintf(cgiOut, "<th class=\"inner\" width=150>");
    fprintf(cgiOut, "Order By</th>");
    fprintf(cgiOut, "<th class=\"inner\" width=150>");
    fprintf(cgiOut, "Sort Order</th>");
    fprintf(cgiOut, "</tr>\n");
    /* 2nd row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"6\" checked name=\"start\"> Last 6 Hours</td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 3rd row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "(192.168.111.222)</td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"12\" name=\"start\"> Last 12 Hours</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\"> (choose one)</td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"asc\" checked name=\"sort_order\">");
    fprintf(cgiOut, "&nbsp;Ascending</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 4th row, request values */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner-ctr\">");
    fprintf(cgiOut, "<input type=text name=\"ipaddr\" size=\"15\"></td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"24\" name=\"start\"> Last 24 Hours</td>");
    fprintf(cgiOut, "<td class=\"inner-ctr\"><select name=\"order_by\" size=\"1\">");
    fprintf(cgiOut, "<option value=\"router\">Router</option>");
    fprintf(cgiOut, "<option value=\"service\">Service</option>");
    fprintf(cgiOut, "<option value=\"ip_or_phone\">IP or Phone</option>");
    fprintf(cgiOut, "<option selected value=\"start_date\">Start Date</option>");
    fprintf(cgiOut, "<option value=\"stop_date\">Stop Date</option>");
    fprintf(cgiOut, "<option value=\"elapsed_mins\">Elapsed Time</option>");
    fprintf(cgiOut, "<option value=\"bytes_in\">Bytes In</option>");
    fprintf(cgiOut, "<option value=\"bytes_out\">Bytes Out</option>");
    fprintf(cgiOut, "<option value=\"throughput\">Throughput</option>");
    fprintf(cgiOut, "</select></td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio name=\"sort_order\" value=\"desc\">&nbsp;Descending</td>");
    fprintf(cgiOut, "</tr>\n");
    /* 5th row */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\">");
    fprintf(cgiOut, "<input type=radio value=\"168\" name=\"start\"> Last Week</td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "<td class=\"inner\"></td>");
    fprintf(cgiOut, "</tr>\n");
    /* 6th and last row, close the frame */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=4>");
    fprintf(cgiOut, "<input type=submit value=\"Run Query\"></th>");
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
    fprintf(cgiOut, "</form>\n");

    fprintf(cgiOut, "<h3>Additional Information</h3>\n");
    fprintf(cgiOut, "<hr>\n");
    fprintf(cgiOut, "<p>\n");
    fprintf(cgiOut, "This query returns the list of user sessions for this IP address during the last time period.");
    fprintf(cgiOut, "<ul>");
    fprintf(cgiOut, "<li>Type the IP address into the text field. If unsure, query the last sessions to see which IP's are given out.");
    fprintf(cgiOut, "<li>The time frame can be selected from the radio menu, time is counting back from now.");
    fprintf(cgiOut, "<li>Choosing a large time frame can result in a long query and a very large result set (thousands of rows).");
    fprintf(cgiOut, "<li>The results list can be ordered using criteria from the \"Order By\" drop down list.");
    fprintf(cgiOut, "</ul></font>");
    fprintf(cgiOut, "</p>\n");

    pageside();
  } /* end if for displaying the query request */
  else {
  /* ------------------------------------------------------------------- *
   * check if we got all information to make the SQL query               *
   * --------------------------------------------------------------------*/
    if ( cgiFormString("ipaddr", ipaddr, sizeof(ipaddr))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving the IP address.");
  
    if ( cgiFormIntegerBounded( "start", &period, 1, 2160, 6) 
                                                     != cgiFormSuccess ) 
      cgi_error("Error retrieving start period information.");
  
    if ( cgiFormString("order_by", order_by, sizeof(order_by))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving order_by information.");
  
    if ( cgiFormString("sort_order", sort_order, sizeof(sort_order))
                                                     != cgiFormSuccess )
      cgi_error("Error retrieving sort_order information.");
  
    /* ------------------------------------------------------------------- * 
     * The calculate query start and end time from given period in hours   *
     * ------------------------------------------------------------------- */
    now = time(NULL);
    tm_ptr = localtime(&now);
    strftime(end_date, sizeof(end_date), "%d.%m.%Y", (tm_ptr));
    strftime(end_time, sizeof(end_time), "%H:%M", tm_ptr);
    old = time(NULL) - (period * 3600);
    tm_ptr = localtime(&old);
    strftime(start_date, sizeof(start_date), "%d.%m.%Y", tm_ptr);
    strftime(start_time, sizeof(start_time), "%H:%M", tm_ptr);
  
    /* ------------------------------------------------------------------- *
     * check we got all parts and can start doing the SQL query below      *
     * --------------------------------------------------------------------*/
#ifdef ORACLE_DB
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT USERNAME, ROUTER, SERVICE, IP_OR_PHONE, IP_ADDR, %s, %s, ELAPSED_MINS_STR, TTY, BYTES_IN_STR, BYTES_OUT_STR, PACKETS_IN_STR, PACKETS_OUT_STR, KBS_STR FROM %s.V_EDACS WHERE IP_ADDR = '%s' AND START_DATE BETWEEN TO_DATE('%s %s', 'dd.mm.yyyy hh24:mi') and TO_DATE ('%s %s', 'dd.mm.yyyy hh24:mi') ORDER BY %s %s",
           "TO_CHAR(START_DATE, 'dd-mm-yyyy hh24:mi:ss')",
           "TO_CHAR(STOP_DATE, 'dd-mm-yyyy hh24:mi:ss')",
           EDACSADMIN, ipaddr, start_date, start_time, end_date,
           end_time, order_by, sort_order);

    /* initialize the statement handle */
    sth1 = SQLO_STH_INIT;
  
    /* opens a cursor for the query statement */
    if ( 0 > (sqlo_open2(&sth1, dbh, sqlquery_str, 0, NULL))) {
      if(DEBUG == 0) cgi_error(sqlo_geterror(dbh));
      else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
               sqlo_geterror(dbh), sqlquery_str);
      cgi_error(err_str);
    }
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
  
    /* get the output column names */
    //if (SQLO_SUCCESS != sqlo_ocol_names2(sth1, &colcount, &colnames))
    //  cgi_error("Error getting the DB columns with sqlo_ocol_names2()");
    //RETURN_ON_ABORT; /* finish if SIGINT was catched */
  #endif
#ifdef MYSQL_DB
    snprintf(sqlquery_str, sizeof(sqlquery_str), "SELECT username, router, service, ip_or_phone, ip_addr, %s, %s, elapsed_mins_str, bytes_in, bytes_out, throughput FROM v_edacs WHERE ip_addr = '%s' AND start_date BETWEEN STR_TO_DATE('%s %s', '%s') and STR_TO_DATE('%s %s', '%s') ORDER BY %s %s",
           "DATE_FORMAT(start_date, '%d-%m-%Y %H:%i:%s')",
           "DATE_FORMAT(stop_date, '%d-%m-%Y %H:%i:%s')",
           ipaddr,
           start_date, start_time, "%d.%m.%Y %H:%i",
           end_date, end_time, "%d.%m.%Y %H:%i",
           order_by, sort_order);

  /* Prepare and execute the SQL statement */
  if(mysql_query(dbh, sqlquery_str) != 0) {
    if(DEBUG == 0) cgi_error(mysql_error(dbh));
    else snprintf(err_str, sizeof(err_str), "DB error %s\n\nQuery string %s",
             mysql_error(dbh), sqlquery_str);
    cgi_error(err_str);
  }
 /* get query results set */
  result = mysql_store_result(dbh);
  if (result == NULL) {
    snprintf(err_str, sizeof(err_str), "No results for query: %s\n", sqlquery_str);
    cgi_error( err_str);
  }

  allrows = mysql_num_rows(result);
  colcount = mysql_num_fields(result);
#endif

  /* ------------------------------------------------------------------------ *
   * start the html output                                                    *
   * -------------------------------------------------------------------------*/
    snprintf(title, sizeof(title), "Latest Session Activity for IP Address %s", ipaddr);
  
    pagehead(title);
    fprintf(cgiOut, "<div id=\"content-wide\">\n");
    fprintf(cgiOut, "<p>\n");
    fprintf(cgiOut, "<b>IP Address:</b> %s <b>Timeperiod:</b> %s %s - %s %s <b>Data Records:</b> %d",
               ipaddr, start_date, start_time, end_date, end_time, allrows);
    fprintf(cgiOut, "</p>\n");
  
    fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\">#</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">User</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Router</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Service</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">IP / Phone</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">IP Address</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Session Start</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Session End</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Duration</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Data In</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Data Out</th>\n");
    fprintf(cgiOut, "<th class=\"inner\">Throughput</th>\n");
    fprintf(cgiOut, "</tr>\n");
 
    /* fetch the data */
#ifdef ORACLE_DB
    while ( SQLO_SUCCESS == (stat = (sqlo_fetch(sth1, 1)))) {
       /* get one record */
       values = sqlo_values(sth1, NULL, 1);
#endif
#ifdef MYSQL_DB
     while((values = mysql_fetch_row(result)) != NULL) {
#endif
     rowcount++;

     /* check for even/odd rows */
     oddline_calc = div(rowcount, 2);
     if(oddline_calc.rem) fprintf(cgiOut, "<tr class=\"odd\">\n");
     else fprintf(cgiOut, "<tr class=\"even\">\n");

     /* calculate transer data sums */
     if (values[8]) sum_bin = sum_bin + atoll(values[8]);
     if (values[9]) sum_bout = sum_bout + atoll(values[9]);

     fprintf(cgiOut, "<td>%d</td>\n", rowcount);
     fprintf(cgiOut, "<td>");
     if (values[0]) fprintf(cgiOut, "%s</td>\n", values[0]); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "<td>");
     if (values[1]) fprintf(cgiOut, "%s</td>\n", values[1]); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "<td>");
     if (values[2]) fprintf(cgiOut, "%s</td>\n", values[2]); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "<td>");
     if (values[3]) fprintf(cgiOut, "%s</td>\n", values[3]); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "<td>");
     if (values[4]) fprintf(cgiOut, "%s</td>\n", values[4]); else fprintf(cgiOut, "none</td>");
     fprintf(cgiOut, "<td>");
     if (values[5]) fprintf(cgiOut, "%s</td>\n", values[5]); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "<td>");
     if (values[6]) fprintf(cgiOut, "%s</td>\n", values[6]); else fprintf(cgiOut, "in progress</td>");
     fprintf(cgiOut, "<td>");
     if (values[7]) fprintf(cgiOut, "%s</td>\n", values[7]); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "<td>");
     if (values[8]) fprintf(cgiOut, "%s</td>\n", calc_units(values[8], dataunit)); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "<td>");
     if (values[9]) fprintf(cgiOut, "%s</td>\n", calc_units(values[9], dataunit)); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "<td>");
     if (values[10]) fprintf(cgiOut, "%s/s</td>\n", calc_units(values[10], dataunit)); else fprintf(cgiOut, "&nbsp;</td>");
     fprintf(cgiOut, "</tr>\n");
   } /* end while fetch row data */
#ifdef ORACLE_DB
    if (SQLO_SUCCESS != sqlo_close(sth1))
      cgi_error("Error Closing the SQL statment handle.");
    RETURN_ON_ABORT; /* finish if SIGINT was catched */
#endif
#ifdef MYSQL_DB
   mysql_close(dbh);
#endif

    /* ----------------------------------------------------------------- *
     * IF there was no data for the selection, display a notification    *
     * ----------------------------------------------------------------- */
    if(rowcount == 0) {
      fprintf(cgiOut, "<tr>\n");
      fprintf(cgiOut, "<td colspan=12>");
      fprintf(cgiOut, "No data found for IP address %s between %s %s and %s %s.",
              ipaddr, start_date, start_time, end_date, end_time);
      fprintf(cgiOut, "</td>\n");
      fprintf(cgiOut, "</tr>\n");
    } /* end if rowcount is zero */
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" colspan=12>Inbound Data Total:\n");
    sprintf(sum_buf, "%llu", sum_bin);
    fprintf(cgiOut, " %s Outbound Data Total:", calc_units(sum_buf, dataunit));
    sprintf(sum_buf, "%llu", sum_bout);
    fprintf(cgiOut, " %s Transfered Data Total:", calc_units(sum_buf, dataunit));
    sum_ball = sum_ball + sum_bin + sum_bout;
    sprintf(sum_buf, "%llu", sum_ball);
    fprintf(cgiOut, " %s</th>\n", calc_units(sum_buf, dataunit));
    fprintf(cgiOut, "</tr>\n");
    fprintf(cgiOut, "</table>\n");
  } /* end else we were called with form data */

  pagefoot();
  return(0);
}
コード例 #12
0
ファイル: static.c プロジェクト: HermannDppes/clearsilver
int main(int argc, char **argv, char **envp)
{
  NEOERR *err;
  CGI *cgi;
  char *cs_file;
  char hdf_file[PATH_BUF_SIZE];
  char *p;

  /* CGI works by passing information from the server to the CGI program via
   * environment variables and stdin.  cgi_debug_init looks for a file as the
   * first argument, and loads it.  That file contains key=value pairs which
   * cgi_debug_init will load into the environment, allowing you to test your
   * program via the command line. */
  cgi_debug_init(argc, argv);

  /* The ClearSilver cgi toolkit accesses the CGI environment through a
   * wrapper.  This allows the program to be used in other environments and
   * fake the CGI environment, such as FastCGI, mod_python, PyApache, or even
   * just from Python to access the python objects instead of the libc API.
   * cgiwrap_init_std just sets up for the default CGI environment using the
   * libc api. */
  cgiwrap_init_std(argc, argv, envp);

  /* cgi_init creates a CGI struct, and parses the CGI environment variables. 
   * It creates an HDF structure as well.  */
  err = cgi_init(&cgi, NULL);
  if (err != STATUS_OK)
  {
    /* cgi_neo_error renders a NEOERR as an error CGI result */
    cgi_neo_error(cgi, err);
    /* nerr_warn_error logs the error to stderr and cleans up */
    nerr_warn_error(err);
    return -1;
  }

  /* CGI.PathTranslated is a CGI env var which maps the URL with the
   * DocumentRoot to give you the location of the referenced file on disk */
  cs_file = hdf_get_value(cgi->hdf, "CGI.PathTranslated", NULL);
  if (cs_file == NULL)
  {
    /* cgi_error returns a simple error page */
    cgi_error(cgi, "No PATH_TRANSLATED var");
    return -1;
  }

  /* The hdf.loadpaths variables specify where HDF and ClearSilver look for
   * files on the file system.  We start setting that up here based on
   * the directory of the file referenced */
  p = strrchr (cs_file, '/');
  if (p)
  {
    *p = '\0';
    err = hdf_set_value(cgi->hdf, "hdf.loadpaths.0", cs_file);
    chdir(cs_file);
    *p = '/';
    if (err)
    {
      cgi_neo_error(cgi, err);
      nerr_warn_error(err);
      return -1;
    }
  }
  /* Next, we look for a shared HDF static dataset in common.hdf */
  err = hdf_read_file(cgi->hdf, "common.hdf");
  if (err && !nerr_handle(&err, NERR_NOT_FOUND))
  {
    cgi_neo_error(cgi, err);
    nerr_warn_error(err);
    return -1;
  }
  /* Next, we look for an HDF file for this specific page.  We first look
   * for passedfile.html.hdf, then we check for a file by removing an extension
   * from the file, so something like passedfile.html we'll look for
   * passedfile.hdf */
  snprintf (hdf_file, sizeof(hdf_file), "%s.hdf", cs_file);
  err = hdf_read_file (cgi->hdf, hdf_file);
  if (err && !nerr_handle(&err, NERR_NOT_FOUND))
  {
    cgi_neo_error(cgi, err);
    nerr_warn_error(err);
    return -1;
  }
  p = strrchr (cs_file, '.');
  if (p)
  {
    *p = '\0';
    snprintf (hdf_file, sizeof(hdf_file), "%s.hdf", cs_file);
    *p = '.';
    err = hdf_read_file (cgi->hdf, hdf_file);
    if (err && !nerr_handle(&err, NERR_NOT_FOUND))
    {
      cgi_neo_error(cgi, err);
      nerr_warn_error(err);
      return -1;
    }
  }
  /* Lastly, we need to render a template.  The template is either the
   * file that was passed to us, or its specificed by CGI.StaticContent
   * in one of the HDF files we loaded above. */
  cs_file = hdf_get_value (cgi->hdf, "CGI.StaticContent", cs_file);
  err = cgi_display (cgi, cs_file);
  if (err != STATUS_OK)
  {
    cgi_neo_error(cgi, err);
    nerr_warn_error(err);
    return -1;
  }
  return 0;
}
コード例 #13
0
ファイル: tinyweb.c プロジェクト: sqwsummerwind/tinyweb
/*
处理cgi的内容
*/
void deal_cgi(int client_sock,char *path,char *method,char *query_string){
	
	int charnum=-1;
	char buf[1024];
	//请求的cgi的参数长度
	int content_len=-1;
	//也是参数长度
	char con_len[10];
	int cgi_output[2];
	int cgi_input[2];
	//进程号
	pid_t pid;
	//参数的内容
	char content[255];
	char c;
	int status;

	buf[0]='a';
	buf[1]='\0';
	//方法如果为post,不断读取剩下的内容并丢弃
	if(strcasecmp(method,"POST")==0){
		charnum=get_line(client_sock,buf,sizeof(buf));
		while(charnum>0 && strcmp(buf,"\n")){
			//找到content-length,获取参数内容的长度
			buf[15]='\0';
			if(strcmp(buf,"Content-Length:")==0){
				content_len=atoi(&buf[16]);
			}

			charnum=get_line(client_sock,buf,sizeof(buf));
		}

		if(content_len==-1){
			invalid_req(client_sock);
			return;
		}
		

	}
	
	//创建管道
	if(pipe(cgi_output)==-1){
		cgi_error(client_sock);
		return;
	}
	//创建管道
	if(pipe(cgi_input)==-1){
		cgi_error(client_sock);
		return;
	}
	//fork一个新的进程处理cgi
	if((pid=fork())==-1){
		cgi_error(client_sock);
		return;
	}

	sprintf(buf,"HTTP/1.0 200 OK\r\n");
	send(client_sock,buf,strlen(buf),0);

	//子进程
	if(pid==0){
		
		//把cgi_input的输出端重定向为stdin
		dup2(cgi_input[0],0);
		//把客户sock重定向为stdout
		dup2(client_sock,1);
		//分别关闭不使用的两个管道端口
		close(cgi_input[1]);
		close(cgi_output[0]);
		
		//设置环境变量,在cgi程序中可以获取
		setenv("REQUEST_METHOD",method,1);
		if(strcasecmp(method,"GET")==0)
			setenv("QUERY_STRING",query_string,1);
		else
			setenv("CONTENT_LENGTH",con_len,1);
		
		//使用exec系列函数调用cgi程序
		execl(path,path,NULL);
		exit(0);
	}
	else
	{
		
		close(cgi_input[0]);
		close(cgi_output[1]);
		
		if(strcasecmp(method,"POST")==0){
			//读取参数的内容,输出到管道中,cgi程序可以在管道中获取
			recv(client_sock,content,content_len,0);
			write(cgi_input[1],content,content_len);
			
		}
		//while(read(cgi_output[0],&c,1)>0)
			//send(client_sock,&c,1,0);

		close(cgi_output[0]);
		close(cgi_input[1]);

		waitpid(pid,&status,0);

	}

}
コード例 #14
0
void parse_cgi(void)
{
	cgidata_t *postdata, *pwalk;
	struct tm schedtm;
	struct tm endtm;
	struct tm nowtm;

	memset(&schedtm, 0, sizeof(schedtm));
	memset(&endtm, 0, sizeof(endtm));

	postdata = cgi_request();
	if (cgi_method == CGI_GET) return;

	if (!postdata) {
		errormsg(cgi_error());
	}

	pwalk = postdata;
	while (pwalk) {
		/*
		 * When handling the "go", the "Disable now" and "Schedule disable"
		 * radio buttons mess things up. So ignore the "go" if we have seen a
		 * "filter" request already.
		 */
		if ((strcmp(pwalk->name, "go") == 0) && (action != ACT_FILTER)) {
			if      (strcasecmp(pwalk->value, "enable") == 0)           action = ACT_ENABLE;
			else if (strcasecmp(pwalk->value, "disable now") == 0)      action = ACT_DISABLE;
			else if (strcasecmp(pwalk->value, "schedule disable") == 0) action = ACT_SCHED_DISABLE;
			else if (strcasecmp(pwalk->value, "cancel") == 0)           action = ACT_SCHED_CANCEL;
			else if (strcasecmp(pwalk->value, "apply filters") == 0)    action = ACT_FILTER;
		}
		else if ((strcmp(pwalk->name, "go2") == 0) && (action != ACT_FILTER)) { 
			if (strcasecmp(pwalk->value, "Disable until") == 0) disableend = DISABLE_UNTIL;
		}
		else if (strcmp(pwalk->name, "duration") == 0) {
			duration = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "untilok") == 0) {
			if (strcasecmp(pwalk->value, "on") == 0) {
				duration = -1;
				scale = 1;
			}
		}
		else if (strcmp(pwalk->name, "scale") == 0) {
			scale = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "cause") == 0) {
			disablemsg = strdup(pwalk->value);
		}
		else if (strcmp(pwalk->name, "hostname") == 0) {
			if (hostnames == NULL) {
				hostnames = (char **)malloc(2 * sizeof(char *));
				hostnames[0] = strdup(pwalk->value);
				hostnames[1] = NULL;
				hostcount = 1;
			}
			else {
				hostnames = (char **)realloc(hostnames, (hostcount + 2) * sizeof(char *));
				hostnames[hostcount] = strdup(pwalk->value);
				hostnames[hostcount+1] = NULL;
				hostcount++;
			}
		}
		else if (strcmp(pwalk->name, "enabletest") == 0) {
			char *val = pwalk->value;

			if (strcmp(val, "ALL") == 0) val = "*";

			if (enabletest == NULL) {
				enabletest = (char **)malloc(2 * sizeof(char *));
				enabletest[0] = strdup(val);
				enabletest[1] = NULL;
				enablecount = 1;
			}
			else {
				enabletest = (char **)realloc(enabletest, (enablecount + 2) * sizeof(char *));
				enabletest[enablecount] = strdup(val);
				enabletest[enablecount+1] = NULL;
				enablecount++;
			}
		}
		else if (strcmp(pwalk->name, "disabletest") == 0) {
			char *val = pwalk->value;

			if (strcmp(val, "ALL") == 0) val = "*";

			if (disabletest == NULL) {
				disabletest = (char **)malloc(2 * sizeof(char *));
				disabletest[0] = strdup(val);
				disabletest[1] = NULL;
				disablecount = 1;
			}
			else {
				disabletest = (char **)realloc(disabletest, (disablecount + 2) * sizeof(char *));
				disabletest[disablecount] = strdup(val);
				disabletest[disablecount+1] = NULL;
				disablecount++;
			}
		}
		else if (strcmp(pwalk->name, "year") == 0) {
			schedtm.tm_year = atoi(pwalk->value) - 1900;
		}
		else if (strcmp(pwalk->name, "month") == 0) {
			schedtm.tm_mon = atoi(pwalk->value) - 1;
		}
		else if (strcmp(pwalk->name, "day") == 0) {
			schedtm.tm_mday = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "hour") == 0) {
			schedtm.tm_hour = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "minute") == 0) {
			schedtm.tm_min = atoi(pwalk->value);
		}

		/* Until start */
		else if (strcmp(pwalk->name, "endyear") == 0) {
			endtm.tm_year = atoi(pwalk->value) - 1900;
		}
		else if (strcmp(pwalk->name, "endmonth") == 0) {
			endtm.tm_mon = atoi(pwalk->value) - 1;
		}
		else if (strcmp(pwalk->name, "endday") == 0) {
			endtm.tm_mday = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "endhour") == 0) {
			endtm.tm_hour = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "endminute") == 0) {
			endtm.tm_min = atoi(pwalk->value);
		}
		/* Until end */

		else if (strcmp(pwalk->name, "canceljob") == 0) {
			cancelid = atoi(pwalk->value);
		}
		else if (strcmp(pwalk->name, "preview") == 0) {
			preview = (strcasecmp(pwalk->value, "on") == 0);
		}
		else if ((strcmp(pwalk->name, "hostpattern") == 0) && pwalk->value && strlen(pwalk->value)) {
			hostpattern = strdup(pwalk->value);
		}
		else if ((strcmp(pwalk->name, "pagepattern") == 0) && pwalk->value && strlen(pwalk->value)) {
			pagepattern = strdup(pwalk->value);
		}
		else if ((strcmp(pwalk->name, "ippattern") == 0)   && pwalk->value && strlen(pwalk->value)) {
			ippattern = strdup(pwalk->value);
		}

		pwalk = pwalk->next;
	}

	schedtm.tm_isdst = -1;
	schedtime = mktime(&schedtm);
	endtm.tm_isdst = -1;
	endtime = mktime(&endtm);
}
コード例 #15
0
ファイル: fcgiwrap.c プロジェクト: Lekensteyn/fcgiwrap
static void handle_fcgi_request(void)
{
	int pipe_in[2];
	int pipe_out[2];
	int pipe_err[2];
	char *filename;
	char *last_slash;
	char *p;
	pid_t pid;

	struct fcgi_context fc;

	if (pipe(pipe_in) < 0) goto err_pipein;
	if (pipe(pipe_out) < 0) goto err_pipeout;
	if (pipe(pipe_err) < 0) goto err_pipeerr;

	switch((pid = fork())) {
		case -1:
			goto err_fork;

		case 0: /* child */
			close(pipe_in[1]);
			close(pipe_out[0]);
			close(pipe_err[0]);

			dup2(pipe_in[0], 0);
			dup2(pipe_out[1], 1);
			dup2(pipe_err[1], 2);

			close(pipe_in[0]);
			close(pipe_out[1]);
			close(pipe_err[1]);

			close(FCGI_fileno(FCGI_stdout));

			signal(SIGCHLD, SIG_DFL);
			signal(SIGPIPE, SIG_DFL);

			filename = get_cgi_filename();
			inherit_environment();
			if (!filename)
				cgi_error("403 Forbidden", "Cannot get script name, are DOCUMENT_ROOT and SCRIPT_NAME (or SCRIPT_FILENAME) set and is the script executable?", NULL);

			if (!is_allowed_program(filename))
				cgi_error("403 Forbidden", "The given script is not allowed to execute", filename);

			p = getenv("FCGI_CHDIR");
			if (p == NULL) {
				last_slash = strrchr(filename, '/');
				if (!last_slash)
					cgi_error("403 Forbidden", "Script name must be a fully qualified path", filename);

				*last_slash = 0;
				if (chdir(filename) < 0)
					cgi_error("403 Forbidden", "Cannot chdir to script directory", filename);

				*last_slash = '/';
			} else if (strcmp(p, "-") != 0) {
				if (chdir(p) < 0) {
					cgi_error("403 Forbidden", "Cannot chdir to FCGI_CHDIR directory", p);
				}
			}

			execl(filename, filename, (void *)NULL);
			cgi_error("502 Bad Gateway", "Cannot execute script", filename);

		default: /* parent */
			close(pipe_in[0]);
			close(pipe_out[1]);
			close(pipe_err[1]);

			fc.fd_stdin = pipe_in[1];
			fc.fd_stdout = pipe_out[0];
			fc.fd_stderr = pipe_err[0];
			fc.reply_state = REPLY_STATE_INIT;
			fc.cgi_pid = pid;

			fcgi_pass(&fc);
	}
	return;

err_fork:
	close(pipe_err[0]);
	close(pipe_err[1]);

err_pipeerr:
	close(pipe_out[0]);
	close(pipe_out[1]);

err_pipeout:
	close(pipe_in[0]);
	close(pipe_in[1]);

err_pipein:

	FCGI_puts("Status: 502 Bad Gateway\nContent-type: text/plain\n");
	FCGI_puts("System error");
}
コード例 #16
0
ファイル: user-stats-day.c プロジェクト: fm4dd/edacs
int cgiMain() {

  char router[16]          ="";   /* selected router IP address */
  char title[256]          ="";   /* cgi title string */
  char type[4]             ="";   /* selected image type [upd|apd] */
  int i;                          /* loop counter */

  if ( cgiFormString("router", router, sizeof(router)) != cgiFormSuccess )
      cgi_error("Error retrieving the IP address of the router.");
  if ( cgiFormString("type", type, sizeof(type)) != cgiFormSuccess )
      cgi_error("Error retrieving the image type information.");

  if(strcmp(type,"upd") == 0)
     snprintf(title, sizeof(title), "Daily User Statistics for Router %s", router);
  else if(strcmp(type,"apd") == 0)
     snprintf(title, sizeof(title), "Daily Data per User for Router %s", router);
  else cgi_error("Error image type is invalid.");

/* -------------------------------------------------------------------------- *
 * start the html output                                                      *
 * ---------------------------------------------------------------------------*/

  pagehead(title);
  fprintf(cgiOut, "<div id=\"content\">\n");

  fprintf(cgiOut, "<table class=\"inner\" width=100%%>\n");
  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th class=\"inner\">#</th>\n");
  if(strcmp(type,"upd") == 0)
    fprintf(cgiOut, "<th class=\"inner\">Unique Users/Day</th>\n");
  else if(strcmp(type,"apd") == 0)
    fprintf(cgiOut, "<th class=\"inner\">Average Data per User/Day</th>\n");
  fprintf(cgiOut, "</tr>\n");

  for(i=0;i<DAYSTATS_HIST; i++) {
    fprintf(cgiOut, "<tr>\n");
    fprintf(cgiOut, "<th class=\"inner\" width=20>%d</th>\n", i+1);
    fprintf(cgiOut, "<td class=\"inner\">");
    if(strcmp(type,"upd") == 0)
      fprintf(cgiOut, "<img src=\"../images/usercount-mon%d-%s.png\" border=0>", i, router);
    else if(strcmp(type,"apd") == 0)
      fprintf(cgiOut, "<img src=\"../images/avgbytes-mon%d-%s.png\" border=0>", i, router);
    fprintf(cgiOut, "</td>");
    fprintf(cgiOut, "</tr>\n");
  }

  fprintf(cgiOut, "<tr>\n");
  fprintf(cgiOut, "<th class=\"inner\" colspan=3>&nbsp;</th>");
  fprintf(cgiOut, "</tr>\n");
  fprintf(cgiOut, "</table>\n");

  fprintf(cgiOut, "<h3>Additional information</h3>\n");
  fprintf(cgiOut, "<hr>\n");
  fprintf(cgiOut, "<p>");
  if(strcmp(type,"upd") == 0) {
    fprintf(cgiOut, "This page shows the daily summary for unique users per router");
    fprintf(cgiOut, "<ul>");
    fprintf(cgiOut, "<li>The number of connections is a summary of all unique users on this router, per day.");
  }
  else if(strcmp(type,"apd") == 0) {
    fprintf(cgiOut, "This page shows the daily summary of the average transfered data per user.");
    fprintf(cgiOut, "<ul>");
    fprintf(cgiOut, "<li>The data transfer is the summary of all data in and data out, calculated as the average per user.");
  }
  fprintf(cgiOut, "<li>The graphs are pre-generated on the web server by edacs-chartsgen, which runs through cron.");
  fprintf(cgiOut, "</ul>");
  fprintf(cgiOut, "</p>\n");

  pageside();
  pagefoot();
  return(0);
}