示例#1
0
static int
/*ARGSUSED*/
set_timezone_menu(struct menudesc *menu, void *arg)
{
	configinfo **confp = arg;
	set_timezone();
	get_tz_default();
	confp[menu->cursel]->setting = tz_default;
	return 0;
}
示例#2
0
static void process_time_report() {
	while(msg_available()) {
		if (msg_get_16() != ATTR_TIMEANDZONE) return;
		if (msg_get() != TYPE_OCTET_STRING) return;
		if (msg_get() != 8) return; // Weird length
		time_t t = msg_get_32()+ZIGBEE_TIME_OFFSET;
		int32_t zone = msg_get_i32();

		/* Setting time and zone must be done without WET
		 * macro because this function is only run in dry mode
		 * (no response generated, because it's a report) */
		stime(&t);
		set_timezone(zone);
	}
}
示例#3
0
void print_ddate(yajl_gen json_gen, char *buffer, const char *format, time_t t) {
        char *outwalk = buffer;
        static char *form = NULL;
        struct tm current_tm;
        struct disc_time *dt;
        set_timezone(NULL);  /* Use local time. */
        localtime_r(&t, &current_tm);
        if ((dt = get_ddate(&current_tm)) == NULL)
                return;
        if (form == NULL)
                if ((form = malloc(strlen(format) + 1)) == NULL)
                        return;
        strcpy(form, format);
        outwalk += format_output(outwalk, form, dt);
        OUTPUT_FULL_TEXT(buffer);
}
示例#4
0
 /**
  * Change the timezone and time format ios state;
  */
 void operator()(std::ios_base &ios) const
 {
   //set_time_fmt<typename out_stream::char_type>(ios, "");
   set_timezone(ios, tz_);
 }
示例#5
0
 /**
  * Change the timezone and time format ios state;
  */
 void operator()(std::ios_base &ios) const
 {
   set_time_fmt<CharT> (ios, fmt_);
   set_timezone(ios, tz_);
 }
