void platform_setCurrentWorkingDir(const char *path)
{
    chdir(path);
}
Exemple #2
0
int send_message(char * msg, char * from, char ** recipients, int num_recipients)
{
    /*	...Adds Date:
    	...Adds Message-Id:*/
    int r;
    int wstat;
    int i;
    struct tm * dt;
    unsigned long msgwhen;
    FILE * fdm;
    FILE * fde;
    pid_t pid;
    int pim[2];				/*message pipe*/
    int pie[2];				/*envelope pipe*/
    FILE *mfp;
    char msg_buffer[256];

    /*open a pipe to qmail-queue*/
    if(pipe(pim)==-1 || pipe(pie)==-1) {
        return -1;
    }
    pid = vfork();
    if(pid == -1) {
        /*failure*/
        return -1;
    }
    if(pid == 0) {
        /*I am the child*/
        close(pim[1]);
        close(pie[1]);
        /*switch the pipes to fd 0 and 1
          pim[0] goes to 0 (stdin)...the message*/
        if(fcntl(pim[0],F_GETFL,0) == -1) {
            /*			fprintf(stderr,"Failure getting status flags.\n");*/
            _exit(120);
        }
        close(0);
        if(fcntl(pim[0],F_DUPFD,0)==-1) {
            /*			fprintf(stderr,"Failure duplicating file descriptor.\n");*/
            _exit(120);
        }
        close(pim[0]);
        /*pie[0] goes to 1 (stdout)*/
        if(fcntl(pie[0],F_GETFL,0) == -1) {
            /*			fprintf(stderr,"Failure getting status flags.\n");*/
            _exit(120);
        }
        close(1);
        if(fcntl(pie[0],F_DUPFD,1)==-1) {
            /*			fprintf(stderr,"Failure duplicating file descriptor.\n");*/
            _exit(120);
        }
        close(pie[0]);
        if(chdir(QMAIL_LOCATION) == -1) {
            _exit(120);
        }
        execv(*binqqargs,binqqargs);
        _exit(120);
    }

    /*I am the parent*/
    fdm = fdopen(pim[1],"wb");					/*updating*/
    fde = fdopen(pie[1],"wb");
    if(fdm==NULL || fde==NULL) {
        return -1;
    }
    close(pim[0]);
    close(pie[0]);

    /*prepare to add date and message-id*/
    msgwhen = time(NULL);
    dt = gmtime((long *)&msgwhen);
    /*start outputting to qmail-queue
      date is in 822 format
      message-id could be computed a little better*/
    fprintf(fdm,"Date: %u %s %u %02u:%02u:%02u -0000\nMessage-ID: <%lu.%u.blah>\n"
            ,dt->tm_mday,montab[dt->tm_mon],dt->tm_year+1900,dt->tm_hour,dt->tm_min,dt->tm_sec,msgwhen,getpid() );

    mfp = fopen( msg, "rb" );

    while ( fgets( msg_buffer, sizeof(msg_buffer), mfp ) != NULL )
    {
        fprintf(fdm,"%s",msg_buffer);
    }

    fclose(mfp);

    fclose(fdm);


    /*send the envelopes*/

    fprintf(fde,"F%s",from);
    fwrite("",1,1,fde);					/*write a null char*/
    for(i=0; i<num_recipients; i++) {
        fprintf(fde,"T%s",recipients[i]);
        fwrite("",1,1,fde);					/*write a null char*/
    }
    fwrite("",1,1,fde);					/*write a null char*/
    fclose(fde);

    /*wait for qmail-queue to close*/
    do {
        r = wait(&wstat);
    } while ((r != pid) && ((r != -1) || (errno == EINTR)));
    if(r != pid) {
        /*failed while waiting for qmail-queue*/
        return -1;
    }
    if(wstat & 127) {
        /*failed while waiting for qmail-queue*/
        return -1;
    }
    /*the exit code*/

    if((wstat >> 8)!=0) {
        /*non-zero exit status
          failed while waiting for qmail-queue*/
        return -1;
    }
    return 0;
}
Exemple #3
0
int
rm_r(const char *path)
{
	int ret = 0;
	DIR *dir;
	struct dirent *dent;

	if (path == NULL) {
		opkg_perror(ERROR, "Missing directory parameter");
		return -1;
	}

	dir = opendir(path);
	if (dir == NULL) {
		opkg_perror(ERROR, "Failed to open dir %s", path);
		return -1;
	}

	if (fchdir(dirfd(dir)) == -1) {
		opkg_perror(ERROR, "Failed to change to dir %s", path);
		closedir(dir);
		return -1;
	}

	while (1) {
		errno = 0;
		if ((dent = readdir(dir)) == NULL) {
			if (errno) {
				opkg_perror(ERROR, "Failed to read dir %s",
						path);
				ret = -1;
			}
			break;
		}

		if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, ".."))
			continue;

#ifdef _BSD_SOURCE
		if (dent->d_type == DT_DIR) {
			if ((ret = rm_r(dent->d_name)) == -1)
				break;
			continue;
		} else if (dent->d_type == DT_UNKNOWN)
#endif
		{
			struct stat st;
			if ((ret = lstat(dent->d_name, &st)) == -1) {
				opkg_perror(ERROR, "Failed to lstat %s",
						dent->d_name);
				break;
			}
			if (S_ISDIR(st.st_mode)) {
				if ((ret = rm_r(dent->d_name)) == -1)
					break;
				continue;
			}
		}

		if ((ret = unlink(dent->d_name)) == -1) {
			opkg_perror(ERROR, "Failed to unlink %s", dent->d_name);
			break;
		}
	}

	if (chdir("..") == -1) {
		ret = -1;
		opkg_perror(ERROR, "Failed to change to dir %s/..", path);
	}

	if (rmdir(path) == -1 ) {
		ret = -1;
		opkg_perror(ERROR, "Failed to remove dir %s", path);
	}

	if (closedir(dir) == -1) {
		ret = -1;
		opkg_perror(ERROR, "Failed to close dir %s", path);
	}

	return ret;
}
void InitNx()
{
    // Create the physics SDK
	gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, &gErrorStream);
    if (!gPhysicsSDK)  return;

	// Set the physics parameters
	gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.05);

	// Set the debug visualization parameters
	gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1);	
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_AXES, 1);

	gPhysicsSDK->setParameter(NX_VISUALIZE_CONTACT_POINT, 1);
	gPhysicsSDK->setParameter(NX_VISUALIZE_CONTACT_NORMAL, 1);

    // Create the scene
    NxSceneDesc sceneDesc;
    sceneDesc.gravity               = gDefaultGravity;
	sceneDesc.simType				= NX_SIMULATION_HW;
    gScene = gPhysicsSDK->createScene(sceneDesc);	
 if(!gScene){ 
		sceneDesc.simType				= NX_SIMULATION_SW; 
		gScene = gPhysicsSDK->createScene(sceneDesc);  
		if(!gScene) return;
	}

	NxU32 set = 0;

#ifdef WIN32
	set = SetCurrentDirectory(&fname[0]);
	if (!set) set = SetCurrentDirectory(&fname1[0]);
	if (!set)
	{
		char basePath[256];
		GetModuleFileName(NULL, basePath, 256);
		char* pTmp = strrchr(basePath, '\\');
		basePath[pTmp-basePath+1] = 0;
		SetCurrentDirectory(basePath);//for running from start menu

		set = SetCurrentDirectory(&fname2[0]);
	}
	if (!set) set = SetCurrentDirectory(&fname3[0]);
#elif LINUX
	set = chdir(&fname[0]);
	if (set != 0) set = chdir(&fname2[0]);
	if (set != 0) set = chdir(&fname3[0]);
#endif

	// Create the default material
	NxMaterialDesc defaultMaterial;
	defaultMaterial.restitution		= 0;
	defaultMaterial.staticFriction	= 0.5;
	defaultMaterial.dynamicFriction	= 0.5;
	NxMaterial* m = gScene->getMaterialFromIndex(0);
	m->loadFromDesc(defaultMaterial);

	// Load the ramp scene
	char buffer[512];
	FindMediaFile("Ramp.pml", buffer);
	nxmlLoadScene(buffer, gPhysicsSDK, gScene);

	// Switch from Max Coordinate System to
	// Training Program Coordinate System
	NxMat34 mat;
    NxMat33 orient;
	orient.setColumn(0, NxVec3(-1,0,0));
	orient.setColumn(1, NxVec3(0,0,1));
	orient.setColumn(2, NxVec3(0,1,0));
	mat.M = orient;
	SwitchCoordinateSystem(gScene, mat);

	// Reset wheel material
	wsm = NULL;

	// Create board actor
	board = CreateBoard(NxVec3(0,3,0));
	board->wakeUp(1e30);

    AddUserDataToActors(gScene);

	gSelectedActor = board;

	// Initialize HUD
	InitializeHUD();
	InitializeSpecialHUD();

	// Get the current time
	getElapsedTime();

	// Start the first frame of the simulation
	if (gScene)  StartPhysics();
}
Exemple #5
0
int
main(int argc, char *argv[])
{
	char pidstr[16];
	ssize_t ret;
	int c, log_method;
	char *logfile, *pidfile;
	int facility, fd;
	char *username = NULL;
	char *chrootdir = NULL;
	int configtest = 0;
	int singleprocess = 0;
#ifdef HAVE_GETOPT_LONG
	int opt_idx;
#endif

	pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0];

	srand((unsigned int)time(NULL));

	log_method = L_STDERR_SYSLOG;
	logfile = PATH_RADVD_LOG;
	conf_file = PATH_RADVD_CONF;
	facility = LOG_DAEMON;    //brcm
	pidfile = PATH_RADVD_PID;

	/* parse args */
#define OPTIONS_STR "d:C:l:m:p:t:u:vhcs"
#ifdef HAVE_GETOPT_LONG
	while ((c = getopt_long(argc, argv, OPTIONS_STR, prog_opt, &opt_idx)) > 0)
#else
	while ((c = getopt(argc, argv, OPTIONS_STR)) > 0)
#endif
	{
		switch (c) {
		case 'C':
			conf_file = optarg;
			break;
		case 'd':
			set_debuglevel(atoi(optarg));
			break;
		case 'f':
			facility = atoi(optarg);
			break;
		case 'l':
			logfile = optarg;
			break;
		case 'p':
			pidfile = optarg;
			break;
		case 'm':
			if (!strcmp(optarg, "syslog"))
			{
				log_method = L_SYSLOG;
			}
			else if (!strcmp(optarg, "stderr_syslog"))
			{
				log_method = L_STDERR_SYSLOG;
			}
			else if (!strcmp(optarg, "stderr"))
			{
				log_method = L_STDERR;
			}
			else if (!strcmp(optarg, "logfile"))
			{
				log_method = L_LOGFILE;
			}
			else if (!strcmp(optarg, "none"))
			{
				log_method = L_NONE;
			}
			else
			{
				fprintf(stderr, "%s: unknown log method: %s\n", pname, optarg);
				exit(1);
			}
			break;
		case 't':
			chrootdir = strdup(optarg);
			break;
		case 'u':
			username = strdup(optarg);
			break;
		case 'v':
			version();
			break;
		case 'c':
			configtest = 1;
			break;
		case 's':
			singleprocess = 1;
			break;
		case 'h':
			usage();
#ifdef HAVE_GETOPT_LONG
		case ':':
			fprintf(stderr, "%s: option %s: parameter expected\n", pname,
				prog_opt[opt_idx].name);
			exit(1);
#endif
		case '?':
			exit(1);
		}
	}

	if (chrootdir) {
		if (!username) {
			fprintf(stderr, "Chroot as root is not safe, exiting\n");
			exit(1);
		}

		if (chroot(chrootdir) == -1) {
			perror("chroot");
			exit (1);
		}

		if (chdir("/") == -1) {
			perror("chdir");
			exit (1);
		}
		/* username will be switched later */
	}

	if (configtest) {
		log_method = L_STDERR;
	}

	if (log_open(log_method, pname, logfile, facility) < 0) {
		perror("log_open");
		exit(1);
	}

	if (!configtest) {
		flog(LOG_INFO, "version %s started", "1.8");
	}

	/* get a raw socket for sending and receiving ICMPv6 messages */
	sock = open_icmpv6_socket();
	if (sock < 0) {
		perror("open_icmpv6_socket");
		exit(1);
	}

#ifndef BRCM_CMS_BUILD //brcm
	/* check that 'other' cannot write the file
         * for non-root, also that self/own group can't either
         */
	if (check_conffile_perm(username, conf_file) < 0) {
		if (get_debuglevel() == 0) {
			flog(LOG_ERR, "Exiting, permissions on conf_file invalid.\n");
			exit(1);
		}
		else
			flog(LOG_WARNING, "Insecure file permissions, but continuing anyway");
	}

	/* if we know how to do it, check whether forwarding is enabled */
	if (check_ip6_forwarding()) {
		flog(LOG_WARNING, "IPv6 forwarding seems to be disabled, but continuing anyway.");
	}
#endif

	/* parse config file */
	if (readin_config(conf_file) < 0) {
		flog(LOG_ERR, "Exiting, failed to read config file.\n");
		exit(1);
	}

	if (configtest) {
		fprintf(stderr, "Syntax OK\n");
		exit(0);
	}

	/* drop root privileges if requested. */
	if (username) {
		if (!singleprocess) {
		 	dlog(LOG_DEBUG, 3, "Initializing privsep");
		 	if (privsep_init() < 0)
				flog(LOG_WARNING, "Failed to initialize privsep.");
		}

		if (drop_root_privileges(username) < 0) {
			perror("drop_root_privileges");
			exit(1);
		}
	}

	if ((fd = open(pidfile, O_RDONLY, 0)) > 0)
	{
		ret = read(fd, pidstr, sizeof(pidstr) - 1);
		if (ret < 0)
		{
			flog(LOG_ERR, "cannot read radvd pid file, terminating: %s", strerror(errno));
			exit(1);
		}
		pidstr[ret] = '\0';
		if (!kill((pid_t)atol(pidstr), 0))
		{
			flog(LOG_ERR, "radvd already running, terminating.");
			exit(1);
		}
		close(fd);
		fd = open(pidfile, O_CREAT|O_TRUNC|O_WRONLY, 0644);
	}
	else	/* FIXME: not atomic if pidfile is on an NFS mounted volume */
		fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644);

	if (fd < 0)
	{
		flog(LOG_ERR, "cannot create radvd pid file, terminating: %s", strerror(errno));
		exit(1);
	}

	/*
	 * okay, config file is read in, socket and stuff is setup, so
	 * lets fork now...
	 */

#ifndef BRCM_CMS_BUILD //brcm
	if (get_debuglevel() == 0) {

		/* Detach from controlling terminal */
		if (daemon(0, 0) < 0)
			perror("daemon");

		/* close old logfiles, including stderr */
		log_close();

		/* reopen logfiles, but don't log to stderr unless explicitly requested */
		if (log_method == L_STDERR_SYSLOG)
			log_method = L_SYSLOG;
		if (log_open(log_method, pname, logfile, facility) < 0) {
			perror("log_open");
			exit(1);
		}

	}
#endif

	/*
	 *	config signal handlers
	 */
#ifdef BRCM_CMS_BUILD //brcm
	signal(SIGHUP, SIG_IGN);
	signal(SIGTERM, sigterm_handler);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGINT, SIG_IGN);
	signal(SIGUSR1, SIG_IGN);
#else
	signal(SIGHUP, sighup_handler);
	signal(SIGTERM, sigterm_handler);
	signal(SIGINT, sigint_handler);
	signal(SIGUSR1, sigusr1_handler);
