Ejemplo n.º 1
0
void log_enabled_syscalls_biarch(void)
{
	struct syscallentry *entry;
	struct msg_syscallsenabled *udpmsg;
	int *entries;
	unsigned int i;
	unsigned int index = 0;
	unsigned int size = sizeof(struct msg_syscallsenabled);

	/* First the 64bit syscalls */
	size += shm->nr_active_64bit_syscalls * sizeof(unsigned int);
	udpmsg = zmalloc(size);
	init_msghdr(&udpmsg->hdr, SYSCALLS_ENABLED);
	udpmsg->nr_enabled = shm->nr_active_64bit_syscalls;
	udpmsg->arch_is_biarch = TRUE;
	udpmsg->is_64 = TRUE;
	entries = udpmsg->entries;

	for_each_64bit_syscall(i) {
		entry = syscalls_64bit[i].entry;
		if (entry == NULL)
			continue;

		if (entry->flags & ACTIVE)
			entries[index++] = i;
	}

	sendudp((char *) udpmsg, size);
	free(udpmsg);

	/* Now send the 32bit syscalls */
	index = 0;
	size = sizeof(struct msg_syscallsenabled);
	size += shm->nr_active_32bit_syscalls * sizeof(unsigned int);
	udpmsg = zmalloc(size);
	init_msghdr(&udpmsg->hdr, SYSCALLS_ENABLED);
	udpmsg->nr_enabled = shm->nr_active_32bit_syscalls;
	udpmsg->arch_is_biarch = TRUE;
	udpmsg->is_64 = FALSE;
	entries = udpmsg->entries;

	for_each_32bit_syscall(i) {
		entry = syscalls_32bit[i].entry;
		if (entry == NULL)
			continue;

		if (entry->flags & ACTIVE)
			entries[index++] = i;
	}
	sendudp((char *) udpmsg, size);
	free(udpmsg);
}
Ejemplo n.º 2
0
static int
tryudpsend(struct silly_socket *ss, struct cmdpacket *cmd)
{
        struct socket *s = checksocket(ss, cmd->u.udpsend.sid);
        uint8_t *data = cmd->u.udpsend.data;
        size_t sz = cmd->u.udpsend.size;
        const struct sockaddr *addr = &cmd->u.udpsend.to;
        if (s == NULL) {
                silly_free(data);
                return 0;
        }
        assert(s->protocol == PROTOCOL_UDP);
        if (s->type == STYPE_SOCKET) //udp client need no address
                addr = NULL;
        if (wlist_empty(s)) {//try send
                ssize_t n = sendudp(s->fd, data, sz, addr);
                if (n == -1 || n >= 0) {        //occurs error or send ok
                        silly_free(data);
                        return 0;
                }
                assert(n == -2);        //EAGAIN 
                wlist_append(s, data, 0, sz, addr);
        } else {
                wlist_append(s, data, 0, sz, addr);
        }
        return 0;
}
Ejemplo n.º 3
0
static void
send_msg_udp(struct silly_socket *ss, struct socket *s)
{
        struct wlist *w;
        w = s->wlhead.next;
        assert(w);
        while (w) {
                ssize_t sz;
                sz = sendudp(s->fd, w->buff + w->offset, w->size, &w->udpaddress);
                if (sz == -2)   //EAGAIN, so block it
                        break;
                assert(sz == -1 || sz == w->size);
                //send fail && send ok will clear
                s->wlhead.next = w->next;
                silly_free(w->buff);
                silly_free(w);
                w = s->wlhead.next;
                if (w == NULL) {//send all
                        s->wltail = &s->wlhead;
                        sp_write_enable(ss->spfd, s->fd, s, 0);
                        if (s->type == STYPE_HALFCLOSE)
                                delsocket(ss, s);
                }
        }
        return ;
}
Ejemplo n.º 4
0
/* send error message back. */
static void
tftp_senderr(struct tftp_handle *h, u_short errcode, const char *msg)
{
	struct {
		u_char header[HEADER_SIZE];
		struct tftphdr  t;
		u_char space[63]; /* +1 from t */
	} __packed __aligned(4) wbuf;
	char           *wtail;
	int             len;

	len = strlen(msg);
	if (len > sizeof(wbuf.space))
		len = sizeof(wbuf.space);

	wbuf.t.th_opcode = htons((u_short) ERROR);
	wbuf.t.th_code   = htons(errcode);

	wtail = wbuf.t.th_msg;
	bcopy(msg, wtail, len);
	wtail[len] = '\0';
	wtail += len + 1;

	sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
}
Ejemplo n.º 5
0
void do_syscall(struct syscallrecord *rec)
{
	struct syscallentry *entry;
	struct msg_syscallprep scmsg;
	struct childdata *child = this_child();
	unsigned int call;

	init_msgchildhdr(&scmsg.hdr, SYSCALL_PREP, pids[child->num], child->num);
	scmsg.sequence_nr = child->op_nr;
	scmsg.nr = rec->nr;
	scmsg.is32bit = rec->do32bit;
	scmsg.a1 = rec->a1;
	scmsg.a2 = rec->a2;
	scmsg.a3 = rec->a3;
	scmsg.a4 = rec->a4;
	scmsg.a5 = rec->a5;
	scmsg.a6 = rec->a6;
	rec->tp = scmsg.hdr.tp;
	sendudp((char *) &scmsg, sizeof(scmsg));

	call = rec->nr;
	entry = syscalls[call].entry;

	if (entry->flags & EXTRA_FORK)
		do_extrafork(rec);
	else
		 /* common-case, do the syscall in this child process. */
		__do_syscall(rec, BEFORE);

	/* timestamp again for when we returned */
	clock_gettime(CLOCK_MONOTONIC, &rec->tp);
}
Ejemplo n.º 6
0
static void
tftp_sendack(struct tftp_handle *h)
{
	struct {
		u_char header[HEADER_SIZE];
		struct tftphdr  t;
	} __packed __aligned(4) wbuf;
	char           *wtail;

	wbuf.t.th_opcode = htons((u_short) ACK);
	wtail = (char *) &wbuf.t.th_block;
	wbuf.t.th_block = htons((u_short) h->currblock);
	wtail += 2;

	sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
}
Ejemplo n.º 7
0
void send_dvr_message(struct node* src, char* dest)
{
    // create msg
    char message[BUFSIZE];

    struct routing_table_entry *rte = src->routing_table;
    while (rte != NULL)
    {
        if (strcmp(rte->through, dest) != 0)
        {
            bzero(message, BUFSIZE);
            sprintf(message, msgformat, src->name, rte->name, rte->weight);
            sendudp(src->name, message, dest);
        }
        rte = rte->next;
    }
}
Ejemplo n.º 8
0
/** @brief function for sending demultiplexed data.
 */