示例#6
0
static void handle_method_call(GDBusConnection *connection, const gchar *caller, const gchar *object_path,
			       const gchar *interface_name, const gchar *method_name, GVariant *parameters,
			       GDBusMethodInvocation *invocation, gpointer user_data) {
	GVariantBuilder builder;
	GVariant *result;
	const gchar *interface, *property;

	if (!g_strcmp0(interface_name, TIMEDATED_INTERFACE)) {
		if (!g_strcmp0(method_name, "SetTime"))
			set_time(parameters, invocation, caller);
		else if (!g_strcmp0(method_name, "SetTimezone"))
			set_timezone(parameters, invocation, caller);
		else if (!g_strcmp0(method_name, "SetLocalRTC"))
			set_rtc_local(parameters, invocation, caller);
		else if (!g_strcmp0(method_name, "SetNTP"))
			set_ntp_active(parameters, invocation, caller);
		else
			g_assert_not_reached();

	} else if (!g_strcmp0(interface_name, PROPERTIES_INTERFACE)) {
		if (!g_strcmp0(method_name, "Get")) {

			g_variant_get(parameters, "(&s&s)", &interface, &property);

			if (g_strcmp0(interface, TIMEDATED_INTERFACE) && g_strcmp0(interface, "")) {
				return_error(invocation, G_DBUS_ERROR_INVALID_ARGS, "No such interface");
				return;
			}

			if (!g_strcmp0(property, "Timezone"))
				result = get_timezone();
			else if (!g_strcmp0(property, "LocalRTC"))
				result = get_rtc_local();
			else if (!g_strcmp0(property, "CanNTP"))
				result = get_ntp_available();
			else if (!g_strcmp0(property, "NTP"))
				result = get_ntp_active();
			else if (!g_strcmp0(property, "NTPSynchronized"))
				result = get_clock_synchronized();
			else if (!g_strcmp0(property, "TimeUSec"))
				result = get_system_time();
			else if (!g_strcmp0(property, "RTCTimeUSec"))
				result = get_rtc_time();
			else {
				return_error(invocation, G_DBUS_ERROR_INVALID_ARGS, "No such property");
				return;
			}

			g_dbus_method_invocation_return_value(invocation, g_variant_new("(v)", result));

		} else if (!g_strcmp0(method_name, "GetAll")) {
			g_variant_get(parameters, "(&s)", &interface);

			if (g_strcmp0(interface, TIMEDATED_INTERFACE) && g_strcmp0(interface, "")) {
				return_error(invocation, G_DBUS_ERROR_INVALID_ARGS, "No such interface");
				return;
			}

			g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));
			g_variant_builder_add(&builder, "{sv}", "Timezone", get_timezone());
			g_variant_builder_add(&builder, "{sv}", "LocalRTC", get_rtc_local());
			g_variant_builder_add(&builder, "{sv}", "CanNTP", get_ntp_available());
			g_variant_builder_add(&builder, "{sv}", "NTP", get_ntp_active());
			g_variant_builder_add(&builder, "{sv}", "NTPSynchronized", get_clock_synchronized());
			g_variant_builder_add(&builder, "{sv}", "TimeUSec", get_system_time());
			g_variant_builder_add(&builder, "{sv}", "RTCTimeUSec", get_rtc_time());

			result = g_variant_new("(a{sv})", &builder);

			g_dbus_method_invocation_return_value(invocation, result);

		} else if (!g_strcmp0(method_name, "Set")) {
			g_variant_get(parameters, "(&s&sv)", &interface, &property, NULL);
			return_error(invocation, G_DBUS_ERROR_INVALID_ARGS, "Property %s not writable",
				     property);
		} else {
			g_assert_not_reached();
		}
	} else {
		g_assert_not_reached();
	}
}
示例#7
0
int
main (int argc, char *argv[])
{
    time_t t = 0;
    char *x = NULL;
    struct sigaction sa;
    iopause_fd *iop = NULL;
    int i = 0, n = 0, *udp53 = NULL;

    prog = strdup ((x = strrchr (argv[0], '/')) != NULL ? x + 1 : argv[0]);

    sa.sa_handler = handle_term;
    sigaction (SIGINT, &sa, NULL);
    sigaction (SIGTERM, &sa, NULL);

    sa.sa_handler = SIG_IGN;
    sigaction (SIGPIPE, &sa, NULL);

    i = check_option (argc, argv);
    argc -= i;
    argv += i;

    if (mode & DAEMON)
    {
        i = fork ();
        if (i == -1)
            err (-1, "could not fork a daemon process");
        if (i > 0)
            return 0;
    }

    time (&t);
    memset (buf, 0, sizeof (buf));
    strftime (buf, sizeof (buf), "%b-%d %Y %T %Z", localtime (&t));
    warnx ("version %s: starting: %s\n", VERSION, buf);

    set_timezone ();
    if (debug_level)
        warnx ("TIMEZONE: %s", env_get ("TZ"));

    initialize ();
    if (!debug_level)
        if ((x = env_get ("DEBUG_LEVEL")))
            debug_level = atol (x);
    warnx ("DEBUG_LEVEL set to `%d'", debug_level);

    if ((x = env_get ("DATALIMIT")))
    {
        struct rlimit r;
        unsigned long dlimit = atol (x);

        if (getrlimit (RLIMIT_DATA,  &r) != 0)
            err (-1, "could not get resource RLIMIT_DATA");

        r.rlim_cur = (dlimit <= r.rlim_max) ? dlimit : r.rlim_max;

        if (setrlimit (RLIMIT_DATA, &r) != 0)
            err (-1, "could not set resource RLIMIT_DATA");

        if (debug_level)
            warnx ("DATALIMIT set to `%ld' bytes", r.rlim_cur);
    }

    if (!(x = env_get ("IP")))
        err (-1, "$IP not set");
    for (i = 0; (unsigned)i < strlen (x); i++)
        n = (x[i] == ',') ? n+1 : n;
    if (!(udp53 = calloc (n+1, sizeof (int))))
        err (-1, "could not allocate enough memory for udp53");
    if (!(iop = calloc (n+1, sizeof (iopause_fd))))
        err (-1, "could not allocate enough memory for iop");

    i = n = 0;
    while (x[i])
    {
        unsigned int l = 0;

        if (!(l = ip4_scan(x+i, ip)))
            errx (-1, "could not parse IP address `%s'", x + i);

        udp53[n] = socket_udp();
        if (udp53[n] == -1)
            errx (-1, "could not open UDP socket");
        if (socket_bind4_reuse (udp53[n], ip, server_port) == -1)
            errx (-1, "could not bind UDP socket");

        ndelay_off (udp53[n]);
        socket_tryreservein (udp53[n], 65536);

        iop[n].fd = udp53[n];
        iop[n].events = IOPAUSE_READ;

        n++;
        i += (x[i + l] == ',') ? l + 1 : l;
    }

    droproot ();
    while (1)
    {
        struct taia stamp;
        struct in_addr odst; /* original destination IP */
        struct taia deadline;

        taia_now (&stamp);
        taia_uint (&deadline, 300);
        taia_add (&deadline, &deadline, &stamp);
        iopause (iop, n, &deadline, &stamp);

        for (i = 0; i < n; i++)
        {
            if (!iop[i].revents)
                continue;

            len = socket_recv4 (udp53[i], buf, sizeof (buf), ip, &port, &odst);
            if (len < 0)
                continue;
            if (!doit ())
                continue;
            if (response_len > 512)
                response_tc ();

            /* may block for buffer space; if it fails, too bad */
            len = socket_send4 (udp53[i], response,
                                response_len, ip, port, &odst);
            if (len < 0)
                continue;
            if (debug_level > 1)
                log_querydone(qnum, response, response_len);
        }
    }

    return 0;
}
示例#8
0
int
main (int argc, char *argv[])
{
    int i = 0;
    time_t t = 0;
    struct sigaction sa;
    unsigned long cachesize = 0;
    char *x = NULL, char_seed[128];

    sa.sa_handler = handle_term;
    sigaction (SIGINT, &sa, NULL);
    sigaction (SIGTERM, &sa, NULL);

    sa.sa_handler = SIG_IGN;
    sigaction (SIGPIPE, &sa, NULL);

    seed_addtime ();
    seed_adduint32 (getpid ());
    seed_adduint32 (getppid ());
    seed_adduint32 (getuid ());
    seed_adduint32 (getgid ());

    seed_addtime ();
    prog = strdup ((x = strrchr (argv[0], '/')) != NULL ?  x + 1 : argv[0]);
    i = check_option (argc, argv);
    argc -= i;
    argv += i;

    if (mode & DAEMON)
    {
        i = fork ();
        if (i == -1)
            err (-1, "could not fork a daemon process");
        if (i > 0)
            return 0;
    }

    time (&t);
    strftime (char_seed, sizeof (char_seed), "%b-%d %Y %T %Z", localtime (&t));
    warnx ("version %s: starting: %s\n", VERSION, char_seed);

    set_timezone ();
    if (debug_level)
        warnx ("TIMEZONE: %s", env_get ("TZ"));

    read_conf (CFGFILE);
    if (!debug_level)
        if ((x = env_get ("DEBUG_LEVEL")))
            debug_level = atol (x);
    warnx ("DEBUG_LEVEL set to `%d'", debug_level);

    if ((x = env_get ("DATALIMIT")))
    {
        struct rlimit r;
        unsigned long dlimit = atol (x);

        if (getrlimit (RLIMIT_DATA,  &r) != 0)
            err (-1, "could not get resource RLIMIT_DATA");

        r.rlim_cur = (dlimit <= r.rlim_max) ? dlimit : r.rlim_max;

        if (setrlimit (RLIMIT_DATA, &r) != 0)
            err (-1, "could not set resource RLIMIT_DATA");

        if (debug_level)
            warnx ("DATALIMIT set to `%ld' bytes", r.rlim_cur);
    }

    if (!(x = env_get ("IP")))
        err (-1, "$IP not set");
    if (!ip4_scan (x, myipincoming))
        err (-1, "could not parse IP address `%s'", x);

    seed_addtime ();
    udp53 = socket_udp ();
    if (udp53 == -1)
        err (-1, "could not open UDP socket");
    if (socket_bind4_reuse (udp53, myipincoming, 53) == -1)
        err (-1, "could not bind UDP socket");

    seed_addtime ();
    tcp53 = socket_tcp ();
    if (tcp53 == -1)
        err (-1, "could not open TCP socket");
    if (socket_bind4_reuse (tcp53, myipincoming, 53) == -1)
        err (-1, "could not bind TCP socket");

    if (mode & DAEMON)
    {
        /* redirect stdout & stderr to a log file */
        redirect_to_log (LOGFILE, STDOUT_FILENO | STDERR_FILENO);

        write_pid (PIDFILE);
    }

    seed_addtime ();
    droproot ();
    if (mode & DAEMON)
        /* crerate a new session & detach from controlling tty */
        if (setsid () < 0)
            err (-1, "could not start a new session for the daemon");

    seed_addtime ();
    socket_tryreservein (udp53, 131072);

    memset (char_seed, 0, sizeof (char_seed));
    for (i = 0, x = (char *)seed; (unsigned)i < sizeof (char_seed); i++, x++)
        char_seed[i] = *x;
    dns_random_init (char_seed);

    if (!(x = env_get ("IPSEND")))
        err (-1, "$IPSEND not set");
    if (!ip4_scan (x, myipoutgoing))
        err (-1, "could not parse IP address `%s'", x);

    if (!(x = env_get ("CACHESIZE")))
        err (-1, "$CACHESIZE not set");
    scan_ulong (x, &cachesize);
    if (!cache_init (cachesize))
        err (-1, "could not allocate `%ld' bytes for cache", cachesize);

    if (env_get ("HIDETTL"))
        response_hidettl ();
    if (env_get ("FORWARDONLY"))
        query_forwardonly ();
    if (env_get ("MERGEQUERIES"))
        dns_enable_merge (log_merge);
    if (!roots_init ())
        err (-1, "could not read servers");
    if (debug_level > 3)
        roots_display();
    if (socket_listen (tcp53, 20) == -1)
        err (-1, "could not listen on TCP socket");
    if (!dbl_init() && debug_level > 1)
        warnx ("could not read dnsbl.cdb");

    doit ();

    return 0;
}
示例#9
0
void 
handle_notifications(void)
{
	int i, stop_handle = 0;
	char notify_name[256];

	DIR *directory = opendir(DIR_RC_NOTIFY);
	if (!directory)
		return;

	// handle max 10 requests at once (prevent deadlock)
	for (i=0; i < 10; i++)
	{
		struct dirent *entry;
		FILE *test_fp;
		
		entry = readdir(directory);
		if (!entry)
			break;
		if (strcmp(entry->d_name, ".") == 0)
			continue;
		if (strcmp(entry->d_name, "..") == 0)
			continue;
		
		/* Remove the marker file. */
		snprintf(notify_name, sizeof(notify_name), "%s/%s", DIR_RC_NOTIFY, entry->d_name);
		remove(notify_name);
		
		printf("rc notification: %s\n", entry->d_name);
		
		/* Take the appropriate action. */
		if (!strcmp(entry->d_name, RCN_RESTART_REBOOT))
		{
			stop_handle = 1;
			sys_exit();
		}
		else if (!strcmp(entry->d_name, "flash_firmware"))
		{
			stop_handle = 1;
			flash_firmware();
		}
#if defined (USE_IPV6)
		else if (!strcmp(entry->d_name, RCN_RESTART_IPV6))
		{
			if (!get_ap_mode()) {
				full_restart_ipv6(nvram_ipv6_type);
				nvram_ipv6_type = get_ipv6_type();
			}
		}
		else if (strcmp(entry->d_name, RCN_RESTART_RADVD) == 0)
		{
			restart_dhcpd();
			restart_radvd();
		}
#endif
		else if (!strcmp(entry->d_name, RCN_RESTART_WAN))
		{
			full_restart_wan();
		}
		else if (!strcmp(entry->d_name, RCN_RESTART_LAN))
		{
			full_restart_lan();
		}
		else if (!strcmp(entry->d_name, "stop_whole_wan"))
		{
			stop_wan();
		}
		else if (!strcmp(entry->d_name, RCN_RESTART_IPTV))
		{
			int is_ap_mode = get_ap_mode();
			restart_iptv(is_ap_mode);
			if (!is_ap_mode)
				restart_firewall();
		}
		else if(!strcmp(entry->d_name, "deferred_wan_connect"))
		{
			deferred_wan_connect();
		}
		else if(!strcmp(entry->d_name, "auto_wan_reconnect"))
		{
			auto_wan_reconnect();
		}
		else if(!strcmp(entry->d_name, "auto_wan_reconnect_pause"))
		{
			auto_wan_reconnect_pause();
		}
		else if(!strcmp(entry->d_name, "manual_wan_reconnect"))
		{
			manual_wan_reconnect();
		}
		else if(!strcmp(entry->d_name, "manual_wan_disconnect"))
		{
			manual_wan_disconnect();
		}
		else if(!strcmp(entry->d_name, "manual_ddns_hostname_check"))
		{
			manual_ddns_hostname_check();
		}
#if (BOARD_NUM_USB_PORTS > 0)
		else if (!strcmp(entry->d_name, RCN_RESTART_MODEM))
		{
			int wan_stopped = 0;
			int modules_reloaded = 0;
			int need_restart_wan = get_usb_modem_wan(0);
			int modem_rule = nvram_get_int("modem_rule");
			int modem_type = nvram_get_int("modem_type");
			if (nvram_modem_rule != modem_rule)
			{
				nvram_modem_rule = modem_rule;
				if (need_restart_wan) {
					wan_stopped = 1;
					stop_wan();
				}
				if (modem_rule > 0) {
					modules_reloaded = 1;
					reload_modem_modules(modem_type, 1);
				} else {
					unload_modem_modules();
				}
			}
			if (nvram_modem_type != modem_type)
			{
				if (nvram_modem_type == 3 || modem_type == 3) {
					if (modem_rule > 0 && !modules_reloaded) {
						if (need_restart_wan && !wan_stopped)
							stop_wan();
						reload_modem_modules(modem_type, 1);
					}
				}
				nvram_modem_type = modem_type;
			}
			if (need_restart_wan)
				full_restart_wan();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_SPOOLER) == 0)
		{
			restart_usb_printer_spoolers();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_HDDTUNE) == 0)
		{
			system("/sbin/hddtune.sh");
			set_pagecache_reclaim();
		}
