Ejemplo n.º 1
0
static void net_timeout(struct net_device *dev)
{
	struct net_local *lp = dev->priv;
	int ioaddr = dev->base_addr;
	unsigned long flags;
	
	
	printk(KERN_WARNING "%s: transmit timed out with status %04x, %s?\n", dev->name,
		   htons(inw(ioaddr + TX_STATUS)),
		   inb(ioaddr + TX_STATUS) & 0x80
		   ? "IRQ conflict" : "network cable problem");
	printk(KERN_WARNING "%s: timeout registers: %04x %04x %04x %04x %04x %04x %04x %04x.\n",
		   dev->name, htons(inw(ioaddr + 0)),
		   htons(inw(ioaddr + 2)), htons(inw(ioaddr + 4)),
		   htons(inw(ioaddr + 6)), htons(inw(ioaddr + 8)),
		   htons(inw(ioaddr +10)), htons(inw(ioaddr +12)),
		   htons(inw(ioaddr +14)));
	printk(KERN_WARNING "eth card: %04x %04x\n",
		htons(inw(ioaddr+FJ_STATUS0)),
		htons(inw(ioaddr+FJ_CONFIG0)));
	lp->stats.tx_errors++;
	/* ToDo: We should try to restart the adaptor... */
	spin_lock_irqsave(&lp->lock, flags);

	/* Initialize LAN Controller and LAN Card */
	outb(0xda, ioaddr + CONFIG_0);   /* Initialize LAN Controller */
	outb(0x00, ioaddr + CONFIG_1);   /* Stand by mode */
	outb(0x00, ioaddr + FJ_CONFIG1); /* Disable IRQ of LAN Card */
	outb(0x00, ioaddr + FJ_BUFCNTL); /* Reset ? I'm not sure */
	net_open(dev);
	spin_unlock_irqrestore(&lp->lock, flags);

	netif_wake_queue(dev);
}
Ejemplo n.º 2
0
Archivo: netctrl.c Proyecto: mubawa/TDE
int netctrl_connect()
{
	int  port;
    char ip[IP_ADDR_LEN];

    if (cfg_getstring(SECTION_NAME_IP, ip, IP_ADDR_LEN) != SUCCESS){
    	return ERROR;
    }

    printf("NET CONNECT GETSTRING %s\n", ip);

    port = cfg_getnumber(SECTION_NAME_PORT);
    if (port == 0)
    	return ERROR;

    port = 9000;

    printf("NET CONNECT GET PORT %d\n", port);

    if (net_open(ip, port) != SUCCESS)
    	return ERROR;

    printf("NET CONNECT OPEN\n");

    return SUCCESS;
}
Ejemplo n.º 3
0
int
devopen(struct open_file *f, const char *fname, char **file)
{
	struct devsw   *dp;
	int             error = 0;

	dp = &devsw[0];
	f->f_dev = dp;

	if(fname)
		strncpy(bootfile, fname, FNAME_SIZE);

	error = net_open(f);

	if (bootfile[0])
		*file = bootfile;
	else
		*file = (char *) fname;

#ifdef _STANDALONE
	strncpy(bibp.bootpath, *file, sizeof(bibp.bootpath));
	BI_ADD(&bibp, BTINFO_BOOTPATH, sizeof(bibp));
#endif

	return (error);
}
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
   int sockfd, port;
   char host[200];
   char msg[200], *p, *cmd;

   strcpy(host, SERV_HOST_ADDR);
   port = SERV_TCP_PORT;

   if (argc > 1) {
      strcpy(host, argv[1]); /* get host from command line */
      p = strchr(host, ':');
      if (p) {
	 *p++ = 0;
	 port = atoi(p);
      }
   }

   if (argc > 2) {
      cmd = argv[2];
   } else {
      cmd = NULL;
   }

   if ((sockfd = net_open(host, NULL, port)) < 0) {
      sprintf(msg, "client: tcp_open for host %s on %d failed\n", host, port);
      error_abort(msg);
   }

   handle_client(stdin, sockfd, cmd);	    /* do it all */
   net_close(sockfd);
   exit(0);
}
Ejemplo n.º 5
0
int main(int argc, char **argv)
{
  struct net_handle* file_ctx = NULL;
  struct timeval start,end;

  char rcv_buf[MAX_BUFSIZE];
  if (argc < 3) {
    printf("usage:need argument ip_address port_num\n");
    exit(-1);
  }
  int rvl=0; 
  int port_num= strtoul(argv[2],NULL,0);
  zlog_init("./zlog.conf");
  rvl = net_module_init(NULL);
  assert(!rvl);

  file_ctx = net_open(argv[1],port_num,4,16,SPK_DIR_WRITE,net_intf_tcp);
  if (!file_ctx) {
    printf("failed to open net\n");
    rvl = SPKERR_BADRES;
    goto out;
  }
  rvl= net_intf_is_connected(file_ctx);
  if(!rvl) {
    printf("net is not connected!\n");
	goto out;
  }
  
  uint64_t xfer=0;
  gettimeofday(&start, NULL);
  uint64_t total_count=0;
  while (1) {

    xfer = net_write(file_ctx, rcv_buf, MAX_BUFSIZE);
    if(xfer != MAX_BUFSIZE) {
	    printf("send data error=>xfer:%ld\n",xfer);
	} else {
//	    printf("write OK!\n");
	}

	total_count++;
    gettimeofday(&end, NULL);
    float diff=(end.tv_sec-start.tv_sec)+(end.tv_usec - start.tv_usec)/1000000.0;
	if(diff > 5) {
    	float speed=(total_count*MAX_BUFSIZE)/1024/diff;
		printf("time:%-15f s speed:%-15f KB/s\n",diff,speed);
        gettimeofday(&start, NULL);
		total_count=0;
	}
  }

out:
    if (file_ctx) {
        net_close(file_ctx);
        file_ctx = NULL;
    }
  return rvl;
}
Ejemplo n.º 6
0
/*
 * A server thread (task)
 * assumes network is started and shutdown by parent thread
 */
server_task (XML *xml)
{
  SSL_CTX *ctx;
  NETCON *conn, *ssl;
  int port, threads, e;


  if ((threads = xml_get_int (xml, "Phineas.Server.NumThreads")) == 0)
    threads = 2;
  if (port = xml_get_int (xml, "Phineas.Server.Port"))
  {
    if ((conn = net_open ("ANY", port, threads, NULL)) == NULL)
    {
      return (phineas_fatal ("Failed to open port %d\n", port));
    }
  }
  if (port = xml_get_int (xml, "Phineas.Server.SSL.Port"))
  {
    ctx = server_ctx (xml);
    if ((ssl = net_open ("ANY", port, threads, ctx)) == NULL)
    {
      if (conn != NULL)
        net_close (conn);
      return (phineas_fatal ("Failed to open SSL port %d\n", port));
    }
    if (conn != NULL)
      threads *= 2;
  }
  e = server_listen (xml, conn, ssl, ctx, threads);
  if (conn != NULL)
    net_close (conn);
  if (ssl != NULL)
  {
    net_close (ssl);
    if (ctx != NULL)
      SSL_CTX_free (ctx);
  }
  if (e)
    phineas_fatal ("Failed to start PHINEAS server");
  return (0);
}
Ejemplo n.º 7
0
struct wif *wi_open(char *iface)
{
	struct wif *wi;

	/* XXX assume for now that all OSes have UNIX sockets */
	wi = net_open(iface);
	if (!wi)
		wi = wi_open_osdep(iface);
	if (!wi)
		return NULL;

	strncpy(wi->wi_interface, iface, sizeof(wi->wi_interface)-1);
	wi->wi_interface[sizeof(wi->wi_interface)-1] = 0;

