Example #1
0
void SparseMatrix::Randomise ()
{
  for (int lQ = 0; lQ < nrows(); ++lQ)
    for (int rQ = 0; rQ < ncols(); ++rQ)
      if (allowed(lQ, rQ))
	SpinAdapted::Randomise (operator_element(lQ, rQ));
}
Example #2
0
static void showtab(int tab, int expand, token_t * e1, char *fname, int allowed())
{
    int i, t;
    symentry_t *sym;
    
    for (i = 0; i < HSIZE; i++)
	for (sym = EiC_HTAB[i]; sym; sym = sym->next) {

	    if ((t = EiC_gettype(sym->type)) == t_eic || sym->nspace != tab)
		continue;

	    if(e1 && e1->Type && ! EiC_sametypes(e1->Type,sym->type))
		continue;

	    /*printf("looking at [%s]\n",sym->fname);*/
	    if(fname && strcmp(fname,sym->fname) != 0)
		continue;
	    
	    if(allowed && !allowed(t))
		continue;
	    displaySclass(sym);
	    fputs(sym->id, stdout);
	    fputs(" -> ", stdout);
	    EiC_showdectype(sym->type, expand,stdout);
	    fputc('\n', stdout);
	}
}
Example #3
0
void entry_clamp_text(GtkEntry *entry, int length, int setcase, int allowed(char))
{
    const gchar *text;
    gchar *clamped, *ptr_put, *ptr_get;

    text = gtk_entry_get_text(entry);

    switch (setcase) {
    case 1:
        clamped = g_ascii_strup(text, length);
        break;
    case -1:
        clamped = g_ascii_strdown(text, length);
        break;
    default:
        clamped = g_strndup(text, length);
    }

    ptr_put = ptr_get = clamped;
    while (*ptr_get) {
        if (allowed == NULL || allowed(*ptr_get)) {
            *ptr_put = *ptr_get;
            ptr_put++;
        }
        ptr_get++;
    }
    *ptr_put = '\0';

    gtk_entry_set_text(entry, clamped);
    g_free(clamped);
    /* *text need not be freed per gtk_entry_get_text docs */
}
Example #4
0
void
SequenceNumber::slotOk()
{
    if (!allowed("Update")) {
	qApp->beep();
	QString message = tr("Changing data is not allowed");
	QMessageBox::critical(this, tr("Error"), message);
	return;
    }

    // Verify all are valid
    for (unsigned int i = 0; i < _ids.size(); ++i) {
	IdInfo& info = _ids[i];
	fixed minNum = info.minNum->getFixed();
	if (minNum < 1) {
	    error(tr("Invalid minimum number"), info.minNum);
	    return;
	}

	fixed maxNum = info.maxNum->getFixed();
	if (maxNum < 1) {
	    error(tr("Invalid maximum number"), info.maxNum);
	    return;
	}

	fixed nextNum = info.nextNum->getFixed();
	if (nextNum < 1) {
	    error(tr("Invalid next number"), info.nextNum);
	    return;
	}

	if (nextNum < minNum || nextNum > maxNum) {
	    error(tr("Invalid next number"), info.nextNum);
	    return;
	}
    }

    // Set the numbers that have changed
    for (unsigned int i = 0; i < _ids.size(); ++i) {
	IdInfo& info = _ids[i];
	fixed minNum = info.minNum->getFixed();
	fixed maxNum = info.maxNum->getFixed();
	fixed nextNum = info.nextNum->getFixed();

	bool changed = false;
	if (minNum != info.seq.minNumber()) changed = true;
	if (maxNum != info.seq.maxNumber()) changed = true;
	if (nextNum != info.seq.nextNumber()) changed = true;

	if (changed) {
	    info.seq.setMinNumber(minNum);
	    info.seq.setMaxNumber(maxNum);
	    info.seq.setNextNumber(nextNum);
	    _quasar->db()->setSequence(info.seq);
	}
    }
    close();
}
void ActivityPartitionDialog::menu_represents()
{
    if (!hasOkButton() && (represented == 0))
        return;

    Q3PopupMenu m(0);

    m.insertItem(TR("Choose"), -1);
    m.insertSeparator();

    if (represented != 0)
        m.insertItem(TR("Select in browser"), 0);

    BrowserNode * bn = BrowserView::selected_item();

    if ((bn != 0) && allowed(bn))
        m.insertItem(TR("Choose element selected in browser"), 1);

    const Q3PtrList<BrowserNode> & l = BrowserNode::marked_nodes();

    if ((l.count() == 1) && allowed(l.getFirst()))
        m.insertItem(TR("Choose element marked in browser"), 2);

    switch (m.exec(QCursor::pos())) {
    case 0:
        represented->select_in_browser();
        return;

    case 1:
        represented = bn;
        break;

    case 2:
        represented = l.getFirst();
        break;

    default:
        return;
    }

    edrepresents->changeItem(*(represented->pixmap(0)),
                             represented->full_name(TRUE),
                             0);
}
Example #6
0
int open(const char *pathname, int flags, mode_t mode) {
    static int (*real_open)(const char*, int, mode_t) = NULL;
    if (!real_open) real_open = dlsym(RTLD_NEXT, "open");

    if (!allowed(pathname, flags)) {
        return -1;
    }

    return real_open(pathname, flags, mode);
}
Example #7
0
FILE* fopen(const char* name, const char* mode) {
    static FILE* (*real_fopen)(const char*, const char*) = NULL;
    if (!real_fopen) real_fopen = dlsym(RTLD_NEXT, "fopen");

    if (!allowed(name, (mode[0] == 'r') ? 0 : O_CREAT)) {
        return NULL;
    }

    return real_fopen(name, mode);
}
Example #8
0
	/** Retorna o resultado das ações executadas na ordem em que estão armazenadas. */
	state_t result() const {
		state_t state;

		for(Move *move : moves) {
			if(!allowed(move, state)) break;
			move->execute(state);
		}

		return state;
	}
