Example #1
0
static void udp_sender(void *arg)
{
    Msg *msg;
    Udpc *conn = arg;

    gwlist_add_producer(flow_threads);    
    while (1) {

        if ((msg = gwlist_consume(conn->outgoing_list)) == NULL)
            break;

        info(0, "sending datagram <%s:%ld> -> <%s:%ld>",
              octstr_get_cstr(msg->wdp_datagram.source_address),
              msg->wdp_datagram.source_port,
              octstr_get_cstr(msg->wdp_datagram.destination_address),
              msg->wdp_datagram.destination_port);

        dump(msg);

        if (send_udp(conn->fd, msg) == -1) {
            msg_destroy(msg);
            continue;
        }
        counter_increase(outgoing_wdp_counter);
        msg_destroy(msg);
    }
    gwthread_join(conn->receiver);

    udpc_destroy(conn);
    gwlist_remove_producer(flow_threads);
}
Example #2
0
int fldigi_command (struct iface *ifp, char *cmdstr)
{
	struct mbuf *bp;

	struct socket lsock, rsock;

	int len = strlen (cmdstr);

	lsock.address = INADDR_ANY;
	lsock.port = 10000;

	rsock.address = Axip[ifp->dev].ipaddr;
	rsock.port = 10000;
	
	log (-1, "fldigi_command [%s]", cmdstr);

	if ((bp = alloc_mbuf (len)) == NULLBUF)
		return 0;

	strncpy ((char*)bp->data, cmdstr, len);

	bp->cnt = (int16)len;

	return send_udp (&lsock, &rsock, 0, 0, bp, 0, 0, 0);
}
Example #3
0
static void udp_sender(void *arg)
{
    Msg *msg;
    Udpc *conn = arg;

    gwlist_add_producer(flow_threads);
    while(bb_status != BB_DEAD) {

	gwlist_consume(suspended);	/* block here if suspended */

	if ((msg = gwlist_consume(conn->outgoing_list)) == NULL)
	    break;

	debug("bb.udp", 0, "udp: sending message");
	
        if (send_udp(conn->fd, msg) == -1)
	    /* ok, we failed... tough
	     * XXX log the message or something like that... but this
	     * is not as fatal as it is with SMS-messages...
	     */ {
	    msg_destroy(msg);
	    continue;
	}
	counter_increase(outgoing_wdp_counter);
	msg_destroy(msg);
    }
    gwthread_join(conn->receiver);

    udpc_destroy(conn);
    gwlist_remove_producer(flow_threads);
}
void Connection_Manager::send_dispatch_by_udp(const string& data, uint32_t sid)
{
	Server_Node_Map::iterator it = nodes_.find(sid);
	if(it != nodes_.end())
	{
		send_udp(data, get_udp_remote_addr(it->second));
	}
}
void Connection_Manager::send_dispatch_by_udp(CCorePacket& packet, uint32_t sid)
{
	Server_Node_Map::iterator it = nodes_.find(sid);
	if(it != nodes_.end())
	{
		send_udp(packet, get_udp_remote_addr(it->second));
	}
}
Example #6
0
void ConnServer::snd_conn_run() {
	uint64_t now = get_tick_ms();
	if (_status == CONV_SND_CONV) {
		if (now > _next_snd_conv_tick) {
			send_udp((const char*)&_snd_conv, sizeof(_snd_conv));
			_next_snd_conv_tick = now + 1000;
		}
	}
}
Example #7
0
void ConnClient::req_conn_run() {
	uint64_t now = get_tick_ms();
	if (_status == CONV_REQ_CONN) {
		if (_req_conn_times > 0) {
			if (now > _next_req_conn_tick) {
				send_udp((const char*)&_req_conn, sizeof(_req_conn));
				_req_conn_times--;
				_next_req_conn_tick = now + 1000;
			}
		}
	}
}
Example #8
0
static int forward_audio_pack(struct pack *p, int len)
{
  static uint32_t seq;

  /* re-mangle the pack header */
  p->seq = ++seq;
  P_HTON(p);

  send_udp(p, len, &dest_addr);

  return 0;
}
Example #9
0
void scan_read_buf(int len){
    static int last_zero = 0;
    int i;
    for (i = 0; i < len; i++){
        char c = read_buf[i];
        
        if (last_zero == 3 && c == 1){
            send_udp(1);
            frame_seq++;
            pkg_seq = 0;
            buf = send_pkt + 12;
            buf_len = 0;
            
            // printf("%d\n", frame_seq);
        }
        
        if (c != 0) {
            if (buf_len + last_zero + 1 > 1400) {
                send_udp(0);
                buf = send_pkt + 12;
                buf_len = 0;
                pkg_seq++;
            }
            
            if (last_zero > 0) {
                bzero(buf, last_zero);
                buf+=last_zero;
                buf_len+=last_zero;
            }
            
            *buf = c;
            buf++;
            buf_len++;
            
            last_zero=0;
        }else{
            last_zero++;
        }
    }
}
Example #10
0
void sendCurrentPlayingTime(void) {
  if (currentMode == MODE_REPLAY) {
    char current_time[256];

    sprintf(current_time, "%f", currentPlayingTime);

#if DEBUGMESSAGES
    g_print("sendding value : %s\n", current_time);
#endif

    send_udp("127.0.0.1", 23867, current_time);
  }
}
Example #11
0
int creator_udp(void)
{
	int sockfd, len_payload, len_total;
	struct sockaddr_in *src_addr, *dst_addr;

	char *buf, *payload;
	struct ip *header_ip;
	struct udphdr *header_udp;

	buf = malloc(200);
	payload = malloc(100);
	src_addr = malloc(sizeof(struct sockaddr_in));
	dst_addr = malloc(sizeof(struct sockaddr_in));

	header_ip = (struct ip *)buf;
	header_udp = (struct udphdr *)(buf + sizeof(struct ip));
	payload = buf + sizeof(struct ip) + sizeof(struct udphdr);

	memset(buf, '\0', sizeof(buf));

	memset(src_addr, '\0', sizeof(struct sockaddr_in));
	memset(dst_addr, '\0', sizeof(struct sockaddr_in));

	len_payload = payload_udp_dns(payload);

	len_total = sizeof(struct ip) + sizeof(struct udphdr) + len_payload;

	//构建原始套接字
	sockfd = sock_init_udp(src_addr, dst_addr);

	//初始化ip报头
	creator_udphdr_ip(header_ip, src_addr, dst_addr, len_total);

	//初始化udp报头,并填充数据
	creator_header_udp(header_udp, len_total);

	//ip校验和是否填充无所谓,网卡会自动计算出来
	header_ip->ip_sum = creator_check_sum(buf, IPPROTO_IP);

	//udp校验和
	header_udp->check = creator_check_sum(buf, IPPROTO_UDP);

//      printf("the ip_sum is %02x===\n", header_ip->ip_sum);
//      printf("the udp_sum is %02x===\n", header_udp->check);

	//发送udp数据包
	send_udp(sockfd, dst_addr, buf, len_total);

	return 0;
}
Example #12
0
/*----------------------------------------------------------------------------------------------
 * 函数:    tftpd_xmit()
 *
 * 说明:    发送tftp报文
 *
 * 输入:    1) target_ip     目标ip地址
 *          2) target_port   目标端口
 *          3) opcode        tftp操作码
 *          4) blkid         数据块号(或错误码)
 *          5) buf           数据(或错误信息)
 *          6) buf_len       数据长度
 *
 * 返回:    ok/fail
**--------------------------------------------------------------------------------------------*/
BOOL apical tftpd_xmit(INT32U target_ip, INT16U target_port, INT16U opcode, 
                       INT16U blkid, INT08S *buf, INT16U buf_len)
{
    static INT08S * tx_buf = NULL;
    struct tftphdr * hdr;

    if(!tx_buf)
        allocate_buffer(tx_buf, INT08S *, (INT32U)TFTP_TX_BUF_SIZE, return fail);

    hdr = (struct tftphdr *)tx_buf; /*lint !e826 */

    #if 0
    DispatchLock();
    printf("\ntftpd_xmit: target_ip=%08lX, port=%d, opcode=%d, blkid=%d, buf=%s, buf_len=%d",
        target_ip, target_port, opcode, blkid, buf, buf_len);
    DispatchUnlock();
    #endif

    switch(opcode){
        case TFTP_OP_RRQ:
        case TFTP_OP_WRQ:
            return fail;
        case TFTP_OP_DAT:
            FamesAssert(buf);
            hdr->opcode = INT16XCHG(opcode);
            hdr->un.id  = INT16XCHG(blkid);
            MEMCPY(&tx_buf[4], buf, (INT16S)buf_len);
            buf_len+=4;
            break;
        case TFTP_OP_ACK:
            hdr->opcode = INT16XCHG(opcode);
            hdr->un.id  = INT16XCHG(blkid);
            buf_len=4;
            break;
        case TFTP_OP_ERR:
            FamesAssert(buf);
            hdr->opcode = INT16XCHG(opcode);
            hdr->un.err.err  = INT16XCHG(blkid);
            MEMCPY(&tx_buf[4], buf, (INT16S)buf_len);
            buf_len+=4;
            break;
        default:
            return fail;
    }
    return send_udp(target_ip, target_port, UDP_P_TFTP, tx_buf, buf_len);

}
Example #13
0
static void send_auth(char *username, char *password) {
	struct mt_packet data;
	unsigned short width = 0;
	unsigned short height = 0;
	char *terminal = getenv("TERM");
	char md5data[100];
	unsigned char md5sum[17];
	int plen;
	md5_state_t state;

#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
	mlock(md5data, sizeof(md5data));
	mlock(md5sum, sizeof(md5data));
#endif

	/* Concat string of 0 + password + encryptionkey */
	md5data[0] = 0;
	strncpy(md5data + 1, password, 82);
	md5data[83] = '\0';
	memcpy(md5data + 1 + strlen(password), encryptionkey, 16);

	/* Generate md5 sum of md5data with a leading 0 */
	md5_init(&state);
	md5_append(&state, (const md5_byte_t *)md5data, strlen(password) + 17);
	md5_finish(&state, (md5_byte_t *)md5sum + 1);
	md5sum[0] = 0;

	/* Send combined packet to server */
	init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
	plen = add_control_packet(&data, MT_CPTYPE_PASSWORD, md5sum, 17);
	plen += add_control_packet(&data, MT_CPTYPE_USERNAME, username, strlen(username));
	plen += add_control_packet(&data, MT_CPTYPE_TERM_TYPE, terminal, strlen(terminal));
	
	if (is_a_tty && get_terminal_size(&width, &height) != -1) {
		width = htole16(width);
		height = htole16(height);
		plen += add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2);
		plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2);
	}

	outcounter += plen;

	/* TODO: handle result */
	send_udp(&data, 1);
}
Example #14
0
void cb_rw(int fd, short event, void *args)
{
    connection *c = (connection *)args;

    if(event == EV_READ) {
        if(c->transport == SOCK_STREAM)
            recv_tcp(c);
        else
            recv_udp(c);
    }
   
    if(event == EV_WRITE) {
        if(c->transport == SOCK_STREAM)
            send_tcp(c);
        else
            send_udp(c);
    }
}
Example #15
0
static void showtime() {
	jack_position_t current;
	jack_transport_state_t transport_state;
	jack_nframes_t frame_time;

	transport_state = jack_transport_query(client, &current);
	frame_time = jack_frame_time(client);

	float time = (float) current.frame / (float) current.frame_rate;
	char current_time[256];
	snprintf(current_time, sizeof(current_time), "%f", time);
	send_udp(udp_ip, udp_port, current_time);
	if (lastframe != current.frame) {
		printf(
				"\x1b[Aframe= %u  frame_time= %u usecs= %lld fr_in:%i fr_out:%i time: %f\t ",
				current.frame, frame_time, current.usecs, current.frame_rate, framerate_out , time);
		lastframe = current.frame;

		switch (transport_state) {
		case JackTransportStopped:
			printf("state: Stopped");
			break;
		case JackTransportRolling:
			printf("state: Rolling");
			break;
		case JackTransportStarting:
			printf("state: Starting");
			break;
		default:
			printf("state: [unknown]");
			break;
		}

		if (current.valid & JackPositionBBT)
			printf("\tBBT: %3" PRIi32 "|%" PRIi32 "|%04"
			PRIi32, current.bar, current.beat, current.tick);

		if (current.valid & JackPositionTimecode)
			printf("\tTC: (%.6f, %.6f)", current.frame_time, current.next_time);
		printf("  \n");
	}
}
Example #16
0
static void sig_winch(int sig) {
	unsigned short width,height;
	struct mt_packet data;
	int plen;

	/* terminal height/width has changed, inform server */
	if (get_terminal_size(&width, &height) != -1) {
		init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
		width = htole16(width);
		height = htole16(height);
		plen = add_control_packet(&data, MT_CPTYPE_TERM_WIDTH, &width, 2);
		plen += add_control_packet(&data, MT_CPTYPE_TERM_HEIGHT, &height, 2);
		outcounter += plen;

		send_udp(&data, 1);
	}

	/* reinstate signal handler */
	signal(SIGWINCH, sig_winch);
}
Example #17
0
static void udp_timeout_handler(void *arg)
{
	struct dns_query *q = arg;
	int err = ETIMEDOUT;

	if (q->ntx >= NTX_MAX)
		goto out;

	err = send_udp(q);
	if (err)
		goto out;

	tmr_start(&q->tmr, 1000<<MIN(2, q->ntx - 2),
		  udp_timeout_handler, q);

 out:
	if (err) {
		query_handler(q, err, NULL, NULL, NULL, NULL);
		mem_deref(q);
	}
}
Example #18
0
/**
  * @brief Gestisce la lettura dei pacchetti UDP provenienti dall'Applicazione Mobile.
  * @return void.
 */
