コード例 #1
0
ファイル: dowse.c プロジェクト: cryptocurrent/dowse
int
dowse_start(logerr_t *a_logerr) {
    /*
     * The "start" function is called once, when the program
     * starts.  It is used to initialize the plugin.  If the
     * plugin wants to write debugging and or error messages,
     * it should save the a_logerr pointer passed from the
     * parent code.
     */

    logerr = a_logerr;
    if (filepfx) {
        logerr("Logging to file: %s\n", filepfx);
        fileout = fopen(filepfx, "a");
        if (0 == fileout) {
            logerr("%s: %s\n", filepfx, strerror(errno));
            exit(1);
        }
    }

    // get own hostname
    gethostname(hostname,(size_t)MAX_DOMAIN);

    visited = hashmap_new();

    // load the domain-list path if there
    if(listpath) load_domainlist(listpath);

    connect_redis();

    return 0;
}
コード例 #2
0
ファイル: ickDevice.c プロジェクト: ickStream/ickstream-p2p
/*=========================================================================*\
    Create an new device
\*=========================================================================*/
ickDevice_t *_ickDeviceNew( const char *uuid )
{
  ickDevice_t *device;
  debug( "_ickDeviceNew: \"%s\"", uuid );

/*------------------------------------------------------------------------*\
    Allocate and initialize descriptor
\*------------------------------------------------------------------------*/
  device = calloc( 1, sizeof(ickDevice_t) );
  if( !device ) {
    logerr( "_ickDeviceNew: out of memory" );
    return NULL;
  }
  pthread_mutex_init( &device->mutex, NULL );
  device->uuid = strdup( uuid );
  if( !device->uuid ) {
    logerr( "_ickDeviceNew: out of memory" );
    return NULL;
  }
  device->tCreation = _ickTimeNow();

/*------------------------------------------------------------------------*\
    That's all
\*------------------------------------------------------------------------*/
  return device;
}
コード例 #3
0
BOOL RemoveFromDupWithinList(_In_ PFILEINFO pFileToDelete, _In_ PDUPFILES_WITHIN pDupWithinToSearch)
{
    WCHAR szCompareFromPath[MAX_PATH];
    if (FAILED(PathCchCombine(szCompareFromPath, ARRAYSIZE(szCompareFromPath), pFileToDelete->szPath, pFileToDelete->szFilename) == NULL))
    {
        logerr(L"PathCchCombine() failed for %s + %s", pFileToDelete->szPath, pFileToDelete->szFilename);
        return FALSE;
    }

    WCHAR szCompareToPath[MAX_PATH];
    for (int i = 0; i < pDupWithinToSearch->nCurFiles; ++i)
    {
        PFILEINFO pFile;
        if (FAILED(CHL_DsReadRA(&pDupWithinToSearch->aFiles, i, &pFile, NULL, TRUE)))
        {
            continue;
        }

        if (FAILED(PathCchCombine(szCompareToPath, ARRAYSIZE(szCompareToPath), pFile->szPath, pFile->szFilename) == NULL))
        {
            logerr(L"PathCchCombine() failed for %s + %s", pFile->szPath, pFile->szFilename);
            return FALSE;
        }

        if (_wcsnicmp(szCompareFromPath, szCompareToPath, MAX_PATH) == 0)
        {
            CHL_DsClearAtRA(&pDupWithinToSearch->aFiles, i);
            return TRUE;
        }
    }
    return FALSE;
}
コード例 #4
0
ファイル: agentpns.cpp プロジェクト: tewalds/pentagod
void AgentPNS::PNSThread::run(){
	while(true){
		switch(agent->threadstate){
		case Thread_Cancelled:  //threads should exit
			return;

		case Thread_Wait_Start: //threads are waiting to start
		case Thread_Wait_Start_Cancelled:
			agent->runbarrier.wait();
			CAS(agent->threadstate, Thread_Wait_Start, Thread_Running);
			CAS(agent->threadstate, Thread_Wait_Start_Cancelled, Thread_Cancelled);
			break;

		case Thread_Wait_End:   //threads are waiting to end
			agent->runbarrier.wait();
			CAS(agent->threadstate, Thread_Wait_End, Thread_Wait_Start);
			break;

		case Thread_Running:    //threads are running
			if(agent->root.terminal()){ //solved
				CAS(agent->threadstate, Thread_Running, Thread_Wait_End);
				break;
			}
			if(agent->ctmem.memalloced() >= agent->memlimit){ //out of memory, start garbage collection
				CAS(agent->threadstate, Thread_Running, Thread_GC);
				break;
			}

			pns(agent->rootboard, &agent->root, 0, INF32/2, INF32/2);
			break;

		case Thread_GC:         //one thread is running garbage collection, the rest are waiting
		case Thread_GC_End:     //once done garbage collecting, go to wait_end instead of back to running
			if(agent->gcbarrier.wait()){
				logerr("Starting solver GC with limit " + to_str(agent->gclimit) + " ... ");

				Time starttime;
				agent->garbage_collect(& agent->root);

				Time gctime;
				agent->ctmem.compact(1.0, 0.75);

				Time compacttime;
				logerr(to_str(100.0*agent->ctmem.meminuse()/agent->memlimit, 1) + " % of tree remains - " +
					to_str((gctime - starttime)*1000, 0)  + " msec gc, " + to_str((compacttime - gctime)*1000, 0) + " msec compact\n");

				if(agent->ctmem.meminuse() >= agent->memlimit/2)
					agent->gclimit = (unsigned int)(agent->gclimit*1.3);
				else if(agent->gclimit > 5)
					agent->gclimit = (unsigned int)(agent->gclimit*0.9); //slowly decay to a minimum of 5

				CAS(agent->threadstate, Thread_GC,     Thread_Running);
				CAS(agent->threadstate, Thread_GC_End, Thread_Wait_End);
			}
			agent->gcbarrier.wait();
			break;
		}
	}
}
コード例 #5
0
ファイル: relay.c プロジェクト: achaussier/carbon-c-relay
static void
hup_handler(int sig)
{
	route *newroutes;
	cluster *newclusters;
	int id;
	FILE *newfd;

	logout("caught SIGHUP...\n");
	if (relay_stderr != stderr) {
		/* try to re-open the file first, so we can still try and say
		 * something if that fails */
		if ((newfd = fopen(relay_logfile, "a")) == NULL) {
			logerr("not reopening logfiles: can't open '%s': %s\n",
					relay_logfile, strerror(errno));
		} else {
			logout("closing logfile\n");
			relay_can_log = 0;
			fclose(relay_stderr);
			relay_stdout = newfd;
			relay_stderr = newfd;
			relay_can_log = 1;
			logout("reopening logfile\n");
		}
	}
	logout("reloading config from '%s'...\n", config);

	if (router_readconfig(&newclusters, &newroutes,
				config, queuesize, batchsize) == 0)
	{
		logerr("failed to read configuration '%s', aborting reload\n",
				config);
		return;
	}
	router_optimise(&newroutes);

	logout("reloading worker");
	for (id = 1; id < 1 + workercnt; id++)
		dispatch_schedulereload(workers[id + 0], newroutes);
	for (id = 1; id < 1 + workercnt; id++) {
		while (!dispatch_reloadcomplete(workers[id + 0]))
			usleep((100 + (rand() % 200)) * 1000);  /* 100ms - 300ms */
		fprintf(relay_stdout, " %d", id + 1);
		fflush(relay_stdout);
	}
	fprintf(relay_stdout, "\n");

	logout("reloading collector\n");
	collector_schedulereload(newclusters);
	while (!collector_reloadcomplete())
		usleep((100 + (rand() % 200)) * 1000);  /* 100ms - 300ms */

	router_free(clusters, routes);

	routes = newroutes;
	clusters = newclusters;

	logout("SIGHUP handler complete\n");
}
コード例 #6
0
ファイル: audio.c プロジェクト: braincat/uwin
static HANDLE open_dsp(Devtab_t* dp, Pfd_t* fdp, Path_t *ip, int oflags, HANDLE *extra)
{
	HANDLE hp;
	int blkno, minor = ip->name[1];
	Pdev_t *pdev;
	unsigned short *blocks = devtab_ptr(Share->chardev_index, AUDIO_MAJOR);

	if(load_audio())
	{

		/* If the device is already opened */
		if(blkno = blocks[minor])
		{
			logerr(LOG_DEV+5, "Device Busy");
			errno = EBUSY;
			return 0;
		}
		else
		{
			WAVEFORMATEX *wp;
			if((blkno = block_alloc(BLK_PDEV)) == 0)
				return(0);
			pdev = dev_ptr(blkno);
			wp = (WAVEFORMATEX*)(pdev+1);
			ZeroMemory((void *)pdev, BLOCK_SIZE-1);
			/* Initialising the wave format sturcture */
			wp->wFormatTag=WAVE_FORMAT_PCM;
			wp->nChannels=CHANNELS;
			wp->nSamplesPerSec=SAMPLES_PER_SEC;
			if(minor&1)
				wp->nSamplesPerSec *= 2;
			wp->wBitsPerSample=BITS_PER_SAMPLE;
			wp->nBlockAlign=(wp->wBitsPerSample*CHANNELS)/8 ;
			wp->nAvgBytesPerSec=wp->nSamplesPerSec*wp->nBlockAlign;
			wp->cbSize=EXTRA_FORMAT_SIZE;
			if(!audio_open(pdev,1))

			{
				logerr(LOG_DEV+5, "waveOutOpen");
				block_free((unsigned short)blkno);
				return 0;
			}
			hp = AUDIO_HANDLE;
			pdev->major=AUDIO_MAJOR;
			pdev->minor = minor;
			uwin_pathmap(ip->path, pdev->devname, sizeof(pdev->devname), UWIN_W2U);

			fdp->devno = blkno;
			blocks[minor] = blkno;
			pdev->devpid = P_CP->pid;
		}
		return hp;
	}
	else
	{
		logerr(0, "audio functions not supported");
		return 0;
	}
}
コード例 #7
0
ファイル: daemon.c プロジェクト: YoshikazuNakahara/Unixv7x86
main()
{
	register char *p1, *p2;
	FILE *df;

	dem_setup();
	LDIRNAM = 0;		/*calculate length of directory name. MRW*/
	while(dfname[LDIRNAM])  LDIRNAM++;
	LCHAR = LDIRNAM + 2;
	LPID = LDIRNAM + 3;

again:
	snsum = 0;
	if(access(lock, 0) < 0){
		logerr("Lock has disappeared.");
		dem_dis();
		exit(1);
	}
	df = fopen(dpd, "r");
	if (df) {
		do {
			if(fread((char *)&dbuf, sizeof dbuf, 1, df) < 1){
				dem_dis();	/*disconnect phone line. MRW*/
				unlink(lock);
				exit(0);
			}
		} while (dbuf.d_ino==0 || dbuf.d_name[0]!='d' || dbuf.d_name[1]!='f');
		fclose(df);
	}
	p1 = dbuf.d_name;
	p2 = &dfname[LDIRNAM];
	while (p1 < &dbuf.d_name[DIRSIZ])
		*p2++ = *p1++;
	if (trysend() == 0) {
		waittm = 60;
		nwait = 0;
		goto again;
		}
#if PHONE
	if(nwait > 10){		/*after 3 hours try fresh daemon. MRW*/
		unlink(lock);
		execl("/usr/lib/dpd", "dpd", (char *)0);
		execl("/etc/dpd", "dpd", (char *)0);
		logerr("Can't find dpd.");
		exit(1);
	}
#endif
	sleep(waittm);
#if PHONE || SPIDER
#ifndef DEBUG
	if (waittm <= 8*60)
		waittm *= 2;
	else
		nwait++;
#endif
#endif
	goto again;
}
コード例 #8
0
ファイル: soccr.c プロジェクト: Snorch/criu
static int refresh_sk(struct libsoccr_sk *sk, struct libsoccr_sk_data *data, struct tcp_info *ti)
{
	int size;
	socklen_t olen = sizeof(*ti);

	if (getsockopt(sk->fd, SOL_TCP, TCP_INFO, ti, &olen) || olen != sizeof(*ti)) {
		logerr("Failed to obtain TCP_INFO");
		return -1;
	}

	switch (ti->tcpi_state) {
	case TCP_ESTABLISHED:
	case TCP_FIN_WAIT1:
	case TCP_FIN_WAIT2:
	case TCP_LAST_ACK:
	case TCP_CLOSE_WAIT:
	case TCP_CLOSING:
	case TCP_CLOSE:
	case TCP_SYN_SENT:
		break;
	default:
		loge("Unknown state %d\n", ti->tcpi_state);
		return -1;
	}

	data->state = ti->tcpi_state;

	if (ioctl(sk->fd, SIOCOUTQ, &size) == -1) {
		logerr("Unable to get size of snd queue");
		return -1;
	}

	data->outq_len = size;

	if (ioctl(sk->fd, SIOCOUTQNSD, &size) == -1) {
		logerr("Unable to get size of unsent data");
		return -1;
	}

	data->unsq_len = size;

	/* Don't account the fin packet. It doesn't countain real data. */
	if ((1 << data->state) & (SNDQ_FIRST_FIN | SNDQ_SECOND_FIN)) {
		if (data->outq_len)
			data->outq_len--;
		data->unsq_len = data->unsq_len ? data->unsq_len - 1 : 0;
	}

	if (ioctl(sk->fd, SIOCINQ, &size) == -1) {
		logerr("Unable to get size of recv queue");
		return -1;
	}

	data->inq_len = size;

	return 0;
}
コード例 #9
0
ファイル: T2accel.C プロジェクト: zhuww/tempo2
/**
 * An accelerated cholesky decomposion to form uinv in plac.
 * uinv is a lower triangular, row-major, matrix.
 */
