Пример #1
0
int main(int argc, char *argv[])
{
	char *inputFile, *outputFile;
	int idx, flags = 0, status;

	if(argc < 2)
	{
		help();
	}


	while(1)
	{
		int c = getopt(argc, argv, "-i:hau:o:");
		if(c == -1) break;

		switch(c) 
		{
			case 'i': flags |= FLAG_INPUT_FILE;
				inputFile = optarg;
				break;
			case 'u': flags |= FLAG_UNITEST_NUM;
				idx = atoi(optarg);
				break;
			case 'a': flags |= FLAG_TEST_ALL; 
				break;
			case 'o': flags |= FLAG_OUTPUT_FILE;
				outputFile = optarg;
				break;
			case 'h': help(); 
				exit(0);
			default:
				break;
		}
	}	

	loggerInit((LOG_MODE_CONSOLE | LOG_MODE_FILE),"testModule", LOG_LEVEL_DONTCARE);

	if(flags & FLAG_UNITEST_NUM)
	{
		switch (idx)
		{
			case 1:
				logInfo("muImage basic operiting\n");
				status = testMuImageBasic();
				if(status)
				{
					logInfo("Failed\n");
				}
				break;
			case 5:
				logInfo("muDrawRectangle test\n");
				status = testDrawRectangle(inputFile);
				if(status)
				{
					logInfo("Failed\n");
				}
				break;
			case 6:
				logInfo("muRGB2HSV test\n");
				if(flags & FLAG_INPUT_FILE)
				{
					status = testRGB2HSV(inputFile);
					if(status)
					{
						logInfo("Failed\n");
					}
					else
					{
						logInfo("Passed\n");
					}
				}
				else
				{
					logError("muRGB2HSV must give a input file testModue.exe -i test.bmp -n 6\n");
				}
				break;
			default:
				break;
		}
	}

	loggerExit();
	return 0;

}
void peano::applications::faxen::repositories::FaxenBatchJobRepositoryForSpacetreeGridArrayStackImplementation::logIterationStatistics() const {
  logInfo( "logIterationStatistics()", "|| adapter name \t || iterations \t || total CPU time [t]=s \t || average CPU time [t]=s \t || total user time [t]=s \t || average user time [t]=s " );  
   logInfo( "logIterationStatistics()", "| Initialize \t |  " << _countInitializeRuns << " \t |  " << _measureInitializeCPUTime << " \t |  " << (_countInitializeRuns==0 ? 0 : _measureInitializeCPUTime / static_cast<double>(_countInitializeRuns))  << " \t |  " << _measureInitializeCalendarTime << " \t |  " << (_countInitializeRuns==0 ? 0 : _measureInitializeCalendarTime / static_cast<double>(_countInitializeRuns))  );  
   logInfo( "logIterationStatistics()", "| InitializeAndSetBoundary \t |  " << _countInitializeAndSetBoundaryRuns << " \t |  " << _measureInitializeAndSetBoundaryCPUTime << " \t |  " << (_countInitializeAndSetBoundaryRuns==0 ? 0 : _measureInitializeAndSetBoundaryCPUTime / static_cast<double>(_countInitializeAndSetBoundaryRuns))  << " \t |  " << _measureInitializeAndSetBoundaryCalendarTime << " \t |  " << (_countInitializeAndSetBoundaryRuns==0 ? 0 : _measureInitializeAndSetBoundaryCalendarTime / static_cast<double>(_countInitializeAndSetBoundaryRuns))  );  
   logInfo( "logIterationStatistics()", "| PlotGrid \t |  " << _countPlotGridRuns << " \t |  " << _measurePlotGridCPUTime << " \t |  " << (_countPlotGridRuns==0 ? 0 : _measurePlotGridCPUTime / static_cast<double>(_countPlotGridRuns))  << " \t |  " << _measurePlotGridCalendarTime << " \t |  " << (_countPlotGridRuns==0 ? 0 : _measurePlotGridCalendarTime / static_cast<double>(_countPlotGridRuns))  );  
   logInfo( "logIterationStatistics()", "| ControlTimeStep \t |  " << _countControlTimeStepRuns << " \t |  " << _measureControlTimeStepCPUTime << " \t |  " << (_countControlTimeStepRuns==0 ? 0 : _measureControlTimeStepCPUTime / static_cast<double>(_countControlTimeStepRuns))  << " \t |  " << _measureControlTimeStepCalendarTime << " \t |  " << (_countControlTimeStepRuns==0 ? 0 : _measureControlTimeStepCalendarTime / static_cast<double>(_countControlTimeStepRuns))  );  
   logInfo( "logIterationStatistics()", "| SetVelocitiesBoundary \t |  " << _countSetVelocitiesBoundaryRuns << " \t |  " << _measureSetVelocitiesBoundaryCPUTime << " \t |  " << (_countSetVelocitiesBoundaryRuns==0 ? 0 : _measureSetVelocitiesBoundaryCPUTime / static_cast<double>(_countSetVelocitiesBoundaryRuns))  << " \t |  " << _measureSetVelocitiesBoundaryCalendarTime << " \t |  " << (_countSetVelocitiesBoundaryRuns==0 ? 0 : _measureSetVelocitiesBoundaryCalendarTime / static_cast<double>(_countSetVelocitiesBoundaryRuns))  );  
   logInfo( "logIterationStatistics()", "| SetScenarioBoundary \t |  " << _countSetScenarioBoundaryRuns << " \t |  " << _measureSetScenarioBoundaryCPUTime << " \t |  " << (_countSetScenarioBoundaryRuns==0 ? 0 : _measureSetScenarioBoundaryCPUTime / static_cast<double>(_countSetScenarioBoundaryRuns))  << " \t |  " << _measureSetScenarioBoundaryCalendarTime << " \t |  " << (_countSetScenarioBoundaryRuns==0 ? 0 : _measureSetScenarioBoundaryCalendarTime / static_cast<double>(_countSetScenarioBoundaryRuns))  );  
   logInfo( "logIterationStatistics()", "| ComputeVelocitiesDerivatives \t |  " << _countComputeVelocitiesDerivativesRuns << " \t |  " << _measureComputeVelocitiesDerivativesCPUTime << " \t |  " << (_countComputeVelocitiesDerivativesRuns==0 ? 0 : _measureComputeVelocitiesDerivativesCPUTime / static_cast<double>(_countComputeVelocitiesDerivativesRuns))  << " \t |  " << _measureComputeVelocitiesDerivativesCalendarTime << " \t |  " << (_countComputeVelocitiesDerivativesRuns==0 ? 0 : _measureComputeVelocitiesDerivativesCalendarTime / static_cast<double>(_countComputeVelocitiesDerivativesRuns))  );  
   logInfo( "logIterationStatistics()", "| ComputeRightHandSide \t |  " << _countComputeRightHandSideRuns << " \t |  " << _measureComputeRightHandSideCPUTime << " \t |  " << (_countComputeRightHandSideRuns==0 ? 0 : _measureComputeRightHandSideCPUTime / static_cast<double>(_countComputeRightHandSideRuns))  << " \t |  " << _measureComputeRightHandSideCalendarTime << " \t |  " << (_countComputeRightHandSideRuns==0 ? 0 : _measureComputeRightHandSideCalendarTime / static_cast<double>(_countComputeRightHandSideRuns))  );  
   logInfo( "logIterationStatistics()", "| SetZeroPressureBoundary \t |  " << _countSetZeroPressureBoundaryRuns << " \t |  " << _measureSetZeroPressureBoundaryCPUTime << " \t |  " << (_countSetZeroPressureBoundaryRuns==0 ? 0 : _measureSetZeroPressureBoundaryCPUTime / static_cast<double>(_countSetZeroPressureBoundaryRuns))  << " \t |  " << _measureSetZeroPressureBoundaryCalendarTime << " \t |  " << (_countSetZeroPressureBoundaryRuns==0 ? 0 : _measureSetZeroPressureBoundaryCalendarTime / static_cast<double>(_countSetZeroPressureBoundaryRuns))  );  
   logInfo( "logIterationStatistics()", "| SetPressureBoundary \t |  " << _countSetPressureBoundaryRuns << " \t |  " << _measureSetPressureBoundaryCPUTime << " \t |  " << (_countSetPressureBoundaryRuns==0 ? 0 : _measureSetPressureBoundaryCPUTime / static_cast<double>(_countSetPressureBoundaryRuns))  << " \t |  " << _measureSetPressureBoundaryCalendarTime << " \t |  " << (_countSetPressureBoundaryRuns==0 ? 0 : _measureSetPressureBoundaryCalendarTime / static_cast<double>(_countSetPressureBoundaryRuns))  );  
   logInfo( "logIterationStatistics()", "| SORStep \t |  " << _countSORStepRuns << " \t |  " << _measureSORStepCPUTime << " \t |  " << (_countSORStepRuns==0 ? 0 : _measureSORStepCPUTime / static_cast<double>(_countSORStepRuns))  << " \t |  " << _measureSORStepCalendarTime << " \t |  " << (_countSORStepRuns==0 ? 0 : _measureSORStepCalendarTime / static_cast<double>(_countSORStepRuns))  );  
   logInfo( "logIterationStatistics()", "| ComputeResidualNorm \t |  " << _countComputeResidualNormRuns << " \t |  " << _measureComputeResidualNormCPUTime << " \t |  " << (_countComputeResidualNormRuns==0 ? 0 : _measureComputeResidualNormCPUTime / static_cast<double>(_countComputeResidualNormRuns))  << " \t |  " << _measureComputeResidualNormCalendarTime << " \t |  " << (_countComputeResidualNormRuns==0 ? 0 : _measureComputeResidualNormCalendarTime / static_cast<double>(_countComputeResidualNormRuns))  );  
   logInfo( "logIterationStatistics()", "| ComputeVelocities \t |  " << _countComputeVelocitiesRuns << " \t |  " << _measureComputeVelocitiesCPUTime << " \t |  " << (_countComputeVelocitiesRuns==0 ? 0 : _measureComputeVelocitiesCPUTime / static_cast<double>(_countComputeVelocitiesRuns))  << " \t |  " << _measureComputeVelocitiesCalendarTime << " \t |  " << (_countComputeVelocitiesRuns==0 ? 0 : _measureComputeVelocitiesCalendarTime / static_cast<double>(_countComputeVelocitiesRuns))  );  
   logInfo( "logIterationStatistics()", "| PlotSolution \t |  " << _countPlotSolutionRuns << " \t |  " << _measurePlotSolutionCPUTime << " \t |  " << (_countPlotSolutionRuns==0 ? 0 : _measurePlotSolutionCPUTime / static_cast<double>(_countPlotSolutionRuns))  << " \t |  " << _measurePlotSolutionCalendarTime << " \t |  " << (_countPlotSolutionRuns==0 ? 0 : _measurePlotSolutionCalendarTime / static_cast<double>(_countPlotSolutionRuns))  );  

}
Пример #3
0
/*!
    \fn KmlExport::generate()
 */
void KmlExport::generate()
{
    //! @todo perform a test here before continuing.
    createDir(QString(m_tempDestDir + m_imageDir));

    m_progressDialog->show();
    ImageCollection selection = m_interface->currentSelection();
    ImageCollection album     = m_interface->currentAlbum();

    // create the document, and it's root
    m_kmlDocument                   = new QDomDocument("");
    QDomImplementation impl;
    QDomProcessingInstruction instr = m_kmlDocument->createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");
    m_kmlDocument->appendChild(instr);
    QDomElement kmlRoot             = m_kmlDocument->createElementNS("http://www.opengis.net/kml/2.2", "kml");
    m_kmlDocument->appendChild( kmlRoot );

    QDomElement kmlAlbum            = addKmlElement(kmlRoot, "Document");
    QDomElement kmlName             = addKmlTextElement(kmlAlbum, "name", album.name());
    QDomElement kmlDescription      = addKmlHtmlElement(kmlAlbum, "description",
                                                        "Created with kmlexport <a href=\"http://www.digikam.org/\">kipi-plugin</a>");

    if (m_GPXtracks)
    {
        addTrack(kmlAlbum);
    }

    KPMetadata meta;
    KUrl::List images = selection.images();
    int defectImage   = 0;
    int pos           = 1;
    int count         = images.count();
    KUrl::List::ConstIterator imagesEnd (images.constEnd());

    for( KUrl::List::ConstIterator selIt = images.constBegin(); selIt != imagesEnd; ++selIt, ++pos)
    {
        double alt, lat, lng;
        KUrl url        = *selIt;
        KPImageInfo info(url);
        bool hasGPSInfo = info.hasGeolocationInfo();

        if (hasGPSInfo)
        {
            lat = info.latitude();
            lng = info.longitude();
            alt = info.altitude();
        }
        else
        {
            meta.load(url.path());
            hasGPSInfo = meta.getGPSInfo(alt, lat, lng);
        }

        if ( hasGPSInfo )
        {
            // generation de l'image et de l'icone
            generateImagesthumb(url, kmlAlbum);
        }
        else
        {
            logWarning(i18n("No position data for '%1'", info.name()));
            defectImage++;
        }

        m_progressDialog->progressWidget()->setProgress(pos, count);
        kapp->processEvents();
    }

    if (defectImage)
    {
        /** @todo if defectImage==count there are no pictures exported, does is it worth to continue? */
        KMessageBox::information(kapp->activeWindow(),
                                 i18np("No position data for 1 picture",
                                       "No position data for %1 pictures", defectImage));
    }

    /** @todo change to kml or kmz if compressed */
    QFile file( m_tempDestDir + m_KMLFileName + ".kml");
    /** @todo handle file opening problems */
    file.open( QIODevice::WriteOnly );
    QTextStream stream( &file ); // we will serialize the data into the file
    stream << m_kmlDocument->toString();
    file.close();

    delete m_kmlDocument;
    m_kmlDocument = 0;

    KIO::moveAs(m_tempDestDir, m_baseDestDir, KIO::HideProgressInfo | KIO::Overwrite);
    logInfo(i18n("Move to final directory"));
    m_progressDialog->close();
}
void paraNode()
/* paraNode - a net server. */
{
char *line;
char *command;
struct sockaddr_in sai;

/* We have to know who we are... */
hostName = getMachine();
initRandom();
getTicksToHundreths();

/* log init */
if (optionExists("log"))
    logOpenFile("paraNode", optionVal("log", NULL));
else    
    logOpenSyslog("paraNode", optionVal("logFacility", NULL));
logSetMinPriority(optionVal("logMinPriority", "info"));
logInfo("starting paraNode on %s", hostName);

/* Make job lists. */
jobsRunning = newDlList();
jobsFinished = newDlList();

/* Set up socket and self to listen to it. */
ZeroVar(&sai);
sai.sin_family = AF_INET;
sai.sin_port = htons(paraNodePort);
sai.sin_addr.s_addr = INADDR_ANY;
mainRudp = rudpMustOpenBound(&sai);
mainRudp->maxRetries = 12;

/* Event loop. */
findNow();
for (;;)
    {
    /* Get next incoming message and optionally check to make
     * sure that it's from a host we trust, and check signature
     * on first bit of incoming data. */
    if (pmReceive(&pmIn, mainRudp))
	{
	findNow();
	if (hubName == NULL || ntohl(pmIn.ipAddress.sin_addr.s_addr) == hubIp 
		|| ntohl(pmIn.ipAddress.sin_addr.s_addr) == localIp)
	    {
	    /* Host and signature look ok,  read a string and
	     * parse out first word as command. */
	    line = pmIn.data;
	    logDebug("message from %s: \"%s\"",
                     paraFormatIp(ntohl(pmIn.ipAddress.sin_addr.s_addr)),
                     line);
	    command = nextWord(&line);
	    if (command != NULL)
		{
		if (sameString("quit", command))
		    break;
		else if (sameString("run", command))
		    doRun(line, &pmIn.ipAddress);
		else if (sameString("jobDone", command))
		    jobDone(line);
		else if (sameString("status", command))
		    doStatus();
		else if (sameString("kill", command))
		    doKill(line);
		else if (sameString("check", command))
		    doCheck(line, &pmIn.ipAddress);
		else if (sameString("resurrect", command))
		    doResurrect(line, &pmIn.ipAddress);
		else if (sameString("listJobs", command))
		    listJobs();
		else if (sameString("fetch", command))
		    doFetch(line);
                else
                    logWarn("invalid command: \"%s\"", command);
		}
	    logDebug("done command");
	    }
	else
	    {
	    logWarn("command from unauthorized host %s",
                    paraFormatIp(ntohl(pmIn.ipAddress.sin_addr.s_addr)));
	    }
	}
    }
rudpClose(&mainRudp);
}
Пример #5
0
void PeriodicHeartbeat::event(EventCode code, const char* msg)
{

    // Unused in release mode.
    (void)msg;

	if(code == EVENT_SUCCESS)
	{
		SequenceNumber_t firstSeq, lastSeq;
		Count_t heartbeatCount = 0;
		LocatorList_t locList;
		bool unacked_changes = false;
		{//BEGIN PROTECTION
			boost::lock_guard<boost::recursive_mutex> guardW(*mp_SFW->getMutex());
			for(std::vector<ReaderProxy*>::iterator it = mp_SFW->matchedReadersBegin();
					it != mp_SFW->matchedReadersEnd(); ++it)
			{
				if(!unacked_changes)
				{
                    if((*it)->thereIsUnacknowledged())
					{
						unacked_changes= true;
					}
				}
				locList.push_back((*it)->m_att.endpoint.unicastLocatorList);
				locList.push_back((*it)->m_att.endpoint.multicastLocatorList);
			}

			if (unacked_changes)
			{
				firstSeq = mp_SFW->get_seq_num_min();
				lastSeq = mp_SFW->get_seq_num_max();

				if (firstSeq == c_SequenceNumber_Unknown || lastSeq == c_SequenceNumber_Unknown)
				{
					firstSeq = mp_SFW->next_sequence_number();
					lastSeq = SequenceNumber_t(0, 0);
				}
				else
				{
					(void)firstSeq;
					assert(firstSeq <= lastSeq);
				}

				mp_SFW->incrementHBCount();
				heartbeatCount = mp_SFW->getHeartbeatCount();
			}
		}

		if (unacked_changes)
		{
			CDRMessage::initCDRMsg(&m_periodic_hb_msg);
			// FinalFlag is always false because this class is used only by StatefulWriter in Reliable.
			RTPSMessageCreator::addMessageHeartbeat(&m_periodic_hb_msg, mp_SFW->getGuid().guidPrefix,
				mp_SFW->getHBReaderEntityId(), mp_SFW->getGuid().entityId,
				firstSeq, lastSeq, heartbeatCount, false, false);
			logInfo(RTPS_WRITER,mp_SFW->getGuid().entityId << " Sending Heartbeat ("<<firstSeq<< " - " << lastSeq<<")" );
			for (std::vector<Locator_t>::iterator lit = locList.begin(); lit != locList.end(); ++lit)
				mp_SFW->getRTPSParticipant()->sendSync(&m_periodic_hb_msg,(Endpoint *)mp_SFW , (*lit));
		
			//Reset TIMER
			this->restart_timer();
		}

	}
	else if(code == EVENT_ABORT)
	{
		logInfo(RTPS_WRITER,"Aborted");
	}
	else
	{
		logInfo(RTPS_WRITER,"Boost message: " <<msg);
	}
}
/** notification handler for changed session state
 *
 * @param sessionName
 * @param seatID
 * @param sessionState
 * @return none
 */
