Exemplo n.º 1
0
bool CApoxObj::open( const char *szFileName, unsigned long flags )
{
	const char *p;
	unsigned long busspeed = 125;
	m_emergencyInfo = 0;
	char szDrvParams[ MAX_PATH ];
	m_initFlag = flags;

	m_RxMsgState = USB_IDLE;

	// save parameter string and conbert to upper case
	strncpy( szDrvParams, szFileName, MAX_PATH );
	_strupr( szDrvParams );

	// Initiate statistics
	m_stat.cntReceiveData = 0;
	m_stat.cntReceiveFrames = 0;
	m_stat.cntTransmitData = 0;
	m_stat.cntTransmitFrames = 0;

	m_stat.cntBusOff = 0;
	m_stat.cntBusWarnings = 0;
	m_stat.cntOverruns = 0;

	// if open we have noting to do
	if ( m_bRun ) return true;
		
	// serial
	p = strtok( szDrvParams, ";" );
	if ( NULL != p ) {		
		strcpy( m_SerialNumber, p );	
	}

	// Bus-Speed
	p = strtok( NULL, ";" );
	if ( NULL != p ) {		
		if ( ( NULL != strstr( p, "0x" ) ) || ( NULL != strstr( p, "0X" ) )  ) {
			sscanf( p + 2, "%x", &busspeed );
		}
		else {
			busspeed = atol( p );
		}
	}

	// Handle busspeed
	uint8_t nSpeed = CAN_BAUD_1000;
	switch ( busspeed ) {

		case 125:
			nSpeed = CAN_BAUD_125;
			break;

		case 250:
			nSpeed = CAN_BAUD_250;
			break;

		case 500:
			nSpeed = CAN_BAUD_500;
			break;

		case 1000:
			nSpeed = CAN_BAUD_1000;
			break;

		default:
			nSpeed = CAN_BAUD_125;
			break;

	}


	FT_STATUS ftStatus;
	ftStatus = FT_OpenEx( (void *)m_SerialNumber, 
							FT_OPEN_BY_SERIAL_NUMBER, 
							&m_ftHandle );
	if ( !FT_SUCCESS( ftStatus ) ) return false;
		
	ftStatus = FT_ResetDevice( m_ftHandle );
	ftStatus = FT_Purge( m_ftHandle, FT_PURGE_RX | FT_PURGE_TX );
	ftStatus = FT_SetTimeouts(m_ftHandle, 378, 128);
	ftStatus = FT_SetUSBParameters ( m_ftHandle, 2048, 2048 );
	ftStatus = FT_SetLatencyTimer( m_ftHandle, 3 );
    
	
	// Run run run ..... 

	m_bRun = true;

#ifdef WIN32
	
	// Start write thread 
	DWORD threadId;
	if ( NULL == 
			( m_hTreadTransmit = CreateThread(	NULL,
										0,
										(LPTHREAD_START_ROUTINE) workThreadTransmit,
										this,
										0,
										&threadId ) ) ) { 
		// Failure
		close();
		return false;
	}

	// Start read thread 
	if ( NULL == 
			( m_hTreadReceive = CreateThread(	NULL,
										0,
										(LPTHREAD_START_ROUTINE) workThreadReceive,
										this,
										0,
										&threadId ) ) ) { 
		// Failure
		close();
		return  false;
	}
	
	// Release the mutex
	UNLOCK_MUTEX( m_apoxMutex );
	UNLOCK_MUTEX( m_receiveMutex );
	UNLOCK_MUTEX( m_transmitMutex );
	UNLOCK_MUTEX( m_responseMutex );

#else // LINUX


	pthread_attr_t thread_attr;
	pthread_attr_init( &thread_attr );
	
	
	// Create the log write thread.
	if ( pthread_create( 	&m_threadId,
								&thread_attr,
								workThreadTransmit,
								this ) ) {	
							
		syslog( LOG_CRIT, "canallogger: Unable to create apoxdrv write thread.");
		rv = false;
		fclose( m_flog );
	}


	// Create the log write thread.
	if ( pthread_create( 	&m_threadId,
								&thread_attr,
								workThreadReceive,
								this ) ) {	
							
		syslog( LOG_CRIT, "canallogger: Unable to create apoxdrv receive thread.");
		rv = false;
		fclose( m_flog );
	}
		
    // We are open
	m_bOpen = true;

	// Release the mutex
	pthread_mutex_unlock( &m_apoxMutex );

#endif	

	// Switch to main mode if in boot mode
	if ( RUNMODE_BOOT == getAdapterRunMode() ) {
		setAdapterRunMode( RUNMODE_MAIN );
	}

	// Set baudrate
	setBaudrate( nSpeed );

	// Set initial filter/mask	
	switch( m_initFlag & 0x03 ) {

		case 0:
		case 3:
			m_filtermask.rx_buff1_ext = 0;
			m_filtermask.rx_buff2_ext = 1;
			break;

		case 1:
			m_filtermask.rx_buff1_ext = 0;
			m_filtermask.rx_buff2_ext = 0;
			break;

		case 2:
			m_filtermask.rx_buff1_ext = 1;
			m_filtermask.rx_buff2_ext = 1;
			break;
	}

	m_filtermask.RXM0 = 0;
	m_filtermask.RXM1 = 0;
	m_filtermask.RXF0 = 0;	
	m_filtermask.RXF1 = 0;
	m_filtermask.RXF2 = 0;
	m_filtermask.RXF3 = 0;
	m_filtermask.RXF4 = 0;
	m_filtermask.RXF5 = 0;

	setAdapterFilterMask( &m_filtermask );

	// Set transmission mode
	short trmode = ( (short)( m_initFlag & 0x0c ) >> 2 );
	if ( 0 == trmode ) trmode = TRMODE_NORMAL;
	setTransmissionMode( trmode );

	return true;
}
Exemplo n.º 2
0
void masterconn_download_data(masterconn *eptr,const uint8_t *data,uint32_t length) {
	uint64_t offset;
	uint32_t leng;
	uint32_t crc;
	ssize_t ret;
	if (eptr->metafd<0) {
		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - file not opened");
		eptr->mode = KILL;
		return;
	}
	if (length<16) {
		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - wrong size (%"PRIu32"/16+data)",length);
		eptr->mode = KILL;
		return;
	}
	passert(data);
	offset = get64bit(&data);
	leng = get32bit(&data);
	crc = get32bit(&data);
	if (leng+16!=length) {
		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - wrong size (%"PRIu32"/16+%"PRIu32")",length,leng);
		eptr->mode = KILL;
		return;
	}
	if (offset!=eptr->dloffset) {
		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - unexpected file offset (%"PRIu64"/%"PRIu64")",offset,eptr->dloffset);
		eptr->mode = KILL;
		return;
	}
	if (offset+leng>eptr->filesize) {
		syslog(LOG_NOTICE,"MATOAN_DOWNLOAD_DATA - unexpected file size (%"PRIu64"/%"PRIu64")",offset+leng,eptr->filesize);
		eptr->mode = KILL;
		return;
	}
#ifdef HAVE_PWRITE
	ret = pwrite(eptr->metafd,data,leng,offset);
#else /* HAVE_PWRITE */
	lseek(eptr->metafd,offset,SEEK_SET);
	ret = write(eptr->metafd,data,leng);
#endif /* HAVE_PWRITE */
	if (ret!=(ssize_t)leng) {
		mfs_errlog_silent(LOG_NOTICE,"error writing metafile");
		if (eptr->downloadretrycnt>=5) {
			masterconn_download_end(eptr);
		} else {
			eptr->downloadretrycnt++;
			masterconn_download_next(eptr);
		}
		return;
	}
	if (crc!=mycrc32(0,data,leng)) {
		syslog(LOG_NOTICE,"metafile data crc error");
		if (eptr->downloadretrycnt>=5) {
			masterconn_download_end(eptr);
		} else {
			eptr->downloadretrycnt++;
			masterconn_download_next(eptr);
		}
		return;
	}
	if (fsync(eptr->metafd)<0) {
		mfs_errlog_silent(LOG_NOTICE,"error syncing metafile");
		if (eptr->downloadretrycnt>=5) {
			masterconn_download_end(eptr);
		} else {
			eptr->downloadretrycnt++;
			masterconn_download_next(eptr);
		}
		return;
	}
	eptr->dloffset+=leng;
	eptr->downloadretrycnt=0;
	masterconn_download_next(eptr);
}
Exemplo n.º 3
0
/* 
 * disk_activity() returns back the total number of read and writes done 
 * by the devices listed in the io watch table since the last call to 
 * disk_activity.  The number of reads and writes are determined by 
 * opening and reading each of the valid files listed in the io watch 
 * table.The number of reads and writes are stored in the io watch table so 
 * that the next call to this routine can compare the current number of read 
 * and writes to those stored in the io watch table. The difference for 
 * each device is summed in the activity variable.  The routine lazy 
 * evaluates the existance of the devices in the table. 
 *
 * For the storcenter, we are only concerned with internal drives. 
 *
 * The wt_path element must point at a diskstat file in the sysfs filesystem.  
 * File format can be found at: /usr/src/linux/Documentation/iostats.txt
 * For this routine:
 *	nr, nw - number read and writes
 *	nmr, nmw - number of merged reads and writes
 *	nsr, nsw - number of the sectors read and written
 *	tr, tw - time spent reading and writing
 *	nio - raw number of ios 
 * 	tio, wtio - time spent and weighted time spent doing io
 */