	return wi;
}
Ejemplo n.º 8
0
main()
{
	int fd;
	struct sockaddr_in	my_addr;
	void			echo_serv (int);

	bzero((char *) &my_addr, sizeof(my_addr));
	my_addr.sin_family      = AF_INET;
	my_addr.sin_addr.s_addr = htonl (INADDR_ANY);
	my_addr.sin_port        = htons(SERV_TCP_PORT);

	fd = net_open ("/dev/udp", O_RDWR);
	fd = net_bind (fd, &my_addr, sizeof (struct sockaddr_in));

	echo_serv (fd);
	exit (0);	/* not reached */
}
Ejemplo n.º 9
0
static int ser_open(char * port, long baud, union filedescriptor *fdp)
{
  int rc;
  int fd;

  /*
   * If the port is of the form "net:<host>:<port>", then
   * handle it as a TCP connection to a terminal server.
   */
  if (strncmp(port, "net:", strlen("net:")) == 0) {
    return net_open(port + strlen("net:"), fdp);
  }

  /*
   * open the serial port
   */
  fd = open(port, O_RDWR | O_NOCTTY | O_NONBLOCK);
  if (fd < 0) {
    fprintf(stderr, "%s: ser_open(): can't open device \"%s\": %s\n",
            progname, port, strerror(errno));
    return -1;
  }

  fdp->ifd = fd;

  /*
   * set serial line attributes
   */
  rc = ser_setspeed(fdp, baud);
  if (rc) {
    fprintf(stderr, 
            "%s: ser_open(): can't set attributes for device \"%s\": %s\n",
            progname, port, strerror(-rc));
    close(fd);
    return -1;
  }
  return 0;
}
Ejemplo n.º 10
0
main()
{
	int fd;
	struct sockaddr_in	my_addr;
	struct sockaddr_in	serv_addr;
	char buf[128];
	void echo_driver(int, struct sockaddr_in *);

	if ((fd = net_open ("/dev/udp", O_RDWR)) < 0)
	{
		fprintf (stderr, "open failed.\n");
		exit (-1);
	}
	/*
	 * bind any address to us.
	 */
	bzero((char *) &my_addr, sizeof(my_addr));
	my_addr.sin_family      = AF_INET;
	my_addr.sin_addr.s_addr = htonl (INADDR_ANY);
	my_addr.sin_port        = htons(0);

	fd = net_bind (fd, &my_addr, sizeof (struct sockaddr_in));

	/*
	 * set up server's address
	 */
	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family      = AF_INET;
	serv_addr.sin_addr.s_addr = inet_addr (SERV_HOST_ADDR);
	serv_addr.sin_port        = htons(SERV_TCP_PORT);

	echo_driver (fd, &serv_addr);
	close (fd);

	exit (0);
}
Ejemplo n.º 11
0
int
devopen(struct open_file *of, const char *name, char **file)
{
	char *cp;
	char partition;
	char fname[256];
	char buf[DEV_BSIZE];
	struct disklabel label;
	int handle, part;
	int error = 0;
#ifdef SOFTRAID
	char volno;
#endif

	if (ofdev.handle != -1)
		panic("devopen");
	if (of->f_flags != F_READ)
		return EPERM;
	DNPRINTF(BOOT_D_OFDEV, "devopen: you want %s\n", name);
	if (strlcpy(fname, name, sizeof fname) >= sizeof fname)
		return ENAMETOOLONG;
#ifdef SOFTRAID
	if (bootdev_dip) {
		if (fname[0] == 's' && fname[1] == 'r' &&
		    '0' <= fname[2] && fname[2] <= '9') {
			volno = fname[2];
			if ('a' <= fname[3] &&
			    fname[3] <= 'a' + MAXPARTITIONS) {
				partition = fname[3];
				if (fname[4] == ':')
					cp = &fname[5];
				else
					cp = &fname[4];
			} else {
				partition = 'a';
				cp = &fname[3];
			}
		} else {
			volno = '0';
			partition = 'a';
			cp = &fname[0];
		}
		snprintf(buf, sizeof buf, "sr%c:%c", volno, partition);
		if (strlcpy(opened_name, buf, sizeof opened_name)
		    >= sizeof opened_name)
			return ENAMETOOLONG;
		*file = opened_name + strlen(opened_name);
		if (!*cp) {
			if (strlcpy(buf, DEFAULT_KERNEL, sizeof buf)
			    >= sizeof buf)
				return ENAMETOOLONG;
		} else {
			if (snprintf(buf, sizeof buf, "%s%s",
			    *cp == '/' ? "" : "/", cp) >= sizeof buf)
				return ENAMETOOLONG;
		}
		if (strlcat(opened_name, buf, sizeof opened_name) >=
		    sizeof opened_name)
			return ENAMETOOLONG;
	} else {
#endif
		cp = filename(fname, &partition);
		if (cp) {
			if (strlcpy(buf, cp, sizeof buf) >= sizeof buf)
				return ENAMETOOLONG;
			*cp = 0;
		}
		if (!cp || !*buf) {
			if (strlcpy(buf, DEFAULT_KERNEL, sizeof buf)
			    >= sizeof buf)
				return ENAMETOOLONG;
		}
		if (!*fname) {
			if (strlcpy(fname, bootdev, sizeof fname)
			    >= sizeof fname)
				return ENAMETOOLONG;
		}
		if (strlcpy(opened_name, fname,
		    partition ? (sizeof opened_name) - 2 : sizeof opened_name)
		    >= sizeof opened_name)
			return ENAMETOOLONG;
		if (partition) {
			cp = opened_name + strlen(opened_name);
			*cp++ = ':';
			*cp++ = partition;
			*cp = 0;
		}
		if (*buf != '/') {
			if (strlcat(opened_name, "/", sizeof opened_name) >=
			    sizeof opened_name)
				return ENAMETOOLONG;
		}
		if (strlcat(opened_name, buf, sizeof opened_name) >=
		    sizeof opened_name)
			return ENAMETOOLONG;
		*file = opened_name + strlen(fname) + 1;
#ifdef SOFTRAID
	}
#endif
	DNPRINTF(BOOT_D_OFDEV, "devopen: trying %s\n", fname);
#ifdef SOFTRAID
	if (bootdev_dip) {
		/* Redirect to the softraid boot volume. */
		struct partition *pp;

		bzero(&ofdev, sizeof ofdev);
		ofdev.type = OFDEV_SOFTRAID;

		if (partition) {
			if (partition < 'a' ||
			    partition >= 'a' + MAXPARTITIONS) {
			    	printf("invalid partition '%c'\n", partition);
				return EINVAL;
			}
			part = partition - 'a';
			pp = &bootdev_dip->disklabel.d_partitions[part];
			if (pp->p_fstype == FS_UNUSED || pp->p_size == 0) {
			    	printf("invalid partition '%c'\n", partition);
				return EINVAL;
			}
			bootdev_dip->sr_vol->sbv_part = partition;
		} else
			bootdev_dip->sr_vol->sbv_part = 'a';

		of->f_dev = devsw;
		of->f_devdata = &ofdev;

#ifdef SPARC_BOOT_UFS
		bcopy(&file_system_ufs, &file_system[nfsys++], sizeof file_system[0]);
#else
#error "-DSOFTRAID requires -DSPARC_BOOT_UFS"
#endif
		return 0;
	}
#endif
	if ((handle = OF_finddevice(fname)) == -1)
		return ENOENT;
	DNPRINTF(BOOT_D_OFDEV, "devopen: found %s\n", fname);
	if (OF_getprop(handle, "name", buf, sizeof buf) < 0)
		return ENXIO;
	DNPRINTF(BOOT_D_OFDEV, "devopen: %s is called %s\n", fname, buf);
	if (OF_getprop(handle, "device_type", buf, sizeof buf) < 0)
		return ENXIO;
	DNPRINTF(BOOT_D_OFDEV, "devopen: %s is a %s device\n", fname, buf);
	DNPRINTF(BOOT_D_OFDEV, "devopen: opening %s\n", fname);
	if ((handle = OF_open(fname)) == -1) {
		DNPRINTF(BOOT_D_OFDEV, "devopen: open of %s failed\n", fname);
		return ENXIO;
	}
	DNPRINTF(BOOT_D_OFDEV, "devopen: %s is now open\n", fname);
	bzero(&ofdev, sizeof ofdev);
	ofdev.handle = handle;
	ofdev.type = OFDEV_DISK;
	ofdev.bsize = DEV_BSIZE;
	if (!strcmp(buf, "block")) {
		error = load_disklabel(&ofdev, &label);
		if (error && error != ERDLAB)
			goto bad;
		else if (error == ERDLAB) {
			if (partition)
				/* User specified a parititon, but there is none */
				goto bad;
			/* No, label, just use complete disk */
			ofdev.partoff = 0;
		} else {
			part = partition ? partition - 'a' : 0;
			ofdev.partoff = label.d_partitions[part].p_offset;
			DNPRINTF(BOOT_D_OFDEV, "devopen: setting partition %d "
			    "offset %x\n", part, ofdev.partoff);
		}
		
		of->f_dev = devsw;
		of->f_devdata = &ofdev;
#ifdef SPARC_BOOT_UFS
		bcopy(&file_system_ufs, &file_system[nfsys++], sizeof file_system[0]);
#endif
#ifdef SPARC_BOOT_HSFS
		bcopy(&file_system_cd9660, &file_system[nfsys++],
		    sizeof file_system[0]);
#endif
		DNPRINTF(BOOT_D_OFDEV, "devopen: return 0\n");
		return 0;
	}
#ifdef NETBOOT
	if (!strcmp(buf, "network")) {
		ofdev.type = OFDEV_NET;
		of->f_dev = devsw;
		of->f_devdata = &ofdev;
		bcopy(&file_system_nfs, file_system, sizeof file_system[0]);
		nfsys = 1;
		if (error = net_open(&ofdev))
			goto bad;
		return 0;
	}
#endif
	error = EFTYPE;
bad:
	DNPRINTF(BOOT_D_OFDEV, "devopen: error %d, cannot open device\n",
	    error);
	OF_close(handle);
	ofdev.handle = -1;
	return error;
}
Ejemplo n.º 12
0
int
devopen(struct open_file *of, const char *name, char **file)
{
	char *cp;
	char partition;
	char fname[256];
	char buf[DEV_BSIZE];
	struct disklabel label;
	int handle, part;
	size_t read;
	char *errmsg = NULL;
	int error = 0;

	if (ofdev.handle != -1)
		panic("devopen");
	if (of->f_flags != F_READ)
		return EPERM;
	DNPRINTF(BOOT_D_OFDEV, "devopen: you want %s\n", name);
	strlcpy(fname, name, sizeof fname);
	cp = filename(fname, &partition);
	if (cp) {
		strlcpy(buf, cp, sizeof buf);
		*cp = 0;
	}
	if (!cp || !*buf)
		strlcpy(buf, DEFAULT_KERNEL, sizeof buf);
	if (!*fname)
		strlcpy(fname, bootdev, sizeof fname);
	strlcpy(opened_name, fname, sizeof opened_name);
	if (partition) {
		cp = opened_name + strlen(opened_name);
		*cp++ = ':';
		*cp++ = partition;
		*cp = 0;
	}
	if (*buf != '/')
		strlcat(opened_name, "/", sizeof opened_name);
	strlcat(opened_name, buf, sizeof opened_name);
	*file = opened_name + strlen(fname) + 1;
	DNPRINTF(BOOT_D_OFDEV, "devopen: trying %s\n", fname);
	if ((handle = OF_finddevice(fname)) == -1)
		return ENOENT;
	DNPRINTF(BOOT_D_OFDEV, "devopen: found %s\n", fname);
	if (OF_getprop(handle, "name", buf, sizeof buf) < 0)
		return ENXIO;
	DNPRINTF(BOOT_D_OFDEV, "devopen: %s is called %s\n", fname, buf);
	if (OF_getprop(handle, "device_type", buf, sizeof buf) < 0)
		return ENXIO;
	DNPRINTF(BOOT_D_OFDEV, "devopen: %s is a %s device\n", fname, buf);
	DNPRINTF(BOOT_D_OFDEV, "devopen: opening %s\n", fname);
	if ((handle = OF_open(fname)) == -1) {
		DNPRINTF(BOOT_D_OFDEV, "devopen: open of %s failed\n", fname);
		return ENXIO;
	}
	DNPRINTF(BOOT_D_OFDEV, "devopen: %s is now open\n", fname);
	bzero(&ofdev, sizeof ofdev);
	ofdev.handle = handle;
	if (!strcmp(buf, "block")) {
		ofdev.type = OFDEV_DISK;
		ofdev.bsize = DEV_BSIZE;
		/* First try to find a disklabel without MBR partitions */
		DNPRINTF(BOOT_D_OFDEV, "devopen: trying to read disklabel\n");
		if (strategy(&ofdev, F_READ,
			     LABELSECTOR, DEV_BSIZE, buf, &read) != 0
		    || read != DEV_BSIZE
		    || (errmsg = getdisklabel(buf, &label))) {
#ifdef BOOT_DEBUG
			if (errmsg)
				DNPRINTF(BOOT_D_OFDEV,
				    "devopen: getdisklabel says %s\n", errmsg);
#endif
			/* Else try MBR partitions */
			errmsg = search_label(&ofdev, LABELSECTOR, buf,
			    &label, 0);
			if (errmsg) { 
				printf("devopen: search_label says %s\n", errmsg);
				error = ERDLAB;
			}
			if (error && error != ERDLAB)
				goto bad;
		}

		if (error == ERDLAB) {
			if (partition)
				/* User specified a parititon, but there is none */
				goto bad;
			/* No, label, just use complete disk */
			ofdev.partoff = 0;
		} else {
			part = partition ? partition - 'a' : 0;
			ofdev.partoff = label.d_partitions[part].p_offset;
			DNPRINTF(BOOT_D_OFDEV, "devopen: setting partition %d "
			    "offset %x\n", part, ofdev.partoff);
		}
		
		of->f_dev = devsw;
		of->f_devdata = &ofdev;
#ifdef SPARC_BOOT_UFS
		bcopy(&file_system_ufs, &file_system[nfsys++], sizeof file_system[0]);
#endif
#ifdef SPARC_BOOT_HSFS
		bcopy(&file_system_cd9660, &file_system[nfsys++],
		    sizeof file_system[0]);
#endif
		DNPRINTF(BOOT_D_OFDEV, "devopen: return 0\n");
		return 0;
	}
#ifdef NETBOOT
	if (!strcmp(buf, "network")) {
		ofdev.type = OFDEV_NET;
		of->f_dev = devsw;
		of->f_devdata = &ofdev;
		bcopy(&file_system_nfs, file_system, sizeof file_system[0]);
		nfsys = 1;
		if (error = net_open(&ofdev))
			goto bad;
		return 0;
	}
#endif
	error = EFTYPE;
bad:
	DNPRINTF(BOOT_D_OFDEV, "devopen: error %d, cannot open device\n",
	    error);
	OF_close(handle);
	ofdev.handle = -1;
	return error;
}
Ejemplo n.º 13
0
/*
 * send a message
 * return non-zero if message not sent successful with completed
 * queue info for status and transport
 */