void lettura_pkt_app(void)
{
	uint32_t buf[PKTSIZE];
	uint32_t idmsg;

	/* ricevo un pkt */
	/*ris=Readn(appmobilefd,(char*)buf,PKTSIZE);*/
	ris=Readn(appmobilefd,(char*)buf,sizeof(buf));
	if(ris!=sizeof(buf)) { fprintf(stderr,"recv from appmobile failed, received %d: ", ris); exit(9); }

	idmsg = buf[0];

	/*ris=send_udp(monitordatafd, (char*)buf, PKTSIZE , 1000, "127.0.0.1", cfgPorte[index] );*/
	ris=send_udp(monitordatafd, (char*)buf, sizeof(buf) , 1000, "127.0.0.1", cfgPorte[index] );
	if(!(ris))
	{
		fprintf(stderr,"pkt id %u NOT sent\n", idmsg );
	}
	
	/* Inserisce il pacchetto nella lista */
	lPkt = ins_pkt(buf, lPkt, cfgPorte[index]);
}
Example #19
0
void sendmsg_call_handler(unsigned long long uniqueSockID, int threads,
		unsigned char *buf, ssize_t len) {

	int index;
	int datalen;
	int flags;
	int msg_flags;
	int symbol;
	int controlFlag = 0;
	u_char *data;
	socklen_t addrlen;
	void *msg_control;
	int msg_controlLength;
	struct sockaddr_in *addr;
	u_char *pt;

	PRINT_DEBUG("");

	pt = buf;

	flags = *(int *) pt;
	pt += sizeof(int);

	symbol = *(int *) pt;
	pt += sizeof(int);

	if (symbol) {
		addrlen = *(u_int *) pt;
		pt += sizeof(u_int);

		addr = (struct sockaddr_in *) malloc(addrlen);
		memcpy(addr, pt, addrlen);
		pt += addrlen;
		PRINT_DEBUG("addr=%s/%d", inet_ntoa(addr->sin_addr), addr->sin_port);
	}

	msg_flags = *(int *) pt;
	pt += sizeof(int);

	controlFlag = *(int *) pt;
	pt += sizeof(int);

	if (controlFlag) {
		msg_controlLength = *(u_int *) pt;
		pt += sizeof(u_int);

		msg_control = malloc(msg_controlLength);
		memcpy(msg_control, pt, msg_controlLength);
		pt += msg_controlLength;
	}

	datalen = *(u_int *) pt;
	pt += sizeof(u_int);

	if (datalen <= 0) {
		PRINT_DEBUG("DATA Field is empty!!");
		nack_send(uniqueSockID, sendmsg_call);
		return;
	}

	data = (u_char *) malloc(datalen);
	PRINT_DEBUG("");

	memcpy(data, pt, datalen);
	pt += datalen;

	if (pt - buf != len) {
		PRINT_DEBUG("READING ERROR! CRASH, diff=%d len=%d", pt - buf, len);
		nack_send(uniqueSockID, sendmsg_call);
		return;
	}

	PRINT_DEBUG("");

	index = findjinniSocket(uniqueSockID);
	PRINT_DEBUG("");

	if (index == -1) {
		PRINT_DEBUG(
				"CRASH !!! socket descriptor not found into jinni sockets SO pipe descriptor to reply is notfound too ");
		nack_send(uniqueSockID, sendmsg_call);
		return;
	}
	PRINT_DEBUG("");

	/**
	 * In case of connected sockets
	 */
	if (jinniSockets[index].connection_status > 0) {

		if (jinniSockets[index].type == SOCK_DGRAM)
			send_udp(uniqueSockID, sendmsg_call, datalen, data, flags);
		else if (jinniSockets[index].type == SOCK_STREAM)
			send_tcp(uniqueSockID, sendmsg_call, datalen, data, flags);
		else if ((jinniSockets[index].type == SOCK_RAW)
				&& (jinniSockets[index].protocol == IPPROTO_ICMP)) {

		} else {
			PRINT_DEBUG("unknown socket type has been read !!!");
			nack_send(uniqueSockID, sendmsg_call);
		}

	} else {

		/**
		 * In case of NON-connected sockets, WE USE THE ADDRESS GIVEN BY the APPlication
		 * Process. Check if an address has been passed or not is required
		 */
		if (symbol) { // check that the passed address is not NULL
			if (jinniSockets[index].type == SOCK_DGRAM)
				sendto_udp(uniqueSockID, sendmsg_call, datalen, data, flags,
						addr, addrlen);
			else if (jinniSockets[index].type == SOCK_STREAM)
				sendto_tcp(uniqueSockID, sendmsg_call, datalen, data, flags,
						addr, addrlen);
			else if ((jinniSockets[index].type == SOCK_RAW)
					&& (jinniSockets[index].protocol == IPPROTO_ICMP)) {

				sendto_icmp(uniqueSockID, sendmsg_call, datalen, data, flags,
						addr, addrlen);

			} else {

				PRINT_DEBUG("unknown target address !!!");
				nack_send(uniqueSockID, sendmsg_call);
			}

		}

		else {
			PRINT_DEBUG("unknown target address !!!");
			nack_send(uniqueSockID, sendmsg_call);
		}

	}

	PRINT_DEBUG();
	return;

}
Example #20
0
int main(int argc, char **argv)
{
	int fd,port,ppid,flags;
	unsigned short pid;
	struct 			dmxPesFilterParams flt; 
	char buffer[BSIZE], *bp;
	unsigned char c;
	
	bp = buffer;
	while ((bp-buffer) < BSIZE) {

		read(STDIN_FILENO, &c, 1);

		if ((*bp++=c)=='\n')
			break;
	}

	*bp++ = 0;

	bp = buffer;
	if (!strncmp(buffer, "GET /", 5))
	{
		printf("HTTP/1.1 200 OK\r\nServer: d-Box network\r\n\r\n");
		bp += 5;
	}
	sscanf(bp, "%hx", &pid);
	
	port = 0;
	if ((bp=strchr(bp,',')) != 0) {
		bp++;
		sscanf(bp, "%d", &port);
	}

#ifdef DEBUG
	char a_buffer[20];
	sprintf(a_buffer,"/tmp/streampes%d.log",pid);
	fp_err = fopen(a_buffer,"w");
#endif
	
	fflush(stdout);
	
	fd=open("/dev/dvb/card0/demux0", O_RDWR);

	if (fd < 0) {
#ifdef DEBUG
		perror("/dev/dvb/card0/demux0");
#endif
		return -fd;
	}
	
	ioctl(fd, DMX_SET_BUFFER_SIZE, DMX_BUFFER_SIZE);

	flt.pid=pid;
	flt.input=DMX_IN_FRONTEND;
	flt.output=DMX_OUT_TAP;
	flt.pesType=DMX_PES_OTHER;
	flt.flags=0;
	if (ioctl(fd, DMX_SET_PES_FILTER, &flt)<0)
	{
		perror("DMX_SET_PES_FILTER");
		return errno;
	}
	if (ioctl(fd, DMX_START, 0)<0)
	{
		perror("DMX_SET_PES_FILTER");
		return errno;
	}
/*Geht noch nicht wg. Bug im Demux Device	
	flags = fcntl(fd,F_GETFL,0);
	if (flags == -1) {
		return (errno);
	}
	fcntl(fd,F_SETFL, flags | O_NONBLOCK);
*/	
	if (port > 1023) {
		ppid = fork();
		if (ppid == 0) {
			send_udp (fd, port);
		} 
		else if (ppid > 0) {
			while (read(STDIN_FILENO,buffer,1) >= 0);
		 	kill (ppid,SIGINT);
		 	exit(waitpid(ppid,0,0));
		}
		else {
#ifdef DEBUG
			fprintf(fp_err,"error cannot fork\n");
#endif
			return(-1);
		}
	}
	else {
		setpriority(PRIO_PROCESS,0,-10);
		while (1) {
			int pr = 0, r;
			int tr = BSIZE;
			while (tr) {
				if ((r=read(fd, buffer+pr, tr)) <= 0) {
					if (errno == EAGAIN) {
						sleep (10000);
						continue;
					}
#ifdef DEBUG
					fprintf(fp_err,"error read demux %d\n", errno);
#endif
					sleep (10000);
					continue;
				}
				pr+=r;
				tr-=r;
			}

			if (write(STDOUT_FILENO, buffer, r) != r) {
#ifdef DEBUG
				fprintf(fp_err,"error write stdout %d\n",errno);
#endif
				break;
			}
		}
	}

	close(fd);
	return 0;
}
Example #21
0
void send_call_handler(unsigned long long uniqueSockID, int threads,
		unsigned char *buf, ssize_t len) {

	int index;
	int datalen;
	int flags;
	u_char *data;
	socklen_t addrlen;
	struct sockaddr *addr;
	u_char *pt;

	PRINT_DEBUG("");

	pt = buf;

	datalen = *(ssize_t *) pt;
	pt += sizeof(ssize_t);

	PRINT_DEBUG("passed data len = %d", datalen);
	if (datalen <= 0) {
		PRINT_DEBUG("DATA Field is empty!!");
		nack_send(uniqueSockID, send_call);
		return;
	}

	data = (u_char *) malloc(datalen);
	PRINT_DEBUG("");

	memcpy(data, pt, datalen);
	pt += datalen;

	PRINT_DEBUG("");

	flags = *(int *) pt;
	pt += sizeof(int);

	if (pt - buf != len) {
		PRINT_DEBUG("READING ERROR! CRASH, diff=%d len=%d", pt - buf, len);
		nack_send(uniqueSockID, send_call);
		return;
	}

	PRINT_DEBUG("");

	index = findjinniSocket(uniqueSockID);
	if (index == -1) {
		PRINT_DEBUG(
				"CRASH !!! socket descriptor not found into jinni sockets SO pipe descriptor to reply is notfound too ");
		nack_send(uniqueSockID, send_call);
		return;
	}
	PRINT_DEBUG("");

	if (jinniSockets[index].connection_status <= 0) {
		PRINT_DEBUG("Socket is not connected to any destination !!!");
		nack_send(uniqueSockID, send_call);
	}

	if (jinniSockets[index].type == SOCK_DGRAM)
		send_udp(uniqueSockID, send_call, datalen, data, flags);
	else if (jinniSockets[index].type == SOCK_STREAM)
		send_tcp(uniqueSockID, send_call, datalen, data, flags);
	else {
		PRINT_DEBUG("unknown socket type has been read !!!");
		nack_send(uniqueSockID, send_call);
	}
	PRINT_DEBUG();
	return;

} //end of send_call_handler()
Example #22
0
static int send_udp(struct mt_packet *packet, int retransmit) {
	int sent_bytes;

	/* Clear keepalive counter */
	keepalive_counter = 0;

	if (!use_raw_socket) {
		/* Init SendTo struct */
		struct sockaddr_in socket_address;
		socket_address.sin_family = AF_INET;
		socket_address.sin_port = htons(MT_MACTELNET_PORT);
		socket_address.sin_addr.s_addr = htonl(INADDR_BROADCAST);

		sent_bytes = sendto(send_socket, packet->data, packet->size, 0, (struct sockaddr*)&socket_address, sizeof(socket_address));
	} else {
		sent_bytes = net_send_udp(sockfd, active_interface, srcmac, dstmac, &sourceip,  sourceport, &destip, MT_MACTELNET_PORT, packet->data, packet->size);
	}

	/* 
	 * Retransmit packet if no data is received within
	 * retransmit_intervals milliseconds.
	 */
	if (retransmit) {
		int i;

		for (i = 0; i < MAX_RETRANSMIT_INTERVALS; ++i) {
			fd_set read_fds;
			int reads;
			struct timeval timeout;
			int interval = retransmit_intervals[i] * 1000;

			/* Init select */
			FD_ZERO(&read_fds);
			FD_SET(insockfd, &read_fds);
			timeout.tv_sec = 0;
			timeout.tv_usec = interval;

			/* Wait for data or timeout */
			reads = select(insockfd + 1, &read_fds, NULL, NULL, &timeout);
			if (reads && FD_ISSET(insockfd, &read_fds)) {
				unsigned char buff[1500];
				int result;

				bzero(buff, 1500);
				result = recvfrom(insockfd, buff, 1500, 0, 0, 0);

				/* Handle incoming packets, waiting for an ack */
				if (result > 0 && handle_packet(buff, result) == MT_PTYPE_ACK) {
					return sent_bytes;
				}
			}

			/* Retransmit */
			send_udp(packet, 0);
		}

		if (is_a_tty && terminal_mode) {
			reset_term();
		}

		fprintf(stderr, "\nConnection timed out\n");
		exit(1);
	}
	return sent_bytes;
}
Example #23
0
int main(int argc, char **argv)
{
  struct udp_state *ud;
  struct katcp_dispatch *d;
  unsigned int result;
  struct timeval now;
  fd_set fsr;
  char *ip_addr = NULL;
  uint32_t address, length;
  int i, j, c, pos;
  int wait, nooftries;
  int port = 0;
int rw_flag = 0;

  i = j = 1;
  pos = 0;
  wait = 0;
  nooftries = 10;

  while (i < argc) {
    if (argv[i][0] == '-') {
      c = argv[i][j];
      switch (c) {
        case '\0':
          j = 1;
          i++;
          break;
        case '-' :
          j++;
          break;
        case 'h' :
          fprintf(stderr, "usage: %s -R [-i ipaddress] [-p port] address length\n", argv[0]);
          return 0;
          break;
        case 'i' : 
          j++;
          if(argv[i][j] == '\0'){
            j = 0;
            i++;
          }
          if(i >= argc){
            fprintf(stderr, "%s: option -%c requires a parameter\n", argv[0], c);
          }
          ip_addr = argv[i] + j;	
          i++;
          j = 1;
          break;
        case 'p' : 
          j++;
          if(argv[i][j] == '\0'){
            j = 0;
            i++;
          }
          if(i >= argc){
            fprintf(stderr, "%s: option -%c requires a parameter\n", argv[0], c);
          }
          port = atoi(argv[i] + j);	
#if DEBUG
          fprintf(stderr, "port number is %d\n", port);
#endif
          i++;
          j = 1;
          break;
        case 'R' : 
          rw_flag = 1;	
          i++;
          break;
        default:
          fprintf(stderr, "%s: unknown option -%c\n", argv[0], argv[i][j]);
          return 2;
      }
    } else {
      pos = i;
      i = argc;
    }
  }
  d = setup_katcp(STDOUT_FILENO);
  if(d == NULL){
    fprintf(stderr, "setup katcp failed\n");

    return EX_OSERR;
  }
  ud = create_udp(d);
  if(ud == NULL){
    fprintf(stderr, "create udp failed\n");
    log_message_katcp(d, KATCP_LEVEL_ERROR, DMON_MODULE_NAME, "unable to allocate local udp state");
    write_katcp(d);
    return EX_OSERR;
  }
#if 0
  if(connect_udp(d, ud, port) < 0){
    fprintf(stderr, "connect udp failed\n");
    log_message_katcp(d, KATCP_LEVEL_ERROR, DMON_MODULE_NAME, "unable to bind udp");
    return EX_OSERR;
  }
#endif
  ud->u_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if(ud->u_fd < 0){
    fprintf(stderr, "unable to create udp socket:\n ");
    log_message_katcp(d, KATCP_LEVEL_ERROR, DMON_MODULE_NAME, "unable to create udp socket: %s", strerror(errno));
    return -1;
  }
  ud->u_rw = rw_flag;

  for(;;){

    FD_ZERO(&fsr);

    FD_SET(ud->u_fd, &fsr);
    address = strtol(argv[pos], NULL, 16); 
    length  = strtol(argv[pos + 1], NULL, 16);

#if DEBUG
    printf("pos:%d, address[%x] and length[%x]\n", pos, address, length);
#endif

    send_udp(d, ud, ip_addr, port, address, length);

    now.tv_sec =  10;
    now.tv_usec = 0;
    result = select(ud->u_fd + 1, &fsr, NULL, NULL, &now);
    if(result == 0){
      /* Resend again after timeout */
      printf("Resending udp again\n");
      send_udp(d, ud, ip_addr, port, address, length);
    }

    for(wait = 0; wait < nooftries; wait++){

      if(FD_ISSET(ud->u_fd, &fsr)){
        result = rcv_udp(d, ud);
        if(!result){
          return EX_OK;
        }
      }
    }
    return EX_OSERR;

  }

  destroy_udp(d, ud);
  shutdown_katcp(d);

  return EX_OK;
}
Example #24
0
static int find_interface() {
	fd_set read_fds;
	struct mt_packet data;
	struct sockaddr_in myip;
	unsigned char emptymac[ETH_ALEN];
	int i, testsocket;
	struct timeval timeout;
	int optval = 1;

	/* TODO: reread interfaces on HUP */
	bzero(&interfaces, sizeof(struct net_interface) * MAX_INTERFACES);

	bzero(emptymac, ETH_ALEN);

	if (net_get_interfaces(interfaces, MAX_INTERFACES) <= 0) {
		fprintf(stderr, "Error: No suitable devices found\n");
		exit(1);
	}

	for (i = 0; i < MAX_INTERFACES; ++i) {
		if (!interfaces[i].in_use) {
			break;
		}

		/* Skip loopback interfaces */
		if (memcmp("lo", interfaces[i].name, 2) == 0) {
			continue;
		}

		/* Initialize receiving socket on the device chosen */
		myip.sin_family = AF_INET;
		memcpy((void *)&myip.sin_addr, interfaces[i].ipv4_addr, IPV4_ALEN);
		myip.sin_port = htons(sourceport);

		/* Initialize socket and bind to udp port */
		if ((testsocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
			continue;
		}

		setsockopt(testsocket, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval));
		setsockopt(testsocket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));

		if (bind(testsocket, (struct sockaddr *)&myip, sizeof(struct sockaddr_in)) == -1) {
			close(testsocket);
			continue;
		}

		/* Ensure that we have mac-address for this interface  */
		if (!interfaces[i].has_mac) {
			close(testsocket);
			continue;
		}

		/* Set the global socket handle and source mac address for send_udp() */
		send_socket = testsocket;
		memcpy(srcmac, interfaces[i].mac_addr, ETH_ALEN);
		active_interface = &interfaces[i];

		/* Send a SESSIONSTART message with the current device */
		init_packet(&data, MT_PTYPE_SESSIONSTART, srcmac, dstmac, sessionkey, 0);
		send_udp(&data, 0);

		timeout.tv_sec = connect_timeout;
		timeout.tv_usec = 0;

		FD_ZERO(&read_fds);
		FD_SET(insockfd, &read_fds);
		select(insockfd + 1, &read_fds, NULL, NULL, &timeout);
		if (FD_ISSET(insockfd, &read_fds)) {
			/* We got a response, this is the correct device to use */
			return 1;
		}

		close(testsocket);
	}
	return 0;
}
Example #25
0
/*
 * TODO: Rewrite main() when all sub-functionality is tested
 */