int
disk_activity()
{
	int	activity = 0;
	char	mesg[256];
	int	rc, nr, nmr, nsr, tr, nw, nmw, nsw, tw, nio, tio, wtio;
	FILE	*f;

	struct stat		st;
	struct watch_table	*w;

	for (w = iowt; w->wt_path; w++) {
		/*
		 * If status ids set to check, do the lazy existence 
		 * evaluation. If stat fails set to invalid. Don't 
		 * worry about perms here. 
		 */
		if ((w->wt_status == WT_CHECK) && 
		    (stat(w->wt_path, &st) < 0)) {
			sprintf(mesg, "%s not available", w->wt_path);
			syslog(LOG_INFO, mesg);
			w->wt_status = WT_INVALID;
		}

		/*
		 * Short circuit the loop if invalid.
		 */
		if (w->wt_status == WT_INVALID) 
			continue;

		/*
		 * If it can't be opened rdonly, set to invalid
		 */
		if ((f = fopen(w->wt_path, "r")) < 0) {
			sprintf(mesg, "Unable to open %s, no longer watching",
				w->wt_path);
			syslog(LOG_INFO, mesg);
			w->wt_status = WT_INVALID;
			continue;
		}

		rc = fscanf(f, "%d %d %d %d %d %d %d %d %d %d %d", 
		       &nr, &nmr, &nsr, &tr,
		       &nw, &nmw, &nsw, &tw,
		       &nio, &tio, &wtio);

		fclose(f);

		if (rc != 11) {
			sprintf(mesg, "Unable to read %s", w->wt_path);
			syslog(LOG_INFO, mesg);
			continue;
		}

		/*
		 * If we haven't seen any activity on this device before
		 * then just save the values and go on. This, although
		 * not strictly necessary, prevents the initial call to 
		 * disk_activity returning back the base set io activity.
		 * Remember it takes two calls to get a true difference.
		 */
		if ((w->wt_reads == 0) && (w->wt_writes == 0)) {
			w->wt_reads  = nr;
			w->wt_writes = nw;
			continue;
		}

		activity += (nr - w->wt_reads);
		activity += (nw - w->wt_writes);

		w->wt_reads  = nr;
		w->wt_writes = nw;

		/*
		   printf("%s: %d %d %d %d %d %d %d %d %d %d %d\n",
		       w->wt_path,
		       nr, nmr, nsr, tr,
		       nw, nmw, nsw, tw,
		       nio, tio, wtio);
		*/
	}

	return(activity);
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
	int error __unused, i, r, s;
	FILE *pidf;
	int ch = 0;

	while ((ch = getopt(argc, argv, "d")) != -1) {
		switch(ch) {
		case 'd':
			debugopt = 1;
			break;
		default:
			usage();
			/* NOT REACHED */
		}
	}
	argc -= optind;
	argv += optind;

	TAILQ_INIT(&pdev_array_list);
	TAILQ_INIT(&udev_monitor_list);

	r = ignore_signal(SIGPIPE);
	if (r != 0)
		err(1, "could not ignore_signal SIGPIPE");

	r = pthread_mutex_init(&(monitor_lock), NULL);
	if (r != 0)
		err(1, "could not allocate a pthread_mutex");

	if ((udevfd = open(UDEV_DEVICE_PATH, O_RDWR | O_NONBLOCK)) == -1)
		err(1, "%s", UDEV_DEVICE_PATH);
	unblock_descriptor(udevfd);

	s = init_local_server(LISTEN_SOCKET_FILE, SOCK_STREAM, 0);
	if (s < 0)
		err(1, "init_local_server");

	pidf = fopen("/var/run/udevd.pid", "w");
#if 0
	if (pidf == NULL)
		err(1, "pidfile");
#endif

	set_signal(SIGTERM, killed);
	set_signal(SIGHUP, hangup);

	if (debugopt == 0)
		if (daemon(0, 0) == -1)
			err(1, "daemon");

	if (pidf != NULL) {
		fprintf(pidf, "%ld\n", (long)getpid());
		fclose(pidf);
	}

	syslog(LOG_ERR, "udevd started");

	pdev_array_entry_insert(udev_getdevs(udevfd));

	memset(fds, 0 , sizeof(fds));
	fds[UDEV_DEVICE_FD_IDX].fd = udevfd;
	fds[UDEV_DEVICE_FD_IDX].events = POLLIN;
	fds[UDEV_SOCKET_FD_IDX].fd = s;
	fds[UDEV_SOCKET_FD_IDX].events = POLLIN | POLLPRI;

	for (;;) {
		r = poll(fds, NFDS, -1);
		if (r < 0) {
			if (hangup_ongoing == 0) {
				if (errno == EINTR) {
					usleep(5000);
					continue;
				} else {
					err(1, "polling...");
				}
			} else {
				usleep(20000); /* 20 ms */
				continue;
			}
		}

		for (i = 0; (i < NFDS) && (r > 0); i++) {
			if (fds[i].revents == 0)
				continue;

			--r;
			switch (i) {
			case UDEV_DEVICE_FD_IDX:
				udev_read_event(udevfd);
				break;
			case UDEV_SOCKET_FD_IDX:
				handle_new_connection(s);
				break;
			default:
				break;
			}
		}
	}

	syslog(LOG_ERR, "udevd is exiting normally");
	return 0;
}
Exemplo n.º 5
0
    int StateVersion::OnVersionInfo (const IPacket &packet)
    {
        uint8_t locale = packet.Read<uint8_t>();

        std::string ID = packet.Read();

        uint32_t version = packet.Read<uint32_t>();

        if (!packet.EndOfStream())
            return MSG_ERROR_SIZE;

        boost::shared_ptr<Server> server = m_service->getServer();

        if (!server)
            return MSG_ERROR;

        if (locale != server->Locale() || ID != server->ClientID())
        {
            syslog(LOG_INFO,"Trying to log with a different locale");
            return MSG_ERROR_ARG;
        }

        if (version == server->ClientVersion())
        {
            m_connection->setState(srv::STATE_LOGIN);

            OPacket pkt;

            srv_pkt::WriteVersionE(&pkt);
            m_connection->send(&pkt);

            pkt.Clear();

            srv_pkt::WriteVersionF(&pkt);   ///PERFORM UPDATE PACKET!!
            m_connection->send(&pkt);
        }
        else if (version < server->ClientVersion())
        {
            OPacket pkt(0x600D);
            pkt.Write<uint8_t>(1);
            pkt.Write<uint16_t>(1);
            pkt.Write<uint16_t>(0xA100);
            m_connection->send(&pkt);

            pkt.Clear();

            pkt.WriteOpcode(0x600D);
            pkt.Write<uint8_t>(0);
            pkt.Write<uint8_t>(2);
            pkt.Write<uint8_t>(5);
            m_connection->send(&pkt);
    //		///REDIRECT TO UPDATE SERVER!!!
    //		m_connection->Stop();
        }
        else
        {
            /// TOO NEW
            OPacket pkt(0x600D);
            pkt.Write<uint8_t>(1);
            pkt.Write<uint16_t>(1);
            pkt.Write<uint16_t>(0xA100);
            m_connection->send(&pkt);

            pkt.Clear();

            pkt.WriteOpcode(0x600D);
            pkt.Write<uint8_t>(0);
            pkt.Write<uint8_t>(2);
            pkt.Write<uint8_t>(1);
            m_connection->send(&pkt);
        }

        return MSG_SUCCESS;
    }
Exemplo n.º 6
0
int
getifstats(const char * ifname, struct ifdata * data)
{
	FILE *f;
	char line[512];
	char * p;
	int i;
	int r = -1;
#ifdef ENABLE_GETIFSTATS_CACHING
	static time_t cache_timestamp = 0;
	static struct ifdata cache_data;
	time_t current_time;
#endif
	data->baudrate = 4200000;
	data->opackets = 0;
	data->ipackets = 0;
	data->obytes = 0;
	data->ibytes = 0;
#ifdef ENABLE_GETIFSTATS_CACHING
	current_time = time(NULL);
	if(current_time == ((time_t)-1)) {
		syslog(LOG_ERR, "getifstats() : time() error : %m");
	} else {
		if(current_time < cache_timestamp + GETIFSTATS_CACHING_DURATION) {
			memcpy(data, &cache_data, sizeof(struct ifdata));
			return 0;
		}
	}
#endif
	f = fopen("/proc/net/dev", "r");
	if(!f) {
		syslog(LOG_ERR, "getifstats() : cannot open /proc/net/dev : %m");
		return -1;
	}
	/* discard the two header lines */
	fgets(line, sizeof(line), f);
	fgets(line, sizeof(line), f);
	while(fgets(line, sizeof(line), f)) {
		p = line;
		while(*p==' ') p++;
		i = 0;
		while(ifname[i] == *p) {
			p++; i++;
		}
		/* TODO : how to handle aliases ? */
		if(ifname[i] || *p != ':')
			continue;
		p++;
		while(*p==' ') p++;
		data->ibytes = strtoul(p, &p, 0);
		while(*p==' ') p++;
		data->ipackets = strtoul(p, &p, 0);
		/* skip 6 columns */
		for(i=6; i>0 && *p!='\0'; i--) {
			while(*p==' ') p++;
			while(*p!=' ' && *p) p++;
		}
		while(*p==' ') p++;
		data->obytes = strtoul(p, &p, 0);
		while(*p==' ') p++;
		data->opackets = strtoul(p, &p, 0);
		r = 0;
		break;
	}
	fclose(f);
#ifdef ENABLE_GETIFSTATS_CACHING
	if(r==0 && current_time!=((time_t)-1)) {
		cache_timestamp = current_time;
		memcpy(&cache_data, data, sizeof(struct ifdata));
	}
#endif
	return r;
}
Exemplo n.º 7
0
/*
 * legend:
 *  ! - ERROR:
 *  ^ - WARNING:
 *  ~ - normal
 *  # - normal, not foreground (logfile and syslog only)
 *  * - verbose
 *  $ - debug
 *  none - normal
 *
 *	Default  Foreground LogVerbose Debug  Syslog
 *  !	  yes	   mprintf     yes      yes   LOG_ERR
 *  ^	  yes	   mprintf     yes	yes   LOG_WARNING
 *  ~	  yes	   mprintf     yes	yes   LOG_INFO
 *  #	  yes	     no	       yes	yes   LOG_INFO
 *  *	  no	   mprintf     yes	yes   LOG_DEBUG
 *  $	  no	   mprintf     no	yes   LOG_DEBUG
 *  none  yes	   mprintf     yes	yes   LOG_INFO
 */