int accel_uinv(double* _m, int n){
   int i,j;

   double* _u=_m;
   double* _uinv=_m;
   double* _t=(double*)malloc(sizeof(double)*(n*(n+1))/2);


   // LAPACK Cholesky factorisation.
   // _u is a symetric matrix.
   F77_dpotf2("L",&n,_u,&n,&i);
   if(i!=0){
	  logerr("Error in Cholesky Decomp i=%d",i);
      return i;
   }

   // This code taken from the LAPACK documentation
   // to pack a triangular matrix.
   int jc=0;
   for (j=0;j<n;j++){ // cols
	  for (i=j;i<n;i++){ //rows
		 // note that at this point _u is ordered column major
		 // because the LAPACK routine is a FORTRAN code.
		 _t[jc+i-j] = _u[j*n+i];
	  }
	  jc=jc+n-j;
   }

   logdbg("Done CholDecomp... Inverting...",i);
   F77_dtptri("L","N",&n,_t,&i);
   if(i!=0){
	  logerr("Error in Invert i=%d",i);
      return i;
   }

   // Unpack the triangular matrix using reverse
   // of code above, but unpacking into a row-major matrix
   // for C compatibility.
   jc=0;
   for (j=0;j<n;j++){ // cols
	  for (i=0; i < j; i++){
		 // when unpacking we need to zero out the strict upper triangle.
		 _u[i*n+j]=0;
	  }
	  for (i=j;i<n;i++){ //rows
		 // here we arange _u in row-major order
		 // to be C compatible on return.
		 _u[i*n+j]=_t[jc+i-j];
	  }
	  jc=jc+n-j;
   }
   free(_t);

   logdbg("Done Invert.",i);
   return 0;
}
コード例 #10
0
ファイル: drcomd.c プロジェクト: csujedihy/drcom4mac
static void do_one_client(int s, struct drcom_handle *h)
{
	struct drcomcd_hdr cd_hdr;
	int s2;
	fd_set	rfds;
	struct timeval t;
	int r;

	s2 = accept(s, NULL, NULL);
	if (s2 == -1 && errno != EINTR) {
		logerr("daemon: accept failed: %s", strerror(errno));
		return;
	}

	FD_ZERO(&rfds);
	FD_SET(s2, &rfds);
	t.tv_sec = 2;
	t.tv_usec = 0;
	r = select(s2+1, &rfds, NULL, NULL, &t);
	if(r<=0){
		logerr("accepted, but no data\n");
		goto error;
	}

	if(!FD_ISSET(s2, &rfds)){
		goto error;
	}

	r = safe_recv(s2, &cd_hdr, sizeof(struct drcomcd_hdr));
	if (r != sizeof(struct drcomcd_hdr)){
		logerr("daemon: recv: %s", strerror(errno));
		goto error;
	}
	if (cd_hdr.signature != DRCOM_SIGNATURE) {
		logerr("Unknown signature\n");
		goto error;
	}

	switch (cd_hdr.type) {
	case DRCOMCD_LOGIN:
		do_command_login(s2, h);
		break;
	case DRCOMCD_LOGOUT:
		do_command_logout(s2, h);
		break;
	case DRCOMCD_PASSWD:
		do_command_passwd(s2, h);
		break;
	default:
		break;
	}

error:
	close(s2);
	return;
}
コード例 #11
0
ファイル: Server.cpp プロジェクト: wjkcow/SJTU489P
Server::Server(const char* port){
    int rc;
    
    addrinfo hints;
    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    
    addrinfo *ai;
    getaddrinfo(nullptr, port, &hints, &ai);
    
    if (rc) {
        fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(rc));
        throw std::exception();
    }
    
    listen_sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
    if (listen_sock < 0) {
        logerr("creating socket");
        throw std::exception();
    }
    
    int yes = 1;
    rc = setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
    if (rc) {
        logerr("setsockopt failed");
        throw std::exception();
    }
    
    rc = bind(listen_sock, ai->ai_addr, ai->ai_addrlen);
    if (rc) {
        logerr("bind failed");
        throw std::exception();
    }
    
    freeaddrinfo(ai);
    
    rc = listen(listen_sock, 10);
    if (rc) {
        logerr("listen failed");
        throw std::exception();
    }
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    
    rc = getsockname(listen_sock, (struct sockaddr *)&addr, &len);
    if (rc) {
        logerr("getsockname failed");
        throw std::exception();
    }
    std::cout << "Server accepting connection " << ntohs(addr.sin_port) << std::endl;
    _thread = std::thread(&Server::accept_connection, this);
   // add_task(std::bind(&ServerConnection::accept_connection, this));
}
コード例 #12
0
ファイル: drcomd.c プロジェクト: csujedihy/drcom4mac
static void drcomd_daemon(struct drcom_handle *h)
{
	int s;
	int r;

	s = init_daemon_socket();
	if(s < 0)
		exit(-1);

	if(setup_sig_handlers()<0){
		logerr("sig handlers not setup, exit.\n");
		exit(1);
	}

	loginfo("drcomd %s started.\n", DRCOM_VERSION);

	while (1) {
		int maxfd;
		fd_set readfds;

		FD_ZERO(&readfds);
		FD_SET(s, &readfds);
		FD_SET(sigusr1_pipe[READ_END], &readfds);
		
		maxfd = s;
		if(maxfd < sigusr1_pipe[READ_END])
			maxfd = sigusr1_pipe[READ_END];

		unblock_sigusr1();
		r = select(maxfd+1, &readfds, NULL,NULL, NULL);
		if(r<0){
			if(errno != EINTR)
				logerr("signal caught\n");
			continue;
		}
		if(FD_ISSET(sigusr1_pipe[READ_END], &readfds)){
			char buf[256];
			int *sig = (int*)buf;

			read(sigusr1_pipe[READ_END], &buf, sizeof(buf));
			do_signals(h, *sig);
		}
		if(!FD_ISSET(s, &readfds))
			continue;

		block_sigusr1();
		do_one_client(s, h);
	}

	/* FIXME: 
	 * drcom_clean_up();
	 * drcom_destroy_handle();
	 * close_daemon_socket(); 
	 */
}
コード例 #13
0
ファイル: os_unix.c プロジェクト: askovpen/binkleyforce
/*
 *  Return -1 if error occured while excuting command, other values
 *  are return codes of your command
 */