void CAmNodeStateCommunicatorCAPI::onSessionStateChangedEvent(const std::string & sessionName, const int32_t seatID, const int32_t sessionState)
{
    logInfo(__PRETTY_FUNCTION__, " got signal sessionStateChanged, with session",sessionName,"seatID=",seatID,"sessionState",sessionState);
    assert(mpControlSender);
    mpControlSender->hookSystemSessionStateChanged(sessionName, static_cast<NsmSeat_e>(seatID), static_cast<NsmSessionState_e>(sessionState));
}
Пример #7
0
// based on the trial we're currently writing to disk,
void updateSignalFileInfo(SignalFileInfo* pSignalFile, DataLoggerStatus* pStatus, unsigned trialIdx)
{
    DataLoggerStatusByTrial* trialStatus = pStatus->byTrial + trialIdx;

    unsigned msec;
    struct tm timeInfo;

    convertWallclockToLocalTime(trialStatus->wallclockStart, &timeInfo, &msec);

	// append the date as a folder onto dataRoot
    char dateFolderBuffer[MAX_FILENAME_LENGTH];
    strftime(dateFolderBuffer, MAX_FILENAME_LENGTH, "%Y-%m-%d", &timeInfo);

    // build pathBufferIndex as   dataRoot/storeName/subject/YYYYMMDD/
    // build pathBufferSaveTag as dataRoot/storeName/subject/YYYYMMDD/protocol/saveTag#/
    char pathBufferIndex[MAX_FILENAME_LENGTH];
    char pathBufferTrial[MAX_FILENAME_LENGTH];
    snprintf(pathBufferIndex, MAX_FILENAME_LENGTH,
            "%s/%s/%s/%s", dataRoot, pStatus->dataStore, pStatus->subject, dateFolderBuffer);
    snprintf(pathBufferTrial, MAX_FILENAME_LENGTH,
            "%s/%s/saveTag%03d", pathBufferIndex, pStatus->protocol, pStatus->saveTag);

    // check that this data directory exists if it's changed from last time
    if(strncmp(pathBufferTrial, pSignalFile->filePath, MAX_FILENAME_LENGTH) != 0)
    {
        // path has changed, need to check that this path exists, and/or create it
        if (access( pathBufferTrial, R_OK | W_OK ) == -1)
        {
            // this new path doesn't exist or we can't access it --> mkdir it
            int failed = mkdirRecursive(pathBufferTrial);
            if(failed)
                diep("Error creating trial data directory");
        }

        // update the filePath so we don't try to create it again
        strncpy(pSignalFile->filePath, pathBufferTrial, MAX_FILENAME_LENGTH);
        logInfo("Updating trial data dir : %s\n", pSignalFile->filePath);
    }

    // now check the index file to make sure it exists
    // the index file is simply a list of .mat files written to this directory
    // which makes it is easy for other programs to detect when these files
    // are added, rather than having to stat the whole directory repeatedly
    char indexFileBuffer[MAX_FILENAME_LENGTH];
    snprintf(indexFileBuffer, MAX_FILENAME_LENGTH,
            "%s/trialIndex.txt", pathBufferIndex);

    char saveTagIndexFileBuffer[MAX_FILENAME_LENGTH];
    snprintf(saveTagIndexFileBuffer, MAX_FILENAME_LENGTH,
            "%s/trialIndex.txt", pathBufferTrial);

    // check whether the index file is the same as last time
    if(strncmp(indexFileBuffer, pSignalFile->indexFileName, MAX_FILENAME_LENGTH) != 0)
    {
        // it's changed from last time
        strncpy(pSignalFile->indexFileName, indexFileBuffer, MAX_FILENAME_LENGTH);
        logInfo("Updating trial index file : %s\n", pSignalFile->indexFileName);

        pSignalFile->indexFile = fopen(pSignalFile->indexFileName, "a");

        if(pSignalFile->indexFile == NULL)
        {
            diep("Error opening index file.");
        }
    }

    // check whether the save tag index file is the same as last time
    if(strncmp(saveTagIndexFileBuffer, pSignalFile->saveTagIndexFileName, MAX_FILENAME_LENGTH) != 0)
    {
        // it's changed from last time
        strncpy(pSignalFile->saveTagIndexFileName, saveTagIndexFileBuffer, MAX_FILENAME_LENGTH);
        logInfo("Updating save-tag index file : %s\n", pSignalFile->saveTagIndexFileName);

        pSignalFile->saveTagIndexFile = fopen(pSignalFile->saveTagIndexFileName, "a");

        if(pSignalFile->saveTagIndexFile == NULL)
            diep("Error opening index file.");
    }
    // create a unique mat file name based on <subject>_protocol_<date.time.msec>_id<trialId>.mat
    char fileTimeBuffer[MAX_FILENAME_LENGTH];
    strftime(fileTimeBuffer, MAX_FILENAME_LENGTH, "%Y%m%d.%H%M%S", &timeInfo);

    // assemble short file name without path
    snprintf(pSignalFile->fileNameShort, MAX_FILENAME_LENGTH,
            "%s_%s_id%06d_time%s.%03d.mat", pStatus->subject, pStatus->protocol,
            trialStatus->trialId, fileTimeBuffer, msec);

    // path relative to index file, e.g. protocol/saveTag#/fileName.mat
    snprintf(pSignalFile->fileNameRelativeToIndex, MAX_FILENAME_LENGTH,
            "%s/saveTag%03d/%s", pStatus->protocol, pStatus->saveTag, pSignalFile->fileNameShort);

    // assemble file name with path
    snprintf(pSignalFile->fileName, MAX_FILENAME_LENGTH,
            "%s/%s", pSignalFile->filePath, pSignalFile->fileNameShort);
}
Пример #8
0
int workerPoolSend(struct context *ctx, 
					uint32_t from,
					uint32_t to,
					uint32_t session,
					uint32_t type,
					void *data,
					size_t sz,
					uint32_t ud) {

	char from_name[32];
	snprintf(from_name, 32, "c_%d", from);
	if (from == 0) {
		if (ctx) {
			from = ctx->id;
			snprintf(from_name, 32, "%s", ctx->name);
		}
	}

	if (to == 0) {
		return -1;
	}

	struct context *toctx = ctxMgrGetContext(to);
	if (toctx == NULL) {
		fprintf(stderr, "send to service(%d) type(%d),not found service!\n", to, type);
		if (data) {
			zfree(data);
		}
		return -1;
	}

	struct message msg;
	msg.from = from;

	if (type & MSG_TYPE_NEWSESSION) {
		msg.session = contextNewsession(ctx);
	} else {
		msg.session = session;
	}

	msg.type = type;
	msg.ud = ud;
	msg.sz = sz;
	msg.data = data;
	
	if (!messageQueuePush(toctx->queue, &msg)) {
		fprintf(stderr, "context(%d) queue full, size(%d)!\n", 
							toctx->id,
							messageQueueSize(toctx->queue));

		assert(0);
		ctxMgrReleaseContext(toctx);
		return -1;
	}
	
	logInfo("from(%s) to(%s) type(%X)", from_name, toctx->name);
	if (CAS(&toctx->inGlobal, 0, 1)) {
		contextQueuePush(M->queue, toctx);	
		threadWakeUp();
	} else {
		ctxMgrReleaseContext(toctx);
	}
	return msg.session;
}
void peano::applications::navierstokes::prototype2::repositories::PrototypeRepositoryForSpacetreeGridArrayStackImplementation::logIterationStatistics() const {
  logInfo( "logIterationStatistics()", "|| adapter name \t || iterations \t || total CPU time [t]=s \t || average CPU time [t]=s \t || total user time [t]=s \t || average user time [t]=s " );  

}
Пример #10
0
void RenderThread::run()
{
	logInfo("RenderThread::run : starting thread");
	while (running)
	{
		running_mutex.lock();
		RenderRequest* job;
		if (preview_request != 0)
		{
			job = preview_request;
			preview_request = 0;
		}
		else if (image_request != 0)
		{
			job = image_request;
			image_request = 0;
		}
		else
		{
			rqueue_mutex.lock();
			if (request_queue.isEmpty())
			{
				// sleep only after checking for requests
				current_request = 0;
				rqueue_mutex.unlock();
				running_mutex.unlock();
				usleep(10000);
				continue;
			}
			else
			{
				job = request_queue.dequeue();
				logFine("RenderThread::run : dequeueing request %#x", (long)job);
				rqueue_mutex.unlock();
			}
		}
		render_loop_flag = true;
		current_request = job;

		// make sure there is something to calculate
		bool no_pos_xf = true;
		for (flam3_xform* xf = job->genome()->xform ;
			 xf < job->genome()->xform + job->genome()->num_xforms ; xf++)
			if (xf->density > 0.0)
			{
				no_pos_xf = false;
				break;
			}
		if (no_pos_xf)
		{
			logWarn(QString("RenderThread::run : no xform in request 0x%1").arg((long)job,0,16));
			running_mutex.unlock();
			continue;
		}

		logFiner(QString("RenderThread::run : rendering request 0x%1").arg((long)job,0,16));
		rtype = job->name();
		flame.time = job->time();
		flame.ngenomes = job->numGenomes();
		flam3_genome* genomes = new flam3_genome[flame.ngenomes]();
		flam3_genome* job_genome = job->genome();
		for (int n = 0 ; n < flame.ngenomes ; n++)
			flam3_copy(genomes + n, job_genome + n);
		flame.genomes = genomes;
		QSize imgSize(job->size());
		if (!imgSize.isEmpty())
		{
			for (int n = 0 ; n < flame.ngenomes ; n++)
			{
				flam3_genome* genome = genomes + n;
				// scale images, previews, etc. if necessary
				int width  = genome->width;
				genome->width  = imgSize.width();
				genome->height = imgSize.height();

				// "rescale" the image scale to maintain the camera
				// for smaller/larger image size
				genome->pixels_per_unit /= ((double)width) / genome->width;
			}
		}

		// Load image quality settings for Image, Preview, and File types
		switch (job->type())
		{
			case RenderRequest::File:
				rtype = QFileInfo(job->name()).fileName();

			case RenderRequest::Image:
			case RenderRequest::Preview:
			case RenderRequest::Queued:
			{
				const flam3_genome* g = job->imagePresets();
				if (g->nbatches > 0) // valid quality settings for nbatches > 0
					for (int n = 0 ; n < flame.ngenomes ; n++)
					{
						flam3_genome* genome = genomes + n;
						genome->sample_density =            g->sample_density;
						genome->spatial_filter_radius =     g->spatial_filter_radius;
						genome->spatial_oversample =        g->spatial_oversample;
						genome->nbatches =                  g->nbatches;
						genome->ntemporal_samples =         g->ntemporal_samples;
						genome->estimator =                 g->estimator;
						genome->estimator_curve =           g->estimator_curve;
						genome->estimator_minimum =         g->estimator_minimum;
					}
			}

			default:
				;
		}

		// add symmetry xforms before rendering
		for (int n = 0 ; n < flame.ngenomes ; n++)
		{
			flam3_genome* genome = genomes + n;
			if (genome->symmetry != 1)
				flam3_add_symmetry(genome, genome->symmetry);
		}

		int msize = channels * genomes->width * genomes->height;
		unsigned char* out = new unsigned char[msize];
		unsigned char* head = out;
		logFine("RenderThread::run : allocated %d bytes, rendering...", msize);
		init_status_cb();
		rendering = true;
		ptimer.start();
		int rv = flam3_render(&flame, out, 0, channels, alpha_trans, &_stats);
		millis = ptimer.elapsed();
		rendering = false;
		render_loop_flag = false;

		if (_stop_current_job) // if stopRendering() is called
		{
			logFine(QString("RenderThread::run : %1 rendering stopped").arg(rtype));
			delete[] head;
			for (int n = 0 ; n < flame.ngenomes ; n++)
				clear_cp(genomes + n, flam3_defaults_off);
			delete[] genomes;
			if (kill_all_jobs)
			{
				preview_request = 0;
				image_request = 0;
				rqueue_mutex.lock();
				request_queue.clear();
				rqueue_mutex.unlock();
				kill_all_jobs = false;
				emit flameRenderingKilled();
			}
			else
				if (job->type() == RenderRequest::Queued)
				{
					logFine("RenderThread::run : re-adding queued request");
					rqueue_mutex.lock();
					request_queue.prepend(job);
					rqueue_mutex.unlock();
				}

			_stop_current_job = false;
			running_mutex.unlock();
			continue;
		}

		QSize buf_size(genomes->width, genomes->height);
		if (img_format == RGB32)
		{
			if (buf_size != img_buf.size())
				img_buf = QImage(buf_size, QImage::Format_RGB32);
			if (rv == 0)
			{
				for (int h = 0 ; h < genomes->height ; h++)
					for (int w = 0 ; w < genomes->width ; w++, out += channels)
						img_buf.setPixel(QPoint(w, h), qRgb(out[0], out[1], out[2]));
			}
			else
				img_buf.fill(0);
		}
		else
		{
			if (buf_size != img_buf.size())
				img_buf = QImage(buf_size, QImage::Format_ARGB32);
			if (rv == 0)
			{
				for (int h = 0 ; h < genomes->height ; h++)
					for (int w = 0 ; w < genomes->width ; w++, out += channels)
						img_buf.setPixel(QPoint(w, h), qRgba(out[0], out[1], out[2], out[3]));
			}
			else
				img_buf.fill(0);
		}
		delete[] head;
		for (int n = 0 ; n < flame.ngenomes ; n++)
			clear_cp(genomes + n, flam3_defaults_off);
		delete[] genomes;

		if (job->type() == RenderRequest::File)
			img_buf.save(job->name(), "png", 100);

		job->setImage(img_buf);
		job->setFinished(true);

		// look for a free event
		RenderEvent* event = 0;
		foreach (RenderEvent* e, event_list)
			if (e->accepted())
			{
				e->accept(false);
				event = e;
				break;
			}

		if (!event)
		{
			logFinest(QString("RenderThread::run : adding event"));
			event = new RenderEvent();
			event->accept(false);
			event_list.append(event);
		}
		logFiner(QString("RenderThread::run : event list size %1")
				.arg(event_list.size()));

		event->setRequest(job);
		emit flameRendered(event);
		logFiner(QString("RenderThread::run : finished"));
		running_mutex.unlock();
	}

	logInfo("RenderThread::run : thread exiting");
}
Пример #11
0
void WriterConfig::confDump(const IsoMediaFile::Configuration& configValues, const Json::Value& jsonValues) const
{
    logInfo() << "config.general.output_file: " << configValues.general.output_file << std::endl;
    logInfo() << "config.general.brands.major: " << configValues.general.brands.major << std::endl;
    logInfo() << "config.general.brands.other: ";
    for (unsigned int i = 0; i < configValues.general.brands.other.size(); ++i)
    {
        logInfo() << configValues.general.brands.other[i] << ", ";
    }
    logInfo() << std::endl;

    for (unsigned int i = 0; i < configValues.content.size(); ++i)
    {
        logInfo() << "config.content[" << i << "].master.uniq_bsid: " << configValues.content[i].master.uniq_bsid << std::endl;
        logInfo() << "config.content[" << i << "].master.file_path: " << configValues.content[i].master.file_path << std::endl;
        logInfo() << "config.content[" << i << "].master.code_type: " << configValues.content[i].master.code_type << std::endl;
        logInfo() << "config.content[" << i << "].master.encp_type: " << configValues.content[i].master.encp_type << std::endl;
        logInfo() << "config.content[" << i << "].master.disp_xdim: " << configValues.content[i].master.disp_xdim << std::endl;
        logInfo() << "config.content[" << i << "].master.disp_ydim: " << configValues.content[i].master.disp_ydim << std::endl;
        logInfo() << "config.content[" << i << "].master.disp_rate: " << configValues.content[i].master.disp_rate << std::endl;
        logInfo() << "config.content[" << i << "].master.tick_rate: " << configValues.content[i].master.tick_rate << std::endl;

        if (jsonValues["content"][i]["master"]["edit_file"].asString() != "")
        {
            logInfo() << "config.content[" << i << "].master.edit_list.loop_flag: " << configValues.content[i].master.edit_list.numb_rept << std::endl;
            for (unsigned int j = 0; j < configValues.content[i].master.edit_list.edit_unit.size(); j++)
            {
                logInfo() << "config.content[" << i << "].master.edit_list.edit_unit[" << j << "].edit_type: " << configValues.content[i].master.edit_list.edit_unit[j].edit_type << std::endl;
                logInfo() << "config.content[" << i << "].master.edit_list.edit_unit[" << j << "].mdia_time: " << configValues.content[i].master.edit_list.edit_unit[j].mdia_time << std::endl;
                logInfo() << "config.content[" << i << "].master.edit_list.edit_unit[" << j << "].time_span: " << configValues.content[i].master.edit_list.edit_unit[j].time_span << std::endl;
            }
        }

        for (unsigned int j = 0; j < configValues.content[i].thumbs.size(); ++j)
        {
            logInfo() << "config.content[" << i << "].thumbs[" << j << "].uniq_bsid: " << configValues.content[i].thumbs[j].uniq_bsid << std::endl;
            logInfo() << "config.content[" << i << "].thumbs[" << j << "].file_path: " << configValues.content[i].thumbs[j].file_path << std::endl;
            logInfo() << "config.content[" << i << "].thumbs[" << j << "].code_type: " << configValues.content[i].thumbs[j].code_type << std::endl;
            logInfo() << "config.content[" << i << "].thumbs[" << j << "].disp_xdim: " << configValues.content[i].thumbs[j].disp_xdim << std::endl;
            logInfo() << "config.content[" << i << "].thumbs[" << j << "].disp_ydim: " << configValues.content[i].thumbs[j].disp_ydim << std::endl;
            logInfo() << "config.content[" << i << "].thumbs[" << j << "].tick_rate: " << configValues.content[i].thumbs[j].tick_rate << std::endl;
            logInfo() << "config.content[" << i << "].thumbs[" << j << "].sync_rate: " << configValues.content[i].thumbs[j].sync_rate << std::endl;

            if (jsonValues["content"][i]["thumbs"][j]["edit_file"].asString() != "")
            {
                logInfo() << "config.content[" << i << "].thumbs[" << j << "].edit_list.loop_flag: " << configValues.content[i].master.edit_list.numb_rept << std::endl;
                for (unsigned int k = 0; k < configValues.content[i].thumbs[j].edit_list.edit_unit.size(); k++)
                {
                    logInfo() << "config.content[" << i << "].thumbs[" << j << "].edit_list.edit_unit[" << k << "].edit_type: " << configValues.content[i].master.edit_list.edit_unit[j].edit_type
                        << std::endl;
                    logInfo() << "config.content[" << i << "].thumbs[" << j << "].edit_list.edit_unit[" << k << "].mdia_time: " << configValues.content[i].master.edit_list.edit_unit[j].mdia_time
                        << std::endl;
                    logInfo() << "config.content[" << i << "].thumbs[" << j << "].edit_list.edit_unit[" << k << "].time_span: " << configValues.content[i].master.edit_list.edit_unit[j].time_span
                        << std::endl;
                }
            }

            for (unsigned int k = 0; k < configValues.content[i].thumbs[j].sync_idxs.size(); ++k)
            {
                logInfo() << "config.content[" << i << "].thumbs[" << j << "].sync_idxs[" << k << "]: " << configValues.content[i].thumbs[j].sync_idxs[k] << std::endl;
            }
        }
    }

    for (unsigned int i = 0; i < configValues.egroups.altr.idxs_lists.size(); ++i)
    {
        for (unsigned int j = 0; j < configValues.egroups.altr.idxs_lists.at(i).size(); ++j)
        {
            logInfo() << "config.egroups.altr.idxs_lists[" << i << "][" << j << "].uniq_bsid:" << configValues.egroups.altr.idxs_lists.at(i).at(j).uniq_bsid << std::endl;
            logInfo() << "config.egroups.altr.idxs_lists[" << i << "][" << j << "].item_id:" << configValues.egroups.altr.idxs_lists.at(i).at(j).item_indx << std::endl;
        }
    }
}
Пример #12
0
TVSERVICE_CALLBACK_T tvserviceCallback(void *callback_data, uint32_t reason, uint32_t param1, uint32_t param2)
{
	const char *reasonStr = vc_tv_notification_name((VC_HDMI_NOTIFY_T)reason);
	logInfo(LOG_TVSERVICE, "%s, param1=0x%x, param2=0x%x\n", reasonStr, param1, param2);
}
      void
      MarDynBoundaryConfiguration::parseSubtag(
          tarch::irr::io::IrrXMLReader *xmlReader)
      {
        _isValid = true;

        //STREAMDIR
        if (xmlReader->getAttributeValue(STREAMDIR.c_str()) == 0)
          {
            _log.info("parseSubtag()", "'streamdir' not defined!");

            _streamdir = 3;
          }
        else
          {
            _streamdir = xmlReader->getAttributeValueAsInt(STREAMDIR.c_str());
            assertion(_streamdir >= 0);
            logDebug("parseSubtag()", "'streamdir': " << (_streamdir));
          }

        //STREAM_F_DAMPING
        if (xmlReader->getAttributeValue(STREAM_F_DAMPING.c_str()) == 0)
          {
            _log.info("parseSubtag()", "'stream-f-reduction' not defined!");
            _fStreamDamping = 1.0;

          }
        else
          {
            _fStreamDamping = xmlReader->getAttributeValueAsDouble(
                STREAM_F_DAMPING.c_str());
            assertion(_fStreamDamping > 0);
            logDebug("parseSubtag()", "'stream-f-reduction': "
                << (_fStreamDamping));
          }

        //BENABLED
        if (xmlReader->getAttributeValue(BENABLED.c_str()) == 0)
          {
            _log.info("parseSubtag()", "'benabled' not defined!");
            _bEnabled = true;
          }
        else
          {
            _bEnabled = xmlReader->getAttributeValueAsBool(BENABLED.c_str());

            logDebug("parseSubtag()", "'benabled': " << (_bEnabled));
          }

        //STREAMOUT
        if (xmlReader->getAttributeValue(STREAMOUT.c_str()) == 0)
          {
            _log.info("parseSubtag()", "'streamout' not defined!");
            _streamout = true;
          }
        else
          {
            _streamout = xmlReader->getAttributeValueAsBool(STREAMOUT.c_str());

            logDebug("parseSubtag()", "'streamout': " << (_streamout));
          }

        while (xmlReader->read())
          {
            if (xmlReader->getNodeType() == tarch::irr::io::EXN_ELEMENT)
              {
                if (xmlReader->getNodeName()
                    == MarDynMovingWallConfiguration::TAG)
                  {
                    logInfo("parseSubtag()", "Parse "
                        << MarDynMovingWallConfiguration::TAG);
                    _movingWallConfig.parseSubtag(xmlReader);
                  }
                else
                  {
                    logError("parseSubtag()", "Unknown Subtag "
                        << xmlReader->getNodeName() << " in config");
                    assertion(false);
                  }
              }
            else if (xmlReader->getNodeType()
                == tarch::irr::io::EXN_ELEMENT_END)
              {
                // end was found
                if (getTag() == xmlReader->getNodeName())
                  {
                    return;
                  }
              }
          }
      }