int logg(const char *str, ...)
{
    va_list args;
    char buffer[1025], *abuffer = NULL, *buff;
    time_t currtime;
    size_t len;
    mode_t old_umask;
#ifdef F_WRLCK
    struct flock fl;
#endif

    if ((*str == '$' && logg_verbose < 2) ||
        (*str == '*' && !logg_verbose))
        return 0;

    ARGLEN(args, str, len);
    if (len <= sizeof(buffer))
    {
        len = sizeof(buffer);
        buff = buffer;
    }
    else
    {
        abuffer = malloc(len);
        if (!abuffer)
        {
            len = sizeof(buffer);
            buff = buffer;
        }
        else
        {
            buff = abuffer;
        }
    }
    va_start(args, str);
    vsnprintf(buff, len, str, args);
    va_end(args);
    buff[len - 1] = 0;

#ifdef CL_THREAD_SAFE
    pthread_mutex_lock(&logg_mutex);
#endif

    logg_open();

    if (!logg_fp && logg_file)
    {
        old_umask = umask(0037);
        if ((logg_fp = fopen(logg_file, "at")) == NULL)
        {
            umask(old_umask);
#ifdef CL_THREAD_SAFE
            pthread_mutex_unlock(&logg_mutex);
#endif
            printf("ERROR: Can't open %s in append mode (check permissions!).\n", logg_file);
            if (len > sizeof(buffer))
                free(abuffer);
            return -1;
        }
        else
            umask(old_umask);

#ifdef F_WRLCK
        if (logg_lock)
        {
            memset(&fl, 0, sizeof(fl));
            fl.l_type = F_WRLCK;
            if (fcntl(fileno(logg_fp), F_SETLK, &fl) == -1)
            {
#ifdef EOPNOTSUPP
                if (errno == EOPNOTSUPP)
                    printf("WARNING: File locking not supported (NFS?)\n");
                else
#endif
                {
#ifdef CL_THREAD_SAFE
                    pthread_mutex_unlock(&logg_mutex);
#endif
                    printf("ERROR: %s is locked by another process\n", logg_file);
                    if (len > sizeof(buffer))
                        free(abuffer);
                    return -1;
                }
            }
        }
#endif
    }

    if (logg_fp)
    {
        char flush = !logg_noflush;
        /* Need to avoid logging time for verbose messages when logverbose
               is not set or we get a bunch of timestamps in the log without
               newlines... */
        if (logg_time && ((*buff != '*') || logg_verbose))
        {
            char timestr[32];
            time(&currtime);
            cli_ctime(&currtime, timestr, sizeof(timestr));
            /* cut trailing \n */
            timestr[strlen(timestr) - 1] = '\0';
            fprintf(logg_fp, "%s -> ", timestr);
        }

        if (*buff == '!')
        {
            fprintf(logg_fp, "ERROR: %s", buff + 1);
            flush = 1;
        }
        else if (*buff == '^')
        {
            if (!logg_nowarn)
                fprintf(logg_fp, "WARNING: %s", buff + 1);
            flush = 1;
        }
        else if (*buff == '*' || *buff == '$')
        {
            fprintf(logg_fp, "%s", buff + 1);
        }
        else if (*buff == '#' || *buff == '~')
        {
            fprintf(logg_fp, "%s", buff + 1);
        }
        else
            fprintf(logg_fp, "%s", buff);

        if (flush)
            fflush(logg_fp);
    }

    if (logg_foreground)
    {
        if (buff[0] != '#')
        {
            if (logg_time)
            {
                char timestr[32];
                time(&currtime);
                cli_ctime(&currtime, timestr, sizeof(timestr));
                /* cut trailing \n */
                timestr[strlen(timestr) - 1] = '\0';
                mprintf("%s -> %s", timestr, buff);
            }
            else
            {
                mprintf("%s", buff);
            }
        }
    }

#if defined(USE_SYSLOG) && !defined(C_AIX)
    if (logg_syslog)
    {
        cli_chomp(buff);
        if (buff[0] == '!')
        {
            syslog(LOG_ERR, "%s", buff + 1);
        }
        else if (buff[0] == '^')
        {
            if (!logg_nowarn)
                syslog(LOG_WARNING, "%s", buff + 1);
        }
        else if (buff[0] == '*' || buff[0] == '$')
        {
            syslog(LOG_DEBUG, "%s", buff + 1);
        }
        else if (buff[0] == '#' || buff[0] == '~')
        {
            syslog(LOG_INFO, "%s", buff + 1);
        }
        else
            syslog(LOG_INFO, "%s", buff);
    }
#endif

#ifdef CL_THREAD_SAFE
    pthread_mutex_unlock(&logg_mutex);
#endif

    if (len > sizeof(buffer))
        free(abuffer);
    return 0;
}
Exemplo n.º 8
0
/**********************************************************************
*%FUNCTION: relayGotSessionPacket
*%ARGUMENTS:
* iface -- interface on which packet is waiting
*%RETURNS:
* Nothing
*%DESCRIPTION:
* Receives and processes a session packet.
***********************************************************************/
void
relayGotSessionPacket(PPPoEInterface const *iface)
{
    PPPoEPacket packet;
    int size;
    SessionHash *sh;
    PPPoESession *ses;

    if (receivePacket(iface->sessionSock, &packet, &size) < 0) {
	return;
    }

    /* Ignore unknown code/version */
    if (packet.ver != 1 || packet.type != 1) {
	return;
    }

    /* Must be a session packet */
    if (packet.code != CODE_SESS) {
	syslog(LOG_ERR, "Session packet with code %d", (int) packet.code);
	return;
    }

    /* Ignore session packets whose destination address isn't ours */
    if (memcmp(packet.ethHdr.h_dest, iface->mac, ETH_ALEN)) {
	return;
    }

    /* Validate length */
    if (ntohs(packet.length) + HDR_SIZE > size) {
	syslog(LOG_ERR, "Bogus PPPoE length field (%u)",
	       (unsigned int) ntohs(packet.length));
	return;
    }

    /* Drop Ethernet frame padding */
    if (size > ntohs(packet.length) + HDR_SIZE) {
	size = ntohs(packet.length) + HDR_SIZE;
    }

    /* We're in business!  Find the hash */
    sh = findSession(packet.ethHdr.h_source, packet.session);
    if (!sh) {
	/* Don't log this.  Someone could be running the client and the
	   relay on the same box. */
	return;
    }

    /* Relay it */
    ses = sh->ses;
    ses->epoch = Epoch;
    sh = sh->peer;
    packet.session = sh->sesNum;
    memcpy(packet.ethHdr.h_source, sh->interface->mac, ETH_ALEN);
    memcpy(packet.ethHdr.h_dest, sh->peerMac, ETH_ALEN);
#if 0
    fprintf(stderr, "Relaying %02x:%02x:%02x:%02x:%02x:%02x(%s:%d) to %02x:%02x:%02x:%02x:%02x:%02x(%s:%d)\n",
	    sh->peer->peerMac[0], sh->peer->peerMac[1], sh->peer->peerMac[2],
	    sh->peer->peerMac[3], sh->peer->peerMac[4], sh->peer->peerMac[5],
	    sh->peer->interface->name, ntohs(sh->peer->sesNum),
	    sh->peerMac[0], sh->peerMac[1], sh->peerMac[2],
	    sh->peerMac[3], sh->peerMac[4], sh->peerMac[5],
	    sh->interface->name, ntohs(sh->sesNum));
#endif
    sendPacket(NULL, sh->interface->sessionSock, &packet, size);
}
Exemplo n.º 9
0
/**********************************************************************
*%FUNCTION: relayHandlePADI
*%ARGUMENTS:
* iface -- interface on which packet was received
* packet -- the PADI packet
*%RETURNS:
* Nothing
*%DESCRIPTION:
* Receives and processes a PADI packet.
***********************************************************************/
void
relayHandlePADI(PPPoEInterface const *iface,
		PPPoEPacket *packet,
		int size)
{
    PPPoETag tag;
    unsigned char *loc;
    int i, r;

    int ifIndex;

    /* Can a client legally be behind this interface? */
    if (!iface->clientOK) {
	syslog(LOG_ERR,
	       "PADI packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not permitted",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* Source address must be unicast */
    if (NOT_UNICAST(packet->ethHdr.h_source)) {
	syslog(LOG_ERR,
	       "PADI packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not from a unicast address",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* Destination address must be broadcast */
    if (NOT_BROADCAST(packet->ethHdr.h_dest)) {
	syslog(LOG_ERR,
	       "PADI packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not to a broadcast address",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* Get array index of interface */
    ifIndex = iface - Interfaces;

    loc = findTag(packet, TAG_RELAY_SESSION_ID, &tag);
    if (!loc) {
	tag.type = htons(TAG_RELAY_SESSION_ID);
	tag.length = htons(MY_RELAY_TAG_LEN);
	memcpy(tag.payload, &ifIndex, sizeof(ifIndex));
	memcpy(tag.payload+sizeof(ifIndex), packet->ethHdr.h_source, ETH_ALEN);
	/* Add a relay tag if there's room */
	r = addTag(packet, &tag);
	if (r < 0) return;
	size += r;
    } else {
	/* We do not re-use relay-id tags.  Drop the frame.  The RFC says the
	   relay agent SHOULD return a Generic-Error tag, but this does not
	   make sense for PADI packets. */
	return;
    }

    /* Broadcast the PADI on all AC-capable interfaces except the interface
       on which it came */
    for (i=0; i < NumInterfaces; i++) {
	if (iface == &Interfaces[i]) continue;
	if (!Interfaces[i].acOK) continue;
	memcpy(packet->ethHdr.h_source, Interfaces[i].mac, ETH_ALEN);
	sendPacket(NULL, Interfaces[i].discoverySock, packet, size);
    }

}
Exemplo n.º 10
0
/**********************************************************************
*%FUNCTION: relayHandlePADS
*%ARGUMENTS:
* iface -- interface on which packet was received
* packet -- the PADS packet
*%RETURNS:
* Nothing
*%DESCRIPTION:
* Receives and processes a PADS packet.
***********************************************************************/
void
relayHandlePADS(PPPoEInterface const *iface,
		PPPoEPacket *packet,
		int size)
{
    PPPoETag tag;
    unsigned char *loc;
    int ifIndex;
    int acIndex;
    PPPoESession *ses = NULL;
    SessionHash *sh;

    /* Can a server legally be behind this interface? */
    if (!iface->acOK) {
	syslog(LOG_ERR,
	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not permitted",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    acIndex = iface - Interfaces;

    /* Source address must be unicast */
    if (NOT_UNICAST(packet->ethHdr.h_source)) {
	syslog(LOG_ERR,
	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not from a unicast address",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* Destination address must be interface's MAC address */
    if (memcmp(packet->ethHdr.h_dest, iface->mac, ETH_ALEN)) {
	return;
    }

    /* Find relay tag */
    loc = findTag(packet, TAG_RELAY_SESSION_ID, &tag);
    if (!loc) {
	syslog(LOG_ERR,
	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have Relay-Session-Id tag",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* If it's the wrong length, ignore it */
    if (ntohs(tag.length) != MY_RELAY_TAG_LEN) {
	syslog(LOG_ERR,
	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have correct length Relay-Session-Id tag",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* Extract interface index */
    memcpy(&ifIndex, tag.payload, sizeof(ifIndex));

    if (ifIndex < 0 || ifIndex >= NumInterfaces ||
	!Interfaces[ifIndex].clientOK ||
	iface == &Interfaces[ifIndex]) {
	syslog(LOG_ERR,
	       "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s has invalid interface in Relay-Session-Id tag",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* If session ID is zero, it's the AC respoding with an error.
       Just relay it; do not create a session */
    if (packet->session != htons(0)) {
	/* Check for existing session */
	sh = findSession(packet->ethHdr.h_source, packet->session);
	if (sh) ses = sh->ses;

	/* If already an existing session, assume it's a duplicate PADS.  Send
	   the frame, but do not create a new session.  Is this the right
	   thing to do?  Arguably, should send an error to the client and
	   a PADT to the server, because this could happen due to a
	   server crash and reboot. */

	if (!ses) {
	    /* Create a new session */
	    ses = createSession(iface, &Interfaces[ifIndex],
				packet->ethHdr.h_source,
				loc + TAG_HDR_SIZE + sizeof(ifIndex), packet->session);
	    if (!ses) {
		/* Can't allocate session -- send error PADS to client and
		   PADT to server */
		PPPoETag hostUniq, *hu;
		if (findTag(packet, TAG_HOST_UNIQ, &hostUniq)) {
		    hu = &hostUniq;
		} else {
		    hu = NULL;
		}
		relaySendError(CODE_PADS, htons(0), &Interfaces[ifIndex],
			       loc + TAG_HDR_SIZE + sizeof(ifIndex),
			       hu, "RP-PPPoE: Relay: Unable to allocate session");
		relaySendError(CODE_PADT, packet->session, iface,
			       packet->ethHdr.h_source, NULL,
			       "RP-PPPoE: Relay: Unable to allocate session");
		return;
	    }
	}
	/* Replace session number */
	packet->session = ses->sesNum;
    }

    /* Remove relay-ID tag */
    removeBytes(packet, loc, MY_RELAY_TAG_LEN + TAG_HDR_SIZE);
    size -= (MY_RELAY_TAG_LEN + TAG_HDR_SIZE);

    /* Set destination address to MAC address in relay ID */
    memcpy(packet->ethHdr.h_dest, tag.payload + sizeof(ifIndex), ETH_ALEN);

    /* Set source address to MAC address of interface */
    memcpy(packet->ethHdr.h_source, Interfaces[ifIndex].mac, ETH_ALEN);

    /* Send the PADS to the proper client */
    sendPacket(NULL, Interfaces[ifIndex].discoverySock, packet, size);
}
Exemplo n.º 11
0
/**********************************************************************
*%FUNCTION: createSession
*%ARGUMENTS:
* ac -- Ethernet interface on access-concentrator side
* cli -- Ethernet interface on client side
* acMac -- Access concentrator's MAC address
* cliMac -- Client's MAC address
* acSess -- Access concentrator's session ID.
*%RETURNS:
* PPPoESession structure; NULL if one could not be allocated
*%DESCRIPTION:
* Initializes relay hash table and session tables.
***********************************************************************/
PPPoESession *
createSession(PPPoEInterface const *ac,
	      PPPoEInterface const *cli,
	      unsigned char const *acMac,
	      unsigned char const *cliMac,
	      UINT16_t acSes)
{
    PPPoESession *sess;
    SessionHash *acHash, *cliHash;

    if (NumSessions >= MaxSessions) {
	printErr("Maximum number of sessions reached -- cannot create new session");
	return NULL;
    }

    /* Grab a free session */
    sess = FreeSessions;
    FreeSessions = sess->next;
    NumSessions++;

    /* Link it to the active list */
    sess->next = ActiveSessions;
    if (sess->next) {
	sess->next->prev = sess;
    }
    ActiveSessions = sess;
    sess->prev = NULL;

    sess->epoch = Epoch;

    /* Get two hash entries */
    acHash = FreeHashes;
    cliHash = acHash->next;
    FreeHashes = cliHash->next;

    acHash->peer = cliHash;
    cliHash->peer = acHash;

    sess->acHash = acHash;
    sess->clientHash = cliHash;

    acHash->interface = ac;
    cliHash->interface = cli;

    memcpy(acHash->peerMac, acMac, ETH_ALEN);
    acHash->sesNum = acSes;
    acHash->ses = sess;

    memcpy(cliHash->peerMac, cliMac, ETH_ALEN);
    cliHash->sesNum = sess->sesNum;
    cliHash->ses = sess;

    addHash(acHash);
    addHash(cliHash);

    /* Log */
    syslog(LOG_INFO,
	   "Opened session: server=%02x:%02x:%02x:%02x:%02x:%02x(%s:%d), client=%02x:%02x:%02x:%02x:%02x:%02x(%s:%d)",
	   acHash->peerMac[0], acHash->peerMac[1],
	   acHash->peerMac[2], acHash->peerMac[3],
	   acHash->peerMac[4], acHash->peerMac[5],
	   acHash->interface->name,
	   ntohs(acHash->sesNum),
	   cliHash->peerMac[0], cliHash->peerMac[1],
	   cliHash->peerMac[2], cliHash->peerMac[3],
	   cliHash->peerMac[4], cliHash->peerMac[5],
	   cliHash->interface->name,
	   ntohs(cliHash->sesNum));

    return sess;
}
Exemplo n.º 12
0
/**********************************************************************
*%FUNCTION: relayHandlePADR
*%ARGUMENTS:
* iface -- interface on which packet was received
* packet -- the PADR packet
*%RETURNS:
* Nothing
*%DESCRIPTION:
* Receives and processes a PADR packet.
***********************************************************************/
void
relayHandlePADR(PPPoEInterface const *iface,
		PPPoEPacket *packet,
		int size)
{
    PPPoETag tag;
    unsigned char *loc;
    int ifIndex;
    int cliIndex;

    /* Can a client legally be behind this interface? */
    if (!iface->clientOK) {
	syslog(LOG_ERR,
	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not permitted",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    cliIndex = iface - Interfaces;

    /* Source address must be unicast */
    if (NOT_UNICAST(packet->ethHdr.h_source)) {
	syslog(LOG_ERR,
	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not from a unicast address",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* Destination address must be interface's MAC address */
    if (memcmp(packet->ethHdr.h_dest, iface->mac, ETH_ALEN)) {
	return;
    }

    /* Find relay tag */
    loc = findTag(packet, TAG_RELAY_SESSION_ID, &tag);
    if (!loc) {
	syslog(LOG_ERR,
	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have Relay-Session-Id tag",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* If it's the wrong length, ignore it */
    if (ntohs(tag.length) != MY_RELAY_TAG_LEN) {
	syslog(LOG_ERR,
	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have correct length Relay-Session-Id tag",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* Extract interface index */
    memcpy(&ifIndex, tag.payload, sizeof(ifIndex));

    if (ifIndex < 0 || ifIndex >= NumInterfaces ||
	!Interfaces[ifIndex].acOK ||
	iface == &Interfaces[ifIndex]) {
	syslog(LOG_ERR,
	       "PADR packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s has invalid interface in Relay-Session-Id tag",
	       packet->ethHdr.h_source[0],
	       packet->ethHdr.h_source[1],
	       packet->ethHdr.h_source[2],
	       packet->ethHdr.h_source[3],
	       packet->ethHdr.h_source[4],
	       packet->ethHdr.h_source[5],
	       iface->name);
	return;
    }

    /* Replace Relay-ID tag with opposite-direction tag */
    memcpy(loc+TAG_HDR_SIZE, &cliIndex, sizeof(cliIndex));
    memcpy(loc+TAG_HDR_SIZE+sizeof(ifIndex), packet->ethHdr.h_source, ETH_ALEN);

    /* Set destination address to MAC address in relay ID */
    memcpy(packet->ethHdr.h_dest, tag.payload + sizeof(ifIndex), ETH_ALEN);

    /* Set source address to MAC address of interface */
    memcpy(packet->ethHdr.h_source, Interfaces[ifIndex].mac, ETH_ALEN);

    /* Send the PADR to the proper access concentrator */
    sendPacket(NULL, Interfaces[ifIndex].discoverySock, packet, size);
}
Exemplo n.º 13
0
void NS_CLASS log(int type, int errnum, const char *function, char *format, ...)
{
    va_list ap;
    static char buffer[256] = "";
    static char log_buf[1024];
    char *msg;
    struct timeval now;
    struct tm *time;
    int len = 0;

/* NS_PORT: Include IP address in log */
#ifdef NS_PORT
    if (DEV_NR(NS_DEV_NR).enabled == 1) {
	len += sprintf(log_buf + len, "%s: ",
		       ip_to_str(DEV_NR(NS_DEV_NR).ipaddr));
    }
#endif				/* NS_PORT */

    va_start(ap, format);

    if (type == LOG_WARNING)
	msg = &buffer[9];
    else
	msg = buffer;

    vsprintf(msg, format, ap);
    va_end(ap);

    if (!debug && !log_to_file)
	goto syslog;

    gettimeofday(&now, NULL);

#ifdef NS_PORT
    time = gmtime(&now.tv_sec);
#else
    time = localtime(&now.tv_sec);
#endif

    /*   if (type <= LOG_NOTICE) */
/* 	len += sprintf(log_buf + len, "%s: ", progname); */

    len += sprintf(log_buf + len, "%02d:%02d:%02d.%03ld %s: %s", time->tm_hour,
		   time->tm_min, time->tm_sec, now.tv_usec / 1000, function,
		   msg);

    if (errnum == 0)
	len += sprintf(log_buf + len, "\n");
    else
	len += sprintf(log_buf + len, ": %s\n", strerror(errnum));

    if (len > 1024) {
	fprintf(stderr, "log(): buffer to small! len = %d\n", len);
	goto syslog;
    }

    /* OK, we are clear to write the buffer to the aodv log file... */
    if (log_to_file)
	write_to_log_file(log_buf, len);

    /* If we have the debug option set, also write to stdout */
    if (debug)
	printf(log_buf);

    /* Syslog all messages that are of severity LOG_NOTICE or worse */
  syslog:
    if (type <= LOG_NOTICE) {
	if (errnum != 0) {
	    errno = errnum;
	    syslog(type, "%s: %s: %m", function, msg);
	} else
	    syslog(type, "%s: %s", function, msg);
    }
    /* Exit on error */
    if (type <= LOG_ERR)
	exit(-1);
}
Exemplo n.º 14
0
void DirWatcher::Run(){
	// Load torrents already in place
	this->LoadInitial();
	
	if(this->inotifyfd>=0){
		char buf[1024];
		// Add watches on all current directories
		this->AddWatches();
		
		// Monitor /home for new and removed users
		this->AddHomeWatch();

		// TODO: implement timeout and a way to terminate thread
		ssize_t l;
		struct inotify_event *item;	
		int itemsize;
		while(doRun){
			if((l=read(this->inotifyfd,buf,sizeof(buf)))<0){
				if(errno != EINTR){
					syslog(LOG_NOTICE,"Read event failed: %m");
				}
			}else{
				item=(inotify_event *)buf;
		
				while(l>=(ssize_t)(sizeof(struct inotify_event)+item->len)){
					itemsize=(sizeof(struct inotify_event)+item->len);
					if(item->len ){
						if(this->iwatches[item->wd]=="/home/"){
							syslog(LOG_DEBUG,"dirwatcher: user %s trigged",item->name);
							// This is an action on the home watch
							string pth="/home/"+string(item->name)+"/"+
									FtdConfig::Instance().GetStringOrDefault("torrent","torrentdir","torrents")+
									"/";
							if(item->mask & IN_CREATE){
								// New user
								// Hack to let system add skeleton dir
								sleep(1);
								this->AddWatch(pth);
							}else if(item->mask & IN_DELETE){
								// User deleted, do nothing. Watch removed when torrent dir deleted
								//this->DelWatch(pth);
							}else{
								syslog(LOG_NOTICE, "Unknown event on home dir: %s",pth.c_str());
							}
						}else{
							// TODO: add watch on delete as well.
							// This is an ordinary action on a torrent dir
							if(item->mask && (IN_CREATE|IN_MOVED_TO)){
								// We have a new file, only add if its not our "own"
								if(strncmp(item->name,".ftdtr",6)==0){
									syslog(LOG_DEBUG,"Not readding download");
								}else{
									string dlpath=this->iwatches[item->wd]+string(item->name);
									//AFP hack
									sleep(1);
									this->AddDownload(dlpath);
								}
							}else{
								syslog(LOG_NOTICE,"dirwatcher: Unknown event on %s",item->name);
							}
						}
					}
					l-=itemsize;
					item=(struct inotify_event*)(((unsigned long)item)+itemsize);
				}
			}			
		}
	}			
	syslog(LOG_NOTICE,"Dirwatcher terminating");
}
Exemplo n.º 15
0
/* RESTAuth request dispatcher */
static int pam_restauth_check(
        const char *base_url,
        const char *service_user,
        const char *service_password,
        const char *group,
        int validate_certificate,
        const char *user,
        const char *password) {

    /* allocate structures */
    CURL *session = curl_easy_init();
    char *escaped_user = url_escape(user);
    char *escaped_password = url_escape(password);
    char *url = malloc(strlen(base_url)+strlen("/users/")+strlen(user)*3+1+1);
    char *post_data = malloc(strlen("password="******"%s%susers/%s/", base_url,
            *(base_url+strlen(base_url)-1) == '/' ? "":"/",
            escaped_user);

    /* create POST data: password=<password> */
    sprintf(post_data, "password=%s", escaped_password);

    /* set up CURL request */
    pam_restauth_curl_session_init(session, url,
                                   service_user, service_password,
                                   validate_certificate, post_data);

    /* perform request */
    long curl_http_code = 0;
    int curl_status = curl_easy_perform(session);
    curl_status += curl_easy_getinfo(session, CURLINFO_RESPONSE_CODE,
                                     &curl_http_code);

    if (curl_status == CURLE_OK && curl_http_code >= 200 && curl_http_code < 300) {
        /* success. perform group check if a group is specified */
        if (group) {
            /* create group URL */
            char *escaped_group = url_escape(group);
            char *group_url = malloc(strlen(base_url)+strlen("/groups/")+strlen(escaped_group)+strlen("/users/")+strlen(escaped_user)+1);
            sprintf(group_url, "%s%sgroups/%s/users/%s/", base_url,
                    *(base_url+strlen(base_url)-1) == '/' ? "":"/",
                    escaped_group, escaped_user);

            /* set up CURL request again and perform call */
            pam_restauth_curl_session_init(session, group_url,
                                           service_user, service_password,
                                           validate_certificate, NULL);

            curl_status = curl_easy_perform(session);
            curl_status += curl_easy_getinfo(session, CURLINFO_RESPONSE_CODE,
                                             &curl_http_code);

            if (curl_status == CURLE_OK && curl_http_code >= 200 && curl_http_code < 300) {
                ret = 0; /* success */
            }
            else {
                ret = -1; /* failure */
                syslog(LOG_AUTHPRIV|LOG_NOTICE, __FILE__": user `%s' failed RESTAuth check for group `%s'", escaped_user, escaped_group);
            }

            if (escaped_group) free(escaped_group);
            if (group_url) free(group_url);
        }
        else {
            ret = 0; /* success */
        }
    }
    else {
        ret = -1; /* failure */
    }

cleanup:
    if (session) curl_easy_cleanup(session);
    if (escaped_user) free(escaped_user);
    if (escaped_password) free(escaped_password);
    if (url) free(url);
    if (post_data) free(post_data);

    return ret;
}
Exemplo n.º 16
0
void getPlatformAndDeviceInfo(cl_platform_id* platformIds, cl_uint maxPlatforms, cl_uint myPlatform, cl_device_type devType){

  /* See how many platforms are available.*/
  cl_uint numPlatforms;
  cl_int status = clGetPlatformIDs(maxPlatforms, platformIds, &numPlatforms);
  statusCheck(status, "clGetPlatformIds");
  printf("%d platform(s) detected.\n", numPlatforms);

  /* Get the names of the platforms and display to user. */
  char platNames[maxPlatforms][100];
  uint plat = 0;
  for(plat = 0; plat < numPlatforms; plat++){
    size_t nameBufferLength;
    status = clGetPlatformInfo(platformIds[plat], CL_PLATFORM_NAME, sizeof(platNames[plat]), platNames[plat], &nameBufferLength);
    statusCheck(status, "clGetPlatformInfo");
    printf("\tPlatform %d: %s\n", plat, platNames[plat]);
  }
  
  /* see how many devices our chosen platform platform ...*/
  const cl_uint maxDevices = 4;
  cl_device_id deviceIds[maxDevices];
  cl_uint numDevices;
  clGetDeviceIDs(platformIds[myPlatform], devType, maxDevices, deviceIds, &numDevices);
  statusCheck(status, "clGetDeviceIDs");
  
  /* Give up if we can't find any devices on chosen platform */
  if (numDevices==0) {
    syslog(LOG_ERR, "Error! 0 devices found on platform %s!\n", platNames[myPlatform]);
    syslog(LOG_ERR, "This normally means I can't talk to the X server for some reason.\n");
    syslog(LOG_ERR, "Exiting program.\n");
    fprintf(stderr, "Error! 0 devices found on platform %s!\n", platNames[myPlatform]);
    fprintf(stderr, "This normally means I can't talk to the X server for some reason.\n");
    fprintf(stderr, "Exiting program.\n");
    exit(1);
  }

  /* Prints useful information about the GPU architecture to the screen.*/
  size_t maxWorkGroupSize;
  char devNames[maxDevices][100];
  uint dev=0;
  for(dev = 0; dev < numDevices; dev++){
    size_t length;
    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_NAME, sizeof(devNames[dev]), devNames, &length);
    statusCheck(status, "clGetDeviceInfo");
     
    cl_bool available;
    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_AVAILABLE, sizeof(available), &available, &length);
    statusCheck(status, "clGetDeviceInfo");
     
    cl_uint maxComputeUnits;
    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(maxComputeUnits), &maxComputeUnits, &length);
    statusCheck(status, "clGetDeviceInfo");
     
    cl_uint maxWorkItemDimension;
    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof(maxWorkItemDimension), &maxWorkItemDimension, &length);
    statusCheck(status, "clGetDeviceInfo");

    size_t maxWorkItemSizes[maxWorkItemDimension];
    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(maxWorkItemSizes), &maxWorkItemSizes, &length);
    statusCheck(status, "clGetDeviceInfo");

    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(maxWorkGroupSize), &maxWorkGroupSize, &length);
    statusCheck(status, "clGetDeviceInfo");

    cl_ulong maxMemAllocSize = 0;
    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(maxMemAllocSize), &maxMemAllocSize, &length);
    statusCheck(status, "clGetDeviceInfo");
      
    cl_ulong deviceLocalMemSize = 0;
    status = clGetDeviceInfo(deviceIds[dev], CL_DEVICE_LOCAL_MEM_SIZE, sizeof(deviceLocalMemSize), &deviceLocalMemSize, &length);
    statusCheck(status, "clGetDeviceInfo");

    printf("\t\tDevice: %d\n", dev);
    printf("\t\tName: %s\n", devNames[dev]);
    printf("\t\tAvailable: ");
    if(available){printf("Yes");}
    else{printf("No");}
    printf("\n\t\tNumber of Compute Units: %d\n", maxComputeUnits);
    printf("\t\tNumber of Work Item dimensions: %d\n", maxWorkItemDimension);
    printf("\t\tMax Work Items for each dimension: ");
    uint dim=0; for(dim = 0; dim < maxWorkItemDimension; dim++){ printf("%ld ", maxWorkItemSizes[dim]);}
    printf("\n\t\tMax Work Group size: %ld\n", maxWorkGroupSize);
    printf("\t\tGlobal memory size (bytes): %ld\n", maxMemAllocSize);
    printf("\t\tLocal memory size (bytes): %ld\n", deviceLocalMemSize);
  }
}
Exemplo n.º 17
0
int log_error_write(server *srv, const char *filename, unsigned int line, const char *fmt, ...) {
	va_list ap;

	switch(srv->errorlog_mode) {
	case ERRORLOG_PIPE:
	case ERRORLOG_FILE:
	case ERRORLOG_STDERR:
		/* cache the generated timestamp */
		if (srv->cur_ts != srv->last_generated_debug_ts) {
			buffer_prepare_copy(srv->ts_debug_str, 255);
			strftime(srv->ts_debug_str->ptr, srv->ts_debug_str->size - 1, "%Y-%m-%d %H:%M:%S", localtime(&(srv->cur_ts)));
			srv->ts_debug_str->used = strlen(srv->ts_debug_str->ptr) + 1;

			srv->last_generated_debug_ts = srv->cur_ts;
		}

		buffer_copy_string_buffer(srv->errorlog_buf, srv->ts_debug_str);
		buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(": ("));
		break;
	case ERRORLOG_SYSLOG:
		/* syslog is generating its own timestamps */
		buffer_copy_string_len(srv->errorlog_buf, CONST_STR_LEN("("));
		break;
	}

	buffer_append_string(srv->errorlog_buf, filename);
	buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("."));
	buffer_append_long(srv->errorlog_buf, line);
	buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(") "));


	for(va_start(ap, fmt); *fmt; fmt++) {
		int d;
		char *s;
		buffer *b;
		off_t o;

		switch(*fmt) {
		case 's':           /* string */
			s = va_arg(ap, char *);
			buffer_append_string(srv->errorlog_buf, s);
			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));
			break;
		case 'b':           /* buffer */
			b = va_arg(ap, buffer *);
			buffer_append_string_buffer(srv->errorlog_buf, b);
			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));
			break;
		case 'd':           /* int */
			d = va_arg(ap, int);
			buffer_append_long(srv->errorlog_buf, d);
			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));
			break;
		case 'o':           /* off_t */
			o = va_arg(ap, off_t);
			buffer_append_off_t(srv->errorlog_buf, o);
			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));
			break;
		case 'x':           /* int (hex) */
			d = va_arg(ap, int);
			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("0x"));
			buffer_append_long_hex(srv->errorlog_buf, d);
			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN(" "));
			break;
		case 'S':           /* string */
			s = va_arg(ap, char *);
			buffer_append_string(srv->errorlog_buf, s);
			break;
		case 'B':           /* buffer */
			b = va_arg(ap, buffer *);
			buffer_append_string_buffer(srv->errorlog_buf, b);
			break;
		case 'D':           /* int */
			d = va_arg(ap, int);
			buffer_append_long(srv->errorlog_buf, d);
			break;
		case 'O':           /* off_t */
			o = va_arg(ap, off_t);
			buffer_append_off_t(srv->errorlog_buf, o);
			break;
		case 'X':           /* int (hex) */
			d = va_arg(ap, int);
			buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("0x"));
			buffer_append_long_hex(srv->errorlog_buf, d);
			break;
		case '(':
		case ')':
		case '<':
		case '>':
		case ',':
		case ' ':
			buffer_append_string_len(srv->errorlog_buf, fmt, 1);
			break;
		}
	}
	va_end(ap);

	switch(srv->errorlog_mode) {
	case ERRORLOG_PIPE:
	case ERRORLOG_FILE:
		buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("\n"));
		write(srv->errorlog_fd, srv->errorlog_buf->ptr, srv->errorlog_buf->used - 1);
		break;
	case ERRORLOG_STDERR:
		buffer_append_string_len(srv->errorlog_buf, CONST_STR_LEN("\n"));
		write(STDERR_FILENO, srv->errorlog_buf->ptr, srv->errorlog_buf->used - 1);
		break;
	case ERRORLOG_SYSLOG:
		syslog(LOG_ERR, "%s", srv->errorlog_buf->ptr);
		break;
	}

	return 0;
}
Exemplo n.º 18
0
void
nis_lerror (const nis_error status, const char *label)
{
  syslog (LOG_ERR, "%s: %s", label, nis_sperrno (status));
}
Exemplo n.º 19
0
int
main(int argc, char *const *argv)
{
	struct sockaddr_in bindaddr;
	socklen_t addrlen;
	const char *isDA;
	const char *proxyReg;
	int connfd;
	int lfd;
	const int on = 1;

	detachfromtty();

	openlog("slpd", LOG_PID, LOG_DAEMON);

	do_args(argc, argv);

	/* If slpd has been configured to run as a DA, start it and exit */
	isDA = SLPGetProperty("net.slp.isDA");
	proxyReg = SLPGetProperty("net.slp.serializedRegURL");
	if ((isDA && (strcasecmp(isDA, "true") == 0)) || proxyReg) {
		run_slpd();
		return (1);
	}

	if ((lfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		syslog(LOG_ERR, "socket failed: %s", strerror(errno));
		cleanup_and_exit(1);
	}

	(void) setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on));

	(void) memset((void *)&bindaddr, 0, sizeof (bindaddr));
	bindaddr.sin_family = AF_INET;
	bindaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	bindaddr.sin_port = htons(427);

	if (bind(lfd, (const struct sockaddr *)&bindaddr, sizeof (bindaddr))
	    < 0) {
		syslog(LOG_ERR, "bind failed: %s", strerror(errno));
		cleanup_and_exit(1);
	}

	if (listen(lfd, 1) < 0) {
		syslog(LOG_ERR, "listen failed: %s", strerror(errno));
		cleanup_and_exit(1);
	}

	addrlen = sizeof (bindaddr);
	if ((connfd = accept(lfd, (struct sockaddr *)&bindaddr, &addrlen))
	    < 0) {
		syslog(LOG_ERR, "accept failed: %s", strerror(errno));
		cleanup_and_exit(1);
	}

	(void) close(lfd);

	(void) dup2(connfd, 0);
	(void) close(connfd);
	(void) dup2(0, 1);
	(void) dup2(0, 2);

	run_slpd();

	return (1);
}
int main ( int argc, char * argv[] )
{
	int have_committed = 1; // prevent double commits, 'clean' state to begin with
        int c;

	program_name = argv[0];
	program_name = "ipbatch CLI";
	// this is really important for locating shared libs
	program_version = IPTABLES_VERSION;
        c = xtables_init_all(&iptables_globals, NFPROTO_IPV4);
        if (c < 0) {
                fprintf(stderr, "%s/%s Failed to initialize xtables\n",
                                program_name,
                                program_version);
                exit(1);
        }


	openlog( "SmoothIPSubsys", LOG_NDELAY | LOG_CONS, LOG_DAEMON );
	
/*        lib_dir = getenv("IPTABLES_LIB_DIR");*/
/*	if (!lib_dir)*/
/*		lib_dir = IPT_LIB_DIR;*/

	/* read lines from STDIN */

	char buffer[ BUFFER_SIZE ];
	int error = 0;

	// syslog( LOG_ERR, "Checking input" );
	// there are two special commands end is the same as eof and commit
	// does an early commit rather than the changes only being committed at the end
	while ( fgets( buffer, BUFFER_SIZE - 2, stdin ) != NULL ){
		/* terminate the line at the carriage return */

		if ( strlen( buffer ) > BUFFER_SIZE ){
			// silently ignore long lines
			continue;
		}

		buffer[ strlen( buffer ) - 1 ] = '\0';

		//syslog( LOG_ERR, "Received command %s", buffer );

		if ( strcmp( buffer, "end" ) == 0 ){
			break;
		}

		if ( strcmp( buffer, "commit" ) == 0 ){
			/* commit changes */
			error = iptc_commit(handle);
			iptc_free(handle);
			handle = NULL;
			have_committed = 1;
		} else {
			/* excute the command */
			if(!have_committed) {

				if(table_changed(buffer)) {   
					//syslog( LOG_ERR, "Table change for %s", buffer );
					error = iptc_commit(handle);
					iptc_free(handle);
					handle = NULL;
					have_committed = 1;
				}
			}
			if(*buffer)
			    error = execute( buffer );
			have_committed = 0;
		}

		if ( !error ){
			/* if an error has occured then we're */
			/* in trouble and might as well just  */
			/* leave                              */
			syslog( LOG_ERR, "error: %s", iptc_strerror(errno));
			return !error;
		}

	}

	//syslog( LOG_ERR, "Finished" );
	/* commit the changes, that is flush */
	/* the iptables buffer               */

	if(!have_committed) {
		error = iptc_commit(handle);
		iptc_free(handle);
		handle = NULL;
		syslog( LOG_ERR, "Unable to commit IPTables rules \"%s\"", iptc_strerror( errno ) );
	}

	return !error;
}
Exemplo n.º 21
0
void
udev_read_event(int fd)
{
	struct pdev_array_entry	*pae;
	prop_dictionary_t	dict, evdict, devdict;
	prop_number_t		pn;
	prop_string_t		ps;
	prop_object_t		po;
	prop_array_t		pa;
	char	*xml;
	int	n, idx, evtype;
	size_t	sz;

	sz = 4096 * 1024;

	xml = malloc(sz); /* 4 MB */
again:
	if ((n = read(fd, xml, sz)) <= 0) {
		if (errno == ENOMEM) {
			sz <<= 2;
			if ((xml = realloc(xml, sz)) == NULL) {
				syslog(LOG_ERR, "could not realloc xml memory");
				return;
			}
			goto again;
		}
		free(xml);
		return;
	}

	dict = prop_dictionary_internalize(xml);
	free(xml);
	if (dict == NULL) {
		syslog(LOG_ERR, "internalization of xml failed");
		return;
	}

	pn = prop_dictionary_get(dict, "evtype");
	if (pn == NULL) {
		syslog(LOG_ERR, "read_event: no key evtype");
		goto out;
	}

	evtype = prop_number_integer_value(pn);

	evdict = prop_dictionary_get(dict, "evdict");
	if (evdict == NULL) {
		syslog(LOG_ERR, "read_event: no key evdict");
		goto out;
	}

	switch (evtype) {
	case UDEV_EVENT_ATTACH:
		monitor_queue_event(dict);
		pae = pdev_array_entry_get_last();
		pa = prop_array_copy(pae->pdev_array);
		pdev_array_entry_unref(pae);
		if (pa == NULL)
			goto out;
		prop_array_add(pa, evdict);
		pdev_array_entry_insert(pa);
		break;

	case UDEV_EVENT_DETACH:
		monitor_queue_event(dict);
		if ((devdict = find_dev_dict(-1, evdict, &idx)) == NULL)
			goto out;
		pae = pdev_array_entry_get_last();
		pa = prop_array_copy(pae->pdev_array);
		pdev_array_entry_unref(pae);
		if (pa == NULL)
			goto out;
		prop_array_remove(pa, idx);
		pdev_array_entry_insert(pa);
		break;

	case UDEV_EV_KEY_UPDATE:
		if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL)
			goto out;
		if ((ps = prop_dictionary_get(evdict, "key")) == NULL)
			goto out;
		if ((po = prop_dictionary_get(evdict, "value")) == NULL)
			goto out;
		/* prop_object_retain(po); */ /* not necessary afaik */
		prop_dictionary_set(devdict, prop_string_cstring_nocopy(ps), po);
		break;

	case UDEV_EV_KEY_REMOVE:
		if ((devdict = find_dev_dict(-1, evdict, NULL)) == NULL)
			goto out;
		if ((ps = prop_dictionary_get(evdict, "key")) == NULL)
			goto out;
		prop_dictionary_remove(devdict, prop_string_cstring_nocopy(ps));
		break;

	default:
		syslog(LOG_ERR, "read_event: unknown evtype %d", evtype);
	}

out:
	prop_object_release(dict);
	return;
}
Exemplo n.º 22
0
int					/* O  - 1 if log file open */
cupsdCheckLogFile(cups_file_t **lf,	/* IO - Log file */
	          const char  *logname)	/* I  - Log filename */
{
  char		backname[1024],		/* Backup log filename */
		filename[1024],		/* Formatted log filename */
		*ptr;			/* Pointer into filename */
  const char	*logptr;		/* Pointer into log filename */


 /*
  * See if we have a log file to check...
  */

  if (!lf || !logname || !logname[0])
    return (1);

 /*
  * Handle logging to stderr...
  */

  if (!strcmp(logname, "stderr"))
  {
    *lf = LogStderr;
    return (1);
  }

 /*
  * Format the filename as needed...
  */

  if (!*lf ||
      (strncmp(logname, "/dev/", 5) && cupsFileTell(*lf) > MaxLogSize &&
       MaxLogSize > 0))
  {
   /*
    * Handle format strings...
    */

    filename[sizeof(filename) - 1] = '\0';

    if (logname[0] != '/')
    {
      strlcpy(filename, ServerRoot, sizeof(filename));
      strlcat(filename, "/", sizeof(filename));
    }
    else
      filename[0] = '\0';

    for (logptr = logname, ptr = filename + strlen(filename);
         *logptr && ptr < (filename + sizeof(filename) - 1);
	 logptr ++)
      if (*logptr == '%')
      {
       /*
        * Format spec...
	*/

        logptr ++;
	if (*logptr == 's')
	{
	 /*
	  * Insert the server name...
	  */

	  strlcpy(ptr, ServerName, sizeof(filename) - (size_t)(ptr - filename));
	  ptr += strlen(ptr);
	}
        else
	{
	 /*
	  * Otherwise just insert the character...
	  */

	  *ptr++ = *logptr;
	}
      }
      else
	*ptr++ = *logptr;

    *ptr = '\0';
  }

 /*
  * See if the log file is open...
  */

  if (!*lf)
  {
   /*
    * Nope, open the log file...
    */

    if ((*lf = cupsFileOpen(filename, "a")) == NULL)
    {
     /*
      * If the file is in CUPS_LOGDIR then try to create a missing directory...
      */

      if (!strncmp(filename, CUPS_LOGDIR, strlen(CUPS_LOGDIR)))
      {
       /*
        * Try updating the permissions of the containing log directory, using
	* the log file permissions as a basis...
	*/

        mode_t log_dir_perm = (mode_t)(0300 | LogFilePerm);
					/* LogFilePerm + owner write/search */
	if (log_dir_perm & 0040)
	  log_dir_perm |= 0010;		/* Add group search */
	if (log_dir_perm & 0004)
	  log_dir_perm |= 0001;		/* Add other search */

        cupsdCheckPermissions(CUPS_LOGDIR, NULL, log_dir_perm, RunUser, Group, 1, -1);

        *lf = cupsFileOpen(filename, "a");
      }

      if (*lf == NULL)
      {
#ifdef HAVE_ASL_H
	asl_object_t	m;		/* Log message */

	m = asl_new(ASL_TYPE_MSG);
	asl_set(m, ASL_KEY_FACILITY, "org.cups.cupsd");
	asl_log(NULL, m, ASL_LEVEL_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));
	asl_release(m);

#elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
        sd_journal_print(LOG_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));

#else
	syslog(LOG_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));
#endif /* HAVE_ASL_H */

        if (FatalErrors & CUPSD_FATAL_LOG)
	  cupsdEndProcess(getpid(), 0);

	return (0);
      }
    }

    if (strncmp(filename, "/dev/", 5))
    {
     /*
      * Change ownership and permissions of non-device logs...
      */

      fchown(cupsFileNumber(*lf), RunUser, Group);
      fchmod(cupsFileNumber(*lf), LogFilePerm);
    }
  }

 /*
  * Do we need to rotate the log?
  */

  if (strncmp(logname, "/dev/", 5) && cupsFileTell(*lf) > MaxLogSize &&
      MaxLogSize > 0)
  {
   /*
    * Rotate log file...
    */

    cupsFileClose(*lf);

    strlcpy(backname, filename, sizeof(backname));
    strlcat(backname, ".O", sizeof(backname));

    unlink(backname);
    rename(filename, backname);

    if ((*lf = cupsFileOpen(filename, "a")) == NULL)
    {
#ifdef HAVE_ASL_H
	asl_object_t	m;		/* Log message */

	m = asl_new(ASL_TYPE_MSG);
	asl_set(m, ASL_KEY_FACILITY, "org.cups.cupsd");
	asl_log(NULL, m, ASL_LEVEL_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));
	asl_release(m);

#elif defined(HAVE_SYSTEMD_SD_JOURNAL_H)
        sd_journal_print(LOG_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));