int xsystem(const char *command, const char *p_input, const char *p_output)
{
	pid_t pid;
	int status;

	ASSERT(command != NULL);
	
	DEB((D_INFO, "xsystem: command \"%s\", input \"%s\", output \"%s\"",
		command, p_input, p_output));

	switch(pid=fork()) {
	case -1:
		return(-1);
	case  0:	
		if( p_input )
		{
			close(0);
			if( open(p_input, O_RDONLY) != 0 )
			{
				logerr("can't open stdin \"%s\"", p_input);
				exit(-1);
			}
		}
		if( p_output )
		{
			close(1);
			if( open(p_output, O_WRONLY|O_APPEND|O_CREAT, 0600) != 1 )
			{
				logerr("can't open stdout \"%s\"", p_output);
				exit(-1);
			}
		}
		if( p_output )
		{
			close(2);
			if( open(p_output, O_WRONLY|O_APPEND|O_CREAT, 0600) != 2 )
			{
				logerr("can't open stderr \"%s\"", p_output);
				exit(-1);
			}
		}
#ifdef SHELL
		execl(SHELL, "sh", "-c", command, NULL);
#else
		execl("/bin/sh", "sh", "-c", command, NULL);
#endif
		exit( (errno == 0)?0:-1 );	
	}

	if( waitpid(pid, &status, 0) == pid && WIFEXITED(status) )
	{
		return(WEXITSTATUS(status));
	}
	return(-1);
}
コード例 #14
0
ファイル: pkginfo.c プロジェクト: Sunshine-OS/pkg-gate
static void
rdcontents(void)
{
	VFP_T		*vfp;
	struct cfstat	*dp;
	struct pinfo	*pinfo;
	int		n;

	if (vfpOpen(&vfp, contents, "r", VFP_NEEDNOW) != 0) {
		progerr(gettext("unable to open \"%s\" for reading"), contents);
		exit(1);
	}

	/* check the contents file to look for referenced packages */
	while ((n = srchcfile(&entry, "*", vfp, (VFP_T *)NULL)) > 0) {
		for (pinfo = entry.pinfo; pinfo; pinfo = pinfo->next) {
			/* see if entry is used by indicated packaged */
			if (pkgcnt && (selectp(pinfo->pkg) < 0))
				continue;

			dp = fpkg(pinfo->pkg);
			pkgusage(dp, &entry);

			if (entry.npkgs > 1)
				dp->shared++;

			/*
			 * Only objects specifically tagged with '!' event
			 * character are considered "partial", everything
			 * else is considered "installed" (even server
			 * objects).
			 */
			switch (pinfo->status) {
			case '!' :
				dp->partial++;
				break;
			default :
				dp->installed++;
				break;
			}
		}
	}
	if (n < 0) {
		char	*errstr = getErrstr();
		progerr(gettext("bad entry read in contents file"));
		logerr(gettext("pathname: %s"),
		    (entry.path && *entry.path) ? entry.path : "Unknown");
		logerr(gettext("problem: %s"),
		    (errstr && *errstr) ? errstr : "Unknown");
		exit(1);
	}

	(void) vfpClose(&vfp);
}
コード例 #15
0
ファイル: signal.c プロジェクト: csujedihy/drcom4mac
int setup_sig_handlers(void)
{
	struct sigaction sa;
	int retval;

	retval = pipe(sigusr1_pipe);
	if (retval < 0) {
		logerr("error getting pipes: %s", strerror(errno));
		return -1;
	}

	retval = fcntl(sigusr1_pipe[READ_END], F_GETFL, 0);
	if (retval < 0) {
		logerr("error fcntl on read pipe: %s", strerror(errno));
		goto exit;
	}
	retval = fcntl(sigusr1_pipe[READ_END], F_SETFL, retval | O_NONBLOCK);
	if (retval < 0) {
		logerr("error fcntl on read pipe: %s", strerror(errno));
		goto exit;
	}

	retval = fcntl(sigusr1_pipe[WRITE_END], F_GETFL, 0);
	if (retval < 0) {
		logerr("error fcntl on write pipe: %s", strerror(errno));
		goto exit;
	}
	retval = fcntl(sigusr1_pipe[WRITE_END], F_SETFL, retval | O_NONBLOCK);
	if (retval < 0) {
		logerr("error fcntl on write pipe: %s", strerror(errno));
		goto exit;
	}

	memset(&sa, 0x00, sizeof(sa));
	sa.sa_handler = sigusr1_handler;
	sa.sa_flags = SA_RESTART;
	sigemptyset (&sa.sa_mask);
	sigaction (SIGUSR1, &sa, NULL);
	sigaction (SIGTERM, &sa, NULL);

	memset(&sa, 0, sizeof(sa));
	sa.sa_handler = SIG_IGN;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);
	sigaction(SIGPIPE, &sa, NULL);

	return 0;