int ebxml_send (XML*xml, QUEUEROW *r, MIME *msg)
{
  DBUF *b;
  NETCON *conn;
  char host[MAX_PATH];	/* need buffers for redirect		*/
  char path[MAX_PATH];
  int port, route, timeout, delay, retry;
  SSL_CTX *ctx;
  char *rname, 		/* route name				*/
       *content, 	/* message content			*/
       buf[MAX_PATH];

  /* format up the message					*/
  if ((content = mime_format (msg)) == NULL)
  {
    queue_field_set (r, "PROCESSINGSTATUS", "done");
    queue_field_set (r, "TRANSPORTSTATUS", "failed");
    queue_field_set (r, "TRANSPORTERRORCODE", "failed formatting message");
    return (-1);
  }
  debug ("Send content:\n%s\n", content);

  /*
   * get connection info from the record route
   */
  if ((route = 
    cfg_route_index (xml, queue_field_get (r, "ROUTEINFO"))) < 0)
  {
    queue_field_set (r, "PROCESSINGSTATUS", "done");
    queue_field_set (r, "TRANSPORTSTATUS", "failed");
    queue_field_set (r, "TRANSPORTERRORCODE", "bad route");
    return (-1);
  }
  rname = cfg_route (xml, route, "Name");
  ctx = ebxml_route_ctx (xml, route);
  strcpy (host, cfg_route (xml, route, "Host"));
  port = atoi (cfg_route (xml, route, "Port"));
  if ((retry = atoi (cfg_route (xml, route, "Retry"))) == 0)
    retry = cfg_retries (xml);
  timeout = atoi (cfg_route (xml, route, "Timeout"));
  delay = cfg_delay (xml);
  strcpy (path, cfg_route (xml, route, "Path"));

sendmsg:

  info ("Sending ebXML %s:%d to %s\n", 
    r->queue->name, r->rowid, rname);
  debug ("opening connection socket on port=%d retrys=%d timeout=%d\n", 
    port, retry, timeout);
  if ((conn = net_open (host, port, 0, ctx)) == NULL)
  {
    error ("failed opening connection to %s:%d\n", host, port);
    goto retrysend;
  }
  				/* set read timeout if given	*/
  if (timeout)
  {
    net_timeout (conn, timeout * 1000);
    timeout <<= 1;		/* bump each try		*/
  }
  delay = 0;			/* connection OK, don't delay	*/
  queue_field_set (r, "MESSAGESENTTIME", ptime (NULL, buf));
  sprintf (buf, "POST %s HTTP/1.1\r\n", path);
  // ch = ebxml_beautify (ch);
  				/* all set... send the message	*/
  debug ("sending message...\n");
  net_write (conn, buf, strlen (buf));
  net_write (conn, content, strlen (content));
  debug ("reading response...\n");
  b = ebxml_receive (conn);
  debug ("closing socket...\n");
  net_close (conn);
  				/* no reply?			*/
  if (b == NULL)
  {
    warn ("Send response timed out or closed for %s\n", rname);

retrysend:			/* retry with a wait, or..	*/	
			
    if (retry-- && phineas_running ())
    {
      if (delay)
      {
	info ("Retrying send to %s in %d seconds\n", rname, delay);
        sleep (delay * 1000);
	delay <<= 1;
      }
      else			/* reset connection delay	*/
        delay = cfg_delay (xml);
      goto sendmsg;
    }
    if (ctx != NULL)		/* give up!			*/
      SSL_CTX_free (ctx);
    free (content);
    queue_field_set (r, "PROCESSINGSTATUS", "done");
    queue_field_set (r, "TRANSPORTSTATUS", "failed");
    queue_field_set (r, "TRANSPORTERRORCODE", "retries exhausted");
    return (-1);
  }
  debug ("reply was %d bytes\n%.*s\n", dbuf_size (b),
    dbuf_size (b), dbuf_getbuf (b));

  /*
   * handle redirects...
   * note this assumes the same SSL context should be used
   */
  if (ebxml_redirect (dbuf_getbuf (b), host, &port, path))
  {
    dbuf_free (b);
    goto sendmsg;
  }

  if (ctx != NULL)
    SSL_CTX_free (ctx);
  if (ebxml_parse_reply (dbuf_getbuf (b), r))
  {
    queue_field_set (r, "PROCESSINGSTATUS", "done");
    queue_field_set (r, "TRANSPORTSTATUS", "failed");
    queue_field_set (r, "TRANSPORTERRORCODE", "garbled reply");
  }
  debug ("send completed\n");
  dbuf_free (b);
  free (content);
  return (0);
}
Ejemplo n.º 14
0
int
devopen(struct open_file *of, const char *name, char **file)
{
	char *cp;
	char partition;
	char fname[256];
	char buf[DEV_BSIZE];
	struct disklabel label;
	int handle, part;
	size_t nread;
	int error = 0;

	if (ofdev.handle != -1)
		panic("devopen");
	if (of->f_flags != F_READ)
		return EPERM;
	strcpy(fname, name);
	cp = filename(fname, &partition);
	if (cp) {
		strcpy(buf, cp);
		*cp = 0;
	}
	if (!cp || !*buf)
		return ENOENT;
	if (!*fname)
		strcpy(fname, bootdev);
	strcpy(opened_name, fname);
	if (partition) {
		cp = opened_name + strlen(opened_name);
		*cp++ = ':';
		*cp++ = partition;
		*cp = 0;
	}
	if (*buf != '/')
		strcat(opened_name, "/");
	strcat(opened_name, buf);
	*file = opened_name + strlen(fname) + 1;
	if ((handle = OF_finddevice(fname)) == -1)
		return ENOENT;
	if (OF_getprop(handle, "name", buf, sizeof buf) < 0)
		return ENXIO;
	floppyboot = !strcmp(buf, "floppy");
	if (OF_getprop(handle, "device_type", buf, sizeof buf) < 0)
		return ENXIO;
#if 0
	if (!strcmp(buf, "block"))
		/*
		 * For block devices, indicate raw partition
		 * (:0 in OpenFirmware)
		 */
		strcat(fname, ":0");
#endif
	if ((handle = OF_open(fname)) == -1)
		return ENXIO;
	memset(&ofdev, 0, sizeof ofdev);
	ofdev.handle = handle;
	ofdev.dmabuf = NULL;
	OF_call_method("dma-alloc", handle, 1, 1, MAXPHYS, &ofdev.dmabuf);
	if (!strcmp(buf, "block")) {
		ofdev.type = OFDEV_DISK;
		ofdev.bsize = DEV_BSIZE;
		/* First try to find a disklabel without MBR partitions */
		if (strategy(&ofdev, F_READ,
			     LABELSECTOR, DEV_BSIZE, buf, &nread) != 0
		    || nread != DEV_BSIZE
		    || getdisklabel(buf, &label)) {
			/* Else try MBR partitions */
			error = search_label(&ofdev, 0, buf, &label, 0);
			if (error && error != ERDLAB)
				goto bad;
		}

		if (error == ERDLAB) {
			if (partition)
				/*
				 * User specified a parititon,
				 * but there is none
				 */
				goto bad;
			/* No, label, just use complete disk */
			ofdev.partoff = 0;
		} else {
			part = partition ? partition - 'a' : 0;
			ofdev.partoff = label.d_partitions[part].p_offset;
		}

		of->f_dev = of_devsw;
		of->f_devdata = &ofdev;
		file_system[0] = file_system_ffsv1;
		file_system[1] = file_system_ffsv2;
		file_system[2] = file_system_lfsv1;
		file_system[3] = file_system_lfsv2;
		file_system[4] = file_system_ustarfs;
		file_system[5] = file_system_cd9660;
		file_system[6] = file_system_hfs;
		nfsys = 7;
		return 0;
	}
	if (!strcmp(buf, "network")) {
		ofdev.type = OFDEV_NET;
		of->f_dev = of_devsw;
		of->f_devdata = &ofdev;
		file_system[0] = file_system_nfs;
		nfsys = 1;
		if ((error = net_open(&ofdev)))
			goto bad;
		return 0;
	}
	error = EFTYPE;
bad:
	OF_close(handle);
	ofdev.handle = -1;
	return error;
}
Ejemplo n.º 15
0
static int ser_open(char * port, union pinfo pinfo, union filedescriptor *fdp)
{
	LPVOID lpMsgBuf;
	HANDLE hComPort=INVALID_HANDLE_VALUE;
	char *newname = 0;

	/*
	 * If the port is of the form "net:<host>:<port>", then
	 * handle it as a TCP connection to a terminal server.
	 */
	if (strncmp(port, "net:", strlen("net:")) == 0) {
#ifdef HAVE_LIBWS2_32
		return net_open(port + strlen("net:"), fdp);
#else
		avrdude_message(MSG_INFO, "%s: ser_open(): "
				"not configured for TCP connections\n",
                                progname);
		return -1;
#endif
	}

	if (strncasecmp(port, "com", strlen("com")) == 0) {

	    // prepend "\\\\.\\" to name, required for port # >= 10
	    newname = malloc(strlen("\\\\.\\") + strlen(port) + 1);

	    if (newname == 0) {
		avrdude_message(MSG_INFO, "%s: ser_open(): out of memory\n",
                                progname);
		exit(1);
	    }
	    strcpy(newname, "\\\\.\\");
	    strcat(newname, port);

	    port = newname;
	}

	hComPort = CreateFile(port, GENERIC_READ | GENERIC_WRITE, 0, NULL,
		OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

	if (hComPort == INVALID_HANDLE_VALUE) {
		FormatMessage(
			FORMAT_MESSAGE_ALLOCATE_BUFFER |
			FORMAT_MESSAGE_FROM_SYSTEM |
			FORMAT_MESSAGE_IGNORE_INSERTS,
			NULL,
			GetLastError(),
			MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
			(LPTSTR) &lpMsgBuf,
			0,
			NULL);
		avrdude_message(MSG_INFO, "%s: ser_open(): can't open device \"%s\": %s\n",
				progname, port, (char*)lpMsgBuf);
		LocalFree( lpMsgBuf );
		return -1;
	}

	if (!SetupComm(hComPort, W32SERBUFSIZE, W32SERBUFSIZE))
	{
		CloseHandle(hComPort);
		avrdude_message(MSG_INFO, "%s: ser_open(): can't set buffers for \"%s\"\n",
				progname, port);
		return -1;
	}

        fdp->pfd = (void *)hComPort;
	if (ser_setspeed(fdp, pinfo.baud) != 0)
	{
		CloseHandle(hComPort);
		avrdude_message(MSG_INFO, "%s: ser_open(): can't set com-state for \"%s\"\n",
				progname, port);
		return -1;
	}

	if (!serial_w32SetTimeOut(hComPort,0))
	{
		CloseHandle(hComPort);
		avrdude_message(MSG_INFO, "%s: ser_open(): can't set initial timeout for \"%s\"\n",
				progname, port);
		return -1;
	}

	if (newname != 0) {
	    free(newname);
	}
	return 0;
}
Ejemplo n.º 16
0
static int
net_send_packet(struct sk_buff *skb, struct device *dev)
{
	struct net_local *lp = (struct net_local *)dev->priv;
	int ioaddr = dev->base_addr;

	if (dev->tbusy) {
		/* If we get here, some higher level has decided we are broken.
		   There should really be a "kick me" function call instead. */
		int tickssofar = jiffies - dev->trans_start;
		if (tickssofar < 10)
			return 1;
		printk("%s: transmit timed out with status %04x, %s?\n", dev->name,
			   htons(inw(ioaddr + TX_STATUS)),
			   inb(ioaddr + TX_STATUS) & 0x80
			   ? "IRQ conflict" : "network cable problem");
		printk("%s: timeout registers: %04x %04x %04x %04x %04x %04x %04x %04x.\n",
			   dev->name, htons(inw(ioaddr + 0)),
			   htons(inw(ioaddr + 2)), htons(inw(ioaddr + 4)),
			   htons(inw(ioaddr + 6)), htons(inw(ioaddr + 8)),
			   htons(inw(ioaddr +10)), htons(inw(ioaddr +12)),
			   htons(inw(ioaddr +14)));
		printk("eth card: %04x %04x\n",
			htons(inw(ioaddr+FJ_STATUS0)),
			htons(inw(ioaddr+FJ_CONFIG0)));
		lp->stats.tx_errors++;
		/* ToDo: We should try to restart the adaptor... */
		cli();

		/* Initialize LAN Controller and LAN Card */
		outb(0xda, ioaddr + CONFIG_0);   /* Initialize LAN Controller */
		outb(0x00, ioaddr + CONFIG_1);   /* Stand by mode */
		outb(0x00, ioaddr + FJ_CONFIG1); /* Disable IRQ of LAN Card */
		outb(0x00, ioaddr + FJ_BUFCNTL); /* Reset ? I'm not sure */
		net_open(dev);

		sti();
	}

	/* If some higher layer thinks we've missed an tx-done interrupt
	   we are passed NULL. Caution: dev_tint() handles the cli()/sti()
	   itself. */
	if (skb == NULL) {
		dev_tint(dev);
		return 0;
	}

	/* Block a timer-based transmit from overlapping.  This could better be
	   done with atomic_swap(1, dev->tbusy), but set_bit() works as well. */
	if (set_bit(0, (void*)&dev->tbusy) != 0)
		printk("%s: Transmitter access conflict.\n", dev->name);
	else {
		short length = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
		unsigned char *buf = skb->data;

		if (length > ETH_FRAME_LEN) {
			if (net_debug)
				printk("%s: Attempting to send a large packet (%d bytes).\n",
					dev->name, length);
			return 1;
		}

		if (net_debug > 4)
			printk("%s: Transmitting a packet of length %lu.\n", dev->name,
				   (unsigned long)skb->len);

		/* Disable both interrupts. */
		outw(0x0000, ioaddr + TX_INTR);
		
		outw(length, ioaddr + DATAPORT);
		outsw(ioaddr + DATAPORT, buf, (length + 1) >> 1);

		lp->tx_queue++;
		lp->tx_queue_len += length + 2;

		if (lp->tx_started == 0) {
			/* If the Tx is idle, always trigger a transmit. */
			outb(0x80 | lp->tx_queue, ioaddr + TX_START);
			lp->tx_queue = 0;
			lp->tx_queue_len = 0;
			dev->trans_start = jiffies;
			lp->tx_started = 1;
			dev->tbusy = 0;
		} else if (lp->tx_queue_len < 4096 - 1502)
			/* Yes, there is room for one more packet. */
			dev->tbusy = 0;

		/* Re-enable interrupts */
		outw(0x8182, ioaddr + TX_INTR);
	}
	dev_kfree_skb (skb, FREE_WRITE);

	return 0;
}
Ejemplo n.º 17
0
Archivo: mtr.c Proyecto: RichiH/mtr
int main(int argc, char **argv)
{
  struct hostent *  host                = NULL;
  int               net_preopen_result;
#ifdef ENABLE_IPV6
  struct addrinfo       hints, *res;
  int                   error;
  struct hostent        trhost;
  char *                alptr[2];
  struct sockaddr_in *  sa4;
  struct sockaddr_in6 * sa6;
#endif

  /*  Get the raw sockets first thing, so we can drop to user euid immediately  */

  if ( ( net_preopen_result = net_preopen () ) ) {
    fprintf( stderr, "mtr: unable to get raw sockets.\n" );
    exit( EXIT_FAILURE );
  }

  /*  Now drop to user permissions  */
  if (setgid(getgid()) || setuid(getuid())) {
    fprintf (stderr, "mtr: Unable to drop permissions.\n");
    exit(1);
  }

  /*  Double check, just in case  */
  if ((geteuid() != getuid()) || (getegid() != getgid())) {
    fprintf (stderr, "mtr: Unable to drop permissions.\n");
    exit(1);
  }

  /* reset the random seed */
  srand (getpid());

  display_detect(&argc, &argv);

  /* The field options are now in a static array all together,
     but that requires a run-time initialization. */
  init_fld_options ();

  parse_mtr_options (getenv ("MTR_OPTIONS"));

  parse_arg (argc, argv);

  while (optind < argc) {
    char* name = argv[optind++];
    append_to_names(argv[0], name);
  }

  /* Now that we know mtrtype we can select which socket to use */
  if (net_selectsocket() != 0) {
    fprintf( stderr, "mtr: Couldn't determine raw socket type.\n" );
    exit( EXIT_FAILURE );
  }

  if (PrintVersion) {
    printf ("mtr " MTR_VERSION "\n");
    exit(0);
  }

  if (PrintHelp) {
    printf("usage: %s [-hvrwctglspniuT46] [--help] [--version] [--report]\n"
	   "\t\t[--report-wide] [--report-cycles=COUNT] [--curses] [--gtk]\n"
           "\t\t[--csv|-C] [--raw] [--split] [--mpls] [--no-dns] [--show-ips]\n"
           "\t\t[--address interface] [--filename=FILE|-F]\n" /* BL */
#ifdef IPINFO
           "\t\t[--ipinfo=item_no|-y item_no]\n"
           "\t\t[--aslookup|-z]\n"
#endif
           "\t\t[--psize=bytes/-s bytes]\n"            /* ok */
           "\t\t[--report-wide|-w] [-u|-T] [--port=PORT] [--timeout=SECONDS]\n"            /* rew */
	   "\t\t[--interval=SECONDS] HOSTNAME\n", argv[0]);
    exit(0);
  }

  time_t now = time(NULL);

  if (!names) append_to_names (argv[0], "localhost"); // default: localhost. 

  names_t* head = names;
  while (names != NULL) {

    Hostname = names->name;
    //  if (Hostname == NULL) Hostname = "localhost"; // no longer necessary.
    if (gethostname(LocalHostname, sizeof(LocalHostname))) {
      strcpy(LocalHostname, "UNKNOWNHOST");
    }

    if (net_preopen_result != 0) {
      fprintf(stderr, "mtr: Unable to get raw socket.  (Executable not suid?)\n");
      if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE);
      else {
        names = names->next;
        continue;
      }
    }

#ifdef ENABLE_IPV6
    /* gethostbyname2() is deprecated so we'll use getaddrinfo() instead. */
    bzero( &hints, sizeof hints );
    hints.ai_family = af;
    hints.ai_socktype = SOCK_DGRAM;
    error = getaddrinfo( Hostname, NULL, &hints, &res );
    if ( error ) {
      if (error == EAI_SYSTEM)
         perror ("Failed to resolve host");
      else
         fprintf (stderr, "Failed to resolve host: %s\n", gai_strerror(error));

      if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE);
      else {
        names = names->next;
        continue;
      }
    }
    /* Convert the first addrinfo into a hostent. */
    host = &trhost;
    bzero( host, sizeof trhost );
    host->h_name = res->ai_canonname;
    host->h_aliases = NULL;
    host->h_addrtype = res->ai_family;
    af = res->ai_family;
    host->h_length = res->ai_addrlen;
    host->h_addr_list = alptr;
    switch ( af ) {
    case AF_INET:
      sa4 = (struct sockaddr_in *) res->ai_addr;
      alptr[0] = (void *) &(sa4->sin_addr);
      break;
    case AF_INET6:
      sa6 = (struct sockaddr_in6 *) res->ai_addr;
      alptr[0] = (void *) &(sa6->sin6_addr);
      break;
    default:
      fprintf( stderr, "mtr unknown address type\n" );
      if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE);
      else {
        names = names->next;
        continue;
      }
    }
    alptr[1] = NULL;