#if defined(APP_FTPD)
		else if (strcmp(entry->d_name, RCN_RESTART_FTPD) == 0)
		{
			restart_ftpd();
		}
#endif
#if defined(APP_SMBD)
		else if (strcmp(entry->d_name, RCN_RESTART_SMBD) == 0)
		{
			restart_smbd();
		}
#endif
#if defined(APP_NFSD)
		else if (strcmp(entry->d_name, RCN_RESTART_NFSD) == 0)
		{
			restart_nfsd();
		}
#endif
#if defined(APP_MINIDLNA)
		else if (strcmp(entry->d_name, "restart_dms_rescan") == 0)
		{
			restart_dms(1);
		}
		else if (strcmp(entry->d_name, RCN_RESTART_DMS) == 0)
		{
			restart_dms(0);
		}
#endif
#if defined(APP_FIREFLY)
		else if (strcmp(entry->d_name, RCN_RESTART_ITUNES) == 0)
		{
			restart_itunes();
		}
#endif
#if defined(APP_TRMD)
		else if (strcmp(entry->d_name, RCN_RESTART_TRMD) == 0)
		{
			restart_torrent();
		}
#endif
#if defined(APP_ARIA)
		else if (strcmp(entry->d_name, RCN_RESTART_ARIA) == 0)
		{
			restart_aria();
		}
#endif
		else if (!strcmp(entry->d_name, "on_hotplug_usb_storage"))
		{
			// deferred run usb apps
			nvram_set_int_temp("usb_hotplug_ms", 1);
			alarm(5);
		}
		else if (!strcmp(entry->d_name, "on_unplug_usb_storage"))
		{
			umount_ejected();
		}
		else if (!strcmp(entry->d_name, "on_hotplug_usb_printer"))
		{
			// deferred run usb printer daemons
			nvram_set_int_temp("usb_hotplug_lp", 1);
			alarm(5);
		}
		else if (!strcmp(entry->d_name, "on_unplug_usb_printer"))
		{
			// deferred stop usb printer daemons
			nvram_set_int_temp("usb_unplug_lp", 1);
			alarm(5);
		}
		else if (!strcmp(entry->d_name, "on_hotplug_usb_modem"))
		{
			// deferred run usb modem to wan
			nvram_set_int_temp("usb_hotplug_md", 1);
			alarm(5);
		}
		else if (!strcmp(entry->d_name, "on_unplug_usb_modem"))
		{
			// deferred restart wan
			nvram_set_int_temp("usb_unplug_md", 1);
			alarm(5);
		}
#endif
		else if (strcmp(entry->d_name, RCN_RESTART_HTTPD) == 0)
		{
			restart_httpd();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_TELNETD) == 0)
		{
			stop_telnetd();
			start_telnetd();
		}
#if defined(APP_SSHD)
		else if (strcmp(entry->d_name, RCN_RESTART_SSHD) == 0)
		{
			restart_sshd();
		}
#endif
#if defined(APP_SMBD) || defined(APP_NMBD)
		else if (strcmp(entry->d_name, RCN_RESTART_NMBD) == 0)
		{
			restart_nmbd();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_WINS) == 0)
		{
			restart_nmbd();
			restart_dhcpd();
			reload_vpn_server();
		}