int main (int argc, char **argv) {
	int result;
	struct mt_packet data;
	struct sockaddr_in si_me;
	unsigned char buff[1500];
	unsigned char print_help = 0, have_username = 0, have_password = 0;
	int c;
	int optval = 1;

	while (1) {
		c = getopt(argc, argv, "nqt:u:p:vh?");

		if (c == -1) {
			break;
		}

		switch (c) {

			case 'n':
				use_raw_socket = 1;
				break;

			case 'u':
				/* Save username */
				strncpy(username, optarg, sizeof(username) - 1);
				username[sizeof(username) - 1] = '\0';
				have_username = 1;
				break;

			case 'p':
				/* Save password */
				strncpy(password, optarg, sizeof(password) - 1);
				password[sizeof(password) - 1] = '\0';
				have_password = 1;
				break;

			case 't':
				connect_timeout = atoi(optarg);
				break;

			case 'v':
				print_version();
				exit(0);
				break;

			case 'q':
				quiet_mode = 1;
				break;

			case 'h':
			case '?':
				print_help = 1;
				break;

		}
	}
	if (argc - optind < 1 || print_help) {
		print_version();
		fprintf(stderr, "Usage: %s <MAC|identity> [-h] [-n] [-t <timeout>] [-u <username>] [-p <password>]\n", argv[0]);

		if (print_help) {
			fprintf(stderr, "\nParameters:\n");
			fprintf(stderr, "  MAC       MAC-Address of the RouterOS/mactelnetd device. Use mndp to discover it.\n");
			fprintf(stderr, "  identity  The identity/name of your destination device. Uses MNDP protocol to find it.\n");
			fprintf(stderr, "  -n        Do not use broadcast packets. Less insecure but requires root privileges.\n");
			fprintf(stderr, "  -t        Amount of seconds to wait for a response on each interface.\n");
			fprintf(stderr, "  -u        Specify username on command line.\n");
			fprintf(stderr, "  -p        Specify password on command line.\n");
			fprintf(stderr, "  -q        Quiet mode.\n");
			fprintf(stderr, "  -h        This help.\n");
			fprintf(stderr, "\n");
		}
		return 1;
	}

	is_a_tty = isatty(fileno(stdout)) && isatty(fileno(stdin));
	if (!is_a_tty) {
		quiet_mode = 1;
	}

	/* Seed randomizer */
	srand(time(NULL));

	if (use_raw_socket) {
		if (geteuid() != 0) {
			fprintf(stderr, "You need to have root privileges to use the -n parameter.\n");
			return 1;
		}

		sockfd = net_init_raw_socket();
	}

	/* Receive regular udp packets with this socket */
	insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (insockfd < 0) {
		perror("insockfd");
		return 1;
	}

	if (!use_raw_socket) {
		if (setsockopt(insockfd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof (optval))==-1) {
			perror("SO_BROADCAST");
			return 1;
		}
	}

	/* Need to use, to be able to autodetect which interface to use */
	setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));

	/* Get mac-address from string, or check for hostname via mndp */
	if (!query_mndp_or_mac(argv[optind], dstmac, !quiet_mode)) {
		/* No valid mac address found, abort */
		return 1;
	}

	if (!have_username) {
		if (!quiet_mode) {
			printf("Login: "******"%254s", username);
	}

	if (!have_password) {
		char *tmp;
		tmp = getpass(quiet_mode ? "" : "Password: "******"255.255.255.255", &destip);
	memcpy(&sourceip, &(si_me.sin_addr), IPV4_ALEN);

	/* Sessioon key */
	sessionkey = rand() % 65535;

	/* stop output buffering */
	setvbuf(stdout, (char*)NULL, _IONBF, 0);

	if (!quiet_mode) {
		printf("Connecting to %s...", ether_ntoa((struct ether_addr *)dstmac));
	}

	/* Initialize receiving socket on the device chosen */
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(sourceport);

	/* Bind to udp port */
	if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me)) == -1) {
		fprintf(stderr, "Error binding to %s:%d, %s\n", inet_ntoa(si_me.sin_addr), sourceport, strerror(errno));
		return 1;
	}

	if (!find_interface() || (result = recvfrom(insockfd, buff, 1400, 0, 0, 0)) < 1) {
		fprintf(stderr, "Connection failed.\n");
		return 1;
	}
	if (!quiet_mode) {
		printf("done\n");
	}

	/* Handle first received packet */
	handle_packet(buff, result);

	init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, 0);
	outcounter +=  add_control_packet(&data, MT_CPTYPE_BEGINAUTH, NULL, 0);

	/* TODO: handle result of send_udp */
	result = send_udp(&data, 1);

	while (running) {
		fd_set read_fds;
		int reads;
		static int terminal_gone = 0;
		struct timeval timeout;

		/* Init select */
		FD_ZERO(&read_fds);
		if (!terminal_gone) {
			FD_SET(0, &read_fds);
		}
		FD_SET(insockfd, &read_fds);

		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		/* Wait for data or timeout */
		reads = select(insockfd+1, &read_fds, NULL, NULL, &timeout);
		if (reads > 0) {
			/* Handle data from server */
			if (FD_ISSET(insockfd, &read_fds)) {
				bzero(buff, 1500);
				result = recvfrom(insockfd, buff, 1500, 0, 0, 0);
				handle_packet(buff, result);
			}
			/* Handle data from keyboard/local terminal */
			if (FD_ISSET(0, &read_fds) && terminal_mode) {
				unsigned char keydata[512];
				int datalen;

				datalen = read(STDIN_FILENO, &keydata, 512);

				if (datalen > 0) {
					/* Data received, transmit to server */
					init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
					add_control_packet(&data, MT_CPTYPE_PLAINDATA, &keydata, datalen);
					outcounter += datalen;
					send_udp(&data, 1);
				} else {
					terminal_gone = 1;
				}
			}
		/* Handle select() timeout */
		} else {
			/* handle keepalive counter, transmit keepalive packet every 10 seconds
			   of inactivity  */
			if (keepalive_counter++ == 10) {
				struct mt_packet odata;
				init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, outcounter);
				send_udp(&odata, 0);
			}
		}
	}

	if (is_a_tty && terminal_mode) {
		/* Reset terminal back to old settings */
		reset_term();
	}

	close(sockfd);
	close(insockfd);

	return 0;
}
Example #26
0
static int handle_packet(unsigned char *data, int data_len) {
	struct mt_mactelnet_hdr pkthdr;
	parse_packet(data, &pkthdr);

	/* We only care about packets with correct sessionkey */
	if (pkthdr.seskey != sessionkey) {
		return -1;
	}

	/* Handle data packets */
	if (pkthdr.ptype == MT_PTYPE_DATA) {
		struct mt_packet odata;
		struct mt_mactelnet_control_hdr cpkt;
		int success = 0;

		/* Always transmit ACKNOWLEDGE packets in response to DATA packets */
		init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, pkthdr.counter + (data_len - MT_HEADER_LEN));
		send_udp(&odata, 0);

		/* Accept first packet, and all packets greater than incounter, and if counter has
		wrapped around. */
		if (incounter == 0 || pkthdr.counter > incounter || (incounter - pkthdr.counter) > 65535) {
			incounter = pkthdr.counter;
		} else {
			/* Ignore double or old packets */
			return -1;
		}

		/* Parse controlpacket data */
		success = parse_control_packet(data + MT_HEADER_LEN, data_len - MT_HEADER_LEN, &cpkt);

		while (success) {

			/* If we receive encryptionkey, transmit auth data back */
			if (cpkt.cptype == MT_CPTYPE_ENCRYPTIONKEY) {
				memcpy(encryptionkey, cpkt.data, cpkt.length);
				send_auth(username, password);
			}

			/* If the (remaining) data did not have a control-packet magic byte sequence,
			   the data is raw terminal data to be outputted to the terminal. */
			else if (cpkt.cptype == MT_CPTYPE_PLAINDATA) {
				cpkt.data[cpkt.length] = 0;
				printf("%s", cpkt.data);
			}

			/* END_AUTH means that the user/password negotiation is done, and after this point
			   terminal data may arrive, so we set up the terminal to raw mode. */
			else if (cpkt.cptype == MT_CPTYPE_END_AUTH) {

				/* we have entered "terminal mode" */
				terminal_mode = 1;

				if (is_a_tty) {
					/* stop input buffering at all levels. Give full control of terminal to RouterOS */
					raw_term();

					setvbuf(stdin,  (char*)NULL, _IONBF, 0);

					/* Add resize signal handler */
					signal(SIGWINCH, sig_winch);
				}
			}

			/* Parse next controlpacket */
			success = parse_control_packet(NULL, 0, &cpkt);
		}
	}
	else if (pkthdr.ptype == MT_PTYPE_ACK) {
		/* Handled elsewhere */
	}

	/* The server wants to terminate the connection, we have to oblige */
	else if (pkthdr.ptype == MT_PTYPE_END) {
		struct mt_packet odata;

		/* Acknowledge the disconnection by sending a END packet in return */
		init_packet(&odata, MT_PTYPE_END, srcmac, dstmac, pkthdr.seskey, 0);
		send_udp(&odata, 0);

		if (!quiet_mode) {
			fprintf(stderr, "Connection closed.\n");
		}

		/* exit */
		running = 0;
	} else {
		fprintf(stderr, "Unhandeled packet type: %d received from server %s\n", pkthdr.ptype, ether_ntoa((struct ether_addr *)dstmac));
		return -1;
	}

	return pkthdr.ptype;
}
Example #27
0
/* client program called with host name and port number of server */
int main(int argc, char *argv[])
{
    int sock, buflen;
    char send_buf[MAX_MES_LEN];
    bzero(send_buf, MAX_MES_LEN);
    struct hostent *hp, *gethostbyname();

    if(argc < 3) {
	printf("usage: cli remote_host_name remote_port_number\n");
	exit(1);
    }

    /* create socket for connecting to server */
    sock = socket(AF_INET, SOCK_DGRAM,0);
    if(sock < 0) {
	perror("opening datagram socket");
	exit(2);
    }

    /* construct name for connecting to server */
    name.sin_family = AF_INET;
    name.sin_port = htons(atoi(argv[2]));

    /* convert hostname to IP address and enter into name */
    hp = gethostbyname(argv[1]);
    if(hp == 0) {
	fprintf(stderr, "%s:unknown host\n", argv[1]);
	exit(3);
    }
    bcopy((char *)hp->h_addr, (char *)&name.sin_addr, hp->h_length);
    pid_t pid;
    char recv_buf[MAX_MES_LEN];
    if((pid = fork()) < 0){
	    perror("fork error!!!");
    } else if(pid == 0) {
	    printf("In the child process, process id is %d\n", getpid());
	    sprintf(send_buf,"msg send from child, process id %d\n", getpid());
	    send_udp(sock,send_buf);
	    if(recv(sock, recv_buf, MAX_MES_LEN,0)<0) {
		    perror("error recv msg");
		    exit(5);
	    }
	    printf("In child process %d, Client receives: %s\n", getpid(),recv_buf);

    } else {
	    printf("In the parent process, process id is %d\n", getpid());
	    sprintf(send_buf,"msg send from parent, process id %d\n", getpid());
	    send_udp(sock, send_buf);
	    if(recv(sock, recv_buf, MAX_MES_LEN,0)<0) {
		    perror("error recv msg");
		    exit(5);
	    }
	    printf("In parent process %d, Client receives: %s\n", getpid(), recv_buf);

    }
    sleep(5);
    bzero(send_buf, MAX_MES_LEN);
    strcpy(send_buf,"1");
    send_udp(sock,send_buf);
    if(recv(sock, recv_buf, MAX_MES_LEN,0)<0) {
	    perror("error recv msg");
	    exit(5);
    }
    printf("In process %d, Client receives: %s\n", getpid(), recv_buf);
    /* close connection */
    close(sock);
    return 0;
}
Example #28
0
/*
 * TODO: Rewrite main() when all sub-functionality is tested
 */