#endif

	snprintf(pidstr, sizeof(pidstr), "%ld\n", (long)getpid());

	ret = write(fd, pidstr, strlen(pidstr));
	if (ret != strlen(pidstr))
	{
		flog(LOG_ERR, "cannot write radvd pid file, terminating: %s", strerror(errno));
		exit(1);
	}

	close(fd);

	config_interface();
	kickoff_adverts();
	main_loop();
	stop_adverts();
	unlink(pidfile);

	return 0;
}
int pmix_compress_bzip_decompress_nb(char * cname, char **fname, pid_t *child_pid)
{
    char **argv = NULL;
    char * dir_cname = NULL;
    pid_t loc_pid = 0;
    int status;
    bool is_tar = false;

    if( 0 == strncmp(&(cname[strlen(cname)-8]), ".tar.bz2", strlen(".tar.bz2")) ) {
        is_tar = true;
    }

    *fname = strdup(cname);
    if( is_tar ) {
        (*fname)[strlen(cname)-8] = '\0';
    } else {
        (*fname)[strlen(cname)-4] = '\0';
    }

    pmix_output_verbose(10, mca_compress_bzip_component.super.output_handle,
                        "compress:bzip: decompress_nb(%s -> [%s])",
                        cname, *fname);

    *child_pid = fork();
    if( *child_pid == 0 ) { /* Child */
        dir_cname  = pmix_dirname(cname);

        chdir(dir_cname);

        /* Fork(bunzip) */
        loc_pid = fork();
        if( loc_pid == 0 ) { /* Child */
            char * cmd;
            pmix_asprintf(&cmd, "bunzip2 %s", cname);

            pmix_output_verbose(10, mca_compress_bzip_component.super.output_handle,
                                "compress:bzip: decompress_nb() command [%s]",
                                cmd);

            argv = pmix_argv_split(cmd, ' ');
            status = execvp(argv[0], argv);

            pmix_output(0, "compress:bzip: decompress_nb: Failed to exec child [%s] status = %d\n", cmd, status);
            exit(PMIX_ERROR);
        }
        else if( loc_pid > 0 ) { /* Parent */
            waitpid(loc_pid, &status, 0);
            if( !WIFEXITED(status) ) {
                pmix_output(0, "compress:bzip: decompress_nb: Failed to bunzip the file [%s] status = %d\n", cname, status);
                exit(PMIX_ERROR);
            }
        }
        else {
            exit(PMIX_ERROR);
        }

        /* tar_decompress */
        if( is_tar ) {
            /* Strip off '.bz2' leaving just '.tar' */
            cname[strlen(cname)-4] = '\0';
            pmix_compress_base_tar_extract(&cname);
        }

        /* Once this child is done, then directly exit */
        exit(PMIX_SUCCESS);
    }
    else if( *child_pid > 0 ) {
        ;
    }
    else {
        return PMIX_ERROR;
    }

    return PMIX_SUCCESS;
}
void usrAppInit (void)
{
    int status;
    char srcPath[0xff+1];
    /*
     * Step 1: create ramdisk
     */
    status = addRamDisk(ASP_RAMDISK_SIZE, ASP_RAMDISK_DEVICE);
    if(status == ERROR)
    {
        printf("Unable to create ramdisk [%s] with [%d] blocks. Error [%s]\n", 
               ASP_RAMDISK_DEVICE, ASP_RAMDISK_SIZE, strerror(errno));
        return;
    }
    /*
     * Step 2: nfs mount
     */
    status = nfsMount(ASP_NFS_HOST, ASP_NFS_MOUNT_POINT, ASP_RUNTIME_DIR);
    if(status == ERROR)
    {
        printf("Unable to mount [%s] from nfs server [%s]. Error [%s]\n", 
               ASP_NFS_MOUNT_POINT, ASP_NFS_HOST, strerror(errno));
        return ;
    }
    /*
     * Step 3: copy asp loader to ramdisk and change directory to ramdisk. before spawning ASP loader
     */
    snprintf(srcPath, sizeof(srcPath), "%s/%s", ASP_RUNTIME_DIR, ASP_LOADER_IMAGE);
    if(cp(srcPath, ASP_RAMDISK_DEVICE) == ERROR)
    {
        printf("Unable to copy [%s] to [%s]. Error [%s]\n", 
               srcPath, ASP_RAMDISK_DEVICE, strerror(errno));
        return;
    }
    /*
     * Change directory to ramdisk. 
     */
    printf("Changing directory to %s\n\n", ASP_RAMDISK_DEVICE);
    if(chdir(ASP_RAMDISK_DEVICE) == ERROR)
    {
        printf("Unable to change directory to [%s]. Error [%s]\n\n", 
               ASP_RAMDISK_DEVICE, strerror(errno));
    }
    else
    {
        int rtpId = 0;
        char aspImage[0xff+1];
        const char *args[] = { 
            ASP_LOADER_IMAGE, "-c", "0", "-l", ASP_SLOT_ID, "-n", ASP_NODE_NAME, 
            "-s", ASP_RAMDISK_DEVICE, ASP_RUNTIME_DIR, NULL 
        };
        snprintf(aspImage, sizeof(aspImage), "%s/%s", ASP_RAMDISK_DEVICE, ASP_LOADER_IMAGE);
        printf("Starting ASP...\n\n");
        rtpId = rtpSpawn(aspImage, (const char **)args, NULL, 100, 256<<10, 0, VX_FP_TASK);
        if(rtpId == ERROR)
        {
            printf("Unable to spawn image [%s]. Error [%s]\n", aspImage, strerror(errno));
        }
        else
            printf("rtpSpawn for image [%s] success\n", aspImage);
    }
}
int
ar_open(const char *name)
{
	struct mtget mb;

	if (arfd != -1)
		(void)close(arfd);
	arfd = -1;
	can_unlnk = did_io = io_ok = invld_rec = 0;
	artyp = ISREG;
	flcnt = 0;

	/*
	 * open based on overall operation mode
	 */
	switch (act) {
	case LIST:
	case EXTRACT:
		if (name == NULL) {
			arfd = STDIN_FILENO;
			arcname = stdn;
		} else if ((arfd = open(name, EXT_MODE, DMOD)) < 0)
			syswarn(0, errno, "Failed open to read on %s", name);
		if (arfd != -1 && gzip_program != NULL)
			ar_start_gzip(arfd, gzip_program, 0);
		break;
	case ARCHIVE:
		if (name == NULL) {
			arfd = STDOUT_FILENO;
			arcname = stdo;
		} else if ((arfd = open(name, AR_MODE, DMOD)) < 0)
			syswarn(0, errno, "Failed open to write on %s", name);
		else
			can_unlnk = 1;
		if (arfd != -1 && gzip_program != NULL)
			ar_start_gzip(arfd, gzip_program, 1);
		break;
	case APPND:
		if (name == NULL) {
			arfd = STDOUT_FILENO;
			arcname = stdo;
		} else if ((arfd = open(name, APP_MODE, DMOD)) < 0)
			syswarn(0, errno, "Failed open to read/write on %s",
				name);
		break;
	case COPY:
		/*
		 * arfd not used in COPY mode
		 */
		arcname = none;
		lstrval = 1;
		return(0);
	}
	if (arfd < 0)
		return(-1);

	if (chdname != NULL)
		if (chdir(chdname) != 0) {
			syswarn(1, errno, "Failed chdir to %s", chdname);
			return(-1);
		}
	/*
	 * set up is based on device type
	 */
	if (fstat(arfd, &arsb) < 0) {
		syswarn(0, errno, "Failed stat on %s", arcname);
		(void)close(arfd);
		arfd = -1;
		can_unlnk = 0;
		return(-1);
	}
	if (S_ISDIR(arsb.st_mode)) {
		paxwarn(0, "Cannot write an archive on top of a directory %s",
		    arcname);
		(void)close(arfd);
		arfd = -1;
		can_unlnk = 0;
		return(-1);
	}

	if (S_ISCHR(arsb.st_mode))
		artyp = ioctl(arfd, MTIOCGET, &mb) ? ISCHR : ISTAPE;
	else if (S_ISBLK(arsb.st_mode))
		artyp = ISBLK;
	else if ((lseek(arfd, (off_t)0L, SEEK_CUR) == -1) && (errno == ESPIPE))
		artyp = ISPIPE;
	else
		artyp = ISREG;

	/*
	 * make sure we beyond any doubt that we only can unlink regular files
	 * we created
	 */
	if (artyp != ISREG)
		can_unlnk = 0;
	/*
	 * if we are writing, we are done
	 */
	if (act == ARCHIVE) {
		blksz = rdblksz = wrblksz;
		lstrval = 1;
		return(0);
	}

	/*
	 * set default blksz on read. APPNDs writes rdblksz on the last volume
	 * On all new archive volumes, we shift to wrblksz (if the user
	 * specified one, otherwize we will continue to use rdblksz). We
	 * must to set blocksize based on what kind of device the archive is
	 * stored.
	 */
	switch(artyp) {
	case ISTAPE:
		/*
		 * Tape drives come in at least two flavors. Those that support
		 * variable sized records and those that have fixed sized
		 * records. They must be treated differently. For tape drives
		 * that support variable sized records, we must make large
		 * reads to make sure we get the entire record, otherwise we
		 * will just get the first part of the record (up to size we
		 * asked). Tapes with fixed sized records may or may not return
		 * multiple records in a single read. We really do not care
		 * what the physical record size is UNLESS we are going to
		 * append. (We will need the physical block size to rewrite
		 * the trailer). Only when we are appending do we go to the
		 * effort to figure out the true PHYSICAL record size.
		 */
		blksz = rdblksz = MAXBLK;
		break;
	case ISPIPE:
	case ISBLK:
	case ISCHR:
		/*
		 * Blocksize is not a major issue with these devices (but must
		 * be kept a multiple of 512). If the user specified a write
		 * block size, we use that to read. Under append, we must
		 * always keep blksz == rdblksz. Otherwise we go ahead and use
		 * the device optimal blocksize as (and if) returned by stat
		 * and if it is within pax specs.
		 */
		if ((act == APPND) && wrblksz) {
			blksz = rdblksz = wrblksz;
			break;
		}

#if 0	/* Not on minix */
		if ((arsb.st_blksize > 0) && (arsb.st_blksize < MAXBLK) &&
		    ((arsb.st_blksize % BLKMULT) == 0))
			rdblksz = arsb.st_blksize;
		else
#endif
			rdblksz = DEVBLK;
		/*
		 * For performance go for large reads when we can without harm
		 */
		if ((act == APPND) || (artyp == ISCHR))
			blksz = rdblksz;
		else
			blksz = MAXBLK;
		break;
	case ISREG:
		/*
		 * if the user specified wrblksz works, use it. Under appends
		 * we must always keep blksz == rdblksz
		 */
		if ((act == APPND) && wrblksz && ((arsb.st_size%wrblksz)==0)){
			blksz = rdblksz = wrblksz;
			break;
		}
		/*
		 * See if we can find the blocking factor from the file size
		 */
		for (rdblksz = MAXBLK; rdblksz > 0; rdblksz -= BLKMULT)
			if ((arsb.st_size % rdblksz) == 0)
				break;
		/*
		 * When we cannot find a match, we may have a flawed archive.
		 */
		if (rdblksz <= 0)
			rdblksz = FILEBLK;
		/*
		 * for performance go for large reads when we can
		 */
		if (act == APPND)
			blksz = rdblksz;
		else
			blksz = MAXBLK;
		break;
	default:
		/*
		 * should never happen, worse case, slow...
		 */
		blksz = rdblksz = BLKMULT;
		break;
	}
	lstrval = 1;
	return(0);
}
Exemple #9
0
void trace_listen(int argc, char **argv)
{
	char *logfile = NULL;
	char *port = NULL;
	char *iface;
	int daemon = 0;
	int c;

	if (argc < 2)
		usage(argv);

	if (strcmp(argv[1], "listen") != 0)
		usage(argv);

	for (;;) {
		int option_index = 0;
		static struct option long_options[] = {
			{"port", required_argument, NULL, 'p'},
			{"help", no_argument, NULL, '?'},
			{"debug", no_argument, NULL, OPT_debug},
			{NULL, 0, NULL, 0}
		};

		c = getopt_long (argc-1, argv+1, "+hp:o:d:i:l:D",
			long_options, &option_index);
		if (c == -1)
			break;
		switch (c) {
		case 'h':
			usage(argv);
			break;
		case 'p':
			port = optarg;
			break;
		case 'i':
			iface = optarg;
			break;
		case 'd':
			output_dir = optarg;
			break;
		case 'o':
			output_file = optarg;
			break;
		case 'l':
			logfile = optarg;
			break;
		case 'D':
			daemon = 1;
			break;
		case OPT_debug:
			debug = 1;
			break;
		default:
			usage(argv);
		}
	}

	if (!port)
		usage(argv);

	if ((argc - optind) >= 2)
		usage(argv);

	if (!output_file)
		output_file = default_output_file;

	if (!output_dir)
		output_dir = default_output_dir;

	if (logfile) {
		/* set the writes to a logfile instead */
		logfp = fopen(logfile, "w");
		if (!logfp)
			die("creating log file %s", logfile);
	}

	if (chdir(output_dir) < 0)
		die("Can't access directory %s", output_dir);

	if (daemon)
		start_daemon();

	signal_setup(SIGINT, finish);
	signal_setup(SIGTERM, finish);

	do_listen(port);

	return;
}
Exemple #10
0
static int get_grid_info_and_install(i_mysql_iface* db_conn, const char *grid_name_list)
{
    char   install_path[PATH_MAX] = {'\0'};
    char   file_path[PATH_MAX] = {'\0'};
    char   select_sql[MAX_STR_LEN] = {'\0'};
    char   cmd_str[MAX_STR_LEN] = {'\0'};
    int    len = 0;
    FILE  *fp = NULL;

    strncpy(install_path, g_install_prefix, sizeof(install_path));

    if(strlen(grid_name_list) <= 0) {
        sprintf(select_sql, "SELECT grid_id FROM v_grid_info ORDER BY grid_id DESC");
    }
    else {
        sprintf(select_sql, "SELECT grid_id FROM v_grid_info WHERE grid_id IN(%s)", grid_name_list);
    }

    MYSQL_ROW row = NULL;
    int  ret = db_conn->select_first_row(&row, select_sql);
    if(ret < 0) {
        fprintf(stderr, "%sQuery db error.\nSQL:[%s] db error:[%s].%s\n",
                START_RED_TIP, select_sql, db_conn->get_last_errstr(), END_COLOR_TIP);
        return -1;
    }
    else if(ret == 0) {
        fprintf(stderr, "%sNo record satisfied the conditions.\nSQL:[%s]%s\n",
                START_RED_TIP, select_sql, END_COLOR_TIP);
        return -1;
    }

    int   exist = -1;
    char  ch  = 0;
    while(row != NULL) {
        if(!row[0]) {
            goto next;
        }

        strcat(install_path, "oa-head-");
        strcat(install_path, row[0]);

        if(check_dir(install_path, &exist) != 0) {
            fprintf(stderr, "OA_HEAD for grid %s%s %sinstall failed.%s\n", 
                    START_RED_TIP, row[0], START_YELLOW_TIP, END_COLOR_TIP);
            goto next;
        }

        if(exist) {
            fprintf(stderr, 
                    "The OA_HEAD for grid %s%s %salready exist%s.\n%sDo you want to overwrite it?[Y|N]", 
                    START_RED_TIP, row[0], START_YELLOW_TIP, END_COLOR_TIP, START_GREEN_TIP);
            ch = get_yes_no_input(3);
            if(ch != 'Y' && ch != 'y') {
                goto next;
            }
        }

        chmod(install_path, 0755);
        chown(install_path, g_nobody_uid, g_nobody_gid);

        sprintf(cmd_str, "rm -rf %s/* ;cp -rf ./install-pkg/* %s", install_path, install_path);
        if(system(cmd_str) == -1) {
            fprintf(stderr, "Copy file to [%s] failed.\n", install_path);
            fprintf(stderr, "OA_HEAD for grid %s%s%s install failed.%s\n", 
                    START_RED_TIP, row[0], START_YELLOW_TIP, END_COLOR_TIP);
            goto next;
        }

        sprintf(file_path, "%s/start_oa_head.sh", install_path);
        fp = fopen(file_path, "a");
        if(fp == NULL) {
            fprintf(stderr, "Open file %s failed,sys error:%s.\n", file_path, strerror(errno));
            fprintf(stderr, "OA_HEAD for grid %s%s%s install failed.%s\n", 
                    START_RED_TIP, row[0], START_YELLOW_TIP, END_COLOR_TIP);
            goto next;
        }

        len = sprintf(cmd_str, "./oa_head -h%s -d%s -u%s -p%s -n%s \nexit 0\n", 
                g_db_host, g_db_name, g_db_user, g_db_pass, row[0]);
        if(fwrite(cmd_str, 1, strlen(cmd_str), fp) != strlen(cmd_str)) {
            fprintf(stderr, "Modify file %s failed.\n", file_path);
            fprintf(stderr, "OA_HEAD for grid %s%s%s install failed.%s\n", 
                    START_RED_TIP, row[0], START_YELLOW_TIP, END_COLOR_TIP);
            fclose(fp);
            goto next;
        }
        fclose(fp);

        sprintf(cmd_str, "chown nobody.nogroup -R %s/*", install_path);
        if(system(cmd_str) == -1) {
            fprintf(stderr, "Chown failed.\n");
            fprintf(stderr, "OA_HEAD for grid %s%s%s install failed.%s\n", 
                    START_RED_TIP, row[0], START_YELLOW_TIP, END_COLOR_TIP);
            goto next;
        }

        fprintf(stderr, "OA_HEAD for grid %s%s%s installed success.%s\nDo you want to start it[Y/N]?", 
                START_RED_TIP, row[0], START_YELLOW_TIP, END_COLOR_TIP);
        ch = 0;
        ch = get_yes_no_input(3);
        if(ch != 'Y' && ch != 'y')
            goto next;

        chdir(install_path);
        if(system("./start_oa_head.sh") == -1) {
            fprintf(stderr, "Start failed.\n");
            fprintf(stderr, "OA_HEAD for grid %s%s%s start failed.%s\n", 
                    START_RED_TIP, row[0], START_YELLOW_TIP, END_COLOR_TIP);
        }
        chdir(g_cur_path);
next:
        usleep(900000);
        fprintf(stderr, "\n");
        strncpy(install_path, g_install_prefix, sizeof(install_path));
        row = db_conn->select_next_row(false);
    }
    return 0;
}
Exemple #11
0
pid_t
control(void)
{
	struct sockaddr_un	 sun;
	int			 fd;
	mode_t			 old_umask;
	pid_t			 pid;
	struct passwd		*pw;
	struct event		 ev_sigint;
	struct event		 ev_sigterm;

	switch (pid = fork()) {
	case -1:
		fatal("control: cannot fork");
	case 0:
		break;
	default:
		return (pid);
	}

	purge_config(PURGE_EVERYTHING);

	pw = env->sc_pw;

	if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
		fatal("control: socket");

	bzero(&sun, sizeof(sun));
	sun.sun_family = AF_UNIX;
	if (strlcpy(sun.sun_path, SMTPD_SOCKET,
	    sizeof(sun.sun_path)) >= sizeof(sun.sun_path))
		fatal("control: socket name too long");

	if (connect(fd, (struct sockaddr *)&sun, sizeof(sun)) == 0)
		fatalx("control socket already listening");

	if (unlink(SMTPD_SOCKET) == -1)
		if (errno != ENOENT)
			fatal("control: cannot unlink socket");

	old_umask = umask(S_IXUSR|S_IXGRP|S_IWOTH|S_IROTH|S_IXOTH);
	if (bind(fd, (struct sockaddr *)&sun, sizeof(sun)) == -1) {
		(void)umask(old_umask);
		fatal("control: bind");
	}
	(void)umask(old_umask);

	if (chmod(SMTPD_SOCKET,
		S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) == -1) {
		(void)unlink(SMTPD_SOCKET);
		fatal("control: chmod");
	}

	session_socket_blockmode(fd, BM_NONBLOCK);
	control_state.fd = fd;

	stat_backend = env->sc_stat;
	stat_backend->init();

	if (chroot(PATH_CHROOT) == -1)
		fatal("control: chroot");
	if (chdir("/") == -1)
		fatal("control: chdir(\"/\")");

	config_process(PROC_CONTROL);

	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		fatal("control: cannot drop privileges");

	imsg_callback = control_imsg;
	event_init();

	signal_set(&ev_sigint, SIGINT, control_sig_handler, NULL);
	signal_set(&ev_sigterm, SIGTERM, control_sig_handler, NULL);
	signal_add(&ev_sigint, NULL);
	signal_add(&ev_sigterm, NULL);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGHUP, SIG_IGN);

	tree_init(&ctl_conns);

	bzero(&digest, sizeof digest);
	digest.startup = time(NULL);

	config_peer(PROC_SCHEDULER);
	config_peer(PROC_QUEUE);
	config_peer(PROC_SMTP);
	config_peer(PROC_MFA);
	config_peer(PROC_PARENT);
	config_peer(PROC_LKA);
	config_peer(PROC_MDA);
	config_peer(PROC_MTA);
	config_done();

	control_listen();

	if (event_dispatch() < 0)
		fatal("event_dispatch");
	control_shutdown();

	return (0);
}
Exemple #12
0
int
main(int argc, char *argv[]) 
{
  const char *base_uri = "http://example.org/bpath/cpath/d;p?querystr#frag";
  const char *base_uri_xmlbase = "http://example.org/bpath/cpath/d;p";
  const char *base_uri_retrievable = "http://example.org/bpath/cpath/d;p?querystr";
  const char* dirs[6] = { "/etc", "/bin", "/tmp", "/lib", "/var", NULL };
  unsigned char uri_buffer[16]; /* strlen("file:///DIR/foo")+1 */  
  int i;
  const char *dir;
  unsigned char *str;
  raptor_uri *uri1, *uri2, *uri3;

  int failures=0;
  
  fprintf(stderr, "raptor_uri_resolve_uri_reference: Testing with base URI %s\n", base_uri);
  

  failures += assert_resolve_uri (base_uri, "g:h", "g:h");
  failures += assert_resolve_uri (base_uri, "gpath", "http://example.org/bpath/cpath/gpath");
  failures += assert_resolve_uri (base_uri, "./gpath", "http://example.org/bpath/cpath/gpath");
  failures += assert_resolve_uri (base_uri, "gpath/", "http://example.org/bpath/cpath/gpath/");
  failures += assert_resolve_uri (base_uri, "/gpath", "http://example.org/gpath");
  failures += assert_resolve_uri (base_uri, "//gpath", "http://gpath");
  failures += assert_resolve_uri (base_uri, "?y", "http://example.org/bpath/cpath/?y");
  failures += assert_resolve_uri (base_uri, "gpath?y", "http://example.org/bpath/cpath/gpath?y");
  failures += assert_resolve_uri (base_uri, "#s", "http://example.org/bpath/cpath/d;p?querystr#s");
  failures += assert_resolve_uri (base_uri, "gpath#s", "http://example.org/bpath/cpath/gpath#s");
  failures += assert_resolve_uri (base_uri, "gpath?y#s", "http://example.org/bpath/cpath/gpath?y#s");
  failures += assert_resolve_uri (base_uri, ";x", "http://example.org/bpath/cpath/;x");
  failures += assert_resolve_uri (base_uri, "gpath;x", "http://example.org/bpath/cpath/gpath;x");
  failures += assert_resolve_uri (base_uri, "gpath;x?y#s", "http://example.org/bpath/cpath/gpath;x?y#s");
  failures += assert_resolve_uri (base_uri, ".", "http://example.org/bpath/cpath/");
  failures += assert_resolve_uri (base_uri, "./", "http://example.org/bpath/cpath/");
  failures += assert_resolve_uri (base_uri, "..", "http://example.org/bpath/");
  failures += assert_resolve_uri (base_uri, "../", "http://example.org/bpath/");
  failures += assert_resolve_uri (base_uri, "../gpath", "http://example.org/bpath/gpath");
  failures += assert_resolve_uri (base_uri, "../..", "http://example.org/");
  failures += assert_resolve_uri (base_uri, "../../", "http://example.org/");
  failures += assert_resolve_uri (base_uri, "../../gpath", "http://example.org/gpath");

  failures += assert_resolve_uri (base_uri, "", "http://example.org/bpath/cpath/d;p?querystr");

  failures += assert_resolve_uri (base_uri, "../../../gpath", "http://example.org/../gpath");
  failures += assert_resolve_uri (base_uri, "../../../../gpath", "http://example.org/../../gpath");

  failures += assert_resolve_uri (base_uri, "/./gpath", "http://example.org/./gpath");
  failures += assert_resolve_uri (base_uri, "/../gpath", "http://example.org/../gpath");
  failures += assert_resolve_uri (base_uri, "gpath.", "http://example.org/bpath/cpath/gpath.");
  failures += assert_resolve_uri (base_uri, ".gpath", "http://example.org/bpath/cpath/.gpath");
  failures += assert_resolve_uri (base_uri, "gpath..", "http://example.org/bpath/cpath/gpath..");
  failures += assert_resolve_uri (base_uri, "..gpath", "http://example.org/bpath/cpath/..gpath");

  failures += assert_resolve_uri (base_uri, "./../gpath", "http://example.org/bpath/gpath");
  failures += assert_resolve_uri (base_uri, "./gpath/.", "http://example.org/bpath/cpath/gpath/");
  failures += assert_resolve_uri (base_uri, "gpath/./hpath", "http://example.org/bpath/cpath/gpath/hpath");
  failures += assert_resolve_uri (base_uri, "gpath/../hpath", "http://example.org/bpath/cpath/hpath");
  failures += assert_resolve_uri (base_uri, "gpath;x=1/./y", "http://example.org/bpath/cpath/gpath;x=1/y");
  failures += assert_resolve_uri (base_uri, "gpath;x=1/../y", "http://example.org/bpath/cpath/y");

  failures += assert_resolve_uri (base_uri, "gpath?y/./x", "http://example.org/bpath/cpath/gpath?y/./x");
  failures += assert_resolve_uri (base_uri, "gpath?y/../x", "http://example.org/bpath/cpath/gpath?y/../x");
  failures += assert_resolve_uri (base_uri, "gpath#s/./x", "http://example.org/bpath/cpath/gpath#s/./x");
  failures += assert_resolve_uri (base_uri, "gpath#s/../x", "http://example.org/bpath/cpath/gpath#s/../x");

  failures += assert_resolve_uri (base_uri, "http:gauthority", "http:gauthority");

  failures += assert_resolve_uri (base_uri, "gpath/../../../hpath", "http://example.org/hpath");

  failures += assert_resolve_uri ("http://example.org/dir/file", "../../../absfile", "http://example.org/../../absfile");
  failures += assert_resolve_uri ("http://example.org/dir/file", "http://another.example.org/dir/file", "http://another.example.org/dir/file");


#ifdef WIN32
  failures += assert_filename_to_uri ("c:\\windows\\system", "file://c|/windows/system");
  failures += assert_filename_to_uri ("\\\\server\\share\\file.doc", "file://server/share/file.doc");
  failures += assert_filename_to_uri ("a:foo", "file://a|./foo");


  failures += assert_uri_to_filename ("file://c|/windows/system", "c:\\windows\\system");
  failures += assert_uri_to_filename ("file://c:/windows/system", "c:\\windows\\system");
  failures += assert_uri_to_filename ("file://server/share/file.doc", "\\\\server\\share\\file.doc");
  failures += assert_uri_to_filename ("file://a|./foo", "a:foo");
#else

  failures += assert_filename_to_uri ("/path/to/file", "file:///path/to/file");
  failures += assert_uri_to_filename ("file:///path/to/file", "/path/to/file");

#if defined(HAVE_UNISTD_H) && defined(HAVE_SYS_STAT_H)
  /* Need to test this with a real dir (preferably not /)
   * This is just a test so pretty likely to work on all development systems
   * that are not WIN32
   */

  for(i=0; (dir=dirs[i]); i++) {
    struct stat buf;
    if(!lstat(dir, &buf) && S_ISDIR(buf.st_mode) && !S_ISLNK(buf.st_mode)) {
      if(!chdir(dir))
        break;
    }
  }
  if(!dir)
    fprintf(stderr, "WARNING: %s: Found no convenient directory - not testing relative files\n",
            argv[0]);
  else {
    sprintf((char*)uri_buffer, "file://%s/foo", dir);
    fprintf(stderr, "%s: Checking relative file name 'foo' in dir %s expecting URI %s\n",
            argv[0], dir, uri_buffer);
    failures += assert_filename_to_uri ("foo", (const char*)uri_buffer);
  }
#endif
 
#endif

  raptor_uri_init();
  
  uri1=raptor_new_uri((const unsigned char*)base_uri);

  str=raptor_uri_as_string(uri1);
  if(strcmp((const char*)str, base_uri)) {
    fprintf(stderr, "FAIL raptor_uri_as_string URI %s gave %s != %s\n",
            base_uri, str, base_uri);
    failures++;
  }
  
  uri2=raptor_new_uri_for_xmlbase(uri1);
  str=raptor_uri_as_string(uri2);
  if(strcmp((const char*)str, base_uri_xmlbase)) {
    fprintf(stderr, "FAIL raptor_new_uri_for_xmlbase URI %s gave %s != %s\n",
            base_uri, str, base_uri_xmlbase);
    failures++;
  }
  
  uri3=raptor_new_uri_for_retrieval(uri1);

  str=raptor_uri_as_string(uri3);
  if(strcmp((const char*)str, base_uri_retrievable)) {
    fprintf(stderr, "FAIL raptor_new_uri_for_retrievable URI %s gave %s != %s\n",
            base_uri, str, base_uri_retrievable);
    failures++;
  }
  
  raptor_free_uri(uri3);
  raptor_free_uri(uri2);
  raptor_free_uri(uri1);

  return failures ;
}
static void
ngx_worker_process_init(ngx_cycle_t *cycle, ngx_int_t worker)
{
    sigset_t          set;
    uint64_t          cpu_affinity;
    ngx_int_t         n;
    ngx_uint_t        i;
    struct rlimit     rlmt;
    ngx_core_conf_t  *ccf;
    ngx_listening_t  *ls;

    if (ngx_set_environment(cycle, NULL) == NULL) {
        /* fatal */
        exit(2);
    }

    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    if (worker >= 0 && ccf->priority != 0) {
        if (setpriority(PRIO_PROCESS, 0, ccf->priority) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setpriority(%d) failed", ccf->priority);
        }
    }

    if (ccf->rlimit_nofile != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_nofile;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_nofile;

        if (setrlimit(RLIMIT_NOFILE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_NOFILE, %i) failed",
                          ccf->rlimit_nofile);
        }
    }

    if (ccf->rlimit_core != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_core;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_core;

        if (setrlimit(RLIMIT_CORE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_CORE, %O) failed",
                          ccf->rlimit_core);
        }
    }

