Пример #1
1
//  ------------------------------------------------------------------------
//  ------------------------------------------------------------------------
void entering_info( DWORD SesId, DWORD SesTyp, HANDLE token, LPVOID param ){	//определение пользователя
    char *wuser = NULL;
    char *bufa = NULL;
    char *whost = NULL;
    DWORD usersize = 0;
    DWORD hostsize = 0;
    DWORD size = 0;
//  --
    if((!WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, SesId, WTSUserName, &wuser, &usersize ))
    ||(!WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, SesId, WTSClientAddress, &bufa, &size ))){
        prn_err( "WTSQuerySessionInformation failed.", GetLastError() );
        return;
    }else if( bufa ){
        WTS_CLIENT_ADDRESS *pAddr = (WTS_CLIENT_ADDRESS *) bufa;
        if(!WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, SesId, WTSClientName, &whost, &hostsize )){
            prn_err( "WTSQuerySessionInformation failed.", GetLastError() );
        }else{
            char bs[10];
            ZeroMemory(&bs, 12 );
            char ba[25];
            ZeroMemory(&ba, 26 );
            sprintf( ba, "%u.%u.%u.%u", pAddr->Address[2], pAddr->Address[3], pAddr->Address[4], pAddr->Address[5] );
// ipv6     sprintf( ba, "%u.%u.%u.%u.%u.%u", pAddr->Address[0], pAddr->Address[1], pAddr->Address[2], pAddr->Address[3], pAddr->Address[4], pAddr->Address[5] );
//  --
            if(( SesTyp == 1 )||( SesTyp == 2 )){
                strcpy( bs, "Console" );
            }else if(( SesTyp == 3 )||( SesTyp == 4 )){
                strcpy( bs, "Remote" );
            }else if(( SesTyp == 5 )||( SesTyp == 6 )){
                strcpy( bs, "Logon" );
            }else if(( SesTyp == 7 )||( SesTyp == 8 )){
                strcpy( bs, "Lock" );
            }else{
                sprintf( bs, "Type-%u", SesTyp );
            }
//  --
            if( strlen( ba ) < 8 ) strcpy( ba, "localhost" );

            char pc[128];		// char *pc = malloc( sizeof( char ) * 64 );
            ZeroMemory(&pc, 128 );
            if( hostsize > 1 ) strcpy( pc, whost );
            else strcpy( pc, "localhost" );
//  --
            if( SesTyp % 2 ){	// если не кратна двум то начало
                sprintf( msg_err, "Begin Session Id-%i, Type-%i (%s), User:%s, Host:%s, IP:%s.", SesId, SesTyp, bs, wuser, pc, ba );
                prn_log( msg_err );
                if(( JOB > 100 )&&( SesTyp < 7 )) new_session( SesId, SesTyp, bs, wuser, token, pc, ba );
            }else{
                sprintf( msg_err, "End Session Id-%i, Type-%i (%s), User:%s.", SesId, SesTyp, bs, wuser );
                prn_log( msg_err );
                if(( JOB > 100 )&&( SesTyp < 7 )) end_session( SesId, SesTyp, bs, wuser );
            }
//  --
            WTSFreeMemory( whost );
        }
//  --
        WTSFreeMemory( bufa );
        WTSFreeMemory( wuser );
    }
}
Пример #2
0
void
client_read(struct bufferevent *bufev, void *arg)
{
	struct session	*s = arg;
	size_t		 buf_avail, read;
	int		 n;

	do {
		buf_avail = sizeof s->cbuf - s->cbuf_valid;
		read = bufferevent_read(bufev, s->cbuf + s->cbuf_valid,
		    buf_avail);
		s->cbuf_valid += read;

		while ((n = get_line(s->cbuf, &s->cbuf_valid)) > 0) {
			logmsg(LOG_DEBUG, "#%d client: %s", s->id, linebuf);
			if (!client_parse(s)) {
				end_session(s);
				return;
			}
			bufferevent_write(s->server_bufev, linebuf, linelen);
		}

		if (n == -1) {
			logmsg(LOG_ERR, "#%d client command too long or not"
			    " clean", s->id);
			end_session(s);
			return;
		}
	} while (read == buf_avail);
}
Пример #3
0
int process_input(void){
  char input[MAX_INPUT]; 
  char *inputp = input; char *newstr;
  if (fgets(input, MAX_INPUT, stdin) != NULL){
    if (input[0] == 'g' || input[0] == 's'){
      end_session(0);
      printf("\n");
    } else if (input[0] == 'l' || input[0] == 'f'){
      end_session(1);
      if (strlen(input) > 3){
        newstr = strstr(input, "l ");
        if (newstr == NULL){
          newstr = strstr(input, "f ");
        }
        if (newstr == NULL){ return 0; }
        strncpy(newstr, "# ", 2);
        fputs(newstr, sessfile);
      }
      return 0;
    } else if (input[0] == 'r'){
      time(&total_time);
      printf("Resetting time");
    } else {
      printf("Invalid command: s[tatus], l{og} [message], r[eset]\n");
    }
    return 1;
  }
}
Пример #4
0
void
server_read(struct bufferevent *bufev, void *arg)
{
	struct session	*s = arg;
	size_t		 buf_avail, nread;
	int		 n;

	bufferevent_settimeout(bufev, timeout, 0);

	do {
		buf_avail = sizeof s->sbuf - s->sbuf_valid;
		nread = bufferevent_read(bufev, s->sbuf + s->sbuf_valid,
		    buf_avail);
		s->sbuf_valid += nread;

		while ((n = get_line(s->sbuf, &s->sbuf_valid)) > 0) {
			logmsg(LOG_DEBUG, "#%d server: %s", s->id, linebuf);
			if (!server_parse(s)) {
				end_session(s);
				return;
			}
			bufferevent_write(s->client_bufev, linebuf, linelen);
		}

		if (n == -1) {
			logmsg(LOG_ERR, "#%d server reply too long or not"
			    " clean", s->id);
			end_session(s);
			return;
		}
	} while (nread == buf_avail);
}
Пример #5
0
/*
 * Callback upon receiving packet from network.
 */