exit:
	close(sigusr1_pipe[READ_END]);
	close(sigusr1_pipe[WRITE_END]);
	return -1;
}
コード例 #16
0
int lookup_init(const char *mapfmt, int argc, const char *const *argv, void **context)
{
	struct lookup_context *ctxt;
	char buf[MAX_ERR_BUF];
	struct stat st;

	*context = NULL;
	ctxt = malloc(sizeof(struct lookup_context));
	if (!ctxt) {
		char *estr = strerror_r(errno, buf, MAX_ERR_BUF);
		logerr(MODPREFIX "malloc: %s", estr);
		return 1;
	}

	if (argc < 1) {
		free(ctxt);
		logerr(MODPREFIX "No map name");
		return 1;
	}

	ctxt->mapname = argv[0];

	if (ctxt->mapname[0] != '/') {
		free(ctxt);
		logmsg(MODPREFIX
		     "dir map %s is not an absolute pathname", argv[0]);
		return 1;
	}

	if (access(ctxt->mapname, R_OK)) {
		free(ctxt);
		warn(LOGOPT_NONE, MODPREFIX
		     "dir map %s missing or not readable", argv[0]);
		return 1;
	}

	if (stat(ctxt->mapname, &st)) {
		free(ctxt);
		warn(LOGOPT_NONE, MODPREFIX
		     "dir map %s, could not stat", argv[0]);
		return 1;
	}

	if ( (!S_ISDIR(st.st_mode)) && (!S_ISLNK(st.st_mode)) ) {
		free(ctxt);
		warn(LOGOPT_NONE, MODPREFIX
		     "dir map %s, is not a directory", argv[0]);
		return 1;
	}

	*context = ctxt;
	return 0;
}
コード例 #17
0
ファイル: pkgtrans.c プロジェクト: apprisi/illumos-gate
/*
 * Name:		dump_hdr_and_pkgs
 * Description:	Dumps datastream header and each package's contents
 *		to the supplied BIO
 *
 * Arguments:	bio - BIO object to dump data to
 *		hdr - Header for the datastream being dumped
 *		pkglist - NULL-terminated list of packages
 *		to dump.  The location of the packages are stored
 *		in the static 'srcdev' variable.
 *
 * Returns :   	0 - success
 *		nonzero - failure.  errors printed to screen.
 */
