Example #1
0
int main(int argc, char *argv[]) {
    // Local Main Declarations
    float startCountDown = 5.0;
    double data[4];
    FILE *enc_zero;

 //   printf("The present position will be the home position.\n");
    enc_init();
 //   printf("The present position will be the home position2.\n");

    while(startCountDown > 0.0){
        printf("%0.0f seconds to end\n",startCountDown);
        startCountDown -= 1.0;
        sleep(1);
    }
    printf("The present position will be the home position.\n");

    data[0]= read_angle_rad(1);
    data[1]= read_angle_rad(2);
    data[2]= read_angle_rad(3);
    data[3]=-read_angle_rad(4);

    enc_zero=fopen("enc_home.dat","w+");
    fprintf(enc_zero,"%f %f %f %f\n",data[0],data[1],data[2],data[3]);
	fclose(enc_zero);
    return( 0 );
}
Example #2
0
void init_ethernet(void)
{
	  enc28j60_comm_init();
	  UARTprintf("Welcome\n");

	  enc_init(mac_addr);
	  systick_init();

	  lwip_init();

	#if !LWIP_DHCP
	  IP4_ADDR(&gw_g, 10,0,0,1);
	  IP4_ADDR(&ipaddr_g, 10,0,0,100);
	  IP4_ADDR(&netmask_g, 255, 255, 255, 0)
	#else
	  IP4_ADDR(&gw_g, 0,0,0,0);
	  IP4_ADDR(&ipaddr_g, 0,0,0,0);
	  IP4_ADDR(&netmask_g, 0, 0, 0, 0);
	#endif

	  netif_add(&netif_g, &ipaddr_g, &netmask_g, &gw_g, NULL, enc28j60_init, ethernet_input);
	  netif_set_default(&netif_g);

	#if !LWIP_DHCP
	  netif_set_up(&netif_g);
	#else
	  dhcp_start(&netif_g);
	#endif

}
Example #3
0
static int ss_instance_init(struct redudp_instance_t *instance)
{
    ss_instance * ss = (ss_instance *)(instance+1);
    const redudp_config *config = &instance->config;
    char buf1[RED_INET_ADDRSTRLEN];

    int valid_cred =  ss_is_valid_cred(config->login, config->password);
    if (!valid_cred 
    || (ss->method = enc_init(&ss->info, config->password, config->login), ss->method == -1))
    {
        log_error(LOG_ERR, "Invalided encrytion method or password.");
        return -1;
    }
    else
    {
        log_error(LOG_INFO, "%s @ %s: encryption method: %s",
            instance->relay_ss->name,
            red_inet_ntop(&instance->config.bindaddr, buf1, sizeof(buf1)),
            config->login);
    }
    // An additional buffer is allocated for each instance for encryption/decrption.
    ss->buff = malloc(MAX_UDP_PACKET_SIZE);
    if (!ss->buff) {
        log_error(LOG_ERR, "Out of memory.");
        return -1;
    }
    return 0;
}
Example #4
0
int main(void)
{

	lb_init(&lb);
	event_init();
	motor_init();
	uart_init(); 	// init USART
	enc_init();
	i2c_init();
	adc_init();
	kalman_init();
	sei();  		// enable interrupts


	// Wait a second at startup
	_delay_ms(1000);

	// send initial string
	printf_P(PSTR("Hello world!\n"));
	imu_init();

	for (;/*ever*/;)
	{
//		ADCSRA |= (1<<ADSC);								// Set start conversion bit and wait for conversion to finish
//		while(ADCSRA&(1<<ADSC));

//		OCR1AL = ADCH;										// Set ADC reading to timer 0 compare

		if(event_pending())
		{
			event_action();
		}
		else // No pending operation, do low priority tasks
		{
			// dequeue receive buffer if any bytes waiting
			while (uart_avail())
			{
				char c = uart_getc();
				if (lb_append(&lb, c) == LB_BUFFER_FULL)
				{
					lb_init(&lb); // Clear line
					printf_P(PSTR("\nMax line length exceeded\n"));
				}
				// Process command if line buffer is ready ...
				if (lb_line_ready(&lb))
				{
					strcpy(cmd_string,lb_gets(&lb));
					do_cmd(cmd_string);
					lb_init(&lb);
				}
			}
		}
		// Process command if line buffer is terminated by a line feed or carriage return
	}
	return 0;
}
Example #5
0
int precompute_response(FILE* fp, Chal * c,char * key) {

	unsigned char message[v*BLOCK_SIZE];
	unsigned char codeword[w*BLOCK_SIZE];
	char uth[BLOCK_SIZE];
	char ct[BLOCK_SIZE];
	int i,j,p;
	enc_init(key);
    // for each of the challenge
	for (j=0;j<q;j++) {

		int index = 0;
		for (i=0;i<v;i++) {
            // read in the random indexed blocks
            fseek(fp,c[j].s[i]*BLOCK_SIZE,SEEK_SET);
			unsigned char buffer[BLOCK_SIZE];
            readStartTime = getCPUTime();
            clock_gettime(CLOCK_MONOTONIC, &start);
			fread(buffer, BLOCK_SIZE, 1, fp);
            clock_gettime(CLOCK_MONOTONIC, &finish);
            double addTime = finish.tv_sec - start.tv_sec;
            addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
            readTime += getCPUTime() - readStartTime+addTime;
			for(p=0;p<BLOCK_SIZE;p++) {
				message[index] = buffer[p];
				index++;
			}
			fflush(stdout);
		}
        // perform a concatenated encoding
		concat_encode(message,codeword);
		for (i=0;i<BLOCK_SIZE;i++) {
            // get the u-th symbol
			uth[i] = codeword[BLOCK_SIZE*c[j].u+i];
		}
		clock_gettime(CLOCK_MONOTONIC, &start);
		encStartTime = getCPUTime();
        // encrypt the response and append at the end
		encrypt(ct,uth,sizeof(uth));
		clock_gettime(CLOCK_MONOTONIC, &finish);
		double addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
		encTime += getCPUTime()-encStartTime+addTime;

        write2StartTime = getCPUTime();
		clock_gettime(CLOCK_MONOTONIC, &start);
		fwrite(ct,BLOCK_SIZE,1,fp);
		clock_gettime(CLOCK_MONOTONIC, &finish);
		addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
        write2Time+=getCPUTime()-write2StartTime+addTime;

	}
}
Example #6
0
int init_systems() {
  var_load(CONFIG_FILE); // Nacti vsechny promenne
  led_init();
  input_event_init(); // Klavesnice
  enc_init(); // Nastav encodery
//  motor_init(); // PID -> zapinat az po encoderech
  i2c_init(); // Priprav i2c komunikaci

  pthread_attr_t *thAttr = NULL;
  pthread_create(&bumpers_loop_tid, thAttr, bumpers_loop, NULL);
  return 0;
}
Example #7
0
int main(void)
{
	char packet[1500];
	struct cfg_s cfg;
	
	/*wait 500 for ethernet*/
	_delay_ms(500);
	
	enc_init();
	twi_init();
	spi_init();
	ip_init();
	pwm_init();
	sei();
	
	/*
	 * EEPROM:
	 * Mac Address:6
	 * IP:4
	 * Subnet Mask:4
	 * Port:2
	 * ID:4
	 */
	eeprom_read_block(&eecfg,  &cfg, sizeof(struct cfg_s));
	
	ip_setipmac((char*)cfg.ip, (char*)cfg.subnet, (char*)cfg.mac);
	
	while(1) {
		/*
		 * Provide encoder deltas
		 * Provide Integrated/Corrected Gyro
		 * Accelerometer?
		 * Pipe PWMS
		 * Pipe Spike
		 * IP? - TCP/UDP
		 * 
		 * Do reliability on cpu side.
		 * Send immediate acks only.
		 * 
		 * Timeout of 250 ms?
		 */
		/* TODO:
		 *  ANALOG:
		 *   GYRO
		 *   TEMP
		 *  ACCELEROMETER
		 *  CONTROL STATION
		 *  PID?
		 */
		/*LOOP*/
	}
}
Example #8
0
/*配置XVID CODEC视频编解码算法*/
void CMainFrame::Config_XVIECODEC()
{
	////////////////////////////////////////////////////////////////
	ENC_PARAM m_Param;
	m_Param.width = lpbiIn->bmiHeader.biWidth;	//视频图像宽度
	m_Param.height= lpbiIn->bmiHeader.biHeight;	//视频图像高度
	m_Param.bitrate = 800000;					//码流大小,使用码流控制
	m_Param.max_key_interval = 100;				//关键帧间隔
	m_Param.framerate = 25;						//帧率
	m_Param.quant = 0;							//量化步长,0表示使用码流控制

	enc_init(&m_Param);							//创建xvid codec编码器
	dec_init(m_Param.width,m_Param.height);		//创建xvid codec解码器
	////////////////////////////////////////////////////////////////
}
Example #9
0
//以wavstream和wavstreamlen,计算amr编码后需要的长度并分配空间,返回amrstream和amrstream的长度
int amr_encode_init(unsigned char *wavstream, int wavstreamlen, AmrEncState **s, unsigned char **amrstream)
{
if(NULL==wavstream || wavstreamlen<=0)	return	-1;
	*s = enc_init();
	if(*s == NULL)	return	-1;		// "enc_init fail!";
		
	if(enc_set_file(*s, wavstream, wavstreamlen) == -1) {
		enc_uninit(*s);
		*s = NULL;
		return	-1;		// mes;
	}	
	
	
	*armstream = (*s)->amrstream;
	return	(*s)->amrstreamlen;
}
Example #10
0
JNIEXPORT void JNICALL Java_me_smartproxy_crypto_CryptoUtils_initEncryptor(JNIEnv *env, jclass thiz, jstring jpassword, jstring jmethod, jlong id) {
    enc_connection *connection = enc_ctx_map[id];

    if(connection == NULL) {
        const char *password = env->GetStringUTFChars(jpassword, 0);
        const char *method = env->GetStringUTFChars(jmethod, 0);
        connection = (enc_connection *)ss_malloc(sizeof(struct enc_connection));
        connection->text_e_ctx = (enc_ctx *)ss_malloc(sizeof(struct enc_ctx));
        connection->text_d_ctx = (enc_ctx *)ss_malloc(sizeof(struct enc_ctx));
        int enc_method = enc_init(password, method);
        enc_ctx_init(enc_method, connection->text_e_ctx, 1);
        enc_ctx_init(enc_method, connection->text_d_ctx, 0);
        enc_ctx_map[id] = connection;
        env->ReleaseStringUTFChars(jpassword, password);
        env->ReleaseStringUTFChars(jmethod, method);
    }
}
Example #11
0
static int ss_instance_init(struct redsocks_instance_t *instance)
{
    ss_instance * ss = (ss_instance *)(instance+1);
    const redsocks_config *config = &instance->config;

    int valid_cred =  ss_is_valid_cred(config->login, config->password);
    if (!valid_cred 
    || (ss->method = enc_init(&ss->info, config->password, config->login), ss->method == -1))
    {
        log_error(LOG_ERR, "Invalided encrytion method or password.");
        return -1;
    }
    else
    {
        log_error(LOG_INFO, "using encryption method: %s", config->login);
    }
    return 0;
}
Example #12
0
int main(void) {
    enc_init();
    motor_init();

    encoder_debug_init();

    right_turns = 0;
    left_turns = 0;
    right_direction = REVERSE;
    left_direction = REVERSE;

    encoder_debug_init();

    //Enable all interrupts
    sei();

    DDRC &= ~(_BV(DDC5));
    while (!(has_wall(RIGHT) && has_wall(RIGHT))) {
        move_forward(1);
    }
    turn_right(1);
    move_forward(1);

    while (1) {
        if (has_wall(RIGHT)) {
            PORTC |= _BV(PORTC3);
        } else {
            PORTC &= ~(_BV(PORTC3));
        }
        if (has_wall(LEFT)) {
            PORTC |= _BV(PORTC2);
        } else {
            PORTC &= ~(_BV(PORTC2));
        }
        /*
        while ((PINC & _BV(PINC5)));
        move_forward(1);
        move_forward(1);
        turn_right(1);
        move_forward(1);
        */
    }
}
Example #13
0
int main(int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    srand(time(NULL));

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    int option_index = 0;
    static struct option long_options[] =
    {
        { "fast-open", no_argument,       0, 0 },
        { "acl",       required_argument, 0, 0 },
        { 0,           0,                 0, 0 }
    };

    opterr = 0;

    USE_TTY();

#ifdef ANDROID
    while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:a:uvVA",
                            long_options, &option_index)) != -1) {
#else
    while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:a:uvA",
                            long_options, &option_index)) != -1) {
#endif
        switch (c) {
        case 0:
            if (option_index == 0) {
                fast_open = 1;
            } else if (option_index == 1) {
                LOGI("initialize acl...");
                acl = !init_acl(optarg);
            }
            break;
        case 's':
            if (remote_num < MAX_REMOTE_NUM) {
                remote_addr[remote_num].host = optarg;
                remote_addr[remote_num++].port = NULL;
            }
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'a':
            user = optarg;
            break;
        case 'u':
            mode = TCP_AND_UDP;
            break;
        case 'v':
            verbose = 1;
            break;
        case 'A':
            auth = 1;
            break;
#ifdef ANDROID
        case 'V':
            vpn = 1;
            break;
#endif
        }
    }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (argc == 1) {
        if (conf_path == NULL) {
            conf_path = DEFAULT_CONF_PATH;
        }
    }
    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0) {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++) {
                remote_addr[i] = conf->remote_addr[i];
            }
        }
        if (remote_port == NULL) {
            remote_port = conf->remote_port;
        }
        if (local_addr == NULL) {
            local_addr = conf->local_addr;
        }
        if (local_port == NULL) {
            local_port = conf->local_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
        if (fast_open == 0) {
            fast_open = conf->fast_open;
        }
#ifdef HAVE_SETRLIMIT
        if (nofile == 0) {
            nofile = conf->nofile;
        }
        /*
         * no need to check the return value here since we will show
         * the user an error message if setrlimit(2) fails
         */
        if (nofile) {
            if (verbose) {
                LOGI("setting NOFILE to %d", nofile);
            }
            set_nofile(nofile);
        }
#endif
    }

    if (remote_num == 0 || remote_port == NULL ||
        local_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) {
        timeout = "60";
    }

    if (local_addr == NULL) {
        local_addr = "127.0.0.1";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    if (fast_open == 1) {
#ifdef TCP_FASTOPEN
        LOGI("using tcp fast open");
#else
        LOGE("tcp fast open is not supported by this environment");
#endif
    }

    if (auth) {
        LOGI("onetime authentication enabled");
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    struct ev_signal sigint_watcher;
    struct ev_signal sigterm_watcher;
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    // Setup keys
    LOGI("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup proxy context
    struct listen_ctx listen_ctx;
    listen_ctx.remote_num = remote_num;
    listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *) * remote_num);
    for (i = 0; i < remote_num; i++) {
        char *host = remote_addr[i].host;
        char *port = remote_addr[i].port == NULL ? remote_port :
            remote_addr[i].port;
        struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage));
        memset(storage, 0, sizeof(struct sockaddr_storage));
        if (get_sockaddr(host, port, storage, 1) == -1) {
            FATAL("failed to resolve the provided hostname");
        }
        listen_ctx.remote_addr[i] = (struct sockaddr *)storage;
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.iface = iface;
    listen_ctx.method = m;

    struct ev_loop *loop = EV_DEFAULT;

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port);
    if (listenfd < 0) {
        FATAL("bind() error");
    }
    if (listen(listenfd, SOMAXCONN) == -1) {
        FATAL("listen() error");
    }
    setnonblocking(listenfd);

    listen_ctx.fd = listenfd;

    ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start(loop, &listen_ctx.io);

    // Setup UDP
    if (mode != TCP_ONLY) {
        LOGI("udprelay enabled");
        init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0],
                      get_sockaddr_len(listen_ctx.remote_addr[0]), m, listen_ctx.timeout, iface);
    }

    LOGI("listening at %s:%s", local_addr, local_port);

    // setuid
    if (user != NULL) {
        run_as(user);
    }

    // Init connections
    cork_dllist_init(&connections);

    // Enter the loop
    ev_run(loop, 0);

    if (verbose) {
        LOGI("closed gracefully");
    }

    // Clean up
    ev_io_stop(loop, &listen_ctx.io);
    free_connections(loop);

    if (mode != TCP_ONLY) {
        free_udprelay();
    }

    for (i = 0; i < remote_num; i++) {
        free(listen_ctx.remote_addr[i]);
    }
    free(listen_ctx.remote_addr);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    ev_signal_stop(EV_DEFAULT, &sigint_watcher);
    ev_signal_stop(EV_DEFAULT, &sigterm_watcher);

    return 0;
}

