Exemplo n.º 1
0
/*
 * Create the file n and copy from file descriptor f.
 */
static void
copy(int f, char *n)
{
	int fd, i, nr, nc;
	char buf[BUFSIZ];

	if (format == 'p')
		card('T', title ? title : n);
	for (i = 0; i < ncopies; i++)
		card(format, &dfname[inchar-2]);
	card('U', &dfname[inchar-2]);
	card('N', n);
	fd = nfile(dfname);
	nr = nc = 0;
	while ((i = read(f, buf, sizeof(buf))) > 0) {
		if (write(fd, buf, i) != i) {
			warn("%s", n);
			break;
		}
		nc += i;
		if (nc >= sizeof(buf)) {
			nc -= sizeof(buf);
			nr++;
			if (MX > 0 && nr > MX) {
				warnx("%s: copy file is too large", n);
				break;
			}
		}
	}
	(void)close(fd);
	if (nc == 0 && nr == 0) 
		warnx("%s: empty input file", f ? n : "stdin");
	else
		nact++;
}
Exemplo n.º 2
0
void OSInterface::doCopy(std::string &src, std::string &dst){
    std::shared_ptr<Data> data_instance = Data::getInstance();
    if(isDir(src)){ //je to adresar
        OSInterface os;
        os.getDirInfo(src, "*");
#ifdef __unix__
        if(mkdir(dst.c_str(), 0755) == -1)
#endif
#ifdef __WIN32__
            if(mkdir(dst.c_str()) == -1)
#endif
                throw new OSException(src, strerror(errno));
        for(auto &a : os.dirs){ // rekurzivni kopie podadresaru
            std::string nsrc, ndst;
            nsrc = src;
            nsrc.push_back(dir_sep);
            nsrc.append(a->name);
            ndst = dst;
            ndst.push_back(dir_sep);
            ndst.append(a->name);
            doCopy(nsrc, ndst);
        }
    }else{ // kopie souboru pomoci buferu
        std::ifstream file(src, std::ios::in | std::ios::binary | std::ios::ate);
        std::ifstream test(dst, std::ios::in | std::ios::binary | std::ios::ate);
        if(test.tellg() > 0)
            throw new OSException(dst, "File exists");
        test.close();
        std::ofstream nfile(dst, std::ios::out | std::ios::binary | std::ios::ate);
        char buf[data_instance->bufsize];
        long long copied = 0;
        if(!nfile.is_open())
            throw new OSException(dst, "Failed to create.");
        if (file.is_open())
        {
            long long size = file.tellg();
            file.seekg (0, std::ios::beg);
            while(file.good() && !file.eof()){
                file.read(buf, data_instance->bufsize);
                nfile.write(buf, file.gcount());
                copied += file.gcount();
                if(nfile.fail())
                    throw new OSException(dst, "Failed to write.");
            }
            if(copied != size)
                throw new OSException(src, "Failed to copy.");
        }else
            throw new OSException(src, "Failed to open.");
        nfile.flush();
        file.close();
        nfile.close();
    }
}
Exemplo n.º 3
0
void MainWindow::on_load_clicked()
{
    QFile nfile("todolist.txt");

    if(nfile.open(QIODevice::ReadOnly))
    {
        QString nline;
        QTextStream in(&nfile);
        while(!in.atEnd())
        {
            nline = in.readLine();
            ui->textBrowser->append(nline);
        }
    }
}
Exemplo n.º 4
0
void MainWindow::on_Enter_clicked()
{
    todolist = ui->lineEdit->text();
    totaltoString = datetoString + '\0' + timetoString  + '\0' + todolist;
    ui->textBrowser->append(totaltoString);


    clock = new QTimer;
    clock->setInterval(1000);
    connect(clock, SIGNAL(timeout()), this, SLOT(updateTime()));

    current_time = current_time.currentTime();
    clock->start();

    QFile nfile("todolist.txt");
    if(nfile.open(QFile::Append|QFile::Text))
    {
        QTextStream out(&nfile);
        out << totaltoString << endl;
    }
}
Exemplo n.º 5
0
Arquivo: lpr.c Projeto: ryo/netbsd-src
/*
 * Create the file n and copy from file descriptor f.
 */
static void
copy(int f, const char *n)
{
	int fd, i, nr;
	size_t nc;
	char buf[BUFSIZ];

	if (format == 'p')
		card('T', title ? title : n);
	for (i = 0; i < ncopies; i++)
		card(format, &dfname[inchar-2]);
	card('U', &dfname[inchar-2]);
	card('N', n);
	fd = nfile(dfname);
	nr = nc = 0;
	while ((i = read(f, buf, sizeof buf)) > 0) {
		if (write(fd, buf, i) != i) {
			warn("%s: temp file write error", n);
			break;
		}
		nc += i;
		if (nc >= sizeof buf) {
			nc -= sizeof buf;
			nr++;
			if (MX > 0 && nr > MX) {
				warnx("%s: copy file is too large "
				    "(check :mx:?)\n", n);
				break;
			}
		}
	}
	(void)close(fd);
	if (nc == 0 && nr == 0) 
		printf("%s: %s: empty input file\n", getprogname(),
		    f ? n : "stdin");
	else
		nact++;
}
Exemplo n.º 6
0
bool File::copy(const char* newPath)
{
    File nfile(newPath);

    if(nfile.exists())
        return false;

    int size = this->getSize();
    char cs[size];
    this->open();
    if(!this->isOpen())
        return false;
    this->read(cs, size);
    this->close();

    nfile.openWrite();
    if(!nfile.isOpen())
        return false;
    nfile.write(cs, size);
    nfile.close();

    return true;
}
Exemplo n.º 7
0
/*
 * Create the file n and copy from file descriptor f.
 */
