Esempio n. 1
0
HRESULT SerialPort::setIOBase(ULONG aIOBase)
{
    /* check IOBase limits
     * (when changing this, make sure it corresponds to XML schema */
    if (aIOBase > 0xFFFF)
        return setError(E_INVALIDARG,
                        tr("Invalid I/O port base address of the serial port %d: %lu (must be in range [0, 0x%X])"),
                        m->bd->ulSlot, aIOBase, 0, 0xFFFF);

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    /* the machine needs to be mutable */
    AutoMutableStateDependency adep(m->pMachine);
    if (FAILED(adep.rc())) return adep.rc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    HRESULT rc = S_OK;

    if (m->bd->ulIOBase != aIOBase)
    {
        m->bd.backup();
        m->bd->ulIOBase = aIOBase;

        m->fModified = true;
        // leave the lock before informing callbacks
        alock.release();

        AutoWriteLock mlock(m->pMachine COMMA_LOCKVAL_SRC_POS);
        m->pMachine->i_setModified(Machine::IsModified_SerialPorts);
        mlock.release();

        m->pMachine->i_onSerialPortChange(this);
    }

    return rc;
}
Esempio n. 2
0
STDMETHODIMP USBDeviceFilter::COMSETTER(Remote) (IN_BSTR aRemote)
{
    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    /* the machine needs to be mutable */
    AutoMutableStateDependency adep(mParent->getMachine());
    if (FAILED(adep.rc())) return adep.rc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    if (mData->mRemote.string() != aRemote)
    {
        Data::BOOLFilter flt = aRemote;
        ComAssertRet(!flt.isNull(), E_FAIL);
        if (!flt.isValid())
            return setError(E_INVALIDARG,
                            tr("Remote state filter string '%ls' is not valid (error at position %d)"),
                            aRemote, flt.errorPosition() + 1);

        m_fModified = true;
        ComObjPtr<Machine> pMachine = mParent->getMachine();

        mData.backup();
        mData->mRemote = flt;

        // leave the lock before informing callbacks
        alock.release();

        AutoWriteLock mlock(pMachine COMMA_LOCKVAL_SRC_POS);
        pMachine->setModified(Machine::IsModified_USB);
        mlock.release();

        return mParent->onDeviceFilterChange(this);
    }

    return S_OK;
}
Esempio n. 3
0
void *
tdb_htrie_open(void *addr, const char *fname, size_t size, int *fd)
{
	void *p;
	struct stat sb = { 0 };

	if (!stat(fname, &sb)) {
		printf("filesize: %ld\n", sb.st_size);
	} else {
		TDB_WARN("no files, create them\n");
	}

	if ((*fd = open(fname, O_RDWR|O_CREAT, O_RDWR)) < 0) {
		perror("ERROR: open failure");
		exit(1);
	}

	if (sb.st_size != size)
		if (fallocate(*fd, 0, 0, size)) {
			perror("ERROR: fallocate failure");
			exit(1);
		}

	/* Use MAP_SHARED to carry changes to underlying file. */
	p = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_SHARED, *fd, 0);
	if (p != addr) {
		perror("ERROR: cannot mmap the file");
		exit(1);
	}
	printf("maped to %p\n", p);

	if (mlock(p, size)) {
		perror("ERROR: mlock failure");
		exit(1);
	}

	return p;
}
HRESULT StorageController::setUseHostIOCache(BOOL fUseHostIOCache)
{
    /* the machine needs to be mutable */
    AutoMutableStateDependency adep(m->pParent);
    if (FAILED(adep.rc())) return adep.rc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    if (m->bd->fUseHostIOCache != !!fUseHostIOCache)
    {
        m->bd.backup();
        m->bd->fUseHostIOCache = !!fUseHostIOCache;

        alock.release();
        AutoWriteLock mlock(m->pParent COMMA_LOCKVAL_SRC_POS);        // m->pParent is const, needs no locking
        m->pParent->i_setModified(Machine::IsModified_Storage);
        mlock.release();

        m->pParent->i_onStorageControllerChange();
    }

    return S_OK;
}
Esempio n. 5
0
File: mem.c Progetto: Nan619/ltp-ddt
static int _alloc_mem(long int length, int testcase)
{
	void *s;

	tst_resm(TINFO, "allocating %ld bytes.", length);
	s = mmap(NULL, length, PROT_READ | PROT_WRITE,
		 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
	if (s == MAP_FAILED) {
		if (testcase == OVERCOMMIT && errno == ENOMEM)
			return 1;
		else
			tst_brkm(TBROK | TERRNO, cleanup, "mmap");
	}
	if (testcase == MLOCK && mlock(s, length) == -1)
		tst_brkm(TINFO | TERRNO, cleanup, "mlock");
#ifdef HAVE_MADV_MERGEABLE
	if (testcase == KSM && madvise(s, length, MADV_MERGEABLE) == -1)
		tst_brkm(TBROK | TERRNO, cleanup, "madvise");
#endif
	memset(s, '\a', length);

	return 0;
}
Esempio n. 6
0
void *makeWork()
{
	myield();
	while(workDone < MAX_WORK)
	{
		mlock(&mutex);
		lastWork = workDone;
		workDone++;
		munlock(&mutex);
		if (workDone <= lastWork || workDone -1 != lastWork)
		{
			puts("Mutual Exclusion error!!!!!!!");
			printf("%d -> %d\n", lastWork, workDone);
			exit(0);
		}
		if (workDone < MAX_WORK)
		{
			printf("Work #%d done.\n", workDone);
			myield();
		}
	}
        return (NULL);
}
/**
 * Applies flags to an allocation.
 *
 * @param   pv              The allocation.
 * @param   cb              The size of the allocation (page aligned).
 * @param   fFlags          RTMEMPAGEALLOC_F_XXX.
 */
DECLINLINE(void) rtMemPagePosixApplyFlags(void *pv, size_t cb, uint32_t fFlags)
{
#ifndef RT_OS_OS2
    if (fFlags & RTMEMPAGEALLOC_F_ADVISE_LOCKED)
    {
        int rc = mlock(pv, cb);
        AssertMsg(rc == 0, ("mlock %p LB %#zx -> %d errno=%d\n", pv, cb, rc, errno));
        NOREF(rc);
    }

# ifdef MADV_DONTDUMP
    if (fFlags & RTMEMPAGEALLOC_F_ADVISE_NO_DUMP)
    {
        int rc = madvise(pv, cb, MADV_DONTDUMP);
        AssertMsg(rc == 0, ("madvice %p LB %#zx MADV_DONTDUMP -> %d errno=%d\n", pv, cb, rc, errno));
        NOREF(rc);
    }
# endif
#endif

    if (fFlags & RTMEMPAGEALLOC_F_ZERO)
        RT_BZERO(pv, cb);
}
Esempio n. 8
0
void kdf_login_key(const char *username, const char *password, int iterations, char hex[KDF_HEX_LEN])
{
	unsigned char hash[KDF_HASH_LEN];
	size_t password_len;
	_cleanup_free_ char *user_lower = xstrlower(username);

	password_len = strlen(password);

	if (iterations < 1)
		iterations = 1;

	if (iterations == 1) {
		sha256_hash(user_lower, strlen(user_lower), password, password_len, hash);
		bytes_to_hex(hash, &hex, KDF_HASH_LEN);
		sha256_hash(hex, KDF_HEX_LEN - 1, password, password_len, hash);
	} else {
		pbkdf2_hash(user_lower, strlen(user_lower), password, password_len, iterations, hash);
		pbkdf2_hash(password, password_len, (char *)hash, KDF_HASH_LEN, 1, hash);
	}

	bytes_to_hex(hash, &hex, KDF_HASH_LEN);
	mlock(hex, KDF_HEX_LEN);
}
HRESULT StorageController::setInstance(ULONG aInstance)
{
    /* the machine needs to be mutable */
    AutoMutableStateDependency adep(m->pParent);
    if (FAILED(adep.rc())) return adep.rc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    if (m->bd->ulInstance != aInstance)
    {
        m->bd.backup();
        m->bd->ulInstance = aInstance;

        alock.release();
        AutoWriteLock mlock(m->pParent COMMA_LOCKVAL_SRC_POS);        // m->pParent is const, needs no locking
        m->pParent->i_setModified(Machine::IsModified_Storage);
        mlock.release();

        m->pParent->i_onStorageControllerChange(m->pParent->i_getId(), m->bd->strName);
    }

    return S_OK;
}
STDMETHODIMP AudioAdapter::COMSETTER(Enabled)(BOOL aEnabled)
{
    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    /* the machine needs to be mutable */
    AutoMutableStateDependency adep(mParent);
    if (FAILED(adep.rc())) return adep.rc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    if (mData->mEnabled != aEnabled)
    {
        mData.backup();
        mData->mEnabled = aEnabled;

        alock.release();
        AutoWriteLock mlock(mParent COMMA_LOCKVAL_SRC_POS);  // mParent is const, needs no locking
        mParent->setModified(Machine::IsModified_AudioAdapter);
    }

    return S_OK;
}
Esempio n. 11
0
File: v4v.c Progetto: OpenXT/v4v
ssize_t
v4v_send (int fd, const void *buf, size_t len, int flags)
{
  struct v4v_dev op;
  ssize_t ret;

  op.buf = (void *) buf;
  op.len = len;
  op.flags = flags;
  op.addr = NULL;

#ifdef I_AM_A_BROKEN_WEENIE
  mlock (op.buf, op.len);
#endif

  ret = v4v_ioctl (fd, V4VIOCSEND, &op);

#ifdef I_AM_A_BROKEN_WEENIE
  munlock (op.buf, op.len);
#endif

  return ret;
}
Esempio n. 12
0
int preload(char *path, size_t *size)
{
	int file = open(path, O_RDONLY);
	struct stat statrec;
	if (file < 0) {
		fprintf(stderr, "Failed to open file \"%s\" (%d)\n", path, errno);
		return 1;
	}
	if (fstat(file, &statrec) != 0) {
		close(file);
		fprintf(stderr, "Failed to stat file \"%s\" (%d)\n", path, errno);
		return 2;
	}
	size_t length = statrec.st_size;
	if (length == 0) {
		close(file);
		fprintf(stderr, "Skipping empty file \"%s\"\n", path);
		return 0;
	}
	void *map = mmap(NULL, length, PROT_READ | PROT_EXEC,
		MAP_SHARED, file, 0);
	if (map == MAP_FAILED) {
		close(file);
		fprintf(stderr, "Failed to map file \"%s\" (%d)\n", path, errno);
		return 3;
	}
	int mlock_error = mlock(map, length);
	if (mlock_error != 0) {
		close(file);
		print_mlock_error(path, errno);
		return 4;
	}
	close(file);
	push_ptr(map, length);
	*size = length;
	return 0;
}
Esempio n. 13
0
int main(void)
{
	void *addr;
	size_t map_len = NUM_PAGES * getpagesize();
	size_t i;
	int rc;
	struct rlimit r;

	rc = getrlimit(RLIMIT_MEMLOCK, &r);
	if (rc < 0) {
		perror("getrlimit");
		exit(EXIT_FAILURE);
	}
	printf("memlock limit: %zu (current), %zu (maximum)\n",
			r.rlim_cur, r.rlim_max);
	printf("map_len: %zu\n", NUM_PAGES * map_len);
	wait_for_input("Call mmap()");
	addr = mmap(NULL, NUM_PAGES * map_len, PROT_READ | PROT_WRITE,
			MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (addr == MAP_FAILED) {
		perror("mmap");
		exit(EXIT_FAILURE);
	}

	wait_for_input("Access mapped page");
	for (i = 0; i < NUM_PAGES; i++)
		memcpy(addr + i*getpagesize(), "anaaremere", 10);
	wait_for_input("Call mlock()");
	rc = mlock(addr, NUM_PAGES * map_len);
	if (rc < 0) {
		perror("mlock");
		exit(EXIT_FAILURE);
	}
	wait_for_input("mlock() has been called");

	return 0;
}
Esempio n. 14
0
File: ipc.c Progetto: drfh/OceanFS
char* ipc_mmap_alloc(const char* name,int mode,int opts,int *fd,long size)
{
	void*		map_buff=NULL;

	if((*fd=shm_open(name,opts,mode))==-1)
	{
		perror("shm_open");
		return NULL;
	}
	if(ftruncate(*fd,size)==-1)
	{
		fprintf(stderr,"Could not allocate the shared memory space.\n");
		return NULL;
	}
	map_buff=mmap(NULL,size,PROT_READ|PROT_WRITE,MAP_SHARED,*fd,0);
	if(map_buff==MAP_FAILED)
	{
		 perror("Couldn't mmap");
		 exit(EX_IOERR);
	}
	mlock(map_buff,size);
//	fprintf(stderr,"ipc_shm_mmap(%s) @ %p of size %d\n",name,map_buff,size);
	return map_buff;
}
Esempio n. 15
0
int cuda_rpc_init(struct cuda_rpc *rpc, size_t batch_size)
{
	memset(rpc, 0, sizeof(*rpc));
	rpc->batch.buffer = malloc(CUDA_BATCH_BUFFER_SZ);
	if (!rpc->batch.buffer) {
		printd(DBG_ERROR, "Out of memory\n");
		fprintf(stderr, "Out of memory\n");
		return -1;
	}
	if (batch_size > CUDA_BATCH_MAX) {
		printd(DBG_ERROR, "Batch size %lu too large (max %d)\n",
				batch_size, CUDA_BATCH_MAX);
		return -1;
	}
	rpc->batch.max = batch_size;
#if 0
	int err = mlock(rpc->batch.buffer, CUDA_BATCH_BUFFER_SZ);
	if (err < 0) {
		printd(DBG_WARNING, "Could not pin batch buffer: %s\n",
				strerror(errno));
	}
#endif
	return 0;
}
Esempio n. 16
0
static struct vsmw_cluster *
vsmw_newcluster(struct vsmw *vsmw, size_t len, const char *pfx)
{
	struct vsmw_cluster *vc;
	int fd;
	size_t ps;

	ALLOC_OBJ(vc, VSMW_CLUSTER_MAGIC);
	AN(vc);

	vsmw_mkent(vsmw, pfx);
	REPLACE(vc->fn, VSB_data(vsmw->vsb));

	VTAILQ_INSERT_TAIL(&vsmw->clusters, vc, list);

	ps = getpagesize();
	len = RUP2(len, ps);
	vc->len = len;

	fd = openat(vsmw->vdirfd, vc->fn,
	    O_RDWR | O_CREAT | O_EXCL, vsmw->mode);
	assert(fd >= 0);

	AZ(VFIL_allocate(fd, (off_t)len, 1));

	vc->ptr = (void *)mmap(NULL, len,
	    PROT_READ|PROT_WRITE,
	    MAP_HASSEMAPHORE | MAP_NOSYNC | MAP_SHARED,
	    fd, 0);

	AZ(close(fd));
	assert(vc->ptr != MAP_FAILED);
	(void)mlock(vc->ptr, len);

	return (vc);
}
Esempio n. 17
0
/* we don't lock future pages here; it would increase the chance that
 * we'd fail to mmap later on. */
void lockdown_memory(bool valgrinding)
{
#if defined(HAVE_MLOCKALL) && !defined(_AIX_)
	/* Extra stack, please! */
	char dummy[10000];
	memset(dummy, 0, sizeof(dummy));

	if (valgrinding) {
		return;
	}

	/* Ignore when running in local daemons mode */
	if (getuid() != 0) {
		return;
	}

	/* Avoid compiler optimizing out dummy. */
	mlock(dummy, sizeof(dummy));
	if (mlockall(MCL_CURRENT) != 0) {
		DEBUG(DEBUG_WARNING,("Failed to lockdown memory: %s'\n",
				     strerror(errno)));
	}
#endif
}
Esempio n. 18
0
gint wsh_client_lock_password_pages(void** passwd_mem) {
	do {
		if (errno == EINTR)
			errno = 0;

		if ((gintptr)(*passwd_mem = mmap(NULL, WSH_MAX_PASSWORD_LEN * 3,
		                                 PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0)) == -1 &&
		        errno != EINTR)
			return errno;

		if (*passwd_mem == NULL && errno != EINTR)
			return errno;
	} while (errno == EINTR);

	do {
		if (errno == EINTR)
			errno = 0;

		if (mlock(*passwd_mem, WSH_MAX_PASSWORD_LEN * 3) && errno != EINTR)
			return errno;
	} while (errno == EINTR);

	return EXIT_SUCCESS;
}
Esempio n. 19
0
File: mem.c Progetto: HackLinux/ltp
static int alloc_mem(long int length, int testcase)
{
	char *s;
	long i, pagesz = getpagesize();

	tst_resm(TINFO, "thread (%lx), allocating %ld bytes.",
		(unsigned long) pthread_self(), length);

	s = mmap(NULL, length, PROT_READ | PROT_WRITE,
		 MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
	if (s == MAP_FAILED)
		return errno;

	if (testcase == MLOCK && mlock(s, length) == -1)
		return errno;
#ifdef HAVE_MADV_MERGEABLE
	if (testcase == KSM && madvise(s, length, MADV_MERGEABLE) == -1)
		return errno;
#endif
	for (i = 0; i < length; i += pagesz)
		s[i] = '\a';

	return 0;
}
Esempio n. 20
0
STDMETHODIMP NetworkAdapter::COMSETTER(HostOnlyInterface)(IN_BSTR aHostOnlyInterface)
{
    Bstr bstrEmpty("");
    if (!aHostOnlyInterface)
        aHostOnlyInterface = bstrEmpty.raw();

    AutoCaller autoCaller(this);
    if (FAILED(autoCaller.rc())) return autoCaller.rc();

    /* the machine needs to be mutable */
    AutoMutableStateDependency adep(mParent);
    if (FAILED(adep.rc())) return adep.rc();

    AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);

    if (mData->mHostOnlyInterface != aHostOnlyInterface)
    {
        mData.backup();
        mData->mHostOnlyInterface = aHostOnlyInterface;

        m_fModified = true;
        // leave the lock before informing callbacks
        alock.release();

        AutoWriteLock mlock(mParent COMMA_LOCKVAL_SRC_POS);       // mParent is const, no need to lock
        mParent->setModified(Machine::IsModified_NetworkAdapters);
        mlock.release();

        /* When changing the host adapter, adapt the CFGM logic to make this
         * change immediately effect and to notify the guest that the network
         * might have changed, therefore changeAdapter=TRUE. */
        mParent->onNetworkAdapterChange(this, TRUE);
    }

    return S_OK;
}
Esempio n. 21
0
int WriteOutResults(PPROGRAM_CONTEXT ProgramContext)
{
	FILE_WRITER_CONTEXT FileWriterContext;
	int Result = NO_ERROR;
	
	//Open File
	Result = OpenOutputFile(ProgramContext, &FileWriterContext);
	if(Result != NO_ERROR)
	{
		return Result;
	}	
	
	mlock(ProgramContext->TweetStrings, ProgramContext->TweetStringsSize);
	
	//Write all Elements
	WriteTweetsToFile(ProgramContext, &FileWriterContext);
	
	munlock(ProgramContext->TweetStrings, ProgramContext->TweetStringsSize);
	
	//close file
	fclose(FileWriterContext.OutputFile);

	return Result;
}
Esempio n. 22
0
static int
tapdisk_syslog_ring_init(td_syslog_t *log, size_t size)
{
	int prot, flags, err;

	__tapdisk_syslog_ring_init(log);

	log->bufsz = page_align(size);

	prot  = PROT_READ|PROT_WRITE;
	flags = MAP_ANONYMOUS|MAP_PRIVATE;

	log->buf = mmap(NULL, log->bufsz, prot, flags, -1, 0);
	if (log->buf == MAP_FAILED) {
		log->buf = NULL;
		err = -ENOMEM;
		goto fail;
	}

	err = mlock(log->buf, size);
	if (err) {
		err = -errno;
		goto fail;
	}

	log->msg    = log->buf;
	log->ring   = log->buf + TD_SYSLOG_PACKET_MAX;
	log->ringsz = size     - TD_SYSLOG_PACKET_MAX;

	return 0;

fail:
	tapdisk_syslog_ring_uninit(log);

	return err;
}
Esempio n. 23
0
static void
lock_pool( void *p, size_t n )
{
#if defined(USE_CAPABILITIES) && defined(HAVE_MLOCK)
    int err;

    cap_set_proc( cap_from_text("cap_ipc_lock+ep") );
    err = mlock( p, n );
    if( err && errno )
	err = errno;
    cap_set_proc( cap_from_text("cap_ipc_lock+p") );

    if( err ) {
	if( errno != EPERM
#ifdef EAGAIN  /* OpenBSD returns this */
	    && errno != EAGAIN
#endif
#ifdef ENOSYS  /* Some SCOs return this (function not implemented) */
	    && errno != ENOSYS
#endif
#ifdef ENOMEM  /* Linux can return this */
            && errno != ENOMEM
#endif
	  )
	    log_error("can't lock memory: %s\n", strerror(err));
	show_warning = 1;
    }

#elif defined(HAVE_MLOCK)
    uid_t uid;
    int err;

    uid = getuid();

#ifdef HAVE_BROKEN_MLOCK
    /* ick. but at least we get secured memory. about to lock
       entire data segment. */
#ifdef HAVE_PLOCK
# ifdef _AIX
    /* The configure for AIX returns broken mlock but the plock has
       the strange requirement to somehow set the stack limit first.
       The problem might turn out in indeterministic program behaviour
       and hanging processes which can somehow be solved when enough
       processes are clogging up the memory.  To get this problem out
       of the way we simply don't try to lock the memory at all.
       */    
    errno = EPERM;
    err = errno;
# else /* !_AIX */
    err = plock( DATLOCK );
    if( err && errno )
        err = errno;
# endif /*_AIX*/
#else /*!HAVE_PLOCK*/
    if( uid ) {
	errno = EPERM;
	err = errno;
    }
    else {
	err = mlock( p, n );
	if( err && errno )
	    err = errno;
    }
#endif /*!HAVE_PLOCK*/
#else
    err = mlock( p, n );
    if( err && errno )
	err = errno;
#endif

    if( uid && !geteuid() ) {
	/* check that we really dropped the privs.
	 * Note: setuid(0) should always fail */
	if( setuid( uid ) || getuid() != geteuid() || !setuid(0) )
	    log_fatal("failed to reset uid: %s\n", strerror(errno));
    }

    if( err ) {
	if( errno != EPERM
#ifdef EAGAIN  /* OpenBSD returns this */
	    && errno != EAGAIN
#endif
#ifdef ENOSYS  /* Some SCOs return this (function not implemented) */
	    && errno != ENOSYS
#endif
#ifdef ENOMEM  /* Linux can return this */
            && errno != ENOMEM
#endif
	  )
#ifdef __VMS
	    log_warning ("can't lock memory: %s\n", strerror(err));
#else
	    log_error ("can't lock memory: %s\n", strerror(err));
#endif
	show_warning = 1;
    }

#elif defined ( __QNX__ )
    /* QNX does not page at all, so the whole secure memory stuff does
     * not make much sense.  However it is still of use because it
     * wipes out the memory on a free().
     * Therefore it is sufficient to suppress the warning
     */
#elif defined (HAVE_DOSISH_SYSTEM) || defined (__CYGWIN__)
    /* It does not make sense to print such a warning, given the fact that 
     * this whole Windows !@#$% and their user base are inherently insecure
     */
#elif defined (__riscos__)
    /* no virtual memory on RISC OS, so no pages are swapped to disc,
     * besides we don't have mmap, so we don't use it! ;-)
     * But don't complain, as explained above.
     */
#else
    log_info("Please note that you don't have secure memory on this system\n");
#endif
}
Esempio n. 24
0
EIF_INTEGER posix_mlock(EIF_POINTER addr, EIF_INTEGER len)
{
  return mlock(addr, len);
}
Esempio n. 25
0
int main(int argc, char *argv[]) {
    struct passwd *pw;
    char *username;
    char *image_path = NULL;
    int ret;
    struct pam_conv conv = {conv_callback, NULL};
    int curs_choice = CURS_NONE;
    int o;
    int optind = 0;
    struct option longopts[] = {
        {"version", no_argument, NULL, 'v'},
        {"nofork", no_argument, NULL, 'n'},
        {"beep", no_argument, NULL, 'b'},
        {"dpms", no_argument, NULL, 'd'},
        {"color", required_argument, NULL, 'c'},
        {"pointer", required_argument, NULL, 'p'},
        {"debug", no_argument, NULL, 0},
        {"help", no_argument, NULL, 'h'},
        {"no-unlock-indicator", no_argument, NULL, 'u'},
        {"image", required_argument, NULL, 'i'},
        {"tiling", no_argument, NULL, 't'},
        {"ignore-empty-password", no_argument, NULL, 'e'},
        {"inactivity-timeout", required_argument, NULL, 'I'},
        {"show-failed-attempts", no_argument, NULL, 'f'},
        {NULL, no_argument, NULL, 0}
    };

    if ((pw = getpwuid(getuid())) == NULL)
        err(EXIT_FAILURE, "getpwuid() failed");
    if ((username = pw->pw_name) == NULL)
        errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");

    char *optstring = "hvnbdc:p:ui:teI:f";
    while ((o = getopt_long(argc, argv, optstring, longopts, &optind)) != -1) {
        switch (o) {
        case 'v':
            errx(EXIT_SUCCESS, "version " VERSION " © 2010 Michael Stapelberg");
        case 'n':
            dont_fork = true;
            break;
        case 'b':
            beep = true;
            break;
        case 'd':
            fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
            break;
        case 'I': {
            int time = 0;
            if (sscanf(optarg, "%d", &time) != 1 || time < 0)
                errx(EXIT_FAILURE, "invalid timeout, it must be a positive integer\n");
            inactivity_timeout = time;
            break;
        }
        case 'c': {
            char *arg = optarg;

            /* Skip # if present */
            if (arg[0] == '#')
                arg++;

            if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
                errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");

            break;
        }
        case 'u':
            unlock_indicator = false;
            break;
        case 'i':
            image_path = strdup(optarg);
            break;
        case 't':
            tile = true;
            break;
        case 'p':
            if (!strcmp(optarg, "win")) {
                curs_choice = CURS_WIN;
            } else if (!strcmp(optarg, "default")) {
                curs_choice = CURS_DEFAULT;
            } else {
                errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
            }
            break;
        case 'e':
            ignore_empty_password = true;
            break;
        case 0:
            if (strcmp(longopts[optind].name, "debug") == 0)
                debug_mode = true;
            break;
        case 'f':
            show_failed_attempts = true;
            break;
        default:
            errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
                 " [-i image.png] [-t] [-e] [-I timeout] [-f]");
        }
    }

    /* We need (relatively) random numbers for highlighting a random part of
     * the unlock indicator upon keypresses. */
    srand(time(NULL));

    /* Initialize PAM */
    ret = pam_start("i3lock", username, &conv, &pam_handle);
    if (ret != PAM_SUCCESS)
        errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));

    /* Using mlock() as non-super-user seems only possible in Linux. Users of other
     * operating systems should use encrypted swap/no swap (or remove the ifdef and
     * run i3lock as super-user). */