int SDLHardwareRenderDevice::createContext(bool allow_fallback) {
	bool settings_changed = (fullscreen != FULLSCREEN || hwsurface != HWSURFACE || vsync != VSYNC || texture_filter != TEXTURE_FILTER);

	Uint32 w_flags = 0;
	Uint32 r_flags = 0;
	int window_w = SCREEN_W;
	int window_h = SCREEN_H;

	if (FULLSCREEN) {
		w_flags = w_flags | SDL_WINDOW_FULLSCREEN_DESKTOP;

		// make the window the same size as the desktop resolution
		SDL_DisplayMode desktop;
		if (SDL_GetDesktopDisplayMode(0, &desktop) == 0) {
			window_w = desktop.w;
			window_h = desktop.h;
		}
	}
	else if (fullscreen && is_initialized) {
		// if the game was previously in fullscreen, resize the window when returning to windowed mode
		window_w = MIN_SCREEN_W;
		window_h = MIN_SCREEN_H;
		w_flags = w_flags | SDL_WINDOW_SHOWN;
	}
	else {
		w_flags = w_flags | SDL_WINDOW_SHOWN;
	}

	w_flags = w_flags | SDL_WINDOW_RESIZABLE;

	if (HWSURFACE) {
		r_flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE;
	}
	else {
		r_flags = SDL_RENDERER_SOFTWARE | SDL_RENDERER_TARGETTEXTURE;
		VSYNC = false; // can't have software mode & vsync at the same time
	}
	if (VSYNC) r_flags = r_flags | SDL_RENDERER_PRESENTVSYNC;

	if (settings_changed || !is_initialized) {
		destroyContext();

		window = SDL_CreateWindow(NULL, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, window_w, window_h, w_flags);
		if (window) {
			renderer = SDL_CreateRenderer(window, -1, r_flags);
			if (renderer) {
				if (TEXTURE_FILTER && !IGNORE_TEXTURE_FILTER)
					SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
				else
					SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");

				windowResize();
			}

			SDL_SetWindowMinimumSize(window, MIN_SCREEN_W, MIN_SCREEN_H);
			// setting minimum size might move the window, so set position again
			SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
		}

		bool window_created = window != NULL && renderer != NULL;

		if (!window_created) {
			if (allow_fallback) {
				// try previous setting first
				FULLSCREEN = fullscreen;
				HWSURFACE = hwsurface;
				VSYNC = vsync;
				TEXTURE_FILTER = texture_filter;
				if (createContext(false) == -1) {
					// last resort, try turning everything off
					FULLSCREEN = false;
					HWSURFACE = false;
					VSYNC = false;
					TEXTURE_FILTER = false;
					int last_resort = createContext(false);
					if (last_resort == -1 && !is_initialized) {
						// If this is the first attempt and it failed we are not
						// getting anywhere.
						logError("SDLHardwareRenderDevice: createContext() failed: %s", SDL_GetError());
						logErrorDialog("SDLHardwareRenderDevice: createContext() failed: %s", SDL_GetError());
						Exit(1);
					}
					return last_resort;
				}
				else {
					return 0;
				}
			}
		}
		else {
			if (!is_initialized) {
				// save the system gamma levels if we just created the window
				SDL_GetWindowGammaRamp(window, gamma_r, gamma_g, gamma_b);
				logInfo("RenderDevice: Window size is %dx%d", SCREEN_W, SCREEN_H);
			}

			fullscreen = FULLSCREEN;
			hwsurface = HWSURFACE;
			vsync = VSYNC;
			texture_filter = TEXTURE_FILTER;
			is_initialized = true;

			logInfo("RenderDevice: Fullscreen=%d, Hardward surfaces=%d, Vsync=%d, Texture Filter=%d", fullscreen, hwsurface, vsync, texture_filter);
		}
	}

	if (is_initialized) {
		// update minimum window size if it has changed
		if (min_screen.x != MIN_SCREEN_W || min_screen.y != MIN_SCREEN_H) {
			min_screen.x = MIN_SCREEN_W;
			min_screen.y = MIN_SCREEN_H;
			SDL_SetWindowMinimumSize(window, MIN_SCREEN_W, MIN_SCREEN_H);
			SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
		}

		windowResize();

		// update title bar text and icon
		updateTitleBar();

		// load persistent resources
		delete icons;
		icons = new IconManager();
		delete curs;
		curs = new CursorManager();

		if (CHANGE_GAMMA)
			setGamma(GAMMA);
		else {
			resetGamma();
			CHANGE_GAMMA = false;
			GAMMA = 1.0;
		}
	}

	return (is_initialized ? 0 : -1);
}
Пример #15
0
	int TcpClient::receiveThread_(void*)
	{
		mem::Array<uint8_t> tmpReceivedData;

		while (true)
		{
			// 停止チェック
			if (mIsConnectionClosed)
			{
				break;
			}

			// データ受信
			auto receivedSize = 0;
			{
				UniqueLock lock(mSocketLock);
				receivedSize = socketUtil::receive(&tmpReceivedData, mpSocket);

				if (receivedSize > 0)
				{
					if (socketUtil::isKeepAlive(tmpReceivedData))
					{
						socketUtil::replyKeepAlive(mpSocket);
						logInfo("reply keep-alive");
						receivedSize = 0;
					}
					else
					{
						// 受信通知を送信
						if (!socketUtil::sendReceivedConfirmation(mpSocket))
						{
							logError("sending receive-confirmation failed");
							receivedSize = -1;
						}
					}
				}
			}

			if (receivedSize > 0)
			{
				// 受信データをキューに詰める
				TcpReceivedData result;
				result.buffer = tmpReceivedData.get();
				result.bufferSize = tmpReceivedData.size();

				mReceivedList.emplaceBack(std::move(result));
			}
			else if (receivedSize == 0)
			{
				// 何もしない
			}
			else
			{
				// エラー
				logError("receiving from server failed");
				close();
				break;
			}

			Sleep(cThreadPollingInterval);
		}

		return 0;
	}