int main (int argc, char **argv) {
	int result;
	struct mt_packet data;
	struct sockaddr_in si_me;
	struct autologin_profile *login_profile;
	unsigned char buff[1500];
	unsigned char print_help = 0, have_username = 0, have_password = 0;
	unsigned char drop_priv = 0;
	int c;
	int optval = 1;

	strncpy(autologin_path, AUTOLOGIN_PATH, 254);

	setlocale(LC_ALL, "");
	bindtextdomain("mactelnet","/usr/share/locale");
	textdomain("mactelnet");

	while (1) {
		c = getopt(argc, argv, "lnqt:u:p:U:vh?BAa:");

		if (c == -1) {
			break;
		}

		switch (c) {

			case 'n':
				use_raw_socket = 1;
				break;

			case 'u':
				/* Save username */
				strncpy(username, optarg, sizeof(username) - 1);
				username[sizeof(username) - 1] = '\0';
				have_username = 1;
				break;

			case 'p':
				/* Save password */
#if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE)
				mlock(password, sizeof(password));
#endif
				strncpy(password, optarg, sizeof(password) - 1);
				password[sizeof(password) - 1] = '\0';
				have_password = 1;
				break;

			case 'U':
				/* Save nonpriv_username */
				strncpy(nonpriv_username, optarg, sizeof(nonpriv_username) - 1);
				nonpriv_username[sizeof(nonpriv_username) - 1] = '\0';
				drop_priv = 1;
				break;

			case 't':
				connect_timeout = atoi(optarg);
				mndp_timeout = connect_timeout;
				break;

			case 'v':
				print_version();
				exit(0);
				break;

			case 'q':
				quiet_mode = 1;
				break;

			case 'l':
				run_mndp = 1;
				break;

			case 'B':
				batch_mode = 1;
				break;

			case 'A':
				no_autologin = 1;
				break;

			case 'a':
				strncpy(autologin_path, optarg, 254);
				break;

			case 'h':
			case '?':
				print_help = 1;
				break;

		}
	}
	if (run_mndp) {
		return mndp(mndp_timeout, batch_mode);
	}
	if (argc - optind < 1 || print_help) {
		print_version();
		fprintf(stderr, _("Usage: %s <MAC|identity> [-h] [-n] [-a <path>] [-A] [-t <timeout>] [-u <user>] [-p <password>] [-U <user>] | -l [-B] [-t <timeout>]\n"), argv[0]);

		if (print_help) {
			fprintf(stderr, _("\nParameters:\n"
			"  MAC            MAC-Address of the RouterOS/mactelnetd device. Use mndp to\n"
			"                 discover it.\n"
			"  identity       The identity/name of your destination device. Uses\n"
			"                 MNDP protocol to find it.\n"
			"  -l             List/Search for routers nearby (MNDP). You may use -t to set timeout.\n"
			"  -B             Batch mode. Use computer readable output (CSV), for use with -l.\n"
			"  -n             Do not use broadcast packets. Less insecure but requires\n"
			"                 root privileges.\n"
			"  -a <path>      Use specified path instead of the default: " AUTOLOGIN_PATH " for autologin config file.\n"
			"  -A             Disable autologin feature.\n"
			"  -t <timeout>   Amount of seconds to wait for a response on each interface.\n"
			"  -u <user>      Specify username on command line.\n"
			"  -p <password>  Specify password on command line.\n"
			"  -U <user>      Drop privileges to this user. Used in conjunction with -n\n"
			"                 for security.\n"
			"  -q             Quiet mode.\n"
			"  -h             This help.\n"
			"\n"));
		}
		return 1;
	}

	is_a_tty = isatty(fileno(stdout)) && isatty(fileno(stdin));
	if (!is_a_tty) {
		quiet_mode = 1;
	}

	if (!no_autologin) {
		autologin_readfile(autologin_path);
		login_profile = autologin_find_profile(argv[optind]);

		if (!quiet_mode && login_profile != NULL && (login_profile->hasUsername || login_profile->hasPassword)) {
			fprintf(stderr, _("Using autologin credentials from %s\n"), autologin_path);
		}
		if (!have_username) {
			if (login_profile != NULL && login_profile->hasUsername) {
				have_username = 1;
				strncpy(username, login_profile->username, sizeof(username) - 1);
				username[sizeof(username) - 1] = '\0';
			}
		}

		if (!have_password) {
			if (login_profile != NULL && login_profile->hasPassword) {
				have_password = 1;
				strncpy(password, login_profile->password, sizeof(password) - 1);
				password[sizeof(password) - 1] = '\0';
			}
		}
	}

	/* Seed randomizer */
	srand(time(NULL));

	if (use_raw_socket) {
		if (geteuid() != 0) {
			fprintf(stderr, _("You need to have root privileges to use the -n parameter.\n"));
			return 1;
		}

		sockfd = net_init_raw_socket();

		if (drop_priv) {
			drop_privileges(nonpriv_username);
		}
	} else if (drop_priv) {
		fprintf(stderr, _("The -U option must be used in conjunction with the -n parameter.\n"));
		return 1;
	}

	/* Receive regular udp packets with this socket */
	insockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (insockfd < 0) {
		perror("insockfd");
		return 1;
	}

	if (!use_raw_socket) {
		if (setsockopt(insockfd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof (optval))==-1) {
			perror("SO_BROADCAST");
			return 1;
		}
	}

	/* Need to use, to be able to autodetect which interface to use */
	setsockopt(insockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof (optval));

	/* Get mac-address from string, or check for hostname via mndp */
	if (!query_mndp_or_mac(argv[optind], dstmac, !quiet_mode)) {
		/* No valid mac address found, abort */
		return 1;
	}

	if (!have_username) {
		if (!quiet_mode) {
			printf(_("Login: "******"%254s", username);
	}

	if (!have_password) {
		char *tmp;
		tmp = getpass(quiet_mode ? "" : _("Password: "******"255.255.255.255", &destip);
	memcpy(&sourceip, &(si_me.sin_addr), IPV4_ALEN);

	/* Session key */
	sessionkey = rand() % 65535;

	/* stop output buffering */
	setvbuf(stdout, (char*)NULL, _IONBF, 0);

	if (!quiet_mode) {
		printf(_("Connecting to %s..."), ether_ntoa((struct ether_addr *)dstmac));
	}

	/* Initialize receiving socket on the device chosen */
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(sourceport);

	/* Bind to udp port */
	if (bind(insockfd, (struct sockaddr *)&si_me, sizeof(si_me)) == -1) {
		fprintf(stderr, _("Error binding to %s:%d, %s\n"), inet_ntoa(si_me.sin_addr), sourceport, strerror(errno));
		return 1;
	}

	if (!find_interface() || (result = recvfrom(insockfd, buff, 1400, 0, 0, 0)) < 1) {
		fprintf(stderr, _("Connection failed.\n"));
		return 1;
	}
	if (!quiet_mode) {
		printf(_("done\n"));
	}

	/* Handle first received packet */
	handle_packet(buff, result);

	init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, 0);
	outcounter +=  add_control_packet(&data, MT_CPTYPE_BEGINAUTH, NULL, 0);

	/* TODO: handle result of send_udp */
	result = send_udp(&data, 1);

	while (running) {
		fd_set read_fds;
		int reads;
		static int terminal_gone = 0;
		struct timeval timeout;

		/* Init select */
		FD_ZERO(&read_fds);
		if (!terminal_gone) {
			FD_SET(0, &read_fds);
		}
		FD_SET(insockfd, &read_fds);

		timeout.tv_sec = 1;
		timeout.tv_usec = 0;

		/* Wait for data or timeout */
		reads = select(insockfd+1, &read_fds, NULL, NULL, &timeout);
		if (reads > 0) {
			/* Handle data from server */
			if (FD_ISSET(insockfd, &read_fds)) {
				bzero(buff, 1500);
				result = recvfrom(insockfd, buff, 1500, 0, 0, 0);
				handle_packet(buff, result);
			}
			/* Handle data from keyboard/local terminal */
			if (FD_ISSET(0, &read_fds) && terminal_mode) {
				unsigned char keydata[512];
				int datalen;

				datalen = read(STDIN_FILENO, &keydata, 512);

				if (datalen > 0) {
					/* Data received, transmit to server */
					init_packet(&data, MT_PTYPE_DATA, srcmac, dstmac, sessionkey, outcounter);
					add_control_packet(&data, MT_CPTYPE_PLAINDATA, &keydata, datalen);
					outcounter += datalen;
					send_udp(&data, 1);
				} else {
					terminal_gone = 1;
				}
			}
		/* Handle select() timeout */
		} else {
			/* handle keepalive counter, transmit keepalive packet every 10 seconds
			   of inactivity  */
			if (keepalive_counter++ == 10) {
				struct mt_packet odata;
				init_packet(&odata, MT_PTYPE_ACK, srcmac, dstmac, sessionkey, outcounter);
				send_udp(&odata, 0);
			}
		}
	}

	if (is_a_tty && terminal_mode) {
		/* Reset terminal back to old settings */
		reset_term();
	}

	close(sockfd);
	close(insockfd);

	return 0;
}
Example #29
0
void sendto_call_handler(unsigned long long uniqueSockID, int threads,
		unsigned char *buf, ssize_t len) {

	int index;
	int datalen;
	int flags;
	u_char *data;
	socklen_t addrlen;
	struct sockaddr_in *addr;
	u_char *pt;

	PRINT_DEBUG("");

	pt = buf;

	datalen = *(int *) pt;
	pt += sizeof(int);

	PRINT_DEBUG("passed data len = %d", datalen);
	if (datalen <= 0) {
		PRINT_DEBUG("DATA Field is empty!!");
		nack_send(uniqueSockID, sendto_call);
		return;
	}

	data = (u_char *) malloc(datalen);
	PRINT_DEBUG("");

	memcpy(data, pt, datalen);
	pt += datalen;

	PRINT_DEBUG("");

	flags = *(int *) pt;
	pt += sizeof(int);

	PRINT_DEBUG("");

	addrlen = *(socklen_t *) pt;
	pt += sizeof(socklen_t);

	PRINT_DEBUG("");

	addr = (struct sockaddr_in *) malloc(addrlen);

	memcpy(addr, pt, addrlen);
	pt += addrlen;

	PRINT_DEBUG("");

	if (pt - buf != len) {
		PRINT_DEBUG("READING ERROR! CRASH, diff=%d len=%d", pt - buf, len);
		nack_send(uniqueSockID, sendto_call);
		return;
	}

	index = findjinniSocket(uniqueSockID);
	if (index == -1) {
		PRINT_DEBUG(
				"CRASH !!! socket descriptor not found into jinni sockets SO pipe descriptor to reply is notfound too ");
		nack_send(uniqueSockID, sendto_call);
		return;
	}
	PRINT_DEBUG("");

	/**
	 *
	 * In case a connected socket has been called by mistake using sendto
	 * (IGNORE THE ADDRESSES AND USET THE ADDRESS THE SOCKET IS CONNECTED TO IT)
	 */

	if (jinniSockets[index].connection_status > 0) {

		if (jinniSockets[index].type == SOCK_DGRAM)
			send_udp(uniqueSockID, sendto_call, datalen, data, flags);
		else if (jinniSockets[index].type == SOCK_STREAM)
			send_tcp(uniqueSockID, sendto_call, datalen, data, flags);
		else if (jinniSockets[index].type == SOCK_RAW) {

		} else {
			PRINT_DEBUG("unknown socket type has been read !!!");
			nack_send(uniqueSockID, sendto_call);
		}

	} else {
		/**
		 * The default case , the socket is not connected socket
		 */

		if (jinniSockets[index].type == SOCK_DGRAM)
			sendto_udp(uniqueSockID, sendto_call, datalen, data, flags, addr,
					addrlen);
		else if (jinniSockets[index].type == SOCK_STREAM)
			sendto_tcp(uniqueSockID, sendto_call, datalen, data, flags, addr,
					addrlen);
		else if (jinniSockets[index].type == SOCK_RAW) {

		} else {
			PRINT_DEBUG("unknown socket type has been read !!!");
			nack_send(uniqueSockID, sendto_call);
		}

	}
	PRINT_DEBUG();
	return;

} //end of sendto_call_handler()
void sendto_udp(int senderid,int sockfd,int datalen,u_char *data,int flags,
		struct sockaddr *addr,socklen_t addrlen)
{

		uint16_t hostport;
		uint16_t dstport;
		uint32_t host_IP;
		uint32_t dst_IP;

		int len=datalen;
		int index;

		/** check if the original call is either (sendto) or (send) or (write)*/
		if ( (addr == NULL) &&  (addrlen == 0) && (flags != -1000) )
		{
			/** In case of (send) */
			PRINT_DEBUG();
	return ( send_udp(senderid,sockfd,datalen,data,flags) ) ;

		}

		if ( (addr == NULL) &&  (addrlen == 0) && (flags == -1000))
		{
			PRINT_DEBUG();

			/** In case of (write) */
			 return ( write_udp (senderid,sockfd,datalen,data) ) ;
		}
		PRINT_DEBUG();

		/** TODO handle flags cases */
			switch (flags)
			{
			case MSG_CONFIRM:
			case MSG_DONTROUTE:
			case MSG_DONTWAIT :
			case MSG_EOR:
			case MSG_MORE :
			case MSG_NOSIGNAL:
			case MSG_OOB: /** case of recieving a (write call)*/
			default:
			break;


			}
		PRINT_DEBUG("");

		struct sockaddr_in *address;
		address = (struct sockaddr_in *) addr;
		/** TODO lock access to the jinnisockets */

		index = findjinniSocket(senderid,sockfd);
		PRINT_DEBUG("");

		/** TODO unlock access to the jinnisockets */
		if (index == -1)
			{
				PRINT_DEBUG("CRASH !! socket descriptor not found into jinni sockets");
				exit(1);
			}

		if (address->sin_family != AF_INET )
		{
			PRINT_DEBUG("Wrong address family");
			PRINT_DEBUG("");

			sem_wait(jinniSockets[index].s);
				PRINT_DEBUG("");

				nack_write(jinniSockets[index].jinniside_pipe_ds,senderid,sockfd);
				sem_post(jinniSockets[index].as);

			sem_post(jinniSockets[index].s);
			PRINT_DEBUG("");

		}

/** copying the data passed to be able to free the old memory location
 * the new created location is the one to be included into the newly created finsFrame*/
		PRINT_DEBUG("");

/** Keep all ports and addresses in host order until later  action taken */
dstport =ntohs( address->sin_port); /** reverse it since it is in network order after application used htons */
if (dst_IP != INADDR_LOOPBACK)
dst_IP = ntohl(address-> sin_addr.s_addr);/** it is in network format since application used htonl */
else
	dst_IP = ntohl(address-> sin_addr.s_addr);
//hostport = jinniSockets[index].hostport;
hostport = 3000;
host_IP = jinniSockets[index].host_IP;
PRINT_DEBUG("");

PRINT_DEBUG("%d,%d,%d,%d", dst_IP, dstport, host_IP,hostport);
//free(data);
//free(addr);
PRINT_DEBUG("");

/** the meta-data paraters are all passes by copy starting from this point
 *
 */
if (jinni_UDP_to_fins(data,len,dstport,dst_IP,hostport,host_IP)== 1)

{
	PRINT_DEBUG("");
 /** TODO prevent the socket interceptor from holding this semaphore before we reach this point */
	sem_wait(jinniSockets[index].s);
		PRINT_DEBUG("");

		ack_write(jinniSockets[index].jinniside_pipe_ds,senderid,sockfd);
		sem_post(jinniSockets[index].as);

	sem_post(jinniSockets[index].s);
	PRINT_DEBUG("");

}
else
{
	PRINT_DEBUG("socketjinni failed to accomplish sendto");
	sem_wait(jinniSockets[index].s);
		nack_write(jinniSockets[index].jinniside_pipe_ds,senderid,sockfd);
		sem_post(jinniSockets[index].as);

	sem_post(jinniSockets[index].s);

}


return;

} //end of sendto_udp