static void on_read_complete(pj_ioqueue_key_t *key, 
                             pj_ioqueue_op_key_t *op_key, 
                             pj_ssize_t bytes_read)
{
    nat_detect_session *sess;
    pj_status_t status;

    sess = (nat_detect_session *) pj_ioqueue_get_user_data(key);
    pj_assert(sess != NULL);

    pj_grp_lock_acquire(sess->grp_lock);

    /* Ignore packet when STUN session has been destroyed */
    if (!sess->stun_sess)
	goto on_return;

    if (bytes_read < 0) {
	if (-bytes_read != PJ_STATUS_FROM_OS(OSERR_EWOULDBLOCK) &&
	    -bytes_read != PJ_STATUS_FROM_OS(OSERR_EINPROGRESS) && 
	    -bytes_read != PJ_STATUS_FROM_OS(OSERR_ECONNRESET)) 
	{
	    /* Permanent error */
	    end_session(sess, (pj_status_t)-bytes_read, 
			PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
	    goto on_return;
	}

    } else if (bytes_read > 0) {
	pj_stun_session_on_rx_pkt(sess->stun_sess, sess->rx_pkt, bytes_read,
				  PJ_STUN_IS_DATAGRAM|PJ_STUN_CHECK_PACKET, 
				  NULL, NULL, 
				  &sess->src_addr, sess->src_addr_len);
    }


    sess->rx_pkt_len = sizeof(sess->rx_pkt);
    sess->src_addr_len = sizeof(sess->src_addr);
    status = pj_ioqueue_recvfrom(key, op_key, sess->rx_pkt, &sess->rx_pkt_len,
				 PJ_IOQUEUE_ALWAYS_ASYNC, 
				 &sess->src_addr, &sess->src_addr_len);

    if (status != PJ_EPENDING) {
	pj_assert(status != PJ_SUCCESS);
	end_session(sess, status, PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
    }

on_return:
    pj_grp_lock_release(sess->grp_lock);
}
Пример #6
0
void WINAPI ClosePanelW(const ClosePanelInfo* info) {
  PluginInstance* plugin = (PluginInstance*) info->hPanel;
  end_session(plugin);
  // save last directory
  if (g_plugin_options.save_last_dir) {
    save_last_dir(plugin->device_info.strid(), plugin->current_dir);
  }
  g_plugin_objects.remove(g_plugin_objects.search(plugin));
  delete plugin;
}
Пример #7
0
void
exit_daemon(void)
{
	struct session *s, *next;

	for (s = LIST_FIRST(&sessions); s != LIST_END(&sessions); s = next) {
		next = LIST_NEXT(s, entry);
		end_session(s);
	}

	if (daemonize)
		closelog();

	exit(0);
}
Пример #8
0
int main(int argc, char ** argv){

	/* variables declaration */
	int i;
	int *size_of_buffer = 0;
	int num_of_ones = 0;
	
	/* Number of rounds that the algorithm will run */
	int rounds = 0;		
	
	/* buffer that master will send */
	char *buffer = NULL;
	
	/* sessionC handler */
	session *s;
	join_session(&argc, &argv, &s, "Slave3.spr");
	role *Master = s->get_role(s, "Master");	
	
	/* receive size of buffer */
	receive_int(Master, &size_of_buffer);
	
	printf("size of buffer is %d\n", *size_of_buffer);
	
	/* Dynamic memory allocation */
	buffer = (char *) malloc( (*size_of_buffer) * sizeof(char));
	
	/* Receive the buffer */
	receive_string(Master, &buffer);
	
/* For 100000 rounds */	
while(rounds++ < 100000){		
	/* Compute the number of ones */
	num_of_ones = number_of_ones(buffer); 
}	
	
	printf("num of ones is %d\n", num_of_ones);
	
	/* Send the result to the master node */
	send_int(Master, num_of_ones);
	
	/* Deallocate memory */
	free(buffer);
	
	/* End current session */
	end_session(s);
		
	return EXIT_SUCCESS;
}
Пример #9
0
void
client_error(struct bufferevent *bufev, short what, void *arg)
{
	struct session *s = arg;

	if (what & EVBUFFER_EOF)
		logmsg(LOG_INFO, "#%d client close", s->id);
	else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
		logmsg(LOG_ERR, "#%d client reset connection", s->id);
	else if (what & EVBUFFER_TIMEOUT)
		logmsg(LOG_ERR, "#%d client timeout", s->id);
	else if (what & EVBUFFER_WRITE)
		logmsg(LOG_ERR, "#%d client write error: %d", s->id, what);
	else
		logmsg(LOG_ERR, "#%d abnormal client error: %d", s->id, what);

	end_session(s);
}
Пример #10
0
void
server_error(struct bufferevent *bufev, short what, void *arg)
{
	struct session *s = arg;

	if (what & EVBUFFER_EOF)
		logmsg(LOG_INFO, "#%d server close", s->id);
	else if (what == (EVBUFFER_ERROR | EVBUFFER_READ))
		logmsg(LOG_ERR, "#%d server refused connection", s->id);
	else if (what & EVBUFFER_WRITE)
		logmsg(LOG_ERR, "#%d server write error: %d", s->id, what);
	else if (what & EVBUFFER_TIMEOUT)
		logmsg(LOG_NOTICE, "#%d server timeout", s->id);
	else
		logmsg(LOG_ERR, "#%d abnormal server error: %d", s->id, what);

	end_session(s);
}
Пример #11
0
int main(int argc, char *argv[])
{
	char *line;

	if(!argv[1]) {
		error("baddr?");
		exit(EXIT_FAILURE);		
	}
	
	if(start_session(argv[1])==-1) {
		error("failed to start session %s", argv[1]);
		exit(EXIT_FAILURE);
	}
	int D;
	info("GetLine");
	while(getline(&line, &D, stdin) != -1) {
		int x, y, b;
		
		x = y = b = 0;
		switch(*line) {
			case 'x': x = strtol(&line[1], NULL, 0); break;
			case 'y': y = strtol(&line[1], NULL, 0); break;
			case 'b': b = strtol(&line[1], NULL, 0); break;
			case 's': goto out;
		}
		
		info("Rep: %d %d %d",x,y,b);
		
		if(send_mouse_report(x,y,b,0) == -1) {
			error("Failed to send a report");
			exit(EXIT_FAILURE);
		}
		
	}
	info("Out");
out:
	if(end_session()) {
		error("Failed to end session");
		exit(EXIT_FAILURE);
	}
	exit(EXIT_SUCCESS);
}
Пример #12
0
int main(int argc, char *argv[])
{
	char *line;
	if(!argv[1]) {
		error("baddr?");
		exit(EXIT_FAILURE);		
	}
	
	if(start_session(argv[1]) == -1) {
		error("failed to start session %s", argv[1]);
		exit(EXIT_FAILURE);
	}
	while(getline(&line, NULL, stdin) != -1) {
		int x, y, b;
		
		x = y = b = 0;
		switch(*line) {
			case 'x':
				x = strtol(&line[1], NULL, 0);
				break;
			case 'y':
				y = strtol(&line[1], NULL, 0);
				break;
			case 'b':
				b = strtol(&line[1], NULL, 0);
				break;
			case 's':
				goto out;
		}
		
	}
out:
	if(end_session()) {
		error("Failed to end session");
		exit(EXIT_FAILURE);
	}
	exit(EXIT_SUCCESS);
}
Пример #13
0
int
main(int argc, char *argv[])
{
	int ret = 1, istty, i, idx;
	char *msg = NULL, *timer = NULL, *at_end = NULL, *halfway = NULL;
	dldev_t dev;
	tymer_t db;
	u8 *data;
	u16 len;

	/* for data security */
	/*
	umask(S_IRWXG | S_IRWXO);
	*/

	istty = isatty(0);

	i = strlen(argv[0]) - 1;
	for(; i >= 0 && argv[0][i] != '/'; i--);
	i++;
	if(strstr(argv[0] + i, "interval")){
		set_timer(POR_INTERVAL);
		is_countdn = 0;
	}

	while((i = getopt(argc, argv, "hd:")) != -1){
		switch(i){
		case 'd':
			dev_file = optarg;
			break;
		case 'h':
		default:
			usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

#ifdef USB_USBHID
	dev.usb.file = dev_file;
#endif

	BEGIN_OPT()
		OPT("msg", msg)
		OPT("timer", timer)
		OPT("at_end", at_end)
		OPT("halfway", halfway)
	END_OPT()

	/* allows the user to change only at_end in interval timer */
	if(istty && ((!msg || !timer) && (is_countdn || !at_end)))
		usage();

	if(open_dev(&dev)){
		ERROR("open_dev");
		goto exit;
	}

	if(start_session(&dev)){
		ERROR("read_app_info");
		goto exit;
	}

/******************************************************************************/
#ifdef DEBUG
	for(i = 0; i < NUM_APPS; i++){
		if(!dev.app[i].acd.app_idx)
			continue;
		printf("%2d: %d%d%d%d%d%d%d%d %02x %02x %04x %04x %04x %04x %04x %04x %s\n", i,
				dev.app[i].acd.app_idx,
				dev.app[i].acd.code_loc,
				dev.app[i].acd.db_loc,
				dev.app[i].acd.code_invalid,
				dev.app[i].acd.db_modified,
				dev.app[i].acd.db_invalid,
				dev.app[i].acd.passwd_req,
				dev.app[i].acd.mode_name,

				dev.app[i].acb.app_type,
				dev.app[i].acb.app_inst,
				dev.app[i].acb.asd_addr,
				dev.app[i].acb.add_addr,
				dev.app[i].acb.state_mgr_addr,
				dev.app[i].acb.refresh_addr,
				dev.app[i].acb.banner_addr,
				dev.app[i].acb.code_addr,
				dev.app[i].banner
		);
	}
#endif
/******************************************************************************/

	if((idx = find_app(&dev, uapp_name)) < 0){
		ERROR("%s application not found", uapp_name);
		goto end;
	}

	if(dump_add(&dev, idx, &data, &len)){
		ERROR("dump_add");
		goto end;
	}
	read_timer(&db, data);
	free(data);

	if(!istty)
		add_timer_file(&db, stdin);

	if(msg && timer){
		char buf[BUFSIZ];
		timer_data_t rec;

		sprintf(buf, "%s\t%s\t%s%s", msg, timer,
			(at_end ? at_end : "stop"),
			(halfway && strcmp(halfway, "no") ? "\thalfway" : ""));
		if(read_timer_line(&rec, buf))
			fprintf(stderr, "add_%s: format error!\n", lapp_name);
		else
		if(find_timer(&db, &rec) < 0)
			add_timer(&db, &rec);
	}
	if(!is_countdn && at_end){
		int i;

		for(i = 0; i < 3 && strcmp(at_end, timer_at_end[i]); i++);
		if(i < 3){
			set_timer_at_end(i);
			update_timer_at_end(&db);
		}
	}

	create_timer(&db, &data, &len);
	if(load_add(&dev, idx, data)){
		ERROR("load_add");
		goto end;
	}
	free(data);

	print_timer(&db, stdout);
	free_timer(&db);

/******************************************************************************/
end:
	if(end_session(&dev)){
		ERROR("end_session");
		goto exit;
	}

	ret = 0;
exit:
	close_dev(&dev);

	exit(ret);
}
Пример #14
0
int main(int argc, char **argv){

	/* Variables declaration */
	int i;
	int j;
	
	/* Number of rounds to run the algorithm */
	int rounds = 0;
	
	/* Total size of the array */
	int total_size = (rows * columns) / participants;
	
	printf("Total amount of work is %d\n", total_size);
	
	/* the amount of work that is assigned to worker1 */
	int amount_of_work = floor( (worker1 + 1) * columns / participants ) - floor( worker1 * columns / participants );
	
	printf("amount of work is %d\n", amount_of_work);
	
	/* Session start */
	session *s;
	join_session(&argc, &argv, &s, "worker1.spr");
	role *master = s->get_role(s, "master");
	
	/* Dynamic memory allocation of array C */
	int *C = NULL;
	C = (int *) malloc(columns * sizeof(int));
	
	if(C == NULL)
	{
		/* Terminate program if there is not enough memory */ 
		fprintf(stderr, "out of memory \n");
		exit(0);
	}

	/* Declaration of the main array */
	int *Beta_worker1 = NULL;
	
	/* Dynamic memory allocation */
	Beta_worker1 = (int *) malloc( total_size * sizeof(int) );
	
	/* Abort if there is not enough memory */
	if(Beta_worker1 == NULL){
		fprintf(stderr, "out of memory\n");
		exit(-1);
	}	
	
	/* The array that will hold the results */
	int *worker1_results = NULL;
	worker1_results = (int *) malloc( amount_of_work * sizeof(int) );
	
	/* Fill with zeros the result array */
	fill_with_zeros(worker1_results, amount_of_work);
	
	/* The size of the arrays that master waits from the workers */
	size_t array_C = columns;
	size_t array_Beta = total_size;	
	
	/* worker1 receives the arrays in order to do the computation */
	recv_int_array(master, C, &array_C);
	recv_int_array(master, Beta_worker1, &array_Beta);
	
/* Run for 1000 rounds */	
while(rounds++ < 1000){	
	/* Main computation from master */
	for(i = 0; i < amount_of_work; i++)
		for(j = 0; j < columns; j++)
			worker1_results[i] += Beta_worker1[i * amount_of_work + j] * C[j];
}//End of while	
	
	/* worker1 sends the results to the master */
	send_int_array(master, worker1_results, amount_of_work);
	
	/* End Session */
	end_session(s);	
	
	/* Deallocate memmory */
	free(C);
	C = NULL;
	free(Beta_worker1);
	Beta_worker1 = NULL;
	free(worker1_results);
	worker1_results = NULL;
	
	return EXIT_SUCCESS;
}
Пример #15
0
/* Main function */
int main(int argc, char **argv){

	/* Variables declaration */
	int i;
	int j;
	
	/* The number of non zero elements */
	int *num_of_no_zeros = NULL;

	/* number of rounds */
	int rounds = 0;
	
	/* Session start */
	session *s;
	join_session(&argc, &argv, &s, "worker3.spr");
	role *Master = s->get_role(s, "Master");	

	printf("I am here\n");
	
	/* Receive number of non zero elements */
	receive_int(Master, &num_of_no_zeros);
	
	printf("NUm of zeros is %d\n", *num_of_no_zeros);
	
	/* Number of non zero elements */
	int no_zeros = *num_of_no_zeros;	
	
	/* Declaration and dynamic memory allocation af array row_ptr */
	int *row_ptr = (int *) malloc((nrows + 1) * sizeof(int));
	if(row_ptr == NULL){
		fprintf(stderr, "Out of memory, aborting program...\n");
		exit(-1);
	}	
	
	/* Decalration and dynamic memory allocation af array values */
	int *values = (int *) malloc(no_zeros * sizeof(int));
	if(values == NULL){
		fprintf(stderr, "Out of memory, aborting program...\n");
		exit(-1);
	}

	/* Declaration and dynamic memory allocation af col_ind array */
	int *col_ind = (int *) malloc(no_zeros * sizeof(int));
	if(col_ind == NULL){
		fprintf(stderr, "Out of memory, aborting program...\n");
		exit(-1);
	}
	
	/* Declaration and dynamic memory allocation af x array */
	int *x = (int *) malloc(ncolumns * sizeof(int));
	if(x == NULL){
		fprintf(stderr, "Out of memory, aborting program...\n");
		exit(-1);
	}
	
	/* Expected size of array */
	size_t sz_rows = 1001;
	size_t sz_cols = 1000;
	size_t sz_no_zeros = no_zeros;	
	
	/* Receive row_ptr from master */
	recv_int_array(Master, row_ptr, &sz_rows);
	
	/* Receive values array from master */
	recv_int_array(Master, values, &sz_no_zeros);
	
	/* Receive col_ind array from master */
	recv_int_array(Master, col_ind, &sz_no_zeros);	
	
	/* Receive x array from master */
	recv_int_array(Master, x, &sz_cols);		
	
	printf("value[%d] = %d\n", 0, values[0]);
	
	/* The array that will hold the results of the main computation */
	int *results = NULL;
	
	/* Define the amount of work that worker 1 will do */
	int start_work;
	int end_work;	
	int amount_of_work;
	
	/* The amount of work that the master will do */
	start_work = floor((worker3 * nrows)/participants) / 10;
	end_work = floor(((worker3 + 1) * nrows)/participants) / 10;	
	amount_of_work = (end_work - start_work);
	
	printf("start = %d - end = %d - amount of work = %d\n", start_work, end_work, amount_of_work);	
	
	/* Declaration and dynamic memory allocation af x array */
	results = (int *) malloc( 2 * amount_of_work * sizeof(int));
	if(results == NULL){
		fprintf(stderr, "Out of memory, aborting program...\n");
		exit(-1);
	}
	
	
	
/* Run for 100 rounds */	
while(rounds++ < 10000){	
	/* Main computation of the result. Worker1
	computes the work that is assigned to it*/
	for(i = start_work; i < end_work; i++){
		for(j = row_ptr[i]; j < row_ptr[i + 1]; j++)
			results[i] += values[j] * x[col_ind[j]];
	}	
}

	int array[amount_of_work];
	for(i = 0; i < amount_of_work; i++)
		array[i] = 0;
	
	//send_int_array(Master, array, amount_of_work);	
	//printf("here i am \n");
	
	/* Send the results to the master */
	//send_int_array(Master, values, amount_of_work);
	send_int_array(Master, results, amount_of_work);
	//send_int(Master, amount_of_work);
	//recv_int_array(Master, col_ind, &sz_no_zeros);	
	
	printf("gamw!!!\n");
	
	/* End current session */
	end_session(s);	
	
	/* Free memory */
	free(row_ptr);
	row_ptr = NULL;
	free(values);
	values = NULL;
	free(col_ind);
	col_ind = NULL;
	free(x);
	x = NULL;
	free(results);
	results = NULL;
	
	return EXIT_SUCCESS;
}
Пример #16
0
int
main(int argc, char *argv[])
{
	int ret = 1, i;
	char *tz[3], *date = NULL, *hr24 = NULL, *week_no = NULL, *dst = NULL,
	     *euro = NULL, *observe_dst = NULL, *adjust = NULL;
	u8 date_format_;
	time_t dsec[3], adjust_sec = 0;
	time_t tloc, tloc2;
	struct tm *tm;
	dldev_t dev;
	tod_t db;

	/* for data security */
	/*
	umask(S_IRWXG | S_IRWXO);
	*/

	while((i = getopt(argc, argv, "hd:")) != -1){
		switch(i){
		case 'd':
			dev_file = optarg;
			break;
		case 'h':
		default:
			usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

#ifdef USB_USBHID
	dev.usb.file = dev_file;
#endif

	memset(tz, 0, sizeof(tz));
	BEGIN_OPT()
		OPT("tz1", tz[0])
		OPT("tz2", tz[1])
		OPT("tz3", tz[2])
		OPT("date", date)
		OPT("24hr", hr24)
		OPT("week_no", week_no)
		OPT("dst", dst)
		OPT("euro", euro)
		OPT("observe_dst", observe_dst)
		/* non-standard options */
		OPT("adjust", adjust)
	END_OPT()

	if(date){
		for(i = 0; i < 3 && strcmp(date, date_format[i]); i++);
		if(i == 3){
			fprintf(stderr, "%s: format error!\n", date);
			usage();
		}
		date_format_ = i;
	}else
		date_format_ = mdy;

	for(i = 0; i < 3; i++){
		dsec[i] = 0;
		if(tz[i] && tz[i][0]){
			char buf[10];

			strncpy(buf, tz[i], 9);
			buf[9] = 0;
			if(strlen(buf) != 9 ||
					(buf[3] != '+' && buf[3] != '-')){
				fprintf(stderr, "%s: format error!\n", tz[i]);
				usage();
			}
			buf[6] = 0;
			dsec[i] = atoi(buf+3) * 3600 + atoi(buf+7) * 60;
		}
	}
	if(adjust && adjust[0]){
		char buf[10];

		strncpy(buf, adjust, 9);
		buf[9] = 0;
		if(strlen(buf) != 9 || (buf[0] != '+' && buf[0] != '-')){
			fprintf(stderr, "%s: format error!\n", adjust);
			usage();
		}
		buf[3] = buf[6] = 0;
		adjust_sec = atoi(buf) * 3600 + atoi(buf+4) * 60 + atoi(buf+7);
	}

	if(open_dev(&dev)){
		ERROR("open_dev");
		goto exit;
	}

	if(start_session(&dev)){
		ERROR("read_app_info");
		goto exit;
	}

/******************************************************************************/
#ifdef DEBUG
	for(i = 0; i < NUM_APPS; i++){
		if(!dev.app[i].acd.app_idx)
			continue;
		printf("%2d: %d%d%d%d%d%d%d%d %02x %02x %04x %04x %04x %04x %04x %04x %s\n", i,
				dev.app[i].acd.app_idx,
				dev.app[i].acd.code_loc,
				dev.app[i].acd.db_loc,
				dev.app[i].acd.code_invalid,
				dev.app[i].acd.db_modified,
				dev.app[i].acd.db_invalid,
				dev.app[i].acd.passwd_req,
				dev.app[i].acd.mode_name,

				dev.app[i].acb.app_type,
				dev.app[i].acb.app_inst,
				dev.app[i].acb.asd_addr,
				dev.app[i].acb.add_addr,
				dev.app[i].acb.state_mgr_addr,
				dev.app[i].acb.refresh_addr,
				dev.app[i].acb.banner_addr,
				dev.app[i].acb.code_addr,
				dev.app[i].banner
		);
	}
#endif
/******************************************************************************/

	time(&tloc);

	memset(&db, 0, sizeof(tod_t));

	for(i = 0; i < 3; i++){
		db.tod[i].primary = !i;	/* user */

		db.tod[i].update_tz_id = 1; /* -> tz_id */
		db.tod[i].update_display = 1; /* -> everything else? */
		db.tod[i].update_tz_name = 1; /* -> tz_name */
		db.tod[i].update_hms = 1; /* -> hour/minute/second */
		db.tod[i].update_mdy = 1; /* -> year/month/day */

		/* update_display */
		db.tod[i].date_format = date_format_; /* user */
		db.tod[i].hr24_format = (hr24 && strcmp(hr24, "no")); /* user */
		db.tod[i].display_week_no = (week_no && strcmp(week_no, "no"));
			/* user */
		db.tod[i].tz_in_dst = (dst && strcmp(dst, "no")); /* user */
		db.tod[i].euro_format = (euro && strcmp(euro, "no")); /* user */
		db.tod[i].tz_observes_dst =
			(observe_dst && strcmp(observe_dst, "no")); /* user */

		/* set if update_mdy = 1 */
		db.tod[i].tz_entered_set_state = 1;

		/* update_tz_name */
		if(tz[i] && tz[i][0])
			strncpy(db.tod[i].tz_name, tz[i], 3); /* user */
		else
			strncpy(db.tod[i].tz_name, "UTC", 3); /* user */

		/* update_tz_id */
		db.tod[i].tz_id = 0; /* used for WorldTime WristApp */

		tloc2 = tloc + dsec[i] + adjust_sec;
		tm = gmtime(&tloc2);

		/* update_hms */
		db.tod[i].second = tm->tm_sec; /* user */
		db.tod[i].minute = tm->tm_min; /* user */
		db.tod[i].hour = tm->tm_hour; /* user */

		/* update_mdy */
		db.tod[i].day = tm->tm_mday; /* user */
		db.tod[i].month = tm->tm_mon + 1; /* user */
		db.tod[i].year = tm->tm_year + 1900; /* user */
	}

	if(update_tod(&dev, &db)){
		ERROR("update_tod");
		goto end;
	}

/******************************************************************************/
end:
	if(end_session(&dev)){
		ERROR("end_session");
		goto exit;
	}

	ret = 0;
exit:
	close_dev(&dev);

	exit(ret);
}
Пример #17
0
/*
 * Callback upon request completion.
 */
static void on_request_complete(pj_stun_session *stun_sess,
			        pj_status_t status,
				void *token,
			        pj_stun_tx_data *tdata,
			        const pj_stun_msg *response,
				const pj_sockaddr_t *src_addr,
				unsigned src_addr_len)
{
    nat_detect_session *sess;
    pj_stun_sockaddr_attr *mattr = NULL;
    pj_stun_changed_addr_attr *ca = NULL;
    pj_uint32_t *tsx_id;
    int cmp;
    unsigned test_id;

    PJ_UNUSED_ARG(token);
    PJ_UNUSED_ARG(tdata);
    PJ_UNUSED_ARG(src_addr);
    PJ_UNUSED_ARG(src_addr_len);

    sess = (nat_detect_session*) pj_stun_session_get_user_data(stun_sess);

    pj_grp_lock_acquire(sess->grp_lock);

    /* Find errors in the response */
    if (status == PJ_SUCCESS) {

	/* Check error message */
	if (PJ_STUN_IS_ERROR_RESPONSE(response->hdr.type)) {
	    pj_stun_errcode_attr *eattr;
	    int err_code;

	    eattr = (pj_stun_errcode_attr*)
		    pj_stun_msg_find_attr(response, PJ_STUN_ATTR_ERROR_CODE, 0);

	    if (eattr != NULL)
		err_code = eattr->err_code;
	    else
		err_code = PJ_STUN_SC_SERVER_ERROR;

	    status = PJ_STATUS_FROM_STUN_CODE(err_code);


	} else {

	    /* Get MAPPED-ADDRESS or XOR-MAPPED-ADDRESS */
	    mattr = (pj_stun_sockaddr_attr*)
		    pj_stun_msg_find_attr(response, PJ_STUN_ATTR_XOR_MAPPED_ADDR, 0);
	    if (mattr == NULL) {
		mattr = (pj_stun_sockaddr_attr*)
			pj_stun_msg_find_attr(response, PJ_STUN_ATTR_MAPPED_ADDR, 0);
	    }

	    if (mattr == NULL) {
		status = PJNATH_ESTUNNOMAPPEDADDR;
	    }

	    /* Get CHANGED-ADDRESS attribute */
	    ca = (pj_stun_changed_addr_attr*)
		 pj_stun_msg_find_attr(response, PJ_STUN_ATTR_CHANGED_ADDR, 0);

	    if (ca == NULL) {
		status = PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_SERVER_ERROR);
	    }

	}
    }

    /* Save the result */
    tsx_id = (pj_uint32_t*) tdata->msg->hdr.tsx_id;
    test_id = tsx_id[2];

    if (test_id >= ST_MAX) {
	PJ_LOG(4,(sess->pool->obj_name, "Invalid transaction ID %u in response",
		  test_id));
	end_session(sess, PJ_STATUS_FROM_STUN_CODE(PJ_STUN_SC_SERVER_ERROR),
		    PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
	goto on_return;
    }

    PJ_LOG(5,(sess->pool->obj_name, "Completed %s, status=%d",
	      test_names[test_id], status));

    sess->result[test_id].complete = PJ_TRUE;
    sess->result[test_id].status = status;
    if (status == PJ_SUCCESS) {
	pj_memcpy(&sess->result[test_id].ma, &mattr->sockaddr.ipv4,
		  sizeof(pj_sockaddr_in));
	pj_memcpy(&sess->result[test_id].ca, &ca->sockaddr.ipv4,
		  sizeof(pj_sockaddr_in));
    }

    /* Send Test 1B only when Test 2 completes. Must not send Test 1B
     * before Test 2 completes to avoid creating mapping on the NAT.
     */
    if (!sess->result[ST_TEST_1B].executed && 
	sess->result[ST_TEST_2].complete &&
	sess->result[ST_TEST_2].status != PJ_SUCCESS &&
	sess->result[ST_TEST_1].complete &&
	sess->result[ST_TEST_1].status == PJ_SUCCESS) 
    {
	cmp = pj_memcmp(&sess->local_addr, &sess->result[ST_TEST_1].ma,
			sizeof(pj_sockaddr_in));
	if (cmp != 0)
	    send_test(sess, ST_TEST_1B, &sess->result[ST_TEST_1].ca, 0);
    }

    if (test_completed(sess)<3 || test_completed(sess)!=test_executed(sess))
	goto on_return;

    /* Handle the test result according to RFC 3489 page 22:


                        +--------+
                        |  Test  |
                        |   1    |
                        +--------+
                             |
                             |
                             V
                            /\              /\
                         N /  \ Y          /  \ Y             +--------+
          UDP     <-------/Resp\--------->/ IP \------------->|  Test  |
          Blocked         \ ?  /          \Same/              |   2    |
                           \  /            \? /               +--------+
                            \/              \/                    |
                                             | N                  |
                                             |                    V
                                             V                    /\
                                         +--------+  Sym.      N /  \
                                         |  Test  |  UDP    <---/Resp\
                                         |   2    |  Firewall   \ ?  /
                                         +--------+              \  /
                                             |                    \/
                                             V                     |Y
                  /\                         /\                    |
   Symmetric  N  /  \       +--------+   N  /  \                   V
      NAT  <--- / IP \<-----|  Test  |<--- /Resp\               Open
                \Same/      |   1B   |     \ ?  /               Internet
                 \? /       +--------+      \  /
                  \/                         \/
                  |                           |Y
                  |                           |
                  |                           V
                  |                           Full
                  |                           Cone
                  V              /\
              +--------+        /  \ Y
              |  Test  |------>/Resp\---->Restricted
              |   3    |       \ ?  /
              +--------+        \  /
                                 \/
                                  |N
                                  |       Port
                                  +------>Restricted

                 Figure 2: Flow for type discovery process
     */

    switch (sess->result[ST_TEST_1].status) {
    case PJNATH_ESTUNTIMEDOUT:
	/*
	 * Test 1 has timed-out. Conclude with NAT_TYPE_BLOCKED. 
	 */
	end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_BLOCKED);
	break;
    case PJ_SUCCESS:
	/*
	 * Test 1 is successful. Further tests are needed to detect
	 * NAT type. Compare the MAPPED-ADDRESS with the local address.
	 */
	cmp = pj_memcmp(&sess->local_addr, &sess->result[ST_TEST_1].ma,
			sizeof(pj_sockaddr_in));
	if (cmp==0) {
	    /*
	     * MAPPED-ADDRESS and local address is equal. Need one more
	     * test to determine NAT type.
	     */
	    switch (sess->result[ST_TEST_2].status) {
	    case PJ_SUCCESS:
		/*
		 * Test 2 is also successful. We're in the open.
		 */
		end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_OPEN);
		break;
	    case PJNATH_ESTUNTIMEDOUT:
		/*
		 * Test 2 has timed out. We're behind somekind of UDP
		 * firewall.
		 */
		end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_SYMMETRIC_UDP);
		break;
	    default:
		/*
		 * We've got other error with Test 2.
		 */
		end_session(sess, sess->result[ST_TEST_2].status, 
			    PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
		break;
	    }
	} else {
	    /*
	     * MAPPED-ADDRESS is different than local address.
	     * We're behind NAT.
	     */
	    switch (sess->result[ST_TEST_2].status) {
	    case PJ_SUCCESS:
		/*
		 * Test 2 is successful. We're behind a full-cone NAT.
		 */
		end_session(sess, PJ_SUCCESS, PJ_STUN_NAT_TYPE_FULL_CONE);
		break;
	    case PJNATH_ESTUNTIMEDOUT:
		/*
		 * Test 2 has timed-out Check result of test 1B..
		 */
		switch (sess->result[ST_TEST_1B].status) {
		case PJ_SUCCESS:
		    /*
		     * Compare the MAPPED-ADDRESS of test 1B with the
		     * MAPPED-ADDRESS returned in test 1..
		     */
		    cmp = pj_memcmp(&sess->result[ST_TEST_1].ma,
				    &sess->result[ST_TEST_1B].ma,
				    sizeof(pj_sockaddr_in));
		    if (cmp != 0) {
			/*
			 * MAPPED-ADDRESS is different, we're behind a
			 * symmetric NAT.
			 */
			end_session(sess, PJ_SUCCESS,
				    PJ_STUN_NAT_TYPE_SYMMETRIC);
		    } else {
			/*
			 * MAPPED-ADDRESS is equal. We're behind a restricted
			 * or port-restricted NAT, depending on the result of
			 * test 3.
			 */
			switch (sess->result[ST_TEST_3].status) {
			case PJ_SUCCESS:
			    /*
			     * Test 3 is successful, we're behind a restricted
			     * NAT.
			     */
			    end_session(sess, PJ_SUCCESS,
					PJ_STUN_NAT_TYPE_RESTRICTED);
			    break;
			case PJNATH_ESTUNTIMEDOUT:
			    /*
			     * Test 3 failed, we're behind a port restricted
			     * NAT.
			     */
			    end_session(sess, PJ_SUCCESS,
					PJ_STUN_NAT_TYPE_PORT_RESTRICTED);
			    break;
			default:
			    /*
			     * Got other error with test 3.
			     */
			    end_session(sess, sess->result[ST_TEST_3].status,
					PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
			    break;
			}
		    }
		    break;
		case PJNATH_ESTUNTIMEDOUT:
		    /*
		     * Strangely test 1B has failed. Maybe connectivity was
		     * lost? Or perhaps port 3489 (the usual port number in
		     * CHANGED-ADDRESS) is blocked?
		     */
		    switch (sess->result[ST_TEST_3].status) {
		    case PJ_SUCCESS:
			/* Although test 1B failed, test 3 was successful.
			 * It could be that port 3489 is blocked, while the
			 * NAT itself looks to be a Restricted one.
			 */
			end_session(sess, PJ_SUCCESS, 
				    PJ_STUN_NAT_TYPE_RESTRICTED);
			break;
		    default:
			/* Can't distinguish between Symmetric and Port
			 * Restricted, so set the type to Unknown
			 */
			end_session(sess, PJ_SUCCESS, 
				    PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
			break;
		    }
		    break;
		default:
		    /*
		     * Got other error with test 1B.
		     */
		    end_session(sess, sess->result[ST_TEST_1B].status,
				PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
		    break;
		}
		break;
	    default:
		/*
		 * We've got other error with Test 2.
		 */
		end_session(sess, sess->result[ST_TEST_2].status, 
			    PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
		break;
	    }
	}
	break;
    default:
	/*
	 * We've got other error with Test 1.
	 */
	end_session(sess, sess->result[ST_TEST_1].status, 
		    PJ_STUN_NAT_TYPE_ERR_UNKNOWN);
	break;
    }

on_return:
    pj_grp_lock_release(sess->grp_lock);
}
Пример #18
0
int
main(int argc, char *argv[])
{
	int ret = 1, istty, i, idx, delete_all = 0, updated = 0;
	dldev_t dev;
	contact_t db;
	contact_data_t rec;
	u8 *data;
	u16 len;

	/* for data security */
	/*
	umask(S_IRWXG | S_IRWXO);
	*/

	istty = isatty(0);

	while((i = getopt(argc, argv, "hd:a")) != -1){
		switch(i){
		case 'd':
			dev_file = optarg;
			break;
		case 'a':
			delete_all = 1;
			break;
		case 'h':
		default:
			usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

#ifdef USB_USBHID
	dev.usb.file = dev_file;
#endif

	memset(&rec, 0, sizeof(contact_data_t));
	BEGIN_OPT()
		OPT("msg", rec.msg)
		OPT("type", rec.type)
		OPT("area", rec.area)
		OPT("number", rec.number)
	END_OPT()

	if(delete_all){
		fprintf(stderr,
			"WARNING: DELETE ALL CONTACTS IN THE WATCH (Y/N)? ");
		if(tolower(getchar()) != 'y')
			exit(0);
	}else
	if(istty && (!rec.msg || !rec.type || !rec.area || !rec.number))
		usage();

	/* TODO: long phone number extending to the next or previous record */

	if(open_dev(&dev)){
		ERROR("open_dev");
		goto exit;
	}

	if(start_session(&dev)){
		ERROR("read_app_info");
		goto exit;
	}

/******************************************************************************/
#ifdef DEBUG
	for(i = 0; i < NUM_APPS; i++){
		if(!dev.app[i].acd.app_idx)
			continue;
		printf("%2d: %d%d%d%d%d%d%d%d %02x %02x %04x %04x %04x %04x %04x %04x %s\n", i,
				dev.app[i].acd.app_idx,
				dev.app[i].acd.code_loc,
				dev.app[i].acd.db_loc,
				dev.app[i].acd.code_invalid,
				dev.app[i].acd.db_modified,
				dev.app[i].acd.db_invalid,
				dev.app[i].acd.passwd_req,
				dev.app[i].acd.mode_name,

				dev.app[i].acb.app_type,
				dev.app[i].acb.app_inst,
				dev.app[i].acb.asd_addr,
				dev.app[i].acb.add_addr,
				dev.app[i].acb.state_mgr_addr,
				dev.app[i].acb.refresh_addr,
				dev.app[i].acb.banner_addr,
				dev.app[i].acb.code_addr,
				dev.app[i].banner
		);
	}
#endif
/******************************************************************************/

	if((idx = find_app(&dev, "CONTACT")) < 0){
		ERROR("CONTACT application not found");
		goto end;
	}

	if(dump_add(&dev, idx, &data, &len)){
		ERROR("dump_add");
		goto end;
	}

	read_contact(&db, data);
	free(data);

	if(delete_all){
		while(!del_contact(&db, 0))
			updated = 1;
	}else{
		if(!istty && !del_contact_file(&db, stdin))
			updated = 1;

		if(rec.msg && rec.type && rec.area && rec.number &&
			(i = find_contact(&db, &rec)) >= 0 &&
			!del_contact(&db, i))
			updated = 1;
	}

	if(updated){
		create_contact(&db, &data, &len);
		if(load_add(&dev, idx, data)){
			ERROR("load_add");
			goto end;
		}
		free(data);
	}

	print_contact(&db, stdout);
	free_contact(&db);

/******************************************************************************/
end:
	if(end_session(&dev)){
		ERROR("end_session");
		goto exit;
	}

	ret = 0;
exit:
	close_dev(&dev);

	exit(ret);
}
Пример #19
0
/**
 * Author: 	 	Joel Denke, Marcus Isaksson
 * Description:		Run the game on client
 */
int main(int argc, char *argv[])
{
	int i, j, no, yb, keysHeld[323] = {0};
	int result = 0;
	SDL_Thread * eventBuffer;
	SDL_Thread * runBuffer;
	struct timer_t2 fps;
	
	char * server_ip = malloc(sizeof(char) * 16);
	char * elem = malloc(sizeof(char) * MESSAGE_SIZE);

	pColor = malloc(sizeof(SDL_Color));
	oColor = malloc(sizeof(SDL_Color));
	connection = malloc(sizeof(connection_data));

	for (i = 0; i < NO_BUFFERS; i++) {
		cb[i] = malloc(sizeof(cBuffer));
		b_lock[i] = SDL_CreateMutex();
	}

	strcpy(server_ip, "127.0.0.1");

	pColor->r = 0;
	pColor->g = 255;
	pColor->b = 255;
	oColor->r = 0;
	oColor->g = 0;
	oColor->b = 255;

	initGraphics();
	initSound();

	printf("Render menu\n");
	graphicsMenu(&gameWorld, server_ip);

	initSlots(cb[0], BUFFER_SIZE);
	initSlots(cb[1], NO_OBJECTS);
	initSlots(cb[2], BUFFER_SIZE);

	state = gStart;

	if (clientConnect(connection, server_ip) == 0)
	{
		eventBuffer = SDL_CreateThread(listenEventBuffer, &connection);

		while (1) {
			switch (state) {
				case gStart:
					runData(2);
					break;
				case gInit:
					timer_start(&fps);
					startDraw();
					drawLoadScr(SCREEN_WIDTH, SCREEN_HEIGHT);
					endDraw();

					initWorld();
					
					if (timer_get_ticks(&fps) < 1000 / FPS)
					{
						//delay the as much time as we need to get desired frames per second
						SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) );
					}
					break;
				case gRunning :
					timer_start(&fps);
					drawGraphics();
					listenInput(keysHeld);

					// i = 0: players; i = 1: objects; i = 2: messages
					for (i = 0; i < NO_BUFFERS; i++) {
						runData(i);
					}

					if (timer_get_ticks(&fps) < 1000 / FPS)
					{
						//delay the as much time as we need to get desired frames per second
						SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) );
					}

					break;
				case gExit :
					//sprintf(string, "%d,quit", connection->client_id);
					printf("Freeing music now\n");
					pauseMusic();
					freeMusic();
					end_session(connection);
					printf("Player is exit game now\n");
					exitClient(eventBuffer);
					break;
				default :
					printf("test\n");
					break;
			}
		}
	} else {
		printf("Misslyckade med att kontakta servern på ip-adress: '%s'\n", server_ip);
		state = gExit;
		pauseMusic();
		freeMusic();
		exitClient(eventBuffer);
	}

	return 0;
}
Пример #20
0
int
main(int argc, char *argv[])
{
	int ret = 1, i, idx, fd, num_apps = 0;
	char *dev_file = "/dev/uhid0", *banner, *file;
	dldev_t dev;
	appinfo *app = NULL;
	u8 *data;
	u16 len;

	/* for data security */
	/*
	umask(S_IRWXG | S_IRWXO);
	*/

	while((i = getopt(argc, argv, "hd:")) != -1){
		switch(i){
		case 'd':
			dev_file = optarg;
			break;
		case 'h':
		default:
			usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

#ifdef USB_USBHID
	dev.usb.file = dev_file;
#endif

	BEGIN_OPT()
		APP_OPT("rom", -3)
		APP_OPT("eeprom", -2)
		APP_OPT("wristapp", -1)
		APP_OPT("contact", APP_CONTACT)
		APP_OPT("note", APP_NOTE)
		APP_OPT("appt", APP_APPT)
		APP_OPT("alarm", APP_ALARM)
		APP_OPT("schedule", APP_SCHEDULE)
		APP_OPT("occasion", APP_OCCASION)
		APP_OPT("chrono", APP_CHRONO)
		APP_OPT("countdn", APP_TIMER)
		APP_OPT("interval", APP_TIMER | 0x100)
#if 0
		APP_OPT("synchro", APP_SYNCHRO)
#endif
		APP_OPT("option", APP_OPTION)
	END_OPT()

	if(!num_apps)
		usage();

	if(open_dev(&dev)){
		ERROR("open_dev");
		goto exit;
	}

	tucp_progress(1);

	if(start_session(&dev)){
		ERROR("read_app_info");
		goto exit;
	}

/******************************************************************************/
#ifdef DEBUG
	for(i = 0; i < NUM_APPS; i++){
		if(!dev.app[i].acd.app_idx)
			continue;
		printf("%2d: %d%d%d%d%d%d%d%d %02x %02x %04x %04x %04x %04x %04x %04x %s\n", i,
				dev.app[i].acd.app_idx,
				dev.app[i].acd.code_loc,
				dev.app[i].acd.db_loc,
				dev.app[i].acd.code_invalid,
				dev.app[i].acd.db_modified,
				dev.app[i].acd.db_invalid,
				dev.app[i].acd.passwd_req,
				dev.app[i].acd.mode_name,

				dev.app[i].acb.app_type,
				dev.app[i].acb.app_inst,
				dev.app[i].acb.asd_addr,
				dev.app[i].acb.add_addr,
				dev.app[i].acb.state_mgr_addr,
				dev.app[i].acb.refresh_addr,
				dev.app[i].acb.banner_addr,
				dev.app[i].acb.code_addr,
				dev.app[i].banner
		);
	}
#endif
/******************************************************************************/

	for(i = 0; i < num_apps; i++){
		if(app[i].file[0])
			fprintf(stderr, "%s\n", app[i].file);
		else
			continue;

		banner = NULL;
		file = app[i].file;

		switch(app[i].app){
		case -3:
			if(dump_rom(&dev, &data, &len)){
				ERROR("dump_rom");
				goto end;
			}
			break;
		case -2:
			if(dump_eeprom(&dev, &data, &len)){
				ERROR("dump_eeprom");
				goto end;
			}
			break;
		case -1:
			banner = file;
			for(; *file && *file != '='; file++);
			if(*file)
				*file++ = 0;
			if(!(*file)){
				ERROR("%s: no file name specified", banner);
				goto end;
			}
			for(; *banner; banner++)
				*banner = toupper(*banner);
			banner = app[i].file;
			break;
		case APP_CONTACT:
			banner = "CONTACT";
			break;
		case APP_NOTE:
			banner = "NOTE";
			break;
		case APP_APPT:
			banner = "APPT";
			break;
		case APP_ALARM:
			banner = "ALARM";
			break;
		case APP_SCHEDULE:
			banner = "SCHEDULE";
			break;
		case APP_OCCASION:
			banner = "OCCASION";
			break;
		case APP_CHRONO:
			banner = "CHRONO";
			break;
		case APP_TIMER:
			banner = "COUNTDN TIMER";
			break;
		case APP_TIMER | 0x100:
			banner = "INTERVAL TIMER";
			break;
#if 0
		case APP_SYNCHRO:
			banner = "SYNCHRO";
			break;
#endif
		case APP_OPTION:
			len = 15;
			data = (u8 *)malloc(len);
			if(read_abs_addr(&dev, dev.sysmap.opt_addr, int_mem,
						data, len)){
				ERROR("read_abs_addr");
				goto end;
			}
			break;
		}

		if(banner){
			if((idx = find_app(&dev, banner)) < 0){
				ERROR("%s application not found", banner);
				goto end;
			}
			if(dump_add(&dev, idx, &data, &len)){
				ERROR("dump_add");
				goto end;
			}
		}

		if((fd = open(file, O_WRITE, S_IRWUSR)) < 0){
			ERROR("%s: open failed", file);
			goto end;
		}
		if(write(fd, data, len) != len){
			ERROR("%s: write failed", file);
			goto end;
		}
		close(fd);
		free(data);
	}

/******************************************************************************/
end:
	if(end_session(&dev)){
		ERROR("end_session");
		goto exit;
	}

	tucp_progress(0);

	ret = 0;
exit:
	close_dev(&dev);

	exit(ret);
}
Пример #21
0
int
main(int argc, char *argv[])
{
	int ret = 1, i;
	dldev_t dev;
	note_t db;
	u8 *data;
	u16 len;

	/* for data security */
	/*
	umask(S_IRWXG | S_IRWXO);
	*/

	while((i = getopt(argc, argv, "hd:u:e:")) != -1){
		switch(i){
		case 'd':
			dev_file = optarg;
			break;
		case 'u':
			unused_recs = atoi(optarg);
			if(unused_recs < 0)
				unused_recs = 0;
			break;
		case 'e':
			extra_msg_len = atoi(optarg);
			if(extra_msg_len < 0)
				extra_msg_len = 0;
			break;
		case 'h':
		default:
			usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

	set_note_unused_recs(unused_recs);
	set_note_extra_len(extra_msg_len);

#ifdef USB_USBHID
	dev.usb.file = dev_file;
#endif

	if(open_dev(&dev)){
		ERROR("open_dev");
		goto exit;
	}

	if(start_session(&dev)){
		ERROR("read_app_info");
		goto exit;
	}

/******************************************************************************/
#ifdef DEBUG
	for(i = 0; i < NUM_APPS; i++){
		if(!dev.app[i].acd.app_idx)
			continue;
		printf("%2d: %d%d%d%d%d%d%d%d %02x %02x %04x %04x %04x %04x %04x %04x %s\n", i,
				dev.app[i].acd.app_idx,
				dev.app[i].acd.code_loc,
				dev.app[i].acd.db_loc,
				dev.app[i].acd.code_invalid,
				dev.app[i].acd.db_modified,
				dev.app[i].acd.db_invalid,
				dev.app[i].acd.passwd_req,
				dev.app[i].acd.mode_name,

				dev.app[i].acb.app_type,
				dev.app[i].acb.app_inst,
				dev.app[i].acb.asd_addr,
				dev.app[i].acb.add_addr,
				dev.app[i].acb.state_mgr_addr,
				dev.app[i].acb.refresh_addr,
				dev.app[i].acb.banner_addr,
				dev.app[i].acb.code_addr,
				dev.app[i].banner
		);
	}
#endif
/******************************************************************************/

	if(read_note_mem(&dev, &db)){
		ERROR("read_note_mem");
		goto end;
	}

	create_note(&db, &data, &len);
	if(load_add(&dev, find_app(&dev, "NOTE"), data)){
		ERROR("load_add");
		goto end;
	}
	free(data);

	print_note(&db, stdout);
	free_note(&db);

/******************************************************************************/
end:
	if(end_session(&dev)){
		ERROR("end_session");
		goto exit;
	}

	ret = 0;
exit:
	close_dev(&dev);

	exit(ret);
}
Пример #22
0
int
main(int argc, char *argv[])
{
	int ret = 1, i, idx;
	dldev_t dev;
	tymer_t db;
	u8 *data;
	u16 len;

	/* for data security */
	/*
	umask(S_IRWXG | S_IRWXO);
	*/

	i = strlen(argv[0]) - 1;
	for(; i >= 0 && argv[0][i] != '/'; i--);
	i++;
	if(strstr(argv[0] + i, "interval")){
		set_timer(POR_INTERVAL);
		is_countdn = 0;
	}

	while((i = getopt(argc, argv, "hd:")) != -1){
		switch(i){
		case 'd':
			dev_file = optarg;
			break;
		case 'h':
		default:
			usage();
			break;
		}
	}
	argc -= optind;
	argv += optind;

#ifdef USB_USBHID
	dev.usb.file = dev_file;
#endif

	if(open_dev(&dev)){
		ERROR("open_dev");
		goto exit;
	}

	if(start_session(&dev)){
		ERROR("read_app_info");
		goto exit;
	}

/******************************************************************************/
#ifdef DEBUG
	for(i = 0; i < NUM_APPS; i++){
		if(!dev.app[i].acd.app_idx)
			continue;
		printf("%2d: %d%d%d%d%d%d%d%d %02x %02x %04x %04x %04x %04x %04x %04x %s\n", i,
				dev.app[i].acd.app_idx,
				dev.app[i].acd.code_loc,
				dev.app[i].acd.db_loc,
				dev.app[i].acd.code_invalid,
				dev.app[i].acd.db_modified,
				dev.app[i].acd.db_invalid,
				dev.app[i].acd.passwd_req,
				dev.app[i].acd.mode_name,

				dev.app[i].acb.app_type,
				dev.app[i].acb.app_inst,
				dev.app[i].acb.asd_addr,
				dev.app[i].acb.add_addr,
				dev.app[i].acb.state_mgr_addr,
				dev.app[i].acb.refresh_addr,
				dev.app[i].acb.banner_addr,
				dev.app[i].acb.code_addr,
				dev.app[i].banner
		);
	}
#endif
/******************************************************************************/

	if((idx = find_app(&dev, uapp_name)) < 0){
		ERROR("%s application not found", uapp_name);
		goto end;
	}

	if(dump_add(&dev, idx, &data, &len)){
		ERROR("dump_add");
		goto end;
	}
	read_timer(&db, data);
	free(data);

	print_timer(&db, stdout);
	free_timer(&db);

/******************************************************************************/
end:
	if(end_session(&dev)){
		ERROR("end_session");
		goto exit;
	}

	ret = 0;
exit:
	close_dev(&dev);

	exit(ret);
}
Пример #23
0
void
handle_connection(const int listen_fd, short event, void *arg)
{
	struct sockaddr_storage tmp_ss;
	struct sockaddr *client_sa, *server_sa, *fixed_server_sa;
	struct sockaddr *proxy_to_server_sa;
	struct session *s;
	socklen_t len;
	int client_fd, fc, on;

	event_add(&listen_ev, NULL);

	if ((event & EV_TIMEOUT))
		/* accept() is no longer paused. */
		return;

	/*
	 * We _must_ accept the connection, otherwise libevent will keep
	 * coming back, and we will chew up all CPU.
	 */
	client_sa = sstosa(&tmp_ss);
	len = sizeof(struct sockaddr_storage);
	if ((client_fd = accept(listen_fd, client_sa, &len)) < 0) {
		logmsg(LOG_CRIT, "accept() failed: %s", strerror(errno));

		/*
		 * Pause accept if we are out of file descriptors, or
		 * libevent will haunt us here too.
		 */
		if (errno == ENFILE || errno == EMFILE) {
			struct timeval pause = { 1, 0 };

			event_del(&listen_ev);
			evtimer_add(&pause_accept_ev, &pause);
		} else if (errno != EWOULDBLOCK && errno != EINTR &&
		    errno != ECONNABORTED)
			logmsg(LOG_CRIT, "accept() failed: %s", strerror(errno));
		return;
	}

	/* Refuse connection if the maximum is reached. */
	if (session_count >= max_sessions) {
		logmsg(LOG_ERR, "client limit (%d) reached, refusing "
		    "connection from %s", max_sessions, sock_ntop(client_sa));
		close(client_fd);
		return;
	}

	/* Allocate session and copy back the info from the accept(). */
	s = init_session();
	if (s == NULL) {
		logmsg(LOG_CRIT, "init_session failed");
		close(client_fd);
		return;
	}
	s->client_fd = client_fd;
	memcpy(sstosa(&s->client_ss), client_sa, client_sa->sa_len);

	/* Cast it once, and be done with it. */
	client_sa = sstosa(&s->client_ss);
	server_sa = sstosa(&s->server_ss);
	proxy_to_server_sa = sstosa(&s->proxy_ss);
	fixed_server_sa = sstosa(&fixed_server_ss);

	/* Log id/client early to ease debugging. */
	logmsg(LOG_DEBUG, "#%d accepted connection from %s", s->id,
	    sock_ntop(client_sa));

	/*
	 * Find out the real server and port that the client wanted.
	 */
	len = sizeof(struct sockaddr_storage);
	if (getsockname(s->client_fd, server_sa, &len) < 0) {
		logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
		    strerror(errno));
		goto fail;
	}
	len = sizeof(s->client_rd);
	if (getsockopt(s->client_fd, SOL_SOCKET, SO_RTABLE, &s->client_rd,
	    &len) && errno != ENOPROTOOPT) {
		logmsg(LOG_CRIT, "#%d getsockopt failed: %s", s->id,
		    strerror(errno));
		goto fail;
	}
	if (fixed_server) {
		memcpy(sstosa(&s->orig_server_ss), server_sa,
		    server_sa->sa_len);
		memcpy(server_sa, fixed_server_sa, fixed_server_sa->sa_len);
	}

	/* XXX: check we are not connecting to ourself. */

	/*
	 * Setup socket and connect to server.
	 */
	if ((s->server_fd = socket(server_sa->sa_family, SOCK_STREAM,
	    IPPROTO_TCP)) < 0) {
		logmsg(LOG_CRIT, "#%d server socket failed: %s", s->id,
		    strerror(errno));
		goto fail;
	}
	if (fixed_proxy && bind(s->server_fd, sstosa(&fixed_proxy_ss),
	    fixed_proxy_ss.ss_len) != 0) {
		logmsg(LOG_CRIT, "#%d cannot bind fixed proxy address: %s",
		    s->id, strerror(errno));
		goto fail;
	}

	/* Use non-blocking connect(), see CONNECT_TIMEOUT below. */
	if ((fc = fcntl(s->server_fd, F_GETFL)) == -1 ||
	    fcntl(s->server_fd, F_SETFL, fc | O_NONBLOCK) == -1) {
		logmsg(LOG_CRIT, "#%d cannot mark socket non-blocking: %s",
		    s->id, strerror(errno));
		goto fail;
	}
	if (connect(s->server_fd, server_sa, server_sa->sa_len) < 0 &&
	    errno != EINPROGRESS) {
		logmsg(LOG_CRIT, "#%d proxy cannot connect to server %s: %s",
		    s->id, sock_ntop(server_sa), strerror(errno));
		goto fail;
	}

	len = sizeof(struct sockaddr_storage);
	if ((getsockname(s->server_fd, proxy_to_server_sa, &len)) < 0) {
		logmsg(LOG_CRIT, "#%d getsockname failed: %s", s->id,
		    strerror(errno));
		goto fail;
	}

	logmsg(LOG_INFO, "#%d FTP session %d/%d started: client %s to server "
	    "%s via proxy %s", s->id, session_count, max_sessions,
	    sock_ntop(client_sa), sock_ntop(server_sa),
	    sock_ntop(proxy_to_server_sa));

	/* Keepalive is nice, but don't care if it fails. */
	on = 1;
	setsockopt(s->client_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
	    sizeof on);
	setsockopt(s->server_fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
	    sizeof on);

	/*
	 * Setup buffered events.
	 */
	s->client_bufev = bufferevent_new(s->client_fd, &client_read, NULL,
	    &client_error, s);
	if (s->client_bufev == NULL) {
		logmsg(LOG_CRIT, "#%d bufferevent_new client failed", s->id);
		goto fail;
	}
	bufferevent_settimeout(s->client_bufev, timeout, 0);
	bufferevent_enable(s->client_bufev, EV_READ | EV_TIMEOUT);

	s->server_bufev = bufferevent_new(s->server_fd, &server_read, NULL,
	    &server_error, s);
	if (s->server_bufev == NULL) {
		logmsg(LOG_CRIT, "#%d bufferevent_new server failed", s->id);
		goto fail;
	}
	bufferevent_settimeout(s->server_bufev, CONNECT_TIMEOUT, 0);
	bufferevent_enable(s->server_bufev, EV_READ | EV_TIMEOUT);

	return;

 fail:
	end_session(s);
}