コード例 #1
0
ファイル: NetFacHTTP.cpp プロジェクト: hackshields/antivirus
KLUPD::CoreError KLUPD::HttpProtocol::httpRequest(
    const Path &fileNameIn,
    const Path &relativeUrlPathIn,
    const Address &serverAddress, const std::string &userAgent,
    const bool useProxy, const Address &proxyAddress,
    const AuthorizationTypeList &proxyAuthorizationMethods,
    const size_t regettingPosition)
{
    // second get file attempt may needed in case current connection has been timed out
    bool needSecondAttempt
        = m_connected && (m_connectedTo == (useProxy ? proxyAddress : serverAddress));

    while(true)
    {
        const CoreError getFileResult = httpRequestAttempt(fileNameIn, relativeUrlPathIn, serverAddress,
            userAgent, useProxy, proxyAddress, proxyAuthorizationMethods, regettingPosition);

        // check if not connection broken problem
        if(getFileResult != CORE_REMOTE_HOST_CLOSED_CONNECTION)
            return getFileResult;

        closeSession();

        // was not connected, thus no timeout could happen
        if(!needSecondAttempt)
            return getFileResult;

        TRACE_MESSAGE("Second HTTP download attempt will be performed, because connection may have been timed out");

        // last attempt (only 2 attempts)
        needSecondAttempt = false;

        // will re-use previous success authorization
        m_authorizationDriver.authorized(false);
    }
}
コード例 #2
0
ファイル: SessionManager.cpp プロジェクト: OpenRcon/OpenRcon
void SessionManager::closeSession(int index)
{
    GameWidget *gameWidget = dynamic_cast<GameWidget*>(TabWidget::getInstance()->widget(index));

    closeSession(gameWidget, index);
}
コード例 #3
0
ファイル: SessionManager.cpp プロジェクト: OpenRcon/OpenRcon
void SessionManager::closeSession(GameWidget *gameWidget)
{
    int index = TabWidget::getInstance()->indexOf(gameWidget);

    closeSession(gameWidget, index);
}
コード例 #4
0
ファイル: tee.c プロジェクト: DBMSRmutl/MaxScale
/**
 * Associate a new session with this instance of the filter.
 *
 * Create the file to log to and open it.
 *
 * @param instance	The filter instance data
 * @param session	The session itself
 * @return Session specific data for this session
 */