Example #9
0
int creat(const char *pathname, mode_t mode) {
    static int (*real_creat)(const char*, mode_t) = NULL;
    if (!real_creat) real_creat = dlsym(RTLD_NEXT, "creat");

    if (!allowed(pathname, O_CREAT)) {
        return -1;
    }

    return real_creat(pathname, mode);
}
Example #10
0
SparseMatrix& SparseMatrix::operator+=(const SparseMatrix& other)
{
  for (int i = 0; i < nrows(); ++i)
    for (int j = 0; j < ncols(); ++j)
      if (allowed(i, j))
	{
	  assert(other.allowed(i, j));
	  MatrixScaleAdd(1., other.operator_element(i, j), operator_element(i, j));
	}
  return *this;
}
Example #11
0
bool State::rewind() {
  if(!allowed()) return false;
  if(!config().system.rewindEnabled) return false;

  if(historyCount == 0) return false;
  serializer state(history[historyIndex].data(), history[historyIndex].size());
  bool result = SNES::system.unserialize(state);
  historyIndex = (historyIndex + historySize - 1) % historySize;  //add historySize to prevent underflow
  historyCount--;
  return true;
}
Example #12
0
void SpinAdapted::Wavefunction::FlattenInto (Matrix& C)
{
  int flatIndex = 0;
  for (int lQ = 0; lQ < nrows (); ++lQ)
    for (int rQ = 0; rQ < ncols (); ++rQ)
      if (allowed(lQ, rQ))
	flatIndex += operator_element(lQ,rQ).Nrows()*operator_element(lQ,rQ).Ncols();
  
  C.ReSize(flatIndex,1);

  flatIndex = 0;
  for (int lQ = 0; lQ < nrows (); ++lQ)
    for (int rQ = 0; rQ < ncols (); ++rQ)
      if (allowed(lQ, rQ))
        for (int lQState = 0; lQState < operator_element(lQ, rQ).Nrows (); ++lQState)
          for (int rQState = 0; rQState < operator_element(lQ, rQ).Ncols (); ++rQState)
	    {
	      C.element (flatIndex,0) = operator_element(lQ, rQ).element (lQState, rQState);
	      ++flatIndex;
	    }
}
Example #13
0
int
main(int argc, char *argv[]) {
	int exitstatus;

	setprogname(argv[0]);
	Pid = getpid();
	(void)setlocale(LC_ALL, "");

	euid = geteuid();
	egid = getegid();
	ruid = getuid();
	rgid = getgid();

	if (euid == ruid && ruid != 0)
		errx(ERROR_EXIT, "Not installed setuid root");

	(void)setvbuf(stderr, NULL, _IOLBF, 0);
	parse_args(argc, argv);		/* sets many globals, opens a file */
	set_cron_cwd();
	if (!allowed(RealUser, CRON_ALLOW, CRON_DENY)) {
		(void)fprintf(stderr,
			"You `%s' are not allowed to use this program `%s'\n",
			User, getprogname());
		(void)fprintf(stderr, "See crontab(1) for more information\n");
		log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
		exit(ERROR_EXIT);
	}
	exitstatus = OK_EXIT;
	switch (Option) {
	case opt_unknown:
		usage("unrecognized option");
		exitstatus = ERROR_EXIT;
		break;
	case opt_list:
		list_cmd();
		break;
	case opt_delete:
		delete_cmd();
		break;
	case opt_edit:
		edit_cmd();
		break;
	case opt_replace:
		if (replace_cmd() < 0)
			exitstatus = ERROR_EXIT;
		break;
	default:
		abort();
	}
	exit(exitstatus);
	/*NOTREACHED*/
}
Example #14
0
void State::frame() {
  if(!allowed()) return;
  if(!config().system.rewindEnabled) return;

  //if a full second has passed, automatically capture state
  if(++frameCounter >= (SNES::system.region() == SNES::System::NTSC ? 60 : 50)) {
    frameCounter = 0;
    historyIndex = (historyIndex + 1) % historySize;
    historyCount = min(historyCount + 1, historySize);
    SNES::system.runtosave();
    history[historyIndex] = SNES::system.serialize();
  }
}
Example #15
0
int
main (int argc, char *argv[])
{
  int exitstatus;
  char *config_file;		/* Name of our configuration file;  NULL if none */

  Pid = getpid ();
  ProgramName = argv[0];

#if defined(POSIX)
  setlocale (LC_ALL, "");
#endif

#if HAVE_SETLINEBUF
  setlinebuf (stderr);
#endif /*HAVE_SETLINEBUF */
  parse_args (argc, argv, &config_file);	/* sets many globals, opens a file */

  read_config (config_file, &allow_only_root, &log_syslog, &allow_file,
	       &deny_file, &crondir, &spool_dir, &log_file, &syscrontab,
	       &lastrun_file, &pidfile, &mailprog, &mailargs);

  set_cron_cwd ();
  if (!allowed (User))
    {
      fprintf (stderr,
	       "You (%s) are not allowed to use this program (%s)\n",
	       User, ProgramName);
      fprintf (stderr, "See crontab(1) for more information\n");
      log_it (RealUser, Pid, "AUTH", "crontab command not allowed");
      exit (ERROR_EXIT);
    }
  exitstatus = OK_EXIT;
  switch (Option)
    {
    case opt_list:
      list_cmd ();
      break;
    case opt_delete:
      delete_cmd ();
      break;
    case opt_edit:
      edit_cmd ();
      break;
    case opt_replace:
      if (replace_cmd () < 0)
	exitstatus = ERROR_EXIT;
      break;
    }
  exit (0);
 /*NOTREACHED*/}
