Example #1
0
void build_request(const char *url)
{
	char tmp[10];
	int i;

	bzero(host,MAXHOSTNAMELEN);
	bzero(request,REQUEST_SIZE);

	if(force_reload && proxyhost!=NULL && http10<1) http10=1;
	if(method==METHOD_HEAD && http10<1) http10=1;
	if(method==METHOD_OPTIONS && http10<2) http10=2;
	if(method==METHOD_TRACE && http10<2) http10=2;

	switch(method)
	{
		default:
		case METHOD_GET: strcpy(request,"GET");break;
		case METHOD_HEAD: strcpy(request,"HEAD");break;
		case METHOD_OPTIONS: strcpy(request,"OPTIONS");break;
		case METHOD_TRACE: strcpy(request,"TRACE");break;
	}

	strcat(request," ");

	if(NULL==strstr(url,"://"))
	{
		fprintf(stderr, "\n%s: is not a valid URL.\n",url);
		exit(2);
	}
	if(strlen(url)>1500)
	{
		fprintf(stderr,"URL is too long.\n");
		exit(2);
	}
	if(proxyhost==NULL)
		if (0!=strncasecmp("http://",url,7)) 
		{ fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n");
			exit(2);
		}
	/* protocol/host delimiter */
	i=strstr(url,"://")-url+3;
	/* printf("%d\n",i); */

	if(strchr(url+i,'/')==NULL) {
		fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n");
		exit(2);
	}
	if(proxyhost==NULL)
	{
		/* get port from hostname */
		if(index(url+i,':')!=NULL &&
				index(url+i,':')<index(url+i,'/'))
		{
			strncpy(host,url+i,strchr(url+i,':')-url-i);
			bzero(tmp,10);
			strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1);
			/* printf("tmp=%s\n",tmp); */
			proxyport=atoi(tmp);
			if(proxyport==0) proxyport=80;
		} else
		{
			strncpy(host,url+i,strcspn(url+i,"/"));
		}
		// printf("Host=%s\n",host);
		strcat(request+strlen(request),url+i+strcspn(url+i,"/"));
	} else
	{
		// printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport);
		strcat(request,url);
	}
	if(http10==1)
		strcat(request," HTTP/1.0");
	else if (http10==2)
		strcat(request," HTTP/1.1");
	strcat(request,"\r\n");
	if(http10>0)
		strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n");
	if(proxyhost==NULL && http10>0)
	{
		strcat(request,"Host: ");
		strcat(request,host);
		strcat(request,"\r\n");
	}
	if(force_reload && proxyhost!=NULL)
	{
		strcat(request,"Pragma: no-cache\r\n");
	}
	if(http10>1)
		strcat(request,"Connection: close\r\n");
	/* add empty line at end */
	if(http10>0) strcat(request,"\r\n"); 
	// printf("Req=%s\n",request);
}
static int findRoots(const QuadImplicitForm& i, const Quadratic& q2, double roots[4],
        bool useCubic, bool& disregardCount) {
    double a, b, c;
    set_abc(&q2[0].x, a, b, c);
    double d, e, f;
    set_abc(&q2[0].y, d, e, f);
    const double t4 =     i.x2() *  a * a
                    +     i.xy() *  a * d
                    +     i.y2() *  d * d;
    const double t3 = 2 * i.x2() *  a * b
                    +     i.xy() * (a * e +     b * d)
                    + 2 * i.y2() *  d * e;
    const double t2 =     i.x2() * (b * b + 2 * a * c)
                    +     i.xy() * (c * d +     b * e + a * f)
                    +     i.y2() * (e * e + 2 * d * f)
                    +     i.x()  *  a
                    +     i.y()  *  d;
    const double t1 = 2 * i.x2() *  b * c
                    +     i.xy() * (c * e + b * f)
                    + 2 * i.y2() *  e * f
                    +     i.x()  *  b
                    +     i.y()  *  e;
    const double t0 =     i.x2() *  c * c
                    +     i.xy() *  c * f
                    +     i.y2() *  f * f
                    +     i.x()  *  c
                    +     i.y()  *  f
                    +     i.c();
#if QUARTIC_DEBUG
    // create a string mathematica understands
    char str[1024];
    bzero(str, sizeof(str));
    sprintf(str, "Solve[%1.19g x^4 + %1.19g x^3 + %1.19g x^2 + %1.19g x + %1.19g == 0, x]",
        t4, t3, t2, t1, t0);
#endif
    if (approximately_zero(t4)) {
        disregardCount = true;
        if (approximately_zero(t3)) {
            return quadraticRootsX(t2, t1, t0, roots);
        }
        return cubicRootsX(t3, t2, t1, t0, roots);
    }
    if (approximately_zero(t0)) { // 0 is one root
        disregardCount = true;
        int num = cubicRootsX(t4, t3, t2, t1, roots);
        for (int i = 0; i < num; ++i) {
            if (approximately_zero(roots[i])) {
                return num;
            }
        }
        roots[num++] = 0;
        return num;
    }
    if (useCubic) {
        assert(approximately_zero(t4 + t3 + t2 + t1 + t0)); // 1 is one root
        int num = cubicRootsX(t4, t4 + t3, -(t1 + t0), -t0, roots); // note that -C==A+B+D+E
        for (int i = 0; i < num; ++i) {
            if (approximately_equal(roots[i], 1)) {
                return num;
            }
        }
        roots[num++] = 1;
        return num;
    }
    return quarticRoots(t4, t3, t2, t1, t0, roots);
}
Example #3
0
main()
{
    int                 sockfd , clisockfd;
    unsigned int        clilen;
    int                 childpid;
    struct sockaddr_in  serv_addr,cli_addr;
#ifdef LPR_with_ASUS//JY1112
    int 		LPRflag = 0;
    fd_set		rfds, afds;
    int			nfds,nfds1;
    int			sockfd_ASUS;
    unsigned int        clilen_ASUS;
    int                 childpid_ASUS;
    struct sockaddr_in  serv_addr_ASUS,cli_addr_ASUS;
#endif
#ifdef Raw_Printing_with_ASUS  //Lisa
    int		netfd, fd, clientlen, one = 1;
    struct sockaddr_in	netaddr, client;
#endif

    //Initial the server the not busy
    lptstatus.busy = FALSE;

    //Setup the signal handler
    signal(SIGCLD, sig_child);
    signal(SIGINT, sig_cleanup);
    signal(SIGQUIT, sig_cleanup);
    signal(SIGKILL, sig_cleanup);
    signal(SIGUSR2, sig_remove);//JY1110

    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0 )
    {
        perror("can't open stream socket:");
        exit(0);
    }

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


    if(bind(sockfd,(struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0 )
    {
        perror("can't bind:");
        exit(0);
    }
    /*JY1111*/
    int windowsize=2920;
    setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (char *)&windowsize, sizeof(windowsize));

#if 1
    int currentpid=getpid();
    FILE *pidfileread;

    if((pidfileread=fopen("/var/run/lpdparent.pid", "r")) == NULL) {
        pidfileread=fopen("/var/run/lpdparent.pid", "w");
        fprintf(pidfileread, "%d", currentpid);
        fclose(pidfileread);
    }
    else {
        printf("another lpd daemon exists!!\n");
        fclose(pidfileread);
        exit(0);
    }
#endif
    /*JY1110
    	int testusb = 0;
    	testusb = check_par_usb_prn();
    	if(testusb){
    		printf("USB\n");//JY1112delete
    		fd_print=open("/dev/usb/lp0", O_RDWR);
    	}
    	else{
    		printf("PARALLEL\n");//JY1112delete
    		fd_print=open("/dev/lp0", O_RDWR);
    	}
    	checkstatus_usb_par();
    	close(fd_print);
    111111*/

    listen(sockfd , 15);

#ifdef Raw_Printing_with_ASUS //Lisa
    if ((netfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) < 0)
    {
//		syslog(LOGOPTS, "socket: %m\n");
        exit(1);
    }
    if (setsockopt(netfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
    {
//		syslog(LOGOPTS, "setsocketopt: %m\n");
        exit(1);
    }
    netaddr.sin_port = htons(BASEPORT);
    netaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    memset(netaddr.sin_zero, 0, sizeof(netaddr.sin_zero));
    if (bind(netfd, (struct sockaddr*) &netaddr, sizeof(netaddr)) < 0)
    {
//		syslog(LOGOPTS, "bind: %m\n");
        exit(1);
    }
    if (listen(netfd, 5) < 0)
    {
//		syslog(LOGOPTS, "listen: %m\n");
        exit(1);
    }
    //clientlen = sizeof(client);
    //memset(&client, 0, sizeof(client));
#endif


#ifdef LPR_with_ASUS//JY1112
    if((sockfd_ASUS = socket(AF_INET,SOCK_STREAM,0)) < 0 )
    {
        perror("can't open stream socket:");
        exit(0);
    }
    bzero((char *)&serv_addr_ASUS , sizeof(serv_addr_ASUS));
    serv_addr_ASUS.sin_family        = AF_INET;
    serv_addr_ASUS.sin_addr.s_addr   = htonl(INADDR_ANY);
    serv_addr_ASUS.sin_port          = htons(PNT_SVR_PORT_ASUS);

    if(bind(sockfd_ASUS,(struct sockaddr *)&serv_addr_ASUS , sizeof(serv_addr_ASUS)) < 0 )
    {
        perror("can't bind:");
        exit(0);
    }

    setsockopt(sockfd_ASUS, SOL_SOCKET, SO_RCVBUF, (char *)&windowsize, sizeof(windowsize));

    listen(sockfd_ASUS , 15);

    /*set the fds*/
    nfds1=MAX(sockfd, sockfd_ASUS);
#ifdef Raw_Printing_with_ASUS //Lisa
    nfds=MAX(nfds1, netfd);
#endif
    FD_ZERO(&afds);
#endif



    while(TRUE)
    {
#ifdef Raw_Printing_with_ASUS //Lisa
        FD_SET(netfd, &afds);
#endif
#ifdef LPR_with_ASUS//JY1112
        FD_SET(sockfd, &afds);
        FD_SET(sockfd_ASUS, &afds);

        int err_select;//JY1113
        memcpy(&rfds, &afds, sizeof(rfds));
        if((err_select=select(nfds+1, &rfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0 )) < 0) {
//JY1120		printf("select error on sockfd: error=%d\n", errno);
            /**/
//		printf("sockfd_FD_ISSET=%d\n", FD_ISSET(sockfd, &rfds));
//JY1120		printf("sockfd_ASUS FD_ISSET=%d\n", FD_ISSET(sockfd_ASUS, &rfds));
            /**/
//		if(errno != 4)//JY1113: delete
            continue;
        }
#endif
        clilen      = sizeof(cli_addr);

        if (busy == FALSE) //Add by Lisa
        {
            busy = TRUE; // Add by Lisa
#ifdef LPR_with_ASUS//JY1112 
            if(FD_ISSET(sockfd, &rfds))
            {
                LPRflag = 1;
                clisockfd   = accept(sockfd,(struct sockaddr *)&cli_addr, &clilen);
//JY1120
                printf("LPR sock received...\n");//JY1114: delete
            }
            else if(FD_ISSET(sockfd_ASUS, &rfds))
            {
                LPRflag = 0;
                clisockfd   = accept(sockfd_ASUS,(struct sockaddr *)&cli_addr, &clilen);
//JY1120
                printf("ASUSRemote port sock receved...\n");//JY1114: delete
            }
#ifdef Raw_Printing_with_ASUS //Lisa
            else if(FD_ISSET(netfd, &rfds))
            {
                LPRflag = 2;
                clisockfd = accept(netfd, (struct sockaddr*) &cli_addr, &clilen);
                printf("Raw Printing sock received...\n");
            }
#endif
            else {
                perror("lpr: no data received...");
                continue;
            }

#else
            clisockfd   = accept(sockfd,(struct sockaddr *)&cli_addr, &clilen);
#endif
            strcpy(clientaddr , inet_ntoa(cli_addr.sin_addr));
            if(clisockfd < 0)
            {
                perror("accept error:");
                continue;
            }

            //remark PRINT("Accept OK ,client address -- %s\n",inet_ntoa(cli_addr.sin_addr));

            if( (childpid = fork() ) < 0)
            {
                perror("fork error:");
            }
            else if(childpid == 0)
            {
                printf("child start\n");
                //child process starts here
//#ifdef LPR_SUPPORT
//JY1120		printf("LPR process....\n");
#ifdef LPR_with_ASUS//JY1114 
//JY1120		printf("lptstatus.busy=%s\n", lptstatus.busy);//JY1114
//JY1120		printf("lptstatus.pid=%d\n", lptstatus.pid);//JY1114
                if(LPRflag == 1)
                {
                    printf("LPRflag_remote=%d \n",LPRflag);
                    processReq_LPR(clisockfd);
                }
#ifdef Raw_Printing_with_ASUS //Lisa
                else if (LPRflag == 2)
                {
                    printf("LPRflag_raw=%d \n",LPRflag);
                    processReq_Raw(clisockfd);
                }
#endif
                else
#endif
                {
                    printf("LPRflag_LPR=%d \n",LPRflag);
                    processReq(clisockfd);
                }

//#else
//            processReq(clisockfd);
//#endif
                //PRINT("client exit\n");
                if(LPRflag == 1)
                    printf("LPR client exit\n");//JY1113delete
                else if (LPRflag == 2)
                    printf("Raw Printing client exit\n");
                else
                    printf("ASUS Remote client exit\n");//JY1113delete
//		check_prn_status(ONLINE, "");
                close(sockfd);//
                close(sockfd_ASUS);//
                exit(0);
            }


            //parents process goes on here
            //remark PRINT("fork -- childpid %d\n",childpid);

            if(lptstatus.busy == FALSE)
            {
                //someone is using the printer now
                //lptstatus.busy = TRUE;

                //record the infomation of the client process
                strcpy(lptstatus.addr , inet_ntoa(cli_addr.sin_addr));
                lptstatus.pid = childpid;
            }
        }
        //PRINT("lptstatus.addr %s\n",lptstatus.addr);

        close(clisockfd);
    }

}
Example #4
0
NODE *
spec(void)
{
	NODE *centry, *last;
	char *p;
	NODE ginfo, *root;
	int c_cur, c_next;
	char *buf, *tbuf = NULL;
	size_t len;

	last = root = NULL;
	bzero(&ginfo, sizeof(ginfo));
	centry = &ginfo;
	c_cur = c_next = 0;
	for (lineno = 1; (buf = fgetln(stdin, &len));
	    ++lineno, c_cur = c_next, c_next = 0) {
		/* Null-terminate the line. */
		if (buf[len - 1] == '\n') {
			buf[--len] = '\0';
		} else {
			/* EOF with no newline. */
			tbuf = malloc(len + 1);
			memcpy(tbuf, buf, len);
			tbuf[len] = '\0';
			buf = tbuf;
		}

		/* Skip leading whitespace. */
		for (p = buf; isspace((unsigned char)*p); p++)
			;

		/* If nothing but whitespace or comment char, continue. */
		if (*p == '\0' || *p == '#')
			continue;

		/* See if next line is continuation line. */
		if (buf[len - 1] == '\\') {
			c_next = 1;
			if (--len == 0)
				continue;
			buf[len] = '\0';
		}

#ifdef DEBUG
		(void)fprintf(stderr, "line %d: {%s}\n", lineno, p);
#endif
		if (c_cur) {
			set(p, centry);
			continue;
		}
			
		/* Grab file name, "$", "set", or "unset". */
		if ((p = strtok(p, "\n\t ")) == NULL)
			error("missing field");

		if (p[0] == '/')
			switch(p[1]) {
			case 's':
				if (strcmp(p + 1, "set"))
					break;
				set(NULL, &ginfo);
				continue;
			case 'u':
				if (strcmp(p + 1, "unset"))
					break;
				unset(NULL, &ginfo);
				continue;
			}

		if (strchr(p, '/'))
			error("slash character in file name");

		if (!strcmp(p, "..")) {
			/* Don't go up, if haven't gone down. */
			if (!root)
				goto noparent;
			if (last->type != F_DIR || last->flags & F_DONE) {
				if (last == root)
					goto noparent;
				last = last->parent;
			}
			last->flags |= F_DONE;
			continue;

noparent:		error("no parent node");
		}

		len = strlen(p) + 1;	/* NUL in struct _node */
		if ((centry = calloc(1, sizeof(NODE) + len - 1)) == NULL)
			error("%s", strerror(errno));
		*centry = ginfo;
#define	MAGIC	"?*["
		if (strpbrk(p, MAGIC))
			centry->flags |= F_MAGIC;
		if (strunvis(centry->name, p) == -1) {
			fprintf(stderr,
			    "mtree: filename (%s) encoded incorrectly\n", p);
			strlcpy(centry->name, p, len);
		}
		set(NULL, centry);

		if (!root) {
			last = root = centry;
			root->parent = root;
		} else if (last->type == F_DIR && !(last->flags & F_DONE)) {
			centry->parent = last;
			last = last->child = centry;
		} else {
			centry->parent = last->parent;
			centry->prev = last;
			last = last->next = centry;
		}
	}
	free(tbuf);
	return (root);
}
Example #5
0
static int
rp_pciattach(device_t dev)
{
	int	num_ports, num_aiops;
	int	aiop;
	CONTROLLER_t	*ctlp;
	int	retval;
	u_int32_t	stcmd;

	ctlp = device_get_softc(dev);
	bzero(ctlp, sizeof(*ctlp));
	ctlp->dev = dev;
	ctlp->aiop2rid = rp_pci_aiop2rid;
	ctlp->aiop2off = rp_pci_aiop2off;
	ctlp->ctlmask = rp_pci_ctlmask;

	/* Wake up the device. */
	stcmd = pci_read_config(dev, PCIR_COMMAND, 4);
	if ((stcmd & PCIM_CMD_PORTEN) == 0) {
		stcmd |= (PCIM_CMD_PORTEN);
		pci_write_config(dev, PCIR_COMMAND, 4, stcmd);
	}

	/* The IO ports of AIOPs for a PCI controller are continuous. */
	ctlp->io_num = 1;
	ctlp->io_rid = kmalloc(sizeof(*(ctlp->io_rid)) * ctlp->io_num, 
				M_DEVBUF, M_WAITOK | M_ZERO);
	ctlp->io = kmalloc(sizeof(*(ctlp->io)) * ctlp->io_num, 
				M_DEVBUF, M_WAITOK | M_ZERO);

	ctlp->bus_ctlp = NULL;

	ctlp->io_rid[0] = 0x10;
	ctlp->io[0] = bus_alloc_resource(dev, SYS_RES_IOPORT, &ctlp->io_rid[0], 0, ~0, 1, RF_ACTIVE);
	if(ctlp->io[0] == NULL) {
		device_printf(dev, "ioaddr mapping failed for RocketPort(PCI).\n");
		retval = ENXIO;
		goto nogo;
	}

	num_aiops = sPCIInitController(ctlp,
				       MAX_AIOPS_PER_BOARD, 0,
				       FREQ_DIS, 0, (pci_get_devid(dev) >> 16) & 0xffff);

	num_ports = 0;
	for(aiop=0; aiop < num_aiops; aiop++) {
		sResetAiopByNum(ctlp, aiop);
		num_ports += sGetAiopNumChan(ctlp, aiop);
	}

	retval = rp_attachcommon(ctlp, num_aiops, num_ports);
	if (retval != 0)
		goto nogo;

	return (0);

nogo:
	rp_pcireleaseresource(ctlp);

	return (retval);
}
Example #6
0
static int
add_event(gs_grid_storage_t * gs, const char *cName, const char *msg)
{
	int rc = -1;
	gs_error_t **gserr = NULL;
	gs_error_t *locerr = NULL;
	struct gs_container_location_s *location = NULL;
	container_id_t cid;
	struct metacnx_ctx_s cnx;
	gchar *hexid = NULL;
	gchar * meta2_url = NULL;
	GError *gerr = NULL;

	metacnx_clear(&cnx);
	if (!gs || !cName || !msg) {
		PRINT_ERROR("Invalid parameter (%p %p %p)\n", gs, cName, msg);
		return rc;
	}

	location = gs_locate_container_by_name(gs, cName, &locerr);
	if (!location) {
		PRINT_ERROR("cannot find %s\n", cName);
		goto exit_label;
	}
	if (!location->m0_url || !location->m1_url || !location->m2_url || !location->m2_url[0]) {
		PRINT_ERROR("cannot find %s\n", cName);
		goto exit_label;
	}
	PRINT_DEBUG("%s found\n", cName);
	hexid = location->container_hexid;
	meta2_url = location->m2_url[0];
	if (!container_id_hex2bin(hexid, strlen(hexid), &cid, &gerr)) {
		GSERRORCAUSE(gserr, gerr, "Invalid container id");
		goto exit_label;
	}

	if (!metacnx_init_with_url(&cnx, meta2_url, &gerr)) {
		GSERRORCAUSE(gserr, gerr, "Invalid META2 address");
		goto exit_label; 
	}

	container_event_t event;
	bzero(&event, sizeof(event));
	event.timestamp = time(0);
	g_strlcpy(event.type, "test", sizeof(event.type));
	g_strlcpy(event.ref, "test", sizeof(event.type));
	event.message = metautils_gba_from_string(msg);

	PRINT_DEBUG("Adding event [%s]", msg);
	rc = meta2_remote_add_container_event(&cnx, cid, &event, &gerr);

	g_byte_array_free(event.message, TRUE);
	event.message = NULL;

	metacnx_close(&cnx);
	metacnx_clear(&cnx);

	if (!rc) {
		PRINT_ERROR("Failed to add event : %s\n", gerror_get_message(gerr));
		g_clear_error(&gerr);
	}

exit_label:
	return rc;
}
Example #7
0
static int
openssh_RSA_verify(int type, u_char *hash, size_t hashlen,
    u_char *sigbuf, size_t siglen, RSA *rsa)
{
	size_t ret, rsasize = 0, oidlen = 0, hlen = 0;
	int len, oidmatch, hashmatch;
	const u_char *oid = NULL;
	u_char *decrypted = NULL;

	ret = SSH_ERR_INTERNAL_ERROR;
	switch (type) {
	case NID_sha1:
		oid = id_sha1;
		oidlen = sizeof(id_sha1);
		hlen = 20;
		break;
	case NID_md5:
		oid = id_md5;
		oidlen = sizeof(id_md5);
		hlen = 16;
		break;
	default:
		goto done;
	}
	if (hashlen != hlen) {
		ret = SSH_ERR_INVALID_ARGUMENT;
		goto done;
	}
	rsasize = RSA_size(rsa);
	if (rsasize <= 0 || rsasize > SSHBUF_MAX_BIGNUM ||
	    siglen == 0 || siglen > rsasize) {
		ret = SSH_ERR_INVALID_ARGUMENT;
		goto done;
	}
	if ((decrypted = malloc(rsasize)) == NULL) {
		ret = SSH_ERR_ALLOC_FAIL;
		goto done;
	}
	if ((len = RSA_public_decrypt(siglen, sigbuf, decrypted, rsa,
	    RSA_PKCS1_PADDING)) < 0) {
		ret = SSH_ERR_LIBCRYPTO_ERROR;
		goto done;
	}
	if (len < 0 || (size_t)len != hlen + oidlen) {
		ret = SSH_ERR_INVALID_FORMAT;
		goto done;
	}
	oidmatch = timingsafe_bcmp(decrypted, oid, oidlen) == 0;
	hashmatch = timingsafe_bcmp(decrypted + oidlen, hash, hlen) == 0;
	if (!oidmatch || !hashmatch) {
		ret = SSH_ERR_SIGNATURE_INVALID;
		goto done;
	}
	ret = 0;
done:
	if (decrypted) {
		bzero(decrypted, rsasize);
		free(decrypted);
	}
	return ret;
}
Example #8
0
int main( int argc, char* argv[] ) {
	setbuf(stdout, NULL);
	INFO("%s v1.0\n", argv[0]);
	config_t cfg;
	global_data_t state;
	struct mosquitto *mosq = NULL;

	config_init(&cfg);
	loadDefaults(&cfg);
    loadSerialDefaults(&cfg);

	if(parseArgs(argc, argv, &cfg)) {
		exit(1);
	}
	if(parseSerialArgs(argc, argv, &cfg)) {
        exit(1);
    }

	//config_write(&cfg, stderr);

	port_t serial;
	loadSerial(&cfg, &serial);

	if(serial.name == NULL) {
		ERR("Could not load serial configuration\n");
		exit(2);
	}

	if(!strlen(serial.name)) {
		ERR("You must specify the serial port\n");
		exit(2);
	}

	DBG("Setting up serial port...");
	state.arduino_fd = setupSerial(serial.name, serial.speed);
	if(state.arduino_fd < 0) {
		ERR("Failed to setup serial port %s @ %d\n", serial.name, serial.speed);
		exit(2);
	}
	INFO("listening for event on %s\n", serial.name);

	mosquitto_lib_init();
	mqttserver_t mqtt;
	loadMQTT(&cfg, &mqtt);

	char hostname[BUF_MAX];
	gethostname(hostname, BUF_MAX);
	asprintf(&state.client_id, "%s.%s", hostname, (char *) strlaststr(serial.name, "/"));
	mosq = mosquitto_new(state.client_id, true, &state.arduino_fd); //use port name as client id
	if(!mosq) {
		ERR("Couldn't create a new mosquitto client instance\n");
		exit(3);
	}

	//TODO setup callbacks
	mosquitto_log_callback_set(mosq, log_callback);
	mosquitto_disconnect_callback_set(mosq, disconnect_callback);
	mosquitto_connect_callback_set(mosq, connect_callback);
	mosquitto_message_callback_set(mosq, message_callback);

	INFO("Connecting to %s:%d ... ", mqtt.servername, mqtt.port);
	if(mosquitto_connect(mosq, mqtt.servername, mqtt.port, mqtt.keepalive)){
		ERR("\nUnable to connect to %s:%d.\n", mqtt.servername, mqtt.port);
		exit(3);
	}
	INFO("done\n");

	int mosq_fd = mosquitto_socket(mosq);

	fd_set active_fd_set, read_fd_set;
	/* Initialize the set of active sockets. */
	FD_ZERO (&active_fd_set);
	FD_SET (state.arduino_fd, &active_fd_set);
	FD_SET (mosq_fd, &active_fd_set);

	char buf[BUF_MAX];
	bzero(buf,BUF_MAX);

	int retries = 0;

	//TODO setup syscall to stop process
	while(1) {
		/* Block until input arrives on one or more active sockets. */
		read_fd_set = active_fd_set;
		if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0) {
			ERR("Error in select\n");
			sleep(BACKOFF);
			int r = mosquitto_reconnect(mosq);
			retries++;
			if(r != MOSQ_ERR_SUCCESS) {
				ERR("Could not reconnect to broker: %s\n", strerror(r));
				if(retries > MAX_RETRIES) {
					/* Cleanup */
					mosquitto_destroy(mosq);
					mosquitto_lib_cleanup();
					exit (EXIT_FAILURE);
				}
			} else {
				retries = 0;
				continue;
			}
		}

		/* Service all the sockets with input pending. */
		int i;
		for (i = 0; i < FD_SETSIZE; ++i)
			if (FD_ISSET (i, &read_fd_set)) {
				if(i == state.arduino_fd) {
					if(!readSerial(state.arduino_fd, buf, BUF_MAX, serial.timeout)) {
						arduinoEvent(buf, &cfg, mosq);
						bzero(buf,BUF_MAX);
					}
				} else if(i == mosq_fd) {
					mosquitto_loop_read(mosq, 1);
					mosquitto_loop_write(mosq, 1);
					mosquitto_loop_misc(mosq);
				}
			}
	};

	return EXIT_SUCCESS;
}
void
simpleaudio_tone(simpleaudio *sa_out, float tone_freq, size_t nsamples_dur)
{
    unsigned int framesize = simpleaudio_get_framesize(sa_out);

    void *buf = malloc(nsamples_dur * framesize);
    assert(buf);

    if ( tone_freq != 0 ) {

	float wave_nsamples = simpleaudio_get_rate(sa_out) / tone_freq;
	size_t i;

#define TURNS_TO_RADIANS(t)	( M_PI*2.0 * (t) )

#define SINE_PHASE_TURNS	( (float)i/wave_nsamples + sa_tone_cphase )
#define SINE_PHASE_RADIANS	TURNS_TO_RADIANS(SINE_PHASE_TURNS)

	switch ( simpleaudio_get_format(sa_out) ) {

	    case SA_SAMPLE_FORMAT_FLOAT:
		{
		    float *float_buf = buf;
		    if ( sin_table_float ) {
			for ( i=0; i<nsamples_dur; i++ )
			    float_buf[i] = sin_lu_float(SINE_PHASE_TURNS);
		    } else {
			for ( i=0; i<nsamples_dur; i++ )
			    float_buf[i] = tone_mag * sinf(SINE_PHASE_RADIANS);
		    }
		}
		break;

	    case SA_SAMPLE_FORMAT_S16:
		{
		    short *short_buf = buf;
		    if ( sin_table_short ) {
			for ( i=0; i<nsamples_dur; i++ )
			    short_buf[i] = sin_lu_short(SINE_PHASE_TURNS);
		    } else {
			unsigned short mag_s = 32767.0 * tone_mag + 0.5f;
			if ( tone_mag > 1.0f ) // clamp to 1.0 to avoid overflow
			    mag_s = 32767;
			if ( mag_s < 1 ) // "short epsilon"
			    mag_s = 1;
			for ( i=0; i<nsamples_dur; i++ )
			    short_buf[i] = lroundf( mag_s * sinf(SINE_PHASE_RADIANS) );
		    }
		    break;
		}

	    default:
		assert(0);
		break;
	}

	sa_tone_cphase
	    = fmodf(sa_tone_cphase + (float)nsamples_dur/wave_nsamples, 1.0);

    } else {

	bzero(buf, nsamples_dur * framesize);
	sa_tone_cphase = 0.0;

    }

    assert ( simpleaudio_write(sa_out, buf, nsamples_dur) > 0 );

    free(buf);
}
Example #10
0
int main(int argc, char *argv[]) // Entrada: IP_Remota, Puerto_Remoto, Puerto_Local, Nick //
{

	if(argc != 5)
{
// Se muetsra el uso correcto en caso de invocación errónea //
printf("\n¡oh oh!\nEl uso exacto del programa es el correcto:\n\t%s IP_Remota Puerto_Remoto Puerto_Local Nickname\n\n", argv[0]);
}

// Nombramiento de los parámetros recibidos //
	char* programa = argv[0];
	char* ip_remota = argv[1];
	int puerto_remoto = atoi(argv[2]);
	int puerto_local = atoi(argv[3]);
	char* nick = argv[4];

printf("\n\t¡Hola %s!\n\tBienvenido a Messenger\n\n", nick);
    
    // BIFURCACIÓN de procesos mediante el uso de fork() //
	pid_t childpid; // process_ID del proceso hijo //
    	childpid = fork(); // Llamada a fork() //
    	
    	if (childpid >= 0) // si el process_ID del hijo es >= 0, el fork fue exitoso //
    {

	if (childpid == 0) // fork() retorna 0 al process_ID del hijo //
        {

// SERVIDOR //

	int fd, fd2; // nombre que describe los sockets //
	int sin_size; // Variable para el tamanno de conexiones //

	char buf[1024]; // bufer para las cadenas de texto recibidas //

	struct sockaddr_in server; // dirección IP del servidor //
	struct sockaddr_in client; // dirección IP del cliente //

	if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) // CREACION DEL SOCKET //
	{
	printf("error en socket()\n"); // ERROR en la creacion del socket //
	exit(-1);
	}

	server.sin_family = AF_INET; // Asignacion de la familia del socket //
	server.sin_port = htons(puerto_local); // Asignacion del Puerto_Local //
	server.sin_addr.s_addr = INADDR_ANY; // Dirección IP local de manera automatica //
	bzero(&(server.sin_zero),8); // Se colocan ceros en el resto de la estructura //

	if(bind(fd,(struct sockaddr*)&server, sizeof(struct sockaddr))==-1) // Intento de hacer bind con los puertos ingresados //
	{
	printf("ERROR Puerto ocupado\n"); // ERROR en caso de que no se pueda completar el bind //
	exit(-1);
	}

	if(listen(fd,1) == -1) // llamada al proceso de escucha, 2do arg es num de conexiones permitidas //
	{
	printf("error en listen()\n"); // ERROR en caso que falle el proceso de listen //
	exit(-1);
	}
	 
	sin_size = sizeof(struct sockaddr_in); // Se captura el tamanno para realizar conexiones //

	if ((fd2 = accept(fd,(struct sockaddr *)&client, &sin_size))==-1) // Valida que la conexion sea aceptada //
	{
	printf("error en accept()\n"); // ERROR en caso que no se pueda aceptar la conexion entrante //
	exit(-1);
	}

// Se muestra ip remota //
	printf("\tUn amigo se ha conectado desde: %s\n\tPara chatear solo teclea y presiona Enter\n\n", (char*)inet_ntoa(client.sin_addr));

	while (strcmp(buf,"Adios") != 0) // revisa que el mensaje entrante no sea "Adios" //
	{
	if ((recv(fd2,buf,1024,0)) > 0) // Recibe el mensaje y valida error //
	{
	printf("%s dice: %s\n",nick, buf); // muestra el mensaje recibido //
	}
	}

	close(fd2); // Se finaliza la conexion //
	close(fd); // Se finaliza el socket //
	printf("\tTu Amig@ terminó la conversación,\n\tVuelve pronto...!\n\n"); // AVISO si el proceso remoto finaliza la charla //
	exit(-1); // Sale del Programa //

	} // FIN del proceso padre //
	else //fork() retorna process_ID del hijo al padre//
		{

// CLIENTE //
		
	int fd; // nombre que describe los sockets //

	struct hostent *he; // estructura para informacion del proceso remoto //
	struct sockaddr_in server; // dirección IP del servidor //

	if ((he=gethostbyname(ip_remota))==NULL) // se comprueba la direccion IP_Remota //
	{
	printf("gethostbyname() error\n"); // ERROR en caso de no poder verificar la IP_Remota //
	exit(-1);
	}

	if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1) // CREACION DEL SOCKET //
	{

	printf("socket() error\n"); // ERROR en la creacion del socket //
	exit(-1);
	}

	server.sin_family = AF_INET; // Asignacion de la familia del socket //
	server.sin_port = htons(puerto_remoto); // Asignacion del Puerto_Remoto //
	server.sin_addr = *((struct in_addr *)he->h_addr); // Dirección IP_Remota //
	bzero(&(server.sin_zero),8); // Se colocan ceros en el resto de la estructura //

	while(connect(fd, (struct sockaddr *)&server, sizeof(struct sockaddr))==-1) // Se intenta realizar la conexion //
	{
// Tratando de Conectarse ////////////////////////////////////////
	}

	int conversacion = 1; // booleano para indicar si termina la conversacion //
	while(conversacion == 1) // bucle de conversacion activa //
	{
		char mensaje[1024]; // bufer para las cadenas de texto recibidas //

		gets (mensaje); // obtener el mensaje del teclado //

		if (strcmp(mensaje, "Adios") == 0) // revisa que el mensaje entrante no sea "Adios" //
			conversacion = 0; // en caso de "Adios" finaliza la conversacion //

		if (send(fd,&mensaje,1024,0) == -1) // Envia el mensaje y valida error //
			printf("\n\tERROR en el envío :/\n\tVuelve a intentarlo\n"); // ERROR en case que falle el envio //

	}

	printf("\tTerminaste la conversación,\n\tVuelve pronto...!\n\n"); // AVISO si se finaliza la charla //
	close(fd); // Se finaliza el socket //
	exit(0); // Sale del Programa //

	}
	    } // FIN de proceso hijo //
	else // fork() retorna un -1 en caso de fallo //
	    {
		perror("Error en la bifurcacion de procesos fork()"); // Despliegue si hay ERROR en el fork() //
		exit(0); // Sale del Programa //
	    } // FIN de error en el fork() //

} // FIN del main //
Example #11
0
void
read_ts_err_stats(struct module *mod)
{
    int                  fd = -1;
    int                  pos;
    char                 buf[LINE_4096];
    struct sockaddr_un   un;
    struct stats_ts_err  st_ts;
    if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
        goto done;
    }
    bzero(&st_ts, sizeof(st_ts));
    bzero(&un, sizeof(un));
    un.sun_family = AF_UNIX;
    strcpy(un.sun_path, sock_path);
    if (connect(fd, (struct sockaddr *)&un, sizeof(un)) < 0) {
        goto done;
    }

    int          i, len;
    int          record_len = sizeof(RECORDS_NAME) / sizeof(RECORDS_NAME[0]);
    const char  *info;
    for ( i = 0; i < record_len; ++i) {
        info = RECORDS_NAME[i];
        long int info_len = strlen(info);
        short int command = TS_RECORD_GET;
        char write_buf[LINE_1024];
        *((short int *)&write_buf[0]) = command;
        *((long int *)&write_buf[2]) = info_len;
        strcpy(write_buf + 6, info);
        len = 2 + 4 + strlen(info);
        if (write(fd, write_buf, len) != len) {
            close(fd);
            return;
        }

        short int ret_status = 0;
        short int ret_type = 0;
        long ret_val = 0;
        int read_len = read(fd, buf, LINE_1024);
        if (read_len != -1) {
            ret_status = *((short int *)&buf[0]);
            ret_type = *((short int *)&buf[6]);

        } else {
            close(fd);
            return;
        }
        if (0 == ret_status) {
            if (ret_type < 2) {
                ret_val= *((long int *)&buf[8]);

            } else if (2 == ret_type) {
                float ret_val_float = *((float *)&buf[8]);
                ret_val_float *= 100;
                ret_val = (unsigned long long)ret_val_float;

            } else {
                goto done;
            }
        }
        ((unsigned long long *)&st_ts)[i] = ret_val;
    }