#ifdef RLIMIT_SIGPENDING
    if (ccf->rlimit_sigpending != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_sigpending;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_sigpending;

        if (setrlimit(RLIMIT_SIGPENDING, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_SIGPENDING, %i) failed",
                          ccf->rlimit_sigpending);
        }
    }
#endif

    if (geteuid() == 0) {
        if (setgid(ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setgid(%d) failed", ccf->group);
            /* fatal */
            exit(2);
        }

        if (initgroups(ccf->username, ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "initgroups(%s, %d) failed",
                          ccf->username, ccf->group);
        }

        if (setuid(ccf->user) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setuid(%d) failed", ccf->user);
            /* fatal */
            exit(2);
        }
    }

    if (worker >= 0) {
        cpu_affinity = ngx_get_cpu_affinity(worker);

        if (cpu_affinity) {
            ngx_setaffinity(cpu_affinity, cycle->log);
        }
    }

#if (NGX_HAVE_PR_SET_DUMPABLE)

    /* allow coredump after setuid() in Linux 2.4.x */

    if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "prctl(PR_SET_DUMPABLE) failed");
    }

#endif

    if (ccf->working_directory.len) {
        if (chdir((char *) ccf->working_directory.data) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "chdir(\"%s\") failed", ccf->working_directory.data);
            /* fatal */
            exit(2);
        }
    }

    sigemptyset(&set);

    if (sigprocmask(SIG_SETMASK, &set, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "sigprocmask() failed");
    }

    /*
     * disable deleting previous events for the listening sockets because
     * in the worker processes there are no events at all at this point
     */
    ls = cycle->listening.elts;
    for (i = 0; i < cycle->listening.nelts; i++) {
        ls[i].previous = NULL;
    }

    for (i = 0; ngx_modules[i]; i++) {
        if (ngx_modules[i]->init_process) {
            if (ngx_modules[i]->init_process(cycle) == NGX_ERROR) {
                /* fatal */
                exit(2);
            }
        }
    }

    for (n = 0; n < ngx_last_process; n++) {

        if (ngx_processes[n].pid == -1) {
            continue;
        }

        if (n == ngx_process_slot) {
            continue;
        }

        if (ngx_processes[n].channel[1] == -1) {
            continue;
        }

        if (close(ngx_processes[n].channel[1]) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "close() channel failed");
        }
    }

    if (close(ngx_processes[ngx_process_slot].channel[0]) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "close() channel failed");
    }

#if 0
    ngx_last_process = 0;