#endif
		else if (strcmp(entry->d_name, RCN_RESTART_LLTD) == 0)
		{
			restart_lltd();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_ADSC) == 0)
		{
			restart_infosvr();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_VPNSVR) == 0)
		{
			restart_vpn_server();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_VPNCLI) == 0)
		{
			restart_vpn_client();
		}
		else if (strcmp(entry->d_name, "start_vpn_client") == 0)
		{
			start_vpn_client();
		}
		else if (strcmp(entry->d_name, "stop_vpn_client") == 0)
		{
			stop_vpn_client();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_DDNS) == 0)
		{
			stop_ddns();
			start_ddns(1);
		}
		else if (strcmp(entry->d_name, RCN_RESTART_DI) == 0)
		{
			if (get_ap_mode() || has_wan_ip4(0))
				notify_run_detect_internet(2);
		}
		else if (strcmp(entry->d_name, RCN_RESTART_DHCPD) == 0)
		{
			if (get_ap_mode())
				update_hosts_ap();
			restart_dhcpd();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_UPNP) == 0)
		{
			restart_upnp();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_SWITCH_CFG) == 0)
		{
			config_bridge(get_ap_mode());
			switch_config_base();
			switch_config_storm();
			switch_config_link();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_SWITCH_VLAN) == 0)
		{
			notify_reset_detect_link();
			switch_config_vlan(0);
		}
		else if (strcmp(entry->d_name, RCN_RESTART_SYSLOG) == 0)
		{
			stop_logger();
			start_logger(0);
		}
		else if (strcmp(entry->d_name, RCN_RESTART_WDG) == 0)
		{
			restart_watchdog_cpu();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_TWEAKS) == 0)
		{
			notify_leds_detect_link();
		}
		else if (strcmp(entry->d_name, "restart_firewall_wan") == 0)
		{
			restart_firewall();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_FIREWALL) == 0)
		{
			reload_nat_modules();
			restart_firewall();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_NTPC) == 0)
		{
			notify_watchdog_time();
		}
		else if (strcmp(entry->d_name, RCN_RESTART_TIME) == 0)
		{
			stop_logger();
			set_timezone();
			notify_watchdog_time();
			notify_rstats_time();
			start_logger(0);
		}
		else if (strcmp(entry->d_name, RCN_RESTART_SYSCTL) == 0)
		{
			int nf_nat_type = nvram_get_int("nf_nat_type");
			
			restart_all_sysctl();
			
			/* flush conntrack after NAT model changing */
			if (nvram_nf_nat_type != nf_nat_type)
			{
				nvram_nf_nat_type = nf_nat_type;
				flush_conntrack_table(NULL);
			}
		}
		else if (!strcmp(entry->d_name, RCN_RESTART_WIFI5))
		{
			int radio_on = get_enabled_radio_wl();
			if (radio_on)
				radio_on = is_radio_allowed_wl();
			restart_wifi_wl(radio_on, 1);
		}
		else if (!strcmp(entry->d_name, RCN_RESTART_WIFI2))
		{
			int radio_on = get_enabled_radio_rt();
			if (radio_on)
				radio_on = is_radio_allowed_rt();
			restart_wifi_rt(radio_on, 1);
		}
		else if (!strcmp(entry->d_name, "control_wifi_guest_wl"))
		{
			int guest_on = is_guest_allowed_wl();
			control_guest_wl(guest_on, 1);
		}
		else if (!strcmp(entry->d_name, "control_wifi_guest_rt"))
		{
			int guest_on = is_guest_allowed_rt();
			control_guest_rt(guest_on, 1);
		}
		else if (!strcmp(entry->d_name, "control_wifi_guest_wl_on"))
		{
			control_guest_wl(1, 0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_guest_wl_off"))
		{
			control_guest_wl(0, 0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_guest_rt_on"))
		{
			control_guest_rt(1, 0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_guest_rt_off"))
		{
			control_guest_rt(0, 0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_radio_wl"))
		{
			int radio_on = get_enabled_radio_wl();
			if (radio_on)
				radio_on = is_radio_allowed_wl();
			control_radio_wl(radio_on, 1);
		}
		else if (!strcmp(entry->d_name, "control_wifi_radio_rt"))
		{
			int radio_on = get_enabled_radio_rt();
			if (radio_on)
				radio_on = is_radio_allowed_rt();
			control_radio_rt(radio_on, 1);
		}
		else if (!strcmp(entry->d_name, "control_wifi_radio_wl_on"))
		{
			control_radio_wl(1, 0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_radio_wl_off"))
		{
			control_radio_wl(0, 0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_radio_rt_on"))
		{
			control_radio_rt(1, 0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_radio_rt_off"))
		{
			control_radio_rt(0, 0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_config_wl"))
		{
			gen_ralink_config_5g(0);
		}
		else if (!strcmp(entry->d_name, "control_wifi_config_rt"))
		{
			gen_ralink_config_2g(0);
		}
		else
		{
			dbg("WARNING: rc notified of unrecognized event `%s'.\n", entry->d_name);
		}
		
		/*
		 * If there hasn't been another request for the same event made since
		 * we started, we can safely remove the ``action incomplete'' marker.
		 * Otherwise, we leave the marker because we'll go through here again
		 * for this even and mark it complete only after we've completed it
		 * without getting another request for the same event while handling
		 * it.
		 */
		test_fp = fopen(notify_name, "r");
		if (test_fp != NULL)
		{
			fclose(test_fp);
		}
		else
		{
			/* Remove the marker file. */
			snprintf(notify_name, sizeof(notify_name), "%s/%s", DIR_RC_INCOMPLETE, entry->d_name);
			remove(notify_name);
		}
		
		if (stop_handle)
			break;
	}

	closedir(directory);
}
示例#10
0
void 
init_router(void)
{
	int log_remote, is_ap_mode, nvram_need_commit;

#if defined (USE_RTL8367)
	rtl8367_node();
#endif
#if defined (USE_MTK_ESW) || defined (USE_MTK_GSW)
	mtk_esw_node();
#endif

	nvram_convert_old_params();

	nvram_need_commit = nvram_restore_defaults();

	get_eeprom_params();

	nvram_convert_misc_values();

	if (nvram_need_commit)
		nvram_commit();

	init_gpio_leds_buttons();

	gen_ralink_config_2g(0);
	gen_ralink_config_5g(0);
	load_wireless_modules();
#if (BOARD_NUM_USB_PORTS > 0)
	load_usb_modules();
#endif
	recreate_passwd_unix(1);

	set_timezone();
	set_pagecache_reclaim();

	storage_load_time();

	is_ap_mode = get_ap_mode();

	log_remote = nvram_invmatch("log_ipaddr", "");
	if (!log_remote)
		start_logger(1);

	init_loopback();
	init_bridge(is_ap_mode);
#if defined (USE_IPV6)
	init_ipv6();
#endif
	start_detect_link();
	start_detect_internet(0);
	start_lan(is_ap_mode, 0);

	if (log_remote)
		start_logger(1);

	start_dns_dhcpd(is_ap_mode);
#if defined(APP_SMBD) || defined(APP_NMBD)
	start_wins();
#endif

	if (!is_ap_mode) {
		ipt_nat_default();
		ipt_filter_default();
#if defined (USE_IPV6)
		ip6t_filter_default();
#endif
		start_wan();
	}

	start_services_once(is_ap_mode);

	notify_leds_detect_link();

	// system ready
	system("/etc/storage/started_script.sh &");
}
示例#11
0
int
main (int argc, char *argv[])
{
    int n = 0;
    time_t t = 0;
    struct sigaction sa;

    char qtype[2];
    char qclass[2];
    char header[12];
    const char *x = NULL;
    unsigned int pos = 0;
    unsigned long long qnum = 0;

    sa.sa_handler = handle_term;
    sigaction (SIGINT, &sa, NULL);
    sigaction (SIGTERM, &sa, NULL);

    sa.sa_handler = SIG_IGN;
    sigaction (SIGPIPE, &sa, NULL);

    prog = strdup ((x = strrchr (argv[0], '/')) != NULL ?  x + 1 : argv[0]);
    n = check_option (argc, argv);
    argc -= n;
    argv += n;

    if (mode & DAEMON)
        /* redirect stderr to a log file */
        redirect_to_log (logfile, STDERR_FILENO);

    time (&t);
    memset (seed, 0, sizeof (seed));
    strftime (seed, sizeof (seed), "%b-%d %Y %T %Z", localtime (&t));
    warnx ("version %s: starting %s\n", VERSION, seed);

    set_timezone ();
    if (debug_level)
        warnx ("TIMEZONE: %s", env_get ("TZ"));

    read_conf (cfgfile);
    if (!debug_level)
        if ((x = env_get ("DEBUG_LEVEL")))
            debug_level = atol (x);
    warnx ("DEBUG_LEVEL set to `%d'", debug_level);

    dns_random_init (seed);

    axfr = env_get ("AXFR");
    if (debug_level)
        warnx ("AXFR set to `%s'", axfr);
    x = env_get ("TCPREMOTEIP");
    if (debug_level)
        warnx ("TCPREMOTEIP set to `%s'", x);
    if (x)
        ip4_scan (x, ip);
    else
        byte_zero (ip, 4);

    x = env_get ("TCPREMOTEPORT");
    if (debug_level)
        warnx ("TCPREMOTEPORT set to `%s'", x);
    if (!x)
        x = "0";
    scan_ulong (x, &port);

    droproot ();
    for (;;)
    {
        netread (tcpheader, 2);
        uint16_unpack_big (tcpheader, &len);
        if (len > 512)
            errx (-1, "excessively large request");
        netread (buf, len);

        pos = dns_packet_copy (buf, len, 0, header, 12);
        if (!pos)
            errx (-1, "truncated request");
        if (header[2] & 254)
            errx (-1, "bogus query");
        if (header[4] || (header[5] != 1))
            errx (-1, "bogus query");

        pos = dns_packet_getname (buf, len, pos, &zone);
        if (!pos)
            errx (-1, "truncated request");
        zonelen = dns_domain_length (zone);
        pos = dns_packet_copy (buf, len, pos, qtype, 2);
        if (!pos)
            errx (-1, "truncated request");
        pos = dns_packet_copy (buf, len, pos, qclass, 2);
        if (!pos)
            errx (-1, "truncated request");

        if (byte_diff(qclass, 2, DNS_C_IN) && byte_diff(qclass, 2, DNS_C_ANY))
            errx (-1, "bogus query: bad class");

        log_query (++qnum, ip, port, header, zone, qtype);
        if (byte_equal(qtype,2,DNS_T_AXFR))
        {
            case_lowerb (zone, zonelen);
            fdcdb = open_read ("data.cdb");
            if (fdcdb == -1)
                errx (-1, "could not read from file `data.cdb'");
            doaxfr (header);
            close (fdcdb);
        }
        else
        {
            if (!response_query (zone, qtype, qclass))
                err (-1, "could not allocate enough memory");
            response[2] |= 4;
            case_lowerb (zone, zonelen);
            response_id (header);
            response[3] &= ~128;
            if (!(header[2] & 1))
                response[2] &= ~1;
            if (!respond (zone, qtype, ip))
                errx (-1, "could not find information in file `data.cdb'");
            print (response, response_len);
        }
    }
}
示例#12
0
static bool slurp_battery_info(struct battery_info *batt_info, yajl_gen json_gen, char *buffer, int number, const char *path, const char *format_down) {
    char *outwalk = buffer;

#if defined(LINUX)
    char buf[1024];
    memset(buf, 0, 1024);
    const char *walk, *last;
    bool watt_as_unit = false;
    int voltage = -1;
    char batpath[512];
    sprintf(batpath, path, number);
    INSTANCE(batpath);

    if (!slurp(batpath, buf, sizeof(buf))) {
        OUTPUT_FULL_TEXT(format_down);
        return false;
    }

    for (walk = buf, last = buf; (walk - buf) < 1024; walk++) {
        if (*walk == '\n') {
            last = walk + 1;
            continue;
        }

        if (*walk != '=')
            continue;

        if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_NOW=")) {
            watt_as_unit = true;
            batt_info->remaining = atoi(walk + 1);
            batt_info->percentage_remaining = -1;
        } else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_NOW=")) {
            watt_as_unit = false;
            batt_info->remaining = atoi(walk + 1);
            batt_info->percentage_remaining = -1;
        } else if (BEGINS_WITH(last, "POWER_SUPPLY_CAPACITY=") && batt_info->remaining == -1) {
            batt_info->percentage_remaining = atoi(walk + 1);
        } else if (BEGINS_WITH(last, "POWER_SUPPLY_CURRENT_NOW="))
            batt_info->present_rate = abs(atoi(walk + 1));
        else if (BEGINS_WITH(last, "POWER_SUPPLY_VOLTAGE_NOW="))
            voltage = abs(atoi(walk + 1));
        /* on some systems POWER_SUPPLY_POWER_NOW does not exist, but actually
         * it is the same as POWER_SUPPLY_CURRENT_NOW but with μWh as
         * unit instead of μAh. We will calculate it as we need it
         * later. */
        else if (BEGINS_WITH(last, "POWER_SUPPLY_POWER_NOW="))
            batt_info->present_rate = abs(atoi(walk + 1));
        else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Charging"))
            batt_info->status = CS_CHARGING;
        else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Full"))
            batt_info->status = CS_FULL;
        else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS=Discharging"))
            batt_info->status = CS_DISCHARGING;
        else if (BEGINS_WITH(last, "POWER_SUPPLY_STATUS="))
            batt_info->status = CS_UNKNOWN;
        else if (BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL_DESIGN=") ||
                 BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL_DESIGN="))
            batt_info->full_design = atoi(walk + 1);
        else if (BEGINS_WITH(last, "POWER_SUPPLY_ENERGY_FULL=") ||
                 BEGINS_WITH(last, "POWER_SUPPLY_CHARGE_FULL="))
            batt_info->full_last = atoi(walk + 1);
    }

    /* the difference between POWER_SUPPLY_ENERGY_NOW and
     * POWER_SUPPLY_CHARGE_NOW is the unit of measurement. The energy is
     * given in mWh, the charge in mAh. So calculate every value given in
     * ampere to watt */
    if (!watt_as_unit && voltage >= 0) {
        if (batt_info->present_rate > 0) {
            batt_info->present_rate = (((float)voltage / 1000.0) * ((float)batt_info->present_rate / 1000.0));
        }
        if (batt_info->remaining > 0) {
            batt_info->remaining = (((float)voltage / 1000.0) * ((float)batt_info->remaining / 1000.0));
        }
        if (batt_info->full_design > 0) {
            batt_info->full_design = (((float)voltage / 1000.0) * ((float)batt_info->full_design / 1000.0));
        }
        if (batt_info->full_last > 0) {
            batt_info->full_last = (((float)voltage / 1000.0) * ((float)batt_info->full_last / 1000.0));
        }
    }
#elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
    int state;
    int sysctl_rslt;
    size_t sysctl_size = sizeof(sysctl_rslt);

    if (sysctlbyname(BATT_LIFE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
        OUTPUT_FULL_TEXT(format_down);
        return false;
    }

    batt_info->percentage_remaining = sysctl_rslt;
    if (sysctlbyname(BATT_TIME, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
        OUTPUT_FULL_TEXT(format_down);
        return false;
    }

    batt_info->seconds_remaining = sysctl_rslt * 60;
    if (sysctlbyname(BATT_STATE, &sysctl_rslt, &sysctl_size, NULL, 0) != 0) {
        OUTPUT_FULL_TEXT(format_down);
        return false;
    }

    state = sysctl_rslt;
    if (state == 0 && batt_info->percentage_remaining == 100)
        batt_info->status = CS_FULL;
    else if ((state & ACPI_BATT_STAT_CHARGING) && batt_info->percentage_remaining < 100)
        batt_info->status = CS_CHARGING;
    else
        batt_info->status = CS_DISCHARGING;
#elif defined(__OpenBSD__)
    /*
	 * We're using apm(4) here, which is the interface to acpi(4) on amd64/i386 and
	 * the generic interface on macppc/sparc64/zaurus, instead of using sysctl(3) and
	 * probing acpi(4) devices.
	 */
    struct apm_power_info apm_info;
    int apm_fd;

    apm_fd = open("/dev/apm", O_RDONLY);
    if (apm_fd < 0) {
        OUTPUT_FULL_TEXT("can't open /dev/apm");
        return false;
    }
    if (ioctl(apm_fd, APM_IOC_GETPOWER, &apm_info) < 0)
        OUTPUT_FULL_TEXT("can't read power info");

    close(apm_fd);

    /* Don't bother to go further if there's no battery present. */
    if ((apm_info.battery_state == APM_BATTERY_ABSENT) ||
        (apm_info.battery_state == APM_BATT_UNKNOWN)) {
        OUTPUT_FULL_TEXT(format_down);
        return false;
    }

    switch (apm_info.ac_state) {
        case APM_AC_OFF:
            batt_info->status = CS_DISCHARGING;
            break;
        case APM_AC_ON:
            batt_info->status = CS_CHARGING;
            break;
        default:
            /* If we don't know what's going on, just assume we're discharging. */
            batt_info->status = CS_DISCHARGING;
            break;
    }

    batt_info->percentage_remaining = apm_info.battery_life;

    /* Can't give a meaningful value for remaining minutes if we're charging. */
    if (batt_info->status != CS_CHARGING) {
        batt_info->seconds_remaining = apm_info.minutes_left * 60;
    }
#elif defined(__NetBSD__)
    /*
     * Using envsys(4) via sysmon(4).
     */
    int fd, rval;
    bool is_found = false;
    char sensor_desc[16];

    prop_dictionary_t dict;
    prop_array_t array;
    prop_object_iterator_t iter;
    prop_object_iterator_t iter2;
    prop_object_t obj, obj2, obj3, obj4, obj5;

    if (number >= 0)
        (void)snprintf(sensor_desc, sizeof(sensor_desc), "acpibat%d", number);

    fd = open("/dev/sysmon", O_RDONLY);
    if (fd < 0) {
        OUTPUT_FULL_TEXT("can't open /dev/sysmon");
        return false;
    }

    rval = prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &dict);
    if (rval == -1) {
        close(fd);
        return false;
    }

    if (prop_dictionary_count(dict) == 0) {
        prop_object_release(dict);
        close(fd);
        return false;
    }

    iter = prop_dictionary_iterator(dict);
    if (iter == NULL) {
        prop_object_release(dict);
        close(fd);
    }

    /* iterate over the dictionary returned by the kernel */
    while ((obj = prop_object_iterator_next(iter)) != NULL) {
        /* skip this dict if it's not what we're looking for */
        if (number < 0) {
            /* we want all batteries */
            if (!BEGINS_WITH(prop_dictionary_keysym_cstring_nocopy(obj),
                             "acpibat"))
                continue;
        } else {
            /* we want a specific battery */
            if (strcmp(sensor_desc,
                       prop_dictionary_keysym_cstring_nocopy(obj)) != 0)
                continue;
        }

        is_found = true;

        array = prop_dictionary_get_keysym(dict, obj);
        if (prop_object_type(array) != PROP_TYPE_ARRAY) {
            prop_object_iterator_release(iter);
            prop_object_release(dict);
            close(fd);
            return false;
        }

        iter2 = prop_array_iterator(array);
        if (!iter2) {
            prop_object_iterator_release(iter);
            prop_object_release(dict);
            close(fd);
            return false;
        }

        struct battery_info batt_buf = {
            .full_design = 0,
            .full_last = 0,
            .remaining = 0,
            .present_rate = 0,
            .status = CS_UNKNOWN,
        };
        int voltage = -1;
        bool watt_as_unit = false;

        /* iterate over array of dicts specific to target battery */
        while ((obj2 = prop_object_iterator_next(iter2)) != NULL) {
            obj3 = prop_dictionary_get(obj2, "description");

            if (obj3 == NULL)
                continue;

            if (strcmp("charging", prop_string_cstring_nocopy(obj3)) == 0) {
                obj3 = prop_dictionary_get(obj2, "cur-value");

                if (prop_number_integer_value(obj3))
                    batt_buf.status = CS_CHARGING;
                else
                    batt_buf.status = CS_DISCHARGING;
            } else if (strcmp("charge", prop_string_cstring_nocopy(obj3)) == 0) {
                obj3 = prop_dictionary_get(obj2, "cur-value");
                obj4 = prop_dictionary_get(obj2, "max-value");
                obj5 = prop_dictionary_get(obj2, "type");

                batt_buf.remaining = prop_number_integer_value(obj3);
                batt_buf.full_design = prop_number_integer_value(obj4);

                if (strcmp("Ampere hour", prop_string_cstring_nocopy(obj5)) == 0)
                    watt_as_unit = false;
                else
                    watt_as_unit = true;
            } else if (strcmp("discharge rate", prop_string_cstring_nocopy(obj3)) == 0) {
                obj3 = prop_dictionary_get(obj2, "cur-value");
                batt_buf.present_rate = prop_number_integer_value(obj3);
            } else if (strcmp("charge rate", prop_string_cstring_nocopy(obj3)) == 0) {
                obj3 = prop_dictionary_get(obj2, "cur-value");
                batt_info->present_rate = prop_number_integer_value(obj3);
            } else if (strcmp("last full cap", prop_string_cstring_nocopy(obj3)) == 0) {
                obj3 = prop_dictionary_get(obj2, "cur-value");
                batt_buf.full_last = prop_number_integer_value(obj3);
            } else if (strcmp("voltage", prop_string_cstring_nocopy(obj3)) == 0) {
                obj3 = prop_dictionary_get(obj2, "cur-value");
                voltage = prop_number_integer_value(obj3);
            }
        }
        prop_object_iterator_release(iter2);

        if (!watt_as_unit && voltage != -1) {
            batt_buf.present_rate = (((float)voltage / 1000.0) * ((float)batt_buf.present_rate / 1000.0));
            batt_buf.remaining = (((float)voltage / 1000.0) * ((float)batt_buf.remaining / 1000.0));
            batt_buf.full_design = (((float)voltage / 1000.0) * ((float)batt_buf.full_design / 1000.0));
            batt_buf.full_last = (((float)voltage / 1000.0) * ((float)batt_buf.full_last / 1000.0));
        }

        if (batt_buf.remaining == batt_buf.full_design)
            batt_buf.status = CS_FULL;

        add_battery_info(batt_info, &batt_buf);
    }

    prop_object_iterator_release(iter);
    prop_object_release(dict);
    close(fd);

    if (!is_found) {
        OUTPUT_FULL_TEXT(format_down);
        return false;
    }

    batt_info->present_rate = abs(batt_info->present_rate);
#endif

    return true;
}

/*
 * Populate batt_info with aggregate information about all batteries.
 * Returns false on error, and an error message will have been written.
 */
static bool slurp_all_batteries(struct battery_info *batt_info, yajl_gen json_gen, char *buffer, const char *path, const char *format_down) {
#if defined(LINUX)
    char *outwalk = buffer;
    bool is_found = false;

    char *placeholder;
    char *globpath = sstrdup(path);
    if ((placeholder = strstr(path, "%d")) != NULL) {
        char *globplaceholder = globpath + (placeholder - path);
        *globplaceholder = '*';
        strcpy(globplaceholder + 1, placeholder + 2);
    }

    if (!strcmp(globpath, path)) {
        OUTPUT_FULL_TEXT("no '%d' in battery path");
        return false;
    }

    glob_t globbuf;
    if (glob(globpath, 0, NULL, &globbuf) == 0) {
        for (size_t i = 0; i < globbuf.gl_pathc; i++) {
            /* Probe to see if there is such a battery. */
            struct battery_info batt_buf = {
                .full_design = 0,
                .full_last = 0,
                .remaining = 0,
                .present_rate = 0,
                .status = CS_UNKNOWN,
            };
            if (!slurp_battery_info(&batt_buf, json_gen, buffer, i, globbuf.gl_pathv[i], format_down))
                return false;

            is_found = true;
            add_battery_info(batt_info, &batt_buf);
        }
    }
    globfree(&globbuf);
    free(globpath);

    if (!is_found) {
        OUTPUT_FULL_TEXT(format_down);
        return false;
    }

    batt_info->present_rate = abs(batt_info->present_rate);
#else
    /* FreeBSD and OpenBSD only report aggregates. NetBSD always
     * iterates through all batteries, so it's more efficient to
     * aggregate in slurp_battery_info. */
    return slurp_battery_info(batt_info, json_gen, buffer, -1, path, format_down);
#endif

    return true;
}

void print_battery_info(yajl_gen json_gen, char *buffer, int number, const char *path, const char *format, const char *format_down, const char *status_chr, const char *status_bat, const char *status_unk, const char *status_full, int low_threshold, char *threshold_type, bool last_full_capacity, bool integer_battery_capacity, bool hide_seconds) {
    const char *walk;
    char *outwalk = buffer;
    struct battery_info batt_info = {
        .full_design = -1,
        .full_last = -1,
        .remaining = -1,
        .present_rate = -1,
        .seconds_remaining = -1,
        .percentage_remaining = -1,
        .status = CS_UNKNOWN,
    };
    bool colorful_output = false;

#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
    /* These OSes report battery stats in whole percent. */
    integer_battery_capacity = true;
#endif
#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__OpenBSD__)
    /* These OSes report battery time in minutes. */
    hide_seconds = true;
#endif

    if (number < 0) {
        if (!slurp_all_batteries(&batt_info, json_gen, buffer, path, format_down))
            return;
    } else {
        if (!slurp_battery_info(&batt_info, json_gen, buffer, number, path, format_down))
            return;
    }

    // *Choose* a measure of the 'full' battery. It is whichever is better of
    // the battery's (hardware-given) design capacity (batt_info.full_design)
    // and the battery's last known good charge (batt_info.full_last).
    // We prefer the design capacity, but use the last capacity if we don't have it,
    // or if we are asked to (last_full_capacity == true); but similarly we use
    // the design capacity if we don't have the last capacity.
    // If we don't have either then both full_design and full_last <= 0,
    // which implies full <= 0, which bails out on the following line.
    int full = batt_info.full_design;
    if (full <= 0 || (last_full_capacity && batt_info.full_last > 0)) {
        full = batt_info.full_last;
    }
    if (full <= 0 && batt_info.remaining < 0 && batt_info.percentage_remaining < 0) {
        /* We have no physical measurements and no estimates. Nothing
         * much we can report, then. */
        OUTPUT_FULL_TEXT(format_down);
        return;
    }

    if (batt_info.percentage_remaining < 0) {
        batt_info.percentage_remaining = (((float)batt_info.remaining / (float)full) * 100);
        /* Some batteries report POWER_SUPPLY_CHARGE_NOW=<full_design> when fully
         * charged, even though that’s plainly wrong. For people who chose to see
         * the percentage calculated based on the last full capacity, we clamp the
         * value to 100%, as that makes more sense.
         * See http://bugs.debian.org/785398 */
        if (last_full_capacity && batt_info.percentage_remaining > 100) {
            batt_info.percentage_remaining = 100;
        }
    }

    if (batt_info.seconds_remaining < 0 && batt_info.present_rate > 0 && batt_info.status != CS_FULL) {
        if (batt_info.status == CS_CHARGING)
            batt_info.seconds_remaining = 3600.0 * (full - batt_info.remaining) / batt_info.present_rate;
        else if (batt_info.status == CS_DISCHARGING)
            batt_info.seconds_remaining = 3600.0 * batt_info.remaining / batt_info.present_rate;
        else
            batt_info.seconds_remaining = 0;
    }

    if (batt_info.status == CS_DISCHARGING && low_threshold > 0) {
        if (batt_info.percentage_remaining >= 0 && strcasecmp(threshold_type, "percentage") == 0 && batt_info.percentage_remaining < low_threshold) {
            START_COLOR("color_bad");
            colorful_output = true;
        } else if (batt_info.seconds_remaining >= 0 && strcasecmp(threshold_type, "time") == 0 && batt_info.seconds_remaining < 60 * low_threshold) {
            START_COLOR("color_bad");
            colorful_output = true;
        }
    }

#define EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT()                   \
    do {                                                       \
        if (outwalk == prevoutwalk) {                          \
            if (outwalk > buffer && isspace((int)outwalk[-1])) \
                outwalk--;                                     \
            else if (isspace((int)*(walk + 1)))                \
                walk++;                                        \
        }                                                      \
    } while (0)

    for (walk = format; *walk != '\0'; walk++) {
        char *prevoutwalk = outwalk;

        if (*walk != '%') {
            *(outwalk++) = *walk;
            continue;
        }

        if (BEGINS_WITH(walk + 1, "status")) {
            const char *statusstr;
            switch (batt_info.status) {
                case CS_CHARGING:
                    statusstr = status_chr;
                    break;
                case CS_DISCHARGING:
                    statusstr = status_bat;
                    break;
                case CS_FULL:
                    statusstr = status_full;
                    break;
                default:
                    statusstr = status_unk;
            }

            outwalk += sprintf(outwalk, "%s", statusstr);
            walk += strlen("status");
        } else if (BEGINS_WITH(walk + 1, "percentage")) {
            if (integer_battery_capacity) {
                outwalk += sprintf(outwalk, "%.00f%s", batt_info.percentage_remaining, pct_mark);
            } else {
                outwalk += sprintf(outwalk, "%.02f%s", batt_info.percentage_remaining, pct_mark);
            }
            walk += strlen("percentage");
        } else if (BEGINS_WITH(walk + 1, "remaining")) {
            if (batt_info.seconds_remaining >= 0) {
                int seconds, hours, minutes;

                hours = batt_info.seconds_remaining / 3600;
                seconds = batt_info.seconds_remaining - (hours * 3600);
                minutes = seconds / 60;
                seconds -= (minutes * 60);

                if (hide_seconds)
                    outwalk += sprintf(outwalk, "%02d:%02d",
                                       max(hours, 0), max(minutes, 0));
                else
                    outwalk += sprintf(outwalk, "%02d:%02d:%02d",
                                       max(hours, 0), max(minutes, 0), max(seconds, 0));
            }
            walk += strlen("remaining");
            EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
        } else if (BEGINS_WITH(walk + 1, "emptytime")) {
            if (batt_info.seconds_remaining >= 0) {
                time_t empty_time = time(NULL) + batt_info.seconds_remaining;
                set_timezone(NULL); /* Use local time. */
                struct tm *empty_tm = localtime(&empty_time);

                if (hide_seconds)
                    outwalk += sprintf(outwalk, "%02d:%02d",
                                       max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0));
                else
                    outwalk += sprintf(outwalk, "%02d:%02d:%02d",
                                       max(empty_tm->tm_hour, 0), max(empty_tm->tm_min, 0), max(empty_tm->tm_sec, 0));
            }
            walk += strlen("emptytime");
            EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
        } else if (BEGINS_WITH(walk + 1, "consumption")) {
            if (batt_info.present_rate >= 0)
                outwalk += sprintf(outwalk, "%1.2fW", batt_info.present_rate / 1e6);

            walk += strlen("consumption");
            EAT_SPACE_FROM_OUTPUT_IF_NO_OUTPUT();
        }
    }

    if (colorful_output)
        END_COLOR;

    OUTPUT_FULL_TEXT(buffer);
}
示例#13
0
int memcache_get (struct connection *c, const char *key, int len) {
  char *ptr;
  //char timezone[32];
  long long cnt_id;
  if (verbosity >= 4) {
    fprintf (stderr, "memcache_get (key = \"");
    debug_key (key, len);
    fprintf (stderr, "\")\n");
  }
  int dog_len = get_at_prefix_length (key, len);
  key += dog_len;
  len -= dog_len;

  Q_raw = 0;
  if (len > 0 && *key == '%') {
    dog_len ++;
    key ++;
    len --;
    Q_raw = 1;
  }


  if (len > 5 && !strncmp (key, "views", 5)) {
    int ver;
    if (!parse_countid_with_version (key + 5, &cnt_id, &ver)) {
      debug_error ("get", "couldn't parse count_id&version", key, len);
      return not_found (c);
    }
    //int res = get_counter_views(cnt_d, ver); TODO!!!
    int res = (ver == -1) ? get_counter_views (cnt_id) : get_counter_views_given_version (cnt_id,ver);
    if (res == -2) {
      return memcache_wait (c);
    }
    if (res >= 0) {
      //int return_one_key (struct connection *c, const char *key, char *val, int vlen) {
      if (!Q_raw) {
        return_one_key (c, key - dog_len, stats_buff, sprintf (stats_buff, "%d", res));
      } else {
        *(int *)stats_buff = res;
        return_one_key (c, key - dog_len, stats_buff, sizeof (int));
      }
    }
    return 0;
  }

  if (len > 8 && !strncmp (key, "visitors", 8)) {
    int ver;
    if (!parse_countid_with_version (key + 8, &cnt_id, &ver)) {
      debug_error ("get","couldn't parse count_id&version",key, len);
      return not_found(c);
    }
    //int res = get_counter_visitors(cnt_id, ver); TODO !!!
    int res = (ver == -1) ? get_counter_visitors (cnt_id) : get_counter_visitors_given_version (cnt_id, ver);
    if (res == -2) {
      return memcache_wait (c);
    }
    if (res >= 0) {
      //int return_one_key (struct connection *c, const char *key, char *val, int vlen) {
      if (!Q_raw) {
        return_one_key (c, key - dog_len, stats_buff, sprintf (stats_buff, "%d", res));
      } else {
        *(int *)stats_buff = res;
        return_one_key (c, key - dog_len, stats_buff, sizeof (int));
      }
    }
    return 0;
  }

  if (len > 14 && !strncmp (key, "enable_counter", 14)) {
    cnt_id = strtoll (key + 14, &ptr, 10);
    if (ptr > key + 14 && !*ptr) {
      int res = enable_counter (cnt_id, 0);
      if (res >= 0) {
      if (!Q_raw) {
        return_one_key (c, key - dog_len, stats_buff, sprintf (stats_buff, "%d", res));
      } else {
        *(int *)stats_buff = res;
        return_one_key (c, key - dog_len, stats_buff, sizeof (int));
      }
      }
      return 0;
    }
  }

  if (len > 15 && !strncmp (key, "disable_counter", 15)) {
    cnt_id = strtoll (key + 15, &ptr, 10);
    if (ptr > key + 15 && !*ptr) {
      int res = disable_counter (cnt_id, 0);
      if (!Q_raw) {
        return_one_key (c, key - dog_len, stats_buff, sprintf (stats_buff, "%d", res));
      } else {
        *(int *)stats_buff = res;
        return_one_key (c, key - dog_len, stats_buff, sizeof (int));
      }
      return 0;
    }
  }

  if (len > 12 && !strncmp(key, "set_timezone", 12)) {
    int tz = 0;
    //if (2 == sscanf(key+12,"%d#%31s",&cnt_id,timezone)) {
    if (2 == sscanf(key + 12,"%lld#%d", &cnt_id, &tz)) {
      tz = tz + 12 + 4;
      if (tz < 0) {
        return 0;
      }
      int res = set_timezone (cnt_id, tz, 0);
      if (!Q_raw) {
        return_one_key (c, key - dog_len, stats_buff, sprintf (stats_buff, "%d", res));
      } else {
        *(int *)stats_buff = res;
        return_one_key (c, key - dog_len, stats_buff, sizeof (int));
      }
      return 0;
    }
  }

  if (len > 8 && !strncmp(key, "timezone", 8)) {
    if (1 == sscanf(key + 8, "%lld", &cnt_id)) {
      int res = get_timezone (cnt_id);
      if (!Q_raw) {
        return_one_key (c, key - dog_len, stats_buff, sprintf (stats_buff, "%d", res));
      } else {
        *(int *)stats_buff = res;
        return_one_key (c, key - dog_len, stats_buff, sizeof (int));
      }
      return 0;
    }
  }


  if (len > 7 && !strncmp (key, "counter", 7)) {
    int ver = 0;
    if (sscanf (key, "counter%lld@%d", &cnt_id, &ver) >= 1) {
      int to_serialize = key[strlen(key) - 1] != '?';
      if (verbosity >= 4) {
        fprintf(stderr, "cnt_id = %lld, ver = %d\n", cnt_id, ver);
      }
      int res = get_counter_serialized (stats_buff, cnt_id, ver);
      if (res == -2) {
        return memcache_wait (c);
      }
      if (res > 0) {
        if (to_serialize && !Q_raw) {
          write_out (&c->Out, stats_buff+res, sprintf (stats_buff+res, "VALUE %s 1 %d\r\n", key - dog_len, res));
        } else {
          write_out (&c->Out, stats_buff+res, sprintf (stats_buff+res, "VALUE %s 0 %d\r\n", key - dog_len, res));
        }
        write_out (&c->Out, stats_buff, res);
        write_out (&c->Out, "\r\n", 2);
      }
      return 0;
    }
  }

  if (len > 16 && !strncmp (key, "monthly_visitors", 16)) {
    cnt_id = 0;
    if (sscanf (key, "monthly_visitors%lld", &cnt_id) >= 1) {
      int res = get_monthly_visitors_serialized (stats_buff, cnt_id);
      if (res == -2) {
        return memcache_wait (c);
      }
      if (res >= 0) {
        return_one_key (c, key - dog_len, stats_buff, res);
      }
      return 0;
    }
  }

  if (len > 13 && !strncmp (key, "monthly_views", 13)) {
    cnt_id = 0;
    if (sscanf (key, "monthly_views%lld", &cnt_id) >= 1) {
      int res = get_monthly_views_serialized (stats_buff, cnt_id);
      if (res == -2) {
        return memcache_wait (c);
      }
      if (res >= 0) {
        return_one_key (c, key - dog_len, stats_buff, res);
      }
      return 0;
    }
  }

  if (len > 12 && !strncmp (key, "counters_sum", 12)) {
    int start_id = 0, finish_id = 0, id = 0;
    int to_serialize = key[strlen(key) - 1] != '?';
    if (sscanf (key, "counters_sum%d_%d_%d", &id, &start_id, &finish_id)) {
      struct counter *C = get_counters_sum (id, start_id, finish_id);
      if (C == (void *)-2l) { 
        return memcache_wait (c);
      }
      if (C) {
        int res = counter_serialize (C, stats_buff);
        assert (res >= 0);
        if (to_serialize && !Q_raw) {
          write_out (&c->Out, stats_buff+res, sprintf (stats_buff+res, "VALUE %s 1 %d\r\n", key - dog_len, res));
        } else {
          write_out (&c->Out, stats_buff+res, sprintf (stats_buff+res, "VALUE %s 0 %d\r\n", key - dog_len, res));
        }
        write_out (&c->Out, stats_buff, res);
        write_out (&c->Out, "\r\n", 2);
      }
    }
  }
  /*
  if (len > 7 && !strncmp (key, "counter", 7)) {
    int cnt_id, subcnt_id = -1, ver = 0;
    if (sscanf (key, "counter%d:%d@%d", &cnt_id, &subcnt_id, &ver) >= 2) {
      //int res = get_counter_serialized (stats_buff, cnt_id, subcnt_id, ver); TODO !!!
      int res = get_counter_serialized (stats_buff, cnt_id, ver);
      if (res > 0) {
        write_out (&c->Out, stats_buff+res, sprintf (stats_buff+res, "VALUE %s 1 %d\r\n", key, res));
        write_out (&c->Out, stats_buff, res);
        write_out (&c->Out, "\r\n", 2);
      }
      return 0;
    }
    if (sscanf (key, "counter%d@%d", &cnt_id, &ver) == 2) {
      //int res = get_counter_serialized (stats_buff, cnt_id, -1, ver); TODO !!!
      int res = get_counter_serialized (stats_buff, cnt_id, ver);
      if (res > 0) {
        write_out (&c->Out, stats_buff+res, sprintf (stats_buff+res, "VALUE %s 1 %d\r\n", key, res));
        write_out (&c->Out, stats_buff, res);
        write_out (&c->Out, "\r\n", 2);
      }
      return 0;
    }
  }
  */

  if (len > 8 && !strncmp (key, "versions", 8)) {
    cnt_id = strtoll (key + 8, &ptr, 10);
    if (ptr > key+8 && !*ptr) {
      int res = get_counter_versions (stats_buff, cnt_id);
      if (res == -2) {
        return memcache_wait (c);
      }
      if (res > 0) {
        write_out (&c->Out, stats_buff + res, sprintf (stats_buff + res, "VALUE %s 0 %d\r\n", key - dog_len, res));
        write_out (&c->Out, stats_buff, res);
        write_out (&c->Out, "\r\n", 2);
      }
      return 0;
    }
  }

  if (len >= 16 && !strncmp (key, "free_block_stats", 16)) {
    return_one_key_list (c, key - dog_len, len + dog_len, MAX_RECORD_WORDS, 0, FreeCnt, MAX_RECORD_WORDS);
    return 0;
  }

  if (len >= 16 && !strncmp (key, "used_block_stats", 16)) {
    return_one_key_list (c, key - dog_len, len + dog_len, MAX_RECORD_WORDS, 0, UsedCnt, MAX_RECORD_WORDS);
    return 0;
  }

  if (len >= 16 && !strncmp (key, "allocation_stats", 16)) {
    return_one_key_list (c, key - dog_len, len + dog_len, MAX_RECORD_WORDS, 0, NewAllocations[0], MAX_RECORD_WORDS * 4);
    return 0;
  }

  if (len >= 17 && !strncmp (key, "split_block_stats", 17)) {
    return_one_key_list (c, key - dog_len, len + dog_len, MAX_RECORD_WORDS, 0, SplitBlocks, MAX_RECORD_WORDS);
    return 0;
  }

  if (len >= 5 && !strncmp (key, "stats", 5)) {
    return_one_key (c, key - dog_len, stats_buff, stats_prepare_stats (c));
    return 0;
  }

  return 0;
}
示例#14
0
static bool process_write_cmd(void) {
	bool success = true;
	reset_modified_state();
	send_zcl_header(CMDID_WRITE_RESPONSE);

	while(msg_available()) {
		uint16_t attr = msg_get_16();

		if (zcl.packet.cluster == CLUSTERID_BASIC) {
			switch(attr) {
			case ATTR_DEVICE_ENABLED:
				if (msg_get() == TYPE_BOOLEAN) {
					uint8_t state = msg_get();
					if (state == BOOL_TRUE) {
						WET set_mode(MODE_PLAYLIST);
					} else if (state == BOOL_FALSE) {
						WET set_mode(MODE_IDLE);
					}
				} else {
					success = false;
					send_cmd_status(attr, STATUS_INVALID_DATA_TYPE);
				}
				break;
			case ATTR_ALARM_MASK:
				//TODO
				break;
			default:
				send_cmd_status(attr, STATUS_UNSUPPORTED_ATTRIBUTE);
				success = false;
				break;
			}
		} else if (zcl.packet.cluster == CLUSTERID_ELOVALO) {
			switch(attr) {
			case ATTR_IEEE_ADDRESS:
				if (msg_get() == TYPE_IEEE_ADDRESS) {
					// TODO write to EEPROM
					uint64_t x = msg_get_64();
					WET {
						mac = x;
						eeprom_update_block(&mac, &eeprom_mac,
								    sizeof(mac));
					}
				} else {
					success = false;
					send_cmd_status(attr, STATUS_INVALID_DATA_TYPE);
				}
				break;
			case ATTR_OPERATING_MODE:
				if (msg_get() == TYPE_ENUM) {
					uint8_t mode = msg_get();
					WET set_mode(mode);
				} else {
					success = false;
					send_cmd_status(attr, STATUS_INVALID_DATA_TYPE);
				}
				break;
			case ATTR_EFFECT_TEXT:
				if (msg_get() == TYPE_OCTET_STRING) {
					uint8_t len = msg_get();
					if (len == 0xff) len = 0; // Invalid value
					WET utf8_string_to_eeprom(msg_i,len);
					WET mark_text_modified();
					msg_i += len; // Put pointer to the end
				} else {
					success = false;
					send_cmd_status(attr, STATUS_INVALID_DATA_TYPE);
				}
				break;
			case ATTR_PLAYLIST:
				if (msg_get() == TYPE_UINT8) {
					uint8_t x = msg_get();
					WET store_playlist(x);
				} else {
					success = false;
					send_cmd_status(attr, STATUS_INVALID_DATA_TYPE);
				}
				break;
			case ATTR_TIMEZONE:
			{
				if (msg_get() == TYPE_INT32) {
					int32_t x = msg_get_i32();
					WET set_timezone(x);
				} else {
					success = false;
					send_cmd_status(attr, STATUS_INVALID_DATA_TYPE);
				}
				break;
			}
			case ATTR_TIME:
				if (msg_get() == TYPE_UTC_TIME) {
					time_t t = msg_get_32()+ZIGBEE_TIME_OFFSET;
					WET stime(&t);
				} else {
					success = false;
					send_cmd_status(attr, STATUS_INVALID_DATA_TYPE);
				}
				break;
			case ATTR_EFFECT:
				if (msg_get() == TYPE_UINT8) {
					uint8_t x = msg_get();
					WET store_effect(x);
				} else {
					success = false;
					send_cmd_status(attr, STATUS_INVALID_DATA_TYPE);
				}
				break;
			case ATTR_PLAYLIST_POSITION:
				send_cmd_status(attr, STATUS_READ_ONLY);
				success = false;
				break;
			default:
				send_cmd_status(attr, STATUS_UNSUPPORTED_ATTRIBUTE);
				success = false;
				break;
			}
		} else {