done:
    if (-1 != fd) {
        close(fd);
    }
    pos = sprintf(buf, "%lld,%lld,%lld,%lld,%lld,%lld,%lld,%lld",
            st_ts.miss_host,
            st_ts.aborts,
            st_ts.pre_accept_hangups,
            st_ts.empty_hangups,
            st_ts.early_hangups,
            st_ts.con_fail,
            st_ts.other,
            st_ts.hangup
             );
    buf[pos] = '\0';
    set_mod_record(mod, buf);
}
Example #12
0
static int
snc_isa_probe(device_t dev)
{
	struct snc_softc *sc = device_get_softc(dev);
	int type;
 	int error = 0;

	bzero(sc, sizeof(struct snc_softc));

	/* Check isapnp ids */
	error = ISA_PNP_PROBE(device_get_parent(dev), dev, snc_ids);

	/* If the card had a PnP ID that didn't match any we know about */
	if (error == ENXIO) {
		return(error);
	}

	switch (error) {
	case 0:		/* Matched PnP */
		type = SNEC_TYPE_PNP;
		break;

	case ENOENT:	/* Legacy ISA */
		type = SNEC_TYPE_LEGACY;
		break;

	default:	/* If we had some other problem. */
		return(error);
	}

	if (type == SNEC_TYPE_PNP && isa_get_portsize(dev) == 0) {
		int port;
		int rid = 0;
		struct resource *res = NULL;

		for (port = 0x0888; port <= 0x3888; port += 0x1000) {
			bus_set_resource(dev, SYS_RES_IOPORT, rid,
					 port, SNEC_NREGS);
			res = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
						 0ul, ~0ul, SNEC_NREGS,
						 0 /* !RF_ACTIVE */);
			if (res) break;
		}

		printf("snc_isa_probe: broken PnP resource, ");
		if (res) {
			printf("use port 0x%x\n", port);
			bus_release_resource(dev, SYS_RES_IOPORT, rid, res);
			snc_isapnp_reconfig(dev);
		} else {
			printf("and can't find port\n");
		}
	}

	error = snc_alloc_port(dev, 0);
	error = max(error, snc_alloc_memory(dev, 0));
	error = max(error, snc_alloc_irq(dev, 0, 0));

	if (!error && !snc_probe(dev, type))
		error = ENOENT;

	snc_release_resources(dev);
	return (error);
}
Example #13
0
int
main(int argc, char *argv[])
{
  int i, cc, fd;
  uint rootino, inum, off;
  struct dirent de;
  char buf[BSIZE];
  struct dinode din;


  static_assert(sizeof(int) == 4, "Integers must be 4 bytes!");

  if(argc < 2){
    fprintf(stderr, "Usage: mkfs fs.img files...\n");
    exit(1);
  }

  assert((BSIZE % sizeof(struct dinode)) == 0);
  assert((BSIZE % sizeof(struct dirent)) == 0);

  fsfd = open(argv[1], O_RDWR|O_CREAT|O_TRUNC, 0666);
  if(fsfd < 0){
    perror(argv[1]);
    exit(1);
  }

  // 1 fs block = 1 disk sector
  nmeta = 2 + nlog + ninodeblocks + nbitmap;
  nblocks = FSSIZE - nmeta;

  sb.size = xint(FSSIZE);
  sb.nblocks = xint(nblocks);
  sb.ninodes = xint(NINODES);
  sb.nlog = xint(nlog);
  sb.logstart = xint(2);
  sb.inodestart = xint(2+nlog);
  sb.bmapstart = xint(2+nlog+ninodeblocks);

  printf("nmeta %d (boot, super, log blocks %u inode blocks %u, bitmap blocks %u) blocks %d total %d\n",
         nmeta, nlog, ninodeblocks, nbitmap, nblocks, FSSIZE);

  freeblock = nmeta;     // the first free block that we can allocate

  for(i = 0; i < FSSIZE; i++)
    wsect(i, zeroes);

  memset(buf, 0, sizeof(buf));
  memmove(buf, &sb, sizeof(sb));
  wsect(1, buf);

  rootino = ialloc(T_DIR);
  assert(rootino == ROOTINO);

  bzero(&de, sizeof(de));
  de.inum = xshort(rootino);
  strcpy(de.name, ".");
  iappend(rootino, &de, sizeof(de));

  bzero(&de, sizeof(de));
  de.inum = xshort(rootino);
  strcpy(de.name, "..");
  iappend(rootino, &de, sizeof(de));

  for(i = 2; i < argc; i++){
    assert(index(argv[i], '/') == 0);

    if((fd = open(argv[i], 0)) < 0){
      perror(argv[i]);
      exit(1);
    }

    // Skip leading _ in name when writing to file system.
    // The binaries are named _rm, _cat, etc. to keep the
    // build operating system from trying to execute them
    // in place of system binaries like rm and cat.
    if(argv[i][0] == '_')
      ++argv[i];

    inum = ialloc(T_FILE);

    bzero(&de, sizeof(de));
    de.inum = xshort(inum);
    strncpy(de.name, argv[i], DIRSIZ);
    iappend(rootino, &de, sizeof(de));

    while((cc = read(fd, buf, sizeof(buf))) > 0)
      iappend(inum, buf, cc);

    close(fd);
  }

  // fix size of root inode dir
  rinode(rootino, &din);
  off = xint(din.size);
  off = ((off/BSIZE) + 1) * BSIZE;
  din.size = xint(off);
  winode(rootino, &din);

  balloc(freeblock);

  exit(0);
}
Example #14
0
/*
 * Open the specified file descriptor and return a pointer to a CTF container.
 * The file can be either an ELF file or raw CTF file.  The caller is
 * responsible for closing the file descriptor when it is no longer needed.
 */