Example #16
0
int px_http_handler (FILE * ds, char * ip) {
	px_url address;
	address.dir = NULL;
	
	if (!validate(ds, &address)) {
		return 0;
	}
	
	char* zeile = (char*)malloc(PX_MAXLINE + 1);
	
	while(fgets(zeile, PX_MAXLINE, ds), px_emptyline(zeile) == 0) {
		printf("%s", zeile);
	}
	
	// Ist die Datei erlaubt?
	if (px_char_count(address.dir, '/') > 1) {
		err403(ds);
		free(zeile);
		return 0;
	}
	
	if (strcmp(address.dir, "/") == 0) {
		fputs("HTTP/1.1 200 OK\nConnection: close\n", ds);
		fputs("Content-Type: text/html\n\n", ds);
		printdir(ds);
		return 0;
	}
	
	if (allowed(address.dir)) {
		char * filename = address.dir;
		if (*filename == '/') filename++;
		if (access(filename, R_OK) != -1) {
			fputs("HTTP/1.1 200 OK\nConnection: close\n", ds);
			deliver(ds, address.dir);
		}
		return 0;
	}
	
	err404(ds);
	
	fputs("\n", ds);
	free(zeile);
	
	return 0;
}
Example #17
0
void printdir (FILE * ds) {
	fputs ("<h1>Inhalt von /</h1>", ds);
	
	DIR *dir;
	struct dirent *entry;     
	dir = opendir ("./");

	if (dir != NULL)
		while ((entry = readdir (dir)) != NULL) 
			if (allowed (entry->d_name)) {
				fputs ("<a href=\"", ds);
		 		fputs (entry->d_name, ds);
				fputs ("\">", ds);
		 		fputs (entry->d_name, ds);
				fputs ("</a><br>", ds);
			}
		(void) closedir (dir);
}
Example #18
0
bool State::save(unsigned slot) {
  if(!allowed()) return false;

  SNES::system.runtosave();
  serializer state = SNES::system.serialize();

  file fp;
  bool result = false;
  if(fp.open(name(slot), file::mode_write)) {
    fp.write(state.data(), state.size());
    fp.close();
    result = true;
  }

  if(result) {
    utility.showMessage(string() << "State " << (slot + 1) << " saved.");
  } else {
    utility.showMessage(string() << "Failed to save state " << (slot + 1) << ".");
  }
  return result;
}
Example #19
0
int
main(int argc, char *argv[])
{
	int	exitstatus;

	Pid = getpid();
	ProgramName = argv[0];

#if defined(POSIX)
	setlocale(LC_ALL, "");
#endif

#if defined(BSD)
	setlinebuf(stderr);
#endif
	parse_args(argc, argv);		/* sets many globals, opens a file */
	set_cron_uid();
	set_cron_cwd();
	if (!allowed(User)) {
		warnx("you (%s) are not allowed to use this program", User);
		log_it(RealUser, Pid, "AUTH", "crontab command not allowed");
		exit(ERROR_EXIT);
	}
	exitstatus = OK_EXIT;
	switch (Option) {
	case opt_list:		list_cmd();
				break;
	case opt_delete:	delete_cmd();
				break;
	case opt_edit:		edit_cmd();
				break;
	case opt_replace:	if (replace_cmd() < 0)
					exitstatus = ERROR_EXIT;
				break;
	case opt_unknown:
				break;
	}
	exit(exitstatus);
	/*NOTREACHED*/
}
Example #20
0
// ---------------------------------------------------------------------------
// CAOSettings::IsCellularAllowedByUser
// ---------------------------------------------------------------------------
//
TBool CAOSettings::IsCellularAllowedByUser() const
{
    TBool allowed( ETrue );
    CRepository* repository = NULL;

    TRAP_IGNORE( repository = CRepository::NewL( KCRUidCmManager ) )

    if ( repository )
    {
        TInt value( 0 );
        TInt err = repository->Get( KCurrentCellularDataUsage, value );

        if ( err == KErrNone )
        {
            if ( value == ECmCellularDataUsageDisabled )
            {
                // Cellular connection is not allowed by user
                allowed = EFalse;
            }
            else
            {
                MAOConnectionManager::TNetworkType nwType =
                    iStateContext.ConnectionManager().NetworkType();

                if ( ( nwType == MAOConnectionManager::EVPLMN ) &&
                        ( value == ECmCellularDataUsageConfirm ) )
                {
                    // Silent connection is not allowed (will fail)
                    // in visitor network if user has chosen confirm option.
                    allowed = EFalse;
                }
            }
        }
    }
    LOG_2( _L("IsCellularAllowedByUser(): %d"), allowed );

    delete repository;
    return allowed;
}
struct quicklist *regions_in_range(struct region *start, int maxdist,
    bool(*allowed) (const struct region *, const struct region *))
{
    quicklist * rlist = NULL;
    node *root = new_node(start, 0, NULL);
    node **end = &root->next;
    node *n = root;

    while (n != NULL) {
        region *r = n->r;
        int depth = n->distance + 1;
        int d;

        if (n->distance >= maxdist)
            break;
        for (d = 0; d != MAXDIRECTIONS; ++d) {
            region *rn = rconnect(r, d);
            if (rn == NULL)
                continue;
            if (fval(rn, RF_MARK))
                continue;               /* already been there */
            if (allowed && !allowed(r, rn))
                continue;               /* can't go there */

            /* add the region to the list of available ones. */
            ql_push(&rlist, rn);

            /* make sure we don't go here again, and put the region into the set for
               further BFS'ing */
            fset(rn, RF_MARK);
            *end = new_node(rn, depth, n);
            end = &(*end)->next;
        }
        n = n->next;
    }
    free_nodes(root);

    return rlist;
}
Example #22
0
bool State::load(unsigned slot) {
  if(!allowed()) return false;

  file fp;
  bool result = false;
  if(fp.open(name(slot), file::mode_read)) {
    unsigned size = fp.size();
    uint8_t *data = new uint8_t[size];
    fp.read(data, size);
    fp.close();
    serializer state(data, size);
    delete[] data;
    result = SNES::system.unserialize(state);
  }

  if(result) {
    utility.showMessage(string() << "State " << (slot + 1) << " loaded.");
    resetHistory();
  } else {
    utility.showMessage(string() << "Failed to load state " << (slot + 1) << ".");
  }
  return result;
}
Example #23
0
	/** Realiza o confronto, alternando os participantes, e retorna o estado 
	 * final da partida.
	 *
	 * @return state_t o estado resultante do confronto.
	 * @see bool allowed(const Move *, const state_t &) const
	 * @see IIA::Action<state_t>* Player::decide_action(const state_t &)
	 * @see void Move::execute(state_t &) const
	 * @see bool over(const state_t &)
	 * @see void setup(const typename std::deque<player_t *> &) */
	state_t play() {
		moves.clear();

		std::deque<player_t *> match_players(players);
		
		state_t state;

		setup(match_players);

		do {
			Move *move = choose_move(match_players.front(), state);
			moves.push_back(move);

			if(!allowed(move, state)) break;

			move->execute(state);
			
			next(match_players);
		} while(!over(state));

		// cleanup(match_players);

		return state;
	}