static int
dump_hdr_and_pkgs(BIO *bio, struct dm_buf *hdr, char **pkglist)
{
	int	block_cnt, i;
	char	srcdir[MAXPATHLEN];
	char	cwd[MAXPATHLEN + 1];
	char	*src;

	/* write out the header to the signature stream */
	for (block_cnt = 0; block_cnt < hdr->allocation;
		block_cnt += BLK_SIZE) {
		(void) BIO_write(bio, (hdr->text_buffer + block_cnt), BLK_SIZE);
	}

	/* save current directory */
	if (getcwd(cwd, MAXPATHLEN + 1) == NULL) {
		logerr(pkg_gt(ERR_GETWD));
		progerr(pkg_gt(ERR_TRANSFER));
		return (1);
	}

	/* now write out each package's contents */
	for (i = 0; pkglist[i]; i++) {
		/*
		 * change to the source dir, so we can find and dump
		 * the package(s) bits into the BIO
		 *
		 */
		src = srcdev.dirname;

		/* change to the package source directory */
		(void) snprintf(srcdir, MAXPATHLEN, "%s/%s", src, pkglist[i]);
		if (chdir(srcdir)) {
			progerr(pkg_gt(ERR_TRANSFER));
			logerr(pkg_gt(MSG_CHDIR), srcdir);
			return (1);
		}

		if (pkgdump(pkglist[i], bio)) {
			pkglist[i] = NULL;
			return (1);
		}
	}

	/* change back to directory we were in upon entering this routine */
	if (chdir(cwd)) {
		progerr(pkg_gt(ERR_TRANSFER));
		logerr(pkg_gt(MSG_CHDIR), cwd);
		return (1);
	}

	return (0);
}
コード例 #18
0
ファイル: dockspace.c プロジェクト: AlfredArouna/illumos-gate
static void
warn(int type, char *name, fsblkcnt_t need, fsblkcnt_t avail, fsblkcnt_t limit)
{
	logerr(gettext("WARNING:"));
	if (type == TYPE_BLCK) {
		logerr(gettext(WRN_NOBLKS), name, avail, (need + limit), limit,
		    (need + limit - avail));
	} else {
		logerr(gettext(WRN_NOFILES), name, avail, (need + limit), limit,
		    (need + limit - avail));
	}
}
コード例 #19
0
ファイル: pkginfo.c プロジェクト: drscream/illumos-joyent
static void
rdcontents(void)
{
	struct cfstat	*dp;
	struct pinfo	*pinfo;
	int		n;
	PKGserver	server;

	if (!socfile(&server, B_TRUE) ||
	    pkgopenfilter(server, pkgcnt == 1 ? pkg[0] :  NULL) != 0)
		exit(1);

	/* check the contents file to look for referenced packages */
	while ((n = srchcfile(&entry, "*", server)) > 0) {
		for (pinfo = entry.pinfo; pinfo; pinfo = pinfo->next) {
			/* see if entry is used by indicated packaged */
			if (pkgcnt && (selectp(pinfo->pkg) < 0))
				continue;

			dp = fpkg(pinfo->pkg);
			pkgusage(dp, &entry);

			if (entry.npkgs > 1)
				dp->shared++;

			/*
			 * Only objects specifically tagged with '!' event
			 * character are considered "partial", everything
			 * else is considered "installed" (even server
			 * objects).
			 */
			switch (pinfo->status) {
			case '!' :
				dp->partial++;
				break;
			default :
				dp->installed++;
				break;
			}
		}
	}
	if (n < 0) {
		char	*errstr = getErrstr();
		progerr(gettext("bad entry read in contents file"));
		logerr(gettext("pathname: %s"),
		    (entry.path && *entry.path) ? entry.path : "Unknown");
		logerr(gettext("problem: %s"),
		    (errstr && *errstr) ? errstr : "Unknown");
		exit(1);
	}
	pkgcloseserver(server);
}
コード例 #20
0
ファイル: server.c プロジェクト: ltp/carbon-c-relay
/**
 * Waits for this server to finish sending pending items from its queue.
 */