ctf_file_t *
ctf_fdopen(int fd, int *errp)
{
	ctf_sect_t ctfsect, symsect, strsect;
	ctf_file_t *fp = NULL;
	size_t shstrndx, shnum;

	struct stat64 st;
	ssize_t nbytes;

	union {
		ctf_preamble_t ctf;
		Elf32_Ehdr e32;
		GElf_Ehdr e64;
	} hdr;

	bzero(&ctfsect, sizeof (ctf_sect_t));
	bzero(&symsect, sizeof (ctf_sect_t));
	bzero(&strsect, sizeof (ctf_sect_t));
	bzero(&hdr.ctf, sizeof (hdr));

	if (fstat64(fd, &st) == -1)
		return (ctf_set_open_errno(errp, errno));

	if ((nbytes = pread64(fd, &hdr.ctf, sizeof (hdr), 0)) <= 0)
		return (ctf_set_open_errno(errp, nbytes < 0? errno : ECTF_FMT));

	/*
	 * If we have read enough bytes to form a CTF header and the magic
	 * string matches, attempt to interpret the file as raw CTF.
	 */
	if (nbytes >= (ssize_t) sizeof (ctf_preamble_t) &&
	    hdr.ctf.ctp_magic == CTF_MAGIC) {
		if (hdr.ctf.ctp_version > CTF_VERSION)
			return (ctf_set_open_errno(errp, ECTF_CTFVERS));

		ctfsect.cts_data = mmap64(NULL, st.st_size, PROT_READ,
		    MAP_PRIVATE, fd, 0);

		if (ctfsect.cts_data == MAP_FAILED)
			return (ctf_set_open_errno(errp, errno));

		ctfsect.cts_name = _CTF_SECTION;
		ctfsect.cts_type = SHT_PROGBITS;
		ctfsect.cts_flags = SHF_ALLOC;
		ctfsect.cts_size = (size_t)st.st_size;
		ctfsect.cts_entsize = 1;
		ctfsect.cts_offset = 0;

		if ((fp = ctf_bufopen(&ctfsect, NULL, NULL, errp)) == NULL)
			ctf_sect_munmap(&ctfsect);

		return (fp);
	}

	/*
	 * If we have read enough bytes to form an ELF header and the magic
	 * string matches, attempt to interpret the file as an ELF file.  We
	 * do our own largefile ELF processing, and convert everything to
	 * GElf structures so that clients can operate on any data model.
	 */
	if (nbytes >= (ssize_t) sizeof (Elf32_Ehdr) &&
	    bcmp(&hdr.e32.e_ident[EI_MAG0], ELFMAG, SELFMAG) == 0) {
#if BYTE_ORDER == _BIG_ENDIAN
		uchar_t order = ELFDATA2MSB;
#else
		uchar_t order = ELFDATA2LSB;
#endif
		GElf_Shdr *sp;

		void *strs_map;
		size_t strs_mapsz, i;
		char *strs;

		if (hdr.e32.e_ident[EI_DATA] != order)
			return (ctf_set_open_errno(errp, ECTF_ENDIAN));
		if (hdr.e32.e_version != EV_CURRENT)
			return (ctf_set_open_errno(errp, ECTF_ELFVERS));

		if (hdr.e32.e_ident[EI_CLASS] == ELFCLASS64) {
			if (nbytes < (ssize_t) sizeof (GElf_Ehdr))
				return (ctf_set_open_errno(errp, ECTF_FMT));
		} else {
			Elf32_Ehdr e32 = hdr.e32;
			ehdr_to_gelf(&e32, &hdr.e64);
		}

		shnum = hdr.e64.e_shnum;
		shstrndx = hdr.e64.e_shstrndx;

		/* Extended ELF sections */
		if ((shstrndx == SHN_XINDEX) || (shnum == 0)) {
			if (hdr.e32.e_ident[EI_CLASS] == ELFCLASS32) {
				Elf32_Shdr x32;

				if (pread64(fd, &x32, sizeof (x32),
				    hdr.e64.e_shoff) != sizeof (x32))
					return (ctf_set_open_errno(errp,
					    errno));

				shnum = x32.sh_size;
				shstrndx = x32.sh_link;
			} else {
				Elf64_Shdr x64;

				if (pread64(fd, &x64, sizeof (x64),
				    hdr.e64.e_shoff) != sizeof (x64))
					return (ctf_set_open_errno(errp,
					    errno));

				shnum = x64.sh_size;
				shstrndx = x64.sh_link;
			}
		}

		if (shstrndx >= shnum)
			return (ctf_set_open_errno(errp, ECTF_CORRUPT));

		nbytes = sizeof (GElf_Shdr) * shnum;

		if ((sp = malloc(nbytes)) == NULL)
			return (ctf_set_open_errno(errp, errno));

		/*
		 * Read in and convert to GElf the array of Shdr structures
		 * from e_shoff so we can locate sections of interest.
		 */
		if (hdr.e32.e_ident[EI_CLASS] == ELFCLASS32) {
			Elf32_Shdr *sp32;

			nbytes = sizeof (Elf32_Shdr) * shnum;

			if ((sp32 = malloc(nbytes)) == NULL || pread64(fd,
			    sp32, nbytes, hdr.e64.e_shoff) != nbytes) {
				free(sp);
				return (ctf_set_open_errno(errp, errno));
			}

			for (i = 0; i < shnum; i++)
				shdr_to_gelf(&sp32[i], &sp[i]);

			free(sp32);

		} else if (pread64(fd, sp, nbytes, hdr.e64.e_shoff) != nbytes) {
			free(sp);
			return (ctf_set_open_errno(errp, errno));
		}

		/*
		 * Now mmap the section header strings section so that we can
		 * perform string comparison on the section names.
		 */
		strs_mapsz = sp[shstrndx].sh_size +
		    (sp[shstrndx].sh_offset & ~_PAGEMASK);

		strs_map = mmap64(NULL, strs_mapsz, PROT_READ, MAP_PRIVATE,
		    fd, sp[shstrndx].sh_offset & _PAGEMASK);

		strs = (char *)strs_map +
		    (sp[shstrndx].sh_offset & ~_PAGEMASK);

		if (strs_map == MAP_FAILED) {
			free(sp);
			return (ctf_set_open_errno(errp, ECTF_MMAP));
		}

		/*
		 * Iterate over the section header array looking for the CTF
		 * section and symbol table.  The strtab is linked to symtab.
		 */
		for (i = 0; i < shnum; i++) {
			const GElf_Shdr *shp = &sp[i];
			const GElf_Shdr *lhp = &sp[shp->sh_link];

			if (shp->sh_link >= shnum)
				continue; /* corrupt sh_link field */

			if (shp->sh_name >= sp[shstrndx].sh_size ||
			    lhp->sh_name >= sp[shstrndx].sh_size)
				continue; /* corrupt sh_name field */

			if (shp->sh_type == SHT_PROGBITS &&
			    strcmp(strs + shp->sh_name, _CTF_SECTION) == 0) {
				ctfsect.cts_name = strs + shp->sh_name;
				ctfsect.cts_type = shp->sh_type;
				ctfsect.cts_flags = shp->sh_flags;
				ctfsect.cts_size = shp->sh_size;
				ctfsect.cts_entsize = shp->sh_entsize;
				ctfsect.cts_offset = (off64_t)shp->sh_offset;

			} else if (shp->sh_type == SHT_SYMTAB) {
				symsect.cts_name = strs + shp->sh_name;
				symsect.cts_type = shp->sh_type;
				symsect.cts_flags = shp->sh_flags;
				symsect.cts_size = shp->sh_size;
				symsect.cts_entsize = shp->sh_entsize;
				symsect.cts_offset = (off64_t)shp->sh_offset;

				strsect.cts_name = strs + lhp->sh_name;
				strsect.cts_type = lhp->sh_type;
				strsect.cts_flags = lhp->sh_flags;
				strsect.cts_size = lhp->sh_size;
				strsect.cts_entsize = lhp->sh_entsize;
				strsect.cts_offset = (off64_t)lhp->sh_offset;
			}
		}

		free(sp); /* free section header array */

		if (ctfsect.cts_type == SHT_NULL) {
			(void) munmap(strs_map, strs_mapsz);
			return (ctf_set_open_errno(errp, ECTF_NOCTFDATA));
		}

		/*
		 * Now mmap the CTF data, symtab, and strtab sections and
		 * call ctf_bufopen() to do the rest of the work.
		 */
		if (ctf_sect_mmap(&ctfsect, fd) == MAP_FAILED) {
			(void) munmap(strs_map, strs_mapsz);
			return (ctf_set_open_errno(errp, ECTF_MMAP));
		}

		if (symsect.cts_type != SHT_NULL &&
		    strsect.cts_type != SHT_NULL) {
			if (ctf_sect_mmap(&symsect, fd) == MAP_FAILED ||
			    ctf_sect_mmap(&strsect, fd) == MAP_FAILED) {
				(void) ctf_set_open_errno(errp, ECTF_MMAP);
				goto bad; /* unmap all and abort */
			}
			fp = ctf_bufopen(&ctfsect, &symsect, &strsect, errp);
		} else
			fp = ctf_bufopen(&ctfsect, NULL, NULL, errp);
bad:
		if (fp == NULL) {
			ctf_sect_munmap(&ctfsect);
			ctf_sect_munmap(&symsect);
			ctf_sect_munmap(&strsect);
		} else
			fp->ctf_flags |= LCTF_MMAP;

		(void) munmap(strs_map, strs_mapsz);
		return (fp);
	}

	return (ctf_set_open_errno(errp, ECTF_FMT));
}
Example #15
0
/*
 * Potentially decap ESP in UDP frame.  Check for an ESP header.
 * If present, strip the UDP header and push the result through IPSec.
 *
 * Returns error if mbuf consumed and/or processed, otherwise 0.
 */