#endif

    if (ngx_add_channel_event(cycle, ngx_channel, NGX_READ_EVENT,
                              ngx_channel_handler)
        == NGX_ERROR)
    {
        /* fatal */
        exit(2);
    }
}
Exemple #14
0
void network_generator::network_evolution(const char **file){
	
	long double coolant_flow_rate;
	long double unit_pressure_drop = 100.0;
	
	stringstream ss;
	ss << file[channel_layer+2];
	ss >> coolant_flow_rate;
	
	if(!Is_Meaningful()){
		return ;
	}
	while(1){
		print_network();
		long double total_Q = 0;
		vector <int> network_col(101,0);
		vector < vector <int> > single_network(101,network_col);
        vector < vector < vector <int> > > network(channel_layer,single_network);
        vector <int> channel_info_col(101,-1);
        vector < vector <int> > single_channel_info(101,channel_info_col);
		vector < vector < vector <int> > > channel_info(channel_layer,single_channel_info);
		vector <long double> flowrate_col(101,0);
		vector < vector <long double> > single_flow_rate(101,flowrate_col);
		vector < vector < vector <long double> > > flow_rate(channel_layer,single_flow_rate);
		vector < vector < vector <int> > > direction(channel_layer,single_network);
		vector < matrix > matrix_a(channel_layer);
		vector < vector <node> > tempnode(channel_layer);
		vector < vector <edge_info> > edges(channel_layer);
		for (int i = 0; i < channel_layer; i++) {
			network_graph( &liquid_network[i], &tempnode[i], &edges[i]);
			cout << "network_graph done!" << endl;
			matrix_a[i].get_num_channel(&tempnode[i], &edges[i]);
			cout << "get_num_channel done!" << endl;
            matrix_a[i].initial_direction(&tempnode[i], &edges[i]);
            cout << "initial_direction done!" << endl;
            matrix_a[i].write_spice_input(&i, &tempnode[i],unit_pressure_drop);
            cout << "write_spice_input done!" << endl;
            string spice_sim = "hspice spice_";
			spice_sim += i + 48;
			spice_sim += ".txt";
			spice_sim += " > test_";
			spice_sim += i + 48;
			spice_sim += ".txt";
			cout << spice_sim << endl;
			system(spice_sim.c_str());
            matrix_a[i].read_spice_result(&i);
            cout << "read_spice_result done!" << endl;
            matrix_a[i].get_inlet_Q(&tempnode[i]);
		}
		for (int i = 0; i < channel_layer; i++) {
			total_Q += matrix_a[i].inlet_Q;
			//cout << i << " " << "total_Q " << total_Q << "\t" ;
		}
		for (int i = 0; i < channel_layer; i++) {
			cout << "\nchannel_layer " << i << endl;
			matrix_a[i].get_pressure_drop(chip.width, chip.height, chip.length, coolant_flow_rate, unit_pressure_drop, total_Q);
			matrix_a[i].fill_flow_rate(&tempnode[i] ,&edges[i],&flow_rate[i],&channel_info[i]);
			matrix_a[i].fill_direction(&tempnode[i] ,&edges[i],&direction[i]);
			matrix_a[i].write_output(&i,&liquid_network[i], &tempnode[i],&flow_rate[i],&direction[i],&channel_info[i]);
		}
		
		//cout << "file done !" << endl;
		vector < RTree<int, int, 2, float>* > edge_rtree(channel_layer);
		for( int i=0;i<channel_layer;i++ ){
			edge_rtree[i] = new RTree<int, int, 2, float>;
			int minp[2], maxp[2];
			for( int j=0;j<edges[i].size();j++ ){
				minp[0] = min(tempnode[i][edges[i][j].nodes.first].coordinate.first, tempnode[i][edges[i][j].nodes.second].coordinate.first);
				minp[1] = min(tempnode[i][edges[i][j].nodes.first].coordinate.second, tempnode[i][edges[i][j].nodes.second].coordinate.second);
				maxp[0] = max(tempnode[i][edges[i][j].nodes.first].coordinate.first, tempnode[i][edges[i][j].nodes.second].coordinate.first);
				maxp[1] = max(tempnode[i][edges[i][j].nodes.first].coordinate.second, tempnode[i][edges[i][j].nodes.second].coordinate.second);
				if(edges[i][j].HV == 'H'){
					minp[0] += 1;
					maxp[0] -= 1;
					/*cout << tempnode[i][edges[i][j].nodes.first].coordinate.first << " " << tempnode[i][edges[i][j].nodes.second].coordinate.first << endl;
					cout << tempnode[i][edges[i][j].nodes.first].coordinate.second << " " << tempnode[i][edges[i][j].nodes.second].coordinate.second << endl;
					cout << minp[0] << " " << maxp[0] << endl;
					cout << minp[1] << " " << maxp[1] << endl;*/
					//getchar();
				}
				else if(edges[i][j].HV == 'V'){
					minp[1] += 1;
					maxp[1] -= 1;
				}
				if(edges[i][j].HV != 'N'){
					edge_rtree[i]->Insert(minp, maxp, j);
				}
			}
		}
		//cout << "Rtree done !" << endl;
		/*int minp[2], maxp[2];
		minp[0] = 17;
		minp[1] = 0;
		maxp[0] = 17;
		maxp[1] = 4;
		vector <int> edge_list;
		for( int i=0;i<channel_layer;i++ ){
			edge_list.clear();
			edge_rtree[i]->Search(minp, maxp, &edge_list);
			for( int k=0;k<edge_list.size();k++ ){
				cout << tempnode[i][edges[i][edge_list[k]].nodes.first].coordinate.first << " " << tempnode[i][edges[i][edge_list[k]].nodes.first].coordinate.second << endl;
				cout << tempnode[i][edges[i][edge_list[k]].nodes.second].coordinate.first << " " << tempnode[i][edges[i][edge_list[k]].nodes.second].coordinate.second << endl;
			}
			cout << edge_list.size() << endl;
		}
		getchar();*/
		
		chdir("3d-ice/bin/");
		string simulator = "./3D-ICE-Emulator test_case_0";
		simulator += chip.case_num + 48;
		simulator += ".stk";
		for( int i=0;i<channel_layer;i++ ){
			simulator += " ../../network_";
			simulator += i+48;
			simulator += " ../../flowrate_";
			simulator += i+48;
			simulator += " ../../direction_";
			simulator += i+48;
		}
		//cout << simulator << endl;
		system(simulator.c_str());
		//getchar();
		
		chdir("../../");
		ifstream *fin = new ifstream[channel_layer+1];
		vector < vector < vector <double> > > T_map;
		double T_max = 0, T_min = 1<<30;
		pair<int, int> target;
		for( int i=0;i<channel_layer+1;i++ ){
			string file_location = "3d-ice/bin/testcase_0";
			vector < vector <double> > temp_T_map(101, vector <double>(101));
			file_location += chip.case_num+48;
			file_location += "/output_";
			file_location += i+48;
			file_location += ".txt";
			cout << file_location << endl;
			
			fin[i].open(file_location.c_str());
			if(fin[i].eof()){
				cout << "error tmap !" << endl;
				return ;
			}
			else{
				for( int k=0;k<temp_T_map.size();k++ ){
					for( int j=0;j<temp_T_map[k].size();j++ ){
						fin[i] >> temp_T_map[k][j];
						if(T_max < temp_T_map[k][j]){
							T_max = temp_T_map[k][j];
							target.first = j;
							target.second = k;
						}
						if(T_min > temp_T_map[k][j]){
							T_min = temp_T_map[k][j];
						}
					}
				}
			}
			fin[i].close();
			T_map.push_back(temp_T_map);
			print_heat_color_picture(&temp_T_map, i);
		}
		if(T_max - T_min >= chip.T_gredient){
			cout << "T_gredient fail !!!" << endl;
			cout << "T_gredient : " << chip.T_gredient << endl;
			cout << "your gragient : " << T_max - T_min << endl;
		}
		if(T_max > chip.T_max+273){
			cout << "T_max fail !!!" << endl;
			cout << "T_max : " << chip.T_max << endl;
			cout << "your T_max : " << T_max << endl;
		}
		cout << "your T_max : " << T_max << endl;
		pout(target);
		cout << endl;
		cout << "sim over !!!!!!!!!!!!!!!!!!" << endl;
		return;
		
		cout << endl;
		cout << T_max << endl;
		if(optimization_move_channel(target, &edge_rtree, &edges, &tempnode)){
			cout << "good" << endl;
		}
		else{
			cout << "bad" << endl;
		}
		getchar();
	}
	
	
}
Exemple #15
0
void command_change_directory(int fd, char * dir) {
    chdir(dir);
}
Exemple #16
0
int
main(int argc, char **argv)
#endif	/* WIN32 */
{
#ifdef	WIN32
	struct arg_param *p = (struct arg_param *)pv;
	int      		argc;
	char			**argv;
	SERVICE_STATUS          ss;
#endif	/* WIN32 */
	char *name = NULL;
	struct tpp_config conf;
	int rpp_fd;
	char *pc;
	int numthreads;
	char lockfile[MAXPATHLEN + 1];
	char path_log[MAXPATHLEN + 1];
	char svr_home[MAXPATHLEN + 1];
	char *log_file = 0;
	char *host;
	int port;
	char *routers = NULL;
	int c, i, rc;
	extern char *optarg;
	int	are_primary;
	int	num_var_env;
#ifndef WIN32
	struct sigaction act;
	struct sigaction oact;
#endif

#ifndef WIN32
	/*the real deal or just pbs_version and exit*/

	execution_mode(argc, argv);
#endif

	/* As a security measure and to make sure all file descriptors	*/
	/* are available to us,  close all above stderr			*/
#ifdef WIN32
	_fcloseall();
#else
	i = sysconf(_SC_OPEN_MAX);
	while (--i > 2)
		(void)close(i); /* close any file desc left open by parent */
#endif

	/* If we are not run with real and effective uid of 0, forget it */
#ifdef WIN32
	argc = p->argc;
	argv = p->argv;

	ZeroMemory(&ss, sizeof(ss));
	ss.dwCheckPoint = 0;
	ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	ss.dwCurrentState = g_dwCurrentState;
	ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	ss.dwWaitHint = 6000;

	if (g_ssHandle != 0)
		SetServiceStatus(g_ssHandle, &ss);

	if (!isAdminPrivilege(getlogin())) {
		fprintf(stderr, "%s: Must be run by root\n", argv[0]);
		return (2);
	}

#else
	if ((getuid() != 0) || (geteuid() != 0)) {
		fprintf(stderr, "%s: Must be run by root\n", argv[0]);
		return (2);
	}
#endif	/* WIN32 */

	/* set standard umask */
#ifndef WIN32
	umask(022);
#endif

	/* load the pbs conf file */
	if (pbs_loadconf(0) == 0) {
		fprintf(stderr, "%s: Configuration error\n", argv[0]);
		return (1);
	}

	umask(022);

#ifdef	WIN32
	save_env();
#endif
	/* The following is code to reduce security risks                */
	/* start out with standard umask, system resource limit infinite */
	if ((num_var_env = setup_env(pbs_conf.pbs_environment)) == -1) {
#ifdef	WIN32
		g_dwCurrentState = SERVICE_STOPPED;
		ss.dwCurrentState = g_dwCurrentState;
		ss.dwWin32ExitCode = ERROR_INVALID_ENVIRONMENT;
		if (g_ssHandle != 0) SetServiceStatus(g_ssHandle, &ss);
		return (1);
#else
		exit(1);
#endif	/* WIN32 */
	}

#ifndef WIN32
	i = getgid();
	(void)setgroups(1, (gid_t *)&i);	/* secure suppl. groups */
#endif

	/* set pbs_comm's process limits */
	set_limits();

	log_event_mask = &pbs_conf.pbs_comm_log_events;
	tpp_set_logmask(*log_event_mask);

#ifdef WIN32
	winsock_init();
#endif

	routers = pbs_conf.pbs_comm_routers;
	numthreads = pbs_conf.pbs_comm_threads;

	server_host[0] = '\0';
	if (pbs_conf.pbs_comm_name) {
		name = pbs_conf.pbs_comm_name;
		host = tpp_parse_hostname(name, &port);
		if (host)
			snprintf(server_host, sizeof(server_host), "%s", host);
		free(host);
		host = NULL;
	} else if (pbs_conf.pbs_leaf_name) {
		name = pbs_conf.pbs_leaf_name;
		host = tpp_parse_hostname(name, &port);
		if (host)
			snprintf(server_host, sizeof(server_host), "%s", host);
		free(host);
		host = NULL;
	} else {
		if (gethostname(server_host, (sizeof(server_host) - 1)) == -1) {
#ifndef WIN32
			sprintf(log_buffer, "Could not determine my hostname, errno=%d", errno);
#else
			sprintf(log_buffer, "Could not determine my hostname, errno=%d", WSAGetLastError());
#endif
			fprintf(stderr, "%s\n", log_buffer);
			return (1);
		}
		if ((get_fullhostname(server_host, server_host, (sizeof(server_host) - 1)) == -1)) {
			sprintf(log_buffer, "Could not determine my hostname");
			fprintf(stderr, "%s\n", log_buffer);
			return (1);
		}
		name = server_host;
	}
	if (server_host[0] == '\0') {
		sprintf(log_buffer, "Could not determine server host");
		fprintf(stderr, "%s\n", log_buffer);
		return (1);
	}

	while ((c = getopt(argc, argv, "r:t:e:N")) != -1) {
		switch (c) {
			case 'e': *log_event_mask = strtol(optarg, NULL, 0);
				break;
			case 'r':
				routers = optarg;
				break;
			case 't':
				numthreads = atol(optarg);
				if (numthreads == -1) {
					usage(argv[0]);
					return (1);
				}
				break;
			case 'N':
				stalone = 1;
				break;
			default:
				usage(argv[0]);
				return (1);
		}
	}

	(void)strcpy(daemonname, "Comm@");
	(void)strcat(daemonname, name);
	if ((pc = strchr(daemonname, (int)'.')) != NULL)
		*pc = '\0';

	if(set_msgdaemonname(daemonname)) {
		fprintf(stderr, "Out of memory\n");
		return 1;
	}



	(void) snprintf(path_log, sizeof(path_log), "%s/%s", pbs_conf.pbs_home_path, PBS_COMM_LOGDIR);
	(void) log_open(log_file, path_log);

	/* set tcp function pointers */
	set_tpp_funcs(log_tppmsg);

	(void) snprintf(svr_home, sizeof(svr_home), "%s/%s", pbs_conf.pbs_home_path, PBS_SVR_PRIVATE);
	if (chdir(svr_home) != 0) {
		(void) sprintf(log_buffer, msg_init_chdir, svr_home);
		log_err(-1, __func__, log_buffer);
		return (1);
	}

	(void) sprintf(lockfile, "%s/%s/comm.lock", pbs_conf.pbs_home_path, PBS_SVR_PRIVATE);
	if ((are_primary = are_we_primary()) == FAILOVER_SECONDARY) {
		strcat(lockfile, ".secondary");
	} else if (are_primary == FAILOVER_CONFIG_ERROR) {
		sprintf(log_buffer, "Failover configuration error");
		log_err(-1, __func__, log_buffer);
#ifdef WIN32
		g_dwCurrentState = SERVICE_STOPPED;
		ss.dwCurrentState = g_dwCurrentState;
		ss.dwWin32ExitCode = ERROR_SERVICE_NOT_ACTIVE;
		if (g_ssHandle != 0) SetServiceStatus(g_ssHandle, &ss);
#endif
		return (3);
	}

	if ((lockfds = open(lockfile, O_CREAT | O_WRONLY, 0600)) < 0) {
		(void) sprintf(log_buffer, "pbs_comm: unable to open lock file");
		log_err(errno, __func__, log_buffer);
		return (1);
	}

	if ((host = tpp_parse_hostname(name, &port)) == NULL) {
		sprintf(log_buffer, "Out of memory parsing leaf name");
		log_err(errno, __func__, log_buffer);
		return (1);
	}

	rc = 0;
	if (pbs_conf.auth_method == AUTH_RESV_PORT) {
		rc = set_tpp_config(&pbs_conf, &conf, host, port, routers, pbs_conf.pbs_use_compression,
				TPP_AUTH_RESV_PORT, NULL, NULL);
	} else {
		/* for all non-resv-port based authentication use a callback from TPP */
		rc = set_tpp_config(&pbs_conf, &conf, host, port, routers, pbs_conf.pbs_use_compression,
				TPP_AUTH_EXTERNAL, get_ext_auth_data, validate_ext_auth_data);
	}
	if (rc == -1) {
		(void) sprintf(log_buffer, "Error setting TPP config");
		log_err(-1, __func__, log_buffer);
		return (1);
	}
	free(host);

	i = 0;
	if (conf.routers) {
		while (conf.routers[i]) {
			sprintf(log_buffer, "Router[%d]:%s", i, conf.routers[i]);
			fprintf(stdout, "%s\n", log_buffer);		
			log_event(PBSEVENT_SYSTEM | PBSEVENT_FORCE, PBS_EVENTCLASS_SERVER, LOG_INFO, msg_daemonname, log_buffer);
			i++;
		}
	}

#ifndef DEBUG
#ifndef WIN32
	if (stalone != 1)
		go_to_background();
#endif
#endif


#ifdef WIN32
	ss.dwCheckPoint = 0;
	g_dwCurrentState = SERVICE_RUNNING;
	ss.dwCurrentState = g_dwCurrentState;
	if (g_ssHandle != 0) SetServiceStatus(g_ssHandle, &ss);
#endif

	if (already_forked == 0)
		lock_out(lockfds, F_WRLCK);

	/* go_to_backgroud call creates a forked process,
	 * thus print/log pid only after go_to_background()
	 * has been called
	 */
	sprintf(log_buffer, "%s ready (pid=%d), Proxy Name:%s, Threads:%d", argv[0], getpid(), conf.node_name, numthreads);
	fprintf(stdout, "%s\n", log_buffer);
	log_event(PBSEVENT_SYSTEM | PBSEVENT_FORCE, PBS_EVENTCLASS_SERVER, LOG_INFO, msg_daemonname, log_buffer);

#ifndef DEBUG
	pbs_close_stdfiles();
#endif

#ifdef WIN32
	signal(SIGINT, stop_me);
	signal(SIGTERM, stop_me);
#else
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	act.sa_handler = hup_me;
	if (sigaction(SIGHUP, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for HUP");
		return (2);
	}
	act.sa_handler = stop_me;
	if (sigaction(SIGINT, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for INT");
		return (2);
	}
	if (sigaction(SIGTERM, &act, &oact) != 0) {
		log_err(errno, __func__, "sigactin for TERM");
		return (2);
	}
	if (sigaction(SIGQUIT, &act, &oact) != 0) {
		log_err(errno, __func__, "sigactin for QUIT");
		return (2);
	}
#ifdef SIGSHUTDN
	if (sigaction(SIGSHUTDN, &act, &oact) != 0) {
		log_err(errno, __func__, "sigactin for SHUTDN");
		return (2);
	}
#endif	/* SIGSHUTDN */

	act.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for PIPE");
		return (2);
	}
	if (sigaction(SIGUSR1, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for USR1");
		return (2);
	}
	if (sigaction(SIGUSR2, &act, &oact) != 0) {
		log_err(errno, __func__, "sigaction for USR2");
		return (2);
	}
#endif 	/* WIN32 */

	conf.node_type = TPP_ROUTER_NODE;
	conf.numthreads = numthreads;

	if ((rpp_fd = tpp_init_router(&conf)) == -1) {
		log_err(-1, __func__, "tpp init failed\n");
		return 1;
	}

	/* Protect from being killed by kernel */
	daemon_protect(0, PBS_DAEMON_PROTECT_ON);

	/* go in a while loop */
	while (get_out == 0) {

		if (hupped == 1) {
			struct pbs_config pbs_conf_bak;
			int new_logevent;

			hupped = 0; /* reset back */
			memcpy(&pbs_conf_bak, &pbs_conf, sizeof(struct pbs_config));

			if (pbs_loadconf(1) == 0) {
				log_tppmsg(LOG_CRIT, NULL, "Configuration error, ignoring");
				memcpy(&pbs_conf, &pbs_conf_bak, sizeof(struct pbs_config));
			} else {
				/* restore old pbs.conf */
				new_logevent = pbs_conf.pbs_comm_log_events;
				memcpy(&pbs_conf, &pbs_conf_bak, sizeof(struct pbs_config));
				pbs_conf.pbs_comm_log_events = new_logevent;
				log_tppmsg(LOG_INFO, NULL, "Processed SIGHUP");

				log_event_mask = &pbs_conf.pbs_comm_log_events;
				tpp_set_logmask(*log_event_mask);
			}
		}

		sleep(3);
	}

	tpp_router_shutdown();

	log_event(PBSEVENT_SYSTEM | PBSEVENT_FORCE, PBS_EVENTCLASS_SERVER, LOG_NOTICE, msg_daemonname, "Exiting");
	log_close(1);

	lock_out(lockfds, F_UNLCK);	/* unlock  */
	(void)close(lockfds);
	(void)unlink(lockfile);

	return 0;
}
Exemple #17
0
int main(int argc, char *argv[]) {
    pa_core *c = NULL;
    pa_strbuf *buf = NULL;
    pa_daemon_conf *conf = NULL;
    pa_mainloop *mainloop = NULL;
    char *s;
    int r = 0, retval = 1, d = 0;
    pa_bool_t valid_pid_file = FALSE;
    pa_bool_t ltdl_init = FALSE;
    int passed_fd = -1;
    const char *e;
#ifdef HAVE_FORK
    int daemon_pipe[2] = { -1, -1 };
#endif
#ifdef OS_IS_WIN32
    pa_time_event *win32_timer;
    struct timeval win32_tv;
#endif
    int autospawn_fd = -1;
    pa_bool_t autospawn_locked = FALSE;
#ifdef HAVE_DBUS
    pa_dbus_connection *dbus = NULL;
#endif

    pa_log_set_ident("pulseaudio");
    pa_log_set_level(PA_LOG_NOTICE);
    pa_log_set_flags(PA_LOG_COLORS|PA_LOG_PRINT_FILE|PA_LOG_PRINT_LEVEL, PA_LOG_RESET);

#if defined(__linux__) && defined(__OPTIMIZE__)
    /*
       Disable lazy relocations to make usage of external libraries
       more deterministic for our RT threads. We abuse __OPTIMIZE__ as
       a check whether we are a debug build or not. This all is
       admittedly a bit snake-oilish.
    */

    if (!getenv("LD_BIND_NOW")) {
        char *rp;
        char *canonical_rp;

        /* We have to execute ourselves, because the libc caches the
         * value of $LD_BIND_NOW on initialization. */

        pa_set_env("LD_BIND_NOW", "1");

        if ((canonical_rp = pa_realpath(PA_BINARY))) {

            if ((rp = pa_readlink("/proc/self/exe"))) {

                if (pa_streq(rp, canonical_rp))
                    pa_assert_se(execv(rp, argv) == 0);
                else
                    pa_log_warn("/proc/self/exe does not point to %s, cannot self execute. Are you playing games?", canonical_rp);

                pa_xfree(rp);

            } else
                pa_log_warn("Couldn't read /proc/self/exe, cannot self execute. Running in a chroot()?");

            pa_xfree(canonical_rp);

        } else
            pa_log_warn("Couldn't canonicalize binary path, cannot self execute.");
    }
#endif

    if ((e = getenv("PULSE_PASSED_FD"))) {
        passed_fd = atoi(e);

        if (passed_fd <= 2)
            passed_fd = -1;
    }

    /* We might be autospawned, in which case have no idea in which
     * context we have been started. Let's cleanup our execution
     * context as good as possible */

    pa_reset_personality();
    pa_drop_root();
    pa_close_all(passed_fd, -1);
    pa_reset_sigs(-1);
    pa_unblock_sigs(-1);
    pa_reset_priority();

    setlocale(LC_ALL, "");
    pa_init_i18n();

    conf = pa_daemon_conf_new();

    if (pa_daemon_conf_load(conf, NULL) < 0)
        goto finish;

    if (pa_daemon_conf_env(conf) < 0)
        goto finish;

    if (pa_cmdline_parse(conf, argc, argv, &d) < 0) {
        pa_log(_("Failed to parse command line."));
        goto finish;
    }

    pa_log_set_level(conf->log_level);
    pa_log_set_target(conf->auto_log_target ? PA_LOG_STDERR : conf->log_target);
    if (conf->log_meta)
        pa_log_set_flags(PA_LOG_PRINT_META, PA_LOG_SET);
    if (conf->log_time)
        pa_log_set_flags(PA_LOG_PRINT_TIME, PA_LOG_SET);
    pa_log_set_show_backtrace(conf->log_backtrace);

    LTDL_SET_PRELOADED_SYMBOLS();
    pa_ltdl_init();
    ltdl_init = TRUE;

    if (conf->dl_search_path)
        lt_dlsetsearchpath(conf->dl_search_path);

#ifdef OS_IS_WIN32
    {
        WSADATA data;
        WSAStartup(MAKEWORD(2, 0), &data);
    }
#endif

    pa_random_seed();

    switch (conf->cmd) {
        case PA_CMD_DUMP_MODULES:
            pa_dump_modules(conf, argc-d, argv+d);
            retval = 0;
            goto finish;

        case PA_CMD_DUMP_CONF: {

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            s = pa_daemon_conf_dump(conf);
            fputs(s, stdout);
            pa_xfree(s);
            retval = 0;
            goto finish;
        }

        case PA_CMD_DUMP_RESAMPLE_METHODS: {
            int i;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            for (i = 0; i < PA_RESAMPLER_MAX; i++)
                if (pa_resample_method_supported(i))
                    printf("%s\n", pa_resample_method_to_string(i));

            retval = 0;
            goto finish;
        }

        case PA_CMD_HELP :
            pa_cmdline_help(argv[0]);
            retval = 0;
            goto finish;

        case PA_CMD_VERSION :

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            printf(PACKAGE_NAME" "PACKAGE_VERSION"\n");
            retval = 0;
            goto finish;

        case PA_CMD_CHECK: {
            pid_t pid;

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_check_running(&pid, "pulseaudio") < 0)
                pa_log_info(_("Daemon not running"));
            else {
                pa_log_info(_("Daemon running as PID %u"), pid);
                retval = 0;
            }

            goto finish;

        }
        case PA_CMD_KILL:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_pid_file_kill(SIGINT, NULL, "pulseaudio") < 0)
                pa_log(_("Failed to kill daemon: %s"), pa_cstrerror(errno));
            else
                retval = 0;

            goto finish;

        case PA_CMD_CLEANUP_SHM:

            if (d < argc) {
                pa_log("Too many arguments.\n");
                goto finish;
            }

            if (pa_shm_cleanup() >= 0)
                retval = 0;

            goto finish;

        default:
            pa_assert(conf->cmd == PA_CMD_DAEMON || conf->cmd == PA_CMD_START);
    }

    if (d < argc) {
        pa_log("Too many arguments.\n");
        goto finish;
    }

    if (getuid() == 0 && !conf->system_instance)
        pa_log_warn(_("This program is not intended to be run as root (unless --system is specified)."));
    else if (getuid() != 0 && conf->system_instance) {
        pa_log(_("Root privileges required."));
        goto finish;
    }

    if (conf->cmd == PA_CMD_START && conf->system_instance) {
        pa_log(_("--start not supported for system instances."));
        goto finish;
    }

    if (conf->system_instance && !conf->disallow_exit)
        pa_log_warn(_("Running in system mode, but --disallow-exit not set!"));

    if (conf->system_instance && !conf->disallow_module_loading)
        pa_log_warn(_("Running in system mode, but --disallow-module-loading not set!"));

    if (conf->system_instance && !conf->disable_shm) {
        pa_log_notice(_("Running in system mode, forcibly disabling SHM mode!"));
        conf->disable_shm = TRUE;
    }

    if (conf->system_instance && conf->exit_idle_time >= 0) {
        pa_log_notice(_("Running in system mode, forcibly disabling exit idle time!"));
        conf->exit_idle_time = -1;
    }

    if (conf->cmd == PA_CMD_START) {
        /* If we shall start PA only when it is not running yet, we
         * first take the autospawn lock to make things
         * synchronous. */

        if ((autospawn_fd = pa_autospawn_lock_init()) < 0) {
            pa_log("Failed to initialize autospawn lock");
            goto finish;
        }

        if ((pa_autospawn_lock_acquire(TRUE) < 0)) {
            pa_log("Failed to acquire autospawn lock");
            goto finish;
        }

        autospawn_locked = TRUE;
    }

    if (conf->daemonize) {
        pid_t child;
        int tty_fd;

        if (pa_stdio_acquire() < 0) {
            pa_log(_("Failed to acquire stdio."));
            goto finish;
        }

#ifdef HAVE_FORK
        if (pipe(daemon_pipe) < 0) {
            pa_log(_("pipe failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if ((child = fork()) < 0) {
            pa_log(_("fork() failed: %s"), pa_cstrerror(errno));
            goto finish;
        }

        if (child != 0) {
            ssize_t n;
            /* Father */

            pa_assert_se(pa_close(daemon_pipe[1]) == 0);
            daemon_pipe[1] = -1;

            if ((n = pa_loop_read(daemon_pipe[0], &retval, sizeof(retval), NULL)) != sizeof(retval)) {

                if (n < 0)
                    pa_log(_("read() failed: %s"), pa_cstrerror(errno));

                retval = 1;
            }

            if (retval)
                pa_log(_("Daemon startup failed."));
            else
                pa_log_info(_("Daemon startup successful."));

            goto finish;
        }

        if (autospawn_fd >= 0) {
            /* The lock file is unlocked from the parent, so we need
             * to close it in the child */

            pa_autospawn_lock_release();
            pa_autospawn_lock_done(TRUE);

            autospawn_locked = FALSE;
            autospawn_fd = -1;
        }

        pa_assert_se(pa_close(daemon_pipe[0]) == 0);
        daemon_pipe[0] = -1;
#endif

        if (conf->auto_log_target)
            pa_log_set_target(PA_LOG_SYSLOG);

#ifdef HAVE_SETSID
        setsid();
#endif
#ifdef HAVE_SETPGID
        setpgid(0,0);
#endif

#ifndef OS_IS_WIN32
        pa_close(0);
        pa_close(1);
        pa_close(2);

        pa_assert_se(open("/dev/null", O_RDONLY) == 0);
        pa_assert_se(open("/dev/null", O_WRONLY) == 1);
        pa_assert_se(open("/dev/null", O_WRONLY) == 2);
#else
        FreeConsole();
#endif

#ifdef SIGTTOU
        signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTTIN
        signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTSTP
        signal(SIGTSTP, SIG_IGN);
#endif

#ifdef TIOCNOTTY
        if ((tty_fd = open("/dev/tty", O_RDWR)) >= 0) {
            ioctl(tty_fd, TIOCNOTTY, (char*) 0);
            pa_assert_se(pa_close(tty_fd) == 0);
        }
#endif
    }

    pa_set_env_and_record("PULSE_INTERNAL", "1");
    pa_assert_se(chdir("/") == 0);
    umask(0022);

#ifdef HAVE_SYS_RESOURCE_H
    set_all_rlimits(conf);
#endif
    pa_rtclock_hrtimer_enable();

    pa_raise_priority(conf->nice_level);

    if (conf->system_instance)
        if (change_user() < 0)
            goto finish;

    pa_set_env_and_record("PULSE_SYSTEM", conf->system_instance ? "1" : "0");

    pa_log_info(_("This is PulseAudio %s"), PACKAGE_VERSION);
    pa_log_debug(_("Compilation host: %s"), CANONICAL_HOST);
    pa_log_debug(_("Compilation CFLAGS: %s"), PA_CFLAGS);

    s = pa_uname_string();
    pa_log_debug(_("Running on host: %s"), s);
    pa_xfree(s);

    pa_log_debug(_("Found %u CPUs."), pa_ncpus());

    pa_log_info(_("Page size is %lu bytes"), (unsigned long) PA_PAGE_SIZE);

#ifdef HAVE_VALGRIND_MEMCHECK_H
    pa_log_debug(_("Compiled with Valgrind support: yes"));
#else
    pa_log_debug(_("Compiled with Valgrind support: no"));
#endif

    pa_log_debug(_("Running in valgrind mode: %s"), pa_yes_no(pa_in_valgrind()));

    pa_log_debug(_("Running in VM: %s"), pa_yes_no(pa_running_in_vm()));

#ifdef __OPTIMIZE__
    pa_log_debug(_("Optimized build: yes"));
#else
    pa_log_debug(_("Optimized build: no"));
#endif

#ifdef NDEBUG
    pa_log_debug(_("NDEBUG defined, all asserts disabled."));
#elif defined(FASTPATH)
    pa_log_debug(_("FASTPATH defined, only fast path asserts disabled."));
#else
    pa_log_debug(_("All asserts enabled."));
#endif

    if (!(s = pa_machine_id())) {
        pa_log(_("Failed to get machine ID"));
        goto finish;
    }
    pa_log_info(_("Machine ID is %s."), s);
    pa_xfree(s);

    if ((s = pa_session_id())) {
        pa_log_info(_("Session ID is %s."), s);
        pa_xfree(s);
    }

    if (!(s = pa_get_runtime_dir()))
        goto finish;
    pa_log_info(_("Using runtime directory %s."), s);
    pa_xfree(s);

    if (!(s = pa_get_state_dir()))
        goto finish;
    pa_log_info(_("Using state directory %s."), s);
    pa_xfree(s);

    pa_log_info(_("Using modules directory %s."), conf->dl_search_path);

    pa_log_info(_("Running in system mode: %s"), pa_yes_no(pa_in_system_mode()));

    if (pa_in_system_mode())
        pa_log_warn(_("OK, so you are running PA in system mode. Please note that you most likely shouldn't be doing that.\n"
                      "If you do it nonetheless then it's your own fault if things don't work as expected.\n"
                      "Please read http://pulseaudio.org/wiki/WhatIsWrongWithSystemMode for an explanation why system mode is usually a bad idea."));

    if (conf->use_pid_file) {
        int z;

        if ((z = pa_pid_file_create("pulseaudio")) != 0) {

            if (conf->cmd == PA_CMD_START && z > 0) {
                /* If we are already running and with are run in
                 * --start mode, then let's return this as success. */

                retval = 0;
                goto finish;
            }

            pa_log(_("pa_pid_file_create() failed."));
            goto finish;
        }

        valid_pid_file = TRUE;
    }

    pa_disable_sigpipe();

    if (pa_rtclock_hrtimer())
        pa_log_info(_("Fresh high-resolution timers available! Bon appetit!"));
    else
        pa_log_info(_("Dude, your kernel stinks! The chef's recommendation today is Linux with high-resolution timers enabled!"));

    if (conf->lock_memory) {
#ifdef HAVE_SYS_MMAN_H
        if (mlockall(MCL_FUTURE) < 0)
            pa_log_warn("mlockall() failed: %s", pa_cstrerror(errno));
        else
            pa_log_info("Sucessfully locked process into memory.");
#else
        pa_log_warn("Memory locking requested but not supported on platform.");
#endif
    }

    pa_memtrap_install();

    if (!getenv("PULSE_NO_SIMD")) {
        pa_cpu_init_x86();
        pa_cpu_init_arm();
    }

    pa_assert_se(mainloop = pa_mainloop_new());

    if (!(c = pa_core_new(pa_mainloop_get_api(mainloop), !conf->disable_shm, conf->shm_size))) {
        pa_log(_("pa_core_new() failed."));
        goto finish;
    }

    c->default_sample_spec = conf->default_sample_spec;
    c->default_channel_map = conf->default_channel_map;
    c->default_n_fragments = conf->default_n_fragments;
    c->default_fragment_size_msec = conf->default_fragment_size_msec;
    c->exit_idle_time = conf->exit_idle_time;
    c->scache_idle_time = conf->scache_idle_time;
    c->resample_method = conf->resample_method;
    c->realtime_priority = conf->realtime_priority;
    c->realtime_scheduling = !!conf->realtime_scheduling;
    c->disable_remixing = !!conf->disable_remixing;
    c->disable_lfe_remixing = !!conf->disable_lfe_remixing;
    c->running_as_daemon = !!conf->daemonize;
    c->disallow_exit = conf->disallow_exit;
    c->flat_volumes = conf->flat_volumes;

    pa_assert_se(pa_signal_init(pa_mainloop_get_api(mainloop)) == 0);
    pa_signal_new(SIGINT, signal_callback, c);
    pa_signal_new(SIGTERM, signal_callback, c);
#ifdef SIGUSR1
    pa_signal_new(SIGUSR1, signal_callback, c);
#endif
#ifdef SIGUSR2
    pa_signal_new(SIGUSR2, signal_callback, c);
#endif
#ifdef SIGHUP
    pa_signal_new(SIGHUP, signal_callback, c);
#endif

#ifdef OS_IS_WIN32
    win32_timer = pa_mainloop_get_api(mainloop)->rtclock_time_new(pa_mainloop_get_api(mainloop), pa_gettimeofday(&win32_tv), message_cb, NULL);
#endif

    if (!conf->no_cpu_limit)
        pa_assert_se(pa_cpu_limit_init(pa_mainloop_get_api(mainloop)) == 0);

    buf = pa_strbuf_new();
    if (conf->load_default_script_file) {
        FILE *f;

        if ((f = pa_daemon_conf_open_default_script_file(conf))) {
            r = pa_cli_command_execute_file_stream(c, f, buf, &conf->fail);
            fclose(f);
        }
    }

    if (r >= 0)
        r = pa_cli_command_execute(c, conf->script_commands, buf, &conf->fail);

    pa_log_error("%s", s = pa_strbuf_tostring_free(buf));
    pa_xfree(s);

    /* We completed the initial module loading, so let's disable it
     * from now on, if requested */
    c->disallow_module_loading = !!conf->disallow_module_loading;

    if (r < 0 && conf->fail) {
        pa_log(_("Failed to initialize daemon."));
        goto finish;
    }

    if (!c->modules || pa_idxset_size(c->modules) == 0) {
        pa_log(_("Daemon startup without any loaded modules, refusing to work."));
        goto finish;
    }

#ifdef HAVE_FORK
    if (daemon_pipe[1] >= 0) {
        int ok = 0;
        pa_loop_write(daemon_pipe[1], &ok, sizeof(ok), NULL);
        pa_close(daemon_pipe[1]);
        daemon_pipe[1] = -1;
    }
#endif

#ifdef HAVE_DBUS
    dbus = register_dbus(c);
#endif

    pa_log_info(_("Daemon startup complete."));

    retval = 0;
    if (pa_mainloop_run(mainloop, &retval) < 0)
        goto finish;

    pa_log_info(_("Daemon shutdown initiated."));

finish:
#ifdef HAVE_DBUS
    if (dbus)
        pa_dbus_connection_unref(dbus);
#endif

    if (autospawn_fd >= 0) {
        if (autospawn_locked)
            pa_autospawn_lock_release();

        pa_autospawn_lock_done(FALSE);
    }

#ifdef OS_IS_WIN32
    if (win32_timer)
        pa_mainloop_get_api(mainloop)->time_free(win32_timer);
#endif

    if (c) {
        pa_core_unref(c);
        pa_log_info(_("Daemon terminated."));
    }

    if (!conf->no_cpu_limit)
        pa_cpu_limit_done();

    pa_signal_done();

#ifdef HAVE_FORK
    if (daemon_pipe[1] >= 0)
        pa_loop_write(daemon_pipe[1], &retval, sizeof(retval), NULL);

    pa_close_pipe(daemon_pipe);
#endif

    if (mainloop)
        pa_mainloop_free(mainloop);

    if (conf)
        pa_daemon_conf_free(conf);

    if (valid_pid_file)
        pa_pid_file_remove();

    /* This has no real purpose except making things valgrind-clean */
    pa_unset_env_recorded();

#ifdef OS_IS_WIN32
    WSACleanup();
#endif

    if (ltdl_init)
        pa_ltdl_done();

#ifdef HAVE_DBUS
    dbus_shutdown();
#endif

    return retval;
}
Exemple #18
0
int comando_mudadir(char * nome_dir) {
	return chdir(nome_dir);
}
Exemple #19
0
static int convert_normal(const char *boardname)
{
	char buff[256];
	int fd;
	struct fileheader *fh;
	struct fileheader *fhptr;
	struct stat fs;
	int records;
	int i, j, k, rn;
	Node * ptr;

	snprintf(buff, sizeof(buff), "%s/boards/%s", BBS_HOME, boardname);
	chdir(buff);
	///////////// Convert .DIR file ///////////// 

	if ((fd = open(".DIR", O_RDWR)) == -1)
	{
		perror("open .DIR");
		return -1;
	}

	printf("Converting .DIR file ...");
	fflush(stdout);

	fstat(fd, &fs);
	records = fs.st_size / sizeof(struct fileheader);
	fh = mmap(NULL, fs.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (fh == MAP_FAILED)
	{
		perror("mmap");
		close(fd);
		return -1;
	}
	k = 0;
	// read every record in sequence
	for (i = 0; i < records; i++)
	{
		fhptr = fh + i;
        rn = 0 + (int) (52.0 * rand() / (RAND_MAX + 1.0));
		if (!(fhptr->filename[0] != '\0' && fhptr->filename[1] == '.'))
			continue;
		if (fhptr->accessed[0] & FILE_DIGEST)
		{
			ptr = (Node *)malloc(sizeof(Node));
			if (ptr == NULL)
			{
				perror("malloc");
				destroy_list();
				printf(" Failed.\n");
				close(fd);
				munmap(fh, fs.st_size);
				return -2;
			}
			strncpy(ptr->filename, fhptr->filename, sizeof(ptr->filename));
			ptr->directory = alphabet[rn];
			ptr->next = NULL;
			insert_node(ptr);
		}

		fhptr->posttime = atoi(fhptr->filename + 2);
        snprintf(buff, sizeof(buff), "%c/%s", alphabet[rn], fhptr->filename);
        rename(fhptr->filename, buff);
        strncpy(fhptr->filename, buff, sizeof(fhptr->filename));
		k++;
	}
	close(fd);
	munmap(fh, fs.st_size);
	printf(" Done.\n");
	
	///////////// Convert .DIGEST file ///////////// 
	if ((fd = open(".DIGEST", O_RDWR)) == -1)
	{
		printf("No .DIGEST file.\n");
		return 1;
	}

	printf("Converting .DIGEST file ...");
	fflush(stdout);

	fstat(fd, &fs);
	records = fs.st_size / sizeof(struct fileheader);
	fh = mmap(NULL, fs.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
	if (fh == MAP_FAILED)
	{
		perror("mmap");
		close(fd);
		return -1;
	}
	for (i = 0; i < records; i++)
	{
		fhptr = fh + i;
		if (!(fhptr->filename[0] != '\0' && fhptr->filename[1] == '.'))
			continue;
		if ((ptr = search(fhptr->filename)) == NULL)
		{
        	rn = 0 + (int) (52.0 * rand() / (RAND_MAX + 1.0));
        	snprintf(buff, sizeof(buff), "%c/%s", alphabet[rn], fhptr->filename);
		}
		else
			snprintf(buff, sizeof(buff), "%c/%s", ptr->directory, fhptr->filename);

		fhptr->posttime = atoi(fhptr->filename + 2);
        rename(fhptr->filename, buff);
        strncpy(fhptr->filename, buff, sizeof(fhptr->filename));
	}
	close(fd);
	munmap(fh, fs.st_size);
	printf(" Done.\n");

	///////////// Collision Summary ///////////// 

	j = 0;
	for (i = 0; i < HASH_SIZE; i++)
	{
		if (htable[i].count > 1)
			j++;
	}
	printf("  Collision: %4d    Total:    %4d     Ratio: %.2f\n\n",
			j, k, j * 1.0 / k);

	destroy_list();

	return 0;
}
Exemple #20
0
int
main (int argc, char **argv)
{
    int publicsw = -1, zerosw = 0;
    int create = 1, unseensw = 1;
    int fd, msgnum, seqp = 0;
    char *cp, *maildir, *folder = NULL, buf[BUFSIZ];
    char **argp, **arguments, *seqs[NUMATTRS+1];
    struct msgs *mp;
    struct stat st;

    done=unlink_done;

#ifdef LOCALE
    setlocale(LC_ALL, "");
#endif
    invo_name = r1bindex (argv[0], '/');

    /* read user profile/context */
    context_read();

    mts_init (invo_name);
    arguments = getarguments (invo_name, argc, argv, 1);
    argp = arguments;

    /* parse arguments */
    while ((cp = *argp++)) {
	if (*cp == '-') {
	    switch (smatch (++cp, switches)) {
	    case AMBIGSW: 
		ambigsw (cp, switches);
		done (1);
	    case UNKWNSW: 
		adios (NULL, "-%s unknown", cp);

	    case HELPSW: 
		snprintf (buf, sizeof(buf), "%s [+folder] [switches]",
			  invo_name);
		print_help (buf, switches, 1);
		done (1);
	    case VERSIONSW:
		print_version(invo_name);
		done (1);

	    case SEQSW: 
		if (!(cp = *argp++) || *cp == '-')
		    adios (NULL, "missing argument name to %s", argp[-2]);

		/* check if too many sequences specified */
		if (seqp >= NUMATTRS)
		    adios (NULL, "too many sequences (more than %d) specified", NUMATTRS);
		seqs[seqp++] = cp;
		continue;

	    case UNSEENSW:
		unseensw = 1;
		continue;
	    case NUNSEENSW:
		unseensw = 0;
		continue;

	    case PUBSW: 
		publicsw = 1;
		continue;
	    case NPUBSW: 
		publicsw = 0;
		continue;

	    case ZEROSW: 
		zerosw++;
		continue;
	    case NZEROSW: 
		zerosw = 0;
		continue;

	    case CRETSW: 
		create++;
		continue;
	    case NCRETSW: 
		create = 0;
		continue;
	    }
	}
	if (*cp == '+' || *cp == '@') {
	    if (folder)
		adios (NULL, "only one folder at a time!");
	    else
		folder = pluspath (cp);
	} else {
	    adios (NULL, "usage: %s [+folder] [switches]", invo_name);
	}
    }

    seqs[seqp] = NULL;	/* NULL terminate list of sequences */

    if (!context_find ("path"))
	free (path ("./", TFOLDER));

    /* if no folder is given, use default folder */
    if (!folder)
	folder = getfolder (0);
    maildir = m_maildir (folder);

    /* check if folder exists */
    if (stat (maildir, &st) == NOTOK) {
	if (errno != ENOENT)
	    adios (maildir, "error on folder");
	if (!create)
	    adios (NULL, "folder %s doesn't exist", maildir);
	if (!makedir (maildir))
	    adios (NULL, "unable to create folder %s", maildir);
    }

    if (chdir (maildir) == NOTOK)
	adios (maildir, "unable to change directory to");

    /* ignore a few signals */
    SIGNAL (SIGHUP, SIG_IGN);
    SIGNAL (SIGINT, SIG_IGN);
    SIGNAL (SIGQUIT, SIG_IGN);
    SIGNAL (SIGTERM, SIG_IGN);

    /* create a temporary file */
    tmpfilenam = m_mktemp (invo_name, &fd, NULL);
    if (tmpfilenam == NULL) {
	adios ("rcvstore", "unable to create temporary file");
    }
    chmod (tmpfilenam, m_gmprot());

    /* copy the message from stdin into temp file */
    cpydata (fileno (stdin), fd, "standard input", tmpfilenam);

    if (fstat (fd, &st) == NOTOK) {
	unlink (tmpfilenam);
	adios (tmpfilenam, "unable to fstat");
    }
    if (close (fd) == NOTOK)
	adios (tmpfilenam, "error closing");

    /* don't add file if it is empty */
    if (st.st_size == 0) {
	unlink (tmpfilenam);
	advise (NULL, "empty file");
	done (0);
    }

    /*
     * read folder and create message structure
     */
    if (!(mp = folder_read (folder)))
	adios (NULL, "unable to read folder %s", folder);

    /*
     * Link message into folder, and possibly add
     * to the Unseen-Sequence's.
     */
    if ((msgnum = folder_addmsg (&mp, tmpfilenam, 0, unseensw, 0, 0, (char *)0)) == -1)
	done (1);

    /*
     * Add the message to any extra sequences
     * that have been specified.
     */
    for (seqp = 0; seqs[seqp]; seqp++) {
	if (!seq_addmsg (mp, seqs[seqp], msgnum, publicsw, zerosw))
	    done (1);
    }

    seq_setunseen (mp, 0);	/* synchronize any Unseen-Sequence's      */
    seq_save (mp);		/* synchronize and save message sequences */
    folder_free (mp);		/* free folder/message structure          */

    context_save ();		/* save the global context file           */
    unlink (tmpfilenam);	/* remove temporary file                  */
    tmpfilenam = NULL;

    done (0);
    return 1;
}
Exemple #21
0
pid_t
proc_run(struct privsep *ps, struct privsep_proc *p,
    struct privsep_proc *procs, u_int nproc,
    void (*init)(struct privsep *, struct privsep_proc *, void *), void *arg)
{
	pid_t			 pid;
	struct passwd		*pw;
	const char		*root;
	struct control_sock	*rcs;
	u_int			 n;

	if (ps->ps_noaction)
		return (0);

	proc_open(ps, p, procs, nproc);

	/* Fork child handlers */
	switch (pid = fork()) {
	case -1:
		fatal("proc_run: cannot fork");
	case 0:
		/* Set the process group of the current process */
		setpgid(0, 0);
		break;
	default:
		return (pid);
	}

	pw = ps->ps_pw;

	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
		if (control_init(ps, &ps->ps_csock) == -1)
			fatalx(p->p_title);
		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
			if (control_init(ps, rcs) == -1)
				fatalx(p->p_title);
	}

	/* Change root directory */
	if (p->p_chroot != NULL)
		root = p->p_chroot;
	else
		root = pw->pw_dir;

	if (chroot(root) == -1)
		fatal("proc_run: chroot");
	if (chdir("/") == -1)
		fatal("proc_run: chdir(\"/\")");

	privsep_process = p->p_id;

	setproctitle("%s", p->p_title);

	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		fatal("proc_run: cannot drop privileges");

	/* Fork child handlers */
	for (n = 1; n < ps->ps_instances[p->p_id]; n++) {
		if (fork() == 0) {
			ps->ps_instance = p->p_instance = n;
			break;
		}
	}

#ifdef DEBUG
	log_debug("%s: %s %d/%d, pid %d", __func__, p->p_title,
	    ps->ps_instance + 1, ps->ps_instances[p->p_id], getpid());
#endif

	event_init();

	signal_set(&ps->ps_evsigint, SIGINT, proc_sig_handler, p);
	signal_set(&ps->ps_evsigterm, SIGTERM, proc_sig_handler, p);
	signal_set(&ps->ps_evsigchld, SIGCHLD, proc_sig_handler, p);
	signal_set(&ps->ps_evsighup, SIGHUP, proc_sig_handler, p);
	signal_set(&ps->ps_evsigpipe, SIGPIPE, proc_sig_handler, p);
	signal_set(&ps->ps_evsigusr1, SIGUSR1, proc_sig_handler, p);

	signal_add(&ps->ps_evsigint, NULL);
	signal_add(&ps->ps_evsigterm, NULL);
	signal_add(&ps->ps_evsigchld, NULL);
	signal_add(&ps->ps_evsighup, NULL);
	signal_add(&ps->ps_evsigpipe, NULL);
	signal_add(&ps->ps_evsigusr1, NULL);

	proc_listen(ps, procs, nproc);

	if (p->p_id == PROC_CONTROL && ps->ps_instance == 0) {
		TAILQ_INIT(&ctl_conns);
		if (control_listen(&ps->ps_csock) == -1)
			fatalx(p->p_title);
		TAILQ_FOREACH(rcs, &ps->ps_rcsocks, cs_entry)
			if (control_listen(rcs) == -1)
				fatalx(p->p_title);
	}
int main (int argc, const char* argv[]) {
	if (argc == 1) {
		printf("Usage: LocalizationStatusHelper <bundle-path>\n");
	} else {
		if (chdir(argv[1]) == -1) {
			printf("Cannot change directory to %s", argv[1]);
			perror("");
			return 0;
		}
		
		DIR* dir = opendir(".");
		if (dir == NULL) {
			printf("Cannot open %s for reading", argv[1]);
			perror("");
			return 0;
		}
		
		struct languagesAndKeys sk;
		
		sk.languages = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
		sk.keys = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
		
		CFMutableSetRef unionKeys = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
		
		struct dirent* dp;
		// Scan for the directory.
		while ((dp = readdir(dir)) != NULL) {
			if (dp->d_type == DT_DIR) {
				CFStringRef dirName = CFStringCreateWithCString(NULL, dp->d_name, kCFStringEncodingUTF8);
				
				// Check if it's an lproj.
				if (CFStringHasSuffix(dirName, CFSTR(".lproj"))) {
					CFMutableSetRef langKeys = CFSetCreateMutable(NULL, 0, &kCFTypeSetCallBacks);
					
					// Scan for strings files.
					chdir(dp->d_name);
					DIR* subdir = opendir(".");
					if (subdir != NULL) {
						struct dirent* dp2;
						while ((dp2 = readdir(subdir)) != NULL) {
							// Ignore linked strings files.
							if (dp2->d_type == DT_REG) {
								CFStringRef stringsName = CFStringCreateWithCString(NULL, dp2->d_name, kCFStringEncodingUTF8);
								// Ignore non-strings files.
								if (CFStringHasSuffix(stringsName, CFSTR(".strings"))) {
									// Convert to 
									CFURLRef stringsURL = CFURLCreateWithFileSystemPath(NULL, stringsName, kCFURLPOSIXPathStyle, false);
									CFReadStreamRef stringsStream = CFReadStreamCreateWithFile(NULL, stringsURL);
									CFRelease(stringsURL);
									CFReadStreamOpen(stringsStream);
									CFPropertyListRef strings = CFPropertyListCreateFromStream(NULL, stringsStream, 0, kCFPropertyListImmutable, NULL, NULL);
									CFReadStreamClose(stringsStream);
									CFRelease(stringsStream);
									CFDictionaryApplyFunction(strings, (CFDictionaryApplierFunction)&addKeysToSet, langKeys);
									CFDictionaryApplyFunction(strings, (CFDictionaryApplierFunction)&addKeysToSet, unionKeys);
									CFRelease(strings);
								}
								CFRelease(stringsName);
							}
						}
						closedir(subdir);
					}
					chdir("..");
					
					CFStringRef langCode = CFStringCreateWithSubstring(NULL, dirName, CFRangeMake(0, CFStringGetLength(dirName)-6));
					CFArrayAppendValue(sk.languages, langCode);
					CFArrayAppendValue(sk.keys, langKeys);
					CFRelease(langKeys);
					CFRelease(langCode);
				}
				CFRelease(dirName);
			}
		}
		closedir(dir);
		
		sk.count = CFArrayGetCount(sk.languages);
		
		printf("|| *Key* ||");
		CFArrayApplyFunction(sk.languages, CFRangeMake(0, sk.count), (CFArrayApplierFunction)&printHeader, NULL);
		printf("\n");
		
		CFSetApplyFunction(unionKeys, (CFSetApplierFunction)&printSupportedLanguages, &sk);
		
		CFRelease(sk.keys);
		CFRelease(sk.languages);
		CFRelease(unionKeys);
	}
	
	return 0;
}
Exemple #23
0
/**
 * Set up engine.
 *
 */
static ods_status
engine_setup(engine_type* engine)
{
    ods_status status = ODS_STATUS_OK;
    struct sigaction action;
    int result = 0;
    int sockets[2] = {0,0};

    ods_log_debug("[%s] setup signer engine", engine_str);
    if (!engine || !engine->config) {
        return ODS_STATUS_ASSERT_ERR;
    }
    /* set edns */
    edns_init(&engine->edns, EDNS_MAX_MESSAGE_LEN);

    /* create command handler (before chowning socket file) */
    engine->cmdhandler = cmdhandler_create(engine->allocator,
        engine->config->clisock_filename);
    if (!engine->cmdhandler) {
        return ODS_STATUS_CMDHANDLER_ERR;
    }
    engine->dnshandler = dnshandler_create(engine->allocator,
        engine->config->interfaces);
    engine->xfrhandler = xfrhandler_create(engine->allocator);
    if (!engine->xfrhandler) {
        return ODS_STATUS_XFRHANDLER_ERR;
    }
    if (engine->dnshandler) {
        if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sockets) == -1) {
            return ODS_STATUS_XFRHANDLER_ERR;
        }
        engine->xfrhandler->dnshandler.fd = sockets[0];
        engine->dnshandler->xfrhandler.fd = sockets[1];
        status = dnshandler_listen(engine->dnshandler);
        if (status != ODS_STATUS_OK) {
            ods_log_error("[%s] setup: unable to listen to sockets (%s)",
                engine_str, ods_status2str(status));
        }
    }
    /* privdrop */
    engine->uid = privuid(engine->config->username);
    engine->gid = privgid(engine->config->group);
    /* TODO: does piddir exists? */
    /* remove the chown stuff: piddir? */
    ods_chown(engine->config->pid_filename, engine->uid, engine->gid, 1);
    ods_chown(engine->config->clisock_filename, engine->uid, engine->gid, 0);
    ods_chown(engine->config->working_dir, engine->uid, engine->gid, 0);
    if (engine->config->log_filename && !engine->config->use_syslog) {
        ods_chown(engine->config->log_filename, engine->uid, engine->gid, 0);
    }
    if (engine->config->working_dir &&
        chdir(engine->config->working_dir) != 0) {
        ods_log_error("[%s] setup: unable to chdir to %s (%s)", engine_str,
            engine->config->working_dir, strerror(errno));
        return ODS_STATUS_CHDIR_ERR;
    }
    if (engine_privdrop(engine) != ODS_STATUS_OK) {
        return ODS_STATUS_PRIVDROP_ERR;
    }
    /* set up hsm */ /* LEAK */
    result = lhsm_open(engine->config->repositories);
    if (result != HSM_OK) {
        fprintf(stderr, "Fail to open hsm\n");
        return ODS_STATUS_HSM_ERR;
    }
    /* daemonize */
    if (engine->daemonize) {
        switch ((engine->pid = fork())) {
            case -1: /* error */
                ods_log_error("[%s] setup: unable to fork daemon (%s)",
                    engine_str, strerror(errno));
                return ODS_STATUS_FORK_ERR;
            case 0: /* child */
                break;
            default: /* parent */
                engine_cleanup(engine);
                engine = NULL;
                xmlCleanupParser();
                xmlCleanupGlobals();
                xmlCleanupThreads();
                exit(0);
        }
        if (setsid() == -1) {
            hsm_close();
            ods_log_error("[%s] setup: unable to setsid daemon (%s)",
                engine_str, strerror(errno));
            return ODS_STATUS_SETSID_ERR;
        }
    }
    engine->pid = getpid();
    /* write pidfile */
    if (util_write_pidfile(engine->config->pid_filename, engine->pid) == -1) {
        hsm_close();
        return ODS_STATUS_WRITE_PIDFILE_ERR;
    }
    /* setup done */
    ods_log_verbose("[%s] running as pid %lu", engine_str,
        (unsigned long) engine->pid);
    /* catch signals */
    signal_set_engine(engine);
    action.sa_handler = signal_handler;
    sigfillset(&action.sa_mask);
    action.sa_flags = 0;
    sigaction(SIGTERM, &action, NULL);
    sigaction(SIGHUP, &action, NULL);
    sigaction(SIGINT, &action, NULL);
    sigaction(SIGILL, &action, NULL);
    sigaction(SIGUSR1, &action, NULL);
    sigaction(SIGALRM, &action, NULL);
    sigaction(SIGCHLD, &action, NULL);
    action.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &action, NULL);
    /* create workers/drudgers */
    engine_create_workers(engine);
    engine_create_drudgers(engine);
    /* start cmd/dns/xfr handlers */
    engine_start_cmdhandler(engine);
    engine_start_dnshandler(engine);
    engine_start_xfrhandler(engine);
    tsig_handler_init(engine->allocator);
    return ODS_STATUS_OK;
}
Exemple #24
0
int main(int argc, char **argv) {
    const char *root = "/Users/mdhender/Software/Xcode/jr/data";
    if (chdir(root) < 0) {
        perror(root);
        exit(3);
    }
    
    /* port to listen on */
    int portno = 8765;
    
    /* check command line args */
    /*
    if (argc != 2) {
        fprintf(stderr, "usage: %s <port>\n", argv[0]);
        exit(1);
    } else if (argc == 2) {
        portno = atoi(argv[1]);
    } */
    
    /* open socket descriptor for parent socket */
    int fdServer = socket(AF_INET, SOCK_STREAM, 0);
    if (fdServer < 0) {
        perror("ERROR opening socket");
        exit(1);
    } else {
        /* flag value for setsockopt allows us to restart server immediately */
        int optval = 1;
        setsockopt(fdServer, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval, sizeof(int));
    }
    
    /* bind port to socket */
    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons((unsigned short)portno);
    
    if (bind(fdServer, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) {
        perror("ERROR on binding");
        exit(1);
    }
    
    /* get us ready to accept connection requests */
    if (listen(fdServer, 5) < 0) { /* allow 5 requests to queue up */
        perror("ERROR on listen");
        exit(1);
    }
    
    /*
     * main loop: wait for a connection request, parse HTTP,
     * serve requested content, close connection.
     */
    int maxLoops = 5;
    while (1 && maxLoops--) {
        /* wait for a connection request on a socket */
        struct sockaddr_in clientaddr;
        socklen_t clientlen = sizeof(clientaddr);
        int fdClient = accept(fdServer, (struct sockaddr *)&clientaddr, &clientlen);
        if (fdClient < 0) {
            jr_log(ERROR, "error on accept");
        }
        
        /* client host info tells us who sent the message */
        struct hostent *hostp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);
        if (!hostp) {
            jr_log(ERROR, "error on gethostbyaddr");
        }
        
        /* dotted decimal host addr string */
        char *hostaddrp = inet_ntoa(clientaddr.sin_addr);
        if (!hostaddrp) {
            jr_log(ERROR, "error on inet_ntoa");
        }
        
        /* open the child socket descriptor as a stream */
        FILE *stream = fdopen(fdClient, "r+");
        if (!stream) {
            jr_log(ERROR, "error on fdopen");
        }
        
        jr_service_request(fdServer, fdClient, stream);

        fclose(stream);
        close(fdClient);

    }
    
    close(fdServer);
    
    return 0;
}
Exemple #25
0
static char* start_app(app_t* app)
{
  char* wd = app->wd, *prog = app->prog;
  int id = app->id;
  SWI_LOG("APPMON", DEBUG, "start_app, id=%d, wd=%s; prog=%s\n", id, wd, prog);
  char * res = check_params(wd, prog);
  if (res) //check param errors
    return res;

  pid_t child_pid = fork();
  if (-1 == child_pid)
  {
    perror("start_app");
    res = "Fork error, cannot create new process";
    SWI_LOG("APPMON", ERROR, "%s\n", res);
    return res;
  }
  if (0 == child_pid)
  { //in child
    // close inherited stuff
    // note: sig handlers are reset
    close(srv_skt);
    close(client_skt);
    //child will actually run the application
    if (-1 == chdir(wd))
    {
      perror("cannot change working dir: chdir error");
      exit(EXIT_FAILURE);
    }

    setpgrp(); //equivalent to setpgrp(0, 0).
    //the point is that the child process is getting its own process group id, and becomes this process group leader
    //then on stop() daemon will send TERM signal to the process group of the child so that all children of this command will receive this signal.
    //so that all children of the application are killed too.
    //TODO: check if using setsid() can do the same thing, setsid might be more POSIX friendly (setpgrp() is indicated System V)
    SWI_LOG("APPMON", DEBUG, "Child: id= %d, pid=%d,  process group id set to = %d\n", id, getpid(), getpgrp());

    //change uid/gid/priority if necessary
    if (!app->privileged)
    {
      umask(S_IWOTH); //umask man reports that umask always succeeds...
      //SWI_LOG("APPMON", ERROR,"Failed to set umask")

      //may call error
      set_uid_gids(uid, gid, id);

      if (INT_MAX != app_priority)
      {
        //compute nice increment to give to nice
        int current_priority = getpriority(PRIO_PROCESS, 0);
        int nice_inc = app_priority - current_priority;
        //see nice man page, need to test errno manually
        errno = 0;
        int res = nice(nice_inc);
        if (errno)
        {
          SWI_LOG("APPMON", ERROR, "Child: id= %d, error while doing nice failed :%s, target priority was: %d, starting app with priority =%d\n",
                   id, strerror(errno), app_priority, getpriority(PRIO_PROCESS, 0));
        }
        else
        {
          if (res != app_priority)
            SWI_LOG("APPMON", ERROR, "Child: id= %d, nice failed : new priority=%d\n", id, res);
          else
            SWI_LOG("APPMON", DEBUG, "Child: id= %d, new priority=%d\n", id, res);
        }
      }
    }
    else //privileged app
    {
      set_uid_gids(puid, pgid, id);
      //no process priority change for privileged app
    }
    SWI_LOG("APPMON", DEBUG, "Child: id= %d, running with uid=%d gid=%d, eff uid=%d\n", id, getuid(), getgid(), geteuid());

    char* const argv[] = { prog, NULL };
    execvp(prog, argv);
    perror("");
    SWI_LOG("APPMON", ERROR, "Child: execvp has returned, error must have occurred\n");
    exit(EXIT_FAILURE);
  }
  //in daemon: everything is ok, update app infos.
  app->status = STARTED;
  app->pid = child_pid;
  app->start_count++;
  return "ok";
}
Exemple #26
0
int main(int argc, char **argv) {
    int i, port, pid, listenfd, socketfd, hit;
    
    static struct sockaddr_in cli_addr; /* static = initialised to zeros */
    static struct sockaddr_in serv_addr; /* static = initialised to zeros */
    
    if (argc < 3  || argc > 3 || !strcmp(argv[1], "-?")) {
        (void)printf("hint: nweb Port-Number Top-Directory\n\n"
                     "\tnweb is a small and very safe mini web server\n"
                     "\tnweb only servers out file/web pages with extensions named below\n"
                     "\t and only from the named directory or its sub-directories.\n"
                     "\tThere is no fancy features = safe and secure.\n\n"
                     "\tExample: nweb 8181 /home/nwebdir &\n\n\tOnly Supports:");
        
        for (i = 0; extensions[i].ext != 0; i++) {
            (void)printf(" %s", extensions[i].ext);
        }
        
        (void)printf("\n\tNot Supported: URLs including \"..\", Java, Javascript, CGI\n"
                     "\tNot Supported: directories / /etc /bin /lib /tmp /usr /dev/sbin \n"
                     "\tNo warranty given or implied\n\tNigel Griffiths [email protected]\n");
        exit(0);
    }
    
    if (!strncmp(argv[2], "/", 2) || !strncmp(argv[2], "/etc", 5) || !strncmp(argv[2], "/bin", 5) || !strncmp(argv[2], "/lib", 5) || !strncmp(argv[2], "/tmp", 5) || !strncmp(argv[2], "/usr", 5) || !strncmp(argv[2], "/dev", 5) || !strncmp(argv[2], "/sbin", 6)) {
        (void)printf("ERROR: Bad top directory %s, see nweb -?\n", argv[2]);
        exit(3);
    }
    
    if (chdir(argv[2]) == -1) {
        (void)printf("ERROR: Can't Change to directory %s\n", argv[2]);
        exit(4);
    }
    
    /* Become deamon + unstopable and no zombies children (= no wait()) */
    if (fork() != 0) {
        /* parent returns OK to shell */
        return 0;
    }
    
    /* ignore child death */
    (void)signal(SIGCHLD, SIG_IGN);
    
    /* ignore terminal hangups */
    (void)signal(SIGHUP, SIG_IGN);
    
    for (i = 0; i < 32; i++) {
        /* close open files */
        (void)close(i);
    }
    
    /* break away from process group */
    (void)setpgrp();
    jr_log(LOG, "nweb starting", argv[1], getpid());
    
    /* setup the network socket */
    if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        jr_log(ERROR, "system call", "socket", 0);
    }
    
    port = atoi(argv[1]);
    
    if (port < 0 || port > 60000) {
        jr_log(ERROR, "Invalid port number (try 1->60000)", argv[1], 0);
    }
    
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(port);
    
    if (bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        jr_log(ERROR, "system call", "bind", 0);
    }
    
    if (listen(listenfd, 64) < 0) {
        jr_log(ERROR, "system call", "listen", 0);
    }
    
    for (hit = 1;; hit++) {
        socklen_t length = sizeof(cli_addr);
        
        if ((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0) {
            jr_log(ERROR, "system call", "accept", 0);
        }
        
        if ((pid = fork()) < 0) {
            jr_log(ERROR, "system call", "fork", 0);
        } else {
            if (pid == 0) {  /* child */
                (void)close(listenfd);
                web(socketfd, hit); /* never returns */
            } else {        /* parent */
                (void)close(socketfd);
            }
        }
    }
}
Exemple #27
0
int main(int argc, char ** argv)
{
    char * sender;

    char * message;
    unsigned int time_message;
    unsigned int timer;
    unsigned int num;
    char * message_filename;
    char * dir;

    char * ptr;
    char * my_delivered_to;

    DIR * dirp;
    struct dirent * direntp;
    unsigned int message_time;
    char * address;
    unsigned int count;
    char filename[256];
    FILE * f;
    unsigned int message_handling = DEFAULT_MH;
    char buffer[256];
    char *content_boundary;
    char *rpath = DEFAULT_FROM;
    char *TheUser;
    char *TheDomain;

    if(argc > 7 || argc < 5) {
        fprintf(stderr, "\nautorespond: ");
        fprintf(stderr, "usage: time num message dir [ flag arsender ]\n\n");
        fprintf(stderr, "time - amount of time to consider a message (in seconds)\n");
        fprintf(stderr, "num - maximum number of messages to allow within time seconds\n");
        fprintf(stderr, "message - the filename of the message to send\n");
        fprintf(stderr, "dir - the directory to hold the log of messages\n\n");
        fprintf(stderr, "optional parameters:\n\n");
        fprintf(stderr, "flag - handling of original message:\n\n");
        fprintf(stderr, "0 - append nothing\n");
        fprintf(stderr, "1 - append quoted original message without attachments <default>\n\n");
        fprintf(stderr, "arsender - from address in generated message, or:\n\n");
        fprintf(stderr, "+ = blank from envelope !\n");
        fprintf(stderr, "$ = To: address will be used\n\n");
        _exit(111);
    }

    TheUser= getenv("EXT");
    TheDomain= getenv("HOST");

    setvbuf(stderr, NULL, _IONBF, 0);

    if(argc > 7 || argc < 5) {
        fprintf(stderr, "AUTORESPOND: Invalid arguments. (%d)\n",argc);
        _exit(111);
    }

    time_message     = strtoul(argv[1],NULL,10);
    num              = strtoul(argv[2],NULL,10);
    message_filename = argv[3];
    dir              = argv[4];

    if ( argc > 5 )
        message_handling = strtoul(argv[5],NULL,10);
    if ( argc > 6 )
        rpath = argv[6];

    if ( *rpath == '+' )
        rpath = "";
    if ( *rpath == '$' )
    {
        rpath = safe_malloc( strlen(TheUser) + strlen(TheDomain) + 2);
        strncpy( rpath, TheUser, strlen(TheUser) );
        strncat( rpath, "@", 1 );
        strncat( rpath, TheDomain, strlen(TheDomain) );
    }

    timer = time(NULL);

    /*prepare the "delivered-to" string*/
    my_delivered_to = "Delivered-To: Autoresponder\n";

    read_headers( stdin );


    message = read_file(message_filename);
    if(message==NULL) {
        fprintf(stderr, "AUTORESPOND: Failed to open message file.\n");
        _exit(111);
    }

    /*don't autorespond in certain situations*/
    sender = getenv("SENDER");
    if(sender==NULL)
        sender = "";

    /*don't autorespond to a mailer-daemon*/
    if( sender[0]==0 || strncasecmp(sender,"mailer-daemon",13)==0 || strchr(sender,'@')==NULL || strcmp(sender,"#@[]")==0 ) {
        /*exit with success and continue parsing .qmail file*/
        fprintf(stderr,"AUTORESPOND:  Stopping on mail from [%s].\n",sender);
        _exit(0);
    }


    if ( inspect_headers("mailing-list", (char *)NULL ) != (char *)NULL )
    {
        fprintf(stderr,"AUTORESPOND: This looks like it's from a mailing list, I will ignore it.\n");
        _exit(0);			/*report success and exit*/
    }
    if ( inspect_headers("Delivered-To", "Autoresponder" ) != (char *)NULL )
    {
        /*got one of my own messages...*/
        fprintf(stderr,"AUTORESPOND: This message is looping...it has my Delivered-To header.\n");
        _exit(100);			/*hard error*/
    }
    if ( inspect_headers("precedence", "junk" ) != (char *)NULL ||
            inspect_headers("precedence", "bulk" ) != (char *)NULL ||
            inspect_headers("precedence", "list" ) != (char *)NULL )
    {
        fprintf(stderr,"AUTORESPOND: Junk mail received.\n");
        _exit(0); /* don't reply to bulk, junk, or list mail */
    }

    /*check the logs*/
    if(chdir(dir) == -1) {
        fprintf(stderr,"AUTORESPOND: Failed to change into directory.\n");
        _exit(111);
    }

    /*add entry*/
    sprintf(filename,"A%u.%u",getpid(),timer);
    f = fopen(filename,"wb");
    if(f==NULL) {
        fprintf(stderr,"AUTORESPOND: Unable to create file for [%s].",sender);
        _exit(111);
    }
    if(fwrite(sender,1,strlen(sender),f)!=strlen(sender)) {
        fprintf(stderr,"AUTORESPOND: Unable to create file for [%s].",sender);
        fclose(f);
        unlink(filename);
        _exit(111);
    }
    fclose(f);

    /*check if there are too many responses in the logs*/
    dirp = opendir(".");
    count = 0;
    while((direntp = readdir(dirp)) != NULL) {
        if(direntp->d_name[0] != 'A')
            continue;
        ptr = strchr(direntp->d_name,'.');
        if(ptr==NULL)
            continue;
        message_time = strtoul(ptr+1,NULL,10);
        if(message_time < timer-time_message) {
            /*too old..ignore errors on unlink*/
            unlink(direntp->d_name);
        } else {
            address = read_file(direntp->d_name);
            if(address==NULL) {
                /*ignore this?*/
                continue;
            }
            if(strcasecmp(address,sender)==0) {
                count++;
            }
            free(address);
        }
    }
    if(count>num) {
        fprintf(stderr,"AUTORESPOND: too many received from [%s]\n",sender);
        _exit(0); /* don't reply to this message, but allow it to be delivered */
    }

    sprintf(filename,"tmp%u.%u",getpid(),timer);
    f = fopen(filename,"wb");

    fprintf( f, "%sTo: %s\nFrom: %s\nSubject: Re:%s\n%s\n",
             my_delivered_to, sender, rpath, inspect_headers( "Subject", (char *) NULL ), message );

    if ( message_handling == 1 ) {
        fprintf( f, "%s\n\n", "-------- Original Message --------" );
        if ( (content_boundary = get_content_boundary()) == (char *)NULL )
        {
            while ( fgets( buffer, sizeof(buffer), stdin ) != NULL )
            {
                fputs( "> ", f );
                fputs( buffer, f );
            }
        } else
        {
            int content_found = 0;
            while ( fgets( buffer, sizeof(buffer), stdin ) != NULL )
            {
                if ( content_found == 1 )
                {
                    if ( strstr( buffer, content_boundary ) != (char *)NULL )
                        break;
                    fputs( "> ", f );
                    fputs( buffer, f );
                }
                if ( strstr( buffer, content_boundary ) != (char *)NULL )
                {
                    if ( content_found == 1 )
                        break;
                    else
                    {
                        free_headers();
                        read_headers( stdin );
                        if ( inspect_headers("Content-Type", "text/plain" ) != (char *)NULL )
                            content_found = 1;
                        continue;
                    }
                }
            }
        }
    }

    fprintf( f, "\n\n" );

    fclose( f );

    /*send the autoresponse...ignore errors?*/
    send_message(filename,rpath,&sender,1);

    unlink( filename );

    _exit(0);
    return 0;					/*compiler warning squelch*/
}
int main()
{
	char *args[MAX]; //for each part of the command line including command and args
	char *command; // the actual command
	char cmd[MAX+1]; //temporary storage for the whole command line
	char *name = getenv("USER"); //the user's name
	 
	int run = 1; //when set to 0 the quit comman has been executed and execution stops
	 
	char *currentDir = getenv("PWD"); //set the current directory
      
    //welcome message
    printf( "\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    printf( "  \e[0;34m           _______\n");
    printf( "               \\   /\n");
		printf( "                l   l\n");
		printf( "    __       l   l\e[m______________________________________________\n");
		printf( "  \e[0;34m  1  l_________l   l\e[m                                           \\");
    printf( "  \n");
		printf( "  \e[0;34m  l  l/ / / / /l   l\e[m_______________________________________________\\");
    printf( "  \n");
    printf( "  \e[0;34m  l  l_/_/_/_/_l   l     \e[0;31m  Welcome to Nick's Shell   \e[m           /\n");
			
    printf( "  \e[0;34m  l__l        l   l\e[m______________________________________________/\n");
		printf( "  \e[0;34m            l   l\n");
		printf( "                l   l\n");
    printf( "               /_____\\");
    printf( "\n");
    printf( "\n");
		printf( "\n\n\n");
      
    while(run == 1) //run untill quit command is entered
    {
        printf( "\e[0;32m"); //color it green
        printf("%s%s%s%s%s", "[", name, "]",getenv("PWD"), ": "); //print prompt
        printf("\e[m"); //end the green
			
        fgets(cmd, MAX, stdin); //get in the whole line
			
        args[0] = strtok(cmd, " \n"); //get command
          
			command = args[0]; //set the command
          
        if(command != NULL) // make sure they entered something
			{
            if(strcmp(command,"quit") == 0) //handle the quit command
					{
                run = 0;
            }
				else if(strcmp(command,"cd") == 0) //handle the cd command
				{
                currentDir = getenv("PWD");
					
                char *newDir;
					char *enteredDir;
					args[1] = strtok(NULL, " \n");
		enteredDir = args[1];
                  
					if(enteredDir == NULL) // no arguments for cd
                {
                    newDir = currentDir;
                }
                else if(args[1][0] == '/') //new directory begins with a '/'
                {
                    newDir = currentDir;
                    strcat(newDir,enteredDir);
                }
                else if(strcmp(enteredDir,"..") != 0) //new directory is just a folder name
					{
                    newDir = strcat(currentDir,"/");
                    newDir = strcat(newDir,enteredDir);
					}
                else if(strcmp(enteredDir,"..") == 0) //new directory must go back a directory
					{ 
						char *pwd = currentDir;
                    char *place;
						place = strrchr(pwd,'/');
						*place = '\0';
						
						newDir = pwd;
                }
                   
					printf("%s\n",newDir); //print the new directory
                     
                if(chdir(newDir) != 0) //check if it exists
					{
                    char *place;
                    place = strrchr(newDir,'/');
						*place = '\0';
                    printf("Directory does not exist\n");
						}
                   
					setenv("PWD",newDir,1);
                   
                enteredDir = NULL;
					newDir = NULL;
            }
				else // block of code for executing all other commands
            {
                char *temp = strtok(NULL, " \n");
                   
                int counter = 1;
                   
                while(temp != NULL) // take in all arguments
                {
                    args[counter++] = temp;
                    temp = strtok(NULL, " \n");
                }
                   
                if(fork() == 0) // fork to execute command
                {
                    execvp(args[0],args);
                    exit(0);
                }
                   
                wait(NULL);
            }
        }
           
        int i = 0;
        for(i = 0; i < MAX; i++)
            args[i] = NULL;
               
        command = NULL;
    }
}
Exemple #29
0
int main(int argc, char *argv[])
{
	/* initialize SDL first */
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0)
	{
		Debug() << "Error initializing SDL:" << SDL_GetError();

		return 0;
	}

	if (!EventThread::allocUserEvents())
	{
		Debug() << "Error allocating SDL user events";

		return 0;
	}

	/* set working directory */
	char *dataDir = SDL_GetBasePath();
	if (dataDir)
	{
		int result = chdir(dataDir);
		(void)result;
		SDL_free(dataDir);
	}

	/* now we load the config */
	Config conf;

	conf.read(argc, argv);
	conf.readGameINI();

	int imgFlags = IMG_INIT_PNG | IMG_INIT_JPG;
	if (IMG_Init(imgFlags) != imgFlags)
	{
		Debug() << "Error initializing SDL_image:" << SDL_GetError();
		SDL_Quit();

		return 0;
	}

	if (TTF_Init() < 0)
	{
		Debug() << "Error initializing SDL_ttf:" << SDL_GetError();
		IMG_Quit();
		SDL_Quit();

		return 0;
	}

	if (Sound_Init() == 0)
	{
		Debug() << "Error initializing SDL_sound:" << Sound_GetError();
		TTF_Quit();
		IMG_Quit();
		SDL_Quit();

		return 0;
	}

	SDL_SetHint("SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS", "0");

	SDL_Window *win;
	Uint32 winFlags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;

	if (conf.winResizable)
		winFlags |= SDL_WINDOW_RESIZABLE;
	if (conf.fullscreen)
		winFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;

	win = SDL_CreateWindow(conf.game.title.c_str(),
	                       SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
	                       conf.defScreenW, conf.defScreenH, winFlags);

	if (!win)
	{
		Debug() << "Error creating window";
		return 0;
	}

	if (!conf.iconPath.empty())
	{
		SDL_Surface *iconImg = IMG_Load(conf.iconPath.c_str());
		if (iconImg)
		{
			SDL_SetWindowIcon(win, iconImg);
			SDL_FreeSurface(iconImg);
		}
	}

	EventThread eventThread;
	RGSSThreadData rtData(&eventThread, argv[0], win, conf);

	/* Start RGSS thread */
	SDL_Thread *rgssThread =
	        SDL_CreateThread(rgssThreadFun, "rgss", &rtData);

	/* Start event processing */
	eventThread.process(rtData);

	/* Request RGSS thread to stop */
	rtData.rqTerm = true;

	/* Wait for RGSS thread response */
	for (int i = 0; i < 1000; ++i)
	{
		/* We can stop waiting when the request was ack'd */
		if (rtData.rqTermAck)
		{
			Debug() << "RGSS thread ack'd request after" << i*10 << "ms";
			break;
		}

		/* Give RGSS thread some time to respond */
		SDL_Delay(10);
	}

	/* If RGSS thread ack'd request, wait for it to shutdown,
	 * otherwise abandon hope and just end the process as is. */
	if (rtData.rqTermAck)
		SDL_WaitThread(rgssThread, 0);
	else
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, conf.game.title.c_str(),
		                         "The RGSS script seems to be stuck and mkxp will now force quit", win);

	if (!rtData.rgssErrorMsg.empty())
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, conf.game.title.c_str(),
		                         rtData.rgssErrorMsg.c_str(), win);

	/* Clean up any remainin events */
	eventThread.cleanup();

	Debug() << "Shutting down.";

	SDL_DestroyWindow(win);

	Sound_Quit();
	TTF_Quit();
	IMG_Quit();
	SDL_Quit();

	return 0;
}
Exemple #30
0
int thttpd_main(int argc, char **argv)
#endif
{
  int num_ready;
  int cnum;
  FAR struct connect_s *conn;
  FAR httpd_conn *hc;
  httpd_sockaddr sa;
  struct timeval tv;
#ifdef CONFIG_THTTPD_DIR
  int ret;
#endif

  ninfo("THTTPD started\n");

  /* Setup host address */

#ifdef  CONFIG_NET_IPv6
#  error "IPv6 support not yet implemented"
#else
  sa.sin_family      = AF_INET;
  sa.sin_port        = HTONS(CONFIG_THTTPD_PORT);
  sa.sin_addr.s_addr = HTONL(CONFIG_THTTPD_IPADDR);
#endif

  /* Initialize the fdwatch package to handle all of the configured
   * socket descriptors
   */

  fw = fdwatch_initialize(CONFIG_NSOCKET_DESCRIPTORS);
  if (!fw)
    {
      nerr("ERROR: fdwatch initialization failure\n");
      exit(1);
    }

  /* Switch directories again if requested */

#ifdef CONFIG_THTTPD_DATADIR
  if (chdir(CONFIG_THTTPD_DATADIR) < 0)
    {
      ninfo("chdir to %s: %d\n",
           CONFIG_THTTPD_DATADIR, errno);
      exit(1);
    }
#endif

  /* Initialize the timer package */

  tmr_init();

  /* Initialize the HTTP layer */

  ninfo("Calling httpd_initialize()\n");
  hs = httpd_initialize(&sa);
  if (!hs)
    {
      nerr("ERROR: httpd_initialize() failed\n");
      exit(1);
    }

  /* Set up the occasional timer */

  if (tmr_create(NULL, occasional, JunkClientData, CONFIG_THTTPD_OCCASIONAL_MSEC * 1000L, 1) == NULL)
    {
      nerr("ERROR: tmr_create(occasional) failed\n");
      exit(1);
    }

  /* Set up the idle timer */

  if (tmr_create(NULL, idle, JunkClientData, 5 * 1000L, 1) == NULL)
    {
      nerr("ERROR: tmr_create(idle) failed\n");
      exit(1);

    }

  /* Initialize our connections table */

  connects = NEW(struct connect_s, AVAILABLE_FDS);
  if (connects == NULL)
    {
      nerr("ERROR: Out of memory allocating a struct connect_s\n");
      exit(1);
    }

  for (cnum = 0; cnum < AVAILABLE_FDS; ++cnum)
    {
      connects[cnum].conn_state  = CNST_FREE;
      connects[cnum].next        = &connects[cnum + 1];
      connects[cnum].hc          = NULL;
    }

  connects[AVAILABLE_FDS-1].next = NULL;      /* End of link list */
  free_connections               = connects;  /* Beginning of the link list */

  if (hs != NULL)
    {
      if (hs->listen_fd != -1)
        {
          fdwatch_add_fd(fw, hs->listen_fd, NULL);
        }
    }

  /* Main loop */

  ninfo("Entering the main loop\n");
  (void)gettimeofday(&tv, NULL);
  for (;;)
    {
      /* Do the fd watch */

      num_ready = fdwatch(fw, tmr_mstimeout(&tv));
      if (num_ready < 0)
        {
          if (errno == EINTR || errno == EAGAIN)
            {
              /* Not errors... try again */

              continue;
            }

          nerr("ERROR: fdwatch failed: %d\n", errno);
          exit(1);
        }

      (void)gettimeofday(&tv, NULL);

      if (num_ready == 0)
        {
          /* No fd's are ready - run the timers */

          tmr_run(&tv);
          continue;
        }

      /* Is it a new connection? */

      if (fdwatch_check_fd(fw, hs->listen_fd))
        {
          if (!handle_newconnect(&tv, hs->listen_fd))
            {
              /* Go around the loop and do another fdwatch, rather than
               * dropping through and processing existing connections.  New
               * connections always get priority.
               */

              continue;
            }
        }

      /* Find the connections that need servicing */

      while ((conn = (struct connect_s*)fdwatch_get_next_client_data(fw)) != (struct connect_s*)-1)
        {
          if (conn)
            {
              hc = conn->hc;
              if (fdwatch_check_fd(fw, hc->conn_fd))
                {
                  ninfo("Handle conn_state %d\n", conn->conn_state);
                  switch (conn->conn_state)
                    {
                      case CNST_READING:
                        {
                          handle_read(conn, &tv);

                          /* If a GET request was received and a file is ready to
                           * be sent, then fall through to send the file.
                           */

                          if (conn->conn_state != CNST_SENDING)
                            {
                              break;
                            }
                        }

                      case CNST_SENDING:
                        {
                          /* Send a file -- this really should be performed on a
                           * separate thread to keep the serve from locking up during
                           * the write.
                           */

                          handle_send(conn, &tv);
                        }
                        break;

                      case CNST_LINGERING:
                        {
                          /* Linger close the connection */

                          handle_linger(conn, &tv);
                        }
                        break;
                    }
                }
            }
        }
      tmr_run(&tv);
    }

  /* The main loop terminated */

  shut_down();
  ninfo("Exiting\n");
  exit(0);
}