Beispiel #1
0
bool
account_deny_char_entry(struct account *account, struct creature *ch)
{
    // Admins and full wizards can multi-play all they want
    if (is_authorized(ch, MULTIPLAY, NULL))
        return false;

    bool override = false;
    bool found = false;

    for (GList *it = first_living(creatures);it;it = next_living(it)) {
        struct creature *tch = it->data;

        if (tch->account == account) {
            // Admins and full wizards can multi-play all they want
            if (is_authorized(ch, MULTIPLAY, NULL))
                override = true;
            // builder can have on a tester and vice versa.
            if (is_authorized(ch, LOGIN_WITH_TESTER, NULL) && is_tester(tch))
                override = true;
            if (is_tester(ch) && is_authorized(tch, LOGIN_WITH_TESTER, NULL))
                override = true;
            // We have a non-immortal already in the game, so they don't
            // get to come in
            found = true;
        }
    }
    if (override)
        return false;

    return found;
}
Beispiel #2
0
// Returns true if a creature can see another creature
bool
check_sight_vict(struct creature * self, struct creature * vict)
{
    // Immortals players can always see non-immortal players
    if (IS_IMMORT(self) && !IS_IMMORT(vict))
        return true;

    // Nothing at all gets through immort invis
    if (IS_PC(self) && IS_IMMORT(vict)
        && GET_LEVEL(self) < GET_INVIS_LVL(vict))
        return false;

    // Mortals can't see unapproved mobs
    if (!NPC2_FLAGGED(self, NPC2_UNAPPROVED) &&
        NPC2_FLAGGED(vict, NPC2_UNAPPROVED) &&
        !IS_IMMORT(self) && !is_authorized(self, TESTER, NULL))
        return false;

    // Non-tester mortal players can't see testers
    if (!IS_IMMORT(self)
        && !IS_NPC(self)
        && !IS_IMMORT(vict)
        && !is_authorized(self, TESTER, NULL)
        && is_authorized(vict, TESTER, NULL))
        return false;

    // Holy is the light that shines on the chosen
    if (PRF_FLAGGED(self, PRF_HOLYLIGHT))
        return true;

    // Sonic imagery and retina detects transparent creatures
    if (AFF2_FLAGGED(vict, AFF2_TRANSPARENT) &&
        !(AFF3_FLAGGED(self, AFF3_SONIC_IMAGERY) ||
            AFF_FLAGGED(self, AFF_RETINA) ||
            affected_by_spell(self, ZEN_AWARENESS)))
        return false;

    // True seeing and detect invisibility counteract all magical invis
    if (AFF2_FLAGGED(self, AFF2_TRUE_SEEING) ||
        AFF_FLAGGED(self, AFF_DETECT_INVIS))
        return true;

    // Invis/Transparent
    if (AFF_FLAGGED(vict, AFF_INVISIBLE))
        return false;

    // Invis to Undead
    if (IS_UNDEAD(self) && AFF2_FLAGGED(vict, AFF2_INVIS_TO_UNDEAD))
        return false;

    return true;
}
Beispiel #3
0
static void handle_upnp_http_request(struct ezcfg_worker *worker)
{
	struct ezcfg *ezcfg;
	struct ezcfg_http *http;
	char *request_uri;

	ASSERT(worker != NULL);

	http = (struct ezcfg_http *)ezcfg_worker_get_proto_data(worker);
	ASSERT(http != NULL);

	ezcfg = ezcfg_worker_get_ezcfg(worker);

	request_uri = ezcfg_http_get_request_uri(http);
	if (request_uri == NULL) {
		err(ezcfg, "no request uri for HTTP GET method.\n");
		send_http_bad_request(worker);
		return;
	}

	if (need_authorization(request_uri) == true &&
	    is_authorized(worker) == false) {
		/* handle authorization */
		handle_auth_request(worker);
		return ;
	}

	/* don't need authenticate or has been authenticated */
	/* handle SSI enabled web page */
	handle_ssi_request(worker);
}
Beispiel #4
0
// Returns true if a creature can see an object
bool
check_sight_object(struct creature * self, struct obj_data * obj)
{
    if (PRF_FLAGGED(self, PRF_HOLYLIGHT))
        return true;

    if (!OBJ_APPROVED(obj) && !NPC2_FLAGGED(self, NPC2_UNAPPROVED) &&
        !IS_IMMORT(self) && !is_authorized(self, TESTER, NULL))
        return false;

    if (IS_OBJ_STAT(obj, ITEM_TRANSPARENT) &&
        !(AFF3_FLAGGED(self, AFF3_SONIC_IMAGERY) ||
            AFF_FLAGGED(self, AFF_RETINA) ||
            affected_by_spell(self, ZEN_AWARENESS)))
        return false;

    if (AFF_FLAGGED(self, AFF_DETECT_INVIS) ||
        AFF2_FLAGGED(self, AFF2_TRUE_SEEING))
        return true;

    if (IS_OBJ_STAT(obj, ITEM_INVISIBLE))
        return false;

    return true;
}
Beispiel #5
0
int
ref_mon(
	rpc_binding_handle_t		bind_handle,
	int				requested_op)
{
	int				ret;
	rpc_authz_handle_t		privs;
	unsigned_char_t			*client_princ_name, *server_princ_name;
	unsigned32			protect_level, authn_svc, authz_svc,
	                                    status;


	/* Get client auth info. */
	rpc_binding_inq_auth_client(bind_handle, &privs, &server_princ_name,
	    &protect_level, &authn_svc, &authz_svc, &status);
	if (status != rpc_s_ok) {
		fprintf(stderr, "FAULT: %s:%d\n", __FILE__, __LINE__);
		return(DENY_ACCESS);
	}

	/* Check if selected authn service is acceptable to us. */
	if (authn_svc != rpc_c_authn_dce_secret) {
		fprintf(stderr, "FAULT: %s:%d\n", __FILE__, __LINE__);
		return(DENY_ACCESS);
	}

	/* Check if selected protection level is acceptable to us. */
	if (protect_level != rpc_c_protect_level_pkt_integ
	&&  protect_level != rpc_c_protect_level_pkt_privacy) {
		fprintf(stderr, "FAULT: %s:%d\n", __FILE__, __LINE__);
		return(DENY_ACCESS);
	}

	/* Check if selected authz service is acceptable to us. */
	if (authz_svc != rpc_c_authz_name) {
		fprintf(stderr, "FAULT: %s:%d\n", __FILE__, __LINE__);
		return(DENY_ACCESS);
	}
	/* If rpc_c_authz_dce were being used instead of rpc_c_authz_name,
	   privs would be a PAC (sec_id_pac_t *), not a name as it is here. */
	client_princ_name = (unsigned_char_t *)privs;

	/* Check if selected server principal name is supported. */
        fprintf(stderr, "%s %s\n", server_princ_name, SERVER_PRINC_NAME );
	if (strcmp(server_princ_name, SERVER_PRINC_NAME) != 0) {
		fprintf(stderr, "FAULT: %s:%d\n", __FILE__, __LINE__);
		return(DENY_ACCESS);
	}

	/* Now that things seem generally OK, check the specifics. */
	ret = is_authorized(client_princ_name, requested_op);
	if (ret == NOT_AUTHORIZED) {
		fprintf(stderr, "FAULT: %s:%d\n", __FILE__, __LINE__);
		return(DENY_ACCESS);
	}

	/* Cleared all the authorization hurdles -- grant access. */
	return(GRANT_ACCESS);
}
Beispiel #6
0
static xmlrpc_value *freeswitch_api(xmlrpc_env * const envP, xmlrpc_value * const paramArrayP, void *const userData, void *const callInfo)
{
	char *command = NULL, *arg = NULL;
	switch_stream_handle_t stream = { 0 };
	xmlrpc_value *val = NULL;
	switch_bool_t freed = 0;


	/* Parse our argument array. */
	xmlrpc_decompose_value(envP, paramArrayP, "(ss)", &command, &arg);

	if (envP->fault_occurred) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Request!\n");
		return NULL;
	}

	if (!is_authorized((const TSession *) callInfo, command)) {
		val = xmlrpc_build_value(envP, "s", "UNAUTHORIZED!");
		goto end;
	}

	if (switch_stristr("unload", command) && switch_stristr("mod_xml_rpc", arg)) {
		switch_safe_free(command);
		switch_safe_free(arg);
		freed = 1;
		command = "bgapi";
		arg = "unload mod_xml_rpc";
	} else if (switch_stristr("reload", command) && switch_stristr("mod_xml_rpc", arg)) {
		switch_safe_free(command);
		switch_safe_free(arg);
		freed = 1;
		command = "bgapi";
		arg = "reload mod_xml_rpc";
	}

	SWITCH_STANDARD_STREAM(stream);
	if (switch_api_execute(command, arg, NULL, &stream) == SWITCH_STATUS_SUCCESS) {
		/* Return our result. */
		val = xmlrpc_build_value(envP, "s", stream.data);
		free(stream.data);
	} else {
		val = xmlrpc_build_value(envP, "s", "ERROR!");
	}

  end:

	/* xmlrpc-c requires us to free memory it malloced from xmlrpc_decompose_value */
	if (!freed) {
		switch_safe_free(command);
		switch_safe_free(arg);
	}

	return val;
}
Beispiel #7
0
void Server::event_handler(struct mg_connection *conn, int ev, void *p) {
	struct http_message *hm = (struct http_message *) p;

	if (ev == MG_EV_SSI_CALL) {
		mbuf_resize(&conn->send_mbuf, conn->send_mbuf.size * 2);
		std::string resp(conn->send_mbuf.buf, conn->send_mbuf.len);
		boost::replace_all(resp, "href=\"/", std::string("href=\"") + CONFIG_STRING(m_config, "service.base_location"));
		boost::replace_all(resp, "src=\"/", std::string("src=\"") + CONFIG_STRING(m_config, "service.base_location"));
		boost::replace_all(resp, "action=\"/", std::string("action=\"") + CONFIG_STRING(m_config, "service.base_location"));
		strcpy(conn->send_mbuf.buf, resp.c_str());
		mbuf_trim(&conn->send_mbuf);
		return;
	}

	if (ev != MG_EV_HTTP_REQUEST) {
		return;
	}

	hm->uri.p += CONFIG_STRING(m_config, "service.base_location").size() - 1;
	hm->uri.len -= CONFIG_STRING(m_config, "service.base_location").size() - 1;

	if (!is_authorized(conn, hm)) {
		redirect_to(conn, hm, "/login");
	} else if (mg_vcmp(&hm->uri, "/authorize") == 0) {
		authorize(conn, hm);
	} else if (mg_vcmp(&hm->uri, "/logout") == 0) {
		serve_logout(conn, hm);
// 	} else if (mg_vcmp(&hm->uri, "/users") == 0) {
// 		serve_users(conn, hm);
// 	} else if (mg_vcmp(&hm->uri, "/users/add") == 0) {
// 		serve_users_add(conn, hm);
// 	} else if (mg_vcmp(&hm->uri, "/users/remove") == 0) {
// 		serve_users_remove(conn, hm);
	} else if (has_prefix(&hm->uri, "/oauth2")) {
		serve_oauth2(conn, hm);
	} else if (has_prefix(&hm->uri, "/api/v1/")) {
		m_apiServer->handleRequest(this, get_session(hm), conn, hm);
	} else {
		if (hm->uri.p[hm->uri.len - 1] != '/') {
			std::string url(hm->uri.p, hm->uri.len);
			if (url.find(".") == std::string::npos) {
				url += "/";
				redirect_to(conn, hm, url.c_str());
				conn->flags |= MG_F_SEND_AND_CLOSE;
				return;
			}
		}
		mg_serve_http(conn, hm, s_http_server_opts);
	}

	conn->flags |= MG_F_SEND_AND_CLOSE;
}
Beispiel #8
0
static int begin_request_handler(struct mg_connection *conn) {
  const struct mg_request_info *request_info = mg_get_request_info(conn);
  int processed = 1;

  if (!request_info->is_ssl) {
    redirect_to_ssl(conn, request_info);
  } else if (!is_authorized(conn, request_info)) {
    redirect_to_login(conn, request_info);
  } else if (strcmp(request_info->uri, authorize_url) == 0) {
    authorize(conn, request_info);
  } else if (strcmp(request_info->uri, "/ajax/get_messages") == 0) {
    ajax_get_messages(conn, request_info);
  } else if (strcmp(request_info->uri, "/ajax/send_message") == 0) {
    ajax_send_message(conn, request_info);
  } else {
    // No suitable handler found, mark as not processed. Civetweb will
    // try to serve the request.
    processed = 0;
  }
  return processed;
}
Beispiel #9
0
Datei: control.c Projekt: DPMI/mp
static void CIstatus(int sig){ // Runs when ever a ALRM signal is received.
	if( !is_authorized() ){
		logmsg(verbose, CONTROL, "Not authorized. No need to inform MArC about the status.\n");
		return;
	}

	//Populate statistics.
	CIstatusExtended();

	/* Compare with previous stats */
	static struct MPstats prev = {0,};
	struct MPstats delta = {
		.packet_count  = MPstats->packet_count  - prev.packet_count,
		.matched_count = MPstats->matched_count - prev.matched_count,
		.dropped_count = MPstats->dropped_count - prev.dropped_count,
	};
	prev = *MPstats;

	/* Logging */
	logmsg(stderr, CONTROL, "Status report for %s\n"
	       "\t%zd Filters present\n"
	       "\t%d Capture Interfaces.\n"
	       "\t%ld Packets received (%ld new).\n"
	       "\t%ld Packets matched (%ld new).\n"
	       "\t%ld Packets dropped (%ld new).\n",
	       mampid_get(MPinfo->id), mprules_count(), noCI,
	       MPstats->packet_count, delta.packet_count,
	       MPstats->matched_count, delta.matched_count,
	       MPstats->dropped_count, delta.dropped_count);

	char* last_tick;
	for( int i=0; i < noCI; i++){
		const int u = buffer_utilization(&_CI[i]);
		const float BU = (float)u / PKT_BUFFER;
		fprintf(stderr, "\tCI[%d]=%s  PKT=%ld  MCH=%ld  DRP=%ld BU=%.1f%% (%d of %d)\n", i,
		        _CI[i].iface,
		        _CI[i].packet_count,
		        _CI[i].matched_count,
		        _CI[i].dropped_count,
		        BU*100.0f, u, PKT_BUFFER);
		// Handle syncronization status
		
		if(_CI[i].synchronized=='N'){
		  fprintf(stderr,"\tNot Synchronized: ");
		} else if (_CI[i].synchronized=='Y'){
		  fprintf(stderr,"\tSynchronized: ");
		} else {
		  fprintf(stderr,"\tUndefined: ");
		}
		fprintf(stderr," Frequency %dHz \n",_CI[i].frequency);
		last_tick = ctime(&_CI[i].hosttime);
		fprintf(stderr,"\tHost:%s", last_tick);
		last_tick = ctime(&_CI[i].citime);
		fprintf(stderr,"\tCI:%s", last_tick);
		/*
		if(strncmp(_CI[i].iface,"dag",3)==0){
		  
		} else {

		}
		*/
		fprintf(stderr,"\n");
	}

	if ( mprules_count() == 0 ){
		logmsg(stderr, CONTROL, "Warning: no filters present.\n");
	}
}