int
udp_ipsec_input(struct mbuf *m, int off, int af)
{
	union sockaddr_union dst;
	struct secasvar *sav;
	struct udphdr *udp;
	struct ip *ip;
	uint32_t spi;
	int hlen;

	/*
	 * Just return if packet doesn't have enough data.
	 * We need at least [IP header + UDP header + ESP header].
	 * NAT-Keepalive packet has only one byte of payload, so it
	 * by default will not be processed.
	 */
	if (m->m_pkthdr.len < off + sizeof(struct esp))
		return (0);

	m_copydata(m, off, sizeof(uint32_t), (caddr_t)&spi);
	if (spi == 0)	/* Non-ESP marker. */
		return (0);

	/*
	 * Find SA and check that it is configured for UDP
	 * encapsulation.
	 */
	bzero(&dst, sizeof(dst));
	dst.sa.sa_family = af;
	switch (af) {
#ifdef INET
	case AF_INET:
		dst.sin.sin_len = sizeof(struct sockaddr_in);
		ip = mtod(m, struct ip *);
		ip->ip_p = IPPROTO_ESP;
		off = offsetof(struct ip, ip_p);
		hlen = ip->ip_hl << 2;
		dst.sin.sin_addr = ip->ip_dst;
		break;
#endif
#ifdef INET6
	case AF_INET6:
		/* Not yet */
		/* FALLTHROUGH */
#endif
	default:
		ESPSTAT_INC(esps_nopf);
		m_freem(m);
		return (EPFNOSUPPORT);
	}

	sav = key_allocsa(&dst, IPPROTO_ESP, spi);
	if (sav == NULL) {
		ESPSTAT_INC(esps_notdb);
		m_freem(m);
		return (ENOENT);
	}
	udp = mtodo(m, hlen);
	if (sav->natt == NULL ||
	    sav->natt->sport != udp->uh_sport ||
	    sav->natt->dport != udp->uh_dport) {
		/* XXXAE: should we check source address? */
		ESPSTAT_INC(esps_notdb);
		key_freesav(&sav);
		m_freem(m);
		return (ENOENT);
	}
	/*
	 * Remove the UDP header
	 * Before:
	 *   <--- off --->
	 *   +----+------+-----+
	 *   | IP |  UDP | ESP |
	 *   +----+------+-----+
	 *        <-skip->
	 * After:
	 *          +----+-----+
	 *          | IP | ESP |
	 *          +----+-----+
	 *   <-skip->
	 */
	m_striphdr(m, hlen, sizeof(*udp));
	/*
	 * We cannot yet update the cksums so clear any h/w cksum flags
	 * as they are no longer valid.
	 */
	if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)
		m->m_pkthdr.csum_flags &= ~(CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
	/*
	 * We can update ip_len and ip_sum here, but ipsec4_input_cb()
	 * will do this anyway, so don't touch them here.
	 */
	ESPSTAT_INC(esps_input);
	(*sav->tdb_xform->xf_input)(m, sav, hlen, off);
	return (EINPROGRESS);	/* Consumed by IPsec. */
}
Example #16
0
/* main */
int main(int argc, char *argv[])
{
  struct arguments arguments;
  bzero (&arguments, sizeof(struct arguments));
  if (argp_parse (&argp, argc, argv, 0, 0, &arguments) == ARGP_KEY_ERROR){
    fprintf(stderr,
            "[rastro_generate] at %s,"
            "error during the parsing of parameters\n",
            __func__);
    return 1;
  }

  FILE *header = fopen (arguments.header_file, "w");
  if (!header){
    fprintf(stderr,
            "[rastro_generate] at %s,"
            "could not open file %s for writing\n",
            __func__, arguments.header_file);
    return 1;
  }

  FILE *implem = fopen (arguments.implementation_file, "w");
  if (!implem){
    fprintf(stderr,
            "[rastro_generate] at %s,"
            "could not open file %s for writing\n",
            __func__, arguments.implementation_file);
    fclose (header);
    return 1;
  }

  if (arguments.from_file){
    FILE *file = fopen (arguments.from_file, "r");
    if (!file){
      fprintf(stderr,
              "[rastro_generate] at %s,"
              "could not open file %s for reading\n",
              __func__, arguments.from_file);
      fclose (header);
      fclose (implem);
      return 1;
    }
    while (feof(file)==0){
      char read_str[100];
      if (fscanf (file, "%s", read_str) != 1) break;
      if (feof(file)) break;

      arguments.input[arguments.input_size] = strdup (read_str);
      arguments.input_size++;
    }
    fclose (file);
  }

  rst_generate (arguments.input,
                arguments.input_size,
                header,
                implem,
                arguments.header_file);

  fclose (header);
  fclose (implem);
  return 0;
}
Example #17
0
void gmsvproto_sv_callback(int sock, short event, void* arg)
{
    struct event* write_ev;
    int size;
    struct sock_ev* ev = (struct sock_ev*)arg;
    //初始化通信NetPacket以及内部buffer
    //这部分内容在如下函数中释放
    //函数gmsvproto_sv.c:on_write()最后部分
    ev->packet = (struct NetPacket*)malloc(sizeof(struct NetPacket));
    if (ev->packet == NULL)
    {
        char  string[256];
        sprintf(string, "[ERROR]gmsvproto_sv.c:gmsvproto_sv_callback() malloc ev->packet failed!\n");
        LogWrite(LT_SYSTEM, string);
        printf(string);
    }

    ev->packet->m_buffer = (unsigned char*)malloc(DEFAULT_SIZE);
    if (ev->packet->m_buffer == NULL)
    {
        char string[256];
        sprintf(string, "[ERROR]gmsvproto_sv.c:gmsvproto_sv_callback() malloc ev->packet->m_buffer failed!\n");
        LogWrite(LT_SYSTEM, string);
        printf(string);
    }
    bzero(ev->packet->m_buffer, DEFAULT_SIZE);
    ev->packet->opcode = 0;
    ev->packet->m_readPos = 0;
    ev->packet->m_writePos = 0;
    ev->packet->m_buffersize = DEFAULT_SIZE;

    //接受服务器数据
    size = recv(sock, ev->packet->m_buffer, DEFAULT_SIZE, 0);
    if (size == -1)
    {
        if (errno == 104)
        {
            //暂时忽略104 Connection reset by peer
            //因为目前客户端断开连接会收到这个消息
            //不处理会导致服务器崩溃
            return;
        }
    }
    if (size == 0)
    {
        //客户端断开连接
        //这里需要处理断开连接的处理
        closePlayerSocketBySockid(sock);
    }
    printf("sock = %d, receive data:%s, size:%d\n",sock, ev->packet->m_buffer, size);
    //获取数据包的长度
    memcpy(&(ev->packet->m_writePos), ev->packet->m_buffer + sizeof(uint16_t), sizeof(uint16_t));
    if (size == 0) {
        release_sock_event(ev);
        close(sock);
        printf("sock = %d, closed!\n", sock);
        return;
    }


    event_set(ev->write_ev, sock, EV_WRITE, on_write, ev);
    event_base_set(base, ev->write_ev);
    event_add(ev->write_ev, NULL);
}
Example #18
0
library_all_infos_struct* ReadSharedCacheMap(const char *path) {
    uint64_t b_address, e_address;
    char frameworkName[256];
    char *tokens[64];
    char buf[1024];
    char *fnp;
    FILE *fd;
    int    ntokens;
    int    type;
    int    linkedit_found = 0;
    char *substring, *ptr;
    int numFrameworks = 0;

    bzero(buf, sizeof(buf));
    bzero(tokens, sizeof(tokens));

    if ((fd = fopen(path, "r")) == 0)
    {
        return 0;
    }
    while (fgets(buf, 1023, fd)) {
        if (strncmp(buf, "mapping", 7))
            break;
    }
    buf[strlen(buf)-1] = 0;

    frameworkName[0] = 0;

    int start;

    library_all_infos_struct* lib_all_infos =safe_malloc(sizeof(library_all_infos_struct));
    lib_all_infos->count = 0;
    for (;;) {
        //Extract lib name from path name

        ptr = buf;
        substring = ptr;
        start = 0;
        while (*ptr)  {
            if (*ptr == '/' && start == 0) {
                substring = ptr;
                start = 1;
            }
            ptr++;
        }

        strncpy(frameworkName, substring, 256);
        frameworkName[255] = 0;

        fnp = (char *)malloc(strlen(frameworkName) + 1);
        strcpy(fnp, frameworkName);

        while (fgets(buf, 1023, fd) && numFrameworks < (MAXINDEX - 2)) {
            /*
             * Get rid of EOL
             */
            buf[strlen(buf)-1] = 0;

            ntokens = scanline(buf, tokens, 64);

            if (ntokens < 4)
                continue;

            if (strncmp(tokens[0], "__TEXT", 6) == 0)
                type = TEXT_R;
            else if (strncmp(tokens[0], "__DATA", 6) == 0)
                type = DATA_R;
            else if (strncmp(tokens[0], "__OBJC", 6) == 0)
                type = OBJC_R;
            else if (strncmp(tokens[0], "__IMPORT", 8) == 0)
                type = IMPORT_R;
            else if (strncmp(tokens[0], "__UNICODE", 9) == 0)
                type = UNICODE_R;
            else if (strncmp(tokens[0], "__IMAGE", 7) == 0)
                type = IMAGE_R;
            else if (strncmp(tokens[0], "__LINKEDIT", 10) == 0)
                type = LINKEDIT_R;
            else
                type = -1;

            if (type == LINKEDIT_R && linkedit_found)
                break;

            if (type != -1) {
                b_address = strtoull(tokens[1], 0, 16);
                e_address = strtoull(tokens[3], 0, 16);

                library_info_struct* new_lib_info = safe_malloc(sizeof(library_info_struct));

                new_lib_info->b_address    = b_address;
                new_lib_info->e_address    = e_address;
                new_lib_info->r_type    = type;
                new_lib_info->name        = fnp;

                lib_all_infos->lib_info[lib_all_infos->count++] = new_lib_info;

                if (type == LINKEDIT_R) {
                    linkedit_found = 1;
                }
// #if DEBUG
//                 printf("%s(%d): %qx-%qx\n", frameworkInfo[numFrameworks].name, type, b_address, e_address);
// #endif

                numFrameworks++;
            }
            if (type == LINKEDIT_R)
                break;
        }
        if (fgets(buf, 1023, fd) == 0)
            break;

        buf[strlen(buf)-1] = 0;
    }
    fclose(fd);

// #if DEBUG
//     for(int i=0;i<lib_all_infos->count;i++)
//     {
//         library_info_struct* dyldinfo = lib_all_infos->lib_info[i];

//         printf("%p %p %d %s \n", dyldinfo->b_address, dyldinfo->e_address, dyldinfo->r_type, dyldinfo->name);

//     }
// #endif

    return lib_all_infos;
}
Example #19
0
int
ssh_rsa_verify(const struct sshkey *key,
    const u_char *signature, size_t signaturelen,
    const u_char *data, size_t datalen, u_int compat)
{
	struct sshbuf *b = NULL;
	const EVP_MD *evp_md;
	EVP_MD_CTX md;
	char *ktype;
	u_char digest[EVP_MAX_MD_SIZE], *osigblob, *sigblob = NULL;
	size_t len, diff, modlen;
	u_int dlen;
	int nid, ret = SSH_ERR_INTERNAL_ERROR;

	if (key == NULL || key->rsa == NULL || (key->type != KEY_RSA &&
	    key->type != KEY_RSA_CERT && key->type != KEY_RSA_CERT_V00) ||
	    BN_num_bits(key->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE)
		return SSH_ERR_INVALID_ARGUMENT;

	if ((b = sshbuf_from(signature, signaturelen)) == NULL)
		return SSH_ERR_ALLOC_FAIL;
	if (sshbuf_get_cstring(b, &ktype, NULL) != 0) {
		ret = SSH_ERR_INVALID_FORMAT;
		goto out;
	}
	if (strcmp("ssh-rsa", ktype) != 0) {
		ret = SSH_ERR_KEY_TYPE_MISMATCH;
		goto out;
	}
	if (sshbuf_get_string(b, &sigblob, &len) != 0) {
		ret = SSH_ERR_INVALID_FORMAT;
		goto out;
	}
	if (sshbuf_len(b) != 0) {
		ret = SSH_ERR_UNEXPECTED_TRAILING_DATA;
		goto out;
	}
	/* RSA_verify expects a signature of RSA_size */
	modlen = RSA_size(key->rsa);
	if (len > modlen) {
		ret = SSH_ERR_KEY_BITS_MISMATCH;
		goto out;
	} else if (len < modlen) {
		diff = modlen - len;
		osigblob = sigblob;
		if ((sigblob = realloc(sigblob, modlen)) == NULL) {
			free(osigblob);
			ret = SSH_ERR_ALLOC_FAIL;
			goto out;
		}
		memmove(sigblob + diff, sigblob, len);
		memset(sigblob, 0, diff);
		len = modlen;
	}
	nid = (compat & SSH_BUG_RSASIGMD5) ? NID_md5 : NID_sha1;
	if ((evp_md = EVP_get_digestbynid(nid)) == NULL) {
		ret = SSH_ERR_LIBCRYPTO_ERROR;
		goto out;
	}
	if (EVP_DigestInit(&md, evp_md) != 1 ||
	    EVP_DigestUpdate(&md, data, datalen) != 1 ||
	    EVP_DigestFinal(&md, digest, &dlen) != 1) {
		ret = SSH_ERR_LIBCRYPTO_ERROR;
		goto out;
	}

	ret = openssh_RSA_verify(nid, digest, dlen, sigblob, len, key->rsa);
 out:
	if (sigblob != NULL) {
		memset(sigblob, 's', len);
		free(sigblob);
	}
	if (ktype != NULL)
		free(ktype);
	if (b != NULL)
		sshbuf_free(b);
	bzero(digest, sizeof(digest));
	bzero(&md, sizeof(md));
	return ret;
}
Example #20
0
void
process_query(const gchar *host,
              Query *qs,
              guint qn)
{
    gint sockfd;
    struct addrinfo hints;
    struct addrinfo *res;
    GString *child_hostname;
    gint retry;
    pthread_t receiver;
    guint idx;

    if (option.verbose){
        for(idx = 0; idx < qn; idx++){
            fprintf(stderr, "## %d %s\n", idx + 1, qs[idx].str);
        }
        fprintf(stderr, "#####################################\n");
    }

    bzero(&hints, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    if (getaddrinfo(host, "30001", &hints, &res) != 0){
        g_printerr("getaddrinfo failed: hostname = %s\n", host);
        exit(EXIT_FAILURE);
    }
    if ((sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1){
        g_printerr("Cannot make socket\n");
        exit(EXIT_FAILURE);
    }
    gint on = 1;
    MSG("TCP_NODELAY enabled\n");
    if (setsockopt(sockfd, IPPROTO_TCP,
                   TCP_NODELAY, (char *) &on,
                   sizeof(gint)) != 0){
        g_printerr("setsockopt failed: errno = %d\n", errno);
        close(sockfd);
        exit(EXIT_FAILURE);
    }
    if (connect(sockfd, res->ai_addr, res->ai_addrlen) == -1){
        // retry
        g_printerr("[%s] failed to connect: errno = %d\n",
                   hostname, errno);
        exit(EXIT_FAILURE);
    }

    if (option.quit){
        frame_send_quit(sockfd);
        g_printerr("sent QUIT command\n");
        shutdown(sockfd, SHUT_RDWR);
        close(sockfd);
        return;
    }

    struct recv_arg arg;
    arg.qnum = qn;
    arg.sockfd = sockfd;
    if (pthread_create(&receiver, NULL, receiver_thread, &arg) != 0){
        g_printerr("failed to make receiver thread: errno = %d\n",
                   errno);
        exit(EXIT_FAILURE);
    }

    for(idx = 0; idx < qn; idx++){
        frame_send_query(sockfd, qs[idx].str);
    }
    frame_send_bye(sockfd);
    pthread_join(receiver, NULL);
    shutdown(sockfd, SHUT_RDWR);
    close(sockfd);
}
Example #21
0
/* RSASSA-PKCS1-v1_5 (PKCS #1 v2.0 signature) with SHA1 */
int
ssh_rsa_sign(const struct sshkey *key, u_char **sigp, size_t *lenp,
    const u_char *data, size_t datalen, u_int compat)
{
	const EVP_MD *evp_md;
	EVP_MD_CTX md;
	u_char digest[EVP_MAX_MD_SIZE], *sig = NULL;
	size_t slen;
	u_int dlen, len;
	int nid, ret = SSH_ERR_INTERNAL_ERROR;
	struct sshbuf *b = NULL;

	if (key == NULL || key->rsa == NULL || (key->type != KEY_RSA &&
	    key->type != KEY_RSA_CERT && key->type != KEY_RSA_CERT_V00))
		return SSH_ERR_INVALID_ARGUMENT;
	slen = RSA_size(key->rsa);
	if (slen <= 0 || slen > SSHBUF_MAX_BIGNUM)
		return SSH_ERR_INVALID_ARGUMENT;

	nid = (compat & SSH_BUG_RSASIGMD5) ? NID_md5 : NID_sha1;
	if ((evp_md = EVP_get_digestbynid(nid)) == NULL)
		return SSH_ERR_LIBCRYPTO_ERROR;
	if (EVP_DigestInit(&md, evp_md) != 1 ||
	    EVP_DigestUpdate(&md, data, datalen) != 1 ||
	    EVP_DigestFinal(&md, digest, &dlen) != 1) {
		ret = SSH_ERR_LIBCRYPTO_ERROR;
		goto out;
	}
	if ((sig = malloc(slen)) == NULL) {
		ret = SSH_ERR_ALLOC_FAIL;
		goto out;
	}

	if (RSA_sign(nid, digest, dlen, sig, &len, key->rsa) != 1) {
		ret = SSH_ERR_LIBCRYPTO_ERROR;
		goto out;
	}
	if (len < slen) {
		size_t diff = slen - len;
		memmove(sig + diff, sig, len);
		memset(sig, 0, diff);
	} else if (len > slen) {
		ret = SSH_ERR_INTERNAL_ERROR;
		goto out;
	}
	/* encode signature */
	if ((b = sshbuf_new()) == NULL) {
		ret = SSH_ERR_ALLOC_FAIL;
		goto out;
	}
	if ((ret = sshbuf_put_cstring(b, "ssh-rsa")) != 0 ||
	    (ret = sshbuf_put_string(b, sig, slen)) != 0)
		goto out;
	len = sshbuf_len(b);
	if (lenp != NULL)
		*lenp = len;
	if (sigp != NULL) {
		if ((*sigp = malloc(len)) == NULL) {
			ret = SSH_ERR_ALLOC_FAIL;
			goto out;
		}
		memcpy(*sigp, sshbuf_ptr(b), len);
	}
	ret = 0;
 out:
	bzero(digest, sizeof(digest));
	bzero(&md, sizeof(md));
	if (sig != NULL) {
		memset(sig, 's', slen);
		free(sig);
	}
	if (b != NULL)
		sshbuf_free(b);
	return 0;
}
Example #22
0
int ARMCI_Malloc(void *ptr_arr[], armci_size_t bytes)
{
int mynslave = armci_clus_info[armci_clus_me].nslave;
void *servptr,*mynodeptrs[mynslave];
int id,nodeids[mynslave],mynodeid=armci_me-armci_master;

    ARMCI_PR_DBG("enter",0);
#ifdef DEBUG_MEM
    fprintf(stderr,"%d bytes in armci_malloc %d\n",armci_me, (int)bytes);
    fflush(stderr);
    armci_msg_barrier();
#endif
		if(bytes>0){
		  if(mynslave>1){

#ifdef DEBUG_MEM
        printf("\n%d:%s:mynslave is %d",armci_me,__FUNCTION__,mynslave);fflush(stdout);
#endif
        bzero((void *)nodeids,sizeof(int)*mynslave);
        id =nodeids[mynodeid]= armci_shmget(bytes,"ARMCI_Malloc");
        armci_msg_gop_scope(SCOPE_NODE,nodeids,mynslave,"+",ARMCI_INT);
        for(int i=0;i<mynslave;i++){
          if((long)((mynodeptrs[i] = shmat(nodeids[i],mynodeptrs[i],0))) == -1L){
            char command[64];
            CLEANUP_CMD(command);
            if(system(command) == -1) 
              printf("clean shared memory (id=%d): see man ipcrm\n",nodeids[i]);
            armci_die("allocate: failed to attach to shared id=",nodeids[i]);
          }
        }

        /* mark my id for rem so OS cleans when all attached processes vanish*/
        if(shmctl( id, IPC_RMID, (struct shmid_ds *)NULL))
          fprintf(stderr,"failed to remove shm id=%d\n",id);

#ifdef DEBUG_MEM
          printf("%d:attach:id=%d paddr=%p size=%ld\n",armci_me,id,mynodeptrs[mynodeid],bytes);
          fflush(stdout);
#endif

			  if(armci_nclus>1){
          servptr = armci_server_ptr(id);
			  }
        else servptr = mynodeptrs[mynodeid];

		  }
			else{
#ifdef DEBUG_MEM
        printf("\n%d:%s:mynslave is %d, doing malloc",armci_me,__FUNCTION__,mynslave);fflush(stdout);
#endif
        mynodeptrs[mynodeid] = servptr = malloc(bytes);
			}
		}
		else{
        mynodeptrs[mynodeid] = servptr = NULL;    
		}

    bzero((char*)ptr_arr,armci_nproc*sizeof(void*));
    /*ptr_arr[armci_me] = servptr;*/
    ptr_arr[armci_me] = mynodeptrs[mynodeid];
    armci_exchange_address(ptr_arr,armci_nproc);

    if(mynslave>1)for(int i=0;i<mynslave;i++){
      ptr_arr[armci_master+i] = mynodeptrs[i];
    }

    if(armci_nclus>1){
      armci_portals_memsetup((long)servptr-(long)ptr_arr[armci_me]);
    }

    ARMCI_PR_DBG("exit",0);
    return(0);

}
int str_cli(int *fd, int n)
{
	int ret;
	int i;
	char buf[1024];
	int m;
	int prev;
	int count;
	for (i = 0; i < n; i++)
		fprintf(stdout, "fd[%d]:%d\n", i, fd[i]);
	bzero(buf, 1024);
	prev = 0;
	fd_set rset;
	fd_set wset;
	int flags;
	char prompt[1024];
	int countfd;
	for ( ; ; )
	{
		FD_ZERO(&rset);
		FD_ZERO(&wset);
		countfd = 0;
		for (i = 0; i < n; i++)
		{
			if (fd[i] == -1)
				continue;
			FD_SET(fd[i], &rset);
			FD_SET(fd[i], &wset);
			countfd++;
		}
		if (countfd == 0)
			break;

		ret = select(fd[n - 1] + 1, &rset, &wset, NULL, NULL);

		count = 0;
		for (i = 0; i < n; i++)
		{
			if (fd[i] == -1)
				continue;
			flags = 0;
			if (FD_ISSET(fd[i], &rset))
			{
readagain:
				m = recv(fd[i], buf, 1024, 0);
				if (m < 0)
					fprintf(stdout, "recv error:%s\n", strerror(errno));
				else if (m == 0)
				{
					fprintf(stdout, "peer pointer cloese\n");
					close(fd[i]);
					fd[i] = -1;
				}

				/* handle receive buffer remains */
				if (m >= 0 && prev > m)
					bzero(buf + m, prev - m);

				/* recore previous length of buffer */
				if (m >= 0 && prev != m)
					prev = m;
				fprintf(stdout, "fd:%d, buf:%s", fd[i], buf);

#if 0
				/* check isn't read end */
				if (m == 1024)
					goto readagain;
#endif

				flags = 1;

				/* check number of descriptor */
				if (++count == ret)
					break;
			}
			if (FD_ISSET(fd[i], &wset) && flags)
			{
				flags = 0;
				sprintf(prompt, "receive buff %d byte\n", m);
				send(fd[i], prompt, strlen(prompt), 0);

				/* check number of descriptor */
				if (++count == ret)
					break;
			}
		}
	}
	return 0;
}
Example #24
0
FILE *
eftread_fopen(const char *fname, char *idbuf, size_t idbufsz)
{
	FILE *fp;
	FILE *tfp;
	struct eftheader hdr;
#define	BUFLEN	8192
	char buf[BUFLEN];
	int cc;
	uint32_t csum = 0;
	char *ptr;

	if ((ptr = strrchr(fname, '.')) == NULL || strcmp(ptr, ".eft") != 0) {
		out(O_ERR, "%s: not a valid EFT (bad extension)", fname);
		return (NULL);
	}

	if ((fp = fopen(fname, "r")) == NULL) {
		out(O_ERR|O_SYS, "%s", fname);
		return (NULL);
	}

	if (fread(&hdr, 1, sizeof (hdr), fp) < sizeof (hdr)) {
		(void) fclose(fp);
		out(O_ERR, "%s: not a valid EFT (too short)", fname);
		return (NULL);
	}
	hdr.magic = ntohl(hdr.magic);
	hdr.major = ntohs(hdr.major);
	hdr.minor = ntohs(hdr.minor);
	hdr.cmajor = ntohs(hdr.cmajor);
	hdr.cminor = ntohs(hdr.cminor);
	hdr.identlen = ntohl(hdr.identlen);
	hdr.dictlen = ntohl(hdr.dictlen);
	hdr.csum = ntohl(hdr.csum);

	if (Showheader)
		out(O_VERB, "%s: magic %x EFT version %d.%d esc version %d.%d",
		    fname, hdr.magic, hdr.major, hdr.minor,
		    hdr.cmajor, hdr.cminor);

	if (hdr.magic != EFT_HDR_MAGIC) {
		(void) fclose(fp);
		out(O_ERR, "%s: not a valid EFT (bad magic)", fname);
		return (NULL);
	}

	if (hdr.major != EFT_HDR_MAJOR || hdr.minor > EFT_HDR_MINOR) {
		(void) fclose(fp);
		out(O_ERR, "%s is version %d.%d, "
		    "this program supports up to %d.%d", fname,
		    hdr.major, hdr.minor, EFT_HDR_MAJOR, EFT_HDR_MINOR);
		return (NULL);
	}

	bzero(idbuf, idbufsz);
	if (hdr.identlen != 0) {
		long npos = ftell(fp) + (long)hdr.identlen; /* after ident */
		size_t rsz = MIN(hdr.identlen, idbufsz - 1);

		if (fread(idbuf, 1, rsz, fp) != rsz)
			out(O_DIE|O_SYS, "%s: fread", fname);
		if (fseek(fp, npos, SEEK_SET) == -1)
			out(O_DIE|O_SYS, "%s: fseek", fname);
	}

	if (hdr.dictlen && (hdr.dictlen < 2 || hdr.dictlen > 1000)) {
		(void) fclose(fp);
		out(O_ERR, "%s: bad dictlen: %d", fname, hdr.dictlen);
		return (NULL);
	}

	/* read in dict strings */
	if (hdr.dictlen) {
		char *dbuf = alloca(hdr.dictlen);
		char *dptr;

		if ((cc = fread(dbuf, 1, hdr.dictlen, fp)) != hdr.dictlen)
			out(O_DIE|O_SYS, "short fread on %s (dictlen %d)",
			    fname, hdr.dictlen);

		/* work from end of string array backwards, finding names */
		for (dptr = &dbuf[hdr.dictlen - 2]; dptr > dbuf; dptr--)
			if (*dptr == '\0') {
				/* found separator, record string */
				Dicts = lut_add(Dicts,
				    (void *)stable(dptr + 1), (void *)0, NULL);
			}
		/* record the first string */
		Dicts = lut_add(Dicts,
		    (void *)stable(dptr), (void *)0, NULL);
	}

	if ((tfp = tmpfile()) == NULL)
		out(O_DIE|O_SYS, "cannot create temporary file");

	while ((cc = fread(buf, 1, BUFLEN, fp)) > 0) {
		char *ptr;

		for (ptr = buf; ptr < &buf[cc]; ptr++) {
			*ptr = ~((unsigned char)*ptr);
			csum += (uint32_t)*ptr;
		}
		if (cc != fwrite(buf, 1, cc, tfp) || ferror(tfp))
			out(O_DIE|O_SYS, "fwrite on tmpfile");
	}
	if (ferror(fp))
		out(O_DIE|O_SYS, "fread on %s", fname);
	(void) fclose(fp);

	if (hdr.csum != csum) {
		out(O_ERR, "%s: bad checksum (%x != %x)", fname,
		    hdr.csum, csum);
		(void) fclose(tfp);
		return (NULL);
	}

	if (Showheader) {
		int len = strlen(hdr.comment);
		if (len > 0 && hdr.comment[len - 1] == '\n')
			hdr.comment[len - 1] = '\0';
		out(O_OK, "%s:\n\t%s", fname, hdr.comment);
	}

	rewind(tfp);

	return (tfp);
}
Example #25
0
main(int argc, char *argv[])
{
    int fileSize = 0, fd = 0, n =0;
    char *hostname;
    char line[MAX], buff[256], functionName = 0, pathName[256] = {0}, fileName[256] = {0};

    if (argc < 2)
        hostname = "localhost";
    else
        hostname = argv[1];

    chdir("../ServerRoot");
    getcwd(buff, 256);
    //chroot(buff);

    server_init(hostname);
    initializeFunctionList();

    // Try to accept a client request
    while(1) {
        printf("server: accepting new connection ....\n");

        // Try to accept a client connection as descriptor newsock
        length = sizeof(client_addr);
        newsock = accept(sock, (struct sockaddr *)&client_addr, &length);
        if (newsock < 0) {
            printf("server: accept error\n");
            exit(1);
        }
        printf("server: accepted a client connection from\n");
        printf("-----------------------------------------------\n");
        printf("        IP=%s  port=%d\n", (char*)inet_ntoa(client_addr.sin_addr.s_addr),
               ntohs(client_addr.sin_port));
        printf("-----------------------------------------------\n");

        // Processing loop
        while(1)
        {
            printf("@> ");
            n = read(newsock, line, MAX);
            if (n==0)
            {
                printf("server: client died, server loops\n");
                close(newsock);
                break;
            }

            //grab function number and pathname from the client input
            if(line[0] == 'P') //Server receives a put command from client
            {
                strtok(line, " ");
                fileSize = atoi(strtok(NULL, " "));
                strcpy(fileName, strtok(NULL, " "));
                fd = open(fileName, O_WRONLY | O_CREAT, 0644);
                if(fd == 0) {
                    write(newsock, "F", 2);
                }
                else {
                    write(newsock, "S", 2);
                    printf("Reading file from client...\n");
                    while(fileSize > 0)
                    {
                        n = read(newsock, returnString, 4096);

                        write(fd, returnString, n);
                        fileSize -= n;
                    }
                    printf("@> File '%s' from client uploaded...\n", fileName);
                    close (fd);
                }


            }
            else if(line[0] == 'G') //Server receives a get command from client
            {
                int fd = 0, i = 0, n = 0;
                struct stat fileStatus;
                char buff[16];
                char fileName[256] = {0};

                strtok(line, " ");
                strcpy(fileName, strtok(NULL, " "));

                fd = open(fileName, O_RDONLY);

                if(fd == 0) {
                    printf("Server File Not Found.");
                    write(newsock, "F", 2);
                }
                else
                {
                    fstat(fd, &fileStatus);

                    sprintf(buff, "S %d", 74);
                    write(newsock, buff, 16);
                    printf("Sending %s to client...\n", fileName);
                    i = fileStatus.st_size;
                    while(i > 0)
                    {
                        n = read(fd, returnString, 4096);
                        write(newsock, returnString, strlen(returnString));
                        i -= n;
                    }
                    printf("@> Transmission of %d bytes complete...\n", (int) fileStatus.st_size);
                }
            }
            else
            {
                functionName = atoi(&line[0]);
                if(line[1] == ' ')
                {
                    strcpy(pathName, &line[2]);
                }
                else
                {
                    pathName[0] = '\0';
                }
                printf("Server: client sent func: %d | path: %s\n", functionName, pathName);
                executeServerCommand(functionName, pathName, newsock);
            }
            bzero(line, MAX);
        }
    }
}
Example #26
0
int main()
{	int sd;
	struct sigaction act;
	struct sockaddr_in self;

	bzero(&act, sizeof(act));
    act.sa_handler = sig_handler;
    act.sa_flags = SA_NOCLDSTOP;
    sigaction(SIGCHLD, &act, 0);
	/*---Create new socket---*/
	if ( (sd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
	{
		perror("Socket");
		exit(errno);
	}
/*	if ( setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, 0, 0) < 0 ) perror("SocketOpt");*/

	/*---Initialize own server address---*/
	bzero(&self, sizeof(self));
	self.sin_family = AF_INET;
	self.sin_addr.s_addr = INADDR_ANY;
	self.sin_port = htons(MY_PORT);

	/*---Give the socket a "name" (set the IP and Port addresses)---*/
	if ( bind(sd, (struct sockaddr*)&self, sizeof(self)) != 0 )
	{
		perror("Bind");
		abort();
	}

	/*---Make the socket a "listening socket"---*/
	if ( listen(sd, 20) != 0 )
	{
		perror("Listen");
		abort();
	}

	/*---Forever...---*/
	while (1)
	{	static int client;
		int sd_copy, size;
		struct sockaddr_in client_info;

		/*---Accept client connection (creates a new communication port)---*/
		size = sizeof(client_info);
		client = accept(sd, (struct sockaddr*)&client_info, &size);
		if ( client < 0 )
			perror("Accept");
		else
		{
			printf("Connected: %s:%d\n", inet_ntoa(client_info.sin_addr), ntohs(client_info.sin_port));

			/*---Create child task to handle service---*/
			if ( fork() != 0 )
			{
/*Parent*/		/*---The parent doesn't need the child's data connection---*/
				close(client);
			}
			else
			{
/*Child*/		/*---Child doesn't need access to request connection---*/
				close(sd);

				/*---Map stdin, stdout and stderr to the data connection---*/
				dup2(client, 0);
				dup2(client, 1);
				dup2(client, 2);

				/*---Call external program---*/
				execl("/bin/ls", "/bin/ls", "-al", "/sbin", 0);
			}
		}
	}

	/*---Clean up (should never get here)---*/
	close(sd);
	return 0;
}
Example #27
0
int main( int argc, char *argv[] ) {
  int five;
  int myint = 1;
  struct sockaddr_in server,client;
  sigemptyset((sigset_t *)&five);
  int init_fd = socket(AF_INET, SOCK_STREAM, 0);

  if (init_fd == -1) {
     perror("socket");
     exit(-1);
  }
  bzero((char *) &server, sizeof(server));

  if(setsockopt(init_fd,SOL_SOCKET,SO_REUSEADDR,&myint,sizeof(myint)) == -1){
    perror("setsocket");
      exit(-1);
  }

  server.sin_family = AF_INET;
  server.sin_addr.s_addr = htonl(INADDR_ANY);
  server.sin_port = htons(atoi(argv[1]));

  if (bind(init_fd, (struct sockaddr *) &server, sizeof(server)) == -1) {
     perror("bind");
     exit(-1);
  }

  if((listen(init_fd,20)) == -1){
     perror("listen");
     exit(-1);
  }
  int addr_len = sizeof(client);

   while (1) {

        int fd = accept(init_fd,(struct sockaddr *)&client,(socklen_t*)&addr_len);

     if (fd < 0) {
        perror("accept");
        exit(1);
     }
     pid_t pid = fork();

     if (pid == -1) {
       perror("fork");
       close(fd);
     }

     if (pid == 0){
	  alarm(15);
          close(init_fd);
	  int user_priv = priv("tutorial");
	  if(!user_priv){
          	menu(fd);
		close(fd);
	        exit(0);
	  }
     }else{
            close(fd);
      }

    }
  close(init_fd);
}
Example #28
0
void
deattack_init(struct deattack_ctx *dctx)
{
	bzero(dctx, sizeof(*dctx));
	dctx->n = HASH_MINSIZE / HASH_ENTRYSIZE;
}
Example #29
0
int
fuse_io_strategy(struct vnode *vp, struct buf *bp)
{
	struct fuse_filehandle *fufh;
	struct fuse_vnode_data *fvdat = VTOFUD(vp);
	struct ucred *cred;
	struct uio *uiop;
	struct uio uio;
	struct iovec io;
	int error = 0;

	const int biosize = fuse_iosize(vp);

	MPASS(vp->v_type == VREG || vp->v_type == VDIR);
	MPASS(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE);
	FS_DEBUG("inode=%ju offset=%jd resid=%ld\n",
	    (uintmax_t)VTOI(vp), (intmax_t)(((off_t)bp->b_blkno) * biosize),
	    bp->b_bcount);

	error = fuse_filehandle_getrw(vp,
	    (bp->b_iocmd == BIO_READ) ? FUFH_RDONLY : FUFH_WRONLY, &fufh);
	if (error) {
		printf("FUSE: strategy: filehandles are closed\n");
		bp->b_ioflags |= BIO_ERROR;
		bp->b_error = error;
		return (error);
	}
	cred = bp->b_iocmd == BIO_READ ? bp->b_rcred : bp->b_wcred;

	uiop = &uio;
	uiop->uio_iov = &io;
	uiop->uio_iovcnt = 1;
	uiop->uio_segflg = UIO_SYSSPACE;
	uiop->uio_td = curthread;

	/*
         * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
         * do this here so we do not have to do it in all the code that
         * calls us.
         */
	bp->b_flags &= ~B_INVAL;
	bp->b_ioflags &= ~BIO_ERROR;

	KASSERT(!(bp->b_flags & B_DONE),
	    ("fuse_io_strategy: bp %p already marked done", bp));
	if (bp->b_iocmd == BIO_READ) {
		io.iov_len = uiop->uio_resid = bp->b_bcount;
		io.iov_base = bp->b_data;
		uiop->uio_rw = UIO_READ;

		uiop->uio_offset = ((off_t)bp->b_blkno) * biosize;
		error = fuse_read_directbackend(vp, uiop, cred, fufh);

		if ((!error && uiop->uio_resid) ||
		    (fsess_opt_brokenio(vnode_mount(vp)) && error == E_IO &&
		    uiop->uio_offset < fvdat->filesize && fvdat->filesize > 0 &&
		    uiop->uio_offset >= fvdat->cached_attrs.va_size)) {
			/*
	                 * If we had a short read with no error, we must have
	                 * hit a file hole.  We should zero-fill the remainder.
	                 * This can also occur if the server hits the file EOF.
	                 *
	                 * Holes used to be able to occur due to pending
	                 * writes, but that is not possible any longer.
	                 */
			int nread = bp->b_bcount - uiop->uio_resid;
			int left = uiop->uio_resid;

			if (error != 0) {
				printf("FUSE: Fix broken io: offset %ju, "
				       " resid %zd, file size %ju/%ju\n",
				       (uintmax_t)uiop->uio_offset,
				    uiop->uio_resid, fvdat->filesize,
				    fvdat->cached_attrs.va_size);
				error = 0;
			}
			if (left > 0)
				bzero((char *)bp->b_data + nread, left);
			uiop->uio_resid = 0;
		}
		if (error) {
			bp->b_ioflags |= BIO_ERROR;
			bp->b_error = error;
		}
	} else {
		/*
	         * If we only need to commit, try to commit
	         */
		if (bp->b_flags & B_NEEDCOMMIT) {
			FS_DEBUG("write: B_NEEDCOMMIT flags set\n");
		}
		/*
	         * Setup for actual write
	         */
		if ((off_t)bp->b_blkno * biosize + bp->b_dirtyend >
		    fvdat->filesize)
			bp->b_dirtyend = fvdat->filesize -
				(off_t)bp->b_blkno * biosize;

		if (bp->b_dirtyend > bp->b_dirtyoff) {
			io.iov_len = uiop->uio_resid = bp->b_dirtyend
			    - bp->b_dirtyoff;
			uiop->uio_offset = (off_t)bp->b_blkno * biosize
			    + bp->b_dirtyoff;
			io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
			uiop->uio_rw = UIO_WRITE;

			error = fuse_write_directbackend(vp, uiop, cred, fufh);

			if (error == E_INTR || error == E_TIMEDOUT
			    || (!error && (bp->b_flags & B_NEEDCOMMIT))) {

				bp->b_flags &= ~(B_INVAL | B_NOCACHE);
				if ((bp->b_flags & B_PAGING) == 0) {
					bdirty(bp);
					bp->b_flags &= ~B_DONE;
				}
				if ((error == E_INTR || error == E_TIMEDOUT) &&
				    (bp->b_flags & B_ASYNC) == 0)
					bp->b_flags |= B_EINTR;
			} else {
				if (error) {
					bp->b_ioflags |= BIO_ERROR;
					bp->b_flags |= B_INVAL;
					bp->b_error = error;
				}
				bp->b_dirtyoff = bp->b_dirtyend = 0;
			}
		} else {
			bp->b_resid = 0;
			bufdone(bp);
			return (0);
		}
	}
	bp->b_resid = uiop->uio_resid;
	bufdone(bp);
	return (error);
}
Example #30
0
//==========================================================================
// The 'main' function for the booter. Called by boot0 when booting
// from a block device, or by the network booter.
//
// arguments:
//   biosdev - Value passed from boot1/NBP to specify the device
//             that the booter was loaded from.
//
// If biosdev is kBIOSDevNetwork, then this function will return if
// booting was unsuccessful. This allows the PXE firmware to try the
// next boot device on its list.
void common_boot(int biosdev)
{
    int      status;
    char     *bootFile;
    unsigned long adler32;
    bool     quiet;
    bool     firstRun = true;
    bool     instantMenu;
    bool     rescanPrompt = false;
    unsigned int allowBVFlags = kBVFlagSystemVolume|kBVFlagForeignBoot;
    unsigned int denyBVFlags = kBVFlagEFISystem;

    // Set reminder to unload the PXE base code. Neglect to unload
    // the base code will result in a hang or kernel panic.
    gUnloadPXEOnExit = true;

    // Record the device that the booter was loaded from.
    gBIOSDev = biosdev & kBIOSDevMask;

    // Initialize boot info structure.
    initKernBootStruct();

	initBooterLog();

    // Setup VGA text mode.
    // Not sure if it is safe to call setVideoMode() before the
    // config table has been loaded. Call video_mode() instead.
#if DEBUG
    printf("before video_mode\n"); //Azi: this one is not printing... i remember it did.. check trunk.
#endif
    video_mode( 2 );  // 80x25 mono text mode.
#if DEBUG
    printf("after video_mode\n");
#endif

    // Scan and record the system's hardware information.
    scan_platform();

    // First get info for boot volume.
    scanBootVolumes(gBIOSDev, 0);
    bvChain = getBVChainForBIOSDev(gBIOSDev);
	//Azi: initialising gBIOSBootVolume & gBootVolume (Startup volume) for the first time.. i think!?
	// also, kDefaultPartitionKey is checked here, on selectBootVolume.
    setBootGlobals(bvChain);
	msglog("setBootGlobals:\n Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
    msglog(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);

	// Boot Volume is set as Root at this point so, pointing to Extra, /Extra or bt(0,0)/Extra
	// is exactly the same.	Review bt(0,0)/bla bla paths......			(Reviewing...)
	
	//Azi: works as expected but... trying this because Kernel=mach_kernel doesn't work on a
	// override Boot.plist; this makes it impossible to override e.g. Kernel=bt(0,0)mach_kernel
	// on the main Boot.plist, when loading kernel from ramdisk btAliased.
	loadPrebootRAMDisk();
	
    // Load boot.plist config file
    //Azi: on this first check, boot.plist acts as both "booter config file"
    // and bootargs/options "carrier".*****
    status = loadSystemConfig(&bootInfo->bootConfig);

    if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->bootConfig) && quiet) {
        gBootMode |= kBootModeQuiet;
    }

    // Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
    if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->bootConfig) && instantMenu) {
        firstRun = false;
    }

	// Loading preboot ramdisk if exists.
//	loadPrebootRAMDisk(); //Azi: this needs to be done before load_all_modules()
	// because of btAlias...			(Reviewing...)

	// Intialize module system
	if (init_module_system())
	{
		load_all_modules();
	}

    // Disable rescan option by default
    gEnableCDROMRescan = false;

    // If we're loading the booter from optical media...			(Reviewing...)
	if (biosDevIsCDROM(gBIOSDev))
	{
		// ... ask the user for Rescan option by setting "Rescan Prompt"=y in system config...
		if (getBoolForKey(kRescanPromptKey, &rescanPrompt, &bootInfo->bootConfig) && rescanPrompt)
		{
	        gEnableCDROMRescan = promptForRescanOption();
	    }
		else // ... or enable it with Rescan=y in system config.
	    if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->bootConfig) && gEnableCDROMRescan)
		{
	        gEnableCDROMRescan = true;
	    }
	}

	//Azi: Is this a cdrom only thing?			(Reviewing...)
    // Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
    if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->bootConfig) && gScanSingleDrive)
	{
		scanBootVolumes(gBIOSDev, &bvCount);
    }
	else
	{
		//Azi: scanDisks uses scanBootVolumes.
		scanDisks(gBIOSDev, &bvCount);
	}
	
    // Create a separated bvr chain using the specified filters.
    bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);

    gBootVolume = selectBootVolume(bvChain);

