Exemplo n.º 1
0
static size_t
hdrfunc(void *ptr, size_t size, size_t nmemb, void *userdata)
{
  cache_entry_t *ce = userdata;
  char *argv[2];
  size_t len = size * nmemb;
  char *line = alloca(len + 1);
  memcpy(line, ptr, len);
  line[len] = 0;

  line[strcspn(line, "\n\r")] = 0;
  if(str_tokenize(line, argv, 2, -1) != 2)
    return len;
  char *c;
  if((c = strrchr(argv[0], ':')) == NULL)
    return len;
  *c = 0;

  if(!strcasecmp(argv[0], "etag")) {
    free(ce->ce_etag);
    ce->ce_etag = strdup(argv[1]);
  }

  if(!strcasecmp(argv[0], "cache-control")) {
    const char *ma = strstr(argv[1], "max-age=");
    if(ma != NULL) {
      int max_age = atoi(ma + strlen("max-age="));
      ce->ce_expire = time(NULL) + max_age;
    }
  }
  return len;
}
Exemplo n.º 2
0
int main() {
   std::string s;
   std::getline(std::cin, s);
   std::vector<std::pair<int, int> > tokens;

   str_tokenize(s, tokens);
   print_tokens(s, tokens);

   return 0;
}
Exemplo n.º 3
0
        inline obj_vertex(const std::string &string) {
            std::vector<std::string> tokens = str_tokenize(string, '/', true);

            if (tokens.size() < 1 || tokens.size() > 3)
                throw std::runtime_error("Invalid vertex data: \"" + string + "\"");

            p = str_to_uint32_t(tokens[0]);

#if 0
            if (tokens.size() >= 2 && !tokens[1].empty())
                uv = str_to_uint32_t(tokens[1]);

            if (tokens.size() >= 3 && !tokens[2].empty())
                n = str_to_uint32_t(tokens[2]);
#endif
        }