void send_func (mumudvb_channel_t *channel, uint64_t now_time, struct unicast_parameters_t *unicast_vars, multi_p_t *multi_p, fds_t *fds)
{
	//For bandwith measurement (traffic)
	pthread_mutex_lock(&channel->stats_lock);
	channel->sent_data+=channel->nb_bytes+20+8; // IP=20 bytes header and UDP=8 bytes header
	if (multi_p->rtp_header) channel->sent_data+=RTP_HEADER_LEN;
	pthread_mutex_unlock(&channel->stats_lock);


		/********** MULTICAST *************/
		//if the multicast TTL is set to 0 we don't send the multicast packets
		if(multi_p->multicast)
		{
			unsigned char *data;
			int data_len;
			if(multi_p->rtp_header)
			{
				/****** RTP *******/
				rtp_update_sequence_number(channel,now_time);
				data=channel->buf_with_rtp_header;
				data_len=channel->nb_bytes+RTP_HEADER_LEN;
			}
			else
			{
				data=channel->buf;
				data_len=channel->nb_bytes;
			}
			if(multi_p->multicast_ipv4)
				sendudp (channel->socketOut4,
						&channel->sOut4,
						data,
						data_len);
			if(multi_p->multicast_ipv6)
				sendudp6 (channel->socketOut6,
						&channel->sOut6,
						data,
						data_len);
		}
	/*********** UNICAST **************/
	unicast_data_send(channel, fds, unicast_vars);
	/********* END of UNICAST **********/
	channel->nb_bytes = 0;

}
Ejemplo n.º 9
0
int main(int argc, char **argv)
{
 char *saddr,*daddr,*community;
 unsigned char *buf;
 int size;
 int sock;
 unsigned long lsaddr,ldaddr;
 int i;

 saddr = NULL;
 daddr = NULL;
 if (argc != 7) { usage(); erexit("not enough args\n"); }

 if (!strcmp(argv[1],"-s"))
   saddr = strdup(argv[2]);
 if (!strcmp(argv[3],"-d"))
   daddr = strdup(argv[4]);
 if (!strcmp(argv[5],"-c"))
   community = strdup(argv[6]);

 printf("Ok, spoofing packets from %s to %s\n",saddr,daddr);

 if (inet_addr(saddr) == -1 || inet_addr(daddr) == -1)
   erexit("Invalid source/destination IP address\n");

 if (saddr == NULL) { usage(); erexit("No Source Address"); }
 if (daddr == NULL) { usage(); erexit("No Dest Address"); }

 sock = socket(AF_INET,SOCK_RAW,IPPROTO_RAW);
 if (sock == -1)
   erexit("Couldnt open Raw socket!(Are you root?)\n");

 lsaddr = inet_addr(saddr);
 ldaddr = inet_addr(daddr);

 buf = makereq(community,&size);

 sendudp(sock,&lsaddr,&ldaddr,32788,161,buf,size);
 fprintf(stdout,"Sent packet. SNMPd must be down.\n");
 return 0;

}
Ejemplo n.º 10
0
/* Transmit a bootp request */
static ssize_t
bootpsend(struct iodesc *d, void *pkt, size_t len)
{
	struct bootp *bp;

#ifdef BOOTP_DEBUG
	if (debug)
		printf("bootpsend: d=%lx called.\n", (long)d);
#endif

	bp = pkt;
	bp->bp_secs = htons((u_short)(getsecs() - bot));

#ifdef BOOTP_DEBUG
	if (debug)
		printf("bootpsend: calling sendudp\n");
#endif

	return (sendudp(d, pkt, len));
}
Ejemplo n.º 11
0
void
tftp_terminate(struct tftp_handle *h)
{
	struct {
		u_char header[HEADER_SIZE];
		struct tftphdr t;
	} wbuf;
	char           *wtail;

	bzero(&wbuf, sizeof(wbuf));

	if (h->islastblock) {
		wbuf.t.th_opcode = htons((u_short) ACK);
		wbuf.t.th_block = htons((u_short) h->currblock);
	} else {
		wbuf.t.th_opcode = htons((u_short) ERROR);
		wbuf.t.th_code = htons((u_short) ENOSPACE); /* ??? */
	}
	wtail = (char *) &wbuf.t.th_data;

	(void) sendudp(h->iodesc, &wbuf.t, wtail - (char *) &wbuf.t);
}
Ejemplo n.º 12
0
void *gossiper(void *params)
{
  int i;
  int no_entry;
  int ret;
  struct two_hosts host_table[2];
 // char *message = (char *)malloc(500);
  while(1){
      char *message = (char *)malloc(500);
      initialize_two_hosts(host_table);
      no_entry=choose_n_hosts(host_table,2);
      ret = create_message(message);
      if(!no_entry)
         goto Sleep;
      for(i=0;i<MAX_CHOSEN_HOSTS;i++){
          if(host_table[i].valid)     
             sendudp(hb_table[host_table[i].host_id].IP,hb_table[host_table[i].host_id].port,message);
      }
     free(message);
    Sleep:  sleep(2);
  }
}
Ejemplo n.º 13
0
/* ack block, expect next */
static int 
tftp_getnextblock(struct tftp_handle *h)
{
	struct {
		u_char header[HEADER_SIZE];
		struct tftphdr t;
	} __packed __aligned(4) wbuf;
	char           *wtail;
	int             res;
	struct tftphdr *t;
	unsigned short rtype = 0;
	wbuf.t.th_opcode = htons((u_short) ACK);
	wtail = (char *) &wbuf.t.th_block;
	wbuf.t.th_block = htons((u_short) h->currblock);
	wtail += 2;

	t = &h->lastdata.t;

	h->iodesc->xid = h->currblock + 1;	/* expected block */

	res = sendrecv_tftp(h, &sendudp, &wbuf.t, wtail - (char *) &wbuf.t,
		       &recvtftp, t, sizeof(*t) + h->tftp_blksize, &rtype);

	if (res == -1)		/* 0 is OK! */
		return (errno);

	h->currblock++;
	h->validsize = res;
	if (res < h->tftp_blksize)
		h->islastblock = 1;	/* EOF */

	if (h->islastblock == 1) {
		/* Send an ACK for the last block */ 
		wbuf.t.th_block = htons((u_short) h->currblock);
		sendudp(h->iodesc, &wbuf.t, wtail - (char *)&wbuf.t);
	}

	return (0);
}
Ejemplo n.º 14
0
void map_dump(struct object *obj, bool global)
{
	struct map *m;
	struct msg_objcreatedmap objmsg;
	char buf[11];
	int len;

	m = &obj->map;

	init_msgobjhdr(&objmsg.hdr, OBJ_CREATED_MAP, global, obj);
	objmsg.start = m->ptr;
	len = strlen(m->name);
	strncpy(objmsg.name, m->name, len);
	memset(objmsg.name + len, 0, MAPS_NAME_MAX_LEN - len);
	objmsg.prot = m->prot;
	objmsg.type = m->type;
	objmsg.size = m->size;
	sendudp((char *) &objmsg, sizeof(objmsg));

	sizeunit(m->size, buf);
	output(2, " start: %p size:%s  name: %s\n", m->ptr, buf, m->name);
}
Ejemplo n.º 15
0
int main( int argc, char * argv[] )
{
    socketdesc sd;         /* socket descriptor index */
    long n;                /* number of bytes received */
    char sendline[MSGSIZE];   /* send buffer */
    char recvline[MSGSIZE+1]; /* recieve buffer */

    /* need an ip address.. localhost or 127.0.0.1 would work for
       our test case */
    if (argc != 2 )
    {
        fprintf( stderr, "echo <ip address>\n" );
        exit(1);
    }

    initudp();
    sd = openudp( FALSE, argv[1], 2007 );

    if ( sd < 0 )
    {
        fprintf( stderr, "error occured while connecting\n" );
        exit(1);
    }

    while ( fgets( sendline, MSGSIZE, stdin ) != NULL )
    {
        sendudp( sd, sendline, strlen(sendline), argv[1] );
      
        n = recvudp( sd, recvline, MSGSIZE, NULL );
        recvline[n] = '\0';
        fputs(recvline, stdout);
    }

    closeudp( sd );

    return 0;
}
Ejemplo n.º 16
0
static void socket_destructor(struct object *obj)
{
	struct socketinfo *si = &obj->sockinfo;
	struct linger ling = { .l_onoff = FALSE, .l_linger = 0 };
	int fd;

	//FIXME: This is a workaround for a weird bug where we hang forevre
	// waiting for bluetooth sockets when we setsockopt.
	// Hopefully at some point we can remove this when someone figures out what's going on.
	if (si->triplet.family == PF_BLUETOOTH)
		return;

	/* Grab an fd, and nuke it before someone else uses it. */
	fd = si->fd;
	si->fd = 0;

	/* disable linger */
	(void) setsockopt(fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(struct linger));

	(void) shutdown(fd, SHUT_RDWR);

	if (close(fd) != 0)
		output(1, "failed to close socket [%d:%d:%d].(%s)\n",
			si->triplet.family,
			si->triplet.type,
			si->triplet.protocol,
			strerror(errno));
}