static void *
newSession(FILTER *instance, SESSION *session)
{
    TEE_INSTANCE *my_instance = (TEE_INSTANCE *) instance;
    TEE_SESSION *my_session;
    char *remote, *userName;

    if (strcmp(my_instance->service->name, session->service->name) == 0)
    {
        MXS_ERROR("%s: Recursive use of tee filter in service.",
                  session->service->name);
        my_session = NULL;
        goto retblock;
    }

    HASHTABLE* ht = hashtable_alloc(100, simple_str_hash, strcmp);
    bool is_loop = detect_loops(my_instance, ht, session->service);
    hashtable_free(ht);

    if (is_loop)
    {
        MXS_ERROR("%s: Recursive use of tee filter in service.",
                  session->service->name);
        my_session = NULL;
        goto retblock;
    }

    if ((my_session = calloc(1, sizeof(TEE_SESSION))) != NULL)
    {
        my_session->active = 1;
        my_session->residual = 0;
        my_session->tee_replybuf = NULL;
        my_session->client_dcb = session->client;
        my_session->instance = my_instance;
        my_session->client_multistatement = false;
        my_session->queue = NULL;
        spinlock_init(&my_session->tee_lock);
        if (my_instance->source &&
            (remote = session_get_remote(session)) != NULL)
        {
            if (strcmp(remote, my_instance->source))
            {
                my_session->active = 0;

                MXS_WARNING("Tee filter is not active.");
            }
        }
        userName = session_getUser(session);

        if (my_instance->userName &&
            userName &&
            strcmp(userName, my_instance->userName))
        {
            my_session->active = 0;

            MXS_WARNING("Tee filter is not active.");
        }

        if (my_session->active)
        {
            DCB* dcb;
            SESSION* ses;
            FILTER_DEF* dummy;
            UPSTREAM* dummy_upstream;

            if ((dcb = dcb_clone(session->client)) == NULL)
            {
                freeSession(instance, (void *) my_session);
                my_session = NULL;

                MXS_ERROR("Creating client DCB for Tee "
                          "filter failed. Terminating session.");

                goto retblock;
            }

            if ((dummy = filter_alloc("tee_dummy", "tee_dummy")) == NULL)
            {
                dcb_close(dcb);
                freeSession(instance, (void *) my_session);
                my_session = NULL;
                MXS_ERROR("tee: Allocating memory for "
                          "dummy filter definition failed."
                          " Terminating session.");

                goto retblock;
            }



            if ((ses = session_alloc(my_instance->service, dcb)) == NULL)
            {
                filter_free(dummy);
                dcb_close(dcb);
                freeSession(instance, (void *) my_session);
                my_session = NULL;
                MXS_ERROR("Creating client session for Tee "
                          "filter failed. Terminating session.");

                goto retblock;
            }

            ss_dassert(ses->ses_is_child);

            dummy->obj = GetModuleObject();
            dummy->filter = NULL;
            my_session->branch_session = ses;
            my_session->branch_dcb = dcb;
            my_session->dummy_filterdef = dummy;

            if ((dummy_upstream = filterUpstream(
                                                 dummy, my_session, &ses->tail)) == NULL)
            {
                filter_free(dummy);
                closeSession(instance, (void*) my_session);
                dcb_close(dcb);
                free(my_session);
                MXS_ERROR("tee: Allocating memory for"
                          "dummy upstream failed."
                          " Terminating session.");

                return NULL;
            }

            ses->tail = *dummy_upstream;
            MySQLProtocol* protocol = (MySQLProtocol*) session->client->protocol;
            my_session->use_ok = protocol->client_capabilities & (1 << 6);
            free(dummy_upstream);
        }
    }
retblock:
    return my_session;
}
コード例 #5
0
ファイル: SNMPSession.cpp プロジェクト: KiemVM/SNMP_Project
SNMPSession::~SNMPSession() {
	SNMPManager::getManager()->unregisterSession(this);
	closeSession();
}
コード例 #6
0
ファイル: client_legacy.c プロジェクト: hund123/open62541
int main(int argc, char *argv[]) {
	int defaultParams = argc < 8;

	//start parameters
	if(defaultParams) {
		printf("1st parameter: number of nodes to read \n");
		printf("2nd parameter: number of read-tries \n");
		printf("3rd parameter: name of the file to save measurement data \n");
		printf("4th parameter: 1 = read same node, 0 = read different nodes \n");
		printf("5th parameter: ip adress \n");
		printf("6th parameter: port \n");
		printf("7th parameter: 0=stateful, 1=stateless\n");
		printf("8th parameter: 0=tcp, 1=udp (only with stateless calls)\n");
		printf("\nUsing default parameters. \n");
	}

	UA_UInt32 nodesToReadSize;
	UA_UInt32 tries;
	UA_Boolean alwaysSameNode;
	UA_ByteString reply;
	UA_ByteString_newMembers(&reply, 65536);
	UA_Boolean stateless;
	UA_Boolean udp;

	if(defaultParams)
		nodesToReadSize = 1;
	else
		nodesToReadSize = atoi(argv[1]);

	if(defaultParams)
		tries= 2;
	else
		tries = (UA_UInt32) atoi(argv[2]);

	if(defaultParams){
		alwaysSameNode = UA_TRUE;
	}else{
		if(atoi(argv[4]) != 0)
			alwaysSameNode = UA_TRUE;
		else
			alwaysSameNode = UA_FALSE;
	}

	if(defaultParams){
		stateless = UA_FALSE;
	}else{
		if(atoi(argv[7]) != 0)
			stateless = UA_TRUE;
		else
			stateless = UA_FALSE;
	}

	if(defaultParams){
		udp = UA_FALSE;
	}else{
		if(atoi(argv[8]) != 0)
			udp = UA_TRUE;
		else
			udp = UA_FALSE;
	}



    //Connect to remote server
	UA_String endpoint;
	UA_String_copycstring("none",&endpoint);
	ConnectionInfo connectionInfo;


/* REQUEST START*/
    UA_NodeId *nodesToRead;
    nodesToRead = UA_Array_new(&UA_TYPES[UA_TYPES_NODEID], 1);

	for(UA_UInt32 i = 0; i<1; i++) {
		if(alwaysSameNode)
			nodesToRead[i].identifier.numeric = 2253; //ask always the same node
		else
			nodesToRead[i].identifier.numeric = 19000 +i;
		nodesToRead[i].identifierType = UA_NODEIDTYPE_NUMERIC;
		nodesToRead[i].namespaceIndex = 0;
	}

	UA_DateTime tic, toc;
	UA_Double *timeDiffs;
	UA_Int32 received;
	timeDiffs = UA_Array_new(&UA_TYPES[UA_TYPES_DOUBLE], tries);
	UA_Double sum = 0;

	tic = UA_DateTime_now();

	/**
	UA_Double duration;

	UA_UInt32 count = 0;
	UA_Double start = 0, stop = 0;

	UA_UInt32 timeToRun = 30;
	UA_UInt32 timeToStart = 8;
	UA_UInt32 timeToStop = 22;

	do{
		toc = UA_DateTime_now();
		duration = ((UA_Double)toc-(UA_Double)tic)/(UA_Double)1e4;
		if(duration>=timeToStart*1000 && duration <= timeToStop*1000){
			if(start==0.0){
				start=UA_DateTime_now();
			}
		}
			//if(stateless || (!stateless && i==0)){
				if(defaultParams){
					if(ua_client_connectUA("127.0.0.1",atoi("16664"),&endpoint,&connectionInfo,stateless,udp) != 0){
						return 0;
					}
				}else{
					if(ua_client_connectUA(argv[5],atoi(argv[6]),&endpoint,&connectionInfo,stateless,udp) != 0){
						return 0;
					}
				}
			//}
			sendReadRequest(&connectionInfo,1,nodesToRead);
			received = recv(connectionInfo.socket, reply.data, 2000, 0);
			if(duration>=timeToStart*1000 && duration <= timeToStop*1000){
				count++;
			}

			if(!stateless){
			closeSession(&connectionInfo);
			recv(connectionInfo.socket, reply.data, 2000, 0);

			closeSecureChannel(&connectionInfo);
			}
			//if(stateless || (!stateless && i==tries-1)){
				close(connectionInfo.socket);
			//}
		if(duration >= timeToStop*1000 && stop==0){
			stop=UA_DateTime_now();
			printf("%i messages in %f secs, rate %f m/s\n", count, (stop-start)/(UA_Double)1e7, (UA_Double)count/((stop-start)/(UA_Double)1e7));
		}

	}while(duration<timeToRun*1000);

	exit(0);
	**/

	for(UA_UInt32 i = 0; i < tries; i++) {
		//if(stateless || (!stateless && i==0)){
		tic = UA_DateTime_now();
			if(defaultParams){
				if(ua_client_connectUA("127.0.0.1",atoi("16664"),&endpoint,&connectionInfo,stateless,udp) != 0){
					return 0;
				}
			}else{
				if(ua_client_connectUA(argv[5],atoi(argv[6]),&endpoint,&connectionInfo,stateless,udp) != 0){
					return 0;
				}
			}
		//}
		for(UA_UInt32 i = 0; i < nodesToReadSize; i++) {
		sendReadRequest(&connectionInfo,1,nodesToRead);
		received = recv(connectionInfo.socket, reply.data, 2000, 0);
		}
			if(!stateless){
		closeSession(&connectionInfo);
		recv(connectionInfo.socket, reply.data, 2000, 0);
			closeSecureChannel(&connectionInfo);
		}
		//if(stateless || (!stateless && i==tries-1)){
			close(connectionInfo.socket);
		//}
		toc = UA_DateTime_now() - tic;
		timeDiffs[i] = (UA_Double)toc/(UA_Double)1e4;
		sum = sum + timeDiffs[i];
	}

/* REQUEST END*/

	UA_Double mean = sum / tries;
	printf("mean time for handling request: %16.10f ms \n",mean);

	if(received>0)
		printf("received: %i\n",received); // dummy


	//save to file
	char data[100];
	const char flag = 'a';
	FILE* fHandle = UA_NULL;
	if (defaultParams) {
		fHandle =  fopen("client.log", &flag);
	}else{
		fHandle =  fopen(argv[3], &flag);
	}
	//header

	UA_Int32 bytesToWrite = sprintf(data, "measurement %s in ms, nodesToRead %d \n", argv[3], 1);
	fwrite(data,1,bytesToWrite,fHandle);
	for(UA_UInt32 i=0;i<tries;i++) {
		bytesToWrite = sprintf(data,"%16.10f \n",timeDiffs[i]);
		fwrite(data,1,bytesToWrite,fHandle);
	}
	fclose(fHandle);

	UA_String_deleteMembers(&reply);
	UA_Array_delete(nodesToRead,&UA_TYPES[UA_TYPES_NODEID], 1);
    UA_free(timeDiffs);

	return 0;
}
コード例 #7
0
ファイル: lsb.jobs.c プロジェクト: ReiAyanamiQH/jhlava
void 
lsb_closejobinfo()
{
     closeSession(mbdSock);
} 
コード例 #8
0
ファイル: lsb.jobs.c プロジェクト: ReiAyanamiQH/jhlava
struct jobInfoEnt *
lsb_readjobinfo(int *more)
{
    XDR  xdrs;
    int num, i, aa;
    struct LSFHeader hdr;
    char *buffer = NULL;
    static struct jobInfoReply jobInfoReply;
    static struct jobInfoEnt jobInfo;
    static struct submitReq submitReq;   
    static int first = TRUE;

    static int npids = 0;
    static struct pidInfo  *pidInfo = NULL;
    static int npgids = 0;
    static int *pgid = NULL;


    TIMEIT(0, (num = readNextPacket(&buffer, _lsb_recvtimeout, &hdr,
				    mbdSock)), "readNextPacket");
    if (num < 0) {
	closeSession(mbdSock);
        lsberrno = LSBE_EOF;
	return NULL;
    }

    if (first) {
	if ( (submitReq.fromHost = malloc(MAXHOSTNAMELEN)) == NULL
	    || (submitReq.jobFile = malloc(MAXFILENAMELEN)) == NULL
	    || (submitReq.inFile  = malloc(MAXFILENAMELEN)) == NULL
	    || (submitReq.outFile = malloc(MAXFILENAMELEN)) == NULL
	    || (submitReq.errFile = malloc(MAXFILENAMELEN)) == NULL
	    || (submitReq.inFileSpool = malloc(MAXFILENAMELEN)) == NULL
	    || (submitReq.commandSpool = malloc(MAXFILENAMELEN)) == NULL
	    || (submitReq.hostSpec = malloc(MAXHOSTNAMELEN)) == NULL
	    || (submitReq.chkpntDir = malloc(MAXFILENAMELEN)) == NULL
	    || (submitReq.subHomeDir = malloc(MAXFILENAMELEN)) == NULL
	    || (jobInfoReply.userName  = malloc(MAXLSFNAMELEN)) == NULL
	    || (submitReq.cwd       = malloc(MAXFILENAMELEN)) == NULL) {
	    lsberrno = LSBE_NO_MEM;
	    FREEUP(submitReq.fromHost);
	    FREEUP(submitReq.jobFile);
	    FREEUP(submitReq.inFile);
	    FREEUP(submitReq.outFile);
	    FREEUP(submitReq.errFile);
	    FREEUP(submitReq.inFileSpool);
	    FREEUP(submitReq.commandSpool);
	    FREEUP(submitReq.hostSpec);
	    FREEUP(submitReq.chkpntDir);
	    FREEUP(submitReq.subHomeDir);
	    FREEUP(jobInfoReply.userName);
	    FREEUP(submitReq.cwd);

	    free(buffer);
	    return NULL;
	}
	
	submitReq.xf = NULL;             
        submitReq.nxf = 0;
        jobInfoReply.numToHosts = 0;
        submitReq.numAskedHosts = 0;
        first = FALSE;
    }

    jobInfoReply.jobBill = &submitReq;

    if (jobInfoReply.numToHosts > 0) {   
	for (i=0; i<jobInfoReply.numToHosts; i++)
	    FREEUP(jobInfoReply.toHosts[i]);
        FREEUP(jobInfoReply.toHosts);
	jobInfoReply.numToHosts = 0;
	jobInfoReply.toHosts = NULL;
    }

    if (submitReq.xf) { 
	free(submitReq.xf);
        submitReq.xf = NULL;
    }

    
    FREEUP( jobInfoReply.execHome );
    FREEUP( jobInfoReply.execCwd );
    FREEUP( jobInfoReply.execUsername );
    FREEUP( jobInfoReply.parentGroup );
    FREEUP( jobInfoReply.jName );

    TIMEIT(1, xdrmem_create(&xdrs, buffer, XDR_DECODE_SIZE_(hdr.length), XDR_DECODE), "xdrmem_create");
    TIMEIT(1, (aa = xdr_jobInfoReply(&xdrs, &jobInfoReply, &hdr)), "xdr_jobInfoReply");
    if (aa == FALSE) {
	lsberrno = LSBE_XDR;
	xdr_destroy(&xdrs);
	free(buffer);
	jobInfoReply.toHosts = NULL; 
	jobInfoReply.numToHosts = 0;
	return NULL;
    }

    TIMEIT(1, xdr_destroy(&xdrs), "xdr_destroy");
    free(buffer);
    jobInfo.jobId = jobInfoReply.jobId;
    jobInfo.status = jobInfoReply.status;
    jobInfo.numReasons = jobInfoReply.numReasons;
    jobInfo.reasonTb = jobInfoReply.reasonTb;
    jobInfo.reasons = jobInfoReply.reasons;
    jobInfo.subreasons = jobInfoReply.subreasons;
    jobInfo.startTime = jobInfoReply.startTime;
    jobInfo.predictedStartTime = jobInfoReply.predictedStartTime;
    jobInfo.endTime  = jobInfoReply.endTime;
    jobInfo.cpuTime  = jobInfoReply.cpuTime;
    jobInfo.numExHosts = jobInfoReply.numToHosts;
    jobInfo.exHosts = jobInfoReply.toHosts;
    jobInfo.nIdx = jobInfoReply.nIdx;
    jobInfo.loadSched = jobInfoReply.loadSched;
    jobInfo.loadStop = jobInfoReply.loadStop;
    jobInfo.exitStatus = jobInfoReply.exitStatus;
    jobInfo.reserveTime = jobInfoReply.reserveTime;
    jobInfo.jobPid = jobInfoReply.jobPid;
    jobInfo.port = jobInfoReply.port;
    jobInfo.jobPriority = jobInfoReply.jobPriority; 

    jobInfo.user = jobInfoReply.userName;

    jobInfo.execUid = jobInfoReply.execUid;
    jobInfo.execHome = jobInfoReply.execHome;
    jobInfo.execCwd = jobInfoReply.execCwd;
    jobInfo.execUsername = jobInfoReply.execUsername;

    
    jobInfo.jType    = jobInfoReply.jType;
    jobInfo.parentGroup = jobInfoReply.parentGroup;
    jobInfo.jName        = jobInfoReply.jName;
    for (i=0; i<NUM_JGRP_COUNTERS; i++)
        jobInfo.counter[i] = jobInfoReply.counter[i];

    jobInfo.submitTime = jobInfoReply.jobBill->submitTime;
    jobInfo.umask = jobInfoReply.jobBill->umask;
    jobInfo.cwd = jobInfoReply.jobBill->cwd;
    jobInfo.subHomeDir = jobInfoReply.jobBill->subHomeDir;    
    jobInfo.submit.options = jobInfoReply.jobBill->options;
    jobInfo.submit.options2 = jobInfoReply.jobBill->options2;
    jobInfo.submit.numProcessors = jobInfoReply.jobBill->numProcessors;
    jobInfo.submit.maxNumProcessors = jobInfoReply.jobBill->maxNumProcessors;
    jobInfo.submit.jobName = jobInfoReply.jobBill->jobName;
    jobInfo.submit.command = jobInfoReply.jobBill->command;
    jobInfo.submit.resReq = jobInfoReply.jobBill->resReq;
    jobInfo.submit.queue = jobInfoReply.jobBill->queue;
    jobInfo.fromHost = jobInfoReply.jobBill->fromHost;
    jobInfo.submit.inFile = jobInfoReply.jobBill->inFile;
    jobInfo.submit.outFile = jobInfoReply.jobBill->outFile;
    jobInfo.submit.errFile = jobInfoReply.jobBill->errFile;
    jobInfo.submit.beginTime = jobInfoReply.jobBill->beginTime;
    jobInfo.submit.termTime = jobInfoReply.jobBill->termTime;
    jobInfo.submit.userPriority = jobInfoReply.jobBill->userPriority;

     
    for (i=0; i<LSF_RLIM_NLIMITS; i++) {
	jobInfo.submit.rLimits[i] = jobInfoReply.jobBill->rLimits[i];
    }
    jobInfo.submit.hostSpec = jobInfoReply.jobBill->hostSpec;
    jobInfo.submit.sigValue = jobInfoReply.jobBill->sigValue;
    jobInfo.submit.chkpntDir = jobInfoReply.jobBill->chkpntDir;
    jobInfo.submit.dependCond = jobInfoReply.jobBill->dependCond;
    jobInfo.submit.preExecCmd = jobInfoReply.jobBill->preExecCmd;
    jobInfo.submit.chkpntPeriod = jobInfoReply.jobBill->chkpntPeriod;
    jobInfo.submit.numAskedHosts = jobInfoReply.jobBill->numAskedHosts;
    jobInfo.submit.askedHosts = jobInfoReply.jobBill->askedHosts;
    jobInfo.submit.projectName = jobInfoReply.jobBill->projectName;
    jobInfo.submit.mailUser = jobInfoReply.jobBill->mailUser;
    jobInfo.submit.loginShell = jobInfoReply.jobBill->loginShell;
    jobInfo.submit.nxf = jobInfoReply.jobBill->nxf;
    jobInfo.submit.xf = jobInfoReply.jobBill->xf;

    

    jobInfo.jRusageUpdateTime = jobInfoReply.jRusageUpdateTime;
    jobInfo.runRusage.npids = npids;
    jobInfo.runRusage.pidInfo = pidInfo;

    jobInfo.runRusage.npgids = npgids;
    jobInfo.runRusage.pgid = pgid;

    copyJUsage(&(jobInfo.runRusage), &jobInfoReply.runRusage);

     
    npids = jobInfo.runRusage.npids;
    pidInfo = jobInfo.runRusage.pidInfo;

    npgids = jobInfo.runRusage.npgids;
    pgid = jobInfo.runRusage.pgid;
 

     
    if (jobInfoReply.runRusage.npids > 0) {
        FREEUP(jobInfoReply.runRusage.pidInfo); 
        jobInfoReply.runRusage.npids = 0;
    }

    if (jobInfoReply.runRusage.npgids > 0) {
        FREEUP(jobInfoReply.runRusage.pgid); 
        jobInfoReply.runRusage.npgids = 0;
    }

    if (more)
	*more = hdr.reserved;

    return &jobInfo;

} 
コード例 #9
0
ファイル: main.c プロジェクト: blackhole89/compiz
int
main (int argc, char **argv)
{
    CompIOCtx ctx;
    char      *displayName = 0;
    char      *plugin[256];
    int	      i, nPlugin = 0;
    Bool      disableSm = FALSE;
    char      *clientId = NULL;
    char      *refreshRateArg = NULL;

    programName = argv[0];
    programArgc = argc;
    programArgv = argv;

    signal (SIGHUP, signalHandler);
    signal (SIGCHLD, signalHandler);
    signal (SIGINT, signalHandler);
    signal (SIGTERM, signalHandler);
    signal (SIGSEGV, signalHandler);

    emptyRegion.rects = &emptyRegion.extents;
    emptyRegion.numRects = 0;
    emptyRegion.extents.x1 = 0;
    emptyRegion.extents.y1 = 0;
    emptyRegion.extents.x2 = 0;
    emptyRegion.extents.y2 = 0;
    emptyRegion.size = 0;

    infiniteRegion.rects = &infiniteRegion.extents;
    infiniteRegion.numRects = 1;
    infiniteRegion.extents.x1 = MINSHORT;
    infiniteRegion.extents.y1 = MINSHORT;
    infiniteRegion.extents.x2 = MAXSHORT;
    infiniteRegion.extents.y2 = MAXSHORT;

    memset (&ctx, 0, sizeof (ctx));

    for (i = 1; i < argc; i++)
    {
	if (!strcmp (argv[i], "--help"))
	{
	    usage ();
	    return 0;
	}
	else if (!strcmp (argv[i], "--version"))
	{
	    printf (PACKAGE_STRING "\n");
	    return 0;
	}
	else if (!strcmp (argv[i], "--debug"))
	{
	    debugOutput = TRUE;
	}
	else if (!strcmp (argv[i], "--display"))
	{
	    if (i + 1 < argc)
		displayName = argv[++i];
	}
	else if (!strcmp (argv[i], "--refresh-rate"))
	{
	    if (i + 1 < argc)
	    {
		refreshRateArg = programArgv[++i];
		defaultRefreshRate = atoi (refreshRateArg);
		defaultRefreshRate = RESTRICT_VALUE (defaultRefreshRate,
						     1, 1000);
	    }
	}
	else if (!strcmp (argv[i], "--fast-filter"))
	{
	    ctx.textureFilterData = "<default>Fast</default>";
	    defaultTextureFilter = "Fast";
	}
	else if (!strcmp (argv[i], "--indirect-rendering"))
	{
	    /* force Mesa libGL into indirect rendering mode, because
	       glXQueryExtensionsString is context-independant */
	    setenv ("LIBGL_ALWAYS_INDIRECT", "1", True);
	    indirectRendering = TRUE;
	}
	else if (!strcmp (argv[i], "--loose-binding"))
	{
	    strictBinding = FALSE;
	}
	else if (!strcmp (argv[i], "--ignore-desktop-hints"))
	{
	    /* keep command line parameter for backward compatibility */
	    useDesktopHints = FALSE;
	}
	else if (!strcmp (argv[i], "--keep-desktop-hints"))
	{
	    useDesktopHints = TRUE;
	}
	else if (!strcmp (argv[i], "--only-current-screen"))
	{
	    onlyCurrentScreen = TRUE;
	}
	else if (!strcmp (argv[i], "--no-fbo"))
	{
		noFBO = TRUE;
	}

#ifdef USE_COW
	else if (!strcmp (argv[i], "--use-root-window"))
	{
	    useCow = FALSE;
	}
#endif

	else if (!strcmp (argv[i], "--replace"))
	{
	    replaceCurrentWm = TRUE;
	}
	else if (!strcmp (argv[i], "--sm-disable"))
	{
	    disableSm = TRUE;
	}
	else if (!strcmp (argv[i], "--sm-client-id"))
	{
	    if (i + 1 < argc)
		clientId = argv[++i];
	}
	else if (!strcmp (argv[i], "--no-detection"))
	{
	    noDetection = TRUE;
	}
	else if (!strcmp (argv[i], "--bg-image"))
	{
	    if (i + 1 < argc)
		backgroundImage = argv[++i];
	}
	else if (*argv[i] == '-')
	{
	    compLogMessage ("core", CompLogLevelWarn,
			    "Unknown option '%s'\n", argv[i]);
	}
	else
	{
	    if (nPlugin < 256)
		plugin[nPlugin++] = argv[i];
	}
    }

    /* add in default plugins if none are given */
    if (nPlugin == 0)
    {
        plugin[nPlugin++] = "ccp";
        plugin[nPlugin++] = "move";
        plugin[nPlugin++] = "resize";
        plugin[nPlugin++] = "place";
        plugin[nPlugin++] = "decoration";
    }

    if (refreshRateArg)
    {
	ctx.refreshRateData = malloc (strlen (refreshRateArg) + 256);
	if (ctx.refreshRateData)
	    sprintf (ctx.refreshRateData,
		     "<min>1</min><default>%s</default>",
		     refreshRateArg);
    }

    if (nPlugin)
    {
	int size = 256;

	for (i = 0; i < nPlugin; i++)
	    size += strlen (plugin[i]) + 16;

	ctx.pluginData = malloc (size);
	if (ctx.pluginData)
	{
	    char *ptr = ctx.pluginData;

	    ptr += sprintf (ptr, "<type>string</type><default>");

	    for (i = 0; i < nPlugin; i++)
		ptr += sprintf (ptr, "<value>%s</value>", plugin[i]);

	    ptr += sprintf (ptr, "</default>");
	}

	initialPlugins = malloc (nPlugin * sizeof (char *));
	if (initialPlugins)
	{
	    memcpy (initialPlugins, plugin, nPlugin * sizeof (char *));
	    nInitialPlugins = nPlugin;
	}
	else
	{
	    nInitialPlugins = 0;
	}
    }

    xmlInitParser ();

    LIBXML_TEST_VERSION;

    if (!compInitMetadata (&coreMetadata))
    {
	compLogMessage ("core", CompLogLevelFatal,
			"Couldn't initialize core metadata");
	return 1;
    }

    if (!compAddMetadataFromIO (&coreMetadata,
				readCoreXmlCallback, NULL,
				&ctx))
	return 1;

    if (ctx.refreshRateData)
	free (ctx.refreshRateData);

    if (ctx.pluginData)
	free (ctx.pluginData);

    compAddMetadataFromFile (&coreMetadata, "core");

    if (!initCore ())
	return 1;

    coreInitialized = TRUE;

    if (!disableSm)
    {
	if (clientId == NULL)
	{
	    char *desktop_autostart_id = getenv ("DESKTOP_AUTOSTART_ID");
	    if (desktop_autostart_id != NULL)
		clientId = strdup (desktop_autostart_id);
	    unsetenv ("DESKTOP_AUTOSTART_ID");
	}

	initSession (clientId);
    }

    if (!addDisplay (displayName))
	return 1;

    eventLoop ();

    if (!disableSm)
	closeSession ();

    coreInitialized = FALSE;

    finiCore ();
    compFiniMetadata (&coreMetadata);

    xmlCleanupParser ();

    if (initialPlugins)
        free (initialPlugins);

    if (restartSignal)
    {
	execvp (programName, programArgv);
	return 1;
    }

    return 0;
}
コード例 #10
0
int
testCaseSignAndVerifyRecover()
{
	CK_RV rv;
	CK_ULONG ulTokenCount = 0;
	CK_SLOT_ID_PTR pTokenList = NULL_PTR;
	CK_SLOT_ID slotID;
	CK_BYTE application = 42;
	CK_NOTIFY myNotify = NULL;
	CK_SESSION_HANDLE hSession;
	CK_MECHANISM keyMechanism = {
		0, NULL_PTR, 0
	};
	CK_MECHANISM mechanism = {
		0, NULL_PTR, 0
	};
	CK_OBJECT_HANDLE hKey = 0, hPublicKey = 0;
	CK_BYTE_PTR data = NULL_PTR;
	CK_BYTE_PTR dataSigned = NULL_PTR;
	CK_ULONG dataRecoveredLen = 0;
	CK_ULONG dataSignedLen = 0;
	struct timeval start, end, diff;
	
	int i,k,j, temp;
		
	printf("Testing case: SignAndVerifyRecover ...\n");
	printf(" Check dependencies ...\n");
	if(checkDependecies(testCaseSignAndVerifyRecoverDependencies) != 1) return CKR_FUNCTION_NOT_SUPPORTED;
	printf(" Dependencies are fine\n");
	
	//initialize
	printf(" call Initialize ...");
	rv = pFunctionList->C_Initialize(NULL_PTR);
	if(rv != CKR_OK) returnTestCase(rv, 0);
	else printf(" success\n");
	
	//GetSlotList -> Tokenlist
	findActiveTokens(&pTokenList, &ulTokenCount);
	
	for(i=0;i<ulTokenCount;i++)
	{
		
		slotID = pTokenList[i];

		for(j=0;j<pMechaInfoListLen;j++)//each mechanism
		{
			if(!(pMechaInfoList[j].info.flags & (CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER))) continue;
			mechanism.mechanism = pMechaInfoList[j].type;
			
			
			k = searchEleName(mechanism.mechanism, MECHANISM_LIST, (sizeof(MECHANISM_LIST)/sizeof(*MECHANISM_LIST)));
			if(k != -1)	printf(" Signing and Verify Recover(%s) ...\n", MECHANISM_LIST[k].eleName);
			else printf("  Signing and Verify Recover(mecha = %lu) ...\n", mechanism.mechanism);
						
			rv = findGenerateMechanismForMechanism(&keyMechanism, mechanism.mechanism);
			if(rv == 0)
			{
				//OpenSession with CKF_SERIAL_SESSION
				printf(" call C_OpenSession on slot %lu with CKF_SERIAL_SESSION | CKF_RW_SESSION...", slotID);
				rv = pFunctionList->C_OpenSession(slotID, CKF_SERIAL_SESSION | CKF_RW_SESSION, (CK_VOID_PTR) &application, myNotify, &hSession);
				if(rv != CKR_OK) returnTestCase(rv, 0);
				else printf(" success\n");
				
				loginUser(hSession);
					
				hKey = 0;
				hPublicKey = 0;
				if((generateKey(&keyMechanism, &hKey, &hSession) == 0) | (generateKeyPair(&keyMechanism, &hKey, &hPublicKey, hSession) == 0))//gen key
				{								
					generateSampleData(16, &data);
					gettimeofday(&start, NULL);
					rv = signRecover(data, &dataSigned, &dataSignedLen, &hKey, &hSession, &mechanism);
					gettimeofday(&end, NULL);
					if(rv == 0)
					{
						timeval_subtract(&diff, &end, &start);
						printf("   Could sign %zu CK_BYTEs in %ld.%06ld sec.\n", strlen((char *) data), diff.tv_sec, diff.tv_usec);
						temp = dataSignedLen;
						free(data); //because it's reused in verifyRecover
												
						gettimeofday(&start, NULL);
						if(hPublicKey != 0)	rv = verifyRecover(data, &dataRecoveredLen, dataSigned, dataSignedLen, &hPublicKey, &hSession, &mechanism);//asymetric
						if(hPublicKey == 0)	rv = verifyRecover(data, &dataRecoveredLen, dataSigned, dataSignedLen, &hKey, &hSession, &mechanism);//symetric
						gettimeofday(&end, NULL);
						timeval_subtract(&diff, &end, &start);
						if(rv == 0)
						{	
							printf("   Could recover from %d CK_BYTEs in %ld.%06ld sec.\n", temp, diff.tv_sec, diff.tv_usec);
							free(dataSigned);
						}
						else printf("    failed\n");
						free(data);
						
						//try different data length

						generateSampleData(256, &data);
						gettimeofday(&start, NULL);
						rv = signRecover(data, &dataSigned, &dataSignedLen, &hKey, &hSession, &mechanism);
						gettimeofday(&end, NULL);
						if(rv == 0)
						{
							timeval_subtract(&diff, &end, &start);
							printf("   Could sign %zu CK_BYTEs in %ld.%06ld sec.\n", strlen((char *) data), diff.tv_sec, diff.tv_usec);
							temp = dataSignedLen;
							free(data); //because it's reused in verifyRecover
													
							gettimeofday(&start, NULL);
							if(hPublicKey != 0)	rv = verifyRecover(data, &dataRecoveredLen, dataSigned, dataSignedLen, &hPublicKey, &hSession, &mechanism);//asymetric
							if(hPublicKey == 0)	rv = verifyRecover(data, &dataRecoveredLen, dataSigned, dataSignedLen, &hKey, &hSession, &mechanism);//symetric
							gettimeofday(&end, NULL);
							timeval_subtract(&diff, &end, &start);
							if(rv == 0)
							{
								printf("   Could verify %d CK_BYTEs in %ld.%06ld sec.\n", temp, diff.tv_sec, diff.tv_usec);
								free(dataSigned);
							}	
							else printf("    failed\n");
						}
						else printf("    failed\n");
						free(data);
						if(dataSigned!=NULL_PTR) free(dataSigned);

					}
					else printf("    failed\n");
					
											
					if(checkFunctionImplemented("C_DestroyObject")!=-1)
					{
						pFunctionList->C_DestroyObject(hSession, hPublicKey);
						pFunctionList->C_DestroyObject(hSession, hKey);
					}	
				}
				else
				{
					if(k != -1)	printf("  skip %s because mecha is not yet implemented ...\n", MECHANISM_LIST[k].eleName);
					else printf("  skip mecha = %lu because mecha is not yet implemented ...\n", mechanism.mechanism);
				}
				logoutUser(hSession);			
				closeSession(hSession);
			}
			else
			{
				if(k != -1)	printf("  skip %s because the related key generation mechanism was not found...\n", MECHANISM_LIST[k].eleName);
				else printf("  skip mecha = %lu because the related key generation mechanism was not found...\n", mechanism.mechanism);
			}

		}
	}
	
	//finalize
	printf(" call Finalize ...");
	rv = pFunctionList->C_Finalize(NULL_PTR);
	if(rv != CKR_OK) returnTestCase(rv, 0);
	else printf(" success\n");
	
	free(pTokenList);

	printf(" ... case successful\n");
	
	return CKR_OK;
}
コード例 #11
0
ファイル: NetFacHTTP.cpp プロジェクト: hackshields/antivirus
KLUPD::CoreError KLUPD::HttpProtocol::httpRequestAttempt(
    const Path &fileNameIn,
    const Path &relativeUrlPathIn,
    const Address &serverAddressIn, const std::string &userAgent,
    const bool useProxy, const Address &proxyAddressIn,
    const AuthorizationTypeList &proxyAuthorizationMethods,
    const size_t regettingPosition)
{
    size_t infiniteRedirectLoop = 0;

    Path fileName = fileNameIn;
    Path relativeUrlPath = relativeUrlPathIn;
    Address serverAddress = serverAddressIn;
    Address proxyAddress = proxyAddressIn;

    m_regettingPosition = regettingPosition;

    // cache for next iteration generate request
     // at first attempt the target is not known, but proxy server target is used,
     //  because of possible protection from client for authorization on server
    DownloadProgress::AuthorizationTarget authorizationTarget = DownloadProgress::proxyServer;


    ////////////////////
    // the State flags agains proxies that close connection after authorization switch.
    //  There are proxies (e.g. Squid/2.4.STABLE7) which deals in next way:
    // *** Client -> Server:  GET file
    // *** Server -> Client: HTTP 407 / Proxy-Connection: keep-alive
    // *** Server closes connection
    // *** Client -> Server GET 407
    //
    // Here are 3 flags to track such situations, that previous response is received,
    //  BUT then server closes connection
    bool previousResponseReceived = false;
    bool authorizationTypeSwitched = false;
    bool requestHasAlreadyBeenRepeated = false;
    ////////////////////


    ////////////////////
    // in case proxy server requires authorization, but sends incorrect (from HTTP)
    //   code for authorization failure in next way
    // *** Client -> Server:  GET file
    // *** Server -> Client: HTTP 407 / Proxy-Authorization: NTLM
    // *** Client -> Server GET  / Proxy-Authorization: NTLM
    // *** Server -> Client: HTTP 502 (or 403 or other code)
    // *** here is authorization state is forgotten, because 502 request does NOT contain "Proxy-Authorization: NTLM"
    // *** Client ask from product new credentials
    // *** Client -> Server GET  / Proxy-Authorization: NTLM (with new credentials)
    bool authorizationWasNeededOnProxy = false;

    // it makes no sence to try Ntlm without credentials authorization type,
     // because this authorization type does not depend on provided credentials
    bool ntlmAuthorizationTriedAlready = false;

    int lastHttpCode = 0;

    for(size_t protectionAgainstCyclingCounter = 100; protectionAgainstCyclingCounter; --protectionAgainstCyclingCounter)
    {
        const CoreError connectionResult = setupLowLevelConnectionIfNeed(useProxy, useProxy ? proxyAddress : serverAddress, proxyAuthorizationMethods);
        if(connectionResult != CORE_NO_ERROR)
        {
            TRACE_MESSAGE2("Failed to setup connection to HTTP Server, result '%S'",
                toString(connectionResult).toWideChar());
            return connectionResult;
        }

        // make proxy authorization header
        std::string proxyAuthorizationHeader;
        if(!m_authorizationDriver.makeProxyAuthorizationHeader(proxyAuthorizationHeader)
            // we know authorization methods supported by proxy server
            || ((m_authorizationDriver.currentAuthorizationType() == noAuthorization) && !m_authorizationDriver.supportedAuthorizationTypesByServer().empty()))
        {
            if(!switchAuthorization(fileName, relativeUrlPath, authorizationTarget, proxyAddress,
                authorizationTypeSwitched, ntlmAuthorizationTriedAlready))
            {
                if(lastHttpCode)
                    return HttpHeader::convertHttpCodeToUpdaterCode(lastHttpCode);

                return useProxy ? CORE_PROXY_AUTH_ERROR : CORE_SERVER_AUTH_ERROR;
            }

            // try other authorization type
            continue;
        }

        HTTPRequestBuilder requestBuilder(m_method);
        const std::vector<unsigned char> requestBuffer = requestBuilder.generateRequest(
            fileName,
            relativeUrlPath,
            useProxy,
            serverAddress,
            userAgent,
            proxyAuthorizationHeader,
            m_regettingPosition,
            m_postData);

        TRACE_MESSAGE2("Sending HTTP request\n%s", requestBuilder.toString().c_str());

        if(requestBuffer.empty())
        {
            TRACE_MESSAGE("Failed to send empty HTTP request");
            return CORE_DOWNLOAD_ERROR;
        }

        const CoreError sendRequestResult = m_socket.send(reinterpret_cast<const char *>(&requestBuffer[0]), requestBuffer.size());
        if(sendRequestResult != CORE_NO_ERROR)
        {
            TRACE_MESSAGE2("Failed to send HTTP request, error %S", toString(sendRequestResult).toWideChar());
            if((sendRequestResult == CORE_REMOTE_HOST_CLOSED_CONNECTION)
                && previousResponseReceived && authorizationTypeSwitched && !requestHasAlreadyBeenRepeated)
            {
                TRACE_MESSAGE("Repeating the same request (without authorization switch), because server was reachable, but unexpectedly closed connection");
                requestHasAlreadyBeenRepeated = true;
                continue;
            }

            return sendRequestResult;
        }

        HttpHeader httpHeader;
        const CoreError receiveResponseAndDataResult = receiveResponseAndData(httpHeader);

        const bool needCloseConnection = httpHeader.needCloseConnection(useProxy)
            || (receiveResponseAndDataResult != CORE_NO_ERROR);

        if(needCloseConnection)
        {
            TRACE_MESSAGE2("Closing connection to HTTP server, get file result %S",
                toString(receiveResponseAndDataResult).toWideChar());
            closeSession();
        }

        if(receiveResponseAndDataResult != CORE_NO_ERROR)
        {
            TRACE_MESSAGE2("Failed to receive HTTP response, error %S",
                toString(receiveResponseAndDataResult).toWideChar());

            if((receiveResponseAndDataResult == CORE_REMOTE_HOST_CLOSED_CONNECTION)
                && previousResponseReceived && authorizationTypeSwitched && !requestHasAlreadyBeenRepeated)
            {
                TRACE_MESSAGE("Repeating the same request (without authorization switch), because server was reachable, but unexpectedly closed connection");
                requestHasAlreadyBeenRepeated = true;
                continue;
            }
            return receiveResponseAndDataResult;
        }
        previousResponseReceived = true;
        requestHasAlreadyBeenRepeated = false;

        m_authorizationDriver.authorized(
            // authorization information is reset in case connection is to be closed
            !needCloseConnection
            // authorization success in case file received or successful redirect
            && (httpHeader.isFile()
                 || httpHeader.redirectRequired()
                 || httpHeader.fileNotFound()));

        if(httpHeader.isFile())
        {
            // in case proxy server by some ocassion desided to close
            //  connection after successful file receive event
            if(needCloseConnection)
                m_authorizationDriver.resetNtlmState();

            return CORE_NO_ERROR;
        }

        authorizationTarget = httpHeader.authorizationTarget();
		authorizationWasNeededOnProxy = !proxyAuthorizationHeader.empty();
        lastHttpCode = httpHeader.httpCode();

        // authorization error
        if(httpHeader.authorizationNeeded())
        {
            authorizationWasNeededOnProxy = (authorizationTarget == DownloadProgress::proxyServer);
            if(!switchAuthorization(fileName, relativeUrlPath, httpHeader.authorizationTarget(), proxyAddress,
                authorizationTypeSwitched, ntlmAuthorizationTriedAlready))
            {
                return httpHeader.convertHttpCodeToUpdaterCode();
            }
        }
        // redirect needed
        else if(httpHeader.redirectRequired())
        {
            // protection against infinite loop (according to RFC 2616)
            if(++infiniteRedirectLoop > 2)
            {
                TRACE_MESSAGE2("Infinite redirection loop detected for location '%S'",
                    httpHeader.m_location.toWideChar());
                return CORE_NO_SOURCE_FILE;
            }

            if(httpHeader.m_location.isAbsoluteUri())
                serverAddress.parse(httpHeader.m_location);
            else
            {
                serverAddress.parse(toProtocolPrefix(serverAddress.m_protocol) + serverAddress.m_hostname
                    + serverAddress.m_path + httpHeader.m_location);
                serverAddress.m_path.correctPathDelimiters();
            }

            fileName = serverAddress.m_fileName;
            relativeUrlPath.erase();

            TRACE_MESSAGE3("HTTP Redirect to file '%S' on server %S",
                fileName.toWideChar(), serverAddress.toString().toWideChar());
        }
        // known HTTP results
        else if(httpHeader.resourceUnavailable()
            || httpHeader.fileNotFound())
        {
            return httpHeader.convertHttpCodeToUpdaterCode();
        }
        // retry authorization with other credentials in case Forbidden
         // code received after successful authorization has happened
        else if(httpHeader.retryAuthorization(authorizationWasNeededOnProxy)
            && treat_403_502_httpCodesAs407())
        {
            if(!switchAuthorization(fileName, relativeUrlPath, DownloadProgress::proxyServer,
                proxyAddress, authorizationTypeSwitched, ntlmAuthorizationTriedAlready))
            {
                TRACE_MESSAGE2("Authorization was needed, but error HTTP code '%d' received and switch to next authorization type failed",
                    httpHeader.httpCode());
                return httpHeader.convertHttpCodeToUpdaterCode();
            }
            TRACE_MESSAGE3("Authorization was needed, but error HTTP code '%d' received, try next authorization type '%S'",
                httpHeader.httpCode(),
                toString(m_authorizationDriver.currentAuthorizationType()).toWideChar());
        }
        else
        {
            // processing HTTP code is not implemented
            m_authorizationDriver.resetAuthorizatoinState(proxyAuthorizationMethods);
            return httpHeader.convertHttpCodeToUpdaterCode();
        }
    }

    // Authorization state machine is complex and may contain bug,
     //  that is why protection against infinite loop is implemented
    TRACE_MESSAGE3("Error in HTTP authorization state implementation: credentials '%S', current authorization type '%S'",
        m_authorizationDriver.credentials().toString().toWideChar(),
        toString(m_authorizationDriver.currentAuthorizationType()).toWideChar());
    return CORE_DOWNLOAD_ERROR;
}
コード例 #12
0
ファイル: NetFacHTTP.cpp プロジェクト: hackshields/antivirus
KLUPD::HttpProtocol::~HttpProtocol()
{
    closeSession();
}