Example #24
0
static void genFunctions(int tab, int expand, 
		  token_t * e1, 
		  char *mname, 
		  int allowed(), FILE *fp)
{
    int i, n, t;
    int multiplexed;
    symentry_t *sym;
    
    for (i = 0; i < HSIZE; i++)
	for (sym = EiC_HTAB[i]; sym; sym = sym->next) {
	    if ((t = EiC_gettype(sym->type)) == t_eic || sym->nspace != tab)
		continue;

	    if(e1 && e1->Type && ! EiC_sametypes(e1->Type,sym->type))
		continue;

	    if(mname && strcmp(mname,sym->fname) != 0)
		continue;
	    
	    if(allowed && !allowed(t))
		continue;

	    n = 1;
	    multiplexed = 0;
	    while (n)
	    {
		if(DoCallBackNames(EiC_getInf(sym->type),fp)) {
		    int k = 0;
		    if (!multiplexed)
		    {
			multiplexed = 1;
			n = MULTIPLEX;
		    }
		    while(k<Ncalls) {
			genCallBackFunc(sym->type,k++,fp);
		    }
		}
		--n;
	    }

	    fputs("static val_t eic_",fp);
	    fputs(sym->id, fp);
	    fputs("(void)\n",fp);
	    fputs("{\n",fp);
	    
	    fputs("\tval_t v;\n",fp);
	    /*fputs("\tstatic int nb = 0;\n",fp);*/

	    if (multiplexed)
	    {
		genMultiCall(sym->type, sym->id, fp);
	    }
	    else
	    {
		genCall(sym->type, sym->id, fp);
	    }
	    
	    fputs("\n",fp);
	    fputs("\treturn v;\n",fp);
	    fputs("}\n\n",fp);

	}
}
Example #25
0
/*===========================================================================*
 *				do_exec					     *
 *===========================================================================*/