static void socket_dump(struct object *obj, bool global)
{
	struct socketinfo *si = &obj->sockinfo;
	struct msg_objcreatedsocket objmsg;

	output(2, "socket fd:%d domain:%u (%s) type:0x%u protocol:%u\n",
		si->fd, si->triplet.family, get_domain_name(si->triplet.family),
		si->triplet.type, si->triplet.protocol);

	init_msgobjhdr(&objmsg.hdr, OBJ_CREATED_SOCKET, global, obj);
	objmsg.si.fd = si->fd;
	objmsg.si.triplet.family = si->triplet.family;
	objmsg.si.triplet.type = si->triplet.type;
	objmsg.si.triplet.protocol = si->triplet.protocol;
	sendudp((char *) &objmsg, sizeof(objmsg));
}

static int open_sockets(void)
{
	struct objhead *head;
	int bytesread = -1;
	int ret;

	head = get_objhead(OBJ_GLOBAL, OBJ_FD_SOCKET);
	head->destroy = &socket_destructor;
	head->dump = &socket_dump;

	cachefile = open(cachefilename, O_RDONLY);
	if (cachefile < 0) {
		output(1, "Couldn't find socket cachefile. Regenerating.\n");
		ret = generate_sockets();
		output(1, "created %d sockets\n", nr_sockets);
		return ret;
	}

	lock_cachefile(F_RDLCK);

	while (bytesread != 0) {
		unsigned int domain, type, protocol;
		unsigned int buffer[3];
		int fd;

		bytesread = read(cachefile, buffer, sizeof(int) * 3);
		if (bytesread == 0) {
			if (nr_sockets == 0)
				goto regenerate;
			break;
		}

		domain = buffer[0];
		type = buffer[1];
		protocol = buffer[2];

		if (domain >= TRINITY_PF_MAX) {
			output(1, "cachefile contained invalid domain %u\n", domain);
			goto regenerate;
		}

		if ((do_specific_domain == TRUE && domain != specific_domain) ||
		    (no_domains[domain] == TRUE)) {
			output(1, "ignoring socket cachefile due to specific "
			       "protocol request (or protocol disabled), "
			       "and stale data in cachefile.\n");
regenerate:
				unlock_cachefile();	/* drop the reader lock. */
				close(cachefile);
				unlink(cachefilename);

				ret = generate_sockets();
				return ret;
		}

		fd = open_socket(domain, type, protocol);
		if (fd < 0) {
			output(1, "Cachefile is stale. Need to regenerate.\n");
			goto regenerate;
		}

		/* check for ctrl-c */
		if (shm->exit_reason != STILL_RUNNING) {
			close(cachefile);
			return FALSE;
		}
	}

	output(1, "%d sockets created based on info from socket cachefile.\n", nr_sockets);

	unlock_cachefile();
	close(cachefile);

	return TRUE;
}