#else
	syslog(LOG_ERR, "Unable to open log file \"%s\" - %s", filename, strerror(errno));
#endif /* HAVE_ASL_H */

      if (FatalErrors & CUPSD_FATAL_LOG)
	cupsdEndProcess(getpid(), 0);

      return (0);
    }

   /*
    * Change ownership and permissions of non-device logs...
    */

    fchown(cupsFileNumber(*lf), RunUser, Group);
    fchmod(cupsFileNumber(*lf), LogFilePerm);
  }

  return (1);
}
Exemplo n.º 23
0
//!
//! Main log-printing function, which will dump a line into a log, with a prefix appropriate for
//! the log level, given that the log level is above the threshold.
//!
//! @param[in] func the caller function name (i.e. __FUNCTION__)
//! @param[in] file the file in which the caller function reside (i.e. __FILE__)
//! @param[in] line the line at which this function was called (i.e. __LINE__)
//! @param[in] level the log level for this message
//! @param[in] format the format string of the message
//! @param[in] ... the variable argument part of the format
//!
//! @return 0 on success, -1 on failure with this function or 1 if log_line() failed.
//!
//! @see log_line()
//!
//! @pre \li The func field must not be null if the prefix spec contains 'm'.
//!      \li The file field must not be null if the prefix spec contains 'F'.
//!      \li The log level must be valid and greather than or equal to the configured log level
//!      \li The format string must not be null.
//!
//! @post If the given level if greater or equal to the configured log level, the message will be
//!       printed into our log file or syslog.
//!
//! @todo evaluate if we cannot standardize the error code returned.
//!
int logprintfl(const char *func, const char *file, int line, log_level_e level, const char *format, ...)
{
    int rc = -1;
    int left = 0;
    int size = 0;
    int offset = 0;
    char *s = NULL;
    char c = '\0';
    char cn = '\0';
    boolean custom_spec = FALSE;
    char buf[LOGLINEBUF] = "";
    va_list ap = { {0} };
    const char *prefix_spec = NULL;

    // return if level is invalid or below the threshold
    if (level < log_level) {
        return (0);
    }

    if ((level < 0) || (level > EUCA_LOG_OFF)) {
        // unexpected log level
        return (-1);
    }

    if (strcmp(log_custom_prefix, USE_STANDARD_PREFIX) == 0) {
        prefix_spec = log_level_prefix[log_level];
        custom_spec = FALSE;
    } else {
        prefix_spec = log_custom_prefix;
        custom_spec = TRUE;
    }

    // go over prefix format for the log level (defined in log.h or custom)
    for (; *prefix_spec != '\0'; prefix_spec++) {
        s = buf + offset;
        if ((left = sizeof(buf) - offset - 1) < 1) {
            // not enough room in internal buffer for a prefix
            return -1;
        }
        // see if we have a formatting character or a regular one
        c = prefix_spec[0];
        cn = prefix_spec[1];
        if ((c != '%')                 // not a special formatting char
            || (c == '%' && cn == '%') // formatting char, escaped
            || (c == '%' && cn == '\0')) {  // formatting char at the end
            s[0] = c;
            s[1] = '\0';
            offset++;
            if ((c == '%') && (cn == '%')) {
                // swallow the one extra '%' in input
                prefix_spec++;
            }
            continue;
        }
        // move past the '%' to the formatting char
        prefix_spec++;

        size = 0;
        switch (*prefix_spec) {
        case 'T':
            // timestamp
            size = fill_timestamp(s, left);
            break;

        case 'L':{
                // log-level
                char l[6];
                euca_strncpy(l, log_level_names[level], 6); // we want hard truncation
                size = snprintf(s, left, "%5s", l);
                break;
            }

        case 'p':{
                // process ID
                char p[11];
                snprintf(p, sizeof(p), "%010d", getpid());  // 10 chars is enough for max 32-bit unsigned integer
                size = print_field_truncated(&prefix_spec, s, left, p);
                break;
            }

        case 't':{
                // thread ID
                char t[21];
                snprintf(t, sizeof(t), "%020d", (pid_t) syscall(SYS_gettid));   // 20 chars is enough for max 64-bit unsigned integer
                size = print_field_truncated(&prefix_spec, s, left, t);
                break;
            }

        case 'm':
            // method
            size = print_field_truncated(&prefix_spec, s, left, func);
            break;

        case 'F':{
                // file-and-line
                char file_and_line[64];
                snprintf(file_and_line, sizeof(file_and_line), "%s:%d", file, line);
                size = print_field_truncated(&prefix_spec, s, left, file_and_line);
                break;
            }

        case 's':{
                // max RSS of the process
                struct rusage u;
                bzero(&u, sizeof(struct rusage));
                getrusage(RUSAGE_SELF, &u);

                // unfortunately, many fields in 'struct rusage' aren't supported on Linux (notably: ru_ixrss, ru_idrss, ru_isrss)
                char size_str[64];
                snprintf(size_str, sizeof(size_str), "%05ld", u.ru_maxrss / 1024);
                size = print_field_truncated(&prefix_spec, s, left, size_str);
                break;
            }

        case '?':
            // not supported currently
            s[0] = '?';
            s[1] = '\0';
            size = 1;
            break;

        default:
            s[0] = *prefix_spec;
            s[1] = '\0';
            size = 1;
            break;
        }

        if (size < 0) {
            // something went wrong in the snprintf()s above
            logprintf("error in prefix construction in logprintfl()\n");
            return -1;
        }
        offset += size;
    }

    // add a space between the prefix and the message proper
    if ((offset > 0) && ((sizeof(buf) - offset - 1) > 0)) {
        buf[offset++] = ' ';
        buf[offset] = '\0';
    }
    // append the log message passed via va_list
    va_start(ap, format);
    {
        rc = vsnprintf(buf + offset, sizeof(buf) - offset - 1, format, ap);
    }
    va_end(ap);
    if (rc < 0)
        return (rc);

    if (syslog_facility != -1) {
        // log to syslog, at the appropriate level: euca DEBUG, TRACE, and EXTREME use syslog's DEBUG
        int l = LOG_DEBUG;
        if (level == EUCA_LOG_ERROR)
            l = LOG_ERR;
        else if (level == EUCA_LOG_WARN)
            l = LOG_WARNING;
        else if (level == EUCA_LOG_INFO)
            l = LOG_INFO;

        if (custom_spec)
            syslog(l, buf);
        else
            syslog(l, buf + offset);
    }

    return (log_line(buf));
}
Exemplo n.º 24
0
int
main(int argc, char *argv[])
{
#ifdef __FreeBSD__
	FILE *fpid = NULL;
#endif	
	fd_set *fdsr = NULL, *fdsw = NULL;
	struct sockaddr_in sin;
	struct sockaddr_in lin;
	int ch, s, s2, conflisten = 0, syncfd = 0, i, omax = 0, one = 1;
	socklen_t sinlen;
	u_short port;
	struct servent *ent;
	struct rlimit rlp;
	char *bind_address = NULL;
	const char *errstr;
	char *sync_iface = NULL;
	char *sync_baddr = NULL;

	tzset();
	openlog_r("spamd", LOG_PID | LOG_NDELAY, LOG_DAEMON, &sdata);

	if ((ent = getservbyname("spamd", "tcp")) == NULL)
		errx(1, "Can't find service \"spamd\" in /etc/services");
	port = ntohs(ent->s_port);
	if ((ent = getservbyname("spamd-cfg", "tcp")) == NULL)
		errx(1, "Can't find service \"spamd-cfg\" in /etc/services");
	cfg_port = ntohs(ent->s_port);
	if ((ent = getservbyname("spamd-sync", "udp")) == NULL)
		errx(1, "Can't find service \"spamd-sync\" in /etc/services");
	sync_port = ntohs(ent->s_port);

	if (gethostname(hostname, sizeof hostname) == -1)
		err(1, "gethostname");
	maxfiles = get_maxfiles();
	if (maxcon > maxfiles)
		maxcon = maxfiles;
	if (maxblack > maxfiles)
		maxblack = maxfiles;
	while ((ch =
#ifndef __FreeBSD__
	    getopt(argc, argv, "45l:c:B:p:bdG:h:s:S:M:n:vw:y:Y:")) != -1) {
#else
	    getopt(argc, argv, "45l:c:B:p:bdG:h:s:S:M:n:vw:y:Y:t:m:")) != -1) {
#endif
		switch (ch) {
		case '4':
			nreply = "450";
			break;
		case '5':
			nreply = "550";
			break;
		case 'l':
			bind_address = optarg;
			break;
		case 'B':
			i = atoi(optarg);
			maxblack = i;
			break;
		case 'c':
			i = atoi(optarg);
			if (i > maxfiles) {
				fprintf(stderr,
				    "%d > system max of %d connections\n",
				    i, maxfiles);
				usage();
			}
			maxcon = i;
			break;
		case 'p':
			i = atoi(optarg);
			port = i;
			break;
		case 'd':
			debug = 1;
			break;
		case 'b':
			greylist = 0;
			break;
		case 'G':
			if (sscanf(optarg, "%d:%d:%d", &passtime, &greyexp,
			    &whiteexp) != 3)
				usage();
			/* convert to seconds from minutes */
			passtime *= 60;
			/* convert to seconds from hours */
			whiteexp *= (60 * 60);
			/* convert to seconds from hours */
			greyexp *= (60 * 60);
			break;
		case 'h':
			bzero(&hostname, sizeof(hostname));
			if (strlcpy(hostname, optarg, sizeof(hostname)) >=
			    sizeof(hostname))
				errx(1, "-h arg too long");
			break;
		case 's':
			i = atoi(optarg);
			if (i < 0 || i > 10)
				usage();
			stutter = i;
			break;
		case 'S':
			/* 
			 * strtonum is aviable with FreeBSD 6.1,
			 * for older versions we have to fallback
			 */

			i = strtonum(optarg, 0, 90, &errstr);
			if (errstr)
				usage();
			grey_stutter = i;
			break;
		case 'M':
			low_prio_mx_ip = optarg;
			break;
		case 'n':
			spamd = optarg;
			break;
		case 'v':
			verbose = 1;
			break;
		case 'w':
			window = atoi(optarg);
			if (window <= 0)
				usage();
			break;
		case 'Y':
			if (sync_addhost(optarg, sync_port) != 0)
				sync_iface = optarg;
			syncsend++;
			break;
		case 'y':
			sync_baddr = optarg;
			syncrecv++;
			break;
#ifdef __FreeBSD__
		case 't':
			ipfw_tabno = atoi(optarg);
			break;
		case 'm':
			if (strcmp(optarg, "ipfw") == 0)
				use_pf=0;
			break;
#endif
		default:
			usage();
			break;
		}
	}

	setproctitle("[priv]%s%s",
	    greylist ? " (greylist)" : "",
	    (syncrecv || syncsend) ? " (sync)" : "");

	if (!greylist)
		maxblack = maxcon;
	else if (maxblack > maxcon)
		usage();

	rlp.rlim_cur = rlp.rlim_max = maxcon + 15;
	if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
		err(1, "setrlimit");

	con = calloc(maxcon, sizeof(*con));
	if (con == NULL)
		err(1, "calloc");

	con->obuf = malloc(8192);

	if (con->obuf == NULL)
		err(1, "malloc");
	con->osize = 8192;

	for (i = 0; i < maxcon; i++)
		con[i].fd = -1;

	signal(SIGPIPE, SIG_IGN);

	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s == -1)
		err(1, "socket");

	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one,
	    sizeof(one)) == -1)
		return (-1);

	conflisten = socket(AF_INET, SOCK_STREAM, 0);
	if (conflisten == -1)
		err(1, "socket");

	if (setsockopt(conflisten, SOL_SOCKET, SO_REUSEADDR, &one,
	    sizeof(one)) == -1)
		return (-1);

	memset(&sin, 0, sizeof sin);
	sin.sin_len = sizeof(sin);
	if (bind_address) {
		if (inet_pton(AF_INET, bind_address, &sin.sin_addr) != 1)
			err(1, "inet_pton");
	} else
		sin.sin_addr.s_addr = htonl(INADDR_ANY);
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);

	if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1)
		err(1, "bind");

	memset(&lin, 0, sizeof sin);
	lin.sin_len = sizeof(sin);
	lin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	lin.sin_family = AF_INET;
	lin.sin_port = htons(cfg_port);

	if (bind(conflisten, (struct sockaddr *)&lin, sizeof lin) == -1)
		err(1, "bind local");

	if (syncsend || syncrecv) {
		syncfd = sync_init(sync_iface, sync_baddr, sync_port);
		if (syncfd == -1)
			err(1, "sync init");
	}

	pw = getpwnam("_spamd");
	if (!pw)
		pw = getpwnam("nobody");