void
server_shutdown(server *s)
{
	int i;
	size_t failures;
	size_t inqueue;
	int err;

	/* this function should only be called once for each server */
	assert(s->tid != 0);

	if (s->secondariescnt > 0) {
		/* if we have a working connection, or we still have stuff in
		 * our queue, wait for our secondaries, as they might need us,
		 * or we need them */
		do {
			failures = 0;
			inqueue = 0;
			for (i = 0; i < s->secondariescnt; i++) {
				if (s->secondaries[i]->failure)
					failures++;
				if (s->secondaries[i]->running)
					inqueue += queue_len(s->secondaries[i]->queue);
			}
			/* loop until we all failed, or nothing is in the queues */
		} while (failures != s->secondariescnt &&
				inqueue != 0 &&
				logout("any_of cluster pending %zu metrics "
					"(with %zu failed nodes)\n", inqueue, failures) >= -1 &&
				usleep((200 + (rand() % 100)) * 1000) <= 0);
		/* shut down entire cluster */
		for (i = 0; i < s->secondariescnt; i++)
			s->secondaries[i]->keep_running = 0;
		/* to pretend to be dead for above loop (just in case) */
		if (inqueue != 0)
			for (i = 0; i < s->secondariescnt; i++)
				s->secondaries[i]->failure = 1;
	}

	s->keep_running = 0;
	if ((err = pthread_join(s->tid, NULL)) != 0)
		logerr("%s:%u: failed to join server thread: %s\n",
				s->ip, s->port, strerror(err));
	s->tid = 0;

	if (s->ctype == CON_TCP) {
		size_t qlen = queue_len(s->queue);
		if (qlen > 0)
			logerr("dropping %zu metrics for %s:%u\n",
					qlen, s->ip, s->port);
	}
}
コード例 #21
0
HRESULT CDebugInfoWalker::OpenSessionAndExecute()
{
    HRESULT hr = E_UNEXPECTED;
    if(_pArgProcessor->isInputPdb())
    {
        hr = _OpenSessionPdb(_pArgProcessor->getInputFile());
    }
    else if(_pArgProcessor->isInputDllExe())
    {
        hr = _OpenSessionExeDll(_pArgProcessor->getInputFile(), _pArgProcessor->getSearchPath());
    }

    if(SUCCEEDED(hr))
    {
        bool isPublicOnly = _pArgProcessor->isOutputFuncPublic();

        // Has user asked for all functions' size?
        if(_pArgProcessor->isOutputFuncAll())
        {
            _EnumerateFunctions(isPublicOnly);
        }

        // Has user asked for sizes of specific functions?
        if(_pArgProcessor->isOutputFuncSpecific())
        {
            _EnumerateFunctions(_pArgProcessor->getSpecifiedFunctions(), isPublicOnly);
        }

        // Has user asked for functions whose name have the specified sub string?
        if(_pArgProcessor->isOutputFuncSubString())
        {
            _EnumerateFunctions(_pArgProcessor->getFuncSubString(), isPublicOnly);
        }

        // Has user asked for sizes of functions in specific module?
        if(_pArgProcessor->isOutputFuncInModule())
        {
            hr = E_NOTIMPL;
        }

        if(FAILED(hr))
        {
            logerr(L"Error enumerating functions", hr);
        }
    }
    else
    {
        logerr(L"Error opening session", hr);
    }

    return hr;
}
コード例 #22
0
ファイル: kmodule.c プロジェクト: csujedihy/drcom4mac
int module_stop_auth(void)
{
	int retval = 0;
	int ctl_fd = 0;
	struct ctl_info ctl_info;
	struct sockaddr_ctl sc;
	
	struct drcom_set_auth_opt drcom_auth_opt;
	
	ctl_fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
	if (ctl_fd < 0){
		logerr("socket(): %s, errno = %d\n", strerror(errno), errno);
		return -1;
	}
	
	bzero(&ctl_info, sizeof(struct ctl_info));
	strcpy(ctl_info.ctl_name, MYBUNDLEID);
	retval = ioctl(ctl_fd, CTLIOCGINFO, &ctl_info);
	if (retval < 0) {
		logerr("ioctl(CTLIOCGINFO): %s, errno = %d\n", strerror(errno), errno);
		return -1;
	}
	
	bzero(&sc, sizeof(struct sockaddr_ctl));
	sc.sc_len = sizeof(struct sockaddr_ctl);
	sc.sc_family = AF_SYSTEM;
	sc.ss_sysaddr = SYSPROTO_CONTROL;
	sc.sc_id = ctl_info.ctl_id;
	sc.sc_unit = 0;
	retval = connect(ctl_fd, (struct sockaddr *) &sc, sizeof(struct sockaddr_ctl));
	if (retval < 0)
	{
		logerr("connect(): %s, errno = %d\n", strerror(errno), errno);
		close(ctl_fd);
		return -1;
	}
		
	drcom_auth_opt.cmd = DRCOM_AUTH_MODE_OFF;
	
	retval = setsockopt(ctl_fd, SYSPROTO_CONTROL, DRCOM_CTL_AUTH, &drcom_auth_opt, sizeof(drcom_auth_opt));
	if (retval != 0) {
		logerr("setsockopt(DRCOM_CTL_AUTH): %s, errno = %d\n", strerror(errno), errno);
		close(ctl_fd);
		return -1;
	}
	
	close(ctl_fd);

	loginfo("daemon: Stopping authentication...\n");
	return -1;
}
コード例 #23
0
/*=========================================================================*\
      Write repository to file
\*=========================================================================*/
static int _dumpRepository( const char *name )
{
  int retcode  = 0;
  size_t flags = JSON_COMPACT;
  
  DBGMSG( "Dumping persistency file: \"%s\"", name ); 

/*------------------------------------------------------------------------*\
    No name given? 
\*------------------------------------------------------------------------*/
  if( !name ) {
    logerr( "Cannot write persistent repository: no name set " );
    return -1;
  }

/*------------------------------------------------------------------------*\
    No repository in mamory? 
\*------------------------------------------------------------------------*/
  if( !jRepository ) {
    logerr( "Try to dump empty repository object." );
    return -1;
  }

/*------------------------------------------------------------------------*\
    Use toolbox function 
\*------------------------------------------------------------------------*/
#ifdef ICK_DEBUG
  flags = JSON_INDENT(2) | JSON_PRESERVE_ORDER;
#endif

  if( json_dump_file(jRepository,name,flags) ) {
    logerr( "Error writing to persistent repository \"%s\": %s ", 
                     name, strerror(errno) );
    retcode = -1;  
  }

/*------------------------------------------------------------------------*\
    Try to change file mode in any case (might conatain secret info) 
\*------------------------------------------------------------------------*/
  if( chmod(name,S_IRUSR|S_IWUSR) ) {
    logerr( "Could not chmod persistent repository \"%s\": %s ", 
                     name, strerror(errno) );
    retcode = -1; 
  }
  
/*------------------------------------------------------------------------*\
    That's all 
\*------------------------------------------------------------------------*/
  return retcode;
}
コード例 #24
0
ファイル: arena.c プロジェクト: bhanug/harvey
/*
 * read the arena header and trailer blocks from disk
 */