static void
copy(const struct printer *pp, int f, const char n[])
{
	register int fd, i, nr, nc;
	char buf[BUFSIZ];

	if (format == 'p')
		card('T', title ? title : n);
	for (i = 0; i < ncopies; i++)
		card(format, &dfname[inchar-2]);
	card('U', &dfname[inchar-2]);
	card('N', n);
	fd = nfile(dfname);
	nr = nc = 0;
	while ((i = read(f, buf, BUFSIZ)) > 0) {
		if (write(fd, buf, i) != i) {
			printf("%s: %s: temp file write error\n", progname, n);
			break;
		}
		nc += i;
		if (nc >= BUFSIZ) {
			nc -= BUFSIZ;
			nr++;
			if (pp->max_blocks > 0 && nr > pp->max_blocks) {
				printf("%s: %s: copy file is too large\n",
				    progname, n);
				break;
			}
		}
	}
	(void) close(fd);
	if (nc==0 && nr==0)
		printf("%s: %s: empty input file\n", progname,
		    f ? n : "stdin");
	else
		nact++;
}
Exemplo n.º 8
0
bool UserManagerBackend::commit()
{
    
    //Process users
    QMap<QString, User>::Iterator userIt;

    QStringList args;
    
    for ( userIt = userList.begin(); userIt != userList.end(); ++userIt )
    {
	args.clear();
        switch(userIt->getStatus())
        {
            case 1:
                //Modify User
                qDebug() << "Modifying user " << userIt->getUsername();
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "usermod";
                args << userIt->getUsername();
		// Only change home-dir on non-encrypted users
                if ( ! userIt->getEnc() ) {
                  args << "-d";
                  args << userIt->getHome();
		}
                args << "-s";
                args << userIt->getShell();
                args << "-c";
                args << userIt->getFullname();
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                
                if (userIt->getPassword() != "")
                {
		    // Refuse to continue if we are trying to change PW
		    // On an encrypted users homedir
                    if ( userIt->getEnc() ) {
                      qDebug() << "Cannot change encrypted password: "******"Changing password: "******"/tmp/.XXXXXXXX");
  		    if ( rfile.open() ) {
       		      QTextStream stream( &rfile );
      		      stream << userIt->getClearPassword();
    		      rfile.close();
  		    }
		    if ( ! chroot.isEmpty() )
  		      system("cat " + rfile.fileName().toLatin1() + " | chroot " + chroot.toLatin1() + " pw usermod " + userIt->getUsername().toLatin1() + " -h 0 ");
		    else
  		      system("cat " + rfile.fileName().toLatin1() + " | pw usermod " + userIt->getUsername().toLatin1() + " -h 0 ");

  		    rfile.remove();
                }
                break;
            case 2:
	    {
                //Add User
                qDebug() << "Adding user " << userIt->getUsername();
		// Create the new home-directory
		if ( chroot.isEmpty() ) {
		   system("/usr/local/share/pcbsd/scripts/mkzfsdir.sh " + userIt->getHome().toLatin1() );
		   system("pw groupadd " + userIt->getUsername().toLatin1() );
		} else {
		   system("mkdir -p " + chroot.toLatin1() + "/" + userIt->getHome().toLatin1() + " 2>/dev/null" );
		   system("chroot " + chroot.toLatin1() + " ln -s /usr/home /home 2>/dev/null" );
		   system("chroot " + chroot.toLatin1() + " pw groupadd " + userIt->getUsername().toLatin1() );
		}

		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "useradd";
                args << userIt->getUsername();
                args << "-c";
                args << userIt->getFullname();
		args << "-m";
                args << "-d";
                args << userIt->getHome();
                args << "-s";
                args << userIt->getShell();
                if (userIt->getGid() != -1)
                {
                    args << "-g";
                    args << QString::number(userIt->getGid());
		} else {
                    args << "-g";
                    args << userIt->getUsername();
                }
                args << "-G";
                args << "operator";
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);

    		QTemporaryFile nfile("/tmp/.XXXXXXXX");
  		if ( nfile.open() ) {
       		  QTextStream stream( &nfile );
      		  stream << userIt->getClearPassword();
    		  nfile.close();
  		}
		if ( ! chroot.isEmpty() )
  		  system("cat " + nfile.fileName().toLatin1() + " | chroot " + chroot.toLatin1() + " pw usermod " + userIt->getUsername().toLatin1() + " -h 0 ");
		else
  		  system("cat " + nfile.fileName().toLatin1() + " | pw usermod " + userIt->getUsername().toLatin1() + " -h 0 ");
  	        nfile.remove();

		if ( chroot.isEmpty() ) {
		   qDebug() << "Enabling Flash Plugin for " << userIt->getUsername();
		   QString flashCmd = "su " + userIt->getUsername() + " -c \"flashpluginctl on\"";
		   system(flashCmd.toLatin1());
		}

		// Set permissions
		if ( chroot.isEmpty() )
		   system("chown -R " + userIt->getUsername().toLatin1() +":" + userIt->getUsername().toLatin1() + " "  + userIt->getHome().toLatin1() );
		else
		   system("chroot " + chroot.toLatin1() + " chown -R " + userIt->getUsername().toLatin1() +":" + userIt->getUsername().toLatin1() + " "  + userIt->getHome().toLatin1() );

		// Are we enabling encryption?
		if ( userIt->getEnc() ) {
		   QProcess::execute("enable_user_pefs", QStringList() << userIt->getUsername() << userIt->getClearPassword() );

		}

                break;
	    }
            case 3:
                //Delete User
                qDebug() << "Deleting user " << userIt->getUsername();

                if(userIt->getEnc()) {
		  // Unmount PEFS
	  	  system("umount " + userIt->getHome().toLatin1() );
		}
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "userdel";
                args << userIt->getUsername();
                if(userIt->getDeleteHome()) {
			args << "-r";
			system("/usr/local/share/pcbsd/scripts/rmzfsdir.sh " + userIt->getHome().toLatin1() );
		}
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                break;
        }
    }
    refreshUsers();
    
    //Process groups
    QMap<int, Group>::Iterator groupIt;
 
    for ( groupIt = groupList.begin(); groupIt != groupList.end(); ++groupIt )
    {
	args.clear();
        switch(groupIt->getStatus())
        {
            case 1:
                //Modify Group
                qDebug() << "Modifying group " << groupIt->getGroupname();
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
		args << "groupmod";
		args << groupIt->getGroupname();
		args << "-M";
		args << groupIt->getMembers().join(",");
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                break;
            case 2:
                //Add Group
                qDebug() << "Adding group " << groupIt->getGroupname();
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "groupadd";
                args << groupIt->getGroupname();
                args << "-M";
                args << groupIt->getMembers().join(",");
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                break;
            case 3:
                //Delete Group
                qDebug() << "Deleting group " << groupIt->getGroupname();
		if ( ! chroot.isEmpty() )
		   args << chroot << "pw";
                args << "groupdel";
                args << groupIt->getGroupname();
		if ( ! chroot.isEmpty() )
		   QProcess::execute("chroot", args);
		else
		   QProcess::execute("pw", args);
                break;
	}
    }
    refreshGroups();
    emit groupsChanged();
    emit usersChanged();
    
    return true;
}
Exemplo n.º 9
0
int
main(int argc, char *argv[])
{
	struct passwd *pw;
	struct group *gptr;
	const char *arg, *cp, *printer;
	char *p;
	char buf[BUFSIZ];
	int c, i, f, errs;
	int	 ret, didlink;
	struct stat stb;
	struct stat statb1, statb2;
	struct printer myprinter, *pp = &myprinter;

	printer = NULL;
	euid = geteuid();
	uid = getuid();
	PRIV_END
	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, cleanup);
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, cleanup);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
		signal(SIGQUIT, cleanup);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, cleanup);

	progname = argv[0];
	gethostname(local_host, sizeof(local_host));
	openlog("lpd", 0, LOG_LPR);

	errs = 0;
	while ((c = getopt(argc, argv,
			   ":#:1:2:3:4:C:J:L:P:T:U:Z:cdfghi:lnmprstvw:"))
	       != -1)
		switch (c) {
		case '#':		/* n copies */
			i = strtol(optarg, &p, 10);
			if (*p)
				errx(1, "Bad argument to -#, number expected");
			if (i > 0)
				ncopies = i;
			break;

		case '1':		/* troff fonts */
		case '2':
		case '3':
		case '4':
			fonts[optopt - '1'] = optarg;
			break;

		case 'C':		/* classification spec */
			hdr++;
			class = optarg;
			break;

		case 'J':		/* job name */
			hdr++;
			jobname = optarg;
			break;

		case 'P':		/* specifiy printer name */
			printer = optarg;
			break;

		case 'L':               /* pr's locale */
			locale = optarg;
			break;

		case 'T':		/* pr's title line */
			title = optarg;
			break;

		case 'U':		/* user name */
			hdr++;
			Uflag = optarg;
			break;

		case 'Z':
			Zflag = optarg;
			break;

		case 'c':		/* print cifplot output */
		case 'd':		/* print tex output (dvi files) */
		case 'g':		/* print graph(1G) output */
		case 'l':		/* literal output */
		case 'n':		/* print ditroff output */
		case 't':		/* print troff output (cat files) */
		case 'p':		/* print using ``pr'' */
		case 'v':		/* print vplot output */
			format = optopt;
			break;

		case 'f':		/* print fortran output */
			format = 'r';
			break;

		case 'h':		/* nulifiy header page */
			hdr = 0;
			break;

		case 'i':		/* indent output */
			iflag++;
			indent = strtol(optarg, &p, 10);
			if (*p)
				errx(1, "Bad argument to -i, number expected");
			break;

		case 'm':		/* send mail when done */
			mailflg++;
			break;

		case 'q':		/* just queue job */
			qflag++;
			break;

		case 'r':		/* remove file when done */
			rflag++;
			break;

		case 's':		/* try to link files */
			sflag++;
			break;

		case 'w':		/* versatec page width */
			width = optarg;
			break;

		case ':':		/* catch "missing argument" error */
			if (optopt == 'i') {
				iflag++; /* -i without args is valid */
				indent = 8;
			} else
				errs++;
			break;

		default:
			errs++;
		}
	argc -= optind;
	argv += optind;
	if (errs)
		usage();
	if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;
	chkprinter(printer, pp);
	if (pp->no_copies && ncopies > 1)
		errx(1, "multiple copies are not allowed");
	if (pp->max_copies > 0 && ncopies > pp->max_copies)
		errx(1, "only %ld copies are allowed", pp->max_copies);
	/*
	 * Get the identity of the person doing the lpr using the same
	 * algorithm as lprm.  Actually, not quite -- lprm will override
	 * the login name with "root" if the user is running as root;
	 * the daemon actually checks for the string "root" in its
	 * permission checking.  Sigh.
	 */
	userid = getuid();
	if (Uflag) {
		if (userid != 0 && userid != pp->daemon_user)
			errx(1, "only privileged users may use the `-U' flag");
		lpr_username = Uflag;		/* -U person doing 'lpr' */
	} else {
		lpr_username = getlogin();	/* person doing 'lpr' */
		if (userid != pp->daemon_user || lpr_username == 0) {
			if ((pw = getpwuid(userid)) == NULL)
				errx(1, "Who are you?");
			lpr_username = pw->pw_name;
		}
	}

	/*
	 * Check for restricted group access.
	 */
	if (pp->restrict_grp != NULL && userid != pp->daemon_user) {
		if ((gptr = getgrnam(pp->restrict_grp)) == NULL)
			errx(1, "Restricted group specified incorrectly");
		if (gptr->gr_gid != getgid()) {
			while (*gptr->gr_mem != NULL) {
				if ((strcmp(lpr_username, *gptr->gr_mem)) == 0)
					break;
				gptr->gr_mem++;
			}
			if (*gptr->gr_mem == NULL)
				errx(1, "Not a member of the restricted group");
		}
	}
	/*
	 * Check to make sure queuing is enabled if userid is not root.
	 */
	lock_file_name(pp, buf, sizeof buf);
	if (userid && stat(buf, &stb) == 0 && (stb.st_mode & LFM_QUEUE_DIS))
		errx(1, "Printer queue is disabled");
	/*
	 * Initialize the control file.
	 */
	mktemps(pp);
	tfd = nfile(tfname);
	PRIV_START
	(void) fchown(tfd, pp->daemon_user, -1);
	/* owned by daemon for protection */
	PRIV_END
	card('H', local_host);
	card('P', lpr_username);
	card('C', class);
	if (hdr && !pp->no_header) {
		if (jobname == NULL) {
			if (argc == 0)
				jobname = "stdin";
			else
				jobname = ((arg = strrchr(argv[0], '/'))
					   ? arg + 1 : argv[0]);
		}
		card('J', jobname);
		card('L', lpr_username);
	}
	if (format != 'p' && Zflag != 0)
		card('Z', Zflag);
	if (iflag)
		card('I', itoa(indent));
	if (mailflg)
		card('M', lpr_username);
	if (format == 't' || format == 'n' || format == 'd')
		for (i = 0; i < 4; i++)
			if (fonts[i] != NULL)
				card('1'+i, fonts[i]);
	if (width != NULL)
		card('W', width);
	/*
	 * XXX
	 * Our use of `Z' here is incompatible with LPRng's
	 * use.  We assume that the only use of our existing
	 * `Z' card is as shown for `p' format (pr) files.
	 */
	if (format == 'p') {
		char *s;

		if (locale)
			card('Z', locale);
		else if ((s = setlocale(LC_TIME, "")) != NULL)
			card('Z', s);
	}

	/*
	 * Read the files and spool them.
	 */
	if (argc == 0)
		copy(pp, 0, " ");
	else while (argc--) {
		if (argv[0][0] == '-' && argv[0][1] == '\0') {
			/* use stdin */
			copy(pp, 0, " ");
			argv++;
			continue;
		}
		if ((f = test(arg = *argv++)) < 0)
			continue;	/* file unreasonable */

		if (sflag && (cp = linked(arg)) != NULL) {
			(void)snprintf(buf, sizeof(buf), "%ju %ju",
			    (uintmax_t)statb.st_dev, (uintmax_t)statb.st_ino);
			card('S', buf);
			if (format == 'p')
				card('T', title ? title : arg);
			for (i = 0; i < ncopies; i++)
				card(format, &dfname[inchar-2]);
			card('U', &dfname[inchar-2]);
			if (f)
				card('U', cp);
			card('N', arg);
			dfname[inchar]++;
			nact++;
			continue;
		}
		if (sflag)
			printf("%s: %s: not linked, copying instead\n",
			    progname, arg);

		if (f) {
			/*
			 * The user wants the file removed after it is copied
			 * to the spool area, so see if the file can be moved
			 * instead of copy/unlink'ed.  This is much faster and
			 * uses less spool space than copying the file.  This
			 * can be very significant when running services like
			 * samba, pcnfs, CAP, et al.
			 */
			PRIV_START
			didlink = 0;
			/*
			 * There are several things to check to avoid any
			 * security issues.  Some of these are redundant
			 * under BSD's, but are necessary when lpr is built
			 * under some other OS's (which I do do...)
			 */
			if (lstat(arg, &statb1) < 0)
				goto nohardlink;
			if (S_ISLNK(statb1.st_mode))
				goto nohardlink;
			if (link(arg, dfname) != 0)
				goto nohardlink;
			didlink = 1;
			/*
			 * Make sure the user hasn't tried to trick us via
			 * any race conditions
			 */
			if (lstat(dfname, &statb2) < 0)
				goto nohardlink;
			if (statb1.st_dev != statb2.st_dev)
				goto nohardlink;
			if (statb1.st_ino != statb2.st_ino)
				goto nohardlink;
			/*
			 * Skip if the file already had multiple hard links,
			 * because changing the owner and access-bits would
			 * change ALL versions of the file
			 */
			if (statb2.st_nlink > 2)
				goto nohardlink;
			/*
			 * If we can access and remove the original file
			 * without special setuid-ness then this method is
			 * safe.  Otherwise, abandon the move and fall back
			 * to the (usual) copy method.
			 */
			PRIV_END
			ret = access(dfname, R_OK);
			if (ret == 0)
				ret = unlink(arg);
			PRIV_START
			if (ret != 0)
				goto nohardlink;
			/*
			 * Unlink of user file was successful.  Change the
			 * owner and permissions, add entries to the control
			 * file, and skip the file copying step.
			 */
			chown(dfname, pp->daemon_user, getegid());
			chmod(dfname, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
			PRIV_END
			if (format == 'p')
				card('T', title ? title : arg);
			for (i = 0; i < ncopies; i++)
				card(format, &dfname[inchar-2]);
			card('U', &dfname[inchar-2]);
			card('N', arg);
			nact++;
			continue;
		nohardlink:
			if (didlink)
				unlink(dfname);
			PRIV_END           /* restore old uid */
		} /* end: if (f) */

		if ((i = open(arg, O_RDONLY)) < 0) {
			printf("%s: cannot open %s\n", progname, arg);
		} else {
			copy(pp, i, arg);
			(void) close(i);
			if (f && unlink(arg) < 0)
				printf("%s: %s: not removed\n", progname, arg);
		}
	}

	if (nact) {
		(void) close(tfd);
		tfname[inchar]--;
		/*
		 * Touch the control file to fix position in the queue.
		 */
		PRIV_START
		if ((tfd = open(tfname, O_RDWR)) >= 0) {
			char touch_c;

			if (read(tfd, &touch_c, 1) == 1 &&
			    lseek(tfd, (off_t)0, 0) == 0 &&
			    write(tfd, &touch_c, 1) != 1) {
				printf("%s: cannot touch %s\n", progname,
				    tfname);
				tfname[inchar]++;
				cleanup(0);
			}
			(void) close(tfd);
		}
		if (link(tfname, cfname) < 0) {
			printf("%s: cannot rename %s\n", progname, cfname);
			tfname[inchar]++;
			cleanup(0);
		}
		unlink(tfname);
		PRIV_END
		if (qflag)		/* just q things up */
			exit(0);
		if (!startdaemon(pp))
			printf("jobs queued, but cannot start daemon.\n");
		exit(0);
	}
	cleanup(0);
	return (1);
	/* NOTREACHED */
}
Exemplo n.º 10
0
Arquivo: lpr.c Projeto: ryo/netbsd-src
int
main(int argc, char *argv[])
{
	struct passwd *pw;
	struct group *gptr;
	char *arg;
	const char *cp;
	char buf[MAXPATHLEN];
	int i, f, errs, c;
	struct stat stb;
	int oerrno;

	euid = geteuid();
	uid = getuid();
	seteuid(uid);

	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, cleanup);
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, cleanup);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
		signal(SIGQUIT, cleanup);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, cleanup);

	setprogname(*argv);
	gethostname(host, sizeof (host));
	host[sizeof(host) - 1] = '\0';
	openlog("lpd", 0, LOG_LPR);

	errs = 0;
	while ((c = getopt(argc, argv,
	    ":#:1:2:3:4:C:J:P:RT:U:cdfghi:lmnopqrstvw:")) != -1) {
		switch (c) {

		case '#':		/* n copies */
			if (isdigit((unsigned char)*optarg)) {
				i = atoi(optarg);
				if (i > 0)
					ncopies = i;
			}
			break;

		case '4':		/* troff fonts */
		case '3':
		case '2':
		case '1':
			fonts[optopt - '1'] = optarg;
			break;

		case 'C':		/* classification spec */
			hdr++;
			class = optarg;
			break;

		case 'J':		/* job name */
			hdr++;
			jobname = optarg;
			break;

		case 'P':		/* specifiy printer name */
			printer = optarg;
			break;

		case 'R':		/* print request id */
			Rflag++;
			break;
			
		case 'T':		/* pr's title line */
			title = optarg;
			break;

		case 'U':		/* user name */
			hdr++;
			person = optarg;
			break;

		case 'c':		/* print cifplot output */
		case 'd':		/* print tex output (dvi files) */
		case 'g':		/* print graph(1G) output */
		case 'l':		/* literal output */
		case 'o':		/* print postscript output */
		case 'n':		/* print ditroff output */
		case 'p':		/* print using ``pr'' */
		case 't':		/* print troff output (cat files) */
		case 'v':		/* print vplot output */
			format = optopt;
			break;

		case 'f':		/* print fortran output */
			format = 'r';
			break;

		case 'h':		/* toggle want of header page */
			hdr = !hdr;
			break;

		case 'i':		/* indent output */
			iflag++;
			indent = atoi(optarg);
			if (indent < 0)
				indent = 8;
			break;

		case 'm':		/* send mail when done */
			mailflg++;
			break;

		case 'q':		/* just q job */
			qflag++;
			break;

		case 'r':		/* remove file when done */
			rflag++;
			break;

		case 's':		/* try to link files */
			sflag++;
			break;

		case 'w':		/* versatec page width */
			width = optarg;
			break;

		case ':':               /* catch "missing argument" error */
			if (optopt == 'i') {
				iflag++; /* -i without args is valid */
				indent = 8;
			} else
				errs++;
			break;

		default:
			errs++;
		}
	}
	argc -= optind;
	argv += optind;
	if (errs)
		usage();
	if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;
	chkprinter(printer);
	if (SC && ncopies > 1)
		errx(EXIT_FAILURE, "multiple copies are not allowed");
	if (MC > 0 && ncopies > MC)
		errx(EXIT_FAILURE, "only %ld copies are allowed", MC);
	/*
	 * Get the identity of the person doing the lpr using the same
	 * algorithm as lprm. 
	 */
	userid = getuid();
	if (userid != DU || person == 0) {
		if ((pw = getpwuid(userid)) == NULL)
			errx(EXIT_FAILURE, "Who are you?");
		person = pw->pw_name;
	}
	/*
	 * Check for restricted group access.
	 */
	if (RG != NULL && userid != DU) {
		if ((gptr = getgrnam(RG)) == NULL)
			errx(EXIT_FAILURE,
			     "Restricted group specified incorrectly");
		if (gptr->gr_gid != getgid()) {
			while (*gptr->gr_mem != NULL) {
				if ((strcmp(person, *gptr->gr_mem)) == 0)
					break;
				gptr->gr_mem++;
			}
			if (*gptr->gr_mem == NULL)
				errx(EXIT_FAILURE,
				     "Not a member of the restricted group");
		}
	}
	/*
	 * Check to make sure queuing is enabled if userid is not root.
	 */
	(void)snprintf(buf, sizeof buf, "%s/%s", SD, LO);
	if (userid && stat(buf, &stb) == 0 && (stb.st_mode & S_IXGRP))
		errx(EXIT_FAILURE, "Printer queue is disabled");
	/*
	 * Initialize the control file.
	 */
	mktemps();
	tfd = nfile(tfname);
	seteuid(euid);
	(void)fchown(tfd, DU, -1);	/* owned by daemon for protection */
	seteuid(uid);
	card('H', host);
	card('P', person);
	if (hdr && !SH) {
		if (jobname == NULL) {
			if (argc == 0)
				jobname = "stdin";
			else
				jobname = (arg = strrchr(argv[0], '/')) ?
				    arg+1 : argv[0];
		}
		card('J', jobname);
		card('C', class);
		card('L', person);
	}
	if (iflag)
		card('I', itoa(indent));
	if (mailflg)
		card('M', person);
	if (format == 't' || format == 'n' || format == 'd')
		for (i = 0; i < 4; i++)
			if (fonts[i] != NULL)
				card('1'+i, fonts[i]);
	if (width != NULL)
		card('W', width);

	/*
	 * Read the files and spool them.
	 */
	if (argc == 0)
		copy(0, " ");
	else while (argc--) {
		if (argv[0][0] == '-' && argv[0][1] == '\0') {
			/* use stdin */
			copy(0, " ");
			argv++;
			continue;
		}
		if ((f = test(arg = *argv++)) < 0)
			continue;	/* file unreasonable */

		if (sflag && (cp = linked(arg)) != NULL) {
			(void)snprintf(buf, sizeof buf,
			    "%llu %llu",
			    (unsigned long long)statb.st_dev,
			    (unsigned long long)statb.st_ino);
			card('S', buf);
			if (format == 'p')
				card('T', title ? title : arg);
			for (i = 0; i < ncopies; i++)
				card(format, &dfname[inchar-2]);
			card('U', &dfname[inchar-2]);
			if (f)
				card('U', cp);
			card('N', arg);
			dfname[inchar]++;
			nact++;
			continue;
		}
		if (sflag)
			warnx("%s: not linked, copying instead", arg);
		seteuid(uid);
		if ((i = open(arg, O_RDONLY)) < 0) {
			oerrno = errno;
			seteuid(uid);
			errno = oerrno;
			warn("cannot open %s", arg);
			continue;
		} else {
			copy(i, arg);
			(void)close(i);
			if (f && unlink(arg) < 0)
				warn("%s: not removed", arg);
		}
		seteuid(uid);
	}

	if (nact) {
		(void)close(tfd);
		tfname[inchar]--;
		/*
		 * Touch the control file to fix position in the queue.
		 */
		seteuid(euid);
		if ((tfd = open(tfname, O_RDWR)) >= 0) {
			char ch;

			if (read(tfd, &ch, 1) == 1 &&
			    lseek(tfd, (off_t)0, 0) == 0 &&
			    write(tfd, &ch, 1) != 1) {
				warn("cannot touch %s", tfname);
				tfname[inchar]++;
				cleanup(0);
			}
			(void)close(tfd);
		}
		if (link(tfname, cfname) < 0) {
			warn("cannot rename %s", cfname);
			tfname[inchar]++;
			cleanup(0);
		}
		unlink(tfname);
		seteuid(uid);
		if (Rflag)
			printf("request id is %d\n", reqid);
		if (qflag)		/* just queue things up */
			exit(0);
		if (!startdaemon(printer))
			printf("jobs queued, but cannot start daemon.\n");
		exit(0);
	}
	cleanup(0);