//#if DEBUG
//printf
    msglog(":something...???\n Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
    msglog(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
//    getchar();
//#endif

    useGUI = true;
    // Override useGUI default
    getBoolForKey(kGUIKey, &useGUI, &bootInfo->bootConfig);

	// AutoResolution - Azi: default to false
	// http://forum.voodooprojects.org/index.php/topic,1227.0.html
	gAutoResolution = false;
	
	// Check if user enabled AutoResolution on Boot.plist...
	getBoolForKey(kAutoResolutionKey, &gAutoResolution, &bootInfo->bootConfig);
	
	// Patch the Video Bios with the extracted resolution, before initGui.
	if (gAutoResolution == true)
	{
		initAutoRes();
	}

    if (useGUI && initGUI())
	{
		// initGUI() returned with an error, disabling GUI.
		useGUI = false;
	}

    setBootGlobals(bvChain);
	msglog("setBootGlobals:\n Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
    msglog(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n", gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);

    // Parse args, load and start kernel.
    while (1) {
        const char *val;
        int len;
        int trycache;
		long flags, cachetime, kerneltime, exttime, sleeptime, time;
        int ret = -1;
        void *binary = (void *)kLoadAddr;
        bool tryresume;
        bool tryresumedefault;
        bool forceresume;
		bool ignoreKC = false;

        // additional variable for testing alternate kernel image locations on boot helper partitions.
        char     bootFileSpec[512];
		
        // Initialize globals.

        sysConfigValid = false;
        gErrors        = false;

        status = getBootOptions(firstRun);
        firstRun = false;
        if (status == -1) continue;

		//Azi: test (gBootVolume == NULL) - so far Ok!
		// test with optical media again...?
		// Turn off any GUI elements, draw background and update VRAM.
		if ( bootArgs->Video.v_display == GRAPHICS_MODE )
		{
			gui.devicelist.draw = false;
			gui.bootprompt.draw = false;
			gui.menu.draw = false;
			gui.infobox.draw = false;
			gui.logo.draw = false;
			drawBackground();
			updateVRAM();
		}

		status = processBootOptions();

		//Azi: AutoResolution -  closing Vbios here without restoring, causes an allocation error,
		// if the user tries to boot, after a e.g."Can't find bla_kernel" msg.
		// Doing it on execKernel() instead.

		// Status == 1 means to chainboot
		if ( status ==	1 ) break;
		
		// Status == -1 means that gBootVolume is NULL. Config file is not mandatory anymore! 
		if ( status == -1 )
		{
			// gBootVolume == NULL usually means the user hit escape.			(Reviewing...)
			if (gBootVolume == NULL)
			{
				freeFilteredBVChain(bvChain);
				
				if (gEnableCDROMRescan)
					rescanBIOSDevice(gBIOSDev);
				
				bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
				setBootGlobals(bvChain);
				setupDeviceList(&bootInfo->themeConfig);
			}
			continue;
		}
		
        // Other status (e.g. 0) means that we should proceed with boot.

		// If cpu handles 64 bit instructions...
		if (platformCPUFeature(CPU_FEATURE_EM64T))
		{
			// use x86_64 kernel arch,...
			archCpuType = CPU_TYPE_X86_64;
		}
		else
		{
			// else use i386 kernel arch.
			archCpuType = CPU_TYPE_I386;
		}
		// If user override...
		if (getValueForKey(kArchKey, &val, &len, &bootInfo->bootConfig))
		{
			// matches i386...
			if (strncmp(val, "i386", 4) == 0)
			{
				// use i386 kernel arch.
				archCpuType = CPU_TYPE_I386;
			}
		}
		
		if (!getBoolForKey (kWakeKey, &tryresume, &bootInfo->bootConfig)) {
			tryresume = true;
			tryresumedefault = true;
		} else {
			tryresumedefault = false;
		}

		if (!getBoolForKey (kForceWakeKey, &forceresume, &bootInfo->bootConfig)) {
			forceresume = false;
		}
		
		if (forceresume) {
			tryresume = true;
			tryresumedefault = false;
		}
		
		while (tryresume) {
			const char *tmp;
			BVRef bvr;
			if (!getValueForKey(kWakeKeyImageKey, &val, &len, &bootInfo->bootConfig))
				val="/private/var/vm/sleepimage";
			
			// Do this first to be sure that root volume is mounted
			ret = GetFileInfo(0, val, &flags, &sleeptime);

			if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
				break;
			
			// Can't check if it was hibernation Wake=y is required
			if (bvr->modTime == 0 && tryresumedefault)
				break;
			
			if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
				break;
			
			if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
				//Azi: no need for printf at this point - reminder
				printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override.\n",bvr->modTime-sleeptime);
				break;
			}
				
			HibernateBoot((char *)val);
			break;
		}

//Azi:kernelcache stuff
		bool patchKernel = false;
		getBoolForKey(kKPatcherKey, &patchKernel, &bootInfo->bootConfig);
		//Azi: avoiding having to use -f to ignore kernel cache
		//Azi: ignore kernel cache but still use kext cache (E/E.mkext & S/L/E.mkext). - explain...
		getBoolForKey(kUseKCKey, &ignoreKC, &bootInfo->bootConfig); // equivalent to UseKernelCache
		if (ignoreKC)
		{
			verbose("KC: cache ignored by user.\n");
			// make sure the damn thing get's zeroed, just in case... :)*
			bzero(gBootKernelCacheFile, sizeof(gBootKernelCacheFile));
		}
		else if (patchKernel) // to be moved..?
		{
			verbose("KC: kernel patcher enabled, ignore cache.\n");
			bzero(gBootKernelCacheFile, sizeof(gBootKernelCacheFile));
		}
		else if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig))
		{
            strlcpy(gBootKernelCacheFile, val, len + 1);
			verbose("KC: path set by user = %s\n", gBootKernelCacheFile);
			//Azi: bypass time check when user sets path ???
			// cache is still ignored if time doesn't match... (e.g. booter on usb stick)
        }
		else
		{
			// Reset cache name.
			bzero(gCacheNameAdler + 64, sizeof(gCacheNameAdler) - 64);
			
			// kextcache_main.c: Construct entry from UUID of boot volume...(reminder)
			// assemble ?string? to generate adler from...
//			sprintf(gCacheNameAdler + 64, "%s,%s", gRootDevice, bootInfo->bootFile); - OLD
			const char *ProductName = getStringForKey("SMproductname", &bootInfo->smbiosConfig);
			sprintf(gCacheNameAdler, ProductName); // well, at least the smbios.plist can be loaded this early...
			// to set/get "ProductName" this early, booter needs complete rewrite!!
			// see DHP's Revolution booter rework example!
		//	verbose("KC: gCacheNameAdler 1 = %s\n", gCacheNameAdler);
			//Azi: check the validity of this, e.g. on Helper Partitions
			sprintf(gCacheNameAdler + 64, "%s", "\\System\\Library\\CoreServices\\boot.efi");
		//	verbose("KC: gCacheNameAdler 2 = %s\n", gCacheNameAdler + 64);
			sprintf(gCacheNameAdler + (64 + 38), "%s", bootInfo->bootFile);
		//	verbose("KC: gCacheNameAdler 3 = %s\n", gCacheNameAdler + (64 + 38));

			// generate adler
			adler32 = Adler32((unsigned char *)gCacheNameAdler, sizeof(gCacheNameAdler));
		//	verbose("KC: Adler32 = %08X\n", adler32);
//Azi: no check for OS version here ?? - yes there is :)
			// append arch and/or adler (checksum) to kc path...
			if (gMacOSVersion[3] <= '5')
			{
				sprintf(gBootKernelCacheFile, "%s.%08lX", kCachePathTigerLeopard, adler32);
		//		verbose("KC: adler added to path = %s\n", gBootKernelCacheFile);
			}
			else
			{
				sprintf(gBootKernelCacheFile, "%s_%s.%08X", kCachePathSnowLion,
						(archCpuType == CPU_TYPE_I386) ? "i386" : "x86_64", adler32);
		//		verbose("KC: arch & adler added to path = %s\n", gBootKernelCacheFile);
			}
        }

        // Check for cache file.
		//Azi: trycache is done if...
        trycache = ( ( (gBootMode & kBootModeSafe) == 0) //... we're not booting in safe mode (-x arg),
					&& !gOverrideKernel // we're not overriding default kernel "name",
					&& (gBootFileType == kBlockDeviceType) // we're booting from local storage device,
					&& (gMKextName[0] == '\0') // "MKext Cache" key IS NOT in use, and
					&& (gBootKernelCacheFile[0] != '\0') ); // gBootKernelCacheFile is populated.
					// we could add the use of "kernelpatcher" to this bunch..??

//		verbose("Loading Darwin %s\n", gMacOSVersion); //Azi: move?? to getOSVersion? :)
		
        if (trycache) do
		{
			verbose("KC: checking kernel cache (system prelinked kernel)...\n");
            // if we haven't found the kernel yet, don't use the cache
            ret = GetFileInfo(NULL, bootInfo->bootFile, &flags, &kerneltime);
            if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
            {
				verbose("KC: no kernel found (shouldn't happen?!?)\n");
                trycache = 0; // ignore kernel cache...
                break;
            }
			verbose("KC: kerneltime = %d\n", kerneltime);
			
            ret = GetFileInfo(NULL, gBootKernelCacheFile, &flags, &cachetime);
            if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat)
                || (cachetime < kerneltime))
            {
				if (cachetime <= 100) // confirm: 100 = inexistent path, -xxxxxxxxx = wrong name
				// not confirming... i also get -xxxxxxxxx with inexisting prelinked kernel
					verbose("KC: cachetime  = %d, kernel cache path/adler is incorrect, ignoring it. ??? \n",
							cachetime);
				else
					verbose("KC: cachetime  = %d, kernel cache is older than the kernel, ignoring it.\n",
							cachetime);
                trycache = 0;
                break;
            }
			verbose("KC: cachetime  = %d\n", cachetime);
			
            ret = GetFileInfo("/System/Library/", "Extensions", &flags, &exttime);
            if ((ret == 0) && ((flags & kFileTypeMask) == kFileTypeDirectory)
                && (cachetime < exttime))
            {
				verbose("KC: exttime    = %d, kernel cache is older than S/L/E, ignoring it.\n", exttime);
                trycache = 0;
                break;
            }
			verbose("KC: exttime    = %d\n", exttime);
			
            if (kerneltime > exttime) // if S/L/E is older than the kernel...
            {
				verbose("KC: S/L/E is older than the kernel, matching exttime with kerneltime...\n");
                exttime = kerneltime;
            }
			verbose("KC: exttime +1 = %d\n", exttime + 1);
			
            if (cachetime != (exttime + 1))
            {
				verbose("KC: kernel cache time is diff from S/L/E time, ignoring it.\n");
                trycache = 0;
                break;
            }
			verbose("KC: kernel cache found and up to date, will be used.\n");

        } while (0);

        do
        {
			// Load kernel cache if not ignored.
            if (trycache)
            {
                bootFile = gBootKernelCacheFile;
                verbose("Loading kernel cache %s\n", bootFile);

                ret = LoadFile(bootFile);
                binary = (void *)kLoadAddr;

                if (ret >= 0)
                {
                    break;
                }
            }

            bootFile = bootInfo->bootFile;

            // Try to load kernel image from alternate locations on boot helper partitions.
            sprintf(bootFileSpec, "com.apple.boot.P/%s", bootFile);
            ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); 
  	  	    if (ret == -1)
  	  	    {
				sprintf(bootFileSpec, "com.apple.boot.R/%s", bootFile);
				ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); 
				if (ret == -1)
				{
					sprintf(bootFileSpec, "com.apple.boot.S/%s", bootFile);
					ret = GetFileInfo(NULL, bootFileSpec, &flags, &time); 
					if (ret == -1)
					{
						// No alternate location found, using the original kernel image path.
						strcpy(bootFileSpec, bootFile);
					}
				}
            }
            			
            verbose("Loading kernel %s\n", bootFileSpec);
            ret = LoadThinFatFile(bootFileSpec, &binary);
            if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
            {
				archCpuType = CPU_TYPE_I386;
				ret = LoadThinFatFile(bootFileSpec, &binary);				
            }
			
        } while (0);

        clearActivityIndicator();
/*#if DEBUG
        printf("Pausing...");
        sleep(8);
#endif
Azi: annoying stuff :P */
        if (ret <= 0)
		{
			printf("Can't find %s\n", bootFile);

			sleep(1);

            if (gBootFileType == kNetworkDeviceType) {
                // Return control back to PXE. Don't unload PXE base code.
                gUnloadPXEOnExit = false;
                break;
            }
        }
		else
		{
            // Won't return if successful.
            ret = ExecKernel(binary);
        }
    } // while (1)
    
    // chainboot
    if (status==1) {
		if (getVideoMode() == GRAPHICS_MODE) {	// if we are already in graphics-mode,
			setVideoMode(VGA_TEXT_MODE, 0);	// switch back to text mode
		}
    }
	
    if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit)
	{
		nbpUnloadBaseCode();
    }
}