#else
      host = gethostbyname(Hostname);
    if (host == NULL) {
      herror("mtr gethostbyname");
      if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE);
      else {
        names = names->next;
        continue;
      }
    }
    af = host->h_addrtype;
#endif

    if (net_open(host) != 0) {
      fprintf(stderr, "mtr: Unable to start net module.\n");
      if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE);
      else {
        names = names->next;
        continue;
      }
    }

    if (net_set_interfaceaddress (InterfaceAddress) != 0) {
      fprintf( stderr, "mtr: Couldn't set interface address.\n" );
      if ( DisplayMode != DisplayCSV ) exit(EXIT_FAILURE);
      else {
        names = names->next;
        continue;
      }
    }

    lock(argv[0], stdout);
      display_open();
      dns_open();

      display_mode = 0;
      display_loop();

      net_end_transit();
      display_close(now);
    unlock(argv[0], stdout);

    if ( DisplayMode != DisplayCSV ) break;
    else names = names->next;

  }

  net_close();

  while (head != NULL) {
    names_t* item = head;
    free(item->name); item->name = NULL;
    head = head->next;
    free(item); item = NULL;
  }
  head=NULL;

  return 0;
}
Ejemplo n.º 18
0
int main(int argc, char *argv[])
{
	struct cap_handle *caphandle = NULL;
	struct cvt_handle *cvthandle = NULL;
	struct enc_handle *enchandle = NULL;
	struct pac_handle *pachandle = NULL;
	struct net_handle *nethandle = NULL;
	struct cap_param capp;
	struct cvt_param cvtp;
	struct enc_param encp;
	struct pac_param pacp;
	struct net_param netp;
	int stage = 0b00000011;

	U32 vfmt = V4L2_PIX_FMT_YUYV;
	U32 ofmt = V4L2_PIX_FMT_YUV420;

	// set default values
	capp.dev_name = "/dev/video0";
	capp.width = 640;
	capp.height = 480;
	capp.pixfmt = vfmt;
	capp.rate = 15;

	cvtp.inwidth = 640;
	cvtp.inheight = 480;
	cvtp.inpixfmt = vfmt;
	cvtp.outwidth = 640;
	cvtp.outheight = 480;
	cvtp.outpixfmt = ofmt;

	encp.src_picwidth = 640;
	encp.src_picheight = 480;
	encp.enc_picwidth = 640;
	encp.enc_picheight = 480;
	encp.chroma_interleave = 0;
	encp.fps = 15;
	encp.gop = 12;
	encp.bitrate = 1000;

	pacp.max_pkt_len = 1400;
	pacp.ssrc = 1234;

	netp.serip = NULL;
	netp.serport = -1;
	netp.type = UDP;

	char *outfile = NULL;
	// options
	int opt = 0;
	static const char *optString = "?di:o:a:p:w:h:r:f:t:g:s:c:";

	opt = getopt(argc, argv, optString);
	while (opt != -1)
	{
		int fmt;
		switch (opt)
		{
			case '?':
				display_usage();
				return 0;
			case 'd':
				debug = 1;
				break;
			case 's':
				stage = atoi(optarg);
				break;
			case 'i':
				capp.dev_name = optarg;
				break;
			case 'o':
				outfile = optarg;
				break;
			case 'a':
				netp.serip = optarg;
				break;
			case 'p':
				netp.serport = atoi(optarg);
				break;
			case 'c':
				fmt = atoi(optarg);
				if (fmt == 1)
					capp.pixfmt = V4L2_PIX_FMT_YUV420;
				else
					capp.pixfmt = V4L2_PIX_FMT_YUYV;
				break;
			case 'w':
				capp.width = cvtp.inwidth = cvtp.outwidth = encp.src_picwidth =
						encp.enc_picwidth = atoi(optarg);
				break;
			case 'h':
				capp.height = cvtp.inheight = cvtp.outheight =
						encp.src_picheight = encp.enc_picheight = atoi(optarg);
				break;
			case 'r':
				encp.bitrate = atoi(optarg);
				break;
			case 'f':
				capp.rate = encp.fps = atoi(optarg);
				break;
			case 't':
				encp.chroma_interleave = atoi(optarg);
				break;
			case 'g':
				encp.gop = atoi(optarg);
				break;
			default:
				printf("Unknown option: %s\n", optarg);
				display_usage();
				return -1;
		}

		opt = getopt(argc, argv, optString);
	}

	if (outfile)
		outfd = fopen(outfile, "wb");

	signal(SIGINT, quit_func);

	caphandle = capture_open(capp);
	if (!caphandle)
	{
		printf("--- Open capture failed\n");
		return -1;
	}

	if ((stage & 0b00000001) != 0)
	{
		cvthandle = convert_open(cvtp);
		if (!cvthandle)
		{
			printf("--- Open convert failed\n");
			return -1;
		}
	}

	if ((stage & 0b00000010) != 0)
	{
		enchandle = encode_open(encp);
		if (!enchandle)
		{
			printf("--- Open encode failed\n");
			return -1;
		}
	}

	if ((stage & 0b00000100) != 0)
	{
		pachandle = pack_open(pacp);
		if (!pachandle)
		{
			printf("--- Open pack failed\n");
			return -1;
		}
	}

	if ((stage & 0b00001000) != 0)
	{
		if (netp.serip == NULL || netp.serport == -1)
		{
			printf(
					"--- Server ip and port must be specified when using network\n");
			return -1;
		}

		nethandle = net_open(netp);
		if (!nethandle)
		{
			printf("--- Open network failed\n");
			return -1;
		}
	}

	// start capture encode loop
	int ret;
	void *cap_buf, *cvt_buf, *hd_buf, *enc_buf;
	char *pac_buf = (char *) malloc(MAX_RTP_SIZE);
	int cap_len, cvt_len, hd_len, enc_len, pac_len;
	enum pic_t ptype;
	struct timeval ctime, ltime;
	unsigned long fps_counter = 0;
	int sec, usec;
	double stat_time = 0;

	capture_start(caphandle);		// !!! need to start capture stream!
	quit = 0;
	gettimeofday(&ltime, NULL);
	while (!quit)
	{
		if (debug)		// print fps
		{
			gettimeofday(&ctime, NULL);
			sec = ctime.tv_sec - ltime.tv_sec;
			usec = ctime.tv_usec - ltime.tv_usec;
			if (usec < 0)
			{
				sec--;
				usec = usec + 1000000;
			}
			stat_time = (sec * 1000000) + usec;		// diff in microsecond

			if (stat_time >= 1000000)    // >= 1s
			{
				printf("\n*** FPS: %ld\n", fps_counter);

				fps_counter = 0;
				ltime = ctime;
			}
			fps_counter++;
		}

		ret = capture_get_data(caphandle, &cap_buf, &cap_len);
		if (ret != 0)
		{
			if (ret < 0)		// error
			{
				printf("--- capture_get_data failed\n");
				break;
			}
			else	// again
			{
				usleep(10000);
				continue;
			}
		}
		if (cap_len <= 0)
		{
			printf("!!! No capture data\n");
			continue;
		}
		if (debug)
			fputc('.', stdout);

		if ((stage & 0b00000001) == 0)    // no convert, capture only
		{
			if (outfd)
				fwrite(cap_buf, 1, cap_len, outfd);

			continue;
		}

		// convert
		if (capp.pixfmt == V4L2_PIX_FMT_YUV420)    // no need to convert
		{
			cvt_buf = cap_buf;
			cvt_len = cap_len;
		}
		else	// do convert: YUYV => YUV420
		{
			ret = convert_do(cvthandle, cap_buf, cap_len, &cvt_buf, &cvt_len);
			if (ret < 0)
			{
				printf("--- convert_do failed\n");
				break;
			}
			if (cvt_len <= 0)
			{
				printf("!!! No convert data\n");
				continue;
			}
		}
		if (debug)
			fputc('-', stdout);

		if ((stage & 0b00000010) == 0)		// no encode
		{
			if (outfd)
				fwrite(cvt_buf, 1, cvt_len, outfd);

			continue;
		}

		// encode
		// fetch h264 headers first!
		while ((ret = encode_get_headers(enchandle, &hd_buf, &hd_len, &ptype))
				!= 0)
		{
			if (debug)
				fputc('S', stdout);

			if ((stage & 0b00000100) == 0)		// no pack
			{
				if (outfd)
					fwrite(hd_buf, 1, hd_len, outfd);

				continue;
			}

			// pack headers
			pack_put(pachandle, hd_buf, hd_len);
			while (pack_get(pachandle, pac_buf, MAX_RTP_SIZE, &pac_len) == 1)
			{
				if (debug)
					fputc('#', stdout);

				if ((stage & 0b00001000) == 0)    // no network
				{
					if (outfd)
						fwrite(pac_buf, 1, pac_len, outfd);

					continue;
				}

				// network
				ret = net_send(nethandle, pac_buf, pac_len);
				if (ret != pac_len)
				{
					printf("send pack failed, size: %d, err: %s\n", pac_len,
							strerror(errno));
				}
				if (debug)
					fputc('>', stdout);
			}
		}

		ret = encode_do(enchandle, cvt_buf, cvt_len, &enc_buf, &enc_len,
				&ptype);
		if (ret < 0)
		{
			printf("--- encode_do failed\n");
			break;
		}
		if (enc_len <= 0)
		{
			printf("!!! No encode data\n");
			continue;
		}

		if (debug)
		{
			char c;
			switch (ptype)
			{
				case PPS:
					c = 'S';
					break;
				case SPS:
					c = 'S';
					break;
				case I:
					c = 'I';
					break;
				case P:
					c = 'P';
					break;
				case B:
					c = 'B';
					break;
				default:
					c = 'N';
					break;
			}

			fputc(c, stdout);
		}

		if ((stage & 0b00000100) == 0)		// no pack
		{
			if (outfd)
				fwrite(enc_buf, 1, enc_len, outfd);

			continue;
		}

		// pack
		pack_put(pachandle, enc_buf, enc_len);
		while (pack_get(pachandle, pac_buf, MAX_RTP_SIZE, &pac_len) == 1)
		{
			if (debug)
				fputc('#', stdout);

			if ((stage & 0b00001000) == 0)    // no network
			{
				if (outfd)
					fwrite(pac_buf, 1, pac_len, outfd);

				continue;
			}

			// network
			ret = net_send(nethandle, pac_buf, pac_len);
			if (ret != pac_len)
			{
				printf("send pack failed, size: %d, err: %s\n", pac_len,
						strerror(errno));
			}
			if (debug)
				fputc('>', stdout);
		}
	}
	capture_stop(caphandle);

	free(pac_buf);
	if ((stage & 0b00001000) != 0)
		net_close(nethandle);
	if ((stage & 0b00000100) != 0)
		pack_close(pachandle);
	if ((stage & 0b00000010) != 0)
		encode_close(enchandle);
	if ((stage & 0b00000001) != 0)
		convert_close(cvthandle);
	capture_close(caphandle);

	if (outfd)
		fclose(outfd);
	return 0;
}
Ejemplo n.º 19
0
int
devopen(struct open_file *of, const char *name, char **file)
{
	char *cp;
	char partition;
	char fname[256];
	struct disklabel label;
	int handle, part;
	size_t read;
	int error = 0;
	/* allow disk blocks up to 65536 bytes */
	char buf[DEV_BSIZE<<7];

	if (ofdev.handle != -1)
		panic("devopen");
	if (of->f_flags != F_READ)
		return EPERM;

	strcpy(fname, name);
	cp = filename(fname, &partition);
	if (cp) {
		DPRINTF("filename=%s\n", cp);
		strcpy(buf, cp);
		*cp = 0;
	}
	if (!cp || !*buf)
		strcpy(buf, DEFAULT_KERNEL);

	if (!*fname)
		strcpy(fname, bootdev);
	DPRINTF("fname=%s\n", fname);
	strcpy(opened_name, fname);
	if (partition) {
		cp = opened_name + strlen(opened_name);
		*cp++ = ':';
		*cp++ = partition;
		*cp = 0;
	}
	if (*buf != '/')
		strcat(opened_name, "/");
	strcat(opened_name, buf);
	*file = opened_name + strlen(fname) + 1;
	if (partition) {
		*file += 2;
	}

	if ((handle = OF_finddevice(fname)) == -1) {
		DPRINTF("OF_finddevice(\"%s\") failed\n", fname);
		return ENOENT;
	}

	if (OF_getprop(handle, "name", buf, sizeof buf) < 0)
		return ENXIO;
	floppyboot = !strcmp(buf, "floppy");
	if (OF_getprop(handle, "device_type", buf, sizeof buf) < 0)
		return ENXIO;
	if (!strcmp(buf, "block")) {
		/*
		 * For block devices, indicate raw partition
		 * (:0 in OpenFirmware)
		 */
		strcat(fname, ":0");
	}

	DPRINTF("calling OF_open(fname=%s)\n", fname);
	if ((handle = OF_open(fname)) == -1)
		return ENXIO;
	memset(&ofdev, 0, sizeof ofdev);
	ofdev.handle = handle;

	if (!strcmp(buf, "block")) {
		ofdev.type = OFDEV_DISK;
		ofdev.bsize = DEV_BSIZE;

		/* First try to read a disklabel from a NetBSD MBR partition */
		error = search_mbr_label(&ofdev, 0, buf, &label, 0);

		if (error == ERDLAB) {
			/* Try to construct a disklabel from RDB partitions */
			error = search_rdb_label(&ofdev, buf, &label);

			if (error == ERDLAB) {
				/* At last read a raw NetBSD disklabel */
				error = strategy(&ofdev, F_READ, LABELSECTOR,
				    DEV_BSIZE, buf, &read);
				if (error == 0 && read != DEV_BSIZE)
					error = EIO;
				if (error == 0)
					if (getdisklabel(buf, &label) != NULL)
						error = ERDLAB;
			}
		}

		if (error == ERDLAB) {
			if (partition) {
				/*
				 * User specified a partition,
				 * but there is none.
				 */
				goto bad;
			}
			/* No label, just use complete disk */
			ofdev.partoff = 0;
		} else if (error != 0)
			goto bad;
		else {
			part = partition ? partition - 'a' : 0;
			ofdev.partoff = label.d_partitions[part].p_offset;
			if (label.d_partitions[part].p_fstype == FS_RAID) {
#define RF_PROTECTED_SECTORS 64
				ofdev.partoff += RF_PROTECTED_SECTORS;
				DPRINTF("devopen: found RAID partition, "
				    "adjusting offset to %lx\n", ofdev.partoff);
			}
		}
		of->f_dev = devsw;
		of->f_devdata = &ofdev;
		file_system[0] = file_system_ufs;
		file_system[1] = file_system_cd9660;
		file_system[2] = file_system_dosfs;
		nfsys = 3;
		return 0;
	}

	if (!strcmp(buf, "network")) {
		ofdev.type = OFDEV_NET;
		of->f_dev = devsw;
		of->f_devdata = &ofdev;
		file_system[0] = file_system_nfs;
		nfsys = 1;
		if ((error = net_open(&ofdev)) != 0)
			goto bad;
		return 0;
	}

	error = EFTYPE;
    bad:
	OF_close(handle);
	ofdev.handle = -1;
	return error;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    if (argc < 3)
    {
        printf("Usage: #simple_demo ip port\n");
        return  -1;
    }

	struct cap_handle *caphandle = NULL;
	struct cvt_handle *cvthandle = NULL;
	struct enc_handle *enchandle = NULL;
	struct pac_handle *pachandle = NULL;
    struct net_handle *nethandle = NULL;
	struct cap_param capp;
	struct cvt_param cvtp;
	struct enc_param encp;
	struct pac_param pacp;
    struct net_param netp;

	// set paraments
	U32 vfmt = V4L2_PIX_FMT_YUYV;
	U32 ofmt = V4L2_PIX_FMT_YUV420;

	capp.dev_name = "/dev/video0";
	capp.width = WIDTH;
	capp.height = HEIGHT;
	capp.pixfmt = vfmt;
	capp.rate = FRAMERATE;

	cvtp.inwidth = WIDTH;
	cvtp.inheight = HEIGHT;
	cvtp.inpixfmt = vfmt;
	cvtp.outwidth = WIDTH;
	cvtp.outheight = HEIGHT;
	cvtp.outpixfmt = ofmt;

	encp.src_picwidth = WIDTH;
	encp.src_picheight = HEIGHT;
	encp.enc_picwidth = WIDTH;
	encp.enc_picheight = HEIGHT;
	encp.chroma_interleave = 0;
	encp.fps = FRAMERATE;
	encp.gop = 30;
	encp.bitrate = 800;

	pacp.max_pkt_len = 1400;
	pacp.ssrc = 10;

    netp.type = UDP;
    netp.serip = argv[1];
    netp.serport = atoi(argv[2]);

	caphandle = capture_open(capp);
	if (!caphandle)
	{
		printf("--- Open capture failed\n");
		return -1;
	}

	cvthandle = convert_open(cvtp);
	if (!cvthandle)
	{
		printf("--- Open convert failed\n");
		return -1;
	}

	enchandle = encode_open(encp);
	if (!enchandle)
	{
		printf("--- Open encode failed\n");
		return -1;
	}

	pachandle = pack_open(pacp);
	if (!pachandle)
	{
		printf("--- Open pack failed\n");
		return -1;
	}

    nethandle = net_open(netp);
    if (!nethandle)
    {
        printf("--- Open network failed\n");
        return -1;
    }

	// start stream loop
	int ret;
	void *cap_buf, *cvt_buf, *hd_buf, *enc_buf, *pac_buf;
	int cap_len, cvt_len, hd_len, enc_len, pac_len;
	enum pic_t ptype;
	unsigned long framecount = 0;

	capture_start(caphandle);		// !!! need to start capture stream!

	while (1)
	{
		ret = capture_get_data(caphandle, &cap_buf, &cap_len);
		if (ret != 0)
		{
			if (ret < 0)		// error
			{
				printf("--- capture_get_data failed\n");
				break;
			}
			else	// again
			{
				usleep(10000);
				continue;
			}
		}
		if (cap_len <= 0)
		{
			printf("!!! No capture data\n");
			continue;
		}
		// else

		ret = convert_do(cvthandle, cap_buf, cap_len, &cvt_buf, &cvt_len);
		if (ret < 0)
		{
			printf("--- convert_do failed\n");
			break;
		}
		if (cvt_len <= 0)
		{
			printf("!!! No convert data\n");
			continue;
		}
		// else

		// fetch h264 headers first!
		while ((ret = encode_get_headers(enchandle, &hd_buf, &hd_len, &ptype))
				== 1)
		{
            //fwrite(hd_buf, 1, hd_len, dumpfile);
			pack_put(pachandle, hd_buf, hd_len);
			while (pack_get(pachandle, &pac_buf, &pac_len) == 1)
			{
                ret = net_send(nethandle, pac_buf, pac_len);
				if (ret != pac_len)
				{
					printf("send pack data failed, size: %d, err: %s\n", pac_len,
							strerror(errno));
				}
			}
		}

		ret = encode_do(enchandle, cvt_buf, cvt_len, &enc_buf, &enc_len,
				&ptype);
		if (ret < 0)
		{
			printf("--- encode_do failed\n");
			break;
		}
		if (enc_len <= 0)
		{
			printf("!!! No encode data\n");
			continue;
		}
		// else

        //fwrite(enc_buf, 1, enc_len, dumpfile);
		// RTP pack and send
		pack_put(pachandle, enc_buf, enc_len);
		while (pack_get(pachandle, &pac_buf, &pac_len) == 1)
		{
            ret = net_send(nethandle, pac_buf, pac_len);
			if (ret != pac_len)
			{
				printf("send pack failed, size: %d, err: %s\n", pac_len,
						strerror(errno));
			}
		}

		framecount++;
	}
	capture_stop(caphandle);

    net_close(nethandle);
	pack_close(pachandle);
	encode_close(enchandle);
	convert_close(cvthandle);
	capture_close(caphandle);

	return 0;
}
Ejemplo n.º 21
0
		if (!len) continue;

		handle_irc_packet(tty, len, (unsigned char *)buf);
	}
}