#if defined(__linux__)
    /* Lock the area where we store the password in memory, we don’t want it to
     * be swapped to disk. Since Linux 2.6.9, this does not require any
     * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
    if (mlock(password, sizeof(password)) != 0)
        err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
#endif

    /* Double checking that connection is good and operatable with xcb */
    int screennr;
    if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
            xcb_connection_has_error(conn))
        errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");

    if (xkb_x11_setup_xkb_extension(conn,
                                    XKB_X11_MIN_MAJOR_XKB_VERSION,
                                    XKB_X11_MIN_MINOR_XKB_VERSION,
                                    0,
                                    NULL,
                                    NULL,
                                    &xkb_base_event,
                                    &xkb_base_error) != 1)
        errx(EXIT_FAILURE, "Could not setup XKB extension.");

    static const xcb_xkb_map_part_t required_map_parts =
        (XCB_XKB_MAP_PART_KEY_TYPES |
         XCB_XKB_MAP_PART_KEY_SYMS |
         XCB_XKB_MAP_PART_MODIFIER_MAP |
         XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
         XCB_XKB_MAP_PART_KEY_ACTIONS |
         XCB_XKB_MAP_PART_VIRTUAL_MODS |
         XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);

    static const xcb_xkb_event_type_t required_events =
        (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
         XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
         XCB_XKB_EVENT_TYPE_STATE_NOTIFY);

    xcb_xkb_select_events(
        conn,
        xkb_x11_get_core_keyboard_device_id(conn),
        required_events,
        0,
        required_events,
        required_map_parts,
        required_map_parts,
        0);

    /* When we cannot initially load the keymap, we better exit */
    if (!load_keymap())
        errx(EXIT_FAILURE, "Could not load keymap");

    const char *locale = getenv("LC_ALL");
    if (!locale)
        locale = getenv("LC_CTYPE");
    if (!locale)
        locale = getenv("LANG");
    if (!locale) {
        if (debug_mode)
            fprintf(stderr, "Can't detect your locale, fallback to C\n");
        locale = "C";
    }

    load_compose_table(locale);

    xinerama_init();
    xinerama_query_screens();

    screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;

    last_resolution[0] = screen->width_in_pixels;
    last_resolution[1] = screen->height_in_pixels;

    xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
    (uint32_t[]) {
        XCB_EVENT_MASK_STRUCTURE_NOTIFY
    });

    if (image_path) {
        /* Create a pixmap to render on, fill it with the background color */
        img = cairo_image_surface_create_from_png(image_path);
        /* In case loading failed, we just pretend no -i was specified. */
        if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
            fprintf(stderr, "Could not load image \"%s\": %s\n",
                    image_path, cairo_status_to_string(cairo_surface_status(img)));
            img = NULL;
        }
    }

    /* Pixmap on which the image is rendered to (if any) */
    xcb_pixmap_t bg_pixmap = draw_image(last_resolution);

    /* open the fullscreen window, already with the correct pixmap in place */
    win = open_fullscreen_window(conn, screen, color, bg_pixmap);
    xcb_free_pixmap(conn, bg_pixmap);

    pid_t pid = fork();
    /* The pid == -1 case is intentionally ignored here:
     * While the child process is useful for preventing other windows from
     * popping up while i3lock blocks, it is not critical. */
    if (pid == 0) {
        /* Child */
        close(xcb_get_file_descriptor(conn));
        raise_loop(win);
        exit(EXIT_SUCCESS);
    }

    cursor = create_cursor(conn, screen, win, curs_choice);

    grab_pointer_and_keyboard(conn, screen, cursor);
    /* Load the keymap again to sync the current modifier state. Since we first
     * loaded the keymap, there might have been changes, but starting from now,
     * we should get all key presses/releases due to having grabbed the
     * keyboard. */
    (void)load_keymap();

    /* Initialize the libev event loop. */
    main_loop = EV_DEFAULT;
    if (main_loop == NULL)
        errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");

    struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
    struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
    struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);

    ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
    ev_io_start(main_loop, xcb_watcher);

    ev_check_init(xcb_check, xcb_check_cb);
    ev_check_start(main_loop, xcb_check);

    ev_prepare_init(xcb_prepare, xcb_prepare_cb);
    ev_prepare_start(main_loop, xcb_prepare);

    /* Invoke the event callback once to catch all the events which were
     * received up until now. ev will only pick up new events (when the X11
     * file descriptor becomes readable). */
    ev_invoke(main_loop, xcb_check, 0);
    ev_loop(main_loop, 0);
}
Esempio n. 26
0
void sgpgme_create_secret_key(PrefsAccount *account, gboolean ask_create)
{
	AlertValue val = G_ALERTDEFAULT;
	gchar *key_parms = NULL;
	gchar *name = NULL;
	gchar *email = NULL;
	gchar *passphrase = NULL, *passphrase_second = NULL;
	gint prev_bad = 0;
	gchar *tmp = NULL;
	gpgme_error_t err = 0;
	gpgme_ctx_t ctx;
	GtkWidget *window = NULL;
	gpgme_genkey_result_t key;

	if (account == NULL)
		account = account_get_default();

	if (account->address == NULL) {
		alertpanel_error(_("You have to save the account's information with \"OK\" "
				   "before being able to generate a key pair.\n"));
		return;
	}
	if (ask_create) {
		val = alertpanel(_("No PGP key found"),
				_("Claws Mail did not find a secret PGP key, "
				  "which means that you won't be able to sign "
				  "emails or receive encrypted emails.\n"
				  "Do you want to create a new key pair now?"),
				  GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
		if (val == G_ALERTDEFAULT) {
			prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
			prefs_gpg_save_config();
			return;
		}
	}

	if (account->name) {
		name = g_strdup(account->name);
	} else {
		name = g_strdup(account->address);
	}
	email = g_strdup(account->address);
	tmp = g_strdup_printf("%s <%s>", account->name?account->name:account->address, account->address);
again:
	passphrase = passphrase_mbox(tmp, NULL, prev_bad, 1);
	if (passphrase == NULL) {
		g_free(tmp);
		g_free(email);
		g_free(name);		
		return;
	}
	passphrase_second = passphrase_mbox(tmp, NULL, 0, 2);
	if (passphrase_second == NULL) {
		g_free(tmp);
		g_free(email);
		g_free(passphrase);		
		g_free(name);		
		return;
	}
	if (strcmp(passphrase, passphrase_second)) {
		g_free(passphrase);
		g_free(passphrase_second);
		prev_bad = 1;
		goto again;
	}
	
	key_parms = g_strdup_printf("<GnupgKeyParms format=\"internal\">\n"
					"Key-Type: RSA\n"
					"Key-Length: 2048\n"
					"Subkey-Type: RSA\n"
					"Subkey-Length: 2048\n"
					"Name-Real: %s\n"
					"Name-Email: %s\n"
					"Expire-Date: 0\n"
					"%s%s%s"
					"</GnupgKeyParms>\n",
					name, email, 
					strlen(passphrase)?"Passphrase: ":"",
					passphrase,
					strlen(passphrase)?"\n":"");
#ifndef G_PLATFORM_WIN32
	if (mlock(passphrase, strlen(passphrase)) == -1)
		debug_print("couldn't lock passphrase\n");
	if (mlock(passphrase_second, strlen(passphrase_second)) == -1)
		debug_print("couldn't lock passphrase2\n");
#endif
	g_free(tmp);
	g_free(email);
	g_free(name);
	g_free(passphrase_second);
	g_free(passphrase);
	
	err = gpgme_new (&ctx);
	if (err) {
		alertpanel_error(_("Couldn't generate a new key pair: %s"),
				 gpgme_strerror(err));
		g_free(key_parms);
		return;
	}
	

	window = label_window_create(_("Generating your new key pair... Please move the mouse "
			      "around to help generate entropy..."));

	err = gpgme_op_genkey(ctx, key_parms, NULL, NULL);
	g_free(key_parms);

	label_window_destroy(window);

	if (err) {
		alertpanel_error(_("Couldn't generate a new key pair: %s"), gpgme_strerror(err));
		gpgme_release(ctx);
		return;
	}
	key = gpgme_op_genkey_result(ctx);
	if (key == NULL) {
		alertpanel_error(_("Couldn't generate a new key pair: unknown error"));
		gpgme_release(ctx);
		return;
	} else {
		gchar *buf = g_strdup_printf(_("Your new key pair has been generated. "
				    "Its fingerprint is:\n%s\n\nDo you want to export it "
				    "to a keyserver?"),
				    key->fpr ? key->fpr:"null");
		AlertValue val = alertpanel(_("Key generated"), buf,
				  GTK_STOCK_NO, "+" GTK_STOCK_YES, NULL);
		g_free(buf);
		if (val == G_ALERTALTERNATE) {
#ifndef G_OS_WIN32
			gchar *cmd = g_strdup_printf("gpg --no-tty --send-keys %s", key->fpr);
			int res = 0;
			pid_t pid = 0;
			pid = fork();
			if (pid == -1) {
				res = -1;
			} else if (pid == 0) {
				/* son */
				res = system(cmd);
				res = WEXITSTATUS(res);
				_exit(res);
			} else {
				int status = 0;
				time_t start_wait = time(NULL);
				res = -1;
				do {
					if (waitpid(pid, &status, WNOHANG) == 0 || !WIFEXITED(status)) {
						usleep(200000);
					} else {
						res = WEXITSTATUS(status);
						break;
					}
					if (time(NULL) - start_wait > 5) {
						debug_print("SIGTERM'ing gpg\n");
						kill(pid, SIGTERM);
					}
					if (time(NULL) - start_wait > 6) {
						debug_print("SIGKILL'ing gpg\n");
						kill(pid, SIGKILL);
						break;
					}
				} while(1);
			}
			if (res == 0) {
				alertpanel_notice(_("Key exported."));
			} else {
				alertpanel_error(_("Couldn't export key."));
			}
			g_free(cmd);
#else
			alertpanel_error(_("Key export isn't implemented in Windows."));
#endif
		}
	}
	prefs_gpg_get_config()->gpg_ask_create_key = FALSE;
	prefs_gpg_save_config();
	gpgme_release(ctx);
}
Esempio n. 27
0
ATF_TC_BODY(mincore_resid, tc)
{
	void *addr, *addr2, *addr3, *buf;
	size_t npgs = 0, resident;
	struct stat st;
	int fd, rv;
	struct rlimit rlim;

	ATF_REQUIRE(getrlimit(RLIMIT_MEMLOCK, &rlim) == 0);
#ifdef __FreeBSD__
	/*
	 * Bump the mlock limit to unlimited so the rest of the testcase
	 * passes instead of failing on the mlock call.
	 */
	rlim.rlim_max = RLIM_INFINITY;
#endif
	rlim.rlim_cur = rlim.rlim_max;
	ATF_REQUIRE(setrlimit(RLIMIT_MEMLOCK, &rlim) == 0);

	(void)memset(&st, 0, sizeof(struct stat));

	fd = open(path, O_RDWR | O_CREAT, 0700);
	buf = malloc(page * 5);

	ATF_REQUIRE(fd >= 0);
	ATF_REQUIRE(buf != NULL);

	rv = write(fd, buf, page * 5);
	ATF_REQUIRE(rv >= 0);

	ATF_REQUIRE(fd >= 0);
	ATF_REQUIRE(fstat(fd, &st) == 0);

	addr = mmap(NULL, (size_t)st.st_size, PROT_READ,
	    MAP_FILE | MAP_SHARED, fd, (off_t) 0);

	ATF_REQUIRE(addr != MAP_FAILED);

	(void)close(fd);

	npgs = st.st_size / page;

	if (st.st_size % page != 0)
		npgs++;

	(void)check_residency(addr, npgs);

	rv = mlock(addr, npgs * page);
	if (rv == -1 && errno == EAGAIN)
		atf_tc_skip("hit process resource limits");
	ATF_REQUIRE(munmap(addr, st.st_size) == 0);

	npgs = 128;

#ifdef __FreeBSD__
	addr = mmap(NULL, npgs * page, PROT_READ | PROT_WRITE,
	    MAP_ANON | MAP_PRIVATE, -1, (off_t)0);
#else
	addr = mmap(NULL, npgs * page, PROT_READ | PROT_WRITE,
	    MAP_ANON | MAP_PRIVATE | MAP_WIRED, -1, (off_t)0);
#endif

	if (addr == MAP_FAILED)
		atf_tc_skip("could not mmap wired anonymous test area, system "
		    "might be low on memory");

#ifdef __FreeBSD__
	if (mlock(addr, npgs * page) == -1 && errno != ENOMEM)
		atf_tc_skip("could not wire anonymous test area, system might "
		    "be low on memory");
#endif
	ATF_REQUIRE(check_residency(addr, npgs) == npgs);
	ATF_REQUIRE(munmap(addr, npgs * page) == 0);

	npgs = 128;

	addr = mmap(NULL, npgs * page, PROT_READ | PROT_WRITE,
	    MAP_ANON | MAP_PRIVATE, -1, (off_t)0);

	ATF_REQUIRE(addr != MAP_FAILED);

	/*
	 * Check that the in-core pages match the locked pages.
	 */
	ATF_REQUIRE(check_residency(addr, npgs) == 0);

	errno = 0;
	if (mlockall(MCL_CURRENT|MCL_FUTURE) != 0 && errno != ENOMEM)
		atf_tc_fail("mlockall(2) failed");
	if (errno == ENOMEM)
		atf_tc_skip("mlockall() exceeded process resource limits");

	resident = check_residency(addr, npgs);
	if (resident < npgs)
		atf_tc_fail("mlockall(MCL_FUTURE) succeeded, still only "
		    "%zu pages of the newly mapped %zu pages are resident",
		    resident, npgs);

	addr2 = mmap(NULL, npgs * page, PROT_READ, MAP_ANON, -1, (off_t)0);
	addr3 = mmap(NULL, npgs * page, PROT_NONE, MAP_ANON, -1, (off_t)0);

	if (addr2 == MAP_FAILED || addr3 == MAP_FAILED)
		atf_tc_skip("could not mmap more anonymous test pages with "
		    "mlockall(MCL_FUTURE) in effect, system "
		    "might be low on memory");

	ATF_REQUIRE(check_residency(addr2, npgs) == npgs);
	ATF_REQUIRE(check_residency(addr3, npgs) == 0);
	ATF_REQUIRE(mprotect(addr3, npgs * page, PROT_READ) == 0);
	ATF_REQUIRE(check_residency(addr, npgs) == npgs);
	ATF_REQUIRE(check_residency(addr2, npgs) == npgs);

	(void)munlockall();

	ATF_REQUIRE(madvise(addr2, npgs * page, MADV_FREE) == 0);
#ifdef __NetBSD__
	ATF_REQUIRE(check_residency(addr2, npgs) == 0);
#endif

	(void)memset(addr, 0, npgs * page);

	ATF_REQUIRE(madvise(addr, npgs * page, MADV_FREE) == 0);
#ifdef __NetBSD__
	ATF_REQUIRE(check_residency(addr, npgs) == 0);
#endif

	(void)munmap(addr, npgs * page);
	(void)munmap(addr2, npgs * page);
	(void)munmap(addr3, npgs * page);
	(void)unlink(path);
}
Esempio n. 28
0
void CacheObject::setData( const LRULinkedList::node_ref& data)
{
    std::unique_lock< std::mutex > mlock( _mutex );
    _data = data;
}
Esempio n. 29
0
ObjectHandlerPtr CacheObject::createHandler()
{
    std::unique_lock< std::mutex > mlock( _mutex );
    _nRefs++;
    return ObjectHandlerPtr( new ObjectHandler( shared_from_this() ) );
}
Esempio n. 30
0
CacheObject::State CacheObject::getState()
{
    std::unique_lock< std::mutex > mlock( _mutex );
    return _state;
}