static volatile sig_atomic_t fatal_error_in_progress = 0;
static void distress(int sig){
	MPMessage event;
	int ret;

	/* http://www.gnu.org/s/libc/manual/html_node/Termination-in-Handler.html */
	if ( fatal_error_in_progress ){
		raise(sig);
	}
	fatal_error_in_progress = 1;

	logmsg(stderr, CONTROL, "\n\n\n-----------------------------------------------------------------------------------------------\n");

	if ( sig > 0 ){
		logmsg(stderr, CONTROL, "Got fatal signal (%d), sending distress signal to MArCd before dying.\n", sig);
	} else {
		logmsg(stderr, CONTROL, "Assertion fired, sending distress signal to MArCd before dying.\n");
	}

	extern char commandline[];
	logmsg(stderr, CONTROL, "  This is a bug. Please report it to \n");
	logmsg(stderr, CONTROL, "  " PACKAGE_BUGREPORT "\n");
	logmsg(stderr, CONTROL, "\n");
	logmsg(stderr, CONTROL, "  Make sure you include:\n");
	logmsg(stderr, CONTROL, "    - the full message,\n");
	logmsg(stderr, CONTROL, "    - a short description of what happened,\n");
	logmsg(stderr, CONTROL, "    - compiler version (e.g. gcc --version),\n");
	logmsg(stderr, CONTROL, "    - libc version (e.g. ldd --version),\n");
	logmsg(stderr, CONTROL, "    - kernel version (e.g. uname -a),\n");
	logmsg(stderr, CONTROL, "    - MP-" VERSION " (caputils-%s)\n",  caputils_version(NULL));
	logmsg(stderr, CONTROL, "    - commandline: %s\n", commandline);
	logmsg(stderr, CONTROL, "    - if possible, use gdb and execute `bt' and `info threads'.\n");
	logmsg(stderr, CONTROL, "\n");
	logmsg(stderr, CONTROL, "  If using git please include the output of the following commands:\n");
	logmsg(stderr, CONTROL, "    - git status --short --porcelain\n");
	logmsg(stderr, CONTROL, "    - git rev-parse --short HEAD\n");
	logmsg(stderr, CONTROL, "    - git rev-parse --abbrev-ref HEAD\n");

	event.type = MP_CONTROL_DISTRESS;
	mampid_set(event.MAMPid, MPinfo->id);

	if ( (ret=marc_push_event(client, (MPMessage*)&event, NULL)) != 0 ){
		logmsg(stderr, CONTROL, "marc_push_event() returned %d: %s\n", ret, strerror(ret));
	}

	/* if distress is called, it is a fatal error so lets die here. */
	if ( sig != 0 ){
		signal(sig, SIG_DFL);
		raise(sig);
	}
}
Beispiel #10
0
Datei: control.c Projekt: DPMI/mp
void* control(struct thread_data* td, void* prt){
	int ret;

	/* redirect output */
	marc_set_output_handler(output_wrapper_n, output_wrapper_v, stderr, verbose);

	/* get version of libcap_utils */
	caputils_version_t cv;
	caputils_version(&cv);

	/* setup libmarc */
	struct marc_client_info info = {0,};
	info.client_ip = NULL;
	info.server_ip = marc_ip;
	info.client_port = port;
	info.max_filters = MAX_FILTERS;
	info.noCI = noCI;
	info.ma_mtu = MPinfo->MTU;
	info.version.caputils.major = cv.major;
	info.version.caputils.minor = cv.minor;
	info.version.caputils.micro = cv.micro;
	info.version.self.major = VERSION_MAJOR;
	info.version.self.minor = VERSION_MINOR;
	info.version.self.micro = VERSION_MICRO;

	info.drivers = 0;
#ifdef HAVE_DRIVER_RAW
	info.drivers |= 1;
#endif
#ifdef HAVE_DRIVER_PCAP
	info.drivers |= 2;
#endif
#if defined(HAVE_DRIVER_DAG) || defined(HAVE_DRIVER_DAG_LEGACY)
	info.drivers |= 4;
#endif

	for ( int i = 0; i < noCI; i++ ){
		strncpy(info.CI[i].iface, _CI[i].iface, 8);
	}

	if ( (ret=marc_init_client(&client, MPinfo->iface, &info)) != 0 ){
		fprintf(stderr, "marc_init_client() returned %d: %s\n", ret, strerror(ret));
		thread_init_finished(td, ret);
		return NULL;
	}
	logmsg(verbose, CONTROL, "Listening on %s:%d.\n", info.client_ip, info.client_port);

	/* setup status ALRM handler */
	{
		/* unblock SIGALRM in case it was blocked (LinuxThreads seems to inhibit this behaviour) */
		sigset_t sigmask;
		sigemptyset(&sigmask);
		sigaddset(&sigmask, SIGALRM);
		pthread_sigmask(SIG_UNBLOCK, &sigmask, NULL);

		/* timer */
		struct itimerval difftime;
		difftime.it_interval.tv_sec = STATUS_INTERVAL;
		difftime.it_interval.tv_usec = 0;
		difftime.it_value.tv_sec = STATUS_INTERVAL;
		difftime.it_value.tv_usec = 0;
		signal(SIGALRM, CIstatus);
		setitimer(ITIMER_REAL, &difftime, NULL);
	}

	/* Catch various signals to send a distress signal to MArCd */
	signal(SIGSEGV, distress);
	signal(SIGBUS, distress);
	signal(SIGILL, distress);

	thread_init_finished(td, 0);

	/* process messages from MArCd */
	MPMessage event;
	size_t size;
	int auth_retry = 0;
	while( terminateThreads==0 ){
		struct timeval timeout = {1, 0}; /* 1 sec timeout */

		if ( !is_authorized() && auth_retry >= 15 ){
			logmsg(stderr, CONTROL, "No reply from MArCd (make sure MArCd is running). Resending request.\n");
			marc_client_init_request(client, &info);
			auth_retry = 0;
		}

		/* get next message */
		switch ( (ret=marc_poll_event(client, &event, &size, NULL, NULL, &timeout)) ){
		case EAGAIN: /* delivered if using a timeout */
		case EINTR:  /* interuped */
			if ( auth_retry >= 0 ){
				auth_retry++;
			}
			continue;

		case 0: /* success, continue processing */
			/* always handle authorization event */
			if ( event.type == MP_CONTROL_AUTHORIZE_EVENT || event.type == MP_CONTROL_AUTHORIZE_REQUEST ){
				break;
			}

			/* only handle other events if authorized */
			if ( !is_authorized() ){
				logmsg(verbose, CONTROL, "MP not authorized, ignoring message of type %d\n", event.type);
				continue;
			}

			break;

		default: /* error has been raised */
			fprintf(stderr, "marc_poll_event() returned %d: %s\n", ret, strerror(ret));
			return NULL;
		}

		if ( debug_flag ){
			logmsg(verbose, CONTROL, "Got message %d (%zd bytes) from MArCd.\n", event.type, size);
		}

		/* act */
		switch (event.type) { /* ntohl not needed, called by marc_poll_event */
		case MP_CONTROL_AUTHORIZE_EVENT:
			mp_auth(&event.auth);
			auth_retry = -1;
			break;

		case MP_CONTROL_AUTHORIZE_REQUEST:
			logmsg(verbose, CONTROL, "Got an authorization request, asking MArCd for a new authorization message.\n");
			marc_client_init_request(client, &info);
			break;

		case MP_FILTER_EVENT:
			mp_filter(&event.filter, size);
			break;

		case MP_FILTER_RELOAD_EVENT:
			mp_filter_reload(ntohl(event.filter_id.id));
			break;

		case MP_FILTER_DEL_EVENT:
			mp_filter_del(ntohl(event.filter_id.id));
			break;

		case MP_FILTER_REQUEST_EVENT:
			mp_filter_reload(ntohl(event.filter_id.id));
			break;

		case MP_FILTER_INVALID_ID:
			logmsg(verbose, CONTROL, "Filter request failed: invalid id\n");
			break;

		case MP_CONTROL_TERMINATE_EVENT:
			logmsg(stderr, CONTROL, "Got termination request\n");
			terminateThreads = 1;
			break;

		default:
			logmsg(verbose, CONTROL, "Got unhandled event of type %d containing %zd bytes (including header).\n", event.type, size);
			logmsg(verbose, CONTROL, "PAYLOAD (%zd bytes):\n", size-4-sizeof(mampid_t));
			hexdump(verbose, event.payload, size-4-sizeof(mampid_t));
			break;
		}
	}

	/* inform MArCd that MP is terminating (properly) */
	{
		MPMessage ev;
		ev.type = MP_CONTROL_TERMINATE_EVENT;
		mampid_set(ev.MAMPid, MPinfo->id);
		if ( (ret=marc_push_event(client, &ev, NULL)) != 0 ){
			logmsg(stderr, CONTROL, "marc_push_event() returned %d: %s\n", ret, strerror(ret));
		}
	}

	marc_cleanup(client);
	client = NULL;

	return NULL;
}
Beispiel #11
0
static int handle_lua_request(struct mg_connection *conn) {
  struct mg_request_info *request_info = mg_get_request_info(conn);
  u_int len = (u_int)strlen(request_info->uri);
  char username[33] = { 0 };

  if((ntop->getGlobals()->isShutdown())
     //|| (strcmp(request_info->request_method, "GET"))
     || (ntop->getRedis() == NULL /* Starting up... */))
    return(send_error(conn, 403 /* Forbidden */, request_info->uri, 
		      "Unexpected HTTP method or ntopng still starting up..."));

  if(ntop->get_HTTPserver()->is_ssl_enabled() && (!request_info->is_ssl))
    redirect_to_ssl(conn, request_info);

  if(enable_users_login) {
    if((len > 4)
       && ((strcmp(&request_info->uri[len-4], ".css") == 0)
	   || (strcmp(&request_info->uri[len-3], ".js")) == 0))
      ;
    else if(!is_authorized(conn, request_info, username)) {
      redirect_to_login(conn, request_info);
      return(1);
    } else if(strcmp(request_info->uri, AUTHORIZE_URL) == 0) {
      authorize(conn, request_info);
      return(1);
    }
  }

  ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] %s", request_info->uri);

  if(strstr(request_info->uri, "//")
     || strstr(request_info->uri, "&&")
     || strstr(request_info->uri, "??")
     || strstr(request_info->uri, "..")) {
    ntop->getTrace()->traceEvent(TRACE_WARNING, "[HTTP] The URL %s is invalid/dangerous",
				 request_info->uri);
    return(send_error(conn, 400 /* Bad Request */, request_info->uri,
		      "The URL specified contains invalid/dangerous characters"));
  }

  if((strncmp(request_info->uri, "/lua/", 5) == 0)
     || (strcmp(request_info->uri, "/") == 0)) {
    /* Lua Script */
    char path[255] = { 0 }, uri[2048];
    struct stat buf;

    snprintf(path, sizeof(path), "%s%s", httpserver->get_scripts_dir(),
	     (strlen(request_info->uri) == 1) ? "/lua/index.lua" : request_info->uri);

    ntop->fixPath(path);
    if((stat(path, &buf) == 0) && (S_ISREG (buf.st_mode))) {
      Lua *l = new Lua();

      ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] %s [%s]", request_info->uri, path);

      if(l == NULL) {
	ntop->getTrace()->traceEvent(TRACE_ERROR, "[HTTP] Unable to start Lua interpreter");
	return(send_error(conn, 500 /* Internal server error */,
			  "Internal server error", "%s", "Unable to start Lua interpreter"));
      } else {
	l->handle_script_request(conn, request_info, path);
	delete l;
	return(1); /* Handled */
      }
    }

    uri_encode(request_info->uri, uri, sizeof(uri)-1);

    return(send_error(conn, 404, "Not Found", PAGE_NOT_FOUND, uri));
  } else {
    ntop->getTrace()->traceEvent(TRACE_INFO, "[HTTP] Serving file %s%s", 
				 ntop->get_HTTPserver()->get_docs_dir(), request_info->uri);
    return(0); /* This is a static document so let mongoose handle it */
  }
}
Beispiel #12
0
abyss_bool handler_hook(TSession * r)
{
	switch_stream_handle_t stream = { 0 };
	char *command;
	int i;
	char *fs_user = NULL, *fs_domain = NULL;
	char *path_info = NULL;
	abyss_bool ret = TRUE;
	int html = 0, text = 0, xml = 0, api = 0;
	const char *api_str;
	const char *uri = 0;
	TRequestInfo *info = 0;
	switch_event_t *evnt = 0; /* shortcut to stream.param_event */

	if (!r || !(info = &r->requestInfo) || !(uri = info->uri)) {
		return FALSE;
	}

	stream.data = r;
	stream.write_function = http_stream_write;
	stream.raw_write_function = http_stream_raw_write;

	if ((command = strstr(uri, "/api/"))) {
		command += 5;
		api++;
	} else if ((command = strstr(uri, "/webapi/"))) {
		command += 8;
		html++;
	} else if ((command = strstr(uri, "/txtapi/"))) {
		command += 8;
		text++;
	} else if ((command = strstr(uri, "/xmlapi/"))) {
		command += 8;
		xml++;
	} else {
		return FALSE; /* 404 */
	}

	if ((path_info = strchr(command, '/'))) {
		*path_info++ = '\0';
	}

	for (i = 0; i < r->responseHeaderFields.size; i++) {
		TTableItem *ti = &r->responseHeaderFields.item[i];
		if (!strcasecmp(ti->name, "freeswitch-user")) {
			fs_user = ti->value;
		} else if (!strcasecmp(ti->name, "freeswitch-domain")) {
			fs_domain = ti->value;
		}
	}

	if (!is_authorized(r, command)) {
		ret = TRUE;
		goto end;
	}

/*  auth: */

	if (switch_event_create(&stream.param_event, SWITCH_EVENT_API) == SWITCH_STATUS_SUCCESS) {
		const char *const content_length = RequestHeaderValue(r, "content-length");
		evnt = stream.param_event;

		if (html) {
			switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "Content-Type", "text/html");
		} else if (text) {
			switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "Content-Type", "text/plain");
		} else if (xml) {
			switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "Content-Type", "text/xml");
		}
		if (api) {
			switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-API", "api");
		}
		if (fs_user)   switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "FreeSWITCH-User", fs_user);
		if (fs_domain) switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "FreeSWITCH-Domain", fs_domain);
		if (path_info) switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-Path-Info", path_info);

		if (info->host)        switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-HOST", info->host);
		if (info->from)        switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-FROM", info->from);
		if (info->useragent)   switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-USER-AGENT", info->useragent);
		if (info->referer)     switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-REFERER", info->referer);
		if (info->requestline) switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-REQUESTLINE", info->requestline);
		if (info->user)        switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-USER", info->user);
		if (info->port)        switch_event_add_header(evnt, SWITCH_STACK_BOTTOM, "HTTP-PORT", "%u", info->port);

		{
			char *q, *qd;
			char *next;
			char *query = (char *) info->query;
			char *name, *val;
			char qbuf[8192] = "";

			/* first finish reading from the socket if post method was used*/
			if (info->method == m_post && content_length) {
				int len = atoi(content_length);
				int qlen = 0;

				if (len > 0) {
					int succeeded = TRUE;
					char *qp = qbuf;
					char *readError;

					do {
						int blen = r->connP->buffersize - r->connP->bufferpos;

						if ((qlen + blen) > len) {
							blen = len - qlen;
						}

						qlen += blen;

						if (qlen > sizeof(qbuf)) {
							break;
						}

						memcpy(qp, r->connP->buffer.b + r->connP->bufferpos, blen);
						qp += blen;

						if (qlen >= len) {
							break;
						}

						ConnRead(r->connP, 2000, NULL, NULL, &readError);
		                if (readError) {
							succeeded = FALSE;
							free(readError);
						}

					} while (succeeded);

					query = qbuf;
				}
			}

			/* parse query and add kv-pairs as event headers  */
			/* a kv pair starts with '&', '+' or \0 mark the end */
			if (query) {
				switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-QUERY", query);
				qd = strdup(query);
			} else {
				qd = strdup(uri);
			}

			switch_assert(qd != NULL);

			q = qd;
			next = q;

			do {
				char *p;

				if (next = strchr(next, '&')) {
					if (!query) {
						/* pass kv pairs from uri to query       */
			            /* "?" is absent in url so parse uri     */
						*((char *)uri + (next - q - 1)) = '\0';
						query = next;
						switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-QUERY", next);
						/* and strip uri                                     */
						/* the start of first kv pair marks the end of uri   */
						/* to prevent kv-pairs confusing fs api commands     */
						/* that have arguments separated by space            */
					}
					*next++ = '\0';
				}

				for (p = q; p && *p; p++) {
					if (*p == '+') {
						*p = ' ';
					}
				}
				/* hmmm, get method requests are already decoded ... */
				switch_url_decode(q);

				name = q;
				if ((val = strchr(name, '='))) {
					*val++ = '\0';
					switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, name, val);
				}
				q = next;
			} while (q != NULL);

			free(qd);
		}
	}

	switch_event_add_header_string(evnt, SWITCH_STACK_BOTTOM, "HTTP-URI", uri);

	/* We made it this far, always OK */
	if (!HTTPWrite(r, "HTTP/1.1 200 OK\r\n", (uint32_t) strlen("HTTP/1.1 200 OK\r\n"))) {
		return TRUE;
	}

	ResponseAddField(r, "Connection", "close");

	/* generation of the date field */
	if (evnt)
	{
		ResponseAddField(r, "Date", switch_event_get_header(evnt, "Event-Date-GMT"));
	}
	else {
		const char *dateValue;

		DateToString(r->date, &dateValue);
		if (dateValue) {
			ResponseAddField(r, "Date", dateValue);
			free((void *)dateValue);
		}
	}

	/* Generation of the server field */
	ResponseAddField(r, "Server", "FreeSWITCH-" SWITCH_VERSION_FULL "-mod_xml_rpc");

	if (html) {
		ResponseAddField(r, "Content-Type", "text/html");
	} else if (text) {
		ResponseAddField(r, "Content-Type", "text/plain");
	} else if (xml) {
		ResponseAddField(r, "Content-Type", "text/xml");
	}

	for (i = 0; i < r->responseHeaderFields.size; i++) {
		TTableItem *ti = &r->responseHeaderFields.item[i];
		char *header = switch_mprintf("%s: %s\r\n", ti->name, ti->value);
		if (!ConnWrite(r->connP, header, (uint32_t) strlen(header))) {
			switch_safe_free(header);
			return TRUE;
		}
		switch_safe_free(header);
	}

	/* send end http header */
	if (html||text||xml) {
		if (!ConnWrite(r->connP, CRLF, 2)) {
			return TRUE;
		}
	}
	else {
		/* content-type and end of http header will be streamed by fs api or http_stream_write */
	}

	if (switch_stristr("unload", command) && switch_stristr("mod_xml_rpc", info->query)) {
		command = "bgapi";
		api_str = "unload mod_xml_rpc";
	} else if (switch_stristr("reload", command) && switch_stristr("mod_xml_rpc", info->query)) {
		command = "bgapi";
		api_str = "reload mod_xml_rpc";
	} else {
		api_str = info->query;
	}

	/* TODO (maybe): take "refresh=xxx" out of query as to not confuse fs api commands         */

	/* execute actual fs api command                                                            */
	/* fs api command will write to stream,  calling http_stream_write / http_stream_raw_write	*/
	/* switch_api_execute will stream INVALID COMMAND before it fails					        */
	switch_api_execute(command, api_str, NULL, &stream);

	r->responseStarted = TRUE;
	ResponseStatus(r, 200);     /* we don't want an assertion failure */
	r->requestInfo.keepalive = 0;

  end:

	return ret;
}
Beispiel #13
0
// struct creature_payRent will pay the player's rent, selling off items to meet the
// bill, if necessary.
int
pay_player_rent(struct creature *ch, time_t last_time, int code, int currency)
{
    float day_count;
    int factor;
    long cost;

    // Immortals don't pay rent
    if (GET_LEVEL(ch) >= LVL_AMBASSADOR)
        return 0;
    if (is_authorized(ch, TESTER, NULL))
        return 0;

    // Cryoed chars already paid their rent, quit chars don't have any rent
    if (code == RENT_NEW_CHAR || code == RENT_CRYO || code == RENT_QUIT)
        return 0;

    // Calculate total cost
    day_count = (float)(time(NULL) - last_time) / SECS_PER_REAL_DAY;
    if (code == RENT_FORCED)
        factor = 3;
    else
        factor = 1;
    cost = (int)(calc_daily_rent(ch, factor, NULL, false) * day_count);
    slog("Charging %ld for %.2f days of rent", cost, day_count);

    // First we get as much as we can out of their hand
    if (currency == TIME_ELECTRO) {
        if (cost < GET_CASH(ch) + GET_FUTURE_BANK(ch)) {
            withdraw_future_bank(ch->account, cost - GET_CASH(ch));
            GET_CASH(ch) = MAX(GET_CASH(ch) - cost, 0);
            cost = 0;
        } else {
            cost -= GET_CASH(ch) + GET_FUTURE_BANK(ch);
            account_set_future_bank(ch->account, 0);
            GET_CASH(ch) = 0;
        }
    } else {
        if (cost < GET_GOLD(ch) + GET_PAST_BANK(ch)) {
            withdraw_past_bank(ch->account, cost - GET_GOLD(ch));
            GET_GOLD(ch) = MAX(GET_GOLD(ch) - cost, 0);
            cost = 0;
        } else {
            cost -= GET_GOLD(ch) + GET_PAST_BANK(ch);
            account_set_past_bank(ch->account, 0);
            GET_GOLD(ch) = 0;
        }
    }

    // If they didn't have enough, try the cross-time money
    if (cost > 0) {
        if (currency == TIME_ELECTRO) {
            if (cost < GET_GOLD(ch) + GET_PAST_BANK(ch)) {
                withdraw_past_bank(ch->account, cost - GET_GOLD(ch));
                GET_GOLD(ch) = MAX(GET_GOLD(ch) - cost, 0);
                cost = 0;
            } else {
                cost -= GET_GOLD(ch) + GET_PAST_BANK(ch);
                account_set_past_bank(ch->account, 0);
                GET_GOLD(ch) = 0;
            }
        } else {
            if (cost < GET_CASH(ch) + GET_FUTURE_BANK(ch)) {
                withdraw_future_bank(ch->account, cost - GET_CASH(ch));
                GET_CASH(ch) = MAX(GET_CASH(ch) - cost, 0);
                cost = 0;
            } else {
                cost -= GET_CASH(ch) + GET_FUTURE_BANK(ch);
                account_set_future_bank(ch->account, 0);
                GET_CASH(ch) = 0;
            }
        }
    }

    // If they still don't have enough, put them in JAIL
    if (cost > 0)
        return 3;
    return 0;
}
Beispiel #14
0
XttTblGtk::XttTblGtk(GtkWidget* a_parent_wid, void* a_parent_ctx,
    sevcli_tCtx a_sevcli, sevcli_sHistItem* itemlist, int item_cnt)
    : XttTbl(a_parent_ctx, a_sevcli), parent_wid(a_parent_wid)
{
  int sts;
  pwr_tFileName fname;

  toplevel = (GtkWidget*)g_object_new(GTK_TYPE_WINDOW, "default-height", 700,
      "default-width", 500, "title", "SevXtt Navigator", NULL);

  g_signal_connect(toplevel, "delete_event", G_CALLBACK(delete_event), this);
  g_signal_connect(toplevel, "destroy", G_CALLBACK(destroy_event), this);
  g_signal_connect(
      toplevel, "focus-in-event", G_CALLBACK(xtttbl_focus_in_event), this);

  CoWowGtk::SetWindowIcon(toplevel);

  GtkWidget* vbox = gtk_vbox_new(FALSE, 0);

  // Menu
  // Accelerators
  GtkAccelGroup* accel_g
      = (GtkAccelGroup*)g_object_new(GTK_TYPE_ACCEL_GROUP, NULL);
  gtk_window_add_accel_group(GTK_WINDOW(toplevel), accel_g);

  GtkMenuBar* menu_bar = (GtkMenuBar*)g_object_new(GTK_TYPE_MENU_BAR, NULL);

  // File entry
  GtkWidget* file_print = gtk_image_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("_Print"));
  gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(file_print),
      gtk_image_new_from_stock("gtk-print", GTK_ICON_SIZE_MENU));
  g_signal_connect(file_print, "activate", G_CALLBACK(activate_print), this);

  GtkWidget* file_login
      = gtk_menu_item_new_with_mnemonic(CoWowGtk::translate_utf8("_Login"));
  g_signal_connect(file_login, "activate", G_CALLBACK(activate_login), this);

  GtkWidget* file_logout
      = gtk_menu_item_new_with_mnemonic(CoWowGtk::translate_utf8("Log_Out"));
  g_signal_connect(file_logout, "activate", G_CALLBACK(activate_logout), this);

  GtkWidget* file_close
      = gtk_image_menu_item_new_from_stock(GTK_STOCK_CLOSE, accel_g);
  g_signal_connect(file_close, "activate", G_CALLBACK(activate_close), this);

  GtkMenu* file_menu = (GtkMenu*)g_object_new(GTK_TYPE_MENU, NULL);
  gtk_menu_shell_append(GTK_MENU_SHELL(file_menu), file_print);
  gtk_menu_shell_append(GTK_MENU_SHELL(file_menu), file_login);
  gtk_menu_shell_append(GTK_MENU_SHELL(file_menu), file_logout);
  gtk_menu_shell_append(GTK_MENU_SHELL(file_menu), file_close);

  GtkWidget* file = gtk_menu_item_new_with_mnemonic("_File");
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), file);
  gtk_menu_item_set_submenu(GTK_MENU_ITEM(file), GTK_WIDGET(file_menu));

  // Functions entry
  GtkWidget* functions_opensevhist = gtk_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("_Open Process History"));
  g_signal_connect(functions_opensevhist, "activate",
      G_CALLBACK(activate_opensevhist), this);
  gtk_widget_add_accelerator(functions_opensevhist, "activate", accel_g, 'g',
      GdkModifierType(GDK_CONTROL_MASK), GTK_ACCEL_VISIBLE);

  GtkWidget* functions_command
      = gtk_menu_item_new_with_mnemonic(CoWowGtk::translate_utf8("Co_mmand"));
  g_signal_connect(
      functions_command, "activate", G_CALLBACK(activate_command), this);
  gtk_widget_add_accelerator(functions_command, "activate", accel_g, 'b',
      GdkModifierType(GDK_CONTROL_MASK), GTK_ACCEL_VISIBLE);

  GtkWidget* functions_delete_item = gtk_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("_Delete Item"));
  g_signal_connect(functions_delete_item, "activate",
      G_CALLBACK(activate_delete_item), this);

  GtkMenu* functions_menu = (GtkMenu*)g_object_new(GTK_TYPE_MENU, NULL);
  gtk_menu_shell_append(GTK_MENU_SHELL(functions_menu), functions_opensevhist);
  gtk_menu_shell_append(GTK_MENU_SHELL(functions_menu), functions_command);
  gtk_menu_shell_append(GTK_MENU_SHELL(functions_menu), functions_delete_item);

  GtkWidget* functions
      = gtk_menu_item_new_with_mnemonic(CoWowGtk::translate_utf8("_Functions"));
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), functions);
  gtk_menu_item_set_submenu(
      GTK_MENU_ITEM(functions), GTK_WIDGET(functions_menu));

  // View menu
  GtkWidget* view_tree_layout = gtk_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("_Tree Layout"));
  g_signal_connect(
      view_tree_layout, "activate", G_CALLBACK(activate_tree_layout), this);

  GtkWidget* view_list_layout = gtk_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("_List Layout"));
  g_signal_connect(
      view_list_layout, "activate", G_CALLBACK(activate_list_layout), this);

  GtkWidget* view_zoom_in = gtk_image_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("Zoom _In"));
  gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(view_zoom_in),
      gtk_image_new_from_stock("gtk-zoom-in", GTK_ICON_SIZE_MENU));
  g_signal_connect(
      view_zoom_in, "activate", G_CALLBACK(activate_zoom_in), this);
  gtk_widget_add_accelerator(view_zoom_in, "activate", accel_g, 'i',
      GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

  GtkWidget* view_zoom_out = gtk_image_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("Zoom _Out"));
  gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(view_zoom_out),
      gtk_image_new_from_stock("gtk-zoom-out", GTK_ICON_SIZE_MENU));
  g_signal_connect(
      view_zoom_out, "activate", G_CALLBACK(activate_zoom_out), this);
  gtk_widget_add_accelerator(view_zoom_out, "activate", accel_g, 'o',
      GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

  GtkWidget* view_zoom_reset = gtk_image_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("Zoom _Reset"));
  gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(view_zoom_reset),
      gtk_image_new_from_stock("gtk-zoom-100", GTK_ICON_SIZE_MENU));
  g_signal_connect(
      view_zoom_reset, "activate", G_CALLBACK(activate_zoom_reset), this);

  GtkMenu* view_menu = (GtkMenu*)g_object_new(GTK_TYPE_MENU, NULL);
  gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), view_tree_layout);
  gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), view_list_layout);
  gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), view_zoom_in);
  gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), view_zoom_out);
  gtk_menu_shell_append(GTK_MENU_SHELL(view_menu), view_zoom_reset);

  GtkWidget* view
      = gtk_menu_item_new_with_mnemonic(CoWowGtk::translate_utf8("_View"));
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), view);
  gtk_menu_item_set_submenu(GTK_MENU_ITEM(view), GTK_WIDGET(view_menu));

  // Help entry
  GtkWidget* help_overview = gtk_image_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("_Overview"));
  gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(help_overview),
      gtk_image_new_from_stock("gtk-help", GTK_ICON_SIZE_MENU));
  g_signal_connect(help_overview, "activate", G_CALLBACK(activate_help), this);
  gtk_widget_add_accelerator(help_overview, "activate", accel_g, 'h',
      GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

  GtkWidget* help_project
      = gtk_menu_item_new_with_mnemonic(CoWowGtk::translate_utf8("_Project"));
  g_signal_connect(
      help_project, "activate", G_CALLBACK(activate_help_project), this);

  GtkWidget* help_proview = gtk_menu_item_new_with_mnemonic(
      CoWowGtk::translate_utf8("_About Proview"));
  g_signal_connect(
      help_proview, "activate", G_CALLBACK(activate_help_proview), this);

  GtkMenu* help_menu = (GtkMenu*)g_object_new(GTK_TYPE_MENU, NULL);
  gtk_menu_shell_append(GTK_MENU_SHELL(help_menu), help_overview);
  gtk_menu_shell_append(GTK_MENU_SHELL(help_menu), help_project);
  gtk_menu_shell_append(GTK_MENU_SHELL(help_menu), help_proview);

  GtkWidget* help
      = gtk_menu_item_new_with_mnemonic(CoWowGtk::translate_utf8("_Help"));
  gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), help);
  gtk_menu_item_set_submenu(GTK_MENU_ITEM(help), GTK_WIDGET(help_menu));

  // Toolbar
  GtkToolbar* tools = (GtkToolbar*)g_object_new(GTK_TYPE_TOOLBAR, NULL);

  GtkWidget* tools_opensevhist = gtk_button_new();
  dcli_translate_filename(fname, "$pwr_exe/xtt_meth_trend.png");
  gtk_container_add(
      GTK_CONTAINER(tools_opensevhist), gtk_image_new_from_file(fname));
  g_signal_connect(
      tools_opensevhist, "clicked", G_CALLBACK(activate_opensevhist), this);
  g_object_set(tools_opensevhist, "can-focus", FALSE, NULL);
  gtk_toolbar_append_widget(tools, tools_opensevhist,
      CoWowGtk::translate_utf8("Open history item"), "");

  GtkWidget* tools_zoom_in = gtk_button_new();
  dcli_translate_filename(fname, "$pwr_exe/xtt_zoom_in.png");
  gtk_container_add(
      GTK_CONTAINER(tools_zoom_in), gtk_image_new_from_file(fname));
  g_signal_connect(
      tools_zoom_in, "clicked", G_CALLBACK(activate_zoom_in), this);
  g_object_set(tools_zoom_in, "can-focus", FALSE, NULL);
  gtk_toolbar_append_widget(
      tools, tools_zoom_in, CoWowGtk::translate_utf8("Zoom in"), "");

  GtkWidget* tools_zoom_out = gtk_button_new();
  dcli_translate_filename(fname, "$pwr_exe/xtt_zoom_out.png");
  gtk_container_add(
      GTK_CONTAINER(tools_zoom_out), gtk_image_new_from_file(fname));
  g_signal_connect(
      tools_zoom_out, "clicked", G_CALLBACK(activate_zoom_out), this);
  g_object_set(tools_zoom_out, "can-focus", FALSE, NULL);
  gtk_toolbar_append_widget(
      tools, tools_zoom_out, CoWowGtk::translate_utf8("Zoom out"), "");

  GtkWidget* tools_zoom_reset = gtk_button_new();
  dcli_translate_filename(fname, "$pwr_exe/xtt_zoom_reset.png");
  gtk_container_add(
      GTK_CONTAINER(tools_zoom_reset), gtk_image_new_from_file(fname));
  g_signal_connect(
      tools_zoom_reset, "clicked", G_CALLBACK(activate_zoom_reset), this);
  g_object_set(tools_zoom_reset, "can-focus", FALSE, NULL);
  gtk_toolbar_append_widget(
      tools, tools_zoom_reset, CoWowGtk::translate_utf8("Zoom reset"), "");

  // Statusbar and cmd input
  GtkWidget* statusbar = gtk_hbox_new(FALSE, 0);
  msg_label = gtk_label_new("");
  gtk_widget_set_size_request(msg_label, -1, 25);
  cmd_prompt = gtk_label_new("xtt > ");
  gtk_widget_set_size_request(cmd_prompt, -1, 25);

  cmd_recall = new CoWowRecall();
  cmd_entry = new CoWowEntryGtk(cmd_recall);
  cmd_input = cmd_entry->widget();
  gtk_widget_set_size_request(cmd_input, -1, 25);
  g_signal_connect(
      cmd_input, "activate", G_CALLBACK(valchanged_cmd_input), this);

  gtk_box_pack_start(GTK_BOX(statusbar), msg_label, FALSE, FALSE, 20);
  gtk_box_pack_start(GTK_BOX(statusbar), cmd_prompt, FALSE, FALSE, 20);
  gtk_box_pack_start(GTK_BOX(statusbar), cmd_input, TRUE, TRUE, 20);
  gtk_widget_show_all(statusbar);

  tblnav
      = new TblNavGtk(this, toplevel, itemlist, item_cnt, &brow_widget, &sts);
  tblnav->message_cb = &XttTbl::message;
  tblnav->is_authorized_cb = &XttTbl::is_authorized;
  tblnav->command_cb = &XttTbl::command_cb;

  gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(menu_bar), FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(tools), FALSE, FALSE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(brow_widget), TRUE, TRUE, 0);
  gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(statusbar), FALSE, FALSE, 3);

  gtk_container_add(GTK_CONTAINER(toplevel), vbox);

  gtk_widget_show_all(toplevel);

  g_object_set(cmd_prompt, "visible", FALSE, NULL);
  g_object_set(cmd_input, "visible", FALSE, NULL);

  // Create help window
  CoXHelp* xhelp = new CoXHelpGtk(toplevel, this, xhelp_eUtility_Xtt, &sts);
  CoXHelp::set_default(xhelp);

  wow = new CoWowGtk(toplevel);

  if (!is_authorized(pwr_mAccess_AllSev, 0))
    open_login();

  if (!quiet) {
    if (cologin)
      // Set login window as parent to warranty as focus is left to parent.
      ((CoWowGtk*)wow)->SetParent(((CoLoginGtk*)cologin)->widgets.toplevel);

    wow->DisplayWarranty();

    if (cologin)
      ((CoWowGtk*)wow)->SetParent(toplevel);
  }
}
abyss_bool handler_hook(TSession * r)
{
	//char *mime = "text/html";
	char buf[80] = "HTTP/1.1 200 OK\n";
	switch_stream_handle_t stream = { 0 };
	char *command;
	int i;
	TTableItem *ti;
	char *fs_user = NULL, *fs_domain = NULL;
	char *path_info = NULL;
	abyss_bool ret = TRUE;
	int html = 0, text = 0, xml = 0;
	const char *api_str;

	stream.data = r;
	stream.write_function = http_stream_write;
	stream.raw_write_function = http_stream_raw_write;

	if (!r || !r->requestInfo.uri) {
		return FALSE;
	}
	
	if ((command = strstr(r->requestInfo.uri, "/api/"))) {
		command += 5;
	} else if ((command = strstr(r->requestInfo.uri, "/webapi/"))) {
		command += 8;
		html++;
	} else if ((command = strstr(r->requestInfo.uri, "/txtapi/"))) {
		command += 8;
		text++;
	} else if ((command = strstr(r->requestInfo.uri, "/xmlapi/"))) {
		command += 8;
		xml++;
	} else {
		return FALSE;
	}

	if ((path_info = strchr(command, '/'))) {
		*path_info++ = '\0';
	}

	for (i = 0; i < r->response_headers.size; i++) {
		ti = &r->response_headers.item[i];
		if (!strcasecmp(ti->name, "freeswitch-user")) {
			fs_user = ti->value;
		} else if (!strcasecmp(ti->name, "freeswitch-domain")) {
			fs_domain = ti->value;
		}
	}

	if (is_authorized(r, command)) {
		goto auth;
	}

	ret = TRUE;
	goto end;

  auth:

	if (switch_event_create(&stream.param_event, SWITCH_EVENT_API) == SWITCH_STATUS_SUCCESS) {
		const char *const content_length = RequestHeaderValue(r, "content-length");

		if (html)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "Content-type", "text/html");
		else if (text)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "Content-type", "text/plain");
		else if (xml)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "Content-type", "text/xml");
		if (fs_user)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "FreeSWITCH-User", fs_user);
		if (fs_domain)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "FreeSWITCH-Domain", fs_domain);
		if (path_info)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-Path-Info", path_info);
		switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-URI", r->requestInfo.uri);
		if (r->requestInfo.query)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-QUERY", r->requestInfo.query);
		if (r->requestInfo.host)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-HOST", r->requestInfo.host);
		if (r->requestInfo.from)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-FROM", r->requestInfo.from);
		if (r->requestInfo.useragent)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-USER-AGENT", r->requestInfo.useragent);
		if (r->requestInfo.referer)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-REFERER", r->requestInfo.referer);
		if (r->requestInfo.requestline)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-REQUESTLINE", r->requestInfo.requestline);
		if (r->requestInfo.user)
			switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-USER", r->requestInfo.user);
		if (r->requestInfo.port)
			switch_event_add_header(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-PORT", "%u", r->requestInfo.port);
		if (r->requestInfo.query || content_length) {
			char *q, *qd;
			char *next;
			char *query = (char *) r->requestInfo.query;
			char *name, *val;
			char qbuf[8192] = "";

			if (r->requestInfo.method == m_post && content_length) {
				int len = atoi(content_length);
				int qlen = 0;

				if (len > 0) {
					int succeeded;
					char *qp = qbuf;
					do {
						int blen = r->conn->buffersize - r->conn->bufferpos;

						if ((qlen + blen) > len) {
							blen = len - qlen;
						}

						qlen += blen;

						if (qlen > sizeof(qbuf)) {
							break;
						}

						memcpy(qp, r->conn->buffer + r->conn->bufferpos, blen);
						qp += blen;

						if (qlen >= len) {
							break;
						}
					} while ((succeeded = ConnRead(r->conn, 2000)));

					query = qbuf;
				}
			}
			if (query) {
				switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, "HTTP-QUERY", query);

				qd = strdup(query);
				switch_assert(qd != NULL);

				q = qd;
				next = q;

				do {
					char *p;

					if ((next = strchr(next, '&'))) {
						*next++ = '\0';
					}

					for (p = q; p && *p; p++) {
						if (*p == '+') {
							*p = ' ';
						}
					}

					switch_url_decode(q);

					name = q;
					if ((val = strchr(name, '='))) {
						*val++ = '\0';
						switch_event_add_header_string(stream.param_event, SWITCH_STACK_BOTTOM, name, val);
					}
					q = next;
				} while (q != NULL);

				free(qd);
			}
		}
	}
	//ResponseChunked(r);

	//ResponseContentType(r, mime);
	//ResponseWrite(r);

	HTTPWrite(r, buf, (uint32_t) strlen(buf));

	//HTTPWrite(r, "<pre>\n\n", 7);

	/* generation of the date field */
	{
		const char *dateValue;

		DateToString(r->date, &dateValue);

		if (dateValue) {
			ResponseAddField(r, "Date", dateValue);
		}
	}


	/* Generation of the server field */
	ResponseAddField(r, "Server", "FreeSWITCH-" SWITCH_VERSION_FULL "-mod_xml_rpc");

	if (html) {
		ResponseAddField(r, "Content-Type", "text/html");
	} else if (text) {
		ResponseAddField(r, "Content-Type", "text/plain");
	} else if (xml) {
		ResponseAddField(r, "Content-Type", "text/xml");
	}

	for (i = 0; i < r->response_headers.size; i++) {
		ti = &r->response_headers.item[i];
		ConnWrite(r->conn, ti->name, (uint32_t) strlen(ti->name));
		ConnWrite(r->conn, ": ", 2);
		ConnWrite(r->conn, ti->value, (uint32_t) strlen(ti->value));
		ConnWrite(r->conn, CRLF, 2);
	}

	switch_snprintf(buf, sizeof(buf), "Connection: close\r\n");
	ConnWrite(r->conn, buf, (uint32_t) strlen(buf));

	if (html || text || xml) {
		ConnWrite(r->conn, "\r\n", 2);
	}

	if (switch_stristr("unload", command) && switch_stristr("mod_xml_rpc", r->requestInfo.query)) {
		command = "bgapi";
		api_str = "unload mod_xml_rpc";
	} else if (switch_stristr("reload", command) && switch_stristr("mod_xml_rpc", r->requestInfo.query)) {
		command = "bgapi";
		api_str = "reload mod_xml_rpc";
	} else {
		api_str = r->requestInfo.query;
	}

	if (switch_api_execute(command, api_str, NULL, &stream) == SWITCH_STATUS_SUCCESS) {
		ResponseStatus(r, 200);
		r->responseStarted = TRUE;
		//r->done = TRUE;
	} else {
		ResponseStatus(r, 404);
		ResponseError(r);
	}

	//SocketClose(&(r->conn->socket));

	HTTPWriteEnd(r);
	//if (r->conn->channelP)
	//ConnKill(r->conn);
	//ChannelInterrupt(r->conn->channelP);
	//ConnClose(r->conn);
	//ChannelDestroy(r->conn->channelP);
	r->requestInfo.keepalive = 0;

  end:

	return ret;
}