Exemplo n.º 4
0
void run_command_expect(char *args)
{
    char **tokens;
    int count;

    ++tests_performed;

    str_tokenize(args, &tokens, &count);

    if (count == 1) {

        if (strcmp(tokens[0], "SUCCESS") == 0) {
            if (unexpected_fails) {
                report_failure(
                    "Expected success, but %d unexpected failure(s) encountered",
                    unexpected_fails);
            }
        } else if (strcmp(tokens[0], "FAILURE") == 0) {
            if (!unexpected_fails) {
                report_failure("Expected failure, but none encountered");
            } else {
                --unexpected_fails;
            }
        } else {
            fprintf(stderr, "Unexpected single EXPECT argument: %s", tokens[0]);
            exit(1);
        }

    } else if (count == 2) {

        char *type_string = tokens[0];
        char *value_string = tokens[1];

        if (unexpected_fails) {
            report_failure(
                "%d unexpected failure(s) encountered before an expect check",
                unexpected_fails);
        } else if (strcmp(type_string, "bool") == 0) {

            enum ValueType last_type = rt_val_peek_type(&rt->stack, last_loc);
            if (last_type != VAL_BOOL) {
                report_failure(
                    "Expected boolean result type, but %s encountered",
                    type_to_string(last_type));
            } else if (strcmp(value_string, "true") == 0) {
                if (!rt_val_peek_bool(rt, last_loc)) {
                    report_failure("Expected true value, but false encountered");
                }
            } else if (strcmp(value_string, "false") == 0) {
                if (rt_val_peek_bool(rt, last_loc)) {
                    report_failure("Expected false value, but true encountered");
                }
            } else {
                fprintf(stderr, "Unexpected bool literal: %s", value_string);
                exit(1);
            }

        } else if (strcmp(type_string, "int") == 0) {

            enum ValueType last_type = rt_val_peek_type(&rt->stack, last_loc);
            if (last_type != VAL_INT) {
                report_failure(
                    "Expected integer result type, but %s encountered",
                    type_to_string(last_type));
            } else {
                int expected = (int)strtol(value_string, (char**)NULL, 10);
                int actual = rt_val_peek_int(rt, last_loc);
                if (expected != actual) {
                    report_failure("Expected %d, but %d encountered", expected, actual);
                }
            }

        } else if (strcmp(type_string, "real") == 0) {

            enum ValueType last_type = rt_val_peek_type(&rt->stack, last_loc);
            if (last_type != VAL_REAL) {
                report_failure(
                    "Expected real result type, but %s encountered",
                    type_to_string(last_type));
            } else {
                double expected = strtod(value_string, (char**)NULL);
                double actual = rt_val_peek_real(rt, last_loc);
                if (expected != actual) {
                    report_failure("Expected %f, but %f encountered", expected, actual);
                }
            }

        } else if (strcmp(type_string, "char") == 0) {

            enum ValueType last_type = rt_val_peek_type(&rt->stack, last_loc);
            if (last_type != VAL_CHAR) {
                report_failure(
                    "Expected character result type, but %s encountered",
                    type_to_string(last_type));
            } if (strlen(value_string) != 1) {
                fprintf(stderr, "Incorrect value for char expectation: %s", value_string);
                exit(1);
            } else {
                char expected = value_string[0];
                char actual = rt_val_peek_char(rt, last_loc);
                if (expected != actual) {
                    report_failure("Expected %c, but %c encountered", expected, actual);
                }
            }

        } else if (strcmp(type_string, "string") == 0) {

            enum ValueType last_type = rt_val_peek_type(&rt->stack, last_loc);
            if (!rt_val_is_string(rt, last_loc)) {
                report_failure(
                    "Expected string result type, but %s encountered",
                    type_to_string(last_type));
            } else {
                char *actual = rt_val_peek_cpd_as_string(rt, last_loc);
                char *expected = value_string;
                if (strcmp(expected, actual) != 0) {
                    report_failure("Expected %s, but %s encountered", expected, actual);
                }
                mem_free(actual);
            }

        } else {
            fprintf(stderr, "Unexpected EXPECT type argument: %s", type_string);
            exit(1);
        }

    } else {
        fprintf(stderr, "Incorrect arguments count to EXPECT: %d", count);
        exit(1);
    }
}
int main(int argc, char*argv[])
{
	char *conf_file_name = NULL;
	FILE *conf_file_pointer = NULL;
	char line[LINE_MAX] = {'\0'};
	char *tokens[TOKEN_MAX] = {NULL};
	int count = 0;
	sensor_create_params sensor_device = {NULL, NULL, NULL};
	sensor_handle sensor = NULL;

	LOG_DEBUG(("DEBUG: Number of arguments are: %d\n", argc));

	if(argc<3)
	{
		LOG_ERROR(("ERROR: Please provide configuration file name(s)\n"));
		return (0);
	}

	conf_file_name = argv[1];

	LOG_DEBUG(("DEBUG: Configuration File Name is %s\n", conf_file_name));

	conf_file_pointer = fopen(conf_file_name, "r");
	if(!conf_file_pointer)
	{
		LOG_ERROR(("ERROR: Error in opening configuration file\n"));
		return (0);
	}

	/* Read line */
	if(fgets(line, LINE_MAX, conf_file_pointer) == NULL)
	{
		LOG_DEBUG(("DEBUG: Cleanup and return\n"));
		fclose(conf_file_pointer);
		LOG_ERROR(("ERROR: Wrong configuration file\n"));
		return (0);
	}
	str_tokenize(line, ":\n\r", tokens, &count);
	if(count<2)
	{
		LOG_ERROR(("ERROR: Wrong configuration file\n"));
		fclose(conf_file_pointer);
		return (0);
	}

	str_copy(&sensor_device.gateway_ip_address, tokens[0]);
	str_copy(&sensor_device.gateway_port_no, tokens[1]);
	LOG_DEBUG(("DEBUG: Gateway IP Address: %s\n", sensor_device.gateway_ip_address));
	LOG_DEBUG(("DEBUG: Gateway Port No: %s\n", sensor_device.gateway_port_no));

	/* Read line */
	if (fgets(line, LINE_MAX, conf_file_pointer) == NULL)
	{
		LOG_DEBUG(("DEBUG: Cleanup and return\n"));
		fclose(conf_file_pointer);
		LOG_ERROR(("ERROR: Wrong configuration file\n"));
		return (0);
	}
	str_tokenize(line, ":\r\n", tokens, &count);
	if (count < 4)
	{
		LOG_ERROR(("ERROR: Wrong configuration file\n"));
		fclose(conf_file_pointer);
		return (0);
	}
	if(strcmp("sensor", tokens[0])!=0)
	{
		LOG_ERROR(("ERROR: Wrong configuration file\n"));
		fclose(conf_file_pointer);
		return (0);
	}
	str_copy(&sensor_device.sensor_ip_address, tokens[1]);
	str_copy(&sensor_device.sensor_port_no, tokens[2]);
	str_copy(&sensor_device.sensor_area_id, tokens[3]);

	sensor_device.sensor_value_file_name = argv[2];

	LOG_DEBUG(("DEBUG: sensor ip_address: %s\n", sensor_device.sensor_ip_address));
	LOG_DEBUG(("DEBUG: sensor port_no: %s\n", sensor_device.sensor_port_no));
	LOG_DEBUG(("DEBUG: sensor area_id: %s\n", sensor_device.sensor_area_id));

	int return_value = create_sensor(&sensor, &sensor_device);
	if(return_value != E_SUCCESS)
	{
		LOG_ERROR(("ERROR: Unable to create sensor\n"));
		free(sensor_device.gateway_ip_address);
		free(sensor_device.gateway_port_no);
		free(sensor_device.sensor_area_id);
		free(sensor_device.sensor_ip_address);
		free(sensor_device.sensor_port_no);
		fclose(conf_file_pointer);
		return (0);
	}

	LOG_ERROR(("Sensor started successfully\n"));

	char choice;

	printf("Press enter to exit\n");
	scanf("%c", &choice);
	delete_sensor(sensor);

	free(sensor_device.gateway_ip_address);
	free(sensor_device.gateway_port_no);
	free(sensor_device.sensor_area_id);
	free(sensor_device.sensor_ip_address);
	free(sensor_device.sensor_port_no);
	fclose(conf_file_pointer);
	logger_close();
	return (0);
}
Exemplo n.º 6
0
Arquivo: http.c Projeto: azzurra/apm
static void http_request_parse(http_struct *conn) {

	char *err, *ptr;
	char token[32];
	long int port = 0;
	int found = 0;


	switch (conn->zone->idx) {

		case 0:
			ptr = strstr(conn->response, "<td class=\"protohead\">Protocol</td>");

			if ((ptr == NULL) || ((conn->bytes_read - (ptr - conn->response)) < 48)) {

				log_snoop("Error parsing OPM http reply for IP %s: data not found", conn->ip);
				return;
			}

			ptr += 48;

			while (1) {

				ptr = str_tokenize(ptr, token, sizeof(token), '<');

				if ((ptr == NULL) || (token[0] == '\0')) {

					log_snoop("Error parsing OPM http reply for IP %s: port not found", conn->ip);
					return;
				}

				if (!strcasecmp(token, "Evidence")) {

					if (found == 0) {

						if (conn->requested == 1)
							log_snoop("[%s] IP \2%s\2 is positive on known ports only [Details: http://%s%s%s ] [Requested by %s]", conn->zone->name, conn->ip, conn->zone->host, conn->zone->url, conn->ip, conn->nick);
						else
							log_snoop("[%s] IP \2%s\2 used by \2%s\2 is positive on known ports only [Details: http://%s%s%s ]", conn->zone->name, conn->ip, conn->nick, conn->zone->host, conn->zone->url, conn->ip);
					}

					return;
				}

				port = strtol(token, &err, 10);

				if ((port <= 0) || (port > 65535) || (*err != '\0')) {

					log_snoop("Error parsing OPM http reply for IP %s: invalid port (%s)", conn->ip, token);
					return;
				}

				if ((conn->bytes_read - (ptr - conn->response)) < 8) {

					log_snoop("Error parsing OPM http reply for IP %s: invalid protocol data", conn->ip);
					return;
				}

				ptr = str_tokenize(ptr + 8, token, sizeof(token), '<');

				if ((ptr == NULL) || (token[0] == '\0')) {

					log_snoop("Error parsing OPM http reply for IP %s: protocol not found", conn->ip);
					return;
				}

				if ((conn->bytes_read - (ptr - conn->response)) < 17) {

					log_snoop("Error parsing OPM http reply for IP %s: invalid end data", conn->ip);
					return;
				}

				ptr += 17;

				found += scan_http_result(conn, port, token);
			}
			break;

		case 1: {	/* DSBL */

			http_struct *newconn;
			size_t len;

			ptr = strstr(conn->response, "<h1>DSBL: Message Detail</h1>");

			if (IS_NOT_NULL(ptr)) {

				char protocol[32];

				memset(protocol, 0, sizeof(protocol));

				ptr = strstr(conn->response, "<b>Transport:</b>");

				if (IS_NOT_NULL(ptr)) {

					ptr = str_tokenize(ptr + 18, protocol, sizeof(protocol), '\n');

					if ((ptr == NULL) || (protocol[0] == '\0')) {

						log_snoop("Error parsing DSBL http reply for IP %s: invalid transport (%s)", conn->ip, protocol);
						return;
					}
				}

				ptr = strstr(conn->response, "<b>Input Port:</b>");

				if (IS_NOT_NULL(ptr)) {

					ptr = str_tokenize(ptr + 19, token, sizeof(token), '\n');

					if ((ptr == NULL) || (token[0] == '\0')) {

						log_snoop("Error parsing DSBL http reply for IP %s: invalid port (%s)", conn->ip, token);
						return;
					}

					port = strtol(token, &err, 10);

					if ((port < 0) || (port > 65535) || (*err != '\0')) {

						log_snoop("Error parsing DSBL http reply for IP %s: invalid port (%s)", conn->ip, token);
						return;
					}
				}

				if ((port == 0) || (protocol[0] == '\0')) {

					ptr = strstr(conn->response, "Port ");

					if ((ptr == NULL) || ((conn->bytes_read - (ptr - conn->response)) < 30)) {

						log_snoop("Error parsing DSBL http reply for IP %s: invalid data", conn->ip);
						return;
					}

					ptr = str_tokenize(ptr + 5, token, sizeof(token), ',');

					if ((ptr == NULL) || (token[0] == '\0')) {

						log_snoop("Error parsing DSBL http reply for IP %s: port not found", conn->ip);
						return;
					}

					port = strtol(token, &err, 10);

					if ((port < 0) || (port > 65535) || (*err != '\0')) {

						log_snoop("Error parsing DSBL http reply for IP %s: invalid port (%s)", conn->ip, token);
						return;
					}

					ptr = str_tokenize(ptr + 1, protocol, sizeof(protocol), ',');

					if ((ptr == NULL) || (protocol[0] == '\0')) {

						log_snoop("Error parsing DSBL http reply for IP %s: protocol not found", conn->ip);
						return;
					}
				}
				log_snoop("Discovered Port: \2%i\2",port);
				if (port == 21)
				{
					log_snoop("Found anonymous FTP server, skip check");
					return;
				}
				log_snoop("I'm checking for open proxies");


				if ((!scan_http_result(conn, port, protocol)) && (!scan_http_result(conn, port, "SOCKS")) && (!scan_http_result( conn, port, "HTTPPOST")) && (!scan_http_result( conn, port, "HTTP"))) {

					if (conn->requested == 1)
						log_snoop("[%s] IP \2%s\2 is positive on known ports only [Details: http://%s%s%s ] [Requested by %s]", conn->zone->name, conn->ip, conn->zone->host, conn->zone->url, conn->ip, conn->nick);
					else
						log_snoop("[%s] IP \2%s\2 used by \2%s\2 is positive on known ports only [Details: http://%s%s%s ]", conn->zone->name, conn->ip, conn->nick, conn->zone->host, conn->zone->url, conn->ip);
				}

				return;
			}

			ptr = strstr(conn->response, "<h2>Messages from this host</h2>");

			if ((ptr == NULL) || ((conn->bytes_read - (ptr - conn->response)) < 10)) {

				log_snoop("Error parsing DSBL http reply for IP %s: data not found", conn->ip);
				return;
			}

			ptr += 32;

			while (1) {

				ptr = strstr(ptr, "UTC");

				if (IS_NULL(ptr))
					break;

				if ((conn->bytes_read - (ptr - conn->response)) < 50) {

					log_snoop("Error parsing DSBL http reply for IP %s: invalid message", conn->ip);
					return;
				}

				ptr = str_tokenize(ptr + 13, token, sizeof(token), '"');

				if ((ptr == NULL) || (token[0] == '\0')) {

					log_snoop("Error parsing DSBL http reply for IP %s: message url not found", conn->ip);
					return;
				}

				/* Message parsed and written into 'token'. Continue, as we want the last one. */
			}

			log_event(6, "HTTP -> Sending request to %s for IP %s", conn->zone->name, conn->ip);

			newconn = (http_struct *) calloc(1, sizeof(http_struct));

			strncpy(newconn->ip, conn->ip, sizeof(newconn->ip));

			len = strlen(token);

			newconn->url = malloc(len + 2);

			newconn->url[0] = '/';
			memcpy(newconn->url + 1, token, len);
			newconn->url[len + 1] = '\0';

			strncpy(newconn->nick, conn->nick, sizeof(newconn->nick));

			newconn->zone = conn->zone;

			if (conn->requested)
				newconn->requested = conn->requested;

			/* Queue connection. */
			newconn->state = STATE_UNESTABLISHED;

			/* Add struct to list of connections. */
			http_conn_add(newconn);

			/* If we have available FD's, override queue. */
			if (FD_USE < CONF_FDLIMIT)
				http_establish(newconn);
			else
				log_event(6, "HTTP -> File Descriptor limit (%d) reached, queuing request for IP %s on %s", CONF_FDLIMIT, conn->ip, conn->zone->name);

			break;
		}

		case 2: {	/* SORBS */

			char *endtag, *protocol;
			int skip;

			ptr = conn->response;

			while (1) {

				ptr = strstr(ptr, "Address and Port:");

				if (IS_NULL(ptr)) {

					if (found == 0) {

						if (conn->requested == 1)
							log_snoop("[%s] IP \2%s\2 is positive on known ports only [Details: http://%s%s%s ] [Requested by %s]", conn->zone->name, conn->ip, conn->zone->host, conn->zone->url, conn->ip, conn->nick);
						else
							log_snoop("[%s] IP \2%s\2 used by \2%s\2 is positive on known ports only [Details: http://%s%s%s ]", conn->zone->name, conn->ip, conn->nick, conn->zone->host, conn->zone->url, conn->ip);
					}

					return;
				}

				if ((conn->bytes_read - (ptr - conn->response)) < 46) {

					log_snoop("Error parsing SORBS http reply for IP %s: invalid data", conn->ip);
					return;
				}

				ptr = str_tokenize(ptr + 30 + strlen(conn->ip), token, sizeof(token), '<');

				if (IS_NULL(ptr) || (token[0] == '\0')) {

					log_snoop("Error parsing SORBS http reply for IP %s: port not found", conn->ip);
					return;
				}

				port = strtol(token, &err, 10);

				if ((port < 0) || (port > 65535) || (*err != '\0')) {

					log_snoop("Error parsing SORBS http reply for IP %s: invalid port (%s)", conn->ip, token);
					return;
				}

				endtag = strstr(ptr, "<!--/#result-->");

				protocol = strstr(ptr, "Confirmed open ");
				skip = 15;

				if (IS_NULL(protocol) || (protocol > endtag)) {

					protocol = strstr(ptr, "Unconfirmed misc ");
					skip = 17;
				}

				if (IS_NULL(protocol) || (protocol > endtag)) {

					protocol = strstr(ptr, "[Dynablock]");

					if (IS_NOT_NULL(protocol) && (protocol < endtag)) {

						ptr = endtag;
						continue;
					}
				}

				if (IS_NULL(protocol) || (protocol > endtag)) {

					log_snoop("Error parsing SORBS http reply for IP %s: protocol not found", conn->ip);
					return;
				}

				protocol += skip;

				if (str_equals_partial(protocol, "SOCKS v4", 8) ||
					str_equals_partial(protocol, "socks4", 6))
					found += scan_http_result(conn, port, "SOCKS4");

				else if (str_equals_partial(protocol, "SOCKS v5", 8) ||
					str_equals_partial(protocol, "socks5", 6))
					found += scan_http_result(conn, port, "SOCKS5");

				else if (str_equals_partial(protocol, "HTTP CONNECT", 12) ||
					str_equals_partial(protocol, "http-connect", 12) ||
					str_equals_partial(protocol, "wingate proxy", 13) ||
					str_equals_partial(protocol, "open proxy", 10))
					found += scan_http_result(conn, port, "HTTP");

				else
					log_snoop("Error parsing SORBS http reply for IP %s: unknown protocol", conn->ip);

				ptr = endtag;
			}
		}

		case 3: {	/* NJABL */

			char *protocol;
			size_t ipLen;


			ptr = strstr(conn->response, "<pre>");

			if ((ptr == NULL) || ((conn->bytes_read - (ptr - conn->response)) < 17)) {

				log_snoop("Error parsing NJABL http reply for IP %s: data not found", conn->ip);
				return;
			}

			ptr += 17;
			ipLen = strlen(conn->ip);

			while (1) {

				if (str_not_equals_partial(ptr + 3, conn->ip, ipLen)) {

					log_snoop("Error parsing NJABL http reply for IP %s: IP mismatch", conn->ip);
					return;
				}

				ptr += (3 + ipLen + 5);

				protocol = NULL;

				switch (ptr[0]) {

					case 'h':
						switch (ptr[1]) {

							case 'c':	protocol = "HTTP";		break;
							case 'u':	protocol = "HTTP PUT";	break;
							case 'o':	protocol = "HTTPPOST";	break;
						}
						break;

					case 's':
						switch (ptr[1]) {

							case '4':	protocol = "SOCKS4";	break;
							case '5':	protocol = "SOCKS5";	break;
						}
						break;

					case 'w':
						if (ptr[1] == 'g')
							protocol = "WINGATE";
						break;
				}

				if (IS_NOT_NULL(protocol)) {

					ptr = str_tokenize(ptr + 3, token, sizeof(token), ':');

					if ((ptr == NULL) || (token[0] == '\0')) {

						log_snoop("Error parsing NJABL http reply for IP %s: port not found", conn->ip);
						return;
					}

					port = strtol(token, &err, 10);

					if ((port <= 0) || (port > 65535) || (*err != '\0')) {

						log_snoop("Error parsing NJABL http reply for IP %s: invalid port (%s)", conn->ip, token);
						return;
					}

					found += scan_http_result(conn, port, protocol);
				}

				ptr = strstr(ptr, " open");

				if (IS_NULL(ptr)) {

					log_snoop("Error parsing NJABL http reply for IP %s: EOF not found", conn->ip);
					return;
				}

				if (str_equals_partial(ptr + 6, "<BR>", 4)) {

					if (found == 0) {

						if (conn->requested == 1)
							log_snoop("[%s] IP \2%s\2 is positive on known ports only [Details: http://%s%s%s ] [Requested by %s]", conn->zone->name, conn->ip, conn->zone->host, conn->zone->url, conn->ip, conn->nick);
						else
							log_snoop("[%s] IP \2%s\2 used by \2%s\2 is positive on known ports only [Details: http://%s%s%s ]", conn->zone->name, conn->ip, conn->nick, conn->zone->host, conn->zone->url, conn->ip);
					}

					return;
				}

				ptr += 6;
			}
			break;
		}
	}
}
int main(int argc, char*argv[])
{
    char *conf_file_name = NULL;
    FILE *conf_file_pointer = NULL;
    char line[LINE_MAX] = {'\0'};
    char *tokens[TOKEN_MAX] = {NULL};
    int count = 0;
    gateway_create_params gateway_device = {NULL, NULL};
    gateway_handle gateway = NULL;
    int return_value = E_FAILURE;

    LOG_DEBUG(("DEBUG: Number of arguments are: %d\n", argc));

    if(argc<2)
    {
        LOG_ERROR(("ERROR: Please provide configuration file name\n"));
        return (0);
    }

    conf_file_name = argv[1];

    LOG_DEBUG(("DEBUG: Configuration File Name is %s\n", conf_file_name));

    conf_file_pointer = fopen(conf_file_name, "r");
    if(!conf_file_pointer)
    {
        LOG_ERROR(("ERROR: Error in opening configuration file\n"));
        return (0);
    }

    /* Read line */
    if(fgets(line, LINE_MAX, conf_file_pointer) == NULL)
    {
        LOG_DEBUG(("DEBUG: Cleanup and return\n"));
        fclose(conf_file_pointer);
        LOG_ERROR(("ERROR: Wrong configuration file\n"));
        return (0);
    }
    str_tokenize(line, ":\n\r", tokens, &count);
    if(count<2)
    {
        LOG_ERROR(("Wrong configuration file\n"));
        fclose(conf_file_pointer);
        return (0);
    }

    str_copy(&gateway_device.gateway_ip_address, tokens[0]);
    str_copy(&gateway_device.gateway_port_no, tokens[1]);
    LOG_DEBUG(("IP Address: %s\n", gateway_device.gateway_ip_address));
    LOG_DEBUG(("Port No: %s\n", gateway_device.gateway_port_no));

    LOG_GATEWAY(("------------------------------------------------\n"));

    return_value = create_gateway(&gateway, &gateway_device);
    if(E_SUCCESS != return_value)
    {
        LOG_ERROR(("ERROR: Unable to create gateway\n"));
        free(gateway_device.gateway_ip_address);
        free(gateway_device.gateway_port_no);
        fclose(conf_file_pointer);
        return (0);
    }

    LOG_ERROR(("Gateway started successfully\n"));

    int choice, interval;
    while(1)
    {
        printf("-------------------Menu----------------\n");
        printf("1.Change Sensor interval\n");
        printf("2.Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        if(choice==2)
            break;
        switch(choice)
        {
        case 1:
            print_sensors(gateway);
            printf("Enter sensor id: ");
            scanf("%d", &choice);
            printf("Enter new interval: ");
            scanf("%d", &interval);
            return_value = set_interval(gateway, choice, interval);
            if(E_SUCCESS != return_value)
            {
                printf("Unable to set the interval\n");
            }
            break;
        default:
            printf("Enter valid choice...\n");
        }
    }

    delete_gateway(gateway);
    LOG_GATEWAY(("-------------------------------------------------\n"));

    free(gateway_device.gateway_ip_address);
    free(gateway_device.gateway_port_no);
    fclose(conf_file_pointer);
    logger_close();
    return (0);
}
Exemplo n.º 8
0
Arquivo: vmd.C Projeto: quolc/VMDLeap
// look for all environment variables VMD can use, and initialize the
// proper variables.  If an env variable is not found, use a default value.
// ENVIRONMENT VARIABLES USED BY VMD (default values set in config.h):
//	VMDDIR		directory with VMD data files and utility programs
//	VMDTMPDIR	directory in which to put temporary files (def: /tmp)
static void VMDGetOptions(int argc, char **argv) {
  char *envtxt;

  //
  // VMDDISPLAYDEVICE: which display device to use by default
  // 
  if((envtxt = getenv("VMDDISPLAYDEVICE"))) {
    for(int i=0; i < NUM_DISPLAY_TYPES; i++) {
      if(!strupcmp(envtxt, displayTypeNames[i])) {
        which_display = i;
        break;
      }
    }
  }

  // 
  // VMDTITLE: whether to enable the title screen
  //  
  if((envtxt = getenv("VMDTITLE"))) {
    for(int i=0; i < NUM_TITLE_TYPES; i++) {
      if(!strupcmp(envtxt, titleTypeNames[i])) {
        showTitle = i;
        break;
      }
    }
  }

  //
  // VMDSCRHEIGHT: height of the screen
  //
  if((envtxt = getenv("VMDSCRHEIGHT")))
    displayHeight = (float) atof(envtxt);

  //
  // VMDSCRDIST: distance to the screen
  //
  if((envtxt = getenv("VMDSCRDIST")))
    displayDist = (float) atof(envtxt); 

  // 
  // VMDSCRPOS: graphics window location
  //
  if((envtxt = getenv("VMDSCRPOS"))) {
    char * dispStr = NULL;
    char * dispArgv[64];
    int dispArgc;

    if((dispStr = str_tokenize(envtxt, &dispArgc, dispArgv)) != NULL
                && dispArgc == 2) {
      displayLoc[0] = atoi(dispArgv[0]);
      displayLoc[1] = atoi(dispArgv[1]);
    } else {
      msgErr << "Illegal VMDSCRPOS environment variable setting '" 
             << envtxt << "'." << sendmsg;
    }
    if(dispStr)  delete [] dispStr;
  }

  // 
  // VMDSCRSIZE: graphics window size
  //
  if((envtxt = getenv("VMDSCRSIZE"))) {
    char * dispStr = NULL;
    char * dispArgv[64];
    int dispArgc;
    if((dispStr = str_tokenize(envtxt, &dispArgc, dispArgv)) != NULL
                && dispArgc == 2) {
      displaySize[0] = atoi(dispArgv[0]);
      displaySize[1] = atoi(dispArgv[1]);
 
      // force users to do something that makes sense
      if (displaySize[0] < 100) 
        displaySize[0] = 100; // minimum sane width
      if (displaySize[1] < 100) 
        displaySize[1] = 100; // minimum sane height

    } else {
      msgErr << "Illegal VMDSCRSIZE environment variable setting '" 
             << envtxt << "'." << sendmsg;
    }
    if(dispStr)  delete [] dispStr;
  }

  // initialize variables which indicate how VMD starts up, and
  // parse the command-line options

  // go through the arguments
  int ev = 1;
  while(ev < argc) {
    if(!strupcmp(argv[ev], "-dist")) {
      if(argc > (ev + 1)) {
        displayDist = (float) atof(argv[++ev]);
      } else
        msgErr << "-dist must also specify a distance." << sendmsg;

    } else if(!strupcmp(argv[ev], "-e")) {
      if(argc > (ev + 1)) {
        beginCmdFile = argv[++ev];
      } else
        msgErr << "-e must also specify a filename." << sendmsg;

    } else if(!strupcmp(argv[ev], "-height")) {
      if(argc > (ev + 1)) {
        displayHeight = (float) atof(argv[++ev]);
      } else
        msgErr << "-height must also specify a distance." << sendmsg;

    } else if(!strupcmp(argv[ev], "-pos")) {
      if(argc > (ev + 2) && *(argv[ev+1]) != '-' && *(argv[ev+2]) != '-') {
        displayLoc[0] = atoi(argv[++ev]);
        displayLoc[1] = atoi(argv[++ev]);
      } else
        msgErr << "-pos must also specify an X Y pair." << sendmsg;

    } else if(!strupcmp(argv[ev], "-size")) {
      if(argc > (ev + 2) && *(argv[ev+1]) != '-' && *(argv[ev+2]) != '-') {
        displaySize[0] = atoi(argv[++ev]);
        displaySize[1] = atoi(argv[++ev]);
      } else
        msgErr << "-size must also specify an X Y pair." << sendmsg;

    } else if(!strupcmp(argv[ev], "-startup")) {
      // use next argument as startup config file name
      if(argc > (ev + 1))
        startupFileStr = argv[++ev];
      else
        msgErr << "-startup must also have a new file name specified."
	       << sendmsg;

    } else if(!strupcmp(argv[ev], "-nt")) {
      // do not print out the program title
      showTitle = TITLE_OFF;

    } else if (!strupcmp(argv[ev], "-dispdev")) {  // startup Display
      ev++;
      if (argc > ev) {
        if (!strupcmp(argv[ev], "cave")) {  
          which_display = DISPLAY_CAVE;        // use the CAVE
        } else if (!strupcmp(argv[ev], "win")) {       
          which_display = DISPLAY_WIN;         // use OpenGL, the default
        } else if (!strupcmp(argv[ev], "opengl")) {  
          which_display = DISPLAY_WINOGL;      // use OpenGL if available
        } else if (!strupcmp(argv[ev], "text")) {
          which_display = DISPLAY_TEXT;        // use text console only 
        } else if (!strupcmp(argv[ev], "caveforms")) {
          which_display = DISPLAY_CAVEFORMS;   // use CAVE+Forms
        } else if (!strupcmp(argv[ev], "freevr")) {
          which_display = DISPLAY_FREEVR;      // use FreeVR
        } else if (!strupcmp(argv[ev], "freevrforms")) {
          which_display = DISPLAY_FREEVRFORMS; // use FreeVR+Forms
        } else if (!strupcmp(argv[ev], "none")) {      
          which_display = DISPLAY_TEXT;        // use text console only
        } else {
          msgErr << "-dispdev options are 'win' (default), 'cave', 'caveforms', 'freevr', 'freevrforms', or 'text | none'" << sendmsg;
        }
      } else {
        msgErr << "-dispdev options are 'win' (default), 'cave', 'caveforms', 'freevr', 'freevrforms', or 'text | none'" << sendmsg;
      }
    } else if (!strupcmp(argv[ev], "-h") || !strupcmp(argv[ev], "--help")) {
      // print out command-line option summary
      msgInfo << "Available command-line options:" << sendmsg;
      msgInfo << "\t-dispdev <win | cave | text | none> Specify display device";
      msgInfo << sendmsg;
      msgInfo << "\t-dist <d>           Distance from origin to screen";
      msgInfo << sendmsg;
      msgInfo << "\t-e <filename>       Execute commands in <filename>\n";
      msgInfo << "\t-python             Use Python for -e file and subsequent text input\n";
      msgInfo << "\t-eofexit            Exit when end-of-file occurs on input\n";
      msgInfo << "\t-h | --help         Display this command-line summary\n";
      msgInfo << "\t-height <h>         Height of display screen";
      msgInfo << sendmsg;
      msgInfo << "\t-pos <X> <Y>        Lower-left corner position of display";
      msgInfo << sendmsg;
      msgInfo << "\t-nt                 No title display at start" << sendmsg;
      msgInfo << "\t-size <X> <Y>       Size of display" << sendmsg;
      msgInfo << "\t-startup <filename> Specify startup script file" << sendmsg;
      msgInfo << "\t-m                  Load subsequent files as separate molecules\n";
      msgInfo << "\t-f                  Load subsequent files into the same molecule\n";
      msgInfo << "\t<filename>          Load file using best-guess file type\n";
      msgInfo << "\t-<type> <filename>  Load file using specified file type\n";
      msgInfo << "\t-args               Pass subsequent arguments to text interpreter\n";
      msgInfo << sendmsg;
      just_print_help = 1;
    } else if (!strupcmp(argv[ev], "-eofexit")) {  // exit on EOF
      eofexit = 1;
    } else if (!strupcmp(argv[ev], "-node")) { 
      // start VMD process on a cluster node, next parm is node ID..
      ev++; // skip node ID parm
    } else if (!strupcmp(argv[ev], "-webhelper")) { 
      // Unix startup script doesn't run VMD in the background, so that
      // web browsers won't delete files out from under us until it really
      // exits.  We don't do anything special inside VMD itself presently
      // however.
    } else if (!strupcmp(argv[ev], "-python")) {
      cmdFileUsesPython = 1;
    } else if (!strupcmp(argv[ev], "-args")) {
      // pass the rest of the command line arguments, and only those, 
      // to the embedded text interpreters.
      while (++ev < argc)
        customArgv.append(argv[ev]);

    } else if (!strupcmp(argv[ev], "-m")) {
      loadAsMolecules = 1;
      startNewMolecule = 1;
    } else if (!strupcmp(argv[ev], "-f")) {
      loadAsMolecules = 0;
      startNewMolecule = 1;
#ifdef VMDMPI
    } else if (!strupcmp(argv[ev], "-vmddir")) {
      ev++; // skip VMDDIR directory parm, since we already handled this
            // in MPI startup before we got to this loop...
#endif
    } else {
      // any other argument is treated either as a filename or as a 
      // filetype/filename pair of the form -filetype filename.
      const char *filename, *filetype;
      if (argv[ev][0] == '-') {
        // must be filetype/filename pair
        if (argc > ev+1) {
          filetype = argv[ev]+1;
          filename = argv[ev+1];
          ev++;
        } else {
          msgErr << "filetype argument '" << argv[ev] << "' needs a filename."
            << sendmsg;
          ev++;  // because we skip past the ev++ at the bottom of the loop.
          continue; 
        }
      } else {
        // Given just a filename.  The filetype will have to be guessed.
        filename = argv[ev];
        filetype = NULL;
      }
      initFilenames.append(filename);
      initFiletypes.append(filetype);
      startNewMoleculeFlags.append(startNewMolecule);
      if (!loadAsMolecules) startNewMolecule = 0;
    }
    ev++;
  }

  // command-line options have been parsed ... any init status variables that
  // have been given initial values will have flags saying so, and their
  // values will not be changed when the init file(s) is parsed.
}
int main(int argc, char*argv[])
{
	char *conf_file_name = NULL;
	FILE *conf_file_pointer = NULL;
	char line[LINE_MAX] = {'\0'};
	char *tokens[TOKEN_MAX] = {NULL};
	int count = 0;
	gateway_create_params gateway_device = {NULL, NULL};
	gateway_handle gateway = NULL;
	int return_value = E_FAILURE;

	LOG_DEBUG(("DEBUG: Number of arguments are: %d\n", argc));

	if(argc<3)
	{
		LOG_ERROR(("ERROR: Please provide configuration file name\n"));
		return (0);
	}

	conf_file_name = argv[1];

	LOG_DEBUG(("DEBUG: Configuration File Name is %s\n", conf_file_name));

	conf_file_pointer = fopen(conf_file_name, "r");
	if(!conf_file_pointer)
	{
		LOG_ERROR(("ERROR: Error in opening configuration file\n"));
		return (0);
	}

	return_value = log_open_output_file(argv[2]);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: Unable to open the file for writing\n"));
		return (0);
	}

	/* Read line */
	if(fgets(line, LINE_MAX, conf_file_pointer) == NULL)
	{
		LOG_DEBUG(("DEBUG: Cleanup and return\n"));
		fclose(conf_file_pointer);
		LOG_ERROR(("ERROR: Wrong configuration file\n"));
		return (0);
	}
	str_tokenize(line, ":\n\r", tokens, &count);
	if(count<2)
	{
		LOG_ERROR(("Wrong configuration file\n"));
		fclose(conf_file_pointer);
		return (0);
	}

	str_copy(&gateway_device.gateway_ip_address, tokens[0]);
	str_copy(&gateway_device.gateway_port_no, tokens[1]);
	LOG_DEBUG(("IP Address: %s\n", gateway_device.gateway_ip_address));
	LOG_DEBUG(("Port No: %s\n", gateway_device.gateway_port_no));

	return_value = create_gateway(&gateway, &gateway_device);
	if(E_SUCCESS != return_value)
	{
		LOG_ERROR(("ERROR: Unable to create gateway\n"));
		free(gateway_device.gateway_ip_address);
		free(gateway_device.gateway_port_no);
		fclose(conf_file_pointer);
		return (0);
	}

	LOG_SCREEN(("INFO: Gateway Front End started successfully\n"));
	LOG_SCREEN(("INFO: Output is Redirected to: %s\n", argv[2]));

	char choice;
	printf("Press any key to exit...\n");
	scanf("%c", &choice);

	delete_gateway(gateway);

	free(gateway_device.gateway_ip_address);
	free(gateway_device.gateway_port_no);
	fclose(conf_file_pointer);
	logger_close();
	return (0);
}
void* set_value_thread(void *context)
{
	sensor_context *sensor = NULL;
	message msg;
	int return_value;
	char *tokens[10];
	char line[LINE_MAX];
	int count = 0;
	int start, end, value;

	sensor = (sensor_context*)context;

	msg.type = CURRENT_VALUE;
	while(sensor->run)
	{
		if(!(start <= sensor->clock && sensor->clock < end))
		{
			/* Figure out the value from file */
			if(fgets(line, LINE_MAX, sensor->sensor_value_file_pointer) == NULL)
			{
				LOG_DEBUG(("DEBUG: Seeking to beginning of file"));
				rewind(sensor->sensor_value_file_pointer);
				sensor->clock = 0;
				continue;
			}

			str_tokenize(line, ";\n\r", tokens, &count);
			if(count != 3)
			{
				LOG_ERROR(("ERROR: Wrong sensor temperature value file\n"));
				break;
			}

			start = atoi(tokens[0]);
			end = atoi(tokens[1]);
			if(strcmp (tokens[2], "true") == 0)
			{
				value = 1; 
			}
			else
			{
				value = 0;
			}
			sensor->value = value;
		}

		msg.u.value = sensor->value;
		msg.timestamp = time(NULL);

		pthread_mutex_lock(&sensor->mutex_lock);

		sensor->logical_clock[2]++;
		LOG_SCREEN(("INFO: Event Sent, "));
		LOG_INFO(("INFO: Event Sent, "));
		print_logical_clock_to_screen(sensor->logical_clock);
		print_logical_clock(sensor->logical_clock);
		LOG_INFO(("timestamp: %lu, Motion: %s\n", msg.timestamp, tokens[2]));
		LOG_SCREEN(("timestamp: %lu, Motion: %s\n", msg.timestamp, tokens[2]));
		return_value = write_message(sensor->socket_fd, sensor->logical_clock, &msg);
		if(E_SUCCESS != return_value)
		{
			LOG_ERROR(("ERROR: Error in sending sensor temperature value to gateway\n"));
		}

		for(int index=0; index<sensor->send_peer_count; index++)
		{
			return_value = write_message(sensor->send_peer[index]->comm_socket_fd,
					sensor->logical_clock,
					&msg);
			if(E_SUCCESS != return_value)
			{
				LOG_ERROR(("ERROR: Error in sending sensor temperature value to peer\n"));
			}
		}
		pthread_mutex_unlock(&sensor->mutex_lock);

		sleep(sensor->interval);
		sensor->clock += sensor->interval;
	}

	LOG_DEBUG(("Exiting SetValueThread...\n"));
	return (NULL);
}