#else

int start_ss_local_server(profile_t profile)
{
    srand(time(NULL));

    char *remote_host = profile.remote_host;
    char *local_addr = profile.local_addr;
    char *method = profile.method;
    char *password = profile.password;
    char *log = profile.log;
    int remote_port = profile.remote_port;
    int local_port = profile.local_port;
    int timeout = profile.timeout;

    mode = profile.mode;
    fast_open = profile.fast_open;
    verbose = profile.verbose;

    char local_port_str[16];
    char remote_port_str[16];
    sprintf(local_port_str, "%d", local_port);
    sprintf(remote_port_str, "%d", remote_port);

    USE_LOGFILE(log);

    if (profile.acl != NULL) {
        acl = !init_acl(profile.acl);
    }

    if (local_addr == NULL) {
        local_addr = "127.0.0.1";
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    struct ev_signal sigint_watcher;
    struct ev_signal sigterm_watcher;
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    // Setup keys
    LOGI("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage));
    memset(storage, 0, sizeof(struct sockaddr_storage));
    if (get_sockaddr(remote_host, remote_port_str, storage, 1) == -1) {
        return -1;
    }

    // Setup proxy context
    struct ev_loop *loop = EV_DEFAULT;
    struct listen_ctx listen_ctx;

    listen_ctx.remote_num = 1;
    listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *));
    listen_ctx.remote_addr[0] = (struct sockaddr *)storage;
    listen_ctx.timeout = timeout;
    listen_ctx.method = m;
    listen_ctx.iface = NULL;

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port_str);
    if (listenfd < 0) {
        ERROR("bind()");
        return -1;
    }
    if (listen(listenfd, SOMAXCONN) == -1) {
        ERROR("listen()");
        return -1;
    }
    setnonblocking(listenfd);

    listen_ctx.fd = listenfd;

    ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start(loop, &listen_ctx.io);

    // Setup UDP
    if (mode != TCP_ONLY) {
        LOGI("udprelay enabled");
        struct sockaddr *addr = (struct sockaddr *)storage;
        init_udprelay(local_addr, local_port_str, addr,
                      get_sockaddr_len(addr), m, timeout, NULL);
    }

    LOGI("listening at %s:%s", local_addr, local_port_str);

    // Init connections
    cork_dllist_init(&connections);

    // Enter the loop
    ev_run(loop, 0);

    if (verbose) {
        LOGI("closed gracefully");
    }

    // Clean up
    if (mode != TCP_ONLY) {
        free_udprelay();
    }

    ev_io_stop(loop, &listen_ctx.io);
    free_connections(loop);
    close(listen_ctx.fd);

    free(listen_ctx.remote_addr);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    ev_signal_stop(EV_DEFAULT, &sigint_watcher);
    ev_signal_stop(EV_DEFAULT, &sigterm_watcher);

    // cannot reach here
    return 0;
}
Example #14
0
ERL_NIF_TERM
encode(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
    Encoder enc;
    Encoder* e = &enc;

    ErlNifBinary bin;
    ERL_NIF_TERM ret;

    ERL_NIF_TERM stack;
    ERL_NIF_TERM curr;
    ERL_NIF_TERM item;
    const ERL_NIF_TERM* tuple;
    int arity;
    ErlNifSInt64 lval;
    double dval;

    if(argc != 2) {
        return enif_make_badarg(env);
    }

    if(!enc_init(e, env, argv[1], &bin)) {
        return enif_make_badarg(env);
    }

    stack = enif_make_list(env, 1, argv[0]);

    while(!enif_is_empty_list(env, stack)) {
        if(!enif_get_list_cell(env, stack, &curr, &stack)) {
            ret = enc_error(e, "internal_error");
            goto done;
        }
        if(enif_is_identical(curr, e->atoms->ref_object)) {
            if(!enif_get_list_cell(env, stack, &curr, &stack)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            if(enif_is_empty_list(env, curr)) {
                if(!enc_end_object(e)) {
                    ret = enc_error(e, "internal_error");
                    goto done;
                }
                continue;
            }
            if(!enif_get_list_cell(env, curr, &item, &curr)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            if(!enif_get_tuple(env, item, &arity, &tuple)) {
                ret = enc_error(e, "invalid_object_pair");
                goto done;
            }
            if(arity != 2) {
                ret = enc_error(e, "invalid_object_pair");
                goto done;
            }
            if(!enc_comma(e)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            if(!enc_string(e, tuple[0])) {
                ret = enc_error(e, "invalid_object_key");
                goto done;
            }
            if(!enc_colon(e)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            stack = enif_make_list_cell(env, curr, stack);
            stack = enif_make_list_cell(env, e->atoms->ref_object, stack);
            stack = enif_make_list_cell(env, tuple[1], stack);
        } else if(enif_is_identical(curr, e->atoms->ref_array)) {
            if(!enif_get_list_cell(env, stack, &curr, &stack)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            if(enif_is_empty_list(env, curr)) {
                if(!enc_end_array(e)) {
                    ret = enc_error(e, "internal_error");
                    goto done;
                }
                continue;
            }
            if(!enc_comma(e)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            if(!enif_get_list_cell(env, curr, &item, &curr)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            stack = enif_make_list_cell(env, curr, stack);
            stack = enif_make_list_cell(env, e->atoms->ref_array, stack);
            stack = enif_make_list_cell(env, item, stack);
        } else if(enif_compare(curr, e->atoms->atom_null) == 0) {
            if(!enc_literal(e, "null", 4)) {
                ret = enc_error(e, "null");
                goto done;
            }
        } else if(enif_compare(curr, e->atoms->atom_true) == 0) {
            if(!enc_literal(e, "true", 4)) {
                ret = enc_error(e, "true");
                goto done;
            }
        } else if(enif_compare(curr, e->atoms->atom_false) == 0) {
            if(!enc_literal(e, "false", 5)) {
                ret = enc_error(e, "false");
                goto done;
            }
        } else if(enif_is_binary(env, curr)) {
            if(!enc_string(e, curr)) {
                ret = enc_error(e, "invalid_string");
                goto done;
            }
        } else if(enif_is_atom(env, curr)) {
            if(!enc_string(e, curr)) {
                ret = enc_error(e, "invalid_string");
                goto done;
            }
        } else if(enif_get_int64(env, curr, &lval)) {
            if(!enc_long(e, lval)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
        } else if(enif_get_double(env, curr, &dval)) {
            if(!enc_double(e, dval)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
        } else if(enif_get_tuple(env, curr, &arity, &tuple)) {
            if(arity != 1) {
                ret = enc_error(e, "invalid_ejson");
                goto done;
            }
            if(!enif_is_list(env, tuple[0])) {
                ret = enc_error(e, "invalid_object");
                goto done;
            }
            if(!enc_start_object(e)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            if(enif_is_empty_list(env, tuple[0])) {
                if(!enc_end_object(e)) {
                    ret = enc_error(e, "internal_error");
                    goto done;
                }
                continue;
            }
            if(!enif_get_list_cell(env, tuple[0], &item, &curr)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            if(!enif_get_tuple(env, item, &arity, &tuple)) {
                ret = enc_error(e, "invalid_object_member");
                goto done;
            }
            if(arity != 2) {
                ret = enc_error(e, "invalid_object_member_arity");
                goto done;
            }
            if(!enc_string(e, tuple[0])) {
                ret = enc_error(e, "invalid_object_member_key");
                goto done;
            }
            if(!enc_colon(e)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            stack = enif_make_list_cell(env, curr, stack);
            stack = enif_make_list_cell(env, e->atoms->ref_object, stack);
            stack = enif_make_list_cell(env, tuple[1], stack);
        } else if(enif_is_list(env, curr)) {
            if(!enc_start_array(e)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            if(enif_is_empty_list(env, curr)) {
                if(!enc_end_array(e)) {
                    ret = enc_error(e, "internal_error");
                    goto done;
                }
                continue;
            }
            if(!enif_get_list_cell(env, curr, &item, &curr)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
            stack = enif_make_list_cell(env, curr, stack);
            stack = enif_make_list_cell(env, e->atoms->ref_array, stack);
            stack = enif_make_list_cell(env, item, stack);
        } else {
            if(!enc_unknown(e, curr)) {
                ret = enc_error(e, "internal_error");
                goto done;
            }
        }
    }

    if(!enc_done(e, &item)) {
        ret = enc_error(e, "internal_error");
        goto done;
    }

    if(e->iolen == 0) {
        ret = item;
    } else {
        ret = enif_make_tuple2(env, e->atoms->atom_partial, item);
    }

done:
    enc_destroy(e);
    return ret;
}
Example #15
0
XVIDVideoCodec::XVIDVideoCodec()
{
	m_width = 160;
	m_height = 120;

	/* encoder init */
	in_buffer = (unsigned char *) malloc(m_width * m_height * 3);
	mp4_buffer = (unsigned char *) malloc(m_width * m_height * 3);

	ARG_FRAMERATE = 2.0f; /*25.00f;*/
	ARG_QUALITY = ME_ELEMENTS - 1;

	static void *enc_handle = NULL;

	int result = enc_init();
	if (result) {
		wxMessageBox("Could not initialize XVid CODEC", 
			_T("Error"),
			wxICON_ERROR | wxOK);
		exit(0);
	}


	/* decoder init */
	xvid_gbl_init_t   xvid_gbl_init;
	xvid_dec_create_t xvid_dec_create;

	/* Reset the structure with zeros */
	memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init_t));
	memset(&xvid_dec_create, 0, sizeof(xvid_dec_create_t));

	/* Version */
	xvid_gbl_init.version = XVID_VERSION;

	/* Assembly setting */
#ifdef ARCH_IS_IA64
		xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_IA64;
#else
	xvid_gbl_init.cpu_flags = 0;
#endif

	xvid_gbl_init.debug = 0/*debug_level*/;

	xvid_global(NULL, 0, &xvid_gbl_init, NULL);

	xvid_dec_create.version = XVID_VERSION;
	xvid_dec_create.width = m_width;
	xvid_dec_create.height = m_height;
	int ret = xvid_decore(NULL, XVID_DEC_CREATE, &xvid_dec_create, NULL);
	if (ret) {
		wxMessageBox("Could not initialize XVid CODEC", 
			_T("Error"),
			wxICON_ERROR | wxOK);
		exit(0);
	}
	
	dec_handle = xvid_dec_create.handle;

	out_buffer = (unsigned char*)malloc(m_width*m_height*4);
	memset(out_buffer, 0x00, m_width*m_height*4);




}
Example #16
0
void main(void) {
  static struct uip_eth_addr eth_addr;
  uip_ipaddr_t ipaddr;

  cpu_init();
  uart_init();
  printf("Welcome\n");
  spi_init();
  enc28j60_comm_init();

  printf("Welcome\n");

  enc_init(mac_addr);

  //
  // Configure SysTick for a periodic interrupt.
  //
  MAP_SysTickPeriodSet(MAP_SysCtlClockGet() / SYSTICKHZ);
  MAP_SysTickEnable();
  MAP_SysTickIntEnable();

  //MAP_IntEnable(INT_GPIOA);
  MAP_IntEnable(INT_GPIOE);
  MAP_IntMasterEnable();

  MAP_SysCtlPeripheralClockGating(false);

  printf("int enabled\n");

  MAP_GPIOIntTypeSet(GPIO_PORTE_BASE, ENC_INT, GPIO_FALLING_EDGE);
  MAP_GPIOPinIntClear(GPIO_PORTE_BASE, ENC_INT);
  MAP_GPIOPinIntEnable(GPIO_PORTE_BASE, ENC_INT);

  uip_init();

  eth_addr.addr[0] = mac_addr[0];
  eth_addr.addr[1] = mac_addr[1];
  eth_addr.addr[2] = mac_addr[2];
  eth_addr.addr[3] = mac_addr[3];
  eth_addr.addr[4] = mac_addr[4];
  eth_addr.addr[5] = mac_addr[5];

  uip_setethaddr(eth_addr);

#define DEFAULT_IPADDR0 10
#define DEFAULT_IPADDR1 0
#define DEFAULT_IPADDR2 0
#define DEFAULT_IPADDR3 201

#define DEFAULT_NETMASK0 255
#define DEFAULT_NETMASK1 255
#define DEFAULT_NETMASK2 255
#define DEFAULT_NETMASK3 0

#undef STATIC_IP

#ifdef STATIC_IP
  uip_ipaddr(ipaddr, DEFAULT_IPADDR0, DEFAULT_IPADDR1, DEFAULT_IPADDR2,
	     DEFAULT_IPADDR3);
  uip_sethostaddr(ipaddr);
  printf("IP: %d.%d.%d.%d\n", DEFAULT_IPADDR0, DEFAULT_IPADDR1,
	     DEFAULT_IPADDR2, DEFAULT_IPADDR3);
  uip_ipaddr(ipaddr, DEFAULT_NETMASK0, DEFAULT_NETMASK1, DEFAULT_NETMASK2,
	     DEFAULT_NETMASK3);
  uip_setnetmask(ipaddr);
#else
  uip_ipaddr(ipaddr, 0, 0, 0, 0);
  uip_sethostaddr(ipaddr);
  printf("Waiting for IP address...\n");
  uip_ipaddr(ipaddr, 0, 0, 0, 0);
  uip_setnetmask(ipaddr);
#endif

  httpd_init();

#ifndef STATIC_IP
  dhcpc_init(mac_addr, 6);
  dhcpc_request();
#endif

  long lPeriodicTimer, lARPTimer;
  lPeriodicTimer = lARPTimer = 0;

  int i; // = MAP_GPIOPinRead(GPIO_PORTA_BASE, ENC_INT) & ENC_INT;
  while(true) {
    //MAP_IntDisable(INT_UART0);
    MAP_SysCtlSleep();
    //MAP_IntEnable(INT_UART0);

    //i = MAP_GPIOPinRead(GPIO_PORTA_BASE, ENC_INT) & ENC_INT;
    /*while(i != 0 && g_ulFlags == 0) {
      i = MAP_GPIOPinRead(GPIO_PORTA_BASE, ENC_INT) & ENC_INT;
      }*/

    if( HWREGBITW(&g_ulFlags, FLAG_ENC_INT) == 1 ) {
      HWREGBITW(&g_ulFlags, FLAG_ENC_INT) = 0;
      enc_action();
    }

    if(HWREGBITW(&g_ulFlags, FLAG_SYSTICK) == 1) {
      HWREGBITW(&g_ulFlags, FLAG_SYSTICK) = 0;
      lPeriodicTimer += SYSTICKMS;
      lARPTimer += SYSTICKMS;
      //printf("%d %d\n", lPeriodicTimer, lARPTimer);
    }

    if( lPeriodicTimer > UIP_PERIODIC_TIMER_MS ) {
      lPeriodicTimer = 0;
      int l;
      for(l = 0; l < UIP_CONNS; l++) {
	uip_periodic(l);

	//
	// If the above function invocation resulted in data that
	// should be sent out on the network, the global variable
	// uip_len is set to a value > 0.
	//
	if(uip_len > 0) {
	  uip_arp_out();
	  enc_send_packet(uip_buf, uip_len);
	  uip_len = 0;
	}
      }

      for(l = 0; l < UIP_UDP_CONNS; l++) {
	uip_udp_periodic(l);
	if( uip_len > 0) {
	  uip_arp_out();
	  enc_send_packet(uip_buf, uip_len);
	  uip_len = 0;
	}
      }
    }

    if( lARPTimer > UIP_ARP_TIMER_MS) {
      lARPTimer = 0;
      uip_arp_timer();
    }

  }

}
Example #17
0
int main(int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    int server_num = 0;
    const char *server_host[MAX_REMOTE_NUM];

    char * nameservers[MAX_DNS_NUM + 1];
    int nameserver_num = 0;

    int option_index = 0;
    static struct option long_options[] =
    {
        { "fast-open",          no_argument,       0, 0 },
        { "acl",                required_argument, 0, 0 },
        { "manager-address",    required_argument, 0, 0 },
        { 0,                    0,                 0, 0 }
    };

    opterr = 0;

    USE_TTY();

    while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:c:i:d:a:uUv",
                            long_options, &option_index)) != -1) {
        switch (c) {
        case 0:
            if (option_index == 0) {
                fast_open = 1;
            } else if (option_index == 1) {
                LOGI("initialize acl...");
                acl = !init_acl(optarg);
            } else if (option_index == 2) {
                manager_address = optarg;
            }
            break;
        case 's':
            if (server_num < MAX_REMOTE_NUM) {
                server_host[server_num++] = optarg;
            }
            break;
        case 'p':
            server_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'd':
            if (nameserver_num < MAX_DNS_NUM) {
                nameservers[nameserver_num++] = optarg;
            }
            break;
        case 'a':
            user = optarg;
            break;
        case 'u':
            mode = TCP_AND_UDP;
            break;
        case 'U':
            mode = UDP_ONLY;
            break;
        case 'v':
            verbose = 1;
            break;
        }
    }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (argc == 1) {
        if (conf_path == NULL) {
            conf_path = DEFAULT_CONF_PATH;
        }
    }

    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (server_num == 0) {
            server_num = conf->remote_num;
            for (i = 0; i < server_num; i++) {
                server_host[i] = conf->remote_addr[i].host;
            }
        }
        if (server_port == NULL) {
            server_port = conf->remote_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
#ifdef TCP_FASTOPEN
        if (fast_open == 0) {
            fast_open = conf->fast_open;
        }
#endif
#ifdef HAVE_SETRLIMIT
        if (nofile == 0) {
            nofile = conf->nofile;
        }
        /*
         * no need to check the return value here since we will show
         * the user an error message if setrlimit(2) fails
         */
        if (nofile) {
            if (verbose) {
                LOGI("setting NOFILE to %d", nofile);
            }
            set_nofile(nofile);
        }
#endif
        if (conf->nameserver != NULL) {
            nameservers[nameserver_num++] = conf->nameserver;
        }
    }

    if (server_num == 0) {
        server_host[server_num++] = NULL;
    }

    if (server_num == 0 || server_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (method == NULL) {
        method = "table";
    }

    if (timeout == NULL) {
        timeout = "60";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    if (fast_open == 1) {
#ifdef TCP_FASTOPEN
        LOGI("using tcp fast open");
#else
        LOGE("tcp fast open is not supported by this environment");
#endif
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    struct ev_signal sigint_watcher;
    struct ev_signal sigterm_watcher;
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    // setup keys
    LOGI("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // inilitialize ev loop
    struct ev_loop *loop = EV_DEFAULT;

    // setup udns
    if (nameserver_num == 0) {
#ifdef __MINGW32__
        nameservers[nameserver_num++] = "8.8.8.8";
        resolv_init(loop, nameservers, nameserver_num);
#else
        resolv_init(loop, NULL, 0);
#endif
    } else {
        resolv_init(loop, nameservers, nameserver_num);
    }

    for (int i = 0; i < nameserver_num; i++) {
        LOGI("using nameserver: %s", nameservers[i]);
    }

    // inilitialize listen context
    struct listen_ctx listen_ctx_list[server_num];

    // bind to each interface
    while (server_num > 0) {
        int index = --server_num;
        const char * host = server_host[index];

        if (mode != UDP_ONLY) {
            // Bind to port
            int listenfd;
            listenfd = create_and_bind(host, server_port);
            if (listenfd < 0) {
                FATAL("bind() error");
            }
            if (listen(listenfd, SSMAXCONN) == -1) {
                FATAL("listen() error");
            }
            setnonblocking(listenfd);
            struct listen_ctx *listen_ctx = &listen_ctx_list[index];

            // Setup proxy context
            listen_ctx->timeout = atoi(timeout);
            listen_ctx->fd = listenfd;
            listen_ctx->method = m;
            listen_ctx->iface = iface;
            listen_ctx->loop = loop;

            ev_io_init(&listen_ctx->io, accept_cb, listenfd, EV_READ);
            ev_io_start(loop, &listen_ctx->io);
        }

        // Setup UDP
        if (mode != TCP_ONLY) {
            init_udprelay(server_host[index], server_port, m, atoi(timeout),
                          iface);
        }

        LOGI("listening at %s:%s", host ? host : "*", server_port);

    }

    if (manager_address != NULL) {
        ev_timer_init(&stat_update_watcher, stat_update_cb, UPDATE_INTERVAL, UPDATE_INTERVAL);
        ev_timer_start(EV_DEFAULT, &stat_update_watcher);
    }

    if (mode != TCP_ONLY) {
        LOGI("UDP relay enabled");
    }

    if (mode == UDP_ONLY) {
        LOGI("TCP relay disabled");
    }

    // setuid
    if (user != NULL) {
        run_as(user);
    }

    // Init connections
    cork_dllist_init(&connections);

    // start ev loop
    ev_run(loop, 0);

    if (verbose) {
        LOGI("closed gracefully");
    }

    if (manager_address != NULL) {
        ev_timer_stop(EV_DEFAULT, &stat_update_watcher);
    }

    // Clean up
    for (int i = 0; i <= server_num; i++) {
        struct listen_ctx *listen_ctx = &listen_ctx_list[i];
        if (mode != UDP_ONLY) {
            ev_io_stop(loop, &listen_ctx->io);
            close(listen_ctx->fd);
        }
    }

    if (mode != UDP_ONLY) {
        free_connections(loop);
    }

    if (mode != TCP_ONLY) {
        free_udprelay();
    }

    resolv_shutdown(loop);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    ev_signal_stop(EV_DEFAULT, &sigint_watcher);
    ev_signal_stop(EV_DEFAULT, &sigterm_watcher);

    return 0;
}
Example #18
0
File: main.c Project: osrf/wandrr
int main()
{
  led_init();
  led_on();
  console_init();
  printf("===== APP ENTRY =====\r\n");
  systime_init();
  enc_init();
  usb_init();
  halls_init();
  therm_init();
  //enc_print_regs();

  printf("entering blink loop...\r\n");
  __enable_irq();
  usb_tx(1, g_tx_buf, sizeof(g_tx_buf));
  uint16_t raw_angle = 0, prev_raw_angle = 0;
  float raw_vel = 0;
  float filt_vel[3] = {0};
  float filt_angle[3] = {0};
  //float raw_vel = 0, filt_vel = 0, filt_angle = 0;
  bool filter_init = false;
  float unwrapped_raw = 0, prev_unwrapped_raw = 0;
  uint32_t t = 0, t_last_led_blink = 0;

  const float pos_gain[3] = { 0.9f, 0.99f, 0.999f };
  const float vel_gain[3] = { 0.99f, 0.999f, 0.9999f };

  int wraps = 0;
  uint32_t t_last_therm_reading = 0;
  g_therm_celsius = therm_celsius();
  while (1) 
  { 
    if (SYSTIME - t_last_therm_reading > 1000)
    {
      g_therm_celsius = therm_celsius();
      t_last_therm_reading = SYSTIME;
    }
    if (SYSTIME - t_last_led_blink > 100000)
    {
      t_last_led_blink = SYSTIME;
      led_toggle();
      /*
      printf("\n\n");
      printf("gintsts  = 0x%08x\r\n", (unsigned)USB_OTG_FS->GINTSTS);
      printf("dctl     = 0x%08x\r\n", (unsigned)g_usbd_dbg->DCTL);
      printf("dsts     = 0x%08x\r\n", (unsigned)g_usbd_dbg->DSTS);
      printf("dtxfsts1 = 0x%08x\r\n", (unsigned)USB_INEP(1)->DTXFSTS);
      printf("diepctl1 = 0x%08x\r\n", (unsigned)USB_INEP(1)->DIEPCTL);
      printf("diepint1 = 0x%08x\r\n", (unsigned)USB_INEP(1)->DIEPINT);
      printf("dieptsiz1= 0x%08x\r\n", (unsigned)USB_INEP(1)->DIEPTSIZ);
      */
    }
    raw_angle = enc_poll_angle();
    t = SYSTIME;

    if (filter_init)
    {
      int diff = raw_angle - prev_raw_angle;
      if (diff > 8000)
        wraps--;
      else if (diff < -8000)
        wraps++;
      unwrapped_raw = (float)raw_angle + wraps * 16384;
      // calculate raw_vel in ticks/usec for numerical stability
      // TODO: use a better timebase, since we're polling @ 100 khz so there
      // is extreme quantization on the microsecond clock
      float dt_usecs = (float)(t - g_t_angle) * 1000000.0f;
      if (dt_usecs < 1.0f)
        dt_usecs = 1.0f;

      // todo: this leads to bad numerical stability after lots of wraps
      // need to re-work this crap
      raw_vel = (unwrapped_raw - prev_unwrapped_raw) / dt_usecs;
      for (int i = 0; i < 3; i++)
      {
        filt_angle[i] =         pos_gain[i]  * filt_angle[i] + 
                        (1.0f - pos_gain[i]) * unwrapped_raw;
        filt_vel[i]   =         vel_gain[i]  * filt_vel[i]   + 
                        (1.0f - vel_gain[i]) * raw_vel * 1000000.0f;
      }
    }
    else
    {
      filter_init = true;
      for (int i = 0; i < 3; i++)
      {
        filt_angle[i] = raw_angle;
        filt_vel[i] = 0;
      }
    }
    prev_raw_angle = raw_angle;
    prev_unwrapped_raw = unwrapped_raw;

    __disable_irq();
    g_t_angle = t;
    g_raw_angle = raw_angle;
    for (int i = 0; i < 3; i++)
    {
      g_angle[i] = filt_angle[i];
      g_vel[i] = filt_vel[i]; // * 0.000001f; // convert to ticks / sec
    }
    g_num_samp++;
    __enable_irq();
    
  }
  return 0;
}
Example #19
0
int main(int argc, char **argv)
{
    int i, c;
    int pid_flags    = 0;
    char *user       = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password   = NULL;
    char *timeout    = NULL;
    char *method     = NULL;
    char *pid_path   = NULL;
    char *conf_path  = NULL;

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    opterr = 0;

    while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:c:b:a:n:uUvA")) != -1)
        switch (c) {
        case 's':
            if (remote_num < MAX_REMOTE_NUM) {
                remote_addr[remote_num].host   = optarg;
                remote_addr[remote_num++].port = NULL;
            }
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path  = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'a':
            user = optarg;
            break;
#ifdef HAVE_SETRLIMIT
        case 'n':
            nofile = atoi(optarg);
            break;
#endif
        case 'u':
            mode = TCP_AND_UDP;
            break;
        case 'U':
            mode = UDP_ONLY;
            break;
        case 'v':
            verbose = 1;
            break;
        case 'A':
            auth = 1;
            break;
        }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (argc == 1) {
        if (conf_path == NULL) {
            conf_path = DEFAULT_CONF_PATH;
        }
    }

    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0) {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++)
                remote_addr[i] = conf->remote_addr[i];
        }
        if (remote_port == NULL) {
            remote_port = conf->remote_port;
        }
        if (local_addr == NULL) {
            local_addr = conf->local_addr;
        }
        if (local_port == NULL) {
            local_port = conf->local_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
        if (auth == 0) {
            auth = conf->auth;
        }
#ifdef HAVE_SETRLIMIT
        if (nofile == 0) {
            nofile = conf->nofile;
        }
        /*
         * no need to check the return value here since we will show
         * the user an error message if setrlimit(2) fails
         */
        if (nofile > 1024) {
            if (verbose) {
                LOGI("setting NOFILE to %d", nofile);
            }
            set_nofile(nofile);
        }
#endif
    }

    if (remote_num == 0 || remote_port == NULL ||
        local_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) {
        timeout = "60";
    }

    if (local_addr == NULL) {
        local_addr = "127.0.0.1";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    if (auth) {
        LOGI("onetime authentication enabled");
    }

    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);

    // Setup keys
    LOGI("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup proxy context
    listen_ctx_t listen_ctx;
    listen_ctx.remote_num  = remote_num;
    listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *) * remote_num);
    for (int i = 0; i < remote_num; i++) {
        char *host = remote_addr[i].host;
        char *port = remote_addr[i].port == NULL ? remote_port :
                     remote_addr[i].port;
        struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage));
        memset(storage, 0, sizeof(struct sockaddr_storage));
        if (get_sockaddr(host, port, storage, 1) == -1) {
            FATAL("failed to resolve the provided hostname");
        }
        listen_ctx.remote_addr[i] = (struct sockaddr *)storage;
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.method  = m;

    struct ev_loop *loop = EV_DEFAULT;

    if (mode != UDP_ONLY) {
        // Setup socket
        int listenfd;
        listenfd = create_and_bind(local_addr, local_port);
        if (listenfd < 0) {
            FATAL("bind() error");
        }
        if (listen(listenfd, SOMAXCONN) == -1) {
            FATAL("listen() error");
        }
        setnonblocking(listenfd);

        listen_ctx.fd = listenfd;

        ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
        ev_io_start(loop, &listen_ctx.io);
    }

    // Setup UDP
    if (mode != TCP_ONLY) {
        LOGI("UDP relay enabled");
        init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0],
                      get_sockaddr_len(listen_ctx.remote_addr[0]), m, auth, listen_ctx.timeout, NULL);
    }

    if (mode == UDP_ONLY) {
        LOGI("TCP relay disabled");
    }

    LOGI("listening at %s:%s", local_addr, local_port);

    // setuid
    if (user != NULL) {
        run_as(user);
    }

    ev_run(loop, 0);

    return 0;
}
Example #20
0
int start_ss_local_server(profile_t profile)
{
    srand(time(NULL));

    char *remote_host = profile.remote_host;
    char *local_addr = profile.local_addr;
    char *method = profile.method;
    char *password = profile.password;
    char *log = profile.log;
    int remote_port = profile.remote_port;
    int local_port = profile.local_port;
    int timeout = profile.timeout;

    mode = profile.mode;
    fast_open = profile.fast_open;
    verbose = profile.verbose;

    char local_port_str[16];
    char remote_port_str[16];
    sprintf(local_port_str, "%d", local_port);
    sprintf(remote_port_str, "%d", remote_port);

    USE_LOGFILE(log);

    if (profile.acl != NULL) {
        acl = !init_acl(profile.acl);
    }

    if (local_addr == NULL) {
        local_addr = "127.0.0.1";
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    struct ev_signal sigint_watcher;
    struct ev_signal sigterm_watcher;
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    // Setup keys
    LOGI("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage));
    memset(storage, 0, sizeof(struct sockaddr_storage));
    if (get_sockaddr(remote_host, remote_port_str, storage, 1) == -1) {
        return -1;
    }

    // Setup proxy context
    struct ev_loop *loop = EV_DEFAULT;
    struct listen_ctx listen_ctx;

    listen_ctx.remote_num = 1;
    listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *));
    listen_ctx.remote_addr[0] = (struct sockaddr *)storage;
    listen_ctx.timeout = timeout;
    listen_ctx.method = m;
    listen_ctx.iface = NULL;

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port_str);
    if (listenfd < 0) {
        ERROR("bind()");
        return -1;
    }
    if (listen(listenfd, SOMAXCONN) == -1) {
        ERROR("listen()");
        return -1;
    }
    setnonblocking(listenfd);

    listen_ctx.fd = listenfd;

    ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start(loop, &listen_ctx.io);

    // Setup UDP
    if (mode != TCP_ONLY) {
        LOGI("udprelay enabled");
        struct sockaddr *addr = (struct sockaddr *)storage;
        init_udprelay(local_addr, local_port_str, addr,
                      get_sockaddr_len(addr), m, timeout, NULL);
    }

    LOGI("listening at %s:%s", local_addr, local_port_str);

    // Init connections
    cork_dllist_init(&connections);

    // Enter the loop
    ev_run(loop, 0);

    if (verbose) {
        LOGI("closed gracefully");
    }

    // Clean up
    if (mode != TCP_ONLY) {
        free_udprelay();
    }

    ev_io_stop(loop, &listen_ctx.io);
    free_connections(loop);
    close(listen_ctx.fd);

    free(listen_ctx.remote_addr);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    ev_signal_stop(EV_DEFAULT, &sigint_watcher);
    ev_signal_stop(EV_DEFAULT, &sigterm_watcher);

    // cannot reach here
    return 0;
}
Example #21
0
void cmd_lcd_test(uint_least16_t fgcolor, uint_least16_t bgcolor)
{
  uint_least8_t c=1, f_save=features;
  char tmp[32];
#ifdef TP_SUPPORT
  uint_least16_t x, y, z, last_x=0, last_y=0;
  uint_least32_t ms=0;

  tp_init();
  ldr_init();
  features = FEATURE_TP | FEATURE_LDR; //FEATURE_TP | FEATURE_LDR
#else
  uint_least8_t sw;
  int_least8_t pos=0, hpos=0, vpos=0;

  enc_init();
  features = FEATURE_ENC;
#endif

  lcd_fillrect(0,                   0, (LCD_WIDTH-1)/3,     LCD_HEIGHT-1, RGB(255,0,0));
  lcd_fillrect((LCD_WIDTH-1)/3,     0, ((LCD_WIDTH-1)/3)*2, LCD_HEIGHT-1, RGB(0,255,0));
  lcd_fillrect(((LCD_WIDTH-1)/3)*2, 0, LCD_WIDTH-1,         LCD_HEIGHT-1, RGB(0,0,255));
/*
  delay_ms(1500);
  lcd_clear(bgcolor);

  lcd_setorientation(  0); lcd_drawrect(10, 20, 40, 40, RGB(200,  0,  0)); lcd_drawtext(15, 25, "0  ", 0, RGB(200,  0,  0), 0, 0);
  lcd_setorientation( 90); lcd_drawrect(10, 20, 40, 40, RGB(  0,200,  0)); lcd_drawtext(15, 25, "90 ", 0, RGB(  0,200,  0), 0, 0);
  lcd_setorientation(180); lcd_drawrect(10, 20, 40, 40, RGB(  0,  0,200)); lcd_drawtext(15, 25, "180", 0, RGB(  0,  0,200), 0, 0);
  lcd_setorientation(270); lcd_drawrect(10, 20, 40, 40, RGB(200,  0,200)); lcd_drawtext(15, 25, "270", 0, RGB(200,  0,200), 0, 0);

  lcd_setorientation(0);
  lcd_drawline(0, LCD_WIDTH/4*1, LCD_WIDTH-1, LCD_WIDTH/4*1, RGB(120,120,120));
  lcd_drawline(0, LCD_WIDTH/4*2, LCD_WIDTH-1, LCD_WIDTH/4*2, RGB(120,120,120));
  lcd_drawline(0, LCD_WIDTH/4*3, LCD_WIDTH-1, LCD_WIDTH/4*3, RGB(120,120,120));
  lcd_drawline(LCD_WIDTH/4*1, 0, LCD_WIDTH/4*1, LCD_HEIGHT-1, RGB(120,120,120));
  lcd_drawline(LCD_WIDTH/4*2, 0, LCD_WIDTH/4*2, LCD_HEIGHT-1, RGB(120,120,120));
  lcd_drawline(LCD_WIDTH/4*3, 0, LCD_WIDTH/4*3, LCD_HEIGHT-1, RGB(120,120,120));
  lcd_drawcircle(LCD_WIDTH/2, LCD_HEIGHT/2, 40, RGB(120,120,120));
*/

  lcd_drawtext(LCD_CENTER, LCD_HEIGHT/2-5, "v"VERSION, 0, 0, 0, 0);
  lcd_drawtext(LCD_CENTER, LCD_HEIGHT/2+5, "("__DATE__")", 0, 0, 0, 0);
  lcd_drawtext(LCD_CENTER, LCD_HEIGHT-10, "watterott.com", 1, 0, 0, 0);

  do
  {
#ifdef TP_SUPPORT
    tp_read();
    z = tp_getz();
    if(z)
    {
      x = tp_getx();
      y = tp_gety();
      if((x!=last_x) || (y!=last_y))
      {
        last_x = x;
        last_y = y;
        lcd_fillcircle(x, y, 4, fgcolor); //lcd_drawpixel(x, y);
        sprintf(tmp, "X%03i Y%03i Z%03i", x, x, z);
        lcd_drawtext(5, 5, tmp, 0, fgcolor, bgcolor, 1);
      }

      GPIO_SETPIN(LED_PORT, LED_PIN); //LED on
    }
    else
    {
      GPIO_CLRPIN(LED_PORT, LED_PIN); //LED off
    }

    if(features & FEATURE_LDR)
    {
      if((get_ms() - ms) >= 100)
      {
        ms = get_ms();
        x = ldr_service(100);
        sprintf(tmp, "LDR %03i", x);
        lcd_drawtext(5, 15, tmp, 0, fgcolor, bgcolor, 1);
      }
    }

#else //TP_SUPPORT

    pos  += enc_getdelta();
    hpos += nav_gethdelta();
    vpos += nav_getvdelta();
    sprintf(tmp, "P%03i H%03i V%03i", pos, hpos, vpos);
    lcd_drawtext(5, 5, tmp, 0, fgcolor, bgcolor, 1);

    sw  = enc_getsw();
    sw |= nav_getsw();
    if(sw)
    {
      GPIO_SETPIN(LED_PORT, LED_PIN); //LED on
      if(sw & 0x02)
      {
        if(features == FEATURE_ENC)
        {
          sprintf(tmp, "NAV");
          nav_init();
          features = FEATURE_NAV;
        }
        else //if(features == FEATURE_NAV)
        {
          sprintf(tmp, "ENC");
          enc_init();
          features = FEATURE_ENC;
        }
        lcd_drawtext(5, 25, tmp, 0, fgcolor, bgcolor, 1);
        delay_ms(500);
        while(enc_getsw() || nav_getsw());
      }
      else if(sw & 0x01)
      {
        lcd_drawtext(5, 15, "press", 0, fgcolor, bgcolor, 1);
      }
    }
    else
    {
      GPIO_CLRPIN(LED_PORT, LED_PIN); //LED off
    }
#endif
    if(if_available())
    {
      c = if_read8();
    }
  }while(c != 0);

  GPIO_CLRPIN(LED_PORT, LED_PIN); //LED off

  lcd_clear(bgcolor);

  features = f_save;

  return;
}
Example #22
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  /* Chip errata */
  CHIP_Init();

  /* If first word of user data page is non-zero, enable eA Profiler trace */
  BSP_TraceProfilerSetup();

  /* Initial BSP led driver .  **/
  BSP_LedsInit();
  BSP_LedSet(0);
  BSP_LedClear(0);

  /* timer1 intial to generate wave. */
  enc_init();

  /* Initialize LCD controller without boost */
  SegmentLCD_Init(false);

  /* Disable all segments */
  SegmentLCD_AllOff();

  /* Copy contents of the userpage (flash) into the userData struct */
  //memcpy((void *) &userData, (void *) USERPAGE, sizeof(UserData_TypeDef));

  /* Special case for uninitialized data */
  if (userData.number > 10000)
    userData.number = 0;
  if (userData.numWrites == 0xFFFFFFFF)
    userData.numWrites = 0;

  /* Display the number */
  SegmentLCD_Number(userData.number);

  /* Setup GPIO interrupts. PB0 to increase number, PB1 to save to flash */
  gpioSetup();

  /* No save has occured yet */
  recentlySaved = false;

  /* Main loop - just scroll informative text describing the current state of
   * the system */
  while (1)
  {
	EM2Sleep(125);
#if 0
    switch (currentError)
    {
    case mscReturnInvalidAddr:
      ScrollText("     ERROR: INVALID ADDRESS      ");
      break;
    case mscReturnLocked:
      ScrollText("     ERROR: USER PAGE IS LOCKED      ");
      break;
    case mscReturnTimeOut:
      ScrollText("     ERROR: TIMEOUT OCCURED      ");
      break;
    case mscReturnUnaligned:
      ScrollText("     ERROR: UNALIGNED ACCESS     ");
    default:
      if (recentlySaved)
      {
        recentlySaved = false;
        SegmentLCD_Number(userData.numWrites);
        ScrollText("     SAVE NUMBER       ");
      }
      else
      {
        SegmentLCD_Number(userData.number);
        ScrollText("     PRESS PB0 TO INCREASE NUMBER. PB1 TO SAVE TO INTERNAL FLASH        ");
      }
      break;
    }
#endif
  }
}
Example #23
0
int main (int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    int server_num = 0;
    const char *server_host[MAX_REMOTE_NUM];
    const char *server_port = NULL;

    int dns_thread_num = DNS_THREAD_NUM;

    int option_index = 0;
    static struct option long_options[] =
    {
        {"fast-open", no_argument, 0,  0 },
        {"port-start", required_argument, 0, 0 },
        {"port-end", required_argument, 0, 0 },
        {0,           0,           0,  0 }
    };

    opterr = 0;

    while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:c:i:d:a:uv",
                            long_options, &option_index)) != -1)
    {
        printf("option_index %d\n", option_index);
        switch (c)
        {
        case 0:

            if (option_index == 0)
            {
#ifdef TCP_FASTOPEN
                fast_open = 1;
                LOGD("using tcp fast open");
#else
                LOGE("tcp fast open is not supported by this environment");
#endif
            } else
            if (option_index == 1) 
            {
                start_port = atoi(optarg);
            } else
            if (option_index == 2) 
            {
                end_port = atoi(optarg);
            }

            break;
        case 's':
            server_host[server_num++] = optarg;
            break;
        case 'p':
            server_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'd':
            dns_thread_num = atoi(optarg);
            if (!dns_thread_num) FATAL("Invalid DNS thread number");
            break;
        case 'a':
            user = optarg;
            break;
        case 'u':
            udprelay = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        }
    }

    printf("start %d end %d\n", start_port, end_port);

    if (opterr)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (conf_path != NULL)
    {
        jconf_t *conf = read_jconf(conf_path);
        if (server_num == 0)
        {
            server_num = conf->remote_num;
            for (i = 0; i < server_num; i++)
            {
                server_host[i] = conf->remote_addr[i].host;
            }
        }
        if (server_port == NULL) server_port = conf->remote_port;
        if (password == NULL) password = conf->password;
        if (method == NULL) method = conf->method;
        if (timeout == NULL) timeout = conf->timeout;
#ifdef TCP_FASTOPEN
        if (fast_open == 0) fast_open = conf->fast_open;
#endif
#ifdef HAVE_SETRLIMIT
        if (nofile == 0) nofile = conf->nofile;
        /*
         * no need to check the return value here since we will show
         * the user an error message if setrlimit(2) fails
         */
        if (nofile)
        {
            if (verbose)
            {
                LOGD("setting NOFILE to %d", nofile);
            }
            set_nofile(nofile);
        }
#endif
    }

    if ((start_port > 0 && end_port <= 0) || (start_port <= 0 && end_port > 0)) {
        printf("Both start_prot and end_port needs to be specified\n");
        usage();
        exit(EXIT_FAILURE);
    }

    if (server_port != NULL && start_port > 0) {
        printf("server port can't be set if you want to use a port range\n");
        usage();
        exit(EXIT_FAILURE);
    }

    if (server_num == 0 || (server_port == NULL && start_port <= 0) || password == NULL)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) timeout = "60";

    if (pid_flags)
    {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
    signal(SIGABRT, SIG_IGN);

    // setup asyncns
    asyncns_t *asyncns;
    if (!(asyncns = asyncns_new(dns_thread_num)))
    {
        FATAL("asyncns failed");
    }

    // setup keys
    LOGD("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // inilitialize ev loop
    struct ev_loop *loop = EV_DEFAULT;

    // inilitialize listen context
    struct listen_ctx listen_ctx_list[server_num + 1];

    // bind to each interface
    while (server_num > 0)
    {
        int index = --server_num;
        const char* host = server_host[index];
        int success = 1;
        int listenfd;

        if (start_port > 0) {
            server_port = itoa(start_port);
        }
        do {
            // Bind to port
            
            listenfd = create_and_bind(host, server_port);
            success = 1;
            if (listenfd < 0)
            {
                success = 0;
            }
            if (listen(listenfd, SOMAXCONN) == -1)
            {
                success = 0;
            }
            if (!success) {
                if (start_port < end_port) {
                    start_port++;
                    server_port = itoa(start_port);
                } else
                {
                    FATAL("Out of listen ports!");
                    exit(1);
                }
            }
        } while (!success);
        setnonblocking(listenfd);
        LOGD("server listening at port %s.", server_port);

        struct listen_ctx *listen_ctx = &listen_ctx_list[index + 1];

        // Setup proxy context
        listen_ctx->timeout = atoi(timeout);
        listen_ctx->asyncns = asyncns;
        listen_ctx->fd = listenfd;
        listen_ctx->method = m;
        listen_ctx->iface = iface;

        ev_io_init (&listen_ctx->io, accept_cb, listenfd, EV_READ);
        ev_io_start (loop, &listen_ctx->io);
    }

    // initialize the DNS
    struct listen_ctx *listen_ctx = &listen_ctx_list[0];
    int asyncnsfd = asyncns_fd(asyncns);
    listen_ctx->timeout = atoi(timeout);
    listen_ctx->asyncns = asyncns;
    listen_ctx->fd = asyncnsfd;
    listen_ctx->method = m;
    listen_ctx->iface = iface;
    ev_io_init (&listen_ctx->io, server_resolve_cb, asyncnsfd, EV_READ);
    ev_io_start (loop, &listen_ctx->io);

    // Setup UDP
    if (udprelay)
    {
        LOGD("udprelay enabled.");
        udprelay_init(server_host[0], server_port, dns_thread_num, m, listen_ctx->timeout, iface);
    }

    // setuid
    if (user != NULL)
        run_as(user);

    // start ev loop
    ev_run (loop, 0);
    return 0;
}
Example #24
0
// outer layer ECC using incremental encoding
int inc_encoding (FILE* fp,int* prptable)
{
	printf("\nIncremental encoding starts...\n");
	int i,j,enc_blocks,d=n-k;
	// get file length
	fseek(fp,0,SEEK_END);
	fileLen = ftell(fp);
	// divide by message length k, get number of encoding blocks
	if(fileLen % k==0) 
		enc_blocks = fileLen/k;
	else
		enc_blocks = fileLen/k+1;
	printf("There are %d encoding blocks\n",enc_blocks);
	unsigned char message[k];
	unsigned char codeword[n];
	unsigned char ** code; // used to store parity part
	
	long filecounter = 0;
	int blockcounter = 0;
	int round = 0;

	// code is enc_blocks * d
	code = (unsigned char **) malloc(enc_blocks*sizeof(unsigned char *));  
	for (i = 0; i < enc_blocks; i++) {
   	code[i] = (unsigned char *) malloc(d*sizeof(unsigned char)); 
   	int ii;
   	for (ii=0;ii<d;ii++)
   		code[i][ii]=0; 
   	}
   	

   rewind(fp);
	while (!feof(fp))
	{
		unsigned char * buf; 
		if ((buf = malloc(sizeof(unsigned char)*readLen))==NULL) {
			printf("malloc error: inc_encoding\n");
			exit(1);
		}
		// incremental encoding, read reaLen each time
		readStartTime = getCPUTime();
		clock_gettime(CLOCK_MONOTONIC, &start);
		printf("max read in %d bytes\n",readLen);
		size_t br = fread(buf, 1, readLen, fp);
		printf("Read in %lu bytes\n",br);
		fflush(stdout);
		clock_gettime(CLOCK_MONOTONIC, &finish);
		double addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
		readTime += getCPUTime() - readStartTime+addTime;
		// keep a counter to know where the file pointer up to
		filecounter = filecounter + br;
		if (br!=0) {
			printf("round %d\n",round);
			printf("filecounter = %lu\n",filecounter);
			for(i=0;i<enc_blocks;i++) {
				for(j=0;j<k;j++) {
					// for each byte in each message, compute index
					int index = i*k+j;
					// get block and byte index
					int block_index = index/BLOCK_SIZE;
					int byte_index = index%BLOCK_SIZE;
					// if reach the end, padding 0s
					if (index>=fileLen) {
						int a;
						for(a=j;a<k;a++)
							message[a]=0;
						break;
					}
					// compute the PRPed index in the file
					unsigned long file_index = prptable[block_index]*BLOCK_SIZE+byte_index;
					
					// check if this byte is read in the memory or not, copy if yes, put 0 otherwise
					if(file_index<filecounter && file_index>=(filecounter-br)) {
						unsigned long newind = file_index-filecounter+br;
						message[j] = buf[newind];
					}
					else 
						message[j] = 0;
				}
				//printf("msg for block %d: ",i);
				//displayCharArray(message,k);
				// do a partial encoding on the message
				encode_data(message,k,codeword);
				// concatenate with previous code to get a whole
				/*printf("code for block %d: ",i);
				displayCharArray(codeword,n);
				printf("parity (before) for block %d: ",i);
				displayCharArray(code[i],n-k);*/
				for(j=0;j<d;j++)
					code[i][j] = code[i][j] ^ codeword[k+j];
				//printf("parity for block %d: ",i);
				//displayCharArray(code[i],n-k);
				//printf("\n");
			}
			round = round + 1;
		}
		free(buf);
	}
	/*// ------------- for debugging
	unsigned char a[fileLen],r[fileLen];
	unsigned char newc[n],newm[k];
	rewind(fp);
	fread(a, 1, fileLen, fp);
	printf("original:\n");
	for (i=0;i<fileLen;i++) {
		printf("%02x",a[i]);
	}
	printf("\n");
	for (i=0;i<fileLen/32;i++) {
		for (j=0;j<32;j++) {
			r[i*32+j] = a[prptable[i]*32+j];
		}
	}
	printf("prped:\n");
	for (i=0;i<fileLen;i++) {
		printf("%02x",r[i]);
	}
	printf("\n");
	for (i=0;i<enc_blocks;i++) {
		printf("parity part %d: ",i);
		displayCharArray(code[i],d);

		unsigned char newcode[n];
		int iii;
		int ii;
		for(ii=0;ii<k;ii++) {
			if (i*k+ii>=fileLen)
				break;
			newcode[ii] = r[i*k+ii];
			newm[ii] = r[i*k+ii];
		}
		if (i==enc_blocks-1) {
			for(ii=0;ii<k-fileLen%k;ii++){
				newm[fileLen%k+ii]=0;
				newcode[fileLen%k+ii] = 0;
			}
		}
		encode_data(newm,k,newc);
		printf("actual code %d: ",i);
		displayCharArray(newc,n);
		for(iii=0;iii<d;iii++) {
			newcode[k+iii] = code[i][iii];
		}
		newcode[0] = 99;
		printf("whole code %d: ",i);
		displayCharArray(newcode,n);
		decode_data(newcode, n);
		int erasure[1];
		int syn = check_syndrome ();
		printf("syndrome: %d\n",syn);
		if (syn != 0) {
			correct_errors_erasures(newcode,n,0,erasure);
		}
		printf("decode %d: ",i);
		displayCharArray(newcode,n);
	}
	//--------------- for debugging */
	free(prptable);
	prptable = NULL;
	// perform another PRP for parity part
	prptable = malloc(sizeof(int)*(enc_blocks));
	printf("\nSRF PRP for the outer layer ECC...\n");
   prpStartTime = getCPUTime();
	prptable = prp(enc_blocks, k_ecc_perm);
   prpTime += getCPUTime() - prpStartTime;
   
   // encrypt parity part and append to the file with PRPed order
	enc_init(k_ecc_enc);
	for (i=0;i<enc_blocks;i++) {
		unsigned char ct[d];

    	clock_gettime(CLOCK_MONOTONIC, &start);
    	encStartTime = getCPUTime();
		encrypt(ct,code[prptable[i]],sizeof(ct));
		clock_gettime(CLOCK_MONOTONIC, &finish);
		double addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
		encTime += getCPUTime()-encStartTime+addTime;

		//printf("encrypted for %d: ",i);
		//displayCharArray(ct,sizeof(ct));
		//unsigned char pt[d];
		//decrypt(ct,pt,sizeof(ct));
		//printf("decrypted for %d: ",i);
		//displayCharArray(pt,sizeof(ct));
    	clock_gettime(CLOCK_MONOTONIC, &start);
		write1StartTime = getCPUTime();
		fwrite(ct,d,1,fp);
		clock_gettime(CLOCK_MONOTONIC, &finish);
		addTime = finish.tv_sec - start.tv_sec;
		addTime += (finish.tv_nsec - start.tv_nsec)/1000000000.0;
    	write1Time += getCPUTime()-write1StartTime;
	}
	// update t for later challenge computation
	t = t+enc_blocks;
	printf("\nIncremental encoding finishes...\n");
	free(prptable);
	for (i = 0; i < enc_blocks; i++){  
   	free(code[i]);  
	}  
	free(code); 
	return 0;
}
Example #25
0
int start_ss_local_server(profile_t profile)
{
    srand(time(NULL));

    char *remote_host = profile.remote_host;
    char *local_addr = profile.local_addr;
    char *method = profile.method;
    char *password = profile.password;
    char *log = profile.log;
    int remote_port = profile.remote_port;
    int local_port = profile.local_port;
    int timeout = profile.timeout;

    udprelay = profile.udp_relay;
    fast_open = profile.fast_open;
    verbose = profile.verbose;

    char local_port_str[16];
    char remote_port_str[16];
    sprintf(local_port_str, "%d", local_port);
    sprintf(remote_port_str, "%d", remote_port);

    USE_LOGFILE(log);

    if (profile.acl != NULL) {
        acl = !init_acl(profile.acl);
    }

    if (local_addr == NULL) {
        local_addr = "0.0.0.0";
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    struct ev_signal sigint_watcher;
    struct ev_signal sigterm_watcher;
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    // Setup keys
    LOGD("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port_str);
    if (listenfd < 0) {
        FATAL("bind()");
    }
    if (listen(listenfd, SOMAXCONN) == -1) {
        FATAL("listen()");
    }
    setnonblocking(listenfd);
    LOGD("server listening at port %s.", local_port_str);

    // Setup proxy context
    struct listen_ctx listen_ctx;

    listen_ctx.remote_num = 1;
    listen_ctx.remote_addr = malloc(sizeof(ss_addr_t));
    listen_ctx.remote_addr[0].host = remote_host;
    listen_ctx.remote_addr[0].port = remote_port_str;
    listen_ctx.timeout = timeout;
    listen_ctx.fd = listenfd;
    listen_ctx.method = m;
    listen_ctx.iface = NULL;

    struct ev_loop *loop = EV_DEFAULT;
    if (!loop) {
        FATAL("ev_loop error.");
    }
    ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start(loop, &listen_ctx.io);

    // Setup UDP
    if (udprelay) {
        LOGD("udprelay enabled.");
        init_udprelay(local_addr, local_port_str, remote_host, remote_port_str,
                      m, listen_ctx.timeout, NULL);
    }

    // Init connections
    cork_dllist_init(&connections);

    // Enter the loop
    ev_run(loop, 0);

    if (verbose) {
        LOGD("closed nicely.");
    }

    // Clean up
    free_connections(loop);
    if (udprelay) {
        free_udprelay();
    }

    ev_io_stop(loop, &listen_ctx.io);
    free(listen_ctx.remote_addr);
    close(listen_ctx.fd);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    ev_signal_stop(EV_DEFAULT, &sigint_watcher);
    ev_signal_stop(EV_DEFAULT, &sigterm_watcher);

    // cannot reach here
    return 0;
}
Example #26
0
int main(int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    ss_addr_t tunnel_addr = { .host = NULL, .port = NULL };
    char *tunnel_addr_str = NULL;

    opterr = 0;

    USE_TTY();

#ifdef ANDROID
    while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:uUvV")) != -1) {
#else
    while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:i:c:b:L:a:uUv")) != -1) {
#endif
        switch (c) {
        case 's':
            if (remote_num < MAX_REMOTE_NUM) {
                remote_addr[remote_num].host = optarg;
                remote_addr[remote_num++].port = NULL;
            }
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'u':
            mode = TCP_AND_UDP;
            break;
        case 'U':
            mode = UDP_ONLY;
            break;
        case 'L':
            tunnel_addr_str = optarg;
            break;
        case 'a':
            user = optarg;
            break;
        case 'v':
            verbose = 1;
            break;
#ifdef ANDROID
        case 'V':
            vpn = 1;
            break;
#endif
        }
    }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (argc == 1) {
        if (conf_path == NULL) {
            conf_path = DEFAULT_CONF_PATH;
        }
    }

    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0) {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++) {
                remote_addr[i] = conf->remote_addr[i];
            }
        }
        if (remote_port == NULL) {
            remote_port = conf->remote_port;
        }
        if (local_addr == NULL) {
            local_addr = conf->local_addr;
        }
        if (local_port == NULL) {
            local_port = conf->local_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
    }

    if (remote_num == 0 || remote_port == NULL || tunnel_addr_str == NULL ||
        local_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) {
        timeout = "60";
    }

    if (local_addr == NULL) {
        local_addr = "127.0.0.1";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    // parse tunnel addr
    parse_addr(tunnel_addr_str, &tunnel_addr);

    if (tunnel_addr.port == NULL) {
        FATAL("tunnel port is not defined");
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    // Setup keys
    LOGI("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup proxy context
    struct listen_ctx listen_ctx;
    listen_ctx.tunnel_addr = tunnel_addr;
    listen_ctx.remote_num = remote_num;
    listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *) * remote_num);
    for (i = 0; i < remote_num; i++) {
        char *host = remote_addr[i].host;
        char *port = remote_addr[i].port == NULL ? remote_port :
                     remote_addr[i].port;
        struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage));
        memset(storage, 0, sizeof(struct sockaddr_storage));
        if (get_sockaddr(host, port, storage, 1) == -1) {
            FATAL("failed to resolve the provided hostname");
        }
        listen_ctx.remote_addr[i] = (struct sockaddr *)storage;
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.iface = iface;
    listen_ctx.method = m;

    struct ev_loop *loop = EV_DEFAULT;

    if (mode != UDP_ONLY) {
        // Setup socket
        int listenfd;
        listenfd = create_and_bind(local_addr, local_port);
        if (listenfd < 0) {
            FATAL("bind() error:");
        }
        if (listen(listenfd, SOMAXCONN) == -1) {
            FATAL("listen() error:");
        }
        setnonblocking(listenfd);

        listen_ctx.fd = listenfd;

        ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
        ev_io_start(loop, &listen_ctx.io);
    }

    // Setup UDP
    if (mode != TCP_ONLY) {
        LOGI("UDP relay enabled");
        init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0],
                      get_sockaddr_len(listen_ctx.remote_addr[0]),
                      tunnel_addr, m, listen_ctx.timeout, iface);
    }

    if (mode == UDP_ONLY) {
        LOGI("TCP relay disabled");
    }

    LOGI("listening at %s:%s", local_addr, local_port);

    // setuid
    if (user != NULL) {
        run_as(user);
    }

    ev_run(loop, 0);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    return 0;
}
Example #27
0
int main(int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    srand(time(NULL));

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    int option_index = 0;
    static struct option long_options[] =
    {
        { "fast-open", no_argument,             0,
          0 },
        { "acl",       required_argument,       0,
          0 },
        { 0,           0,                       0,
          0 }
    };

    opterr = 0;

    while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:i:c:b:a:uv",
                            long_options, &option_index)) != -1) {
        switch (c) {
        case 0:
            if (option_index == 0) {
                fast_open = 1;
            } else if (option_index == 1) {
                LOGD("initialize acl...");
                acl = !init_acl(optarg);
            }
            break;
        case 's':
            remote_addr[remote_num].host = optarg;
            remote_addr[remote_num++].port = NULL;
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'a':
            user = optarg;
            break;
        case 'u':
            udprelay = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        }
    }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0) {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++) {
                remote_addr[i] = conf->remote_addr[i];
            }
        }
        if (remote_port == NULL) {
            remote_port = conf->remote_port;
        }
        if (local_addr == NULL) {
            local_addr = conf->local_addr;
        }
        if (local_port == NULL) {
            local_port = conf->local_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
        if (fast_open == 0) {
            fast_open = conf->fast_open;
        }
#ifdef HAVE_SETRLIMIT
        if (nofile == 0) {
            nofile = conf->nofile;
        }
        /*
         * no need to check the return value here since we will show
         * the user an error message if setrlimit(2) fails
         */
        if (nofile) {
            if (verbose) {
                LOGD("setting NOFILE to %d", nofile);
            }
            set_nofile(nofile);
        }
#endif
    }

    if (remote_num == 0 || remote_port == NULL ||
        local_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) {
        timeout = "10";
    }

    if (local_addr == NULL) {
        local_addr = "0.0.0.0";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    if (fast_open == 1) {
#ifdef TCP_FASTOPEN
        LOGD("using tcp fast open");
#else
        LOGE("tcp fast open is not supported by this environment");
#endif
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    struct ev_signal sigint_watcher;
    struct ev_signal sigterm_watcher;
    ev_signal_init(&sigint_watcher, signal_cb, SIGINT);
    ev_signal_init(&sigterm_watcher, signal_cb, SIGTERM);
    ev_signal_start(EV_DEFAULT, &sigint_watcher);
    ev_signal_start(EV_DEFAULT, &sigterm_watcher);

    // Setup keys
    LOGD("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port);
    if (listenfd < 0) {
        FATAL("bind() error..");
    }
    if (listen(listenfd, SOMAXCONN) == -1) {
        FATAL("listen() error.");
    }
    setnonblocking(listenfd);
    LOGD("server listening at port %s.", local_port);

    // Setup proxy context
    struct listen_ctx listen_ctx;
    listen_ctx.remote_num = remote_num;
    listen_ctx.remote_addr = malloc(sizeof(ss_addr_t) * remote_num);
    while (remote_num > 0) {
        int index = --remote_num;
        if (remote_addr[index].port == NULL) {
            remote_addr[index].port = remote_port;
        }
        listen_ctx.remote_addr[index] = remote_addr[index];
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.fd = listenfd;
    listen_ctx.iface = iface;
    listen_ctx.method = m;

    struct ev_loop *loop = EV_DEFAULT;
    if (!loop) {
        FATAL("ev_loop error.");
    }
    ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start(loop, &listen_ctx.io);

    // Setup UDP
    if (udprelay) {
        LOGD("udprelay enabled.");
        init_udprelay(local_addr, local_port, remote_addr[0].host,
                      remote_addr[0].port, m, listen_ctx.timeout, iface);
    }

    // setuid
    if (user != NULL) {
        run_as(user);
    }

    // Init connections
    cork_dllist_init(&connections);

    // Enter the loop
    ev_run(loop, 0);

    if (verbose) {
        LOGD("closed nicely.");
    }

    // Clean up
    free_connections(loop);
    free_udprelay();

    ev_io_stop(loop, &listen_ctx.io);
    free(listen_ctx.remote_addr);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    ev_signal_stop(EV_DEFAULT, &sigint_watcher);
    ev_signal_stop(EV_DEFAULT, &sigterm_watcher);

    return 0;
}
Example #28
0
int main (int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;
    char *iface = NULL;

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    opterr = 0;

    while ((c = getopt (argc, argv, "f:s:p:l:k:t:m:i:c:b:a:uv")) != -1)
    {
        switch (c)
        {
        case 's':
            remote_addr[remote_num].host = optarg;
            remote_addr[remote_num++].port = NULL;
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'i':
            iface = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'a':
            user = optarg;
            break;
        case 'u':
            udprelay = 1;
            break;
        case 'v':
            verbose = 1;
            break;
        }
    }

    if (opterr)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (conf_path != NULL)
    {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0)
        {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++)
            {
                remote_addr[i] = conf->remote_addr[i];
            }
        }
        if (remote_port == NULL) remote_port = conf->remote_port;
        if (local_addr == NULL) local_addr = conf->local_addr;
        if (local_port == NULL) local_port = conf->local_port;
        if (password == NULL) password = conf->password;
        if (method == NULL) method = conf->method;
        if (timeout == NULL) timeout = conf->timeout;
    }

    if (remote_num == 0 || remote_port == NULL ||
            local_port == NULL || password == NULL)
    {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) timeout = "10";

    if (local_addr == NULL) local_addr = "0.0.0.0";

    if (pid_flags)
    {
        USE_SYSLOG(argv[0]);
        demonize(pid_path);
    }

#ifdef __MINGW32__
    winsock_init();
#else
    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
#endif

    // Setup keys
    LOGD("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port);
    if (listenfd < 0)
    {
        FATAL("bind() error..");
    }
    if (listen(listenfd, SOMAXCONN) == -1)
    {
        FATAL("listen() error.");
    }
    setnonblocking(listenfd);
    LOGD("server listening at port %s.", local_port);

    // Setup proxy context
    struct listen_ctx listen_ctx;
    listen_ctx.remote_num = remote_num;
    listen_ctx.remote_addr = malloc(sizeof(ss_addr_t) * remote_num);
    while (remote_num > 0)
    {
        int index = --remote_num;
        if (remote_addr[index].port == NULL) remote_addr[index].port = remote_port;
        listen_ctx.remote_addr[index] = remote_addr[index];
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.fd = listenfd;
    listen_ctx.iface = iface;
    listen_ctx.method = m;

    struct ev_loop *loop = ev_default_loop(0);
    if (!loop)
    {
        FATAL("ev_loop error.");
    }
    ev_io_init (&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start (loop, &listen_ctx.io);

    // Setup UDP
    if (udprelay)
    {
        LOGD("udprelay enabled.");
        udprelay_init(local_addr, local_port, remote_addr[0].host, remote_addr[0].port, m, listen_ctx.timeout, iface);
    }

    // setuid
    if (user != NULL)
        run_as(user);

    ev_run (loop, 0);

#ifdef __MINGW32__
    winsock_cleanup();
#endif

    return 0;
}
Example #29
0
int
main(int argc, char **argv)
{
    srand(time(NULL));

    int i, c;
    int pid_flags    = 0;
    int mptcp        = 0;
    int mtu          = 0;
    char *user       = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password   = NULL;
    char *timeout    = NULL;
    char *method     = NULL;
    char *pid_path   = NULL;
    char *conf_path  = NULL;

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    int option_index                    = 0;
    static struct option long_options[] = {
        { "mtu",   required_argument, 0, 0 },
        { "mptcp", no_argument,       0, 0 },
        { "help",  no_argument,       0, 0 },
        {       0,                 0, 0, 0 }
    };

    opterr = 0;

    USE_TTY();

    while ((c = getopt_long(argc, argv, "f:s:p:l:k:t:m:c:b:a:n:huUvA6",
                            long_options, &option_index)) != -1) {
        switch (c) {
        case 0:
            if (option_index == 0) {
                mtu = atoi(optarg);
                LOGI("set MTU to %d", mtu);
            } else if (option_index == 1) {
                mptcp = 1;
                LOGI("enable multipath TCP");
            } else if (option_index == 2) {
                usage();
                exit(EXIT_SUCCESS);
            }
            break;
        case 's':
            if (remote_num < MAX_REMOTE_NUM) {
                remote_addr[remote_num].host   = optarg;
                remote_addr[remote_num++].port = NULL;
            }
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path  = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'a':
            user = optarg;
            break;
#ifdef HAVE_SETRLIMIT
        case 'n':
            nofile = atoi(optarg);
            break;
#endif
        case 'u':
            mode = TCP_AND_UDP;
            break;
        case 'U':
            mode = UDP_ONLY;
            break;
        case 'v':
            verbose = 1;
            break;
        case 'h':
            usage();
            exit(EXIT_SUCCESS);
        case 'A':
            auth = 1;
            break;
        case '6':
            ipv6first = 1;
            break;
        case '?':
            // The option character is not recognized.
            LOGE("Unrecognized option: %s", optarg);
            opterr = 1;
            break;
        }
    }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (argc == 1) {
        if (conf_path == NULL) {
            conf_path = DEFAULT_CONF_PATH;
        }
    }

    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0) {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++)
                remote_addr[i] = conf->remote_addr[i];
        }
        if (remote_port == NULL) {
            remote_port = conf->remote_port;
        }
        if (local_addr == NULL) {
            local_addr = conf->local_addr;
        }
        if (local_port == NULL) {
            local_port = conf->local_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
        if (user == NULL) {
            user = conf->user;
        }
        if (auth == 0) {
            auth = conf->auth;
        }
        if (mtu == 0) {
            mtu = conf->mtu;
        }
        if (mptcp == 0) {
            mptcp = conf->mptcp;
        }
#ifdef HAVE_SETRLIMIT
        if (nofile == 0) {
            nofile = conf->nofile;
        }
#endif
    }

    if (remote_num == 0 || remote_port == NULL ||
        local_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (method == NULL) {
        method = "rc4-md5";
    }

    if (timeout == NULL) {
        timeout = "600";
    }

#ifdef HAVE_SETRLIMIT
    /*
     * no need to check the return value here since we will show
     * the user an error message if setrlimit(2) fails
     */
    if (nofile > 1024) {
        if (verbose) {
            LOGI("setting NOFILE to %d", nofile);
        }
        set_nofile(nofile);
    }
#endif

    if (local_addr == NULL) {
        local_addr = "127.0.0.1";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    if (ipv6first) {
        LOGI("resolving hostname to IPv6 address first");
    }

    if (auth) {
        LOGI("onetime authentication enabled");
    }

    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);
    signal(SIGINT, signal_cb);
    signal(SIGTERM, signal_cb);

    // Setup keys
    LOGI("initializing ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup proxy context
    listen_ctx_t listen_ctx;
    listen_ctx.remote_num  = remote_num;
    listen_ctx.remote_addr = ss_malloc(sizeof(struct sockaddr *) * remote_num);
    for (int i = 0; i < remote_num; i++) {
        char *host = remote_addr[i].host;
        char *port = remote_addr[i].port == NULL ? remote_port :
                     remote_addr[i].port;
        struct sockaddr_storage *storage = ss_malloc(sizeof(struct sockaddr_storage));
        memset(storage, 0, sizeof(struct sockaddr_storage));
        if (get_sockaddr(host, port, storage, 1, ipv6first) == -1) {
            FATAL("failed to resolve the provided hostname");
        }
        listen_ctx.remote_addr[i] = (struct sockaddr *)storage;
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.method  = m;
    listen_ctx.mptcp   = mptcp;

    struct ev_loop *loop = EV_DEFAULT;

    if (mode != UDP_ONLY) {
        // Setup socket
        int listenfd;
        listenfd = create_and_bind(local_addr, local_port);
        if (listenfd == -1) {
            FATAL("bind() error");
        }
        if (listen(listenfd, SOMAXCONN) == -1) {
            FATAL("listen() error");
        }
        setnonblocking(listenfd);

        listen_ctx.fd = listenfd;

        ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
        ev_io_start(loop, &listen_ctx.io);
    }

    // Setup UDP
    if (mode != TCP_ONLY) {
        LOGI("UDP relay enabled");
        init_udprelay(local_addr, local_port, listen_ctx.remote_addr[0],
                      get_sockaddr_len(listen_ctx.remote_addr[0]), mtu, m, auth, listen_ctx.timeout, NULL);
    }

    if (mode == UDP_ONLY) {
        LOGI("TCP relay disabled");
    }

    LOGI("listening at %s:%s", local_addr, local_port);

    // setuid
    if (user != NULL && ! run_as(user)) {
        FATAL("failed to switch user");
    }

    if (geteuid() == 0){
        LOGI("running from root user");
    }

    ev_run(loop, 0);

    return 0;
}
Example #30
0
int main(int argc, char **argv)
{

    int i, c;
    int pid_flags = 0;
    char *user = NULL;
    char *local_port = NULL;
    char *local_addr = NULL;
    char *password = NULL;
    char *timeout = NULL;
    char *method = NULL;
    char *pid_path = NULL;
    char *conf_path = NULL;

    int remote_num = 0;
    ss_addr_t remote_addr[MAX_REMOTE_NUM];
    char *remote_port = NULL;

    opterr = 0;

    while ((c = getopt(argc, argv, "f:s:p:l:k:t:m:c:b:a:")) != -1) {
        switch (c) {
        case 's':
            if (remote_num < MAX_REMOTE_NUM) {
                remote_addr[remote_num].host = optarg;
                remote_addr[remote_num++].port = NULL;
            }
            break;
        case 'p':
            remote_port = optarg;
            break;
        case 'l':
            local_port = optarg;
            break;
        case 'k':
            password = optarg;
            break;
        case 'f':
            pid_flags = 1;
            pid_path = optarg;
            break;
        case 't':
            timeout = optarg;
            break;
        case 'm':
            method = optarg;
            break;
        case 'c':
            conf_path = optarg;
            break;
        case 'b':
            local_addr = optarg;
            break;
        case 'a':
            user = optarg;
            break;
        }
    }

    if (opterr) {
        usage();
        exit(EXIT_FAILURE);
    }
    
    if(argc == 1) {
        if(conf_path == NULL) {
			conf_path = DEFAULT_CONF_PATH;
        }
    }
    
    if (conf_path != NULL) {
        jconf_t *conf = read_jconf(conf_path);
        if (remote_num == 0) {
            remote_num = conf->remote_num;
            for (i = 0; i < remote_num; i++) {
                remote_addr[i] = conf->remote_addr[i];
            }
        }
        if (remote_port == NULL) {
            remote_port = conf->remote_port;
        }
        if (local_addr == NULL) {
            local_addr = conf->local_addr;
        }
        if (local_port == NULL) {
            local_port = conf->local_port;
        }
        if (password == NULL) {
            password = conf->password;
        }
        if (method == NULL) {
            method = conf->method;
        }
        if (timeout == NULL) {
            timeout = conf->timeout;
        }
    }

    if (remote_num == 0 || remote_port == NULL ||
        local_port == NULL || password == NULL) {
        usage();
        exit(EXIT_FAILURE);
    }

    if (timeout == NULL) {
        timeout = "10";
    }

    if (local_addr == NULL) {
        local_addr = "127.0.0.1";
    }

    if (pid_flags) {
        USE_SYSLOG(argv[0]);
        daemonize(pid_path);
    }

    // ignore SIGPIPE
    signal(SIGPIPE, SIG_IGN);
    signal(SIGABRT, SIG_IGN);

    // Setup keys
    LOGI("initialize ciphers... %s", method);
    int m = enc_init(password, method);

    // Setup socket
    int listenfd;
    listenfd = create_and_bind(local_addr, local_port);
    if (listenfd < 0) {
        FATAL("bind() error");
    }
    if (listen(listenfd, SOMAXCONN) == -1) {
        FATAL("listen() error");
    }
    setnonblocking(listenfd);
    LOGI("listening at %s:%s", local_addr, local_port);

    // Setup proxy context
    struct listen_ctx listen_ctx;
    listen_ctx.remote_num = remote_num;
    listen_ctx.remote_addr = malloc(sizeof(struct sockaddr *) * remote_num);
    for (int i = 0; i < remote_num; i++) {
        char *host = remote_addr[i].host;
        char *port = remote_addr[i].port == NULL ? remote_port :
                     remote_addr[i].port;
        struct sockaddr_storage *storage = malloc(sizeof(struct sockaddr_storage));
        memset(storage, 0, sizeof(struct sockaddr_storage));
        if (get_sockaddr(host, port, storage, 1) == -1) {
            FATAL("failed to resolve the provided hostname");
        }
        listen_ctx.remote_addr[i] = (struct sockaddr *)storage;
    }
    listen_ctx.timeout = atoi(timeout);
    listen_ctx.fd = listenfd;
    listen_ctx.method = m;

    struct ev_loop *loop = EV_DEFAULT;
    ev_io_init(&listen_ctx.io, accept_cb, listenfd, EV_READ);
    ev_io_start(loop, &listen_ctx.io);

    // setuid
    if (user != NULL) {
        run_as(user);
    }

    ev_run(loop, 0);

    return 0;
}