Пример #16
0
	// inicializuj assimp a jeho premenne
	CAssimp::CAssimp()
	{
		createAILogger();
		logInfo("App started!");
	}
/** notification handler for changed node application mode
 *
 * @param nodeApplicationMode
 * @return none
 */
void CAmNodeStateCommunicatorCAPI::onNodeApplicationModeEvent(const int32_t nodeApplicationMode)
{
	logInfo(__PRETTY_FUNCTION__, " got signal nodeApplicationMode, with applicationMode",nodeApplicationMode);
    assert(mpControlSender);
    mpControlSender->hookSystemNodeApplicationModeChanged(static_cast<NsmApplicationMode_e>(nodeApplicationMode));
}
Пример #18
0
	// Shutdown
	CAssimp::~CAssimp()
	{
		logInfo("App ended!");
		destroyAILogger();
	}
void peano::applications::pic::demo::repositories::PICBatchJobRepositoryForSpacetreeGridSTDDoubleStackImplementation::logIterationStatistics() const {
  logInfo( "logIterationStatistics()", "|| adapter name \t || iterations \t || total CPU time [t]=s \t || average CPU time [t]=s \t || total user time [t]=s \t || average user time [t]=s " );  
   logInfo( "logIterationStatistics()", "| SetupExperiment \t |  " << _countSetupExperimentRuns << " \t |  " << _measureSetupExperimentCPUTime << " \t |  " << (_countSetupExperimentRuns==0 ? 0 : _measureSetupExperimentCPUTime / static_cast<double>(_countSetupExperimentRuns))  << " \t |  " << _measureSetupExperimentCalendarTime << " \t |  " << (_countSetupExperimentRuns==0 ? 0 : _measureSetupExperimentCalendarTime / static_cast<double>(_countSetupExperimentRuns))  );  
   logInfo( "logIterationStatistics()", "| SetupExperimentAndPlot \t |  " << _countSetupExperimentAndPlotRuns << " \t |  " << _measureSetupExperimentAndPlotCPUTime << " \t |  " << (_countSetupExperimentAndPlotRuns==0 ? 0 : _measureSetupExperimentAndPlotCPUTime / static_cast<double>(_countSetupExperimentAndPlotRuns))  << " \t |  " << _measureSetupExperimentAndPlotCalendarTime << " \t |  " << (_countSetupExperimentAndPlotRuns==0 ? 0 : _measureSetupExperimentAndPlotCalendarTime / static_cast<double>(_countSetupExperimentAndPlotRuns))  );  

}
Пример #20
0
RTPSParticipant* RTPSDomain::createParticipant(RTPSParticipantAttributes& PParam,
		RTPSParticipantListener* listen)
{
	const char* const METHOD_NAME = "createParticipant";
	logInfo(RTPS_PARTICIPANT,"");

	if(PParam.builtin.leaseDuration < c_TimeInfinite && PParam.builtin.leaseDuration <= PParam.builtin.leaseDuration_announcementperiod) //TODO CHeckear si puedo ser infinito
	{
		logError(RTPS_PARTICIPANT,"RTPSParticipant Attributes: LeaseDuration should be >= leaseDuration announcement period");
		return nullptr;
	}
	if(PParam.use_IP4_to_send == false && PParam.use_IP6_to_send == false)
	{
		logError(RTPS_PARTICIPANT,"Use IP4 OR User IP6 to send must be set to true");
		return nullptr;
	}
	uint32_t ID;
	if(PParam.participantID < 0)
	{
		ID = getNewId();
		while(m_RTPSParticipantIDs.insert(ID).second == false)
			ID = getNewId();
	}
	else
	{
		ID = PParam.participantID;
		if(m_RTPSParticipantIDs.insert(ID).second == false)
		{
			logError(RTPS_PARTICIPANT,"RTPSParticipant with the same ID already exists");
			return nullptr;
		}
	}
	if(!PParam.defaultUnicastLocatorList.isValid())
	{
		logError(RTPS_PARTICIPANT,"Default Unicast Locator List contains invalid Locator");
		return nullptr;
	}
	if(!PParam.defaultMulticastLocatorList.isValid())
	{
		logError(RTPS_PARTICIPANT,"Default Multicast Locator List contains invalid Locator");
		return nullptr;
	}
	PParam.participantID = ID;
	int pid;
#if defined(_WIN32)
	pid = (int)_getpid();
#else
	pid = (int)getpid();
#endif
	GuidPrefix_t guidP;
	LocatorList_t loc;
	IPFinder::getIP4Address(&loc);
	if(loc.size()>0)
	{
		guidP.value[0] = c_VendorId_eProsima[0];
		guidP.value[1] = c_VendorId_eProsima[1];
		guidP.value[2] = loc.begin()->address[14];
		guidP.value[3] = loc.begin()->address[15];
	}
	else
	{
		guidP.value[0] = c_VendorId_eProsima[0];
		guidP.value[1] = c_VendorId_eProsima[1];
		guidP.value[2] = 127;
		guidP.value[3] = 1;
	}
	guidP.value[4] = ((octet*)&pid)[0];
	guidP.value[5] = ((octet*)&pid)[1];
	guidP.value[6] = ((octet*)&pid)[2];
	guidP.value[7] = ((octet*)&pid)[3];
	guidP.value[8] = ((octet*)&ID)[0];
	guidP.value[9] = ((octet*)&ID)[1];
	guidP.value[10] = ((octet*)&ID)[2];
	guidP.value[11] = ((octet*)&ID)[3];

	RTPSParticipant* p = new RTPSParticipant(nullptr);
	RTPSParticipantImpl* pimpl = new RTPSParticipantImpl(PParam,guidP,p,listen);
	m_maxRTPSParticipantID = pimpl->getRTPSParticipantID();

	m_RTPSParticipants.push_back(t_p_RTPSParticipant(p,pimpl));
	return p;
}
Пример #21
0
int config_parse(const char *config_file)
{
	FILE *fptr;
	char buf[1024];
	struct stat fileInfo;

	if (stat(config_file, &fileInfo) != 0) {
		//File does not exist.  Create it.
		logInfo("Config file %s does not exist, creating new file.\n", config_file);
		_config_create(config_file);
	}

	fptr = fopen(config_file, "rt");
	if (!fptr) {
		logError("Error opening config file \"%s\".\n", config_file);
		return -1;
	}

	conf.verbose = 7;
	conf.log_pipe = 0;
	conf.log_pipe_file = NULL;
	conf.syslog = 0;
	conf.eeprom_file = NULL;
	conf.eeprom_size = 0;
	conf.soft_hmac_key = NULL;
	conf.soft_serial_key = NULL;
	conf.aes_key = NULL;

	while (fgets(buf, 1024, fptr)) {
		if (buf[0] != '#' && buf[0] != 10 && buf[0] != 13) {
			while (buf[strlen(buf)-1] == 10 || buf[strlen(buf)-1] == 13) {
				buf[strlen(buf)-1] = 0;
			}

			if (!strncmp(buf, "verbose=", 8)) {
				char *verbose = NULL;
				if (_config_parse_string(&(buf[8]), "verbose", &verbose)) {
					fclose(fptr);
					return -1;
				} else {
					if (!strncmp(verbose, "err", 3)) {
						conf.verbose = 3;
					} else if (!strncmp(verbose, "warn", 4)) {
						conf.verbose = 4;
					} else if (!strncmp(verbose, "notice", 6)) {
						conf.verbose = 5;
					} else if (!strncmp(verbose, "info", 4)) {
						conf.verbose = 6;
					} else if (!strncmp(verbose, "debug", 5)) {
						conf.verbose = 7;
					} else {
						logError("Invalid value for verbose in configuration.\n");
						fclose(fptr);
						free(verbose);
						return -1;
					}
					free(verbose);
				}
			} else if (!strncmp(buf, "log_file=", 9)) {
				if (_config_parse_int(&(buf[9]), "log_file", &conf.log_file)) {
					fclose(fptr);
					return -1;
				} else {
					if (conf.log_file != 0 && conf.log_file != 1) {
						logError("log_file must be 1 or 0 in configuration.\n");
						fclose(fptr);
						return -1;
					}
				}
			} else if (!strncmp(buf, "log_filepath=", 13)) {
				if (_config_parse_string(&(buf[13]), "log_filepath", &conf.log_filepath)) {
					fclose(fptr);
					return -1;
				}
			} else if (!strncmp(buf, "log_pipe=", 9)) {
				if (_config_parse_int(&(buf[9]), "log_pipe", &conf.log_pipe)) {
					fclose(fptr);
					return -1;
				} else {
					if (conf.log_pipe != 0 && conf.log_pipe != 1) {
						logError("log_pipe must be 1 or 0 in configuration.\n");
						fclose(fptr);
						return -1;
					}
				}
			} else if (!strncmp(buf, "log_pipe_file=", 14)) {
				if (_config_parse_string(&(buf[14]), "log_pipe_file", &conf.log_pipe_file)) {
					fclose(fptr);
					return -1;
				}
			} else if (!strncmp(buf, "syslog=", 7)) {
				if (_config_parse_int(&(buf[7]), "syslog", &conf.syslog)) {
					fclose(fptr);
					return -1;
				} else {
					if (conf.syslog != 0 && conf.syslog != 1) {
						logError("syslog must be 1 or 0 in configuration.\n");
						fclose(fptr);
						return -1;
					}
				}
			} else if (!strncmp(buf, "eeprom_file=", 12)) {
				if (_config_parse_string(&(buf[12]), "eeprom_file", &conf.eeprom_file)) {
					fclose(fptr);
					return -1;
				}
			} else if (!strncmp(buf, "eeprom_size=", 12)) {
				if (_config_parse_int(&(buf[12]), "eeprom_size", &conf.eeprom_size)) {
					fclose(fptr);
					return -1;
				} else {
					if (conf.eeprom_size <= 0) {
						logError("eeprom_size value must be greater than 0 in configuration.\n");
						fclose(fptr);
						return -1;
					}
				}
			} else if (!strncmp(buf, "soft_hmac_key=", 14)) {
				if (_config_parse_string(&(buf[14]), "soft_hmac_key", &conf.soft_hmac_key)) {
					fclose(fptr);
					return -1;
				}
			} else if (!strncmp(buf, "soft_serial_key=", 16)) {
				if (_config_parse_string(&(buf[16]), "soft_serial_key", &conf.soft_serial_key)) {
					fclose(fptr);
					return -1;
				}
			} else if (!strncmp(buf, "aes_key=", 8)) {
				if (_config_parse_string(&(buf[8]), "aes_key", &conf.aes_key)) {
					fclose(fptr);
					return -1;
				}
			} else {
				logWarning("Unknown config option \"%s\".\n", buf);
			}
		}
	}
	fclose(fptr);

	if (!conf.eeprom_file) {
		logError("No eeprom_file found in configuration.\n");
		return -1;
	}

	if (conf.log_file && !conf.log_filepath) {
		logError("log_filepath must be set if you enable log_file in configuration.\n");
		return -1;
	}

	if (conf.log_pipe && !conf.log_pipe_file) {
		logError("log_pipe_file must be set if you enable log_pipe in configuration.\n");
		return -1;
	}

	return 0;
}
void BundleRTS::run(int nPtsCon, int nCamsCon, int maxIter) {
    refineInput(_mapPts);

    numPtsCon = nPtsCon;
    numCamsCon = nCamsCon;

    compressMeasurements();

    const int cnp = 11; //5:intrinsic parameters 6:extrinsic parameters
    const int pnp = 3;
    const int mnp = 2;

    m_globs.cnp = cnp;
    m_globs.pnp = pnp;
    m_globs.mnp = mnp;

    if (m_globs.rot0params) {
        delete[] m_globs.rot0params;
    }
    m_globs.rot0params = new double[FULLQUATSZ * numCams];

    //set initial camera parameters
    for (int i = 0; i < numCams; ++i) {
        mat2quat(Rs + 9 * i, m_globs.rot0params + 4 * i);
    }

    m_globs.intrcalib = 0;
    m_globs.nccalib = 5;

    m_globs.camparams = 0;
    m_globs.ptparams = 0;

    /* call sparse LM routine */
    double opts[SBA_OPTSSZ];
    opts[0] = SBA_INIT_MU * 1E-4;
    opts[1] = SBA_STOP_THRESH;
    opts[2] = SBA_STOP_THRESH;
    opts[3] = 0; //0.05 * numMeas; // uncomment to force termination if the average reprojection error drops below 0.05
    opts[4] = 1E-16; // uncomment to force termination if the relative reduction in the RMS reprojection error drops below 1E-05

    if (m_paramVec)
        delete[] m_paramVec;
    m_paramVec = new double[numCams * cnp + numPts * pnp];

    double * pParamVec = m_paramVec;
    double* pKs = Ks.data;
    double* pTs = Ts.data;
    for (int i = 0; i < numCams; ++i) {
        pParamVec[0] = pKs[0];
        pParamVec[1] = pKs[2];
        pParamVec[2] = pKs[5];
        pParamVec[3] = pKs[4] / pKs[0];
        pParamVec[4] = pKs[1];

        pParamVec[5] = 0;
        pParamVec[6] = 0;
        pParamVec[7] = 0;
        pParamVec[8] = pTs[0];
        pParamVec[9] = pTs[1];
        pParamVec[10] = pTs[2];

        pParamVec += cnp;
        pKs += 9;
        pTs += 3;
    }
    double* pParamPoints = m_paramVec + numCams * cnp;
    memcpy(pParamPoints, Ms.data, numPts * 3 * sizeof(double));

    double sbaInfo[SBA_INFOSZ];
    if (sba_motstr_levmar_x(numPts, numPtsCon, numCams, numCamsCon, vmask,
                            m_paramVec, cnp, pnp, ms.data, 0, mnp, img_projsKRTS_x,
                            img_projsKRTS_jac_x, (void *) (&m_globs), maxIter, 0, opts,
                            sbaInfo) == SBA_ERROR) {
        //for debug
        //save the bundle data for debug


        repErr("bundle adjustment failed!\n");
    }
    //test
    logInfo(
        "initial error:%lf, final error:%lf #iterations:%lf stop reason:%lf\n",
        sqrt(sbaInfo[0] / numMeas), sqrt(sbaInfo[1] / numMeas), sbaInfo[5],
        sbaInfo[6]);
}
Пример #23
0
PeriodicHeartbeat::~PeriodicHeartbeat()
{
	logInfo(RTPS_WRITER,"Destroying PeriodicHB");
    destroy();
}
Пример #24
0
static void listener_clientLine(void *subject, const char *event, void *data, va_list args)
{
	IrcProxyClient *client = subject;
	IrcMessage *message = va_arg(args, IrcMessage *);

	if(!client->authenticated) { // not yet authenticated, wait for password
		if(g_strcmp0(message->command, "PASS") == 0) {
			char *password = NULL;

			if(message->params_count > 0 && message->params != NULL && message->params[0] != 0) { // password seems to be in the first param
				password = message->params[0];
			} else { // password must be in trailing space
				password = message->trailing;
			}

			if(password != NULL) {
				char **parts = g_strsplit(password, ":", 0);
				int count = 0;
				while(parts[count] != NULL) { // count parts
					count++;
				}

				if(count >= 2) { // there are at least two parts
					char *name = parts[0];
					IrcProxy *proxy;

					if((proxy = g_hash_table_lookup(proxies, name)) != NULL) { // it's a valid ID
						if(g_strcmp0(proxy->password, parts[1]) == 0) { // the password also matches
							logNotice("IRC proxy client %d authenticated successfully to IRC proxy '%s'", client->socket->fd, name);
							client->authenticated = true;

							// associate client and proxy
							client->proxy = proxy;
							g_queue_push_head(proxy->clients, client);

							proxyClientIrcSend(client, ":%s 001 %s :You were successfully authenticated and are now connected to the IRC server", proxy->irc->socket->host, proxy->irc->nick);
							proxyClientIrcSend(client, ":%s 251 %s :There are %d clients online on this bouncer", client->proxy->irc->socket->host, proxy->irc->nick, g_queue_get_length(proxy->clients));
							triggerEvent(proxy, "client_authenticated", client);
						} else {
							proxyClientIrcSend(client, ":kalisko.proxy NOTICE AUTH :*** Login incorrect for IRC proxy ID %c%s%c", (char) 2, name, (char) 2);
						}
					} else {
						proxyClientIrcSend(client, ":kalisko.proxy NOTICE AUTH :*** Invalid IRC proxy ID %c%s%c", (char) 2, name, (char) 2);
					}
				}

				g_strfreev(parts);
			}
		}
	} else if(g_strcmp0(message->command, "PING") == 0) { // reply to pings
		if(message->trailing != NULL) {
			proxyClientIrcSend(client, "PONG :%s", message->trailing);
		}
	} else if(g_strcmp0(message->command, "USER") == 0) { // prevent user command from being passed through
		return;
	} else if(g_strcmp0(message->command, "QUIT") == 0) { // client disconnects
		logInfo("IRC proxy client %d sent QUIT message, disconnecting...", client->socket->fd);
		disconnectSocket(client->socket);
	} else {
		if((g_strcmp0(message->command, "PRIVMSG") == 0 || g_strcmp0(message->command, "NOTICE") == 0) && message->params_count > 0) { // potential filtered command
			for(GList *iter = client->proxy->relay_exceptions->head; iter != NULL; iter = iter->next) {
				if(g_strcmp0(iter->data, message->params[0]) == 0) { // target matches, so don't relay!
					return;
				}
			}
		}

		// Relay message to IRC server
		ircSend(client->proxy->irc, "%s", message->raw_message);
	}
}
Пример #25
0
int Map::load(const std::string& fname) {
	FileParser infile;

	clearEvents();
	clearLayers();
	clearQueues();

	music_filename = "";

	collision_layer = -1;
	w = 1;
	h = 1;
	hero_pos_enabled = false;
	hero_pos.x = 0;
	hero_pos.y = 0;

	// @CLASS Map|Description of maps/
	if (!infile.open(fname))
		return 0;

	logInfo("Map: Loading map '%s'", fname.c_str());

	this->filename = fname;

	while (infile.next()) {
		if (infile.new_section) {

			// for sections that are stored in collections, add a new object here
			if (infile.section == "enemy")
				enemy_groups.push(Map_Group());
			else if (infile.section == "npc")
				npcs.push(Map_NPC());
			else if (infile.section == "event")
				events.push_back(Event());

		}
		if (infile.section == "header")
			loadHeader(infile);
		else if (infile.section == "layer")
			loadLayer(infile);
		else if (infile.section == "enemy")
			loadEnemyGroup(infile, &enemy_groups.back());
		else if (infile.section == "npc")
			loadNPC(infile);
		else if (infile.section == "event")
			EventManager::loadEvent(infile, &events.back());
	}

	infile.close();

	// create StatBlocks for events that need powers
	for (unsigned i=0; i<events.size(); ++i) {
		Event_Component *ec_power = events[i].getComponent(EC_POWER);
		if (ec_power) {
			// store the index of this StatBlock so that we can find it when the event is activated
			ec_power->y = addEventStatBlock(events[i]);
		}
	}

	// ensure that our map contains a collision layer
	if (std::find(layernames.begin(), layernames.end(), "collision") == layernames.end()) {
		layernames.push_back("collision");
		layers.resize(layers.size()+1);
		layers.back().resize(w);
		for (size_t i=0; i<layers.back().size(); ++i) {
			layers.back()[i].resize(h, 0);
		}
		collision_layer = static_cast<int>(layers.size())-1;
	}

	if (!hero_pos_enabled) {
		logError("Map: Hero spawn position (hero_pos) not defined in map header. Defaulting to (0,0).");
	}

	return 0;
}
Пример #26
0
int
startClient( volatile int *pid )
{
	const char *home, *sessargs, *desksess;
	char **env, *xma;
	char **argv, *fname, *str;
#ifdef USE_PAM
	char ** volatile pam_env;
# ifndef HAVE_PAM_GETENVLIST
	char **saved_env;
# endif
	int pretc;
#else
# ifdef _AIX
	char *msg;
	char **theenv;
	extern char **newenv; /* from libs.a, this is set up by setpenv */
# endif
#endif
#ifdef HAVE_SETUSERCONTEXT
	extern char **environ;
#endif
	char *failsafeArgv[2];
	char *buf, *buf2;
	int i;

	if (strCmp( dmrcuser, curuser )) {
		if (curdmrc) { free( curdmrc ); curdmrc = 0; }
		if (dmrcuser) { free( dmrcuser ); dmrcuser = 0; }
	}

#if defined(USE_PAM) || defined(_AIX)
	if (!(p = getpwnam( curuser ))) {
		logError( "getpwnam(%s) failed.\n", curuser );
	  pError:
		displayStr( V_MSG_ERR, 0 );
		return 0;
	}
#endif

#ifndef USE_PAM
# ifdef _AIX
	msg = NULL;
	loginsuccess( curuser, hostname, tty, &msg );
	if (msg) {
		debug( "loginsuccess() - %s\n", msg );
		free( (void *)msg );
	}
# else /* _AIX */
#  if defined(KERBEROS) && defined(AFS)
	if (krbtkfile[0] != '\0') {
		if (k_hasafs()) {
			int fail = 0;
			if (k_setpag() == -1) {
				logError( "setpag() for %s failed\n", curuser );
				fail = 1;
			}
			if ((ret = k_afsklog( NULL, NULL )) != KSUCCESS) {
				logError( "AFS Warning: %s\n", krb_get_err_text( ret ) );
				fail = 1;
			}
			if (fail)
				displayMsg( V_MSG_ERR,
				            "Warning: Problems during Kerberos4/AFS setup." );
		}
	}
#  endif /* KERBEROS && AFS */
# endif /* _AIX */
#endif	/* !PAM */

	curuid = p->pw_uid;
	curgid = p->pw_gid;

	env = baseEnv( curuser );
	xma = 0;
	strApp( &xma, "method=", curtype, (char *)0 );
	if (td_setup)
		strApp( &xma, ",auto", (char *)0 );
	if (xma) {
		env = setEnv( env, "XDM_MANAGED", xma );
		free( xma );
	}
	if (td->autoLock && cursource == PWSRC_AUTOLOGIN)
		env = setEnv( env, "DESKTOP_LOCKED", "true" );
	env = setEnv( env, "PATH", curuid ? td->userPath : td->systemPath );
	env = setEnv( env, "SHELL", p->pw_shell );
	env = setEnv( env, "HOME", p->pw_dir );
#if !defined(USE_PAM) && !defined(_AIX) && defined(KERBEROS)
	if (krbtkfile[0] != '\0')
		env = setEnv( env, "KRBTKFILE", krbtkfile );
#endif
	userEnviron = inheritEnv( env, envvars );
	env = systemEnv( curuser );
	systemEnviron = setEnv( env, "HOME", p->pw_dir );
	debug( "user environment:\n%[|''>'\n's"
	       "system environment:\n%[|''>'\n's"
	       "end of environments\n",
	       userEnviron,
	       systemEnviron );

	/*
	 * for user-based authorization schemes,
	 * add the user to the server's allowed "hosts" list.
	 */
	for (i = 0; i < td->authNum; i++) {
#ifdef SECURE_RPC
		if (td->authorizations[i]->name_length == 9 &&
		    !memcmp( td->authorizations[i]->name, "SUN-DES-1", 9 ))
		{
			XHostAddress addr;
			char netname[MAXNETNAMELEN+1];
			char domainname[MAXNETNAMELEN+1];

			getdomainname( domainname, sizeof(domainname) );
			user2netname( netname, curuid, domainname );
			addr.family = FamilyNetname;
			addr.length = strlen( netname );
			addr.address = netname;
			XAddHost( dpy, &addr );
		}
#endif
#ifdef K5AUTH
		if (td->authorizations[i]->name_length == 14 &&
		    !memcmp( td->authorizations[i]->name, "MIT-KERBEROS-5", 14 ))
		{
			/* Update server's auth file with user-specific info.
			 * Don't need to AddHost because X server will do that
			 * automatically when it reads the cache we are about
			 * to point it at.
			 */
			XauDisposeAuth( td->authorizations[i] );
			td->authorizations[i] =
				krb5GetAuthFor( 14, "MIT-KERBEROS-5", td->name );
			saveServerAuthorizations( td, td->authorizations, td->authNum );
		}
#endif
	}

	if (*dmrcDir)
		mergeSessionArgs( TRUE );

	debug( "now starting the session\n" );

#ifdef USE_PAM

# ifdef HAVE_SETUSERCONTEXT
	if (setusercontext( lc, p, p->pw_uid, LOGIN_SETGROUP )) {
		logError( "setusercontext(groups) for %s failed: %m\n",
		          curuser );
		goto pError;
	}
# else
	if (!setGid( curuser, curgid ))
		goto pError;
# endif

# ifndef HAVE_PAM_GETENVLIST
	if (!(pam_env = initStrArr( 0 ))) {
		resetGids();
		goto pError;
	}
	saved_env = environ;
	environ = pam_env;
# endif
	removeCreds = 1; /* set it first - i don't trust PAM's rollback */
	pretc = pam_setcred( pamh, 0 );
	reInitErrorLog();
# ifndef HAVE_PAM_GETENVLIST
	pam_env = environ;
	environ = saved_env;
# endif
# ifdef HAVE_INITGROUPS
	/* This seems to be a strange place for it, but do it:
	   - after the initial groups are set
	   - after pam_setcred might have set something, even in the error case
	   - before pam_setcred(DELETE_CRED) might need it
	 */
	if (!saveGids())
		goto pError;
# endif
	if (pretc != PAM_SUCCESS) {
		logError( "pam_setcred() for %s failed: %s\n",
		          curuser, pam_strerror( pamh, pretc ) );
		resetGids();
		return 0;
	}

	removeSession = 1; /* set it first - same as above */
	pretc = pam_open_session( pamh, 0 );
	reInitErrorLog();
	if (pretc != PAM_SUCCESS) {
		logError( "pam_open_session() for %s failed: %s\n",
		          curuser, pam_strerror( pamh, pretc ) );
		resetGids();
		return 0;
	}

	/* we don't want sessreg and the startup/reset scripts run with user
	   credentials. unfortunately, we can reset only the gids. */
	resetGids();

# define D_LOGIN_SETGROUP LOGIN_SETGROUP
#else /* USE_PAM */
# define D_LOGIN_SETGROUP 0
#endif /* USE_PAM */

	removeAuth = 1;
	chownCtrl( &td->ctrl, curuid );
	endpwent();
#if !defined(USE_PAM) && defined(USESHADOW) && !defined(_AIX)
	endspent();
#endif
	ctltalk.pipe = &ctlpipe;
	ASPrintf( &buf, "sub-daemon for display %s", td->name );
	ASPrintf( &buf2, "client for display %s", td->name );
	switch (gFork( &ctlpipe, buf, buf2, 0, 0, mstrtalk.pipe, pid )) {
	case 0:

		gCloseOnExec( ctltalk.pipe );
		if (Setjmp( ctltalk.errjmp ))
			exit( 1 );

		gCloseOnExec( mstrtalk.pipe );
		if (Setjmp( mstrtalk.errjmp ))
			goto cError;

#ifndef NOXDMTITLE
		setproctitle( "%s'", td->name );
#endif
		strApp( &prog, " '", (char *)0 );
		reInitErrorLog();

		setsid();

		sessreg( td, getpid(), curuser, curuid );

		/* We do this here, as we want to have the session as parent. */
		switch (source( systemEnviron, td->startup, td_setup )) {
		case 0:
			break;
		case wcCompose( 0, 0, 127 ):
			goto cError;
		default: /* Explicit failure => message already displayed. */
			logError( "Startup script returned non-zero exit code\n" );
			exit( 1 );
		}

	/* Memory leaks are ok here as we exec() soon. */

#if defined(USE_PAM) || !defined(_AIX)

# ifdef USE_PAM
		/* pass in environment variables set by libpam and modules it called */
#  ifdef HAVE_PAM_GETENVLIST
		pam_env = pam_getenvlist( pamh );
		reInitErrorLog();
#  endif
		if (pam_env)
			for (; *pam_env; pam_env++)
				userEnviron = putEnv( *pam_env, userEnviron );
# endif

# ifdef HAVE_SETLOGIN
		if (setlogin( curuser ) < 0) {
			logError( "setlogin for %s failed: %m\n", curuser );
			goto cError;
		}
#  define D_LOGIN_SETLOGIN LOGIN_SETLOGIN
# else
#  define D_LOGIN_SETLOGIN 0
# endif

# if defined(USE_PAM) && defined(HAVE_INITGROUPS)
		if (!restoreGids())
			goto cError;
# endif

# ifndef HAVE_SETUSERCONTEXT

#  ifdef USE_PAM
		if (!setUid( curuser, curuid ))
			goto cError;
#  else
		if (!setUser( curuser, curuid, curgid ))
			goto cError;
#  endif

# else /* !HAVE_SETUSERCONTEXT */

		/*
		 * Destroy environment.
		 * We need to do this before setusercontext() because that may
		 * set or reset some environment variables.
		 */
		if (!(environ = initStrArr( 0 )))
			goto cError;

		/*
		 * Set the user's credentials: uid, gid, groups,
		 * environment variables, resource limits, and umask.
		 */
		if (setusercontext( lc, p, p->pw_uid,
		        LOGIN_SETALL & ~(D_LOGIN_SETGROUP|D_LOGIN_SETLOGIN) ) < 0)
		{
			logError( "setusercontext for %s failed: %m\n", curuser );
			goto cError;
		}

		for (i = 0; environ[i]; i++)
			userEnviron = putEnv( environ[i], userEnviron );

# endif /* !HAVE_SETUSERCONTEXT */

#else /* PAM || !_AIX */
		/*
		 * Set the user's credentials: uid, gid, groups,
		 * audit classes, user limits, and umask.
		 */
		if (setpcred( curuser, NULL ) == -1) {
			logError( "setpcred for %s failed: %m\n", curuser );
			goto cError;
		}

		/*
		 * Set the users process environment. Store protected variables and
		 * obtain updated user environment list. This call will initialize
		 * global 'newenv'.
		 */
		if (setpenv( curuser, PENV_INIT | PENV_ARGV | PENV_NOEXEC,
		             userEnviron, NULL ) != 0)
		{
			logError( "Cannot set %s's process environment\n", curuser );
			goto cError;
		}
		userEnviron = newenv;

#endif /* _AIX */

		/*
		 * for user-based authorization schemes,
		 * use the password to get the user's credentials.
		 */
#ifdef SECURE_RPC
		/* do like "keylogin" program */
		if (!curpass[0])
			logInfo( "No password for NIS provided.\n" );
		else {
			char netname[MAXNETNAMELEN+1], secretkey[HEXKEYBYTES+1];
			int nameret, keyret;
			int len;
			int key_set_ok = 0;
			struct key_netstarg netst;

			nameret = getnetname( netname );
			debug( "user netname: %s\n", netname );
			len = strlen( curpass );
			if (len > 8)
				bzero( curpass + 8, len - 8 );
			keyret = getsecretkey( netname, secretkey, curpass );
			debug( "getsecretkey returns %d, key length %d\n",
			       keyret, strlen( secretkey ) );
			netst.st_netname = netname;
			memcpy( netst.st_priv_key, secretkey, HEXKEYBYTES );
			memset( netst.st_pub_key, 0, HEXKEYBYTES );
			if (key_setnet( &netst ) < 0)
				debug( "Could not set secret key.\n" );
			/* is there a key, and do we have the right password? */
			if (keyret == 1) {
				if (*secretkey) {
					keyret = key_setsecret( secretkey );
					debug( "key_setsecret returns %d\n", keyret );
					if (keyret == -1)
						logError( "Failed to set NIS secret key\n" );
					else
						key_set_ok = 1;
				} else {
					/* found a key, but couldn't interpret it */
					logError( "Password incorrect for NIS principal %s\n",
					          nameret ? netname : curuser );
				}
			}
			if (!key_set_ok)
				nukeAuth( 9, "SUN-DES-1" );
			bzero( secretkey, strlen( secretkey ) );
		}
#endif
#ifdef K5AUTH
		/* do like "kinit" program */
		if (!curpass[0])
			logInfo( "No password for Kerberos5 provided.\n" );
		else
			if ((str = krb5Init( curuser, curpass, td->name )))
				userEnviron = setEnv( userEnviron, "KRB5CCNAME", str );
			else
				nukeAuth( 14, "MIT-KERBEROS-5" );
#endif /* K5AUTH */
		if (td->autoReLogin) {
			gSet( &mstrtalk );
			gSendInt( D_ReLogin );
			gSendStr( curuser );
			gSendStr( curpass );
			gSendStr( newdmrc );
		}
		if (curpass)
			bzero( curpass, strlen( curpass ) );
		setUserAuthorization( td );
		home = getEnv( userEnviron, "HOME" );
		if (home && chdir( home ) < 0) {
			logError( "Cannot chdir to %s's home %s: %m\n", curuser, home );
			sendStr( V_MSG_ERR, "Cannot enter home directory. Using /.\n" );
			chdir( "/" );
			userEnviron = setEnv( userEnviron, "HOME", "/" );
			home = 0;
		}
		if (home || td->clientLogFile[0] == '/') {
			if (!createClientLog( td->clientLogFile )) {
				logWarn( "Session log file according to %s cannot be created: %m\n",
				         td->clientLogFile );
				goto tmperr;
			}
		} else {
		  tmperr:
			if (!createClientLog( td->clientLogFallback ))
				logError( "Fallback session log file according to %s cannot be created: %m\n",
				          td->clientLogFallback );
			/* Could inform the user, but I guess this is only confusing. */
		}
		if (!*dmrcDir)
			mergeSessionArgs( home != 0 );
		if (!(desksess = iniEntry( curdmrc, "Desktop", "Session", 0 )))
			desksess = "failsafe"; /* only due to OOM */
		gSet( &mstrtalk );
		gSendInt( D_User );
		gSendInt( curuid );
		gSendStr( curuser );
		gSendStr( desksess );
		close( mstrtalk.pipe->fd.w );
		userEnviron = setEnv( userEnviron, "DESKTOP_SESSION", desksess );
		for (i = 0; td->sessionsDirs[i]; i++) {
			fname = 0;
			if (strApp( &fname, td->sessionsDirs[i], "/", desksess, ".desktop", (char *)0 )) {
				if ((str = iniLoad( fname ))) {
					if (!strCmp( iniEntry( str, "Desktop Entry", "Hidden", 0 ), "true" ) ||
					    !(sessargs = iniEntry( str, "Desktop Entry", "Exec", 0 )))
						sessargs = "";
					free( str );
					free( fname );
					goto gotit;
				}
				free( fname );
			}
		}
		if (!strcmp( desksess, "failsafe" ) ||
		    !strcmp( desksess, "default" ) ||
		    !strcmp( desksess, "custom" ))
			sessargs = desksess;
		else
			sessargs = "";
	  gotit:
		if (!(argv = parseArgs( (char **)0, td->session )) ||
		    !(argv = addStrArr( argv, sessargs, -1 )))
			exit( 1 );
		if (argv[0] && *argv[0]) {
			debug( "executing session %\"[s\n", argv );
			execute( argv, userEnviron );
			logError( "Session %\"s execution failed: %m\n", argv[0] );
		} else
			logError( "Session has no command/arguments\n" );
		failsafeArgv[0] = td->failsafeClient;
		failsafeArgv[1] = 0;
		execute( failsafeArgv, userEnviron );
		logError( "Failsafe client %\"s execution failed: %m\n",
		          failsafeArgv[0] );
	  cError:
		sendStr( V_MSG_ERR, 0 );
		exit( 1 );
	case -1:
		free( buf );
		return 0;
	}
	debug( "StartSession, fork succeeded %d\n", *pid );
	free( buf );

	gSet( &ctltalk );
	if (!Setjmp( ctltalk.errjmp ))
		while (gRecvCmd( &i )) {
			buf = gRecvStr();
			displayStr( i, buf );
			free( buf );
			gSet( &ctltalk );
			gSendInt( 0 );
		}
	gClosen( ctltalk.pipe );
	finishGreet();

	return 1;
}
Пример #27
0
/*!
\fn KmlExport::generateImagesthumb(const KUrl& imageURL, QDomElement& kmlAlbum )
 */