#ifdef __FreeBSD__
	/* open the pid file just before daemon */
	fpid = fopen(pid_file, "w");
	if (fpid == NULL) {
		syslog(LOG_ERR, "exiting (couldn't create pid file %s)", 
			pid_file);
		err(1, "couldn't create pid file \"%s\"", pid_file);
	}
#endif	

	if (debug == 0) {
		if (daemon(1, 1) == -1)
			err(1, "daemon");
	}

	if (greylist) {
#ifdef __FreeBSD__
		if(use_pf){
#endif			
			pfdev = open("/dev/pf", O_RDWR);
			if (pfdev == -1) {
				syslog_r(LOG_ERR, &sdata, "open /dev/pf: %m");
				exit(1);
			}
#ifdef __FreeBSD__
		} 	
#endif

		maxblack = (maxblack >= maxcon) ? maxcon - 100 : maxblack;
		if (maxblack < 0)
			maxblack = 0;

		/* open pipe to talk to greylister */
		if (pipe(greypipe) == -1) {
			syslog(LOG_ERR, "pipe (%m)");
			exit(1);
		}
		/* open pipe to recieve spamtrap configs */
		if (pipe(trappipe) == -1) {
			syslog(LOG_ERR, "pipe (%m)");
			exit(1);
		}
		jail_pid = fork();
		switch (jail_pid) {
		case -1:
			syslog(LOG_ERR, "fork (%m)");
			exit(1);
		case 0:
			/* child - continue */
			signal(SIGPIPE, SIG_IGN);
			grey = fdopen(greypipe[1], "w");
			if (grey == NULL) {
				syslog(LOG_ERR, "fdopen (%m)");
				_exit(1);
			}
			close(greypipe[0]);
			trapfd = trappipe[0];
			trapcfg = fdopen(trappipe[0], "r");
			if (trapcfg == NULL) {
				syslog(LOG_ERR, "fdopen (%m)");
				_exit(1);
			}
			close(trappipe[1]);
			goto jail;
		}
		/* parent - run greylister */
		grey = fdopen(greypipe[0], "r");
		if (grey == NULL) {
			syslog(LOG_ERR, "fdopen (%m)");
			exit(1);
		}
		close(greypipe[1]);
		trapcfg = fdopen(trappipe[1], "w");
		if (trapcfg == NULL) {
			syslog(LOG_ERR, "fdopen (%m)");
			exit(1);
		}
		close(trappipe[0]);
		return (greywatcher());
		/* NOTREACHED */
	}