DEFINE_SHELL_FUNCTION(irc_init, "irc connector") {
	/* TODO set up IRC socket */

	if (irc_socket) {
		fprintf(tty, "There is already an active IRC connection.\n");
		fprintf(tty, "This module doesn't support more than one connection.\n");
		return 0;
	}

	irc_socket = net_open(SOCK_STREAM);

	if (argc < 2) {
		net_connect(irc_socket, ip_aton("104.131.140.26"), 6667);
	} else if (argc < 3) {
		net_connect(irc_socket, ip_aton(argv[1]), 6667);
	} else {
		net_connect(irc_socket, ip_aton(argv[1]), atoi(argv[2]));
	}

	fprintf(tty, "[irc] Socket is at 0x%x\n", irc_socket);

	/* TODO set up IRC daemon */
	create_kernel_tasklet(ircd, "[ircd]", tty);

	return 0;
Ejemplo n.º 22
0
SENDSTREAM *smtp_open_full (NETDRIVER *dv,char **hostlist,char *service,
			    unsigned long port,long options)
{
  SENDSTREAM *stream = NIL;
  long reply;
  char *s,tmp[MAILTMPLEN];
  NETSTREAM *netstream;
  NETMBX mb;
  if (!(hostlist && *hostlist)) mm_log ("Missing SMTP service host",ERROR);
				/* maximum domain name is 64 characters */
  else do if (strlen (*hostlist) < SMTPMAXDOMAIN) {
    sprintf (tmp,"{%.1000s}",*hostlist);
    if (!mail_valid_net_parse_work (tmp,&mb,service ? service : "smtp") ||
	mb.anoflag || mb.readonlyflag) {
      sprintf (tmp,"Invalid host specifier: %.80s",*hostlist);
      mm_log (tmp,ERROR);
    }
    else {			/* light tryssl flag if requested */
      mb.trysslflag = (options & SOP_TRYSSL) ? T : NIL;
				/* explicit port overrides all */
      if (mb.port) port = mb.port;
				/* else /submit overrides port argument */
      else if (!compare_cstring (mb.service,"submit")) {
	port = SUBMITTCPPORT;	/* override port, use IANA name */
	strcpy (mb.service,"submission");
      }
				/* else port argument overrides SMTP port */
      else if (!port) port = smtp_port ? smtp_port : SMTPTCPPORT;
      if (netstream =		/* try to open ordinary connection */
	  net_open (&mb,dv,port,
		    (NETDRIVER *) mail_parameters (NIL,GET_SSLDRIVER,NIL),
		    "*smtps",smtp_sslport ? smtp_sslport : SMTPSSLPORT)) {
	stream = (SENDSTREAM *) memset (fs_get (sizeof (SENDSTREAM)),0,
					sizeof (SENDSTREAM));
	stream->netstream = netstream;
	stream->host = cpystr ((long) mail_parameters (NIL,GET_TRUSTDNS,NIL) ?
			       net_host (netstream) : mb.host);
	stream->debug = (mb.dbgflag || (options & OP_DEBUG)) ? T : NIL;
	if (options & SOP_SECURE) mb.secflag = T;
				/* get name of local host to use */
	s = compare_cstring ("localhost",mb.host) ?
	  net_localhost (netstream) : "localhost";

	do reply = smtp_reply (stream);
	while ((reply < 100) || (stream->reply[3] == '-'));
	if (reply != SMTPGREET){/* get SMTP greeting */
	  sprintf (tmp,"SMTP greeting failure: %.80s",stream->reply);
	  mm_log (tmp,ERROR);
	  stream = smtp_close (stream);
	}
				/* try EHLO first, then HELO */
	else if (((reply = smtp_ehlo (stream,s,&mb)) != SMTPOK) &&
		 ((reply = smtp_send (stream,"HELO",s)) != SMTPOK)) {
	  sprintf (tmp,"SMTP hello failure: %.80s",stream->reply);
	  mm_log (tmp,ERROR);
	  stream = smtp_close (stream);
	}
	else {
	  NETDRIVER *ssld =(NETDRIVER *)mail_parameters(NIL,GET_SSLDRIVER,NIL);
	  sslstart_t stls = (sslstart_t) mail_parameters(NIL,GET_SSLSTART,NIL);
	  ESMTP.ok = T;		/* ESMTP server, start TLS if present */
	  if (!dv && stls && ESMTP.service.starttls &&
	      !mb.sslflag && !mb.notlsflag &&
	      (smtp_send (stream,"STARTTLS",NIL) == SMTPGREET)) {
	    mb.tlsflag = T;	/* TLS OK, get into TLS at this end */
	    stream->netstream->dtb = ssld;
				/* TLS started, negotiate it */
	    if (!(stream->netstream->stream = (*stls)
		  (stream->netstream->stream,mb.host,
		   (mb.tlssslv23 ? NIL : NET_TLSCLIENT) |
		   (mb.novalidate ? NET_NOVALIDATECERT:NIL)))){
				/* TLS negotiation failed after STARTTLS */
	      sprintf (tmp,"Unable to negotiate TLS with this server: %.80s",
		       mb.host);
	      mm_log (tmp,ERROR);
				/* close without doing QUIT */
	      if (stream->netstream) net_close (stream->netstream);
	      stream->netstream = NIL;
	      stream = smtp_close (stream);
	    }
				/* TLS OK, re-negotiate EHLO */
	    else if ((reply = smtp_ehlo (stream,s,&mb)) != SMTPOK) {
	      sprintf (tmp,"SMTP EHLO failure after STARTTLS: %.80s",
		       stream->reply);
	      mm_log (tmp,ERROR);
	      stream = smtp_close (stream);
	    }
	    else ESMTP.ok = T;	/* TLS OK and EHLO successful */
	  }
	  else if (mb.tlsflag) {/* user specified /tls but can't do it */
	    sprintf (tmp,"TLS unavailable with this server: %.80s",mb.host);
	    mm_log (tmp,ERROR);
	    stream = smtp_close (stream);
	  }

				/* remote name for authentication */
	  if (stream && ((mb.secflag || mb.user[0]))) {
	    if (ESMTP.auth) {	/* use authenticator? */
	      if ((long) mail_parameters (NIL,GET_TRUSTDNS,NIL)) {
				/* remote name for authentication */
		strncpy (mb.host,
			 (long) mail_parameters (NIL,GET_SASLUSESPTRNAME,NIL) ?
			 net_remotehost (netstream) : net_host (netstream),
			 NETMAXHOST-1);
		mb.host[NETMAXHOST-1] = '\0';
	      }
	      if (!smtp_auth (stream,&mb,tmp)) stream = smtp_close (stream);
	    }
	    else {		/* no available authenticators? */
	      sprintf (tmp,"%sSMTP authentication not available: %.80s",
		       mb.secflag ? "Secure " : "",mb.host);
	      mm_log (tmp,ERROR);
	      stream = smtp_close (stream);
	    }
	  }
	}
      }
    }
  } while (!stream && *++hostlist);
  if (stream) {			/* set stream options if have a stream */
    if (options &(SOP_DSN | SOP_DSN_NOTIFY_FAILURE | SOP_DSN_NOTIFY_DELAY |
		  SOP_DSN_NOTIFY_SUCCESS | SOP_DSN_RETURN_FULL)) {
      ESMTP.dsn.want = T;
      if (options & SOP_DSN_NOTIFY_FAILURE) ESMTP.dsn.notify.failure = T;
      if (options & SOP_DSN_NOTIFY_DELAY) ESMTP.dsn.notify.delay = T;
      if (options & SOP_DSN_NOTIFY_SUCCESS) ESMTP.dsn.notify.success = T;
      if (options & SOP_DSN_RETURN_FULL) ESMTP.dsn.full = T;
    }
    if (options & SOP_8BITMIME) ESMTP.eightbit.want = T;
  }
  return stream;
}
Ejemplo n.º 23
0
int
main (int argc, char **argv)
{
  net_addr remote;
  int serial;
  int net;

  graphics_initialise ();
  graphics_mode (0);

  serial = serial_open ();
  net = net_open ();

  if (argc != 1)
  {
    if (argc != 2)
    {
      fprintf (stderr, "only 1 or 0 args\n");
      return 1;
    }

    if (strcmp (argv[1], "--final"))
    {
      fprintf (stderr, "unrecognised option\n");
      return 1;
    }
  }
  else
    randomised = true;

  printf ("randomised: %d\n", randomised);

  while (serial_ready (serial))
    serial_discard (serial);
  net_addr_set (&remote, "10.0.0.2");

  while (true)
  {
    bool ended;

    /* wait for user */
    reset_the_physics (true);
    publish_the_physics (serial, net, &remote);
    graphics_render (0, 0);

    while (!serial_ready (serial))
      check_sdl ();

    reset_the_physics (false);
    ended = false;
    while (!ended)
    {
      serial_read (serial);
      poll (NULL, 0, 10);
      ended = physics_update ();
      publish_the_physics (serial, net, &remote);
      check_sdl ();
      graphics_render (0, 0);
    }

    while (check_sdl () != ' ')
      poll (NULL, 0, 10);

    while (serial_ready (serial))
      serial_read (serial);
  }
}
Ejemplo n.º 24
0
int
main(int argc, char **argv)
{
	struct stat buf;
	int ret;
	char scratch[BUFSIZ];
	char log[BUFSIZ];
	char olog[BUFSIZ];
	char *scratch_p = scratch;
	char *mytag_p;
	FILE *fp;
	extern char *getenv();
	char *parse();
	int	c;
	extern	char *optarg;
	extern	int optind;
	int i;
	char	*Mytag_p = Mytag;

	/* Get my port monitor tag out of the environment		*/
	if ((mytag_p = getenv("PMTAG")) == NULL) {
		/* no place to write */
		exit(1);
	}
	strcpy(Mytag, mytag_p);

	/* open log file */
	sprintf(log, "%s/%s/%s", ALTDIR, Mytag_p, LOGNAME);
	sprintf(olog, "%s/%s/%s", ALTDIR, Mytag_p, OLOGNAME);
	if (stat(log, &buf) == 0) {
		/* file exists, try and save it but if we can't don't worry */
		unlink(olog);
		rename(log, olog);
	}
	if ((i = open(log, O_WRONLY|O_CREAT|O_APPEND, 0444)) < 0)
		logexit(1, nologfile);
	/* as stated above, the log file should be file descriptor 5 */
	if ((ret = fcntl(i, F_DUPFD, 5)) != 5)
		logexit(1, nologfile);
	Logfp = fdopen(ret, "a+");

	/* Get my port monitor tag out of the environment		*/
	if ((mytag_p = getenv("PMTAG")) == NULL) {
		logexit(1, nopmtag);
	}
	strcpy(Mytag, mytag_p);

	(void) umask(022);
	Readdb = FALSE;

	if (geteuid() != (uid_t) 0) {
		logmessage("Must be root to start listener");
		logexit(1, badstart);
	}

	while ((c = getopt(argc, argv, "m:")) != EOF) 
		switch (c) {
		case 'm':
			Minor_prefix = optarg;
			break;
		default:
			logexit(1, usage);
			break;
		}

	if ((Netspec = argv[optind]) == NULL) {
		logexit(1, usage);
	}
	if ((Netconf = getnetconfigent(Netspec)) == NULL) {
		sprintf(scratch, "no netconfig entry for <%s>", Netspec);
		logmessage(scratch);
		logexit(1, badstart);
	}
	if (!Minor_prefix)
		Minor_prefix = argv[optind];

	if ((int) strlen(Netspec) > PATHSIZE)  {
		logmessage(badnspmsg);
		logexit(1, badstart);
	}

	/* 
	 * SAC will start the listener in the correct directory, so we
	 * don't need to chdir there, as we did in older versions
	 */

	strcpy(Provbuf, "/dev/");
	strcat(Provbuf, Netspec);

	(void) umask(0);

	init_files();		/* open Accept, Sac, Pm, Pass files	*/
	pid_open();		/* create pid file			*/

#ifdef	DEBUGMODE
	sprintf(scratch, "%s/%s/%s", ALTDIR, Mytag, DBGNAME);
	Debugfp = fopen(scratch, "w");
#endif


#ifdef	DEBUGMODE
	if ((!Logfp) || (!Debugfp)) 
#else
	if (!Logfp)
#endif
		logexit(1, badstart);

/*
 * In case we started with no environment, find out what timezone we're
 * in.  This will get passed to children, so only need to do once.
 */

	if (getenv("TZ") == NULL) {
		fp = fopen(TZFILE, "r");
		if (fp) {
			while (fgets(tzenv, BUFSIZ, fp)) {
				if (tzenv[strlen(tzenv) - 1] == '\n')
					tzenv[strlen(tzenv) - 1] = '\0';
				if (!strncmp(TZSTR, tzenv, strlen(TZSTR))) {
					putenv(parse(tzenv));
					break;
				}
			}
			fclose(fp);
		}
		else {
			sprintf(scratch, "couldn't open %s, default to GMT",
			    TZFILE);
			logmessage(scratch);
		}
	}

	logmessage("@(#)listen:listen.c	1.19.9.1");

#ifdef	DEBUGMODE
	logmessage("Listener process with DEBUG capability");
#endif

	sprintf(scratch, "Listener port monitor tag: %s", Mytag_p);
	logmessage(scratch);
	DEBUG((9, "Minor prefix: %s  Netspec %s", Minor_prefix, Netspec));

	/* fill in Pmmesg fields that always stay the same */

	Pmmsg.pm_maxclass = MAXCLASS;
	strcpy(Pmmsg.pm_tag, Mytag_p);
	Pmmsg.pm_size = 0;

	/* Find out what state to start in.  If not in env, exit */
	if ((scratch_p = getenv("ISTATE")) == NULL)
		logexit(1, "ERROR: ISTATE variable not set in environment");
	
	if (!strcmp(scratch_p, "enabled")) {
		State = PM_ENABLED;
		logmessage("Starting state: ENABLED");
	}
	else {
		State = PM_DISABLED;
		logmessage("Starting state: DISABLED");
	}

	/* try to get my "basename"		*/
	Progname = strrchr(argv[0], '/');
	if (Progname && Progname[1])
		++Progname;
	else
		Progname = argv[0];

	catch_signals();

	/* 
	 * Allocate memory for private address and file descriptor table 
	 * Here we are assuming that no matter how many private addresses
	 * exist in the system if the system limit is 20 then we will only
	 * get 20 file descriptors
	 */

	Ndesc = ulimit(4,0L);		/* get num of file des on system */

	read_dbf(DB_INIT);
	net_open();			/* init, open, bind names 	*/

	for (i = 3; i < Ndesc; i++)  {	/* leave stdout, stderr open	*/
		fcntl(i, F_SETFD, 1);	/* set close on exec flag*/
	}

	logmessage("Initialization Complete");

	listen();
	return (0);
}
Ejemplo n.º 25
0
/* Get and print status from apcupsd NIS server */
static int apc_query_server (char *host, int port,
		struct apc_detail_s *apcups_detail)
{
	int     n;
	char    recvline[1024];
	char   *tokptr;
	char   *toksaveptr;
	char   *key;
	double  value;
	_Bool retry = 1;
	int status;

#if APCMAIN
# define PRINT_VALUE(name, val) printf("  Found property: name = %s; value = %f;\n", name, val)
#else
# define PRINT_VALUE(name, val) /**/
#endif

	while (retry)
	{
		if (global_sockfd < 0)
		{
			global_sockfd = net_open (host, port);
			if (global_sockfd < 0)
			{
				ERROR ("apcups plugin: Connecting to the "
						"apcupsd failed.");
				return (-1);
			}
		}


		status = net_send (&global_sockfd, "status", strlen ("status"));
		if (status != 0)
		{
			/* net_send is closing the socket on error. */
			assert (global_sockfd < 0);
			if (retry)
			{
				retry = 0;
				count_retries++;
				continue;
			}

			ERROR ("apcups plugin: Writing to the socket failed.");
			return (-1);
		}

		break;
	} /* while (retry) */

        /* When collectd's collection interval is larger than apcupsd's
         * timeout, we would have to retry / re-connect each iteration. Try to
         * detect this situation and shut down the socket gracefully in that
         * case. Otherwise, keep the socket open to avoid overhead. */
	count_iterations++;
	if ((count_iterations == 10) && (count_retries > 2))
	{
		NOTICE ("apcups plugin: There have been %i retries in the "
				"first %i iterations. Will close the socket "
				"in future iterations.",
				count_retries, count_iterations);
		close_socket = 1;
	}

	while ((n = net_recv (&global_sockfd, recvline, sizeof (recvline) - 1)) > 0)
	{
		assert ((unsigned int)n < sizeof (recvline));
		recvline[n] = '\0';
#if APCMAIN
		printf ("net_recv = `%s';\n", recvline);
#endif /* if APCMAIN */

		toksaveptr = NULL;
		tokptr = strtok_r (recvline, " :\t", &toksaveptr);
		while (tokptr != NULL)
		{
			key = tokptr;
			if ((tokptr = strtok_r (NULL, " :\t", &toksaveptr)) == NULL)
				continue;
			value = atof (tokptr);

			PRINT_VALUE (key, value);

			if (strcmp ("LINEV", key) == 0)
				apcups_detail->linev = value;
			else if (strcmp ("BATTV", key) == 0)
				apcups_detail->battv = value;
			else if (strcmp ("ITEMP", key) == 0)
				apcups_detail->itemp = value;
			else if (strcmp ("LOADPCT", key) == 0)
				apcups_detail->loadpct = value;
			else if (strcmp ("BCHARGE", key) == 0)
				apcups_detail->bcharge = value;
			else if (strcmp ("OUTPUTV", key) == 0)
				apcups_detail->outputv = value;
			else if (strcmp ("LINEFREQ", key) == 0)
				apcups_detail->linefreq = value;
			else if (strcmp ("TIMELEFT", key) == 0)
			{
				/* Convert minutes to seconds if requested by
				 * the user. */
				if (conf_report_seconds)
					value *= 60.0;
				apcups_detail->timeleft = value;
			}

			tokptr = strtok_r (NULL, ":", &toksaveptr);
		} /* while (tokptr != NULL) */
	}
	status = errno; /* save errno, net_shutdown() may re-set it. */

	if (close_socket)
		net_shutdown (&global_sockfd);

	if (n < 0)
	{
		char errbuf[1024];
		ERROR ("apcups plugin: Reading from socket failed: %s",
				sstrerror (status, errbuf, sizeof (errbuf)));
		return (-1);
	}

	return (0);
}
Ejemplo n.º 26
0
static int
quh_cddb_in_open (st_quh_nfo_t * file)
{
  int x = 0;
  char buf[MAXBUFSIZE];
  int t = 0, n = 0;
  char buf2[MAXBUFSIZE];
  char *p = NULL;
  st_http_header_t http_header;
  char http_header_s[NET_MAXHTTPHEADERSIZE];

  if (!inited)
    { 
      if (!quh_get_object_s (quh.filter_chain, QUH_OPTION))
        quh_set_object_s (quh.filter_chain, QUH_OPTION, "http://freedb.freedb.org/~cddb/cddb.cgi");

#ifdef  USE_TCP
      net = net_init (NET_TCP|NET_CLIENT, 5);
#endif
      inited = 1; 
    }

  *buf = 0;
  if (!file->indices)
    {
      strcpy (buf, "Failed: Input has no indices");

      quh_set_object_s (quh.filter_chain, QUH_OUTPUT, buf);
  
      return 0;
    }

  for (x = 0; x < file->indices; x++)
    {
      // add to cddb_sum
      n += cddb_sum (file->index_pos[x] / file->channels / file->size / file->rate);

      if (x == 0)
        t = (file->raw_size / file->channels / file->size / file->rate) - 
            (file->index_pos[x] / file->channels / file->size / file->rate) -
            ((file->index_pos[x] / file->channels / file->size / file->rate) % 60); 
    }

  cddb_id = (n % 0xff) << 24 | t << 8 | file->indices;

#ifdef  USE_TCP
  net_open (net, cddb_host, 80);

  sprintf (buf, "%s%s?cmd=cddb+query+%08lx+%d+",
    cddb_host,
    cddb_uri,
    cddb_id,
    file->indices);
  
  for (x = 0; x < file->indices; x++)
    sprintf (strchr (buf, 0), "%ld+", (file->index_pos[x] / 2352) + 150);

  sprintf (strchr (buf, 0), "%ld&hello=anonymous+localhost+%s+%s&proto=6",
    ((file->raw_size / 2352) + 150) / 75,
    "Quh",
    QUH_VERSION_S);

  net_build_http_request (http_header_s, buf, "Quh", 0, NET_METHOD_GET, 0);

  net_write (net, http_header_s, strlen (http_header_s));

  net_parse_http_response (&http_header, net);

  // before: classical 9b10f50b Wayne Marshall / Symphonie
  // after: classical+9b10f50b
  while (net_gets (net, buf, MAXBUFSIZE))
    {
      // 200 classical 9e10cb0b Wayne Marshall / Organ Transcriptions
      if (!strncmp (buf, "200 ", 4))
        {
          strtrim_s (buf, "200 ", NULL);
          p = strchr (buf, ' ');

          if (p)
            *p = '+';

          p = strchr (buf, ' ');

          if (p)
            *p = 0;

          strncpy (buf2, buf, MAXBUFSIZE)[MAXBUFSIZE - 1] = 0;

          break;
        }

      // 211 Found inexact matches, list follows (until terminating .')
      // classical 9b10f50b Wayne Marshall / Symphonie
      // .
      if (!strncmp (buf, "211 ", 4))
        if (net_gets (net, buf, MAXBUFSIZE))
          {
            p = strchr (buf, ' ');

            if (p)
              *p = '+';

            p = strchr (buf, ' ');

            if (p)
              *p = 0;

            strncpy (buf2, buf, MAXBUFSIZE)[MAXBUFSIZE - 1] = 0;

            break;
          }
    }

  // we don't use the http keep alive flag
  net_close (net);
  net_open (net, cddb_host, 80);

  sprintf (buf, "%s%s?cmd=cddb+read+%s&hello=anonymous+localhost+%s+%s&proto=6",
    cddb_host,
    cddb_uri,
    buf2,
    "Quh",
    QUH_VERSION_S);

  p = net_build_http_request (buf, "Quh", 0, NET_METHOD_GET, 0);
  
  net_write (net, p, strlen (p));
  
  net_parse_http_response (net);

  x = 0;
  while (net_gets (net, buf, MAXBUFSIZE))
    if (!strncmp (buf, "TTITLE", 6))
      {
        sprintf (buf2, "TTITLE%d", x);
        p = (char *) get_property_from_string (buf, buf2, '=', '#');
        if (p)
          strncpy (file->index_name[x], p, QUH_INDEX_NAME_LEN)[QUH_INDEX_NAME_LEN - 1] = 0;
        else
          *(file->index_name[x]) = 0;

#ifdef  DEBUG
        printf ("%s\n\n", file->index_name[x]);
#endif

        x++;

        if (x == file->indices)
          break;
      }

  net_close (net);  
#endif  // USE_TCP

  *buf = 0;
  sprintf (strchr (buf, 0), "DiscId: 0x%08lx\n", cddb_id);

  if (file->indices)
    for (x = 1 ; x < file->indices + 1; x++)
      {
        unsigned long len = (x < file->indices ? file->index_pos[x] : file->raw_size) - file->index_pos[x - 1];

        sprintf (strchr (buf, 0), "%0*d:", misc_digits (QUH_MAXINDEX), x);

        sprintf (strchr (buf, 0), " %s", file->index_name[x - 1]);

        sprintf (strchr (buf, 0), "%s",
          quh_bytes_to_units (file, len, QUH_UNITS_CLOCK));
        
        if (x < file->indices)
          strcat (buf, "\n");
      }

  quh_set_object_s (quh.filter_chain, QUH_OUTPUT, buf);

  return 0;
}