#ifdef __GNUC__
	return (0);
#endif
	/* NOTREACHED */
}
Exemplo n.º 11
0
int
main(int argc, char **argv)
{
	struct passwd *pw;
	struct group *gptr;
	char *arg, *cp;
	char buf[MAXPATHLEN];
	int i, f, ch;
	struct stat stb;

	/*
	 * Simulate setuid daemon w/ PRIV_END called.
	 * We don't want lpr to actually be setuid daemon since that
	 * requires that the lpr binary be owned by user daemon, which
	 * is potentially unsafe.
	 */
	if ((pw = getpwuid(DEFUID)) == NULL)
		errx(1, "daemon uid (%u) not in password file", DEFUID);
	effective_uid = pw->pw_uid;
	real_uid = getuid();
	effective_gid = pw->pw_gid;
	real_gid = getgid();
	setresgid(real_gid, real_gid, effective_gid);
	setresuid(real_uid, real_uid, effective_uid);

	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, cleanup);
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, cleanup);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
		signal(SIGQUIT, cleanup);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, cleanup);

	gethostname(host, sizeof (host));
	openlog("lpr", 0, LOG_LPR);

	while ((ch = getopt(argc, argv,
	    ":#:1:2:3:4:C:J:P:T:U:cdfghi:lmnpqrstvw:")) != -1) {
		switch (ch) {

		case '#':		/* n copies */
			if (isdigit((unsigned char)*optarg)) {
				i = atoi(optarg);
				if (i > 0)
					ncopies = i;
			}
			break;

		case '4':		/* troff fonts */
		case '3':
		case '2':
		case '1':
			fonts[ch - '1'] = optarg;
			break;

		case 'C':		/* classification spec */
			hdr++;
			class = optarg;
			break;

		case 'J':		/* job name */
			hdr++;
			jobname = optarg;
			break;

		case 'P':		/* specifiy printer name */
			printer = optarg;
			break;

		case 'T':		/* pr's title line */
			title = optarg;
			break;

		case 'U':		/* user name */
			hdr++;
			person = optarg;
			break;

		case 'c':		/* print cifplot output */
		case 'd':		/* print tex output (dvi files) */
		case 'g':		/* print graph(1G) output */
		case 'l':		/* literal output */
		case 'n':		/* print ditroff output */
		case 'p':		/* print using ``pr'' */
		case 't':		/* print troff output (cat files) */
		case 'v':		/* print vplot output */
			format = ch;
			break;

		case 'f':		/* print fortran output */
			format = 'r';
			break;

		case 'h':		/* toggle want of header page */
			hdr = !hdr;
			break;

		case 'i':		/* indent output */
			iflag++;
			indent = atoi(optarg);
			if (indent < 0)
				indent = 8;
			break;

		case 'm':		/* send mail when done */
			mailflg++;
			break;

		case 'q':		/* just q job */
			qflag++;
			break;

		case 'r':		/* remove file when done */
			rflag++;
			break;

		case 's':		/* try to link files */
			sflag++;
			break;

		case 'w':		/* versatec page width */
			width = optarg;
			break;

		case ':':               /* catch "missing argument" error */
			if (optopt == 'i') {
				iflag++; /* -i without args is valid */
				indent = 8;
			} else
				usage();
			break;

		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;
	if (printer == NULL && (printer = getenv("PRINTER")) == NULL)
		printer = DEFLP;
	chkprinter(printer);
	if (SC && ncopies > 1)
		errx(1, "multiple copies are not allowed");
	if (MC > 0 && ncopies > MC)
		errx(1, "only %ld copies are allowed", MC);
	/*
	 * Get the identity of the person doing the lpr using the same
	 * algorithm as lprm. 
	 */
	if (real_uid != DU || person == NULL) {
		if ((pw = getpwuid(real_uid)) == NULL)
			errx(1, "Who are you?");
		if ((person = strdup(pw->pw_name)) == NULL)
			err(1, NULL);
	}
	/*
	 * Check for restricted group access.
	 */
	if (RG != NULL && real_uid != DU) {
		if ((gptr = getgrnam(RG)) == NULL)
			errx(1, "Restricted group specified incorrectly");
		if (gptr->gr_gid != getgid()) {
			while (*gptr->gr_mem != NULL) {
				if ((strcmp(person, *gptr->gr_mem)) == 0)
					break;
				gptr->gr_mem++;
			}
			if (*gptr->gr_mem == NULL)
				errx(1, "Not a member of the restricted group");
		}
	}
	/*
	 * Check to make sure queuing is enabled if real_uid is not root.
	 */
	(void)snprintf(buf, sizeof(buf), "%s/%s", SD, LO);
	if (real_uid && stat(buf, &stb) == 0 && (stb.st_mode & 010))
		errx(1, "Printer queue is disabled");
	/*
	 * Initialize the control file.
	 */
	mktemps();
	tfd = nfile(tfname);
	card('H', host);
	card('P', person);
	if (hdr) {
		if (jobname == NULL) {
			if (argc == 0)
				jobname = "stdin";
			else
				jobname = (arg = strrchr(argv[0], '/')) ?
				    arg + 1 : argv[0];
		}
		card('J', jobname);
		card('C', class);
		if (!SH)
			card('L', person);
	}
	if (iflag)
		card('I', itoa(indent));
	if (mailflg)
		card('M', person);
	if (format == 't' || format == 'n' || format == 'd')
		for (i = 0; i < 4; i++)
			if (fonts[i] != NULL)
				card('1'+i, fonts[i]);
	if (width != NULL)
		card('W', width);

	/*
	 * Read the files and spool them.
	 */
	if (argc == 0)
		copy(0, " ");
	else while (argc--) {
		if (argv[0][0] == '-' && argv[0][1] == '\0') {
			/* use stdin */
			copy(0, " ");
			argv++;
			continue;
		}
		if ((f = test(arg = *argv++)) < 0)
			continue;	/* file unreasonable */

		if (sflag && (cp = linked(arg)) != NULL) {
			(void)snprintf(buf, sizeof(buf), "%d %llu",
			    statb.st_dev, (unsigned long long)statb.st_ino);
			card('S', buf);
			if (format == 'p')
				card('T', title ? title : arg);
			for (i = 0; i < ncopies; i++)
				card(format, &dfname[inchar-2]);
			card('U', &dfname[inchar-2]);
			if (f)
				card('U', cp);
			card('N', arg);
			dfname[inchar]++;
			nact++;
			continue;
		}
		if (sflag)
			warnx("%s: not linked, copying instead", arg);
		if ((i = safe_open(arg, O_RDONLY, 0)) < 0)
			warn("%s", arg);
		else {
			copy(i, arg);
			(void)close(i);
			if (f && unlink(arg) < 0)
				warnx("%s: not removed", arg);
		}
	}

	if (nact) {
		(void)close(tfd);
		tfname[inchar]--;
		/*
		 * Touch the control file to fix position in the queue.
		 */
		PRIV_START;
		if ((tfd = safe_open(tfname, O_RDWR|O_NOFOLLOW, 0)) >= 0) {
			char c;

			if (read(tfd, &c, 1) == 1 &&
			    lseek(tfd, (off_t)0, SEEK_SET) == 0 &&
			    write(tfd, &c, 1) != 1) {
				warn("%s", tfname);
				tfname[inchar]++;
				cleanup(0);
			}
			(void)close(tfd);
		}
		if (link(tfname, cfname) < 0) {
			warn("cannot rename %s", cfname);
			tfname[inchar]++;
			cleanup(0);
		}
		unlink(tfname);
		PRIV_END;
		if (qflag)		/* just q things up */
			exit(0);
		if (!startdaemon(printer))
			printf("jobs queued, but cannot start daemon.\n");
		exit(0);
	}
	cleanup(0);
	return (1);
	/* NOTREACHED */
}
Exemplo n.º 12
0
Arquivo: look.C Projeto: elaird/nuqe
void NUANCE_compare(Int_t mode,Int_t energy_point,TString file,bool antinu=false) {
  Init();

  //mine
  TFile f(file);
  gROOT->cd();
  TTree *tree=(TTree*)f.Get("tree");
  TGraph *gr=(TGraph*)f.Get("ccqe_rate")->Clone();
  Int_t process=4;
  Double_t xs,dummy;
  gr->GetPoint(process,dummy,xs);
  delete gr;

  //NUANCE
  /*argh--chains are unusable in this ROOT version*/
  Int_t N_files=0;
  if (energy_point== 300) N_files=40;
  if (energy_point== 800) N_files=20;
  if (energy_point==1200) N_files=40;

  TString *tree_var=0;
  TString *nuance_var=0;
  TCut *nuance_cut=0;
  TString *label=0;

  Int_t N_bins=0;
  Double_t lower=0.0;
  Double_t upper=0.0;
  Double_t x_leg=0.0;

  switch (mode) {
  case 1:
    tree_var=new TString("kprime[0]");
    nuance_var=new TString("p_lepton[0][3]/1.0e3");
    nuance_cut=new TCut("cc && bound && channel==1");
    label=new TString(";E_{#mu} (GeV);d#sigma/dE_{#mu} (cm^{2}/GeV)");
    
    x_leg=0.15;
    N_bins=250;
    lower=0.12;
    upper=energy_point/1.0e3;
    break;
  case 2:
    tree_var=new TString("-q[0]**2+q[1]**2+q[2]**2+q[3]**2");
    nuance_var=new TString("-qsq/1.0e6");
    nuance_cut=new TCut("cc && bound && channel==1");
    label=new TString(";Q^{2} (GeV^{2});d#sigma/dQ^{2} (cm^{2}/GeV^{2})");

    x_leg=0.55;
    N_bins=250;
    lower=0.0;
    if (energy_point==300) upper=0.8;
    if (energy_point==800) upper=1.4;
    break;
  case 3:
    tree_var=new TString("mag_p");
    nuance_var=new TString("p_targ[4]/1.0e3");
    nuance_cut=new TCut("cc && bound && channel==1");
    label=new TString(";p_{i} (GeV/c);d#sigma/dp_{i} (cm^{2}/(GeV/c))");

    x_leg=0.15;
    N_bins=150;
    lower=0.0;
    upper=0.25;
    break;
  case 4:
    tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)");
    nuance_var=new TString("p_hadron[][4]/1.0e3");
    nuance_cut=new TCut("cc && bound && channel==1 && n_hadrons==1 && n_leptons==1");
    label=new TString(";p_{f} (GeV/c);d#sigma/dp_{f} (cm^{2}/(GeV/c))");

    x_leg=0.15;
    N_bins=150;
    lower=0.0;
    upper=0.8;
    break;
  case 5:
    tree_var=new TString("sqrt(pprime[1]**2+pprime[2]**2+pprime[3]**2)");
    nuance_var=new TString("sqrt((p_neutrino[0]-p_lepton[0][0]+p_targ[0])**2+(p_neutrino[1]-p_lepton[0][1]+p_targ[1])**2+(p_neutrino[2]-p_lepton[0][2]+p_targ[2])**2)/1.0e3");
    nuance_cut=new TCut("cc && bound && channel==1 && n_leptons==1");
    label=new TString(";p_{f} (GeV/c);d#sigma/dp_{f} (cm^{2}/(GeV/c))");

    x_leg=0.15;
    N_bins=150;
    lower=0.2;
    upper=0.6;
    //lower=0.2;
    //upper=1.3;
    break;
  }

  TCanvas canvas("canvas","",700,1000);
  canvas.Divide(1,2);
  canvas.cd(1);

  TH1D nh("nh",*label,N_bins,lower,upper);
  nh.Sumw2();
  nh.SetStats(kFALSE);

  for (Int_t iFile=0;iFile<N_files;iFile++) {
    TString file;
    if (energy_point== 300           ) file=Form("../../nuance_from_fnal/oxnofp3/nuance%d.root",iFile+1);
    if (energy_point== 800 && !antinu) file=Form("../../nuance_from_fnal/oxyg_no_fp2/nuance%d.root",iFile+1);
    if (energy_point== 800 &&  antinu) file=Form("../../nuance_from_fnal/antinumu_oxygen_dipole_800/nuance%d.root",iFile+1);
    if (energy_point==1200           ) file=Form("../../nuance_from_fnal/numu_oxygen_dipole_1200/nuance%d.root",iFile+1);

    TFile nfile(file);
    gROOT->cd();
    TTree *ntree=(TTree*)nfile.Get("h3");
    ntree->Draw(*nuance_var+">>+nh",*nuance_cut,"goff");
    nfile.Close();
  }
  if (energy_point== 300           ) nh.Scale(0.0033647*8*1.0e-36/nh.Integral("width"));
  if (energy_point== 800 && !antinu) nh.Scale(0.0093045*8*1.0e-36/nh.Integral("width"));
  if (energy_point== 800 &&  antinu) nh.Scale(0.0027100*8*1.0e-36/nh.Integral("width"));
  if (energy_point==1200           ) nh.Scale(0.0100135*8*1.0e-36/nh.Integral("width"));
  nh.Draw("e");

  TH1D *contribs=new TH1D("contribs",*label,N_bins,lower,upper);
  
  Int_t NHistos=1;
  Int_t base_index=0;
  TH1D *h[NHistos];
  for (Int_t iHisto=0;iHisto<NHistos;iHisto++) {
    h[iHisto]=new TH1D(Form("h%d",iHisto),*label,N_bins,lower,upper);
    h[iHisto]->Sumw2();
  }
  
  Int_t color=2;
  Double_t factor=1.0;
  for (Int_t iHisto=0;iHisto<NHistos;iHisto++) {
    tree->Draw(*tree_var+Form(">>h%d",iHisto),Form("(MA_weights[%d]) * (process==%d)",iHisto,process),"goff");
    if (iHisto==0) factor=xs/h[0]->Integral("width");
    h[iHisto]->Scale(factor);
    h[iHisto]->SetStats(kFALSE);
    h[iHisto]->GetXaxis()->CenterTitle();
    h[iHisto]->GetYaxis()->CenterTitle();
    h[iHisto]->GetYaxis()->SetTitleOffset(1.2);
    h[iHisto]->SetLineColor(color);
    h[iHisto]->SetMarkerColor(color);
    if (++color==5) color++;
    h[iHisto]->Draw("esame"); 
    h[iHisto]->Print();
  }
  TString legendtitle;
  if (!antinu) legendtitle=Form("#nu_{#mu} + ^{16}O #rightarrow #mu + p + X (E_{#nu}=%d MeV)",energy_point);
  if ( antinu) legendtitle=Form("#bar{#nu}_{#mu} + ^{16}O #rightarrow #mu + n + X (E_{#nu}=%d MeV)",energy_point);

  TLegend legend(x_leg,0.7,x_leg+0.45,0.9,legendtitle);
  legend.SetBorderSize(0);
  legend.SetFillStyle(0);
  //legend.SetHeader("S-M, dipole, FP=0");
  legend.AddEntry(h[base_index],"my generated events (NUANCE mode)");
  legend.AddEntry(&nh,"NUANCE");
  legend.Draw("same");
  
  chi2_compare(h[base_index],&nh,1,N_bins,contribs);
  
  //TLatex text(0.20,0.92,comp_str);
  //text.SetNDC();
  //text.DrawClone();
  
  canvas.cd(2);
  contribs->Draw();

  canvas.cd(0);
  canvas.DrawClone();

  f.Close();

  delete tree_var;
  delete nuance_var;
  delete nuance_cut;
  delete label;
  delete contribs;
  
  for (Int_t iHisto=0;iHisto<NHistos;iHisto++) {
    delete h[iHisto];
  }

}