struct socketinfo * get_rand_socketinfo(void)
{
	struct object *obj;

	/* When using victim files, sockets can be 0. */
	if (objects_empty(OBJ_FD_SOCKET) == TRUE)
		return NULL;

	obj = get_random_object(OBJ_FD_SOCKET, OBJ_GLOBAL);
	return &obj->sockinfo;
}

static int get_rand_socket_fd(void)
{
	struct socketinfo *sockinfo;

	sockinfo = get_rand_socketinfo();
	if (sockinfo == NULL)
		return -1;

	return sockinfo->fd;
}

int fd_from_socketinfo(struct socketinfo *si)
{
	if (si != NULL) {
		if (!(ONE_IN(1000)))
			return si->fd;
	}
	return get_random_fd();
}

static const struct fd_provider socket_fd_provider = {
	.name = "sockets",
	.enabled = TRUE,
	.open = &open_sockets,
	.get = &get_rand_socket_fd,
};

REG_FD_PROV(socket_fd_provider);
Ejemplo n.º 17
0
/** @brief function for sending demultiplexed data.
 */
void send_func (mumudvb_channel_t *channel, uint64_t *now_time, struct unicast_parameters_t *unicast_vars, multicast_parameters_t *multicast_vars,mumudvb_chan_and_pids_t *chan_and_pids, fds_t *fds)
{
		        //For bandwith measurement (traffic)
		        channel->sent_data+=channel->nb_bytes+20+8; // IP=20 bytes header and UDP=8 bytes header
		        if (multicast_vars->rtp_header) channel->sent_data+=RTP_HEADER_LEN;

		        /********* TRANSCODE **********/
	#ifdef ENABLE_TRANSCODING
			if (NULL != channel->transcode_options.enable &&
				1 == *channel->transcode_options.enable) {

			if (NULL == channel->transcode_handle) {

				strcpy(channel->transcode_options.ip, channel->ip4Out);

				channel->transcode_handle = transcode_start_thread(channel->socketOut4,
				&channel->sOut4, &channel->transcode_options);
			}

			if (NULL != channel->transcode_handle) {
				transcode_enqueue_data(channel->transcode_handle,
				channel->buf,
						   channel->nb_bytes);
			}
			}

			if (NULL == channel->transcode_options.enable ||
				1 != *channel->transcode_options.enable ||
				((NULL != channel->transcode_options.streaming_type &&
				STREAMING_TYPE_MPEGTS != *channel->transcode_options.streaming_type)&&
				(NULL == channel->transcode_options.send_transcoded_only ||
				 1 != *channel->transcode_options.send_transcoded_only)))
	#endif
		        /********** MULTICAST *************/
		         //if the multicast TTL is set to 0 we don't send the multicast packets
		        if(multicast_vars->multicast)
			{
			  unsigned char *data;
			  int data_len;
			  if(multicast_vars->rtp_header)
			  {
			/****** RTP *******/
			rtp_update_sequence_number(channel,*now_time);
			data=channel->buf_with_rtp_header;
			data_len=channel->nb_bytes+RTP_HEADER_LEN;
			  }
			  else
			{
			  data=channel->buf;
			  data_len=channel->nb_bytes;
			}
			  if(multicast_vars->multicast_ipv4)
			sendudp (channel->socketOut4,
				 &channel->sOut4,
				 data,
				 data_len);
			  if(multicast_vars->multicast_ipv6)
			sendudp6 (channel->socketOut6,
				 &channel->sOut6,
				 data,
				 data_len);
			}
		        /*********** UNICAST **************/
			unicast_data_send(channel, chan_and_pids->channels, fds, unicast_vars);
		        /********* END of UNICAST **********/
			channel->nb_bytes = 0;

}
Ejemplo n.º 18
0
Archivo: echod.c Proyecto: ibara/echod
int
main(int argc, char *argv[])
{
	fd_set 		set;
	int 		ch, uflag = 0;
	struct passwd  *pw;

	if (geteuid() != 0) {
		(void) fprintf(stderr, "%s: need root privileges\n",
			       __progname);
		exit(1);
	}
	pw = getpwnam("_echod");
	if (pw == NULL) {
		(void) fprintf(stderr, "%s: no _echod user\n", __progname);
		exit(1);
	}

	while ((ch = getopt(argc, argv, "u")) != -1) {
		switch (ch) {
		case 'u':
			uflag = 1;
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}
	argc -= optind;
	argv += optind;

	openlog("echod", LOG_PID | LOG_NDELAY, LOG_DAEMON);

	/* Start TCP and UDP protocols separately. */
	starttcp();
	if (uflag)
		startudp();

	/* Drop privileges */
	if (chroot("/var/empty") != 0 || chdir("/") != 0) {
		(void) fprintf(stderr, "%s: could not chroot\n", __progname);
		exit(1);
	}
	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid)) {
		(void) fprintf(stderr, "%s: can't drop privileges\n",
			       __progname);
		exit(1);
	}

        if (daemon(0, 0) < 0) {
                (void) fprintf(stderr, "%s: unable to daemonize\n", __progname);
		exit(1);
	}