jail:
#ifdef __FreeBSD__
	/* after switch user and daemon write and close the pid file */
	if (fpid) {
		fprintf(fpid, "%ld\n", (long) getpid());
		if (fclose(fpid) == EOF) {
			syslog(LOG_ERR, "exiting (couldn't close pid file %s)", 
				pid_file);
			exit(1);
		}
	}
#endif	

	if (chroot("/var/empty") == -1 || chdir("/") == -1) {
		syslog(LOG_ERR, "cannot chdir to /var/empty.");
		exit(1);
	}

	if (pw)
		if (setgroups(1, &pw->pw_gid) ||
		    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
		    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
			err(1, "failed to drop privs");

	if (listen(s, 10) == -1)
		err(1, "listen");

	if (listen(conflisten, 10) == -1)
		err(1, "listen");

	if (debug != 0)
		printf("listening for incoming connections.\n");
	syslog_r(LOG_WARNING, &sdata, "listening for incoming connections.");

	while (1) {
		struct timeval tv, *tvp;
		int max, n;
		int writers;

		max = MAX(s, conflisten);
		if (syncrecv)
			max = MAX(max, syncfd);
		max = MAX(max, conffd);
		max = MAX(max, trapfd);

		time(&t);
		for (i = 0; i < maxcon; i++)
			if (con[i].fd != -1)
				max = MAX(max, con[i].fd);

		if (max > omax) {
			free(fdsr);
			fdsr = NULL;
			free(fdsw);
			fdsw = NULL;
			fdsr = (fd_set *)calloc(howmany(max+1, NFDBITS),
			    sizeof(fd_mask));
			if (fdsr == NULL)
				err(1, "calloc");
			fdsw = (fd_set *)calloc(howmany(max+1, NFDBITS),
			    sizeof(fd_mask));
			if (fdsw == NULL)
				err(1, "calloc");
			omax = max;
		} else {
			memset(fdsr, 0, howmany(max+1, NFDBITS) *
			    sizeof(fd_mask));
			memset(fdsw, 0, howmany(max+1, NFDBITS) *
			    sizeof(fd_mask));
		}

		writers = 0;
		for (i = 0; i < maxcon; i++) {
			if (con[i].fd != -1 && con[i].r) {
				if (con[i].r + MAXTIME <= t) {
					closecon(&con[i]);
					continue;
				}
				FD_SET(con[i].fd, fdsr);
			}
			if (con[i].fd != -1 && con[i].w) {
				if (con[i].w + MAXTIME <= t) {
					closecon(&con[i]);
					continue;
				}
				if (con[i].w <= t)
					FD_SET(con[i].fd, fdsw);
				writers = 1;
			}
		}
		FD_SET(s, fdsr);

		/* only one active config conn at a time */
		if (conffd == -1)
			FD_SET(conflisten, fdsr);
		else
			FD_SET(conffd, fdsr);
		if (trapfd != -1)
			FD_SET(trapfd, fdsr);
		if (syncrecv)
			FD_SET(syncfd, fdsr);

		if (writers == 0) {
			tvp = NULL;
		} else {
			tv.tv_sec = 1;
			tv.tv_usec = 0;
			tvp = &tv;
		}

		n = select(max+1, fdsr, fdsw, NULL, tvp);
		if (n == -1) {
			if (errno != EINTR)
				err(1, "select");
			continue;
		}
		if (n == 0)
			continue;

		for (i = 0; i < maxcon; i++) {
			if (con[i].fd != -1 && FD_ISSET(con[i].fd, fdsr))
				handler(&con[i]);
			if (con[i].fd != -1 && FD_ISSET(con[i].fd, fdsw))
				handlew(&con[i], clients + 5 < maxcon);
		}
		if (FD_ISSET(s, fdsr)) {
			sinlen = sizeof(sin);
			s2 = accept(s, (struct sockaddr *)&sin, &sinlen);
			if (s2 == -1)
				/* accept failed, they may try again */
				continue;
			for (i = 0; i < maxcon; i++)
				if (con[i].fd == -1)
					break;
			if (i == maxcon)
				close(s2);
			else {
				initcon(&con[i], s2, (struct sockaddr *)&sin);
				syslog_r(LOG_INFO, &sdata,
				    "%s: connected (%d/%d)%s%s",
				    con[i].addr, clients, blackcount,
				    ((con[i].lists == NULL) ? "" :
				    ", lists:"),
				    ((con[i].lists == NULL) ? "":
				    con[i].lists));
			}
		}
		if (FD_ISSET(conflisten, fdsr)) {
			sinlen = sizeof(lin);
			conffd = accept(conflisten, (struct sockaddr *)&lin,
			    &sinlen);
			if (conffd == -1)
				/* accept failed, they may try again */
				continue;
			else if (ntohs(lin.sin_port) >= IPPORT_RESERVED) {
				close(conffd);
				conffd = -1;
			}
		}
		if (conffd != -1 && FD_ISSET(conffd, fdsr))
			do_config();
		if (trapfd != -1 && FD_ISSET(trapfd, fdsr))
			read_configline(trapcfg);
		if (syncrecv && FD_ISSET(syncfd, fdsr))
			sync_recv();
	}
	exit(1);
}
Exemplo n.º 25
0
void masterconn_metachanges_log(masterconn *eptr,const uint8_t *data,uint32_t length) {
	char logname1[100],logname2[100];
	uint32_t i;
	uint64_t version;
	if (length==1 && data[0]==0x55) {
		if (eptr->logfd!=NULL) {
			fclose(eptr->logfd);
			eptr->logfd=NULL;
		}
		if (BackLogsNumber>0) {
			for (i=BackLogsNumber ; i>0 ; i--) {
				snprintf(logname1,100,"changelog_ml.%"PRIu32".mfs",i);
				snprintf(logname2,100,"changelog_ml.%"PRIu32".mfs",i-1);
				rename(logname2,logname1);
			}
		} else {
			unlink("changelog_ml.0.mfs");
		}
		return;
	}
	if (length<10) {
		syslog(LOG_NOTICE,"MATOAN_METACHANGES_LOG - wrong size (%"PRIu32"/9+data)",length);
		eptr->mode = KILL;
		return;
	}
	if (data[0]!=0xFF) {
		syslog(LOG_NOTICE,"MATOAN_METACHANGES_LOG - wrong packet");
		eptr->mode = KILL;
		return;
	}
	if (data[length-1]!='\0') {
		syslog(LOG_NOTICE,"MATOAN_METACHANGES_LOG - invalid string");
		eptr->mode = KILL;
		return;
	}

	data++;
	version = get64bit(&data);

	if (lastlogversion>0 && version!=lastlogversion+1) {
		syslog(LOG_WARNING, "some changes lost: [%"PRIu64"-%"PRIu64"], download metadata again",lastlogversion,version-1);
		if (eptr->logfd!=NULL) {
			fclose(eptr->logfd);
			eptr->logfd=NULL;
		}
		for (i=0 ; i<=BackLogsNumber ; i++) {
			snprintf(logname1,100,"changelog_ml.%"PRIu32".mfs",i);
			unlink(logname1);
		}
		lastlogversion = 0;
		eptr->mode = KILL;
		return;
	}

	if (eptr->logfd==NULL) {
		eptr->logfd = fopen("changelog_ml.0.mfs","a");
	}

	if (eptr->logfd) {
		fprintf(eptr->logfd,"%"PRIu64": %s\n",version,data);
		lastlogversion = version;
	} else {
		syslog(LOG_NOTICE,"lost MFS change %"PRIu64": %s",version,data);
	}
}
Exemplo n.º 26
0
int log__vprintf(int priority, const char *fmt, va_list va)
{
	char *s;
	char *st;
	int len;
#ifdef WIN32
	char *sp;
#endif
	const char *topic;
	int syslog_priority;
	time_t now = time(NULL);
	static time_t last_flush = 0;

	if((log_priorities & priority) && log_destinations != MQTT3_LOG_NONE){
		switch(priority){
			case MOSQ_LOG_SUBSCRIBE:
				topic = "$SYS/broker/log/M/subscribe";
#ifndef WIN32
				syslog_priority = LOG_NOTICE;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
			case MOSQ_LOG_UNSUBSCRIBE:
				topic = "$SYS/broker/log/M/unsubscribe";
#ifndef WIN32
				syslog_priority = LOG_NOTICE;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
			case MOSQ_LOG_DEBUG:
				topic = "$SYS/broker/log/D";
#ifndef WIN32
				syslog_priority = LOG_DEBUG;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
			case MOSQ_LOG_ERR:
				topic = "$SYS/broker/log/E";
#ifndef WIN32
				syslog_priority = LOG_ERR;
#else
				syslog_priority = EVENTLOG_ERROR_TYPE;
#endif
				break;
			case MOSQ_LOG_WARNING:
				topic = "$SYS/broker/log/W";
#ifndef WIN32
				syslog_priority = LOG_WARNING;
#else
				syslog_priority = EVENTLOG_WARNING_TYPE;
#endif
				break;
			case MOSQ_LOG_NOTICE:
				topic = "$SYS/broker/log/N";
#ifndef WIN32
				syslog_priority = LOG_NOTICE;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
			case MOSQ_LOG_INFO:
				topic = "$SYS/broker/log/I";
#ifndef WIN32
				syslog_priority = LOG_INFO;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
#ifdef WITH_WEBSOCKETS
			case MOSQ_LOG_WEBSOCKETS:
				topic = "$SYS/broker/log/WS";
#ifndef WIN32
				syslog_priority = LOG_DEBUG;
#else
				syslog_priority = EVENTLOG_INFORMATION_TYPE;
#endif
				break;
#endif
			default:
				topic = "$SYS/broker/log/E";
#ifndef WIN32
				syslog_priority = LOG_ERR;
#else
				syslog_priority = EVENTLOG_ERROR_TYPE;
#endif
		}
		len = strlen(fmt) + 500;
		s = mosquitto__malloc(len*sizeof(char));
		if(!s) return MOSQ_ERR_NOMEM;

		vsnprintf(s, len, fmt, va);
		s[len-1] = '\0'; /* Ensure string is null terminated. */

		if(log_destinations & MQTT3_LOG_STDOUT){
			if(int_db.config && int_db.config->log_timestamp){
				fprintf(stdout, "%d: %s\n", (int)now, s);
			}else{
				fprintf(stdout, "%s\n", s);
			}
			fflush(stdout);
		}
		if(log_destinations & MQTT3_LOG_STDERR){
			if(int_db.config && int_db.config->log_timestamp){
				fprintf(stderr, "%d: %s\n", (int)now, s);
			}else{
				fprintf(stderr, "%s\n", s);
			}
			fflush(stderr);
		}
		if(log_destinations & MQTT3_LOG_FILE && int_db.config->log_fptr){
			if(int_db.config && int_db.config->log_timestamp){
				fprintf(int_db.config->log_fptr, "%d: %s\n", (int)now, s);
			}else{
				fprintf(int_db.config->log_fptr, "%s\n", s);
			}
			if(now - last_flush > 1){
				fflush(int_db.config->log_fptr);
				last_flush = now;
			}
		}
		if(log_destinations & MQTT3_LOG_SYSLOG){
#ifndef WIN32
			syslog(syslog_priority, "%s", s);
#else
			sp = (char *)s;
			ReportEvent(syslog_h, syslog_priority, 0, 0, NULL, 1, 0, &sp, NULL);
#endif
		}
		if(log_destinations & MQTT3_LOG_TOPIC && priority != MOSQ_LOG_DEBUG){
			if(int_db.config && int_db.config->log_timestamp){
				len += 30;
				st = mosquitto__malloc(len*sizeof(char));
				if(!st){
					mosquitto__free(s);
					return MOSQ_ERR_NOMEM;
				}
				snprintf(st, len, "%d: %s", (int)now, s);
				db__messages_easy_queue(&int_db, NULL, topic, 2, strlen(st), st, 0);
				mosquitto__free(st);
			}else{
				db__messages_easy_queue(&int_db, NULL, topic, 2, strlen(s), s, 0);
			}
		}
		mosquitto__free(s);
	}

	return MOSQ_ERR_SUCCESS;
}
Exemplo n.º 27
0
void masterconn_read(masterconn *eptr,double now) {
	int32_t i;
	uint32_t type,leng;
	const uint8_t *ptr;
	uint32_t rbleng,rbpos;
	uint8_t err,hup;
	static uint8_t *readbuff = NULL;
	static uint32_t readbuffsize = 0;

	if (eptr == NULL) {
		if (readbuff != NULL) {
			free(readbuff);
		}
		readbuff = NULL;
		readbuffsize = 0;
		return;
	}

	if (readbuffsize==0) {
		readbuffsize = 65536;
		readbuff = malloc(readbuffsize);
		passert(readbuff);
	}

	rbleng = 0;
	err = 0;
	hup = 0;
	for (;;) {
		i = read(eptr->sock,readbuff+rbleng,readbuffsize-rbleng);
		if (i==0) {
			hup = 1;
			break;
		} else if (i<0) {
			if (ERRNO_ERROR) {
				err = 1;
			}
			break;
		} else {
			stats_bytesin+=i;
			rbleng += i;
			if (rbleng==readbuffsize) {
				readbuffsize*=2;
				readbuff = realloc(readbuff,readbuffsize);
				passert(readbuff);
			} else {
				break;
			}
		}
	}

	if (rbleng>0) {
		eptr->lastread = now;
	}

	rbpos = 0;
	while (rbpos<rbleng) {
		if ((rbleng-rbpos)>=eptr->input_bytesleft) {
			memcpy(eptr->input_startptr,readbuff+rbpos,eptr->input_bytesleft);
			i = eptr->input_bytesleft;
		} else {
			memcpy(eptr->input_startptr,readbuff+rbpos,rbleng-rbpos);
			i = rbleng-rbpos;
		}
		rbpos += i;
		eptr->input_startptr+=i;
		eptr->input_bytesleft-=i;

		if (eptr->input_bytesleft>0) {
			break;
		}

		if (eptr->input_packet == NULL) {
			ptr = eptr->input_hdr;
			type = get32bit(&ptr);
			leng = get32bit(&ptr);

			if (leng>MaxPacketSize) {
				syslog(LOG_WARNING,"Master packet too long (%"PRIu32"/%u)",leng,MaxPacketSize);
				eptr->input_end = 1;
				return;
			}

			eptr->input_packet = malloc(offsetof(in_packetstruct,data)+leng);
			passert(eptr->input_packet);
			eptr->input_packet->next = NULL;
			eptr->input_packet->type = type;
			eptr->input_packet->leng = leng;

			eptr->input_startptr = eptr->input_packet->data;
			eptr->input_bytesleft = leng;
		}

		if (eptr->input_bytesleft>0) {
			continue;
		}

		if (eptr->input_packet != NULL) {
			*(eptr->inputtail) = eptr->input_packet;
			eptr->inputtail = &(eptr->input_packet->next);
			eptr->input_packet = NULL;
			eptr->input_bytesleft = 8;
			eptr->input_startptr = eptr->input_hdr;
		}
	}

	if (hup) {
		syslog(LOG_NOTICE,"connection was reset by Master");
		eptr->input_end = 1;
	} else if (err) {
		mfs_errlog_silent(LOG_NOTICE,"read from Master error");
		eptr->input_end = 1;
	}
}
Exemplo n.º 28
0
PAM_EXTERN int
pam_sm_authenticate(pam_handle_t *pamh, int flags,
                    int argc, const char *argv[])
{
    const char *user;
    char *password;
    int pam_err, retry;

    const char *url = NULL;
    const char *service_user = NULL;
    const char *service_password = NULL;
    const char *group = NULL;
    const char *domain = NULL;
    int validate_certificate = 0;
    char *stripped_user = NULL;

    /* parse all parameters */
    {
        int i = 0;
        while (i < argc) {
            const char *val;

            if ((val = string_prefix_match(argv[i], "url=")) != NULL)
                url = val;
            else if ((val = string_prefix_match(argv[i], "service_user="******"service_password="******"group=")) != NULL)
                group = val;
            else if ((val = string_prefix_match(argv[i], "validate_certificate=")) != NULL)
                validate_certificate = !!strcmp(val, "no"); /* no = 0, everything else = 1 */
            else if ((val = string_prefix_match(argv[i], "domain=")) != NULL)
                domain = val;

            i++;
        }
    }

    /* complain about missing arguments, return error */
    if (!url || !(*url))
        syslog(LOG_AUTHPRIV|LOG_ERR, __FILE__": missing or empty required argument 'url'");
    if (!service_user)
        syslog(LOG_AUTHPRIV|LOG_ERR, __FILE__": missing required argument 'service_user'");
    if (!service_password)
        syslog(LOG_AUTHPRIV|LOG_ERR, __FILE__": missing required argument 'service_password'");

    if (!url || !(*url) || !service_user || !service_password)
        return PAM_AUTHINFO_UNAVAIL;

    /* get user */
    if ((pam_err = pam_get_user(pamh, &user, NULL)) != PAM_SUCCESS)
        return (pam_err);

    /* get password - TODO why is this retry loop here? */
    for (retry = 0; retry < 3; retry++) {
        pam_err = pam_get_authtok(pamh, PAM_AUTHTOK, (const char **)&password, NULL);
        if (pam_err == PAM_SUCCESS)
            break;
    }
    if (pam_err != PAM_SUCCESS)
        return (PAM_AUTH_ERR);

    /* strip domain & compare passwords */
    stripped_user = strip_domain(user, domain);
    
    if (stripped_user == NULL || pam_restauth_check(url, service_user, service_password,
                        group, validate_certificate, stripped_user, password)) {
        /* wait a bit */
        sleep(2);
        pam_err = PAM_AUTH_ERR; // TODO AUTHINFO_UNAVAIL (on hardware failure)
    } else {
        pam_err = PAM_SUCCESS;
    }
    
    if (stripped_user)
        free(stripped_user);

    return (pam_err);
}
Exemplo n.º 29
0
static void murmurMessageOutputQString(QtMsgType type, const QString &msg) {
#ifdef Q_OS_UNIX
	if (unixMurmur->logToSyslog) {
		int level;
		switch (type) {
		case QtDebugMsg:
			level = LOG_DEBUG;
			break;
		case QtWarningMsg:
			level = LOG_WARNING;
			break;
		case QtCriticalMsg:
			level = LOG_CRIT;
			break;
		case QtFatalMsg:
		default:
			level = LOG_ALERT;
			break;
		}
		syslog(level, "%s", qPrintable(msg));
		return;
	}
#endif

	char c;
	switch (type) {
		case QtDebugMsg:
			if (! bVerbose)
				return;
			c='D';
			break;
		case QtWarningMsg:
			c='W';
			break;
		case QtCriticalMsg:
			c='C';
			break;
		case QtFatalMsg:
			c='F';
			break;
		default:
			c='X';
	}
	QString m= QString::fromLatin1("<%1>%2 %3").arg(QChar::fromLatin1(c)).arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")).arg(msg);

	if (! qfLog || ! qfLog->isOpen()) {
#ifdef Q_OS_UNIX
		if (! detach)
			fprintf(stderr, "%s\n", qPrintable(m));
		else
			qlErrors << m;
#else
		qlErrors << m;
#ifndef QT_NO_DEBUG
		fprintf(stderr, "%s\n", qPrintable(m));
#endif
#endif
	} else {
		if (! qlErrors.isEmpty()) {
			foreach(const QString &e, qlErrors) {
				qfLog->write(e.toUtf8());
				qfLog->write("\n");
			}
			qlErrors.clear();
		}
Exemplo n.º 30
0
void daemonize(const char *cmd)
{
    int i, fd0, fd1, fd2;
    pid_t pid;
    struct rlimit rl;
    struct sigaction sa;

    /*
     * Clear file creation mask.
     */
    umask(0);

    /*
     * Get maximum number of file descriptors.
     */
    if (getrlimit(RLIMIT_NOFILE, &rl) < 0) {
        fprintf(stderr, "%s: can’t get file limit\n", cmd);
        exit(1);
    }

    /*
     * Become a session leader to lose controlling TTY.
     */
    if ((pid = fork()) < 0) {
        fprintf(stderr, "fork error\n");
        exit(1);
    } else if (pid != 0) {
        // parent
        exit(0);
    }
    setsid();
    /*
     * Ensure future opens won’t allocate controlling TTYs.
     */
    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if (sigaction(SIGHUP, &sa, NULL) < 0) {
        fprintf(stderr, "can't ignore SIGHUP\n");
        exit(0);
    }
    if ((pid = fork()) < 0) {
        fprintf(stderr, "fork error\n");
        exit(1);
    } else if (pid != 0) {
        // parent
        exit(0);
    }

    /*
     * Change the current working directory to the root so
     * we won’t prevent file systems from being unmounted.
     */
    if (chdir("/") < 0) {
        fprintf(stderr, "%s: can’t change directory to /\n", cmd);
        exit(0);
    }

    /*
     * Close all open file descriptors.
     */
    if (rl.rlim_max == RLIM_INFINITY) {
        rl.rlim_max = 1024;
    }
    for (i = 0; i < rl.rlim_max; i++) {
        close(i);
    }

    /*
     * Attach file descriptors 0, 1, and 2 to /dev/null.
     */
    fd0 = open("/dev/null", O_RDWR);
    fd1 = dup(0);
    fd2 = dup(0);

    /*
     * Initialize the log file.
     */
    openlog(cmd, LOG_CONS, LOG_DAEMON);
    if (fd0 != 0 || fd1 != 1 || fd2 != 2) {
        syslog(LOG_ERR, "unexpected file descriptors %d %d %d", fd0, fd1, fd2);
        exit(1);
    }
}