PUBLIC int do_exec()
{
    /* Perform the execve(name, argv, envp) call.  The user library builds a
     * complete stack image, including pointers, args, environ, etc.  The stack
     * is copied to a buffer inside MM, and then to the new core image.
     */

    register struct mproc *rmp;
    struct mproc *sh_mp;
    int m, r, fd, ft, sn;
    static char mbuf[ARG_MAX];	/* buffer for stack and zeroes */
    static char name_buf[PATH_MAX]; /* the name of the file to exec */
    char *new_sp, *basename;
    vir_bytes src, dst, text_bytes, data_bytes, bss_bytes, stk_bytes, vsp;
    phys_bytes tot_bytes;		/* total space for program, including gap */
    long sym_bytes;
    vir_clicks sc;
    struct stat s_buf;
    vir_bytes pc;

    /* Do some validity checks. */
    rmp = mp;
    stk_bytes = (vir_bytes) stack_bytes;
    if (stk_bytes > ARG_MAX) return(ENOMEM);	/* stack too big */
    if (exec_len <= 0 || exec_len > PATH_MAX) return(EINVAL);

    /* Get the exec file name and see if the file is executable. */
    src = (vir_bytes) exec_name;
    dst = (vir_bytes) name_buf;
    r = sys_copy(who, D, (phys_bytes) src,
                 MM_PROC_NR, D, (phys_bytes) dst, (phys_bytes) exec_len);
    if (r != OK) return(r);	/* file name not in user data segment */
    tell_fs(CHDIR, who, FALSE, 0);	/* switch to the user's FS environ. */
    fd = allowed(name_buf, &s_buf, X_BIT);	/* is file executable? */
    if (fd < 0) return(fd);	/* file was not executable */

    /* Read the file header and extract the segment sizes. */
    sc = (stk_bytes + CLICK_SIZE - 1) >> CLICK_SHIFT;
    m = read_header(fd, &ft, &text_bytes, &data_bytes, &bss_bytes,
                    &tot_bytes, &sym_bytes, sc, &pc);
    if (m < 0) {
        close(fd);		/* something wrong with header */
        return(ENOEXEC);
    }

    /* Fetch the stack from the user before destroying the old core image. */
    src = (vir_bytes) stack_ptr;
    dst = (vir_bytes) mbuf;
    r = sys_copy(who, D, (phys_bytes) src,
                 MM_PROC_NR, D, (phys_bytes) dst, (phys_bytes)stk_bytes);
    if (r != OK) {
        close(fd);		/* can't fetch stack (e.g. bad virtual addr) */
        return(EACCES);
    }

    /* Can the process' text be shared with that of one already running? */
    sh_mp = find_share(rmp, s_buf.st_ino, s_buf.st_dev, s_buf.st_ctime);

    /* Allocate new memory and release old memory.  Fix map and tell kernel. */
    r = new_mem(sh_mp, text_bytes, data_bytes, bss_bytes, stk_bytes, tot_bytes);
    if (r != OK) {
        close(fd);		/* insufficient core or program too big */
        return(r);
    }

    /* Save file identification to allow it to be shared. */
    rmp->mp_ino = s_buf.st_ino;
    rmp->mp_dev = s_buf.st_dev;
    rmp->mp_ctime = s_buf.st_ctime;

    /* Patch up stack and copy it from MM to new core image. */
    vsp = (vir_bytes) rmp->mp_seg[S].mem_vir << CLICK_SHIFT;
    vsp += (vir_bytes) rmp->mp_seg[S].mem_len << CLICK_SHIFT;
    vsp -= stk_bytes;
    patch_ptr(mbuf, vsp);
    src = (vir_bytes) mbuf;
    r = sys_copy(MM_PROC_NR, D, (phys_bytes) src,
                 who, D, (phys_bytes) vsp, (phys_bytes)stk_bytes);
    if (r != OK) panic("do_exec stack copy err", NO_NUM);

    /* Read in text and data segments. */
    if (sh_mp != NULL) {
        lseek(fd, (off_t) text_bytes, SEEK_CUR);  /* shared: skip text */
    } else {
        load_seg(fd, T, text_bytes);
    }
    load_seg(fd, D, data_bytes);

#if (SHADOWING == 1)
    if (lseek(fd, (off_t)sym_bytes, SEEK_CUR) == (off_t) -1) ;	/* error */
    if (relocate(fd, (unsigned char *)mbuf) < 0) 	;		/* error */
    pc += (vir_bytes) rp->mp_seg[T].mem_vir << CLICK_SHIFT;
#endif

    close(fd);			/* don't need exec file any more */

    /* Take care of setuid/setgid bits. */
    if ((rmp->mp_flags & TRACED) == 0) { /* suppress if tracing */
        if (s_buf.st_mode & I_SET_UID_BIT) {
            rmp->mp_effuid = s_buf.st_uid;
            tell_fs(SETUID,who, (int)rmp->mp_realuid, (int)rmp->mp_effuid);
        }
        if (s_buf.st_mode & I_SET_GID_BIT) {
            rmp->mp_effgid = s_buf.st_gid;
            tell_fs(SETGID,who, (int)rmp->mp_realgid, (int)rmp->mp_effgid);
        }
    }

    /* Save offset to initial argc (for ps) */
    rmp->mp_procargs = vsp;

    /* Fix 'mproc' fields, tell kernel that exec is done,  reset caught sigs. */
    for (sn = 1; sn <= _NSIG; sn++) {
        if (sigismember(&rmp->mp_catch, sn)) {
            sigdelset(&rmp->mp_catch, sn);
            rmp->mp_sigact[sn].sa_handler = SIG_DFL;
            sigemptyset(&rmp->mp_sigact[sn].sa_mask);
        }
    }

    rmp->mp_flags &= ~SEPARATE;	/* turn off SEPARATE bit */
    rmp->mp_flags |= ft;		/* turn it on for separate I & D files */
    new_sp = (char *) vsp;

    tell_fs(EXEC, who, 0, 0);	/* allow FS to handle FD_CLOEXEC files */

    /* System will save command line for debugging, ps(1) output, etc. */
    basename = strrchr(name_buf, '/');
    if (basename == NULL) basename = name_buf;
    else basename++;
    sys_exec(who, new_sp, rmp->mp_flags & TRACED, basename, pc);
    return(OK);
}
Example #26
0
int
main(int argc, char **argv)
{
	int	c, r;
	int	rflag	= 0;
	int	lflag	= 0;
	int	gflag	= 0;
	int	eflag	= 0;
	int	errflg	= 0;
	char *pp;
	FILE *fp, *tmpfp;
	struct stat stbuf;
	struct passwd *pwp;
	time_t omodtime;
	char *editor;
	uid_t ruid;
	pid_t pid;
	int stat_loc;
	int ret;
	char real_login[UNAMESIZE];
	int tmpfd = -1;
	pam_handle_t *pamh;
	int pam_error;
	char *buf;
	size_t buflen;

	(void) setlocale(LC_ALL, "");
#if !defined(TEXT_DOMAIN)	/* Should be defined by cc -D */
#define	TEXT_DOMAIN "SYS_TEST"	/* Use this only if it weren't */
#endif
	(void) textdomain(TEXT_DOMAIN);

	if (init_yes() < 0) {
		(void) fprintf(stderr, gettext(ERR_MSG_INIT_YES),
		    strerror(errno));
		exit(1);
	}

	while ((c = getopt(argc, argv, "eglr")) != EOF)
		switch (c) {
			case 'e':
				eflag++;
				break;
			case 'g':
				gflag++;
				break;
			case 'l':
				lflag++;
				break;
			case 'r':
				rflag++;
				break;
			case '?':
				errflg++;
				break;
		}

	if (eflag + lflag + rflag > 1)
		errflg++;

	if (gflag && !lflag)
		errflg++;

	argc -= optind;
	argv += optind;
	if (errflg || argc > 1)
		crabort(BADUSAGE);

	ruid = getuid();
	if ((pwp = getpwuid(ruid)) == NULL)
		crabort(INVALIDUSER);

	if (strlcpy(real_login, pwp->pw_name, sizeof (real_login))
	    >= sizeof (real_login))
		crabort(NAMETOOLONG);

	if ((eflag || lflag || rflag) && argc == 1) {
		if ((pwp = getpwnam(*argv)) == NULL)
			crabort(INVALIDUSER);

		if (!cron_admin(real_login)) {
			if (pwp->pw_uid != ruid)
				crabort(NOTROOT);
			else
				pp = getuser(ruid);
		} else
			pp = *argv++;
	} else {
		pp = getuser(ruid);
	}

	if (pp == NULL) {
		if (per_errno == 2)
			crabort(BADSHELL);
		else
			crabort(INVALIDUSER);
	}
	if (strlcpy(login, pp, sizeof (login)) >= sizeof (login))
		crabort(NAMETOOLONG);
	if (!allowed(login, CRONALLOW, CRONDENY))
		crabort(NOTALLOWED);

	/* Do account validation check */
	pam_error = pam_start("cron", pp, NULL, &pamh);
	if (pam_error != PAM_SUCCESS) {
		crabort((char *)pam_strerror(pamh, pam_error));
	}
	pam_error = pam_acct_mgmt(pamh, PAM_SILENT);
	if (pam_error != PAM_SUCCESS) {
		(void) fprintf(stderr, gettext("Warning - Invalid account: "
		    "'%s' not allowed to execute cronjobs\n"), pp);
	}
	(void) pam_end(pamh, PAM_SUCCESS);


	/* check for unaudited shell */
	if (audit_crontab_not_allowed(ruid, pp))
		crabort(AUDITREJECT);

	cf = xmalloc(strlen(CRONDIR)+strlen(login)+2);
	strcat(strcat(strcpy(cf, CRONDIR), "/"), login);

	if (rflag) {
		r = unlink(cf);
		cron_sendmsg(DELETE, login, login, CRON);
		audit_crontab_delete(cf, r);
		exit(0);
	}
	if (lflag) {
		char sysconf[PATH_MAX];

		if (gflag) {
			if (snprintf(sysconf, sizeof (sysconf), "%s/%s",
			    SYSCRONDIR, login) < sizeof (sysconf) &&
			    (fp = fopen(sysconf, "r")) != NULL) {
				while (fgets(line, CTLINESIZE, fp) != NULL)
					fputs(line, stdout);
				fclose(fp);
				exit(0);
			} else {
				crabort(BADOPEN);
			}
		} else {
			if ((fp = fopen(cf, "r")) == NULL)
				crabort(BADOPEN);
			while (fgets(line, CTLINESIZE, fp) != NULL)
				fputs(line, stdout);
			fclose(fp);
			exit(0);
		}
	}
	if (eflag) {
		if ((fp = fopen(cf, "r")) == NULL) {
			if (errno != ENOENT)
				crabort(BADOPEN);
		}
		(void) strcpy(edtemp, "/tmp/crontabXXXXXX");
		tmpfd = mkstemp(edtemp);
		if (fchown(tmpfd, ruid, -1) == -1) {
			(void) close(tmpfd);
			crabort("fchown of temporary file failed");
		}
		(void) close(tmpfd);
		/*
		 * Fork off a child with user's permissions,
		 * to edit the crontab file
		 */
		if ((pid = fork()) == (pid_t)-1)
			crabort("fork failed");
		if (pid == 0) {		/* child process */
			/* give up super-user privileges. */
			setuid(ruid);
			if ((tmpfp = fopen(edtemp, "w")) == NULL)
				crabort("can't create temporary file");
			if (fp != NULL) {
				/*
				 * Copy user's crontab file to temporary file.
				 */
				while (fgets(line, CTLINESIZE, fp) != NULL) {
					fputs(line, tmpfp);
					if (ferror(tmpfp)) {
						fclose(fp);
						fclose(tmpfp);
						crabort("write error on"
						    "temporary file");
					}
				}
				if (ferror(fp)) {
					fclose(fp);
					fclose(tmpfp);
					crabort(BADREAD);
				}
				fclose(fp);
			}
			if (fclose(tmpfp) == EOF)
				crabort("write error on temporary file");
			if (stat(edtemp, &stbuf) < 0)
				crabort("can't stat temporary file");
			omodtime = stbuf.st_mtime;
#ifdef _XPG_NOTDEFINED
			editor = getenv("VISUAL");
			if (editor == NULL) {
#endif
				editor = getenv("EDITOR");
				if (editor == NULL)
					editor = VIPATH;
#ifdef _XPG_NOTDEFINED
			}
#endif
			buflen = strlen(editor) + strlen(edtemp) + 2;
			buf = xmalloc(buflen);
			(void) snprintf(buf, buflen, "%s %s", editor, edtemp);

			sleep(1);

			while (1) {
				ret = system(buf);

				/* sanity checks */
				if ((tmpfp = fopen(edtemp, "r")) == NULL)
					crabort("can't open temporary file");
				if (fstat(fileno(tmpfp), &stbuf) < 0)
					crabort("can't stat temporary file");
				if (stbuf.st_size == 0)
					crabort("temporary file empty");
				if (omodtime == stbuf.st_mtime) {
					(void) unlink(edtemp);
					fprintf(stderr, gettext(
					    "The crontab file was not"
					    " changed.\n"));
					exit(1);
				}
				if ((ret) && (errno != EINTR)) {
					/*
					 * Some editors (like 'vi') can return
					 * a non-zero exit status even though
					 * everything is okay. Need to check.
					 */
					fprintf(stderr, gettext(ED_ERROR));
					fflush(stderr);
					if (isatty(fileno(stdin))) {
						/* Interactive */
						fprintf(stdout,
						    gettext(ED_PROMPT),
						    yesstr, nostr, nostr);
						fflush(stdout);

						if (yes()) {
							/* Edit again */
							continue;
						} else {
							/* Dump changes */
							(void) unlink(edtemp);
							exit(1);
						}
					} else {
						/*
						 * Non-interactive, dump changes
						 */
						(void) unlink(edtemp);
						exit(1);
					}
				}
				exit(0);
			} /* while (1) */
		}

		/* fix for 1125555 - ignore common signals while waiting */
		(void) signal(SIGINT, SIG_IGN);
		(void) signal(SIGHUP, SIG_IGN);
		(void) signal(SIGQUIT, SIG_IGN);
		(void) signal(SIGTERM, SIG_IGN);
		wait(&stat_loc);
		if ((stat_loc & 0xFF00) != 0)
			exit(1);

		/*
		 * unlink edtemp as 'ruid'. The file contents will be held
		 * since we open the file descriptor 'tmpfp' before calling
		 * unlink.
		 */
		if (((ret = seteuid(ruid)) < 0) ||
		    ((tmpfp = fopen(edtemp, "r")) == NULL) ||
		    (unlink(edtemp) == -1)) {
			fprintf(stderr, "crontab: %s: %s\n",
			    edtemp, errmsg(errno));
			if ((ret < 0) || (tmpfp == NULL))
				(void) unlink(edtemp);
			exit(1);
		} else
			seteuid(0);

		copycron(tmpfp);
	} else {
		if (argc == 0)
			copycron(stdin);
		else if (seteuid(getuid()) != 0 || (fp = fopen(argv[0], "r"))
		    == NULL)
			crabort(BADOPEN);
		else {
			seteuid(0);
			copycron(fp);
		}
	}
	cron_sendmsg(ADD, login, login, CRON);
/*
 *	if (per_errno == 2)
 *		fprintf(stderr, gettext(WARNSHELL));
 */
	return (0);
}
Example #27
0
int Package::file_number(QDir & d, bool rec)
{
    if (! allowed(DirFilter, d.dirName()))
        return 0;

    int result = 0;
//  const QFileInfoList * list = d.entryInfoList(QDir::Files | QDir::Readable);
    /*
     if (list != 0) {
       QFileInfoListIterator it(*list);
       QFileInfo * fi;

       while ((fi = it.current()) != 0) {
         if (fi->extension(FALSE) == Ext)
    result += 1;
         ++it;
       }
     }*/

    // Oh lord, Bruno is so used to cut-n-paste, I am getting sick.
    QFileInfoList list = d.entryInfoList(QDir::Files | QDir::Readable);

    if (!list.isEmpty()) {
        QFileInfoList::iterator it = list.begin();

        while (it != list.end()) {
            if ((*it).extension(FALSE) == Ext) result += 1;

            it++;
        }
    }

    if (rec) {
//     // sub directories
//     list = d.entryInfoList(QDir::Dirs | QDir::NoSymLinks);
//
//     if (list != 0) {
//       QFileInfoListIterator itd(*list);
//       QFileInfo * di;
//
//       while ((di = itd.current()) != 0) {
// 	if (((const char *) di->fileName())[0] != '.') {
// 	  QDir sd(di->filePath());
//
// 	  result += file_number(sd, rec);
// 	}
// 	++itd;
//       }
//     }
//   }
//
        list = d.entryInfoList(QDir::Dirs | QDir::NoSymLinks);

        if (!list.isEmpty()) {
            QFileInfoList::iterator it = list.begin();

            while (it != list.end()) {
                if ((*it).fileName()[0] != '.') {
                    QDir sd((*it).filePath());
                    result += file_number(sd, rec);
                }

                it++;
            }
        }
    }

    return result;
}
Example #28
0
void Package::reverse_directory(QDir & d, bool rec)
{
    if (! allowed(DirFilter, d.dirName()))
        return;

    // reads files
    QFileInfoList list = d.entryInfoList(QDir::Files | QDir::Readable);

    if (!list.isEmpty()) {
        QFileInfoList::iterator it = list.begin();

        while (it != list.end()) {
            if ((*it).extension(FALSE) == Ext) {
                if (allowed(FileFilter, (*it).fileName()))
                    reverse_file(WrapperStr((*it).filePath().toAscii().constData()), WrapperStr(my_baseName(&(*it)).toAscii().constData()));

                if (progress)
                    progress->tic();

                app->processEvents();
            }

            ++it;
        }

        /*
            while ((fi = it.current()) != 0) {
              if (fi->extension(FALSE) == Ext) {
        	if (allowed(FileFilter, fi->fileName()))
        	  reverse_file(WrapperStr(fi->filePath()), WrapperStr(my_baseName(fi)));
        	if (progress)
        	  progress->tic();
        	app->processEvents();
              }
              ++it;
            }*/
    }

    if (rec) {
        // sub directories
        list = d.entryInfoList(QDir::Dirs | QDir::NoSymLinks);

        if (!list.isEmpty()) {
            QFileInfoList::iterator itd = list.begin();

            while (itd != list.end()) {

                if ((*itd).fileName()[0] != '.') {
                    QDir sd((*itd).filePath());

                    Package * p = find(WrapperStr(sd.dirName().toAscii().constData()), TRUE);

                    if (p != 0)
                        p->reverse_directory(sd, TRUE);
                }

                ++itd;
            }
        }
    }
}
Example #29
0
int
main (int argc, char **argv)
{
  List nflist;
  struct notesfile nf;
  struct newt note;

  int result;
  int i, pid;
  int director_only = FALSE;
  int exclude_director = FALSE;
  int single_page = FALSE;

  FILE *tocf;

  int opt;
  int option_index = 0;
  extern char *optarg;
  extern int optind, opterr, optopt;

  struct option long_options[] =
    {
      {"cat",0,0,'c'},
      {"debug",0,0,'D'},
      {"director",0,0,'d'},
      {"index-only",0,0,'i'},
      {"length",1,0,'l'},
      {"no-director",0,0,'n'},
      {"page-breaks",0,0,'p'},
      {"help",0,0,'h'},
      {"version",0,0,0},
      {0,0,0,0}
    };

  memset (&nf, 0, sizeof (struct notesfile));
  memset (&note, 0, sizeof (struct newt));

#ifdef __GLIBC__
  program_name = program_invocation_short_name;
#else
  program_name = base_name (argv[0]);
#endif

  /* Initialize i18n. */

#ifdef HAVE_SETLOCALE
  setlocale (LC_ALL, "");
#endif

#if ENABLE_NLS
  bindtextdomain (PACKAGE, LOCALEDIR);
  textdomain (PACKAGE);
#endif

  setup ();

  /* Catch the '-nd' option, replace it with '-n'. This is mostly a backwards-
   * compatibility thing in case people remember it working.
   */

  for (i=0; i < argc; i++)
    {
      if (strcmp (argv[i], "-nd") == 0)
        argv[i] = "-n";
    }

  while ((opt = getopt_long (argc, argv, "cdhil:npt",
                             long_options, &option_index)) != -1)
    {
      switch (opt)
        {
        case 0:
          {
            printf_version_string (N_("nfprint"));

            teardown ();

            if (fclose (stdout) == EOF)
              error (EXIT_FAILURE, errno, _("error writing output"));
            exit (EXIT_SUCCESS);
          }

        case 'c':
          use_cat = TRUE;
          break;

        case 'D':
          debug = TRUE;
          break;

        case 'd':
          director_only = TRUE;
          exclude_director = FALSE;
          break;

        case 'i':
        case 't':   /* Backwards compatibility. */
          index_only = TRUE;
          break;

        case 'l':
          length = atoi (optarg);
          break;

        case 'n':
          director_only = FALSE;
          exclude_director = TRUE;
          break;

        case 'p':
          single_page = TRUE;
          break;

        case 'h':
          printf (_("Usage: %s [OPTION]... NOTESFILE [LIST]\n"
                    "Format and print notes (in LIST) from NOTESFILE.\n\n"),
                  program_name);

          printf (_("  -c, --cat           Use cat(1) instead of pr(1)\n"
                    "  -d, --director      Select only notes with director messages\n"
                    "  -i, --index-only    Print a table of note titles only\n"
                    "  -l, --length=LEN    Use a page length of LEN lines\n"
                    "  -n, --no-director   Select only notes without director messages\n"
                    "  -p, --page-breaks   Insert a page break after each thread\n"
                    "      --debug         Display debugging messages\n\n"
                    "  -h, --help          Display this help and exit\n"
                    "      --version       Display version information and exit\n\n"));

          printf (_("Report bugs to <%s>.\n"), PACKAGE_BUGREPORT);

          teardown ();

          if (fclose (stdout) == EOF)
            error (EXIT_FAILURE, errno, _("error writing output"));
          exit (EXIT_SUCCESS);

        case '?':
          fprintf (stderr, _("Try '%s --help' for more information.\n"),
                   program_name);

          teardown ();

          exit (EXIT_FAILURE);
        }
    }

  if (optind == argc)
    {
      fprintf (stderr, _("%s: too few arguments\n"), program_name);
      fprintf (stderr, _("Try '%s --help' for more information.\n"),
               program_name);

      teardown ();

      exit (EXIT_FAILURE);
    }
  else
    {
      list_init (&nflist,
                 (void * (*) (void)) nfref_alloc,
                 (void (*) (void *)) nfref_free,
                 NULL);
      parse_nf (argv[optind++], &nflist);
    }

  {
    newts_nfref *ref = (newts_nfref *) list_data (list_head (&nflist));

    /* Open the notesfile. */

    result = open_nf (ref, &nf);

    if (result != NEWTS_NO_ERROR)
      {
        list_destroy (&nflist);
        teardown ();

        error (EXIT_FAILURE, 0, _("error opening notesfile '%s'"),
               nfref_pretty_name (ref));
      }

    if (!(nf.perms & READ) && !(nf.perms & DIRECTOR))
      {
        list_destroy (&nflist);
        teardown ();

        error (EXIT_FAILURE, 0, _("you are not allowed to read notesfile '%s'"),
               nfref_pretty_name (ref));
      }
  }

  /* Open a temporary file for the table of contents. */

  tocf = tmpfile ();

  fprintf (tocf,
           _("================================ Index =================================\n\n"));


  /* Create a pipe to either cat or pr as appropriate.  Egads, doing this
   * without popen(3) is so much more annoying.
   */

  {
    int pipedesc[2];

    pipe (pipedesc);
    pid = fork ();
    switch (pid)
      {
      case -1:
        error (EXIT_FAILURE, 0, _("pipe failed"));

      case 0: /* Child process. */
        close (pipedesc[1]);
        dup2 (pipedesc[0], STDIN_FILENO);
        close (pipedesc[0]);
        if (use_cat)
          {
            execl (CAT, CAT, "-", NULL);
          }
        else
          {
            char *lenstr = newts_nmalloc (11, sizeof (char));
            char *header = newts_nmalloc (strlen (fqdn) + strlen (nf.title) + 4,
                                     sizeof (char));

            sprintf (lenstr, "%d", length);
            sprintf (header, "(%s) %s", fqdn, nf.title);
            execl (PR, PR, "-l", lenstr, "-h", header, NULL);
            newts_free (lenstr);
            newts_free (header);
          }
        _exit (EXIT_FAILURE);

      default: /* Parent process. */
        close (pipedesc[0]);
        dup2 (pipedesc[1], STDOUT_FILENO); /* Set up as stdout. */
        close (pipedesc[1]);
        break;
      }
  }

  length -= 10;   /* pr uses 10 for its header/footer. */
  left = length;

  if (optind == argc)
    {
      /* We're going to print every note.  We need to rewrite the arg string a
       * little to cause this.
       */

      char *default_range = newts_nmalloc (13, sizeof (char));
      if (nf.total_notes > 0)
        sprintf (default_range, "%d-%d", nf.options & NF_POLICY ? 0 : 1,
                 nf.total_notes);
      else
        sprintf (default_range, "0");

      optind--;

      argv[optind] = default_range; /* Wipes out the nf name, but we already
                                       * used that, so no problem.
                                       */
    }

  while (optind < argc)
    {
      int second_or_later = FALSE;
      int start, end;
      int bufptr = 0;
      struct newt note;
      memset (&note, 0, sizeof (struct newt));
      nfref_copy (&note.nr.nfr, nf.ref);

      while (list_parse (argv[optind], &bufptr, &start, &end))
        {
          if (start == 0 && end == 0)
            continue;
          if (start > end)
            {
              int temp = start;
              start = end;
              end = temp;
            }
          if (start > nf.total_notes)
            continue;

          if (second_or_later)
            {
              putc ('\n', tocf);
              last_year = last_month = last_day = 0;
            }
          second_or_later = TRUE;

          if ((start < 1 && !(nf.options & NF_POLICY)) || start < 0)
            start = 1;
          if (end > nf.total_notes)
            end = nf.total_notes;
          for (i = start; i <= end; i++)
            {
              note.nr.notenum = i;
              note.nr.respnum = 0;

              get_note (&note, FALSE);
              if ((note.options & NOTE_DELETED ||
                   note.options & NOTE_DIRECTORS_ONLY ||
                   note.options & NOTE_UNAPPROVED) &&
                  !allowed (&nf, DIRECTOR))
                continue;
              if ((director_only && (note.director_message == NULL)) ||
                  (exclude_director && (note.director_message != NULL)))
                continue;
              if (single_page && left != length)
                {
                  if (use_cat)
                    putchar ('\n');
                  else
                    putchar ('\f');
                  page++;
                  left = length;
                }

              lprnote (tocf, &nf, &note);
            }

          printf ("\n========================================================================\n");
        }

      optind++;
    }

  /* Copy the table of contents to the main pipe. */

  fseek (tocf, 0, SEEK_SET);
  if (!index_only)
    {
      if (use_cat)
        putchar ('\n');
      else
      putchar ('\f');
      page++;
      left = length;
    }
  while ((i = getc (tocf)) != EOF)
    {
      if (i == '\n')
        {
          left--;
          if (left == 0)
            {
              if (use_cat)
                putchar ('\n');
              else
                {
                  putchar ('\n');
                  putchar ('\f');
                }
              page++;
              left = length;
            }
          else
            putchar ('\n');
        }
      else
        putchar (i);
    }

  printf ("\n========================================================================\n");

  fclose (tocf);
  waitpid (pid, &i, WNOHANG);

  if (fclose (stdout) == EOF)
    error (EXIT_FAILURE, errno, _("error writing output"));

  exit (EXIT_SUCCESS);
}
Example #30
0
        virtual void doRequest(
            const char *rq, // the full request
            string url,
            // set these and return them:
            string& responseMsg,
            int& responseCode,
            vector<string>& headers, // if completely empty, content-type: text/html will be added
            const SockAddr &from
        )
        {
            //out() << "url [" << url << "]" << endl;
            
            if ( url.size() > 1 ) {
                if ( ! allowed( rq , headers, from ) ){
                    responseCode = 401;
                    responseMsg = "not allowed\n";
                    return;
                }                
                handleRESTRequest( rq , url , responseMsg , responseCode , headers );
                return;
            }


            responseCode = 200;
            stringstream ss;
            ss << "<html><head><title>";

            string dbname;
            {
                stringstream z;
                z << "mongodb " << getHostName() << ':' << mongo::cmdLine.port << ' ';
                dbname = z.str();
            }
            ss << dbname << "</title></head><body><h2>" << dbname << "</h2><p>\n<pre>";

            doUnlockedStuff(ss);

            int n = 2000;
            Timer t;
            while ( 1 ) {
                if ( !dbMutex.info().isLocked() ) {
                    {
                        readlock lk("");
                        ss << "time to get dblock: " << t.millis() << "ms\n";
                        doLockedStuff(ss);
                    }
                    break;
                }
                sleepmillis(1);
                if ( --n < 0 ) {
                    ss << "\n<b>timed out getting dblock</b>\n";
                    break;
                }
            }

            ss << "</pre></body></html>";
            responseMsg = ss.str();

            // we want to return SavedContext from before the authentication was performed
            if ( ! allowed( rq , headers, from ) ){
                responseCode = 401;
                responseMsg = "not allowed\n";
                return;
            }            
        }