#ifdef __OpenBSD__
	if ((ch = pledge("stdio inet proc", NULL)) == -1) {
		fprintf(stderr, "%s: pledge(2) failed: %s\n", __progname,
			strerror(errno));
		exit(1);
	}
#endif

	signal(SIGCHLD, SIG_IGN);
	signal(SIGUSR1, quit);

	FD_ZERO(&set);

	while (1) {
		FD_SET(tcpfd, &set);
		if (uflag)
			FD_SET(udpfd, &set);

		if (select(MAX(tcpfd, udpfd) + 1, &set, NULL, NULL, NULL) < 0) {
			syslog(LOG_ERR, "%s", strerror(errno));
			exit(1);
		}

		if (tcpfd > -1 && FD_ISSET(tcpfd, &set))
			sendtcp();

		if (uflag && udpfd > -1 && FD_ISSET(udpfd, &set))
			sendudp();
	}

	return 0;
}
Ejemplo n.º 19
0
int main (int argc, char *argv[])
{
  fd_set readset;
  fd_set writeset;
  int n, sel;
  int c, errflg=0;
  struct sigaction sigact;
  sigset_t sigmask;
  char *scratch, *next_scratch;
  char nmea_buf[1024];
  char send_buf[1024];
  int  gps_buf[15];
  int  nmea_index = 0;
  int  send_len = 0;
  /* Set default options */
  outfile = stdout;
  int sAnt = 0;

  memset(gps_buf, 0, 15);
  memset(send_buf, 0, 1024);
  send_len = 0;

  /* Process options */
  while ((c = getopt(argc, argv, "Vlqvs:o:p:t:m:u:g:/:")) != EOF)
    switch (c) {
      case 'q':
	quiet=1;
	break;
      case 'v':
        verbose = 1;
        break;
      case 'l':
        linebuff = 1;
        break;
      case 'p':
        opt_ptyname = optarg;
        break;
      case 't':
        opt_ttyname = optarg;
        break;
      case 'm':
	/* mode for pty: [user,[group,]]mode */
	scratch = strdup(optarg);
	if ((next_scratch = strchr(scratch,',')) != NULL) {
	  /* Username */
	  *next_scratch = '\0';
	  next_scratch++;

	  frontend_owner = find_uid(scratch);

	  scratch = next_scratch;

	  if ((next_scratch = strchr(scratch,',')) != NULL)
	  {
	    /* Group */
	    *next_scratch = '\0';
	    next_scratch++;
	    
	    frontend_group = find_gid(scratch);

	    scratch = next_scratch;
	  }
	}
	frontend_mode = strtol(scratch,NULL,8);
	break;
      case 'u':
	switch_uid = find_uid(optarg);
	break;
      case 'g':
	switch_gid = find_gid(optarg);
	break;
      case '/':
	switch_root = strdup(optarg);
	break;
      case 's':
        settings = optarg;
        break;
      case 'o':
        outfilename=optarg;
        if ( (outfile = fopen(outfilename,"w")) == NULL)
          errorf("Couldn't open output file '%s' for write: %s\n",outfilename,strerror(errno));
        break;
      case 'V':
	puts(VERSION);
	exit(0);
      case '?':
      default:
        errflg++;
        break;
    }

  if (errflg || ((argc-optind) < 1) || ((argc-optind) > 2)) {
    usage(argv[0]);
    exit (2);
  }

  /* Process the two non-flag options */
  backend = argv[optind];
  if ((argc-optind) == 2)
    frontend = argv[optind+1];
        
  if (strcmp(frontend,"-") == 0)
    frontend = NULL;
  if (linebuff)
    setlinebuf(outfile);

  atexit (closedown);
  /* Do some initialization */
  stty_initstore();

  sendudp_open();
  /* Setup backend */
  if (setup_backend(backfd) < 0)
    errorf ("select failed. errno = %d\n", errno);

  /* Setup frontend */
  if ((setup_frontend(frontfd)) < 0)
    errorf("setup_frontend failed: %s\n",strerror(errno));

  /* Drop privileges if we've been asked to */
  if (switch_root)
  {
    if (chroot(switch_root) != 0)
      errorf("chroot(%s) failed: %s\n",switch_root,strerror(errno));
  }
  if (switch_gid != -1)
  {
    if (setgroups(1,&switch_gid) == -1)
      errorf("setgroups(1,[%d]) failed: %s\n",switch_gid, strerror(errno));
    if (setregid(switch_gid, switch_gid) == -1)
      errorf("setregid(%d,%d) failed: %s\n",switch_gid,switch_gid);
    if (getgid() != switch_gid)
      errorf("setregid succeeded, but we're the wrong gid!");
    if (getegid() != switch_gid)
      errorf("setregid succeeded, but we're the wrong effective gid!");
  }
  if (switch_uid != -1)
  {
    if (setreuid(switch_uid, switch_uid) == -1)
      errorf("setreuid(%d,%d) failed: %s\n",switch_uid,switch_uid,strerror(errno));
    if (getuid() != switch_uid)
      errorf("setreuid succeeded, but we're the wrong uid!");
    if (geteuid() != switch_uid)
      errorf("setregid succeeded, but we're the wrong effective uid!");
  }

  
  /* calc (initial) max file descriptor to use in select() */
  fdmax = max(backfd[0], frontfd[0]);

  /* Set up signal handlers and such */
  sigemptyset(&sigmask);
  memset(&sigact,0,sizeof sigact);
  sigact.sa_handler = sigdeath;
  sigact.sa_mask = sigmask;

  sigaction(SIGHUP,&sigact,NULL);
  sigaction(SIGINT,&sigact,NULL);
  sigaction(SIGQUIT,&sigact,NULL);
  sigaction(SIGPIPE,&sigact,NULL);
  sigaction(SIGTERM,&sigact,NULL);

  sigact.sa_handler = sigchld;
  sigaction(SIGCHLD,&sigact,NULL);

  pthread_t udp_recv;
  pthread_create(&udp_recv, NULL, udp_recv_gnssmode_thread, NULL);
  pthread_detach(udp_recv);

  struct tm p;
  time_t timep;
  while (!please_die_now)
  {
    do
    {
      FD_ZERO (&readset);
      FD_SET (backfd[0], &readset);
      FD_SET (frontfd[0], &readset);
      FD_ZERO (&writeset);
      FD_SET (backfd[1], &writeset);
      FD_SET (frontfd[1], &writeset);
      sel = select(fdmax + 1, &readset, &writeset, NULL, NULL);
    }
    while (sel == -1 && errno == EINTR && !please_die_now);
    if (sel == -1 && errno != EINTR)
      errorf ("select failed. errno = %d\n", errno);
    else if (please_die_now)
      break;

    if (FD_ISSET(backfd[0], &readset))
    {
      if ((n = read(backfd[0], buff, BUFF_SIZE)) == 0)
      {
	/* Serial port has closed.  This doesn't really make sense for
	 * a real serial port, but for sockets and programs, probably
	 * we should just exit.
	 */
	if (!quiet)
	  errorf("Backend device was closed.\n");
	break;
      }
      else if (n < 0)
      {
	if ( (errno != EAGAIN) && (errno != EINTR) )
	{
	  errorf("Error reading from backend device: %s\n",strerror(errno));
	}
	break;
      }
      else
      {
	/* We should handle this better.  FIX */
    	if(FD_ISSET(frontfd[1], &writeset))
        {
        if (write (frontfd[1], buff, n) != n)
	  errorf("Error writing to frontend device: %s\n",strerror(errno));
        }
       // if (!quiet)
	     //   dumpbuff(1,buff,n);
	//nmea decode
	{
		tNmea_Msg nmeamsg ;	
	 	int i=0;
		int ret = 0;
		for(i=0; i<n; i++)
		{
			if(buff[i] == '$')
				nmea_index = 0;
			nmea_buf[nmea_index] = buff[i];
			if(buff[i] == '\r')
				nmea_buf[nmea_index] = 0;
			if(buff[i] == '\n')
			{
				nmea_buf[nmea_index] = 0;
                #if 0
        			if (!quiet)
					fprintf(outfile,"%s\n",nmea_buf);
                #endif
#if 1 
				
                ret = NmeaDecode(nmea_buf,&nmeamsg);
                
                if(nmeamsg.nMsgMask == GGA_DECODE)
                {
                    memset(send_buf, 0, 1024);
                    send_len = 0;
                }

                memcpy(send_buf+send_len, nmea_buf, nmea_index);
                send_len += strlen(nmea_buf);
                send_buf[send_len] = 0x0D;
                send_len ++;
                                    
				if(nmeamsg.nMsgMask & ANT_DECODE)
				{
					sAnt = nmeamsg.nAnttenaStatus;
					//sendudp(1011,&sAnt, 4);  //gui
					sAnt |= (nmeamsg.version<<8);
				}

				if(nmeamsg.nMsgMask & RMC_DECODE)
				{
				    if (nmea_buf[3] == 'R' && nmea_buf[4] == 'M' && nmea_buf[5] == 'C' )
				    {
                        if (!quiet)
                            fprintf(outfile,"%s=len=%d\n",nmea_buf, strlen(nmea_buf));
                        sendudp(1014,nmea_buf, strlen(nmea_buf));  //busdemaon
				    }
				}
                
				if(nmeamsg.nMsgMask >= 0x8F)
				{
				   sendudp(1012, send_buf, send_len);
                   sendudp(1011,&nmeamsg.aSvInfo, 2*sizeof(tSVData));  //gui satelite display
                   if (!quiet) 
                   {
                       //fprintf(outfile,"\r\n\r\n%s---------send_len=%d\n\n",send_buf,send_len);
                       
                       fprintf(outfile,"nAnttenaStatus=%d,position=%c mode=%d fy=%f fx=%f (%d-%d-%d)(%d:%d:%f)\n",
                           sAnt,
                           nmeamsg.cFixFlag,
                           NmeaGetRxRunMode(),
                           nmeamsg.fLatInDegree,
                           nmeamsg.fLonInDegree,
                           nmeamsg.usYear,    
                           nmeamsg.ucMonth,
                           nmeamsg.ucDay,                           
                           nmeamsg.usHours,    
                           nmeamsg.usMinutes,
                           nmeamsg.fSeconds);
                   }
                   #if 1
                   localtime_r(&timep, &p);
                   p.tm_sec = (int)nmeamsg.fSeconds;
                   p.tm_min = nmeamsg.usMinutes;
                   p.tm_hour = nmeamsg.usHours+8;
                   p.tm_mday = nmeamsg.ucDay;
                   p.tm_mon = nmeamsg.ucMonth-1;
                   p.tm_year = nmeamsg.usYear + 100;
                   timep = mktime(&p);
                    if(nmeamsg.cFixFlag == 'A')
                        gps_buf[0] = 1;
                    else
                        gps_buf[0] = 0;
                    gps_buf[1] = nmeamsg.fLonInDegree*1000000;
                    gps_buf[2] = nmeamsg.fLatInDegree*1000000;
                    gps_buf[3] = (int)timep;
                    gps_buf[4] = (int)timep;
                    gps_buf[5] = nmeamsg.fHeading;
                    gps_buf[6] = nmeamsg.fGroundVel*1.85;
                    if(nmeamsg.cLatIdx == 'S')
                        gps_buf[7] = 1;
                    else
                        gps_buf[7] = 0;
                    if(nmeamsg.cLonIdx == 'W')
                        gps_buf[8] = 1;
                    else
                        gps_buf[8] = 0;
                    gps_buf[9] = nmeamsg.fAltitude;    
                    
                    gps_buf[10] = NmeaGetRxRunMode();
                    gps_buf[11] = nmeamsg.aSvInfo[1].nSvsUsed;
                    gps_buf[12] = nmeamsg.aSvInfo[0].nSvsUsed;
                    gps_buf[13] = sAnt;
#if 0
                    printf("position=%d, flon=%d, flat=%d, %d, %d, iOrientation=%d, vel=%d, s=%d, w=%d, alt=%d, mode=%d, gps=%d, bd=%d\n",
                        gps_buf[0], gps_buf[1],gps_buf[2],gps_buf[3], gps_buf[4],gps_buf[5], gps_buf[6],gps_buf[7], gps_buf[8],gps_buf[9], gps_buf[10],
                        gps_buf[11], gps_buf[12]);
#endif
                    sendudp(1013, gps_buf, 4*14);
                    sendudp(1015, gps_buf, 4*14);  //busdemaon
                    memset(gps_buf, 0 , 15);
                    #endif
                    
                    memset(send_buf, 0, 1024);
                    send_len = 0;
				}
                
#endif
			}	
			nmea_index++;
//			fprintf(outfile,"nmea_index = %d\n",nmea_index);
			if(nmea_index >= 1024)
				nmea_index = 0;
				
		}	
	}
      }
    }

    if (please_die_now)
      break;

    if (FD_ISSET(frontfd[0], &readset))
    {
      if ((n = read(frontfd[0], buff, BUFF_SIZE)) == 0)
      {
        if (listenfd)
        {
          if (close(frontfd[0]) < 0)
            errorf("Couldn't close old frontfd: %s\n",strerror(errno));
          if ((frontfd[0]=frontfd[1]=accept(listenfd,NULL,NULL)) < 0)
            errorf("Couldn't accept new socket connection: %s\n",strerror(errno));
        }
          
      }
      else if (n <= 0)
      {
	if ( (errno == EAGAIN) || (errno == EINTR) )
	{
	  /* No real error */
	}
	else
	{
	  errorf("Error reading from frontend device: %s\n",strerror(errno));
	}
      }
      else
      {
        if (write (backfd[1], buff, n) != n)
	  errorf("Error writing to backend device: %s\n",strerror(errno));
	if (!quiet)
	  dumpbuff(0,buff,n);
      }
    }

  }
  stty_orig();
  exit(0);
}
Ejemplo n.º 20
0
void handle_syscall_ret(struct syscallrecord *rec)
{
	struct syscallentry *entry;
	struct msg_syscallresult scmsg;
	struct childdata *child = this_child();
	unsigned int call;

	init_msgchildhdr(&scmsg.hdr, SYSCALL_RESULT, pids[child->num], child->num);
	scmsg.hdr.tp = rec->tp;
	scmsg.sequence_nr = child->op_nr;
	scmsg.retval = rec->retval;
	scmsg.errno_post = rec->errno_post;
	sendudp((char *) &scmsg, sizeof(scmsg));

	call = rec->nr;
	entry = syscalls[call].entry;

	if (rec->retval == -1UL) {
		int err = rec->errno_post;

		/* only check syscalls that completed. */
		//FIXME: how else would we get here?
		if (rec->state == AFTER) {
			if (err == ENOSYS)
				deactivate_enosys(rec, entry, call);

			entry->failures++;
			if (err < NR_ERRNOS) {
				entry->errnos[err]++;
			} else {
				// "These should never be seen by user programs."
				// But trinity isn't a 'normal' user program, we're doing
				// stuff that libc hides from apps.
				if (err < 512 || err > 530)
					printf("errno out of range after doing %s: %d:%s\n",
						entry->name,
						err, strerror(err));
			}
			shm->stats.failures++;
		}
	} else {
		handle_success(rec);	// Believe me folks, you'll never get bored with winning
		entry->successes++;
		shm->stats.successes++;
	}
	entry->attempted++;

	generic_post(entry->arg1type, rec->a1);
	generic_post(entry->arg2type, rec->a2);
	generic_post(entry->arg3type, rec->a3);
	generic_post(entry->arg4type, rec->a4);
	generic_post(entry->arg5type, rec->a5);
	generic_post(entry->arg6type, rec->a6);

	if (entry->post)
	    entry->post(rec);

	check_uid();

	generic_free_arg(rec);
}
Ejemplo n.º 21
0
int32 do_sockets(fd_set* rfd, int32 next)
{
    struct timeval timeout;
    int32 ret;
    memcpy(rfd, &readfds, sizeof(*rfd));

    timeout.tv_sec = next / 1000;
    timeout.tv_usec = next % 1000 * 1000;

    ret = sSelect(fd_max, rfd, nullptr, nullptr, &timeout);

    if (ret == SOCKET_ERROR)
    {
        if (sErrno != S_EINTR)
        {
            ShowFatalError("do_sockets: select() failed, error code %d!\n", sErrno);
            do_final(EXIT_FAILURE);
        }
        return 0; // interrupted by a signal, just loop and try again
    }

    last_tick = time(nullptr);

    if (sFD_ISSET(map_fd, rfd))
    {
        struct sockaddr_in from;
        socklen_t fromlen = sizeof(from);

        int32 ret = recvudp(map_fd, g_PBuff, map_config.buffer_size, 0, (struct sockaddr*)&from, &fromlen);
        if (ret != -1)
        {
            // find player char
#   ifdef WIN32
            uint32 ip = ntohl(from.sin_addr.S_un.S_addr);
#   else
            uint32 ip = ntohl(from.sin_addr.s_addr);
#   endif

            uint64 port = ntohs(from.sin_port);
            uint64 ipp = ip;
            ipp |= port << 32;
            map_session_data_t* map_session_data = mapsession_getbyipp(ipp);

            if (map_session_data == nullptr)
            {
                map_session_data = mapsession_createsession(ip, ntohs(from.sin_port));
                if (map_session_data == nullptr)
                {
					map_session_list.erase(ipp);
                    return -1;
                }
            }

            map_session_data->last_update = time(nullptr);
            size_t size = ret;

            if (recv_parse(g_PBuff, &size, &from, map_session_data) != -1)
            {
                // если предыдущий пакет был потерян, то мы не собираем новый,
                // а отправляем предыдущий пакет повторно
                if (!parse(g_PBuff, &size, &from, map_session_data))
                {
                    send_parse(g_PBuff, &size, &from, map_session_data);
                }

                ret = sendudp(map_fd, g_PBuff, size, 0, (const struct sockaddr*)&from, fromlen);

                int8* data = g_PBuff;
                g_PBuff = map_session_data->server_packet_data;

                map_session_data->server_packet_data = data;
                map_session_data->server_packet_size = size;
            }
            if (map_session_data->shuttingDown > 0)
            {
                map_close_session(gettick(), map_session_data);
            }
        }
    }
    return 0;
}
Ejemplo n.º 22
0
bool SendHTMSocket(void *htmsendhandle, int length_in_bytes, void *buffer)
{
	desc *o = (desc *)htmsendhandle;
	return sendudp(o->addr, o->sockfd, o->len, length_in_bytes, buffer);
}