void KmlExport::generateImagesthumb(const KUrl& imageURL, QDomElement& kmlAlbum )
{
    KPImageInfo info(imageURL);

    // Load image
    QString path = imageURL.path();
    QFile imageFile(path);

    if (!imageFile.open(QIODevice::ReadOnly))
    {
        logWarning(i18n("Could not read image '%1'",path));
        return;
    }

    QImageReader reader(&imageFile);
    QString imageFormat = reader.format();

    if (imageFormat.isEmpty())
    {
        logWarning(i18n("Format of image '%1' is unknown",path));
        return;
    }

    imageFile.close();
    imageFile.open(QIODevice::ReadOnly);

    QByteArray imageData = imageFile.readAll();
    QImage image;

    if (!image.loadFromData(imageData) )
    {
        logWarning(i18n("Error loading image '%1'",path));
        return;
    }

    // Process images

    if ( info.orientation() != KPMetadata::ORIENTATION_UNSPECIFIED )
    {
        QMatrix matrix = RotationMatrix::toMatrix(info.orientation());
        image          = image.transformed( matrix );
    }

    image = image.scaled(m_size, m_size, Qt::KeepAspectRatioByExpanding);
    QImage icon;

    if (m_optimize_googlemap)
    {
        icon = generateSquareThumbnail(image,m_googlemapSize);
    }
    else
    {
    //    icon = image.smoothScale(m_iconSize, m_iconSize, QImage::ScaleMax);
        icon = generateBorderedThumbnail(image, m_iconSize);
    }

    // Save images
    /** @todo remove the extension of the file
     * it's appear with digikam but not with gwenview
     * which already seems to strip the extension
     */
    QString baseFileName = webifyFileName(info.name());
    //baseFileName       = mUniqueNameHelper.makeNameUnique(baseFileName);
    QString fullFileName;
    fullFileName         = baseFileName + '.' + imageFormat.toLower();
    QString destPath     = m_tempDestDir + m_imageDir + fullFileName;

    if (!image.save(destPath, imageFormat.toAscii(), 85))
    {
        // if not able to save the image, it's pointless to create a placemark
        logWarning(i18n("Could not save image '%1' to '%2'",path,destPath));
    }
    else
    {
        //logInfo(i18n("Creation of picture '%1'").arg(fullFileName));

        double     alt, lat, lng;
        KPMetadata meta;

        if (info.hasGeolocationInfo())
        {
            lat = info.latitude();
            lng = info.longitude();
            alt = info.altitude();
        }
        else
        {
            meta.load(imageURL.path());
            meta.getGPSInfo(alt, lat, lng);
        }

        QDomElement kmlPlacemark = addKmlElement(kmlAlbum, "Placemark");
        addKmlTextElement(kmlPlacemark,"name",fullFileName);
        // location and altitude
        QDomElement kmlGeometry  = addKmlElement(kmlPlacemark, "Point");

        if (alt)
        {
            addKmlTextElement(kmlGeometry, "coordinates", QString("%1,%2,%3 ")
                .arg(lng, 0, 'f', 8)
                .arg(lat, 0, 'f', 8)
                .arg(alt, 0, 'f', 8));
        }
        else
        {
            addKmlTextElement(kmlGeometry, "coordinates", QString("%1,%2 ")
                .arg(lng, 0, 'f', 8)
                .arg(lat, 0, 'f', 8));
        }

        if (m_altitudeMode == 2 )
        {
            addKmlTextElement(kmlGeometry, "altitudeMode", "absolute");
        }
        else if (m_altitudeMode == 1 )
        {
            addKmlTextElement(kmlGeometry, "altitudeMode", "relativeToGround");
        }
        else
        {
            addKmlTextElement(kmlGeometry, "altitudeMode", "clampToGround");
        }

        addKmlTextElement(kmlGeometry, "extrude", "1");

        // we try to load exif value if any otherwise, try the application db
        /** we need to take the DateTimeOriginal
          * if we refer to http://www.exif.org/Exif2-2.PDF
          * (standard)DateTime: is The date and time of image creation. In this standard it is the date and time the file was changed
          * DateTimeOriginal: The date and time when the original image data was generated.
          *                   For a DSC the date and time the picture was taken are recorded.
          * DateTimeDigitized: The date and time when the image was stored as digital data.
          * So for:
          * - a DSC: the right time is the DateTimeDigitized which is also DateTimeOriginal
          *          if the picture has been modified the (standard)DateTime should change.
          * - a scanned picture, the right time is the DateTimeOriginal which should also be the DateTime
          *          the (standard)DateTime should be the same except if the picture is modified
          * - a panorama created from several pictures, the right time is the DateTimeOriginal (average of DateTimeOriginal actually)
          *          The (standard)DateTime is the creation date of the panorama.
          * it's seems the time to take into acccount is the DateTimeOriginal.
          * but the KPMetadata::getImageDateTime() return the (standard)DateTime first
          * KPMetadata seems to take Original dateTime first so it shoul be alright now.
          */
        QDateTime datetime = meta.getImageDateTime();

        if (datetime.isValid())
        {
            QDomElement kmlTimeStamp = addKmlElement(kmlPlacemark, "TimeStamp");
            addKmlTextElement(kmlTimeStamp, "when", datetime.toString("yyyy-MM-ddThh:mm:ssZ"));
        }
        else if (m_interface->hasFeature(ImagesHasTime))
        {
            QDomElement kmlTimeStamp = addKmlElement(kmlPlacemark, "TimeStamp");
            addKmlTextElement(kmlTimeStamp, "when", (info.date()).toString("yyyy-MM-ddThh:mm:ssZ"));
        }

        QString my_description;

        if (m_optimize_googlemap)
        {
            my_description = "<img src=\"" + m_UrlDestDir + m_imageDir + fullFileName + "\">";
        }
        else
        {
            my_description = "<img src=\"" + m_imageDir + fullFileName + "\">";
        }

        if ( m_interface->hasFeature( ImagesHasComments ) )
        {
            my_description += "<br/>" + info.description() ;
        }

        addKmlTextElement(kmlPlacemark, "description", my_description);
        logInfo(i18n("Creation of placemark '%1'", fullFileName));

        // Save icon
        QString iconFileName = "thumb_" + baseFileName + '.' + imageFormat.toLower();
        QString destPath     = m_tempDestDir + m_imageDir + iconFileName;

        if (!icon.save(destPath, imageFormat.toAscii(), 85))
        {
            logWarning(i18n("Could not save icon for image '%1' to '%2'",path,destPath));
        }
        else
        {
            //logInfo(i18n("Creation of icon '%1'").arg(iconFileName));
            // style et icon
            QDomElement kmlStyle     = addKmlElement(kmlPlacemark, "Style");
            QDomElement kmlIconStyle = addKmlElement(kmlStyle,     "IconStyle");
            QDomElement kmlIcon      = addKmlElement(kmlIconStyle, "Icon");

            if (m_optimize_googlemap)
            {
                addKmlTextElement(kmlIcon, "href", m_UrlDestDir + m_imageDir + iconFileName);
            }
            else
            {
                addKmlTextElement(kmlIcon, "href", m_imageDir + iconFileName);
            }

            QDomElement kmlBallonStyle = addKmlElement(kmlStyle, "BalloonStyle");
            addKmlTextElement(kmlBallonStyle, "text", "$[description]");
        }
    }
}
Пример #28
0
static int
#if defined(USE_PAM) || defined(_AIX)
isNoPassAllowed( const char *un )
{
	struct passwd *pw = 0;
# ifdef HAVE_GETSPNAM /* (sic!) - not USESHADOW */
	struct spwd *spw;
# endif
#else
isNoPassAllowed( const char *un, struct passwd *pw )
{
#endif
	struct group *gr;
	char **fp;
	int hg;

	if (!*un)
		return 0;

	if (cursource != PWSRC_MANUAL)
		return 1;

	for (hg = 0, fp = td->noPassUsers; *fp; fp++)
		if (**fp == '@')
			hg = 1;
		else if (!strcmp( un, *fp ))
			return 1;
		else if (!strcmp( "*", *fp )) {
#if defined(USE_PAM) || defined(_AIX)
			if (!(pw = getpwnam( un )))
				return 0;
			if (pw->pw_passwd[0] == '!' || pw->pw_passwd[0] == '*')
				continue;
# ifdef HAVE_GETSPNAM /* (sic!) - not USESHADOW */
			if ((spw = getspnam( un )) &&
			    (spw->sp_pwdp[0] == '!' || spw->sp_pwdp[0] == '*'))
					continue;
# endif
#endif
			if (pw->pw_uid)
				return 1;
		}

#if defined(USE_PAM) || defined(_AIX)
	if (hg && (pw || (pw = getpwnam( un )))) {
#else
	if (hg) {
#endif
		for (setgrent(); (gr = getgrent()); )
			for (fp = td->noPassUsers; *fp; fp++)
				if (**fp == '@' && !strcmp( gr->gr_name, *fp + 1 )) {
					if (pw->pw_gid == gr->gr_gid) {
						endgrent();
						return 1;
					}
					for (; *gr->gr_mem; gr->gr_mem++)
						if (!strcmp( un, *gr->gr_mem )) {
							endgrent();
							return 1;
						}
				}
		endgrent();
	}

	return 0;
}

#if !defined(USE_PAM) && !defined(_AIX) && defined(HAVE_SETUSERCONTEXT)
# define LC_RET0 do { login_close(lc); return 0; } while(0)
#else
# define LC_RET0 return 0
#endif

int
verify( GConvFunc gconv, int rootok )
{
#ifdef USE_PAM
	const char *psrv;
	struct pam_data pdata;
	int pretc, pnopass;
	char psrvb[64];
#elif defined(_AIX)
	char *msg, *curret;
	int i, reenter;
#else
	struct stat st;
	const char *nolg;
	char *buf;
	int fd;
# ifdef HAVE_GETUSERSHELL
	char *s;
# endif
# if defined(HAVE_STRUCT_PASSWD_PW_EXPIRE) || defined(USESHADOW)
	int tim, expir, warntime, quietlog;
# endif
#endif

	debug( "verify ...\n" );

#ifdef USE_PAM

	pnopass = FALSE;
	if (!strcmp( curtype, "classic" )) {
		if (!gconv( GCONV_USER, 0 ))
			return 0;
		if (isNoPassAllowed( curuser )) {
			gconv( GCONV_PASS_ND, 0 );
			if (!*curpass) {
				pnopass = TRUE;
				sprintf( psrvb, "%.31s-np", PAMService );
				psrv = psrvb;
			} else
				psrv = PAMService;
		} else
			psrv = PAMService;
		pdata.usecur = TRUE;
	} else {
		sprintf( psrvb, "%.31s-%.31s", PAMService, curtype );
		psrv = psrvb;
		pdata.usecur = FALSE;
	}
	pdata.gconv = gconv;
	if (!doPAMAuth( psrv, &pdata ))
		return 0;

#elif defined(_AIX)

	if ((td->displayType & d_location) == dForeign) {
		char *tmpch;
		strncpy( hostname, td->name, sizeof(hostname) - 1 );
		hostname[sizeof(hostname)-1] = '\0';
		if ((tmpch = strchr( hostname, ':' )))
			*tmpch = '\0';
	} else
		hostname[0] = '\0';

	/* tty names should only be 15 characters long */
# if 0
	for (i = 0; i < 15 && td->name[i]; i++) {
		if (td->name[i] == ':' || td->name[i] == '.')
			tty[i] = '_';
		else
			tty[i] = td->name[i];
	}
	tty[i] = '\0';
# else
	memcpy( tty, "/dev/xdm/", 9 );
	for (i = 0; i < 6 && td->name[i]; i++) {
		if (td->name[i] == ':' || td->name[i] == '.')
			tty[9 + i] = '_';
		else
			tty[9 + i] = td->name[i];
	}
	tty[9 + i] = '\0';
# endif

	if (!strcmp( curtype, "classic" )) {
		if (!gconv( GCONV_USER, 0 ))
			return 0;
		if (isNoPassAllowed( curuser )) {
			gconv( GCONV_PASS_ND, 0 );
			if (!*curpass) {
				debug( "accepting despite empty password\n" );
				goto done;
			}
		} else
			if (!gconv( GCONV_PASS, 0 ))
				return 0;
		enduserdb();
		msg = NULL;
		if ((i = authenticate( curuser, curpass, &reenter, &msg ))) {
			debug( "authenticate() failed: %s\n", msg );
			if (msg)
				free( msg );
			loginfailed( curuser, hostname, tty );
			if (i == ENOENT || i == ESAD)
				V_RET_AUTH;
			else
				V_RET_FAIL( 0 );
		}
		if (reenter) {
			logError( "authenticate() requests more data: %s\n", msg );
			free( msg );
			V_RET_FAIL( 0 );
		}
	} else if (!strcmp( curtype, "generic" )) {
		if (!gconv( GCONV_USER, 0 ))
			return 0;
		for (curret = 0;;) {
			msg = NULL;
			if ((i = authenticate( curuser, curret, &reenter, &msg ))) {
				debug( "authenticate() failed: %s\n", msg );
				if (msg)
					free( msg );
				loginfailed( curuser, hostname, tty );
				if (i == ENOENT || i == ESAD)
					V_RET_AUTH;
				else
					V_RET_FAIL( 0 );
			}
			if (curret)
				free( curret );
			if (!reenter)
				break;
			if (!(curret = gconv( GCONV_HIDDEN, msg )))
				return 0;
			free( msg );
		}
	} else {
		logError( "Unsupported authentication type %\"s requested\n", curtype );
		V_RET_FAIL( 0 );
	}
	if (msg) {
		displayStr( V_MSG_INFO, msg );
		free( msg );
	}

  done:

#else

	if (strcmp( curtype, "classic" )) {
		logError( "Unsupported authentication type %\"s requested\n", curtype );
		V_RET_FAIL( 0 );
	}

	if (!gconv( GCONV_USER, 0 ))
		return 0;

	if (!(p = getpwnam( curuser ))) {
		debug( "getpwnam() failed.\n" );
		gconv( GCONV_PASS, 0 );
		V_RET_AUTH;
	}
	if (p->pw_passwd[0] == '!' || p->pw_passwd[0] == '*') {
		debug( "account is locked\n" );
		gconv( GCONV_PASS, 0 );
		V_RET_AUTH;
	}

# ifdef USESHADOW
	if ((sp = getspnam( curuser ))) {
		p->pw_passwd = sp->sp_pwdp;
		if (p->pw_passwd[0] == '!' || p->pw_passwd[0] == '*') {
			debug( "account is locked\n" );
			gconv( GCONV_PASS, 0 );
			V_RET_AUTH;
		}
	} else
		debug( "getspnam() failed: %m. Are you root?\n" );
# endif

	if (!*p->pw_passwd) {
		if (!td->allowNullPasswd) {
			debug( "denying user with empty password\n" );
			gconv( GCONV_PASS, 0 );
			V_RET_AUTH;
		}
		goto nplogin;
	}

	if (isNoPassAllowed( curuser, p )) {
	  nplogin:
		gconv( GCONV_PASS_ND, 0 );
		if (!*curpass) {
			debug( "accepting password-less login\n" );
			goto done;
		}
	} else
		if (!gconv( GCONV_PASS, 0 ))
			return 0;

# ifdef KERBEROS
	if (p->pw_uid) {
		int ret;
		char realm[REALM_SZ];

		if (krb_get_lrealm( realm, 1 )) {
			logError( "Cannot get KerberosIV realm.\n" );
			V_RET_FAIL( 0 );
		}

		sprintf( krbtkfile, "%s.%.*s", TKT_ROOT, MAXPATHLEN - strlen( TKT_ROOT ) - 2, td->name );
		krb_set_tkt_string( krbtkfile );
		unlink( krbtkfile );

		ret = krb_verify_user( curuser, "", realm, curpass, 1, "rcmd" );
		if (ret == KSUCCESS) {
			chown( krbtkfile, p->pw_uid, p->pw_gid );
			debug( "KerberosIV verify succeeded\n" );
			goto done;
		} else if (ret != KDC_PR_UNKNOWN && ret != SKDC_CANT) {
			logError( "KerberosIV verification failure %\"s for %s\n",
			          krb_get_err_text( ret ), curuser );
			krbtkfile[0] = '\0';
			V_RET_FAIL( 0 );
		}
		debug( "KerberosIV verify failed: %s\n", krb_get_err_text( ret ) );
	}
	krbtkfile[0] = '\0';
# endif	 /* KERBEROS */

# if defined(ultrix) || defined(__ultrix__)
	if (authenticate_user( p, curpass, NULL ) < 0)
# elif defined(HAVE_PW_ENCRYPT)
	if (strcmp( pw_encrypt( curpass, p->pw_passwd ), p->pw_passwd ))
# elif defined(HAVE_CRYPT)
	if (strcmp( crypt( curpass, p->pw_passwd ), p->pw_passwd ))
# else
	if (strcmp( curpass, p->pw_passwd ))
# endif
	{
		debug( "password verify failed\n" );
		V_RET_AUTH;
	}

  done:

#endif /* !defined(USE_PAM) && !defined(_AIX) */

	debug( "restrict %s ...\n", curuser );

#if defined(USE_PAM) || defined(_AIX)
	if (!(p = getpwnam( curuser ))) {
		logError( "getpwnam(%s) failed.\n", curuser );
		V_RET_FAIL( 0 );
	}
#endif
	if (!p->pw_uid) {
		if (!rootok && !td->allowRootLogin)
			V_RET_FAIL( "Root logins are not allowed" );
		return 1; /* don't deny root to log in */
	}

#ifdef USE_PAM

	debug( " pam_acct_mgmt() ...\n" );
	pretc = pam_acct_mgmt( pamh, 0 );
	reInitErrorLog();
	debug( " pam_acct_mgmt() returned: %s\n", pam_strerror( pamh, pretc ) );
	if (pretc == PAM_NEW_AUTHTOK_REQD) {
		pdata.usecur = FALSE;
		pdata.gconv = conv_interact;
		/* pam will have output a message already, so no prepareErrorGreet() */
		if (gconv != conv_interact || pnopass) {
			pam_end( pamh, PAM_SUCCESS );
			pamh = 0;
			gSendInt( V_CHTOK_AUTH );
			/* this cannot auth the wrong user, as only classic auths get here */
			while (!doPAMAuth( PAMService, &pdata ))
				if (pdata.abort)
					return 0;
			gSendInt( V_PRE_OK );
		} else
			gSendInt( V_CHTOK );
		for (;;) {
			debug( " pam_chauthtok() ...\n" );
			pretc = pam_chauthtok( pamh, PAM_CHANGE_EXPIRED_AUTHTOK );
			reInitErrorLog();
			debug( " pam_chauthtok() returned: %s\n", pam_strerror( pamh, pretc ) );
			if (pdata.abort) {
				pam_end( pamh, PAM_SUCCESS );
				pamh = 0;
				return 0;
			}
			if (pretc == PAM_SUCCESS)
				break;
			/* effectively there is only PAM_AUTHTOK_ERR */
			gSendInt( V_FAIL );
		}
		if (curpass)
			free( curpass );
		curpass = newpass;
		newpass = 0;
	} else if (pretc != PAM_SUCCESS) {
		pam_end( pamh, pretc );
		pamh = 0;
		V_RET_AUTH;
	}

#elif defined(_AIX) /* USE_PAM */

	msg = NULL;
	if (loginrestrictions( curuser,
	                       ((td->displayType & d_location) == dForeign) ? S_RLOGIN : S_LOGIN,
	                       tty, &msg ) == -1)
	{
		debug( "loginrestrictions() - %s\n", msg ? msg : "error" );
		loginfailed( curuser, hostname, tty );
		prepareErrorGreet();
		if (msg) {
			displayStr( V_MSG_ERR, msg );
			free( msg );
		}
		gSendInt( V_AUTH );
		return 0;
	}
	if (msg)
		free( (void *)msg );

#endif /* USE_PAM || _AIX */

#ifndef _AIX

# ifdef HAVE_SETUSERCONTEXT
#  ifdef HAVE_LOGIN_GETCLASS
	lc = login_getclass( p->pw_class );
#  else
	lc = login_getpwclass( p );
#  endif
	if (!lc)
		V_RET_FAIL( 0 );

	p->pw_shell = login_getcapstr( lc, "shell", p->pw_shell, p->pw_shell );
# endif

# ifndef USE_PAM

/* restrict_expired */
#  if defined(HAVE_STRUCT_PASSWD_PW_EXPIRE) || defined(USESHADOW)

#   if !defined(HAVE_STRUCT_PASSWD_PW_EXPIRE) || (!defined(HAVE_SETUSERCONTEXT) && defined(USESHADOW))
	if (sp)
#   endif
	{

#   define DEFAULT_WARN	(2L * 7L)  /* Two weeks */

		tim = time( NULL ) / 86400L;

#   ifdef HAVE_SETUSERCONTEXT
		quietlog = login_getcapbool( lc, "hushlogin", 0 );
		warntime = login_getcaptime( lc, "warnexpire",
		                             DEFAULT_WARN * 86400L,
		                             DEFAULT_WARN * 86400L ) / 86400L;
#   else
		quietlog = 0;
#    ifdef USESHADOW
		warntime = sp->sp_warn != -1 ? sp->sp_warn : DEFAULT_WARN;
#    else
		warntime = DEFAULT_WARN;
#    endif
#   endif

#   ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
		if (p->pw_expire) {
			expir = p->pw_expire / 86400L;
#   else
		if (sp->sp_expire != -1) {
			expir = sp->sp_expire;
#   endif
			if (tim > expir) {
				displayStr( V_MSG_ERR,
				            "Your account has expired;"
				            " please contact your system administrator" );
				gSendInt( V_FAIL );
				LC_RET0;
			} else if (tim > (expir - warntime) && !quietlog) {
				displayMsg( V_MSG_INFO,
				            "Warning: your account will expire in %d day(s)",
				            expir - tim );
			}
		}

#   ifdef HAVE_STRUCT_PASSWD_PW_EXPIRE
		if (p->pw_change) {
			expir = p->pw_change / 86400L;
#   else
		if (!sp->sp_lstchg) {
			displayStr( V_MSG_ERR,
			            "You are required to change your password immediately"
			            " (root enforced)" );
			/* XXX todo password change */
			gSendInt( V_FAIL );
			LC_RET0;
		} else if (sp->sp_max != -1) {
			expir = sp->sp_lstchg + sp->sp_max;
			if (sp->sp_inact != -1 && tim > expir + sp->sp_inact) {
				displayStr( V_MSG_ERR,
				            "Your account has expired;"
				            " please contact your system administrator" );
				gSendInt( V_FAIL );
				LC_RET0;
			}
#   endif
			if (tim > expir) {
				displayStr( V_MSG_ERR,
				            "You are required to change your password immediately"
				            " (password aged)" );
				/* XXX todo password change */
				gSendInt( V_FAIL );
				LC_RET0;
			} else if (tim > (expir - warntime) && !quietlog) {
				displayMsg( V_MSG_INFO,
				            "Warning: your password will expire in %d day(s)",
				            expir - tim );
			}
		}

	}

#  endif /* HAVE_STRUCT_PASSWD_PW_EXPIRE || USESHADOW */

/* restrict_nologin */
#  ifndef _PATH_NOLOGIN
#   define _PATH_NOLOGIN "/etc/nologin"
#  endif

	if ((
#  ifdef HAVE_SETUSERCONTEXT
	     /* Do we ignore a nologin file? */
	     !login_getcapbool( lc, "ignorenologin", 0 )) &&
	    (!stat( (nolg = login_getcapstr( lc, "nologin", "", NULL )), &st ) ||
#  endif
		 !stat( (nolg = _PATH_NOLOGIN), &st )))
	{
		if (st.st_size && (fd = open( nolg, O_RDONLY )) >= 0) {
			if ((buf = Malloc( st.st_size + 1 ))) {
				if (read( fd, buf, st.st_size ) == st.st_size) {
					close( fd );
					buf[st.st_size] = 0;
					displayStr( V_MSG_ERR, buf );
					free( buf );
					gSendInt( V_FAIL );
					LC_RET0;
				}
				free( buf );
			}
			close( fd );
		}
		displayStr( V_MSG_ERR,
		            "Logins are not allowed at the moment.\nTry again later" );
		gSendInt( V_FAIL );
		LC_RET0;
	}

/* restrict_time */
#  if defined(HAVE_SETUSERCONTEXT) && defined(HAVE_AUTH_TIMEOK)
	if (!auth_timeok( lc, time( NULL ) )) {
		displayStr( V_MSG_ERR,
		            "You are not allowed to login at the moment" );
		gSendInt( V_FAIL );
		LC_RET0;
	}
#  endif

#  ifdef HAVE_GETUSERSHELL
	for (;;) {
		if (!(s = getusershell())) {
			debug( "shell not in /etc/shells\n" );
			endusershell();
			V_RET_FAIL( "Your login shell is not listed in /etc/shells" );
		}
		if (!strcmp( s, p->pw_shell )) {
			endusershell();
			break;
		}
	}
#  endif

# endif /* !USE_PAM */

/* restrict_nohome */
# ifdef HAVE_SETUSERCONTEXT
	if (login_getcapbool( lc, "requirehome", 0 )) {
		struct stat st;
		if (!*p->pw_dir || stat( p->pw_dir, &st ) || st.st_uid != p->pw_uid) {
			displayStr( V_MSG_ERR, "Home folder not available" );
			gSendInt( V_FAIL );
			LC_RET0;
		}
	}
# endif

#endif /* !_AIX */

	return 1;

}


static const char *envvars[] = {
	"TZ", /* SYSV and SVR4, but never hurts */
#ifdef _AIX
	"AUTHSTATE", /* for kerberos */
#endif
	NULL
};


#if defined(USE_PAM) && defined(HAVE_INITGROUPS)
static int num_saved_gids;
static gid_t *saved_gids;

static int
saveGids( void )
{
	num_saved_gids = getgroups( 0, 0 );
	if (!(saved_gids = Malloc( sizeof(gid_t) * num_saved_gids )))
		return 0;
	if (getgroups( num_saved_gids, saved_gids ) < 0) {
		logError( "saving groups failed: %m\n" );
		return 0;
	}
	return 1;
}

static int
restoreGids( void )
{
	if (setgroups( num_saved_gids, saved_gids ) < 0) {
		logError( "restoring groups failed: %m\n" );
		return 0;
	}
	if (setgid( p->pw_gid ) < 0) {
		logError( "restoring gid failed: %m\n" );
		return 0;
	}
	return 1;
}
#endif /* USE_PAM && HAVE_INITGROUPS */

static int
resetGids( void )
{
#ifdef HAVE_INITGROUPS
	if (setgroups( 0, &p->pw_gid /* anything */ ) < 0) {
		logError( "restoring groups failed: %m\n" );
		return 0;
	}
#endif
	if (setgid( 0 ) < 0) {
		logError( "restoring gid failed: %m\n" );
		return 0;
	}
	return 1;
}

static int
setGid( const char *name, int gid )
{
	if (setgid( gid ) < 0) {
		logError( "setgid(%d) (user %s) failed: %m\n", gid, name );
		return 0;
	}
#ifdef HAVE_INITGROUPS
	if (initgroups( name, gid ) < 0) {
		logError( "initgroups for %s failed: %m\n", name );
		setgid( 0 );
		return 0;
	}
#endif	 /* QNX4 doesn't support multi-groups, no initgroups() */
	return 1;
}

static int
setUid( const char *name, int uid )
{
	if (setuid( uid ) < 0) {
		logError( "setuid(%d) (user %s) failed: %m\n", uid, name );
		return 0;
	}
	return 1;
}

static int
setUser( const char *name, int uid, int gid )
{
	if (setGid( name, gid )) {
		if (setUid( name, uid ))
			return 1;
		resetGids();
	}
	return 0;
}

#if defined(SECURE_RPC) || defined(K5AUTH)
static void
nukeAuth( int len, const char *name )
{
	int i;

	for (i = 0; i < td->authNum; i++)
		if (td->authorizations[i]->name_length == len &&
		    !memcmp( td->authorizations[i]->name, name, len ))
		{
			memcpy( &td->authorizations[i], &td->authorizations[i+1],
			        sizeof(td->authorizations[i]) * (--td->authNum - i) );
			break;
		}
}
#endif

static void
mergeSessionArgs( int cansave )
{
	char *mfname;
	const char *fname;
	int i, needsave;

	mfname = 0;
	fname = ".dmrc";
	if ((!curdmrc || newdmrc) && *dmrcDir)
		if (strApp( &mfname, dmrcDir, "/", curuser, fname, (char *)0 ))
			fname = mfname;
	needsave = 0;
	if (!curdmrc) {
		curdmrc = iniLoad( fname );
		if (!curdmrc) {
			strDup( &curdmrc, "[Desktop]\nSession=default\n" );
			needsave = 1;
		}
	}
	if (newdmrc) {
		curdmrc = iniMerge( curdmrc, newdmrc );
		needsave = 1;
	}
	if (needsave && cansave)
		if (!iniSave( curdmrc, fname ) && errno == ENOENT && mfname) {
			for (i = 0; mfname[i]; i++)
				if (mfname[i] == '/') {
					mfname[i] = 0;
					mkdir( mfname, 0755 );
					mfname[i] = '/';
				}
			iniSave( curdmrc, mfname );
		}
	if (mfname)
		free( mfname );
}

static int
createClientLog( const char *log )
{
	char randstr[32], *randstrp = 0, *lname;
	int lfd;

	for (;;) {
		struct expando macros[] = {
			{ 'd', 0, td->name },
			{ 'u', 0, curuser },
			{ 'r', 0, randstrp },
			{ 0, 0, 0 }
		};
		if (!(lname = expandMacros( log, macros )))
			exit( 1 );
		unlink( lname );
		if ((lfd = open( lname, O_WRONLY|O_CREAT|O_EXCL, 0600 )) >= 0) {
			dup2( lfd, 1 );
			dup2( lfd, 2 );
			close( lfd );
			free( lname );
			return TRUE;
		}
		if (errno != EEXIST || !macros[2].uses) {
			free( lname );
			return FALSE;
		}
		logInfo( "Session log file %s not usable, trying another one.\n",
		         lname );
		free( lname );
		sprintf( randstr, "%d", secureRandom() );
		randstrp = randstr;
	}
}
Пример #29
0
void setup()
{


#ifdef ESP8266_WiFi
	String mdns_id;

	mdns_id = eepromManager.fetchmDNSName();
	if(mdns_id.length()<=0)
		mdns_id = "ESP" + String(ESP.getChipId());


	// If we're going to set up WiFi, let's get to it
	WiFiManager wifiManager;
	wifiManager.setConfigPortalTimeout(5*60); // Time out after 5 minutes so that we can keep managing temps 
	wifiManager.setDebugOutput(false); // In case we have a serial connection to BrewPi
									   
	// The main purpose of this is to set a boolean value which will allow us to know we
	// just saved a new configuration (as opposed to rebooting normally)
	wifiManager.setSaveConfigCallback(saveConfigCallback);

	// The third parameter we're passing here (mdns_id.c_str()) is the default name that will appear on the form.
	// It's nice, but it means the user gets no actual prompt for what they're entering. 
	WiFiManagerParameter custom_mdns_name("mdns", "Device (mDNS) Name", mdns_id.c_str(), 20);
	wifiManager.addParameter(&custom_mdns_name);

	wifiManager.autoConnect(); // Launch captive portal with auto generated name ESP + ChipID

	// Alright. We're theoretically connected here (or we timed out).
	// If we connected, then let's save the mDNS name
	if (shouldSaveConfig) {
		// If the mDNS name is valid, save it.
		if (isValidmDNSName(custom_mdns_name.getValue())) {
			eepromManager.savemDNSName(custom_mdns_name.getValue());
		} else {
			// If the mDNS name is invalid, reset the WiFi configuration and restart the ESP8266
			WiFi.disconnect(true);
			delay(2000);
			handleReset();
		}
	}

	// Regardless of the above, we need to set the mDNS name and announce it
	if (!MDNS.begin(mdns_id.c_str())) {
		// TODO - Do something about it or log it or something
	}
#endif


#if BREWPI_BUZZER	
	buzzer.init();
	buzzer.beep(2, 500);
#endif	

	piLink.init();

#ifdef ESP8266_WiFi
	// If we're using WiFi, initialize the bridge
	server.begin();
	server.setNoDelay(true);
	// mDNS will stop responding after awhile unless we query the specific service we want
	MDNS.addService("brewpi", "tcp", 23);
	MDNS.addServiceTxt("brewpi", "tcp", "board", "ESP8266");
	MDNS.addServiceTxt("brewpi", "tcp", "branch", "legacy");
	MDNS.addServiceTxt("brewpi", "tcp", "version", VERSION_STRING);
	MDNS.addServiceTxt("brewpi", "tcp", "revision", FIRMWARE_REVISION);
#endif

    bool initialize = !eepromManager.hasSettings();
    if(initialize) {
        eepromManager.zapEeprom();  // Writes all the empty files to SPIFFS
        logInfo(INFO_EEPROM_INITIALIZED);
    }

	logDebug("started");
	tempControl.init();
	settingsManager.loadSettings();

#if BREWPI_SIMULATE
	simulator.step();
	// initialize the filters with the assigned initial temp value
	tempControl.beerSensor->init();
	tempControl.fridgeSensor->init();
#endif	

	display.init();
#ifdef ESP8266_WiFi
	display.printWiFi();  // Print the WiFi info (mDNS name & IP address)
	delay(8000);
	display.clear();
#endif
	display.printStationaryText();
	display.printState();

//	rotaryEncoder.init();

	logDebug("init complete");
}
Пример #30
0
void Aligner::generateConsensus() {
    
    logInfo("Calculating consensus sequence from aligned reads", 1)
#ifdef DEBUG
    logInfo("DR zone: " << AL_ZoneStart << " -> " << AL_ZoneEnd, 1);
#endif

	// chars we luv!
    char alphabet[4] = {'A', 'C', 'G', 'T'};

	
	// populate the conservation array
    int num_GT_zero = 0;
    for(int j = 0; j < AL_length; j++)
	{
		int max_count = 0;
		float total_count = 0.0;
		for(int i = 0; i < 4; i++)
		{
			
			total_count += static_cast<float>(AL_coverage[coverageIndex(j,alphabet[i])]);
			if(AL_coverage[coverageIndex(j,alphabet[i])] > max_count)
			{
				max_count = AL_coverage[coverageIndex(j,alphabet[i])];
				AL_consensus[j] = alphabet[i];
			}
		}
		// we need at least CRASS_DEF_MIN_READ_DEPTH reads to call a DR
		if(total_count > CRASS_DEF_MIN_READ_DEPTH)
		{
			AL_conservation[j] = static_cast<float>(max_count)/total_count;
			num_GT_zero++;
		}
		else
		{
			AL_conservation[j] = 0;
		}
	}
    
    // trim these back a bit (if we trim too much we'll get it back right now anywho)
    // CTS: Not quite true, if it is low coverage then there will be no extension!
    // check to see that this DR is supported by a bare minimum of reads
    if(num_GT_zero < CRASS_DEF_MIN_READ_DEPTH) {
        logWarn("**WARNING: low confidence DR", 1);
    } else {
        // first work from the left and trim back
	    while(AL_ZoneStart > 0)
	    {
		    if(AL_conservation[AL_ZoneStart - 1] < CRASS_DEF_ZONE_EXT_CONS_CUT_OFF) 
                AL_ZoneStart++;
            else 
			    break;
	    }
        
	    // next work from the right
	    while(AL_ZoneEnd < AL_length - 1)
	    {
		    if(AL_conservation[AL_ZoneEnd + 1] < CRASS_DEF_ZONE_EXT_CONS_CUT_OFF)
			    AL_ZoneEnd--;
		    else
			    break;
	    }
    }
	//same as the loops above but this time extend outward
	while(AL_ZoneStart > 0)
	{
		if(AL_conservation[AL_ZoneStart - 1] >= CRASS_DEF_ZONE_EXT_CONS_CUT_OFF) 
            AL_ZoneStart--;
        else 
			break;    
	}
    
	// next work to the right
	while(AL_ZoneEnd < AL_length - 1)
	{
		if(AL_conservation[AL_ZoneEnd + 1] >= CRASS_DEF_ZONE_EXT_CONS_CUT_OFF)
			AL_ZoneEnd++;
		else
			break;
	}
    
#ifdef DEBUG
    logInfo("DR zone (post fix): " << AL_ZoneStart << " -> " << AL_ZoneEnd, 1);
#endif

}