static int
loadarena(Arena *arena)
{
	ArenaHead head;
	ZBlock *b;

	b = alloczblock(arena->blocksize, 0, arena->part->blocksize);
	if(b == nil)
		return -1;
	if(readpart(arena->part, arena->base + arena->size, b->data, arena->blocksize) < 0){
		freezblock(b);
		return -1;
	}
	if(unpackarena(arena, b->data) < 0){
		freezblock(b);
		return -1;
	}
	if(arena->version != ArenaVersion4 && arena->version != ArenaVersion5){
		seterr(EAdmin, "unknown arena version %d", arena->version);
		freezblock(b);
		return -1;
	}
	scorecp(arena->score, &b->data[arena->blocksize - VtScoreSize]);

	if(readpart(arena->part, arena->base - arena->blocksize, b->data, arena->blocksize) < 0){
		logerr(EAdmin, "can't read arena header: %r");
		freezblock(b);
		return 0;
	}
	if(unpackarenahead(&head, b->data) < 0)
		logerr(ECorrupt, "corrupted arena header: %r");
	else if(namecmp(arena->name, head.name)!=0
	     || arena->clumpmagic != head.clumpmagic
	     || arena->version != head.version
	     || arena->blocksize != head.blocksize
	     || arena->size + 2 * arena->blocksize != head.size){
		if(namecmp(arena->name, head.name)!=0)
			logerr(ECorrupt, "arena tail name %s head %s", 
				arena->name, head.name);
		else if(arena->clumpmagic != head.clumpmagic)
			logerr(ECorrupt, "arena %d tail clumpmagic 0x%lux head 0x%lux",
				debugarena, (uint32_t)arena->clumpmagic,
				(uint32_t)head.clumpmagic);
		else if(arena->version != head.version)
			logerr(ECorrupt, "arena tail version %d head version %d",
				arena->version, head.version);
		else if(arena->blocksize != head.blocksize)
			logerr(ECorrupt, "arena tail block size %d head %d",
				arena->blocksize, head.blocksize);
		else if(arena->size+2*arena->blocksize != head.size)
			logerr(ECorrupt, "arena tail size %lud head %lud",
				(uint32_t)arena->size+2*arena->blocksize,
			       head.size);
		else
			logerr(ECorrupt, "arena header inconsistent with arena data");
	}
	freezblock(b);

	return 0;
}
コード例 #25
0
ファイル: http.c プロジェクト: justdoit0823/proxyserver
struct HTTPConnection * new_connect(int fd)
{
  struct HTTPConnection * hc;
  if((hc = malloc(sizeof(*hc))) == NULL){
    logerr("malloc memory for http connection error", errno);
    return NULL;
  }
  hc->fd = fd;
  hc->count = 0;
  hc->events = 0;
  if((hc->buf = initHTTPBuffer(4096*64)) == NULL){
    logerr("malloc memory for http buffer error", errno);
  }
  return hc;
}
コード例 #26
0
ファイル: pdev.c プロジェクト: braincat/uwin
int
pdev_unlock(HANDLE hp, int code)
{
	int rc=0;
	if(hp)
	{
		if(!ReleaseMutex(hp))
			logerr(0, "ReleaseMutex");
		if(!CloseHandle(hp))
		{
			logerr(0, "CloseHandle");
		}
	}
	return(!rc);
}
コード例 #27
0
int NetworkWrapper::Init()
{
	struct sockaddr_in sin;

	gstEvtBase = event_base_new();
	if (!gstEvtBase) 
	{
		logerr("Could not initialize libevent!\n");
		return -1;
	}

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(m_iPort);

	m_stEvtlistener = evconnlistener_new_bind(gstEvtBase, accept_conn_cb, (void *)gstEvtBase,
		LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
		(struct sockaddr*)&sin,
		sizeof(sin));

	if (!m_stEvtlistener)
	{
		logerr("Could not create a listener!\n");
		return -1;
	}
	evconnlistener_set_error_cb(m_stEvtlistener, accept_error_cb);
	m_stSigEvt = evsignal_new(gstEvtBase, SIGINT, signal_cb, (void *)gstEvtBase);

	if (!m_stSigEvt || event_add(m_stSigEvt, NULL)<0) {
		logerr("Could not create/add a signal event!\n");
		return -1;
	}

	/*add tick*/
	struct timeval tv; 
	tv.tv_sec = 1;  
	tv.tv_usec = 0;

	m_stTimeEvt = evtimer_new(gstEvtBase,timer_cb, (void *)this);

	if (!m_stTimeEvt || event_add(m_stTimeEvt, &tv)<0) 
	{
		logerr("Could not create/add a time event!\n");
		return -1;
	}

	return 0;
}
コード例 #28
0
ファイル: run.c プロジェクト: bryanhinton/de0-nano-soc
int destroypktbuf(struct pktbuf *pkbuf) {

	int ret;

   	/* destroy condition variable */
    ret = pthread_cond_destroy(&pkbuf->pktremoved);

    /* pthread_cond_destroy failed */
    if(ret != 0) {

    	errno = ret;
    	logerr(MLOGSTDERR, "pthread_cond_destroy");

	    /* free packet buffer */
	    free(pkbuf);
	    return(EXIT_FAILURE);
	}

   	/* destroy condition variable */
    ret = pthread_cond_destroy(&pkbuf->pktavail);

    /* pthread_cond_destroy failed */
    if(ret != 0) {

    	errno = ret;
    	logerr(MLOGSTDERR, "pthread_cond_destroy");

	    /* free packet buffer */
	    free(pkbuf);
	    return(EXIT_FAILURE);
	}

	/* destroy mutex */
	ret = pthread_mutex_destroy(&pkbuf->lck);

	/* pthread_mutex_destroy failed */
	if(ret != 0) {

		errno = ret;
		logerr(MLOGSTDERR, "pthread_mutex_destroy");

		/* free packet buffer */
		free(pkbuf);
		return(EXIT_FAILURE);
	}

	return(EXIT_SUCCESS);
}
コード例 #29
0
ファイル: soccr.c プロジェクト: Snorch/criu
static int get_queue(int sk, int queue_id,
		__u32 *seq, __u32 len, char **bufp)
{
	int ret, aux;
	socklen_t auxl;
	char *buf;

	aux = queue_id;
	auxl = sizeof(aux);
	ret = setsockopt(sk, SOL_TCP, TCP_REPAIR_QUEUE, &aux, auxl);
	if (ret < 0)
		goto err_sopt;

	auxl = sizeof(*seq);
	ret = getsockopt(sk, SOL_TCP, TCP_QUEUE_SEQ, seq, &auxl);
	if (ret < 0)
		goto err_sopt;

	if (len) {
		/*
		 * Try to grab one byte more from the queue to
		 * make sure there are len bytes for real
		 */
		buf = malloc(len + 1);
		if (!buf) {
			loge("Unable to allocate memory\n");
			goto err_buf;
		}

		ret = recv(sk, buf, len + 1, MSG_PEEK | MSG_DONTWAIT);
		if (ret != len)
			goto err_recv;
	} else
		buf = NULL;

	*bufp = buf;
	return 0;

err_sopt:
	logerr("\tsockopt failed");
err_buf:
	return -1;

err_recv:
	logerr("\trecv failed (%d, want %d)", ret, len);
	free(buf);
	goto err_buf;
}
コード例 #30
0
ファイル: audio.c プロジェクト: braincat/uwin
static ssize_t dsp_write(int fd, Pfd_t* fdp, char *buff, size_t asize)
{
	DWORD size;
	HANDLE hp;
	WAVEHDR whdr;
	Pdev_t *pdev = dev_ptr(fdp->devno);

	if(!(hp=Phandle(fd)))
	{
		errno = EBADF;
		return(-1);
	}
	if(!(hp=audio_open(pdev,0)))
	{
		errno = EBADF;
		return(-1);
	}
	if(asize > SSIZE_MAX)
		asize = SSIZE_MAX;
	size = (DWORD)asize;

	/*  Preparing the Wave Header */
	ZeroMemory((void*)&whdr,sizeof(whdr));
	whdr.lpData=buff;
	whdr.dwBufferLength=size;
	whdr.dwFlags=0;
	if((*pwaveOutPrepareHeader)(hp,&whdr,sizeof(WAVEHDR)) != MMSYSERR_NOERROR)
	{
		logerr(LOG_DEV+5, "waveOutPrepareHeader");
		return(-1);
	}
	else
	{
		/* Writing to the audio port */
		whdr.dwLoops=PLAY_NUMBER_OF_TIMES;
		whdr.dwFlags|=(WHDR_BEGINLOOP|WHDR_ENDLOOP);
		if((*pwaveOutWrite)(hp,&whdr,sizeof(WAVEHDR)) != MMSYSERR_NOERROR)
		{
			logerr(LOG_DEV+5, "waveOutWrite");
			return(-1);
		}
		else
		{
			while((whdr.dwFlags != 15) && (size !=0));
			return(size);
		}
	}
}