Example #1
0
void PokedexData::loadfile()
{
    cleanList();
    string load_str = UserDefault::getInstance()->getStringForKey(pokedex_file_key, "");
//    GAMELOG("PokedexData::loadfile()   load_str = %s", load_str.c_str());
    if(load_str.empty())
        return;
    
    rapidjson::Document doc;
    doc.Parse<0>(load_str.c_str());
    
    if(doc.HasParseError() || !doc.HasMember(pokedex_file_info))
    {
        return;
    }
    rapidjson::Value &array = doc[pokedex_file_info];
    if(array.IsArray())
    {
//        GAMELOG("loadfile  array.Size() = %u", array.Size());
        for(uint i = 0; i < array.Size(); i ++)
        {
            rapidjson::Value &d = array[i];
            Advertise* a = new Advertise();
            if(d.HasMember("adid"))         a->adid = d["adid"].GetString();
            if(d.HasMember("ownerid"))      a->ownerid = d["ownerid"].GetString();
            if(d.HasMember("imgurl"))       a->imgurl = d["imgurl"].GetString();
            if(d.HasMember("logourl"))      a->logourl = d["logourl"].GetString();
            if(d.HasMember("rewardtitle"))  a->rewardtitle = d["rewardtitle"].GetString();
            if(d.HasMember("rewardurl"))    a->rewardurl = d["rewardurl"].GetString();
            if(d.HasMember("datetime"))     a->datetime = d["datetime"].GetInt64();
            v_pokedex.push_back(a);
        }
    }
}
Example #2
0
bool DeckList::loadFromXml(QXmlStreamReader *xml)
{
    if (xml->error()) {
        qDebug() << "Error loading deck from xml: " << xml->errorString();
        return false;
    }

	cleanList();
	while (!xml->atEnd()) {
		xml->readNext();
		if (xml->isStartElement()) {
			if (xml->name() != "cockatrice_deck")
				return false;
			while (!xml->atEnd()) {
				xml->readNext();
				if (!readElement(xml))
					break;
			}
		}
	}
	updateDeckHash();
    if (xml->error()) {
        qDebug() << "Error loading deck from xml: " << xml->errorString();
        return false;
    }
	return true;
}
Example #3
0
int spatch()
{
    ssh_session session = NULL;
    ssh_bind sshbind = NULL;
    sthreadList* list = NULL;

    int port = SERVER_PORT;

    sshbind=ssh_bind_new();
    //session=ssh_new();

    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDPORT, &port);
    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_DSAKEY,
                                            KEYS_FOLDER "ssh_host_dsa_key");
    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_RSAKEY,
                                            KEYS_FOLDER "ssh_host_rsa_key");



    if (ssh_bind_listen(sshbind)<0)
    {
        printf("Error listening to socket: %s\n", ssh_get_error(sshbind));
        return 1;
    }
    printf("Server start on port %d\n", port);

    while(1)
    {
        session=ssh_new();
        if (ssh_bind_accept(sshbind, session) == SSH_ERROR)
        {
            printf("Error accepting a connection: %s\n", ssh_get_error(sshbind));
            ssh_free(session);
        }
        else
        {
            list = newNodeList(list, session);
            if (pthread_create(&(list->thread), NULL, (void*)NewSessionLoop, (void*)&(list->sesData)) != 0)
            {
                sthreadList* tmp;

                ssh_disconnect(session);
                ssh_free(session);
                tmp = list;
                list = list->next;
                free(tmp);
            }
        }
    }
    if (session)
        ssh_free(session);
    cleanList(list);
    ssh_bind_free(sshbind);
    ssh_finalize();
    return 0;
}
Example #4
0
void *clean(void *arg){
	if(sem1 == 1 || sem2 == 1 || sem3 == 1)
		puts("Una delle liste si sta ancora costruendo (non è possibile cancellarla)");
	else{
		puts("Cancello le liste...");
		if(l1 != NULL){
			l1 = cleanList(l1);
		}
		puts("...lista 1 cancellata...");
		if(l2 != NULL){
			l2 = cleanList(l2);
		}
		puts("...lista 2 cancellata...");
		if(l3 != NULL){
			l3 = cleanList(l3);
		}
		puts("...lista 3 cancellata...");
		puts("...tutte le liste svuotate!");
	}
	return arg;
}
Example #5
0
int main(int argc, char* argv[])
{
  char* filename = argv[1];
  linkList *ll = loadData(filename);
  int count = countFirstName(ll,"Jason");
  printf("count is %d\n",count);
  reverseList(ll);
  searchRemoveAge(ll,25);
  removeLastName(ll,"Haining");
  cleanList(ll);
  return 0;
}
Example #6
0
void XdgAutoStart::updateList()
{
    qDebug()<< "XdgAutoStart: getting configpaths";
    QStringList pathList;
    QStringList config_dirs = XdgDirs::configDirs();
    for (int i = 0; i < config_dirs.count(); i++)
        pathList.append(config_dirs.at(i)+"/autostart/");
    pathList.push_back(XdgDirs::configHome()+"/autostart/");

    qDebug() << "XdgAutoStart: beginning building list";

    for (int i=0; i< pathList.length(); i++)
    {
        addDirtoList(pathList.at(i));
    }
    qDebug() << "XdgAutoStart: found "<<m_list.count()<< " items for the autostart...";
    cleanList();
}
Example #7
0
int main(int argc, char* argv[])
{

#if DEBUG
	printf("\n>>==============Debug Value Set=================<<\n");
#endif
	char* file = argv[1];
	dlinklist *newdlinklist = readData(file,1);
	//linkList *newlinkList = readData(file,2); //adding from back
	addatPosition(newdlinklist,2,4.5);
	popFront(newdlinklist);
	popBack(newdlinklist);
	popatPosition(newdlinklist,7);
	popwithValue(newdlinklist,32.34);
	printList(newdlinklist);
	reverseList(newdlinklist);
	printList(newdlinklist);
	float value_f = 33.4;
	searchRemove(newdlinklist,value_f);
	cleanList(newdlinklist);
	return 0;
}
Example #8
0
void iluminatePixel(VECTOR *anchor, VECTOR *rayFromEyeDirection, RGB *color, INTERSECTION *intersection) {

    int sumDiffuse = 0, sumEspecular = 0;
    LIST_NODE_PTR lights = lightsList;
    LIST_NODE_PTR obstacle = NULL;
    long double i = 0.0; //Light Intensity for diffuse illumination
    long double e = 0.0; //Intensity of specular reflexion
    long double productPointResult;
    long double productPointN_L;
    long double lightIntensityThrowObject = 1.0; //Controls the intensity of the light when it pass throw an object, if no object is on the way of the light the intensity is 1

    long double distanceToLight;
    VECTOR vectorToLight_l, vectorToEye_v, vectorReflexionOfL_r;

    //Test that the normal is the correct one
    if (dotProduct(rayFromEyeDirection, &intersection->object.normal) > EPSILON) {
        VECTOR newN;
        newN.x = -1 * intersection->object.normal.x;
        newN.y = -1 * intersection->object.normal.y;
        newN.z = -1 * intersection->object.normal.z;
        intersection->object.dependedNormal = newN;
    }

    while (lights != NULL) {
        LIGHT_POINT currentLight = lights->data.light;
        vectorToLight_l = calculateVectorToLight_L(intersection->intersection, currentLight.position, &distanceToLight);

        //Calculate Vector V, which is a vector to points back to the light, it is the same vector D but with the inverse direction
        vectorToEye_v.x = rayFromEyeDirection->x * -1; //With this is inverse the direction
        vectorToEye_v.y = rayFromEyeDirection->y * -1;
        vectorToEye_v.z = rayFromEyeDirection->z * -1;

        //Calculate Vector R, which is a vector ho is a Reflexion of the vector L taken the VEctor N as reference
        productPointN_L = dotProduct(&intersection->object.dependedNormal, &vectorToLight_l);
        vectorReflexionOfL_r.x = (2 * intersection->object.dependedNormal.x * productPointN_L) - vectorToLight_l.x;
        vectorReflexionOfL_r.y = (2 * intersection->object.dependedNormal.y * productPointN_L) - vectorToLight_l.y;
        vectorReflexionOfL_r.z = (2 * intersection->object.dependedNormal.z * productPointN_L) - vectorToLight_l.z;

        long double fAtt = attenuationFactor(intersection->intersection, currentLight);
        productPointResult = dotProduct(&vectorToLight_l, &intersection->object.dependedNormal);

        if (productPointResult > EPSILON) {

            if (APPLY_SHADOWS) {

                firstIntersection(&intersection->intersection, &vectorToLight_l, &obstacle);

                if (obstacle == NULL) {
                    sumDiffuse = 1;

                    if (APPLY_SPECULAR_REFLEXION) {
                        sumEspecular = 1;
                    }
                } else {
                    lightIntensityThrowObject = obstacle->data.intersection.object.translucencyCoefficient_kt;
                    sumDiffuse = 1;

                    if (APPLY_SPECULAR_REFLEXION) {
                        sumEspecular = 1;
                    }
                }

                //I have to clean the obstacle intersections list, because it depends on the light
                cleanList(&obstacle);
                obstacle = NULL;
            } else {
                sumDiffuse = 1;

                if (APPLY_SPECULAR_REFLEXION) {
                    sumEspecular = 1;
                }
            }

        }

        if (sumDiffuse == 1) {
            i += productPointResult * intersection->object.diffusionCoefficient_Kd * fAtt * (currentLight.intensity_Ip * lightIntensityThrowObject);
        }

        if (sumEspecular == 1) {
            long double dotProductResultRV = dotProduct(&vectorReflexionOfL_r, &vectorToEye_v);
            if (productPointN_L > EPSILON && dotProductResultRV > EPSILON) {
                e += pow(dotProductResultRV, intersection->object.specularReflexionRefinement_Kn) * intersection->object.specularReflexionCoeffient_Ks * (currentLight.intensity_Ip * lightIntensityThrowObject) * fAtt;
            }
        }
        sumDiffuse = 0;
        sumEspecular = 0;
        lights = lights->nextPtr;
        lightIntensityThrowObject = 1.0;
    }

    i += (intersection->object.ambientLightingCoefficient_Ka * ambientLighting_IA);

    if (i > 1.0) {
        i = 1.0;
    }

    color->r = intersection->object.color.r * i;
    color->g = intersection->object.color.g * i;
    color->b = intersection->object.color.b * i;

    if (APPLY_SPECULAR_REFLEXION) {
        color->r = color->r + e * (1.0 - color->r);
        color->g = color->g + e * (1.0 - color->g);
        color->b = color->b + e * (1.0 - color->b);
    }


}
Example #9
0
RGB whichColor(VECTOR *anchor, VECTOR *rayFromEyeDirection, int reflexionLevel, int *setBackground) {
    *setBackground = 0;
    RGB color, reflexionColor, transparencyColor;
    LIST_NODE_PTR intersection = NULL;
    VECTOR vectorToEye_v, vectorReflexionOfV_R;
    long double productPointN_V;

    firstIntersection(anchor, rayFromEyeDirection, &intersection);

    if (intersection == NULL) { //If intersection is equals to NULL
        *setBackground = 1;
        color = backgroundColor;
    } else {

        //Calculate Vector V, which is a vector to points back to the light, it is the same vector D but with the inverse direction
        vectorToEye_v.x = rayFromEyeDirection->x * -1; //With this is inverse the direction
        vectorToEye_v.y = rayFromEyeDirection->y * -1;
        vectorToEye_v.z = rayFromEyeDirection->z * -1;

        iluminatePixel(anchor, rayFromEyeDirection, &color, &intersection->data.intersection);
        if (APPLY_MIRRORS) {
            if (intersection->data.intersection.object.O2 > 0.0 && reflexionLevel > 0) {

                int isReflexionBackground = 0;
                productPointN_V = dotProduct(&intersection->data.intersection.object.dependedNormal, &vectorToEye_v);
                vectorReflexionOfV_R.x = 2 * productPointN_V * intersection->data.intersection.object.dependedNormal.x - vectorToEye_v.x;
                vectorReflexionOfV_R.y = 2 * productPointN_V * intersection->data.intersection.object.dependedNormal.y - vectorToEye_v.y;
                vectorReflexionOfV_R.z = 2 * productPointN_V * intersection->data.intersection.object.dependedNormal.z - vectorToEye_v.z;
                reflexionColor = whichColor(&intersection->data.intersection.intersection, &vectorReflexionOfV_R, reflexionLevel - 1, &isReflexionBackground);


                if (isReflexionBackground == 0) {
                    color.r = intersection->data.intersection.object.O1 * color.r + intersection->data.intersection.object.O2 * reflexionColor.r;
                    color.g = intersection->data.intersection.object.O1 * color.g + intersection->data.intersection.object.O2 * reflexionColor.g;
                    color.b = intersection->data.intersection.object.O1 * color.b + intersection->data.intersection.object.O2 * reflexionColor.b;
                }


                /*
                                color.r = intersection->data.intersection.object.O1 * color.r + intersection->data.intersection.object.O2 * reflexionColor.r;
                                color.g = intersection->data.intersection.object.O1 * color.g + intersection->data.intersection.object.O2 * reflexionColor.g;
                                color.b = intersection->data.intersection.object.O1 * color.b + intersection->data.intersection.object.O2 * reflexionColor.b;
                 */

            }

        }

        if (APPLY_TRANSPARENCY) {
            if (intersection->data.intersection.object.O3 > 0.0 && intersection->nextPtr != NULL) {
                iluminatePixel(anchor, rayFromEyeDirection, &transparencyColor, &intersection->nextPtr->data.intersection);
                color.r += intersection->data.intersection.object.O3 * transparencyColor.r;
                color.g += intersection->data.intersection.object.O3 * transparencyColor.g;
                color.b += intersection->data.intersection.object.O3 * transparencyColor.b;
            }
        }





    }

    cleanList(&intersection);

    return color;
}
Example #10
0
void process_inbound_udp(int sock) {
  #define BUFLEN 1500
  struct sockaddr_in from;
  socklen_t fromlen;
  char buf[BUFLEN];

  fromlen = sizeof(from);
  spiffy_recvfrom(sock, buf, BUFLEN, 0, (struct sockaddr *) &from, &fromlen);
	//recvfrom(sock, buf, BUFLEN, 0, (struct sockaddr *) &from, &fromlen);
  packetHead* pHead = (packetHead* )buf;
  peerEle* peer = resolvePeer(from, peerList);

  
  switch(pHead->type){
	case WHOHAS:{
		printf("Recieve WHOHAS request\n");
		void* ihavep = ihaveCons(buf, &haschunkList);
		if( ihavep!= NULL){
			unsigned int bufSize = ((packetHead *)ihavep)->packLen;
			spiffy_sendto(sock, ihavep, bufSize, 0, (struct sockaddr *) &from, fromlen);
			//sendto(sock, ihavep, bufSize, 0, (struct sockaddr *) &from, fromlen);
			time(&start);
		}
		break;
	}
	case IHAVE:{
		printf("Receieve IHAVE request\n");
		printf("packet length is %u\n", pHead->packLen);
		char tmp[sizeofHash];
		memcpy(tmp, (buf+20), sizeofHash);
		printf("chunk hash: %s\n", tmp);
		peerEle* thisPeer = resolvePeer(from, peerList);
		time_t finish;
		time(&finish);
		if( thisPeer == NULL ){
			printf("RESOLVE FAILED\n");
		}
		thisPeer->rtt = difftime(finish, start);
		AddResponses(thisPeer, buf, &chunkList, sock);
		printChunkList(chunkList);
		break;
	}
	case GET:{
		printf("Receive GET Request\n");
		printf("packet length is %u\n", pHead->packLen);
		
		//check for free connections
		printf("maxcon:%d id: %d numout: %d\n",maxCon,mePeer->id,mePeer->numOut);
		if(mePeer->numOut == maxCon){
			chunkEle* dcp = lookupChunkHash((buf+20),&haschunkList);
			void* deniedp = deniedCons(dcp->chunkId);
			spiffy_sendto(sock, deniedp, headerSize, 0, (struct sockaddr *) &peer->cli_addr, sizeof(peer->cli_addr));
			//sendto(sock, deniedp, headerSize, 0, (struct sockaddr *) &peer->cli_addr, sizeof(peer->cli_addr));
			break;
		}
		

		chunkEle* thisWindow = buildNewWindow(&windowSets, &haschunkList, peer, masterDataFilePath, buf);

		// send first element, no need to clean or fill
		sendWindow(thisWindow, sock);
		mePeer->numOut++;//increase num
		break;
	}
	case DATA:{
		unsigned int bufSize = ((packetHead *)buf)->packLen;
		void* newBuf = malloc(bufSize);
		memcpy(newBuf,buf,bufSize);
		chunkEle* cep = resolveChunk(peer, chunkList);
		
		getRetryTimer = 0;

		// reject packets from finished chunk
		if(cep && (cep->chunkId != ((packetHead*)buf)->ackNum)){
			printf("Wrong chunk!\n");
			break;
		}

		orderedAdd(cep,newBuf);

		printf("Receive data packet %d, with size %d \n", ((packetHead *)buf)->seqNum, ((packetHead *)buf)->packLen - headerSize);

		findMex(cep);
		printPacketList(cep->packetList);
		void* packet = ackCons(cep->nextExpectedSeq - 1);

		printf("Send Ack %d\n", cep->nextExpectedSeq - 1);
		spiffy_sendto(sock, packet, headerSize, 0, (struct sockaddr *) &peer->cli_addr, sizeof(peer->cli_addr));
		//sendto(sock, packet, headerSize, 0, (struct sockaddr *) &peer->cli_addr, sizeof(peer->cli_addr));
		printf("bytes read for hash %s : %d\n",cep->chunkHash, cep->bytesRead);
		//check if finish receiving the whole chunk
		if(cep->bytesRead == chunkSize ){
			if ( cep->fromThisPeer->inUse == 1){
			printf("Sucessfully receive the chunk %s\n", cep->chunkHash);
			chunkList.finished ++;
			cep->fromThisPeer->inUse = 0;
			cep->inProgress = 0;
			mePeer->numOut--;
			}
			printf("FINISHED %d\n", chunkList.finished);
			if(chunkList.finished == chunkList.length){
				printf("Finish receiving the whole file\n");
				// merge the chunks and write to the corresponding output file
				buildOuputFile(outputFile, &chunkList);
				fclose(outputFile);
				printf("GOT %s\n",outputFilePath);
			}else{
				// try to send rest of pending get requests 
				// they are deferred to make sure no concurrent downloading from the same peer
				sendPendingGetRequest(&chunkList, sock);
			}
		}
		
		break;
	}
	case ACK:{
		chunkEle* cep = resolveChunk(peer, windowSets);

		if ( cep->inProgress == 0){
			break;
		}
		//check which wether SLOWSTART or CONGAVOID
		if(cep->mode == SLOWSTART){
			cep->windowSize++;
			printf("####in slow start\n");
		}
		else
			printf("@@@@in cong avoid rtt: %f\n",cep->fromThisPeer->rtt);
		//check if enough to enter cong avoid
		if(cep->windowSize == cep->ssthresh)
			cep->mode = CONGAVOID;

		//check for no ack in rtt
		if((cep->mode == CONGAVOID) && (cep->haveACK == 0)){
			cep->windowSize++;
			printf("IIIIincreasing in cong avoid\n");
		}

		//set ack
		cep->haveACK = 1;

		printf("Receive Ack %d\n", *(int*)(buf+12));
		if( (cep->lastAcked) && ((packetHead* )(cep->lastAcked->data))->seqNum == ((packetHead* )(buf))->ackNum ){
			cep->lastAckedCount ++;
			printf("Incrementing last ack counter for %d to %d\n", ((packetHead* )(buf))->ackNum,cep->lastAckedCount);
			if( cep->lastAckedCount  == 3 ){
				//cut ssthresh in half and set window 1
				cep->ssthresh = halve(cep->windowSize);
				cep->windowSize = 1;
				cep->mode = SLOWSTART;

				//reset this ones time
				time(&cep->afterLastAckedTime);

				//try retrasmit
				cep->lastAckedCount = 0;
				node* retry = cep->lastAcked->prevp;
				printf("Retramsmit packet %d\n", ((packetHead* )retry->data)->seqNum);
				spiffy_sendto(sock, retry->data, ((packetHead* )retry->data)->packLen, 0, (struct sockaddr *) &peer->cli_addr, sizeof(peer->cli_addr));
				break;
			}

		}else{
			cep->lastAcked = resolveLastPacketAcked( ((packetHead*)buf)->ackNum, cep);
			cleanList(cep);
			time(&cep->afterLastAckedTime);
		}
		
		//check if finish sending the whole chunk
		if( cep->bytesRead == chunkSize ){
			printf("Successfully send the chunk %s\n", cep->chunkHash);
			if(cep->lastAcked == cep->lastSent){
				// some clear below
				printf("All sent packets have been acked\n");
				cep->inProgress = 0;
				mePeer->numOut--;
			}else{
				printf("lastAcked:%d, lastSent:%d\n",((packetHead*)cep->lastAcked->data)->seqNum, ((packetHead*)cep->lastSent->data)->seqNum );
			}
			
		}else{
			cleanList(cep);
			fillWindow(cep);
			sendWindow(cep, sock);
		}

		printPacketList(cep->packetList);
		printf("window: %d, ssthresh: %d, mode: %d\n",cep->windowSize, cep->ssthresh,
			cep->mode);
		break;
	}
	case DENIED:{
		printf("Received a denied ack!\n");
		chunkEle* cep = resolveChunk(peer, chunkList);
		//fclose(outputFile);
		time(&getRetryTimer);
		cep->fromThisPeer->inUse = 0;
		break;
	}

	}

  printf("PROCESS_INBOUND_UDP SKELETON -- replace!\n"
	 "Incoming message from %s:%d\n%s\n\n", 
	 inet_ntoa(from.sin_addr),
	 ntohs(from.sin_port),
	 buf);
}
Example #11
0
int main(int argc, char **argv)
{
	//Check whether user has entered enough arguments
	if(argc < 2)
	{
		printf("Usage: ./firewall mode rules_file [input pcap file] [output pcap file] 1/0\n",
				"           Mode: 1/2\n"
				"           Debugging: On/Off\n");
	}
    char errbuf[100];
    int mode = atoi(argv[1]);

    //Convert rules from File to linkedlist
    createList(argv[2]);
    //Print the rules for Debugging
    //iterList();

    //Initialize the hashtables
	state_tbl = NULL;
	arp_tbl = NULL;

	//Intitialze the locks
	if (pthread_rwlock_init(&arp_lock,NULL) != 0)
	{
		printf("ARP lock init failed.\n");
	}
	if (pthread_rwlock_init(&state_lock,NULL) != 0)
	{
		printf("State lock init failed.\n");
	}

	//If mode = 1 then use the interfaces to capture packets
    if(mode == 1)
    {
    	debugging = atoi(argv[3]);

    	pthread_t threads[4];
		//Open the interface handlers
		in_handle = pcap_open_live(INT_IN,65536,1,0,errbuf);
		out_handle = pcap_open_live(INT_OUT,65536,1,0,errbuf);

		//Create four threads
		pthread_create(threads + 0, NULL, func1, (void *) 0);
		pthread_create(threads + 1, NULL, func2, (void *) 1);
		pthread_create(threads + 2, NULL, func3, (void *) 2);
		pthread_create(threads + 3, NULL, func4, (void *) 3);

		//Wait for the four threads
		pthread_join(threads[0], NULL);
		pthread_join(threads[1], NULL);
		pthread_join(threads[2], NULL);
		pthread_join(threads[3], NULL);

		pthread_exit(NULL);
	}
    //Else open the input pcap file for the processing and write to output pcap file
	else
	{
		//Check for the valid arguments
		if(argc < 5)
		{
			printf("Usage: ./firewall mode rule_file [input pcap file] [output pcap file] 0/1\n",
				"           Mode: 1/2\n"
				"           Debug:On/Off\n");
		}
		debugging = atoi(argv[5]);
		in_handle = pcap_open_offline(argv[3],errbuf);
		//802.3 = 1 - link type
		//open new pcap handler
		out_handle = pcap_open_dead(1,65536);
		//open the file with the handler
		dumper = pcap_dump_open(out_handle, argv[4]);
		capture_loop(in_handle, -1, (pcap_handler)parse_packet_file, (u_char*)dumper);
	}
    //Memory cleanup
    cleanList();
    return 0;
}
Example #12
0
void stateMachine(womim* p_womim) {
    int id;
    MUTEX_LOCK(stateMachineMutex);
    //printf("State = %s, receive message = %s\n", stateToStr(automatonState), msgTypeToStr(p_womim->msg.type));
    switch (automatonState) {
    case OFFLINE_CONNECTION_ATTEMPT:
        switch (p_womim->msg.type) {
        case NAK_INSERT:
        case DISCONNECT_PRED:
        case DISCONNECT_SUCC:
            freeWomim(p_womim);
            nextState(WAIT);
            break;
        case INSERT:
            prec = p_womim->msg.body.insert.sender;
            sendOther(p_womim->msg.body.insert.sender, true, NAK_INSERT, myAddress);
            freeWomim(p_womim);
            break;
        case ACK_INSERT:
            prec = p_womim->msg.body.ackInsert.sender;
            openConnection(prec, true);
            sendOther(prec, true, NEWSUCC, myAddress);
            freeWomim(p_womim);
            nextState(OFFLINE_CONFIRMATION_WAIT);
            break;
        default:
            ERROR_AT_LINE_WITHOUT_ERRNUM(EXIT_FAILURE, __FILE__, __LINE__,
                                         "unexpected case : received message %s in state %s",
                                         msgTypeToStr(p_womim->msg.type), stateToStr(automatonState));
            break;
        }
        break;

    case OFFLINE_CONFIRMATION_WAIT:
        switch (p_womim->msg.type) {
        case NEWSUCC:
        case DISCONNECT_PRED:
        case DISCONNECT_SUCC:
            freeWomim(p_womim);
            nextState(WAIT);
            break;
        case INSERT:
            sendOther(p_womim->msg.body.insert.sender, true, NAK_INSERT, myAddress);
            freeWomim(p_womim);
            break;
        case TRAIN:
            id = (int) p_womim->msg.body.train.stamp.id;
            if (addrIsMember(myAddress, p_womim->msg.body.train.circuit)) {
                p_womim->msg.body.train.stamp.lc++;
            }
            releaseWiw(&(lts[id].w.w_w));
            lts[id].w.len = 0;
            if (firstWagon(&(p_womim->msg)) != NULL ) {
                lts[id].w.w_w.p_wagon = firstWagon(&(p_womim->msg));
                lts[id].w.w_w.p_womim = p_womim;
                lts[id].w.len = (p_womim->msg.len - sizeof(stamp) - sizeof(int)
                                 - sizeof(MType) - sizeof(address));
                // We do not need to lock the p_womim->pfx.mutex as we are the only thread
                // accessing to counter
                p_womim->pfx.counter++;
            }
            lts[id].circuit = p_womim->msg.body.train.circuit;
            lts[id].stamp = p_womim->msg.body.train.stamp;
            sendTrain(succ, false, lts[id]);
            if (isInLts(myAddress, lts)) {
#ifdef INSERTION_TEST
                gettimeofday(&trainDate, NULL);
                timersub(&trainDate, &offlineInitDate, &insertionDuration);
                floatInsertionDuration = ((double) insertionDuration.tv_sec) * 1000
                                         + ((double) insertionDuration.tv_usec) / 1000;
                printf("My insertion duration : %.3lfms\n", floatInsertionDuration);
                printf("number of times automaton has been in state WAIT ; %llu\n", counters.wait_states);
#endif /* INSERTION_TEST */
                lis = p_womim->msg.body.train.stamp.id;
                signalArrival(myAddress, lts[lis].circuit);
                nextState(SEVERAL);
                int rc = sem_post(sem_init_done);
                if (rc)
                    ERROR_AT_LINE(EXIT_FAILURE, errno, __FILE__, __LINE__,
                                  "error in sem_post");
            }
            freeWomim(p_womim);
            break;
        default:
            ERROR_AT_LINE_WITHOUT_ERRNUM(EXIT_FAILURE, __FILE__, __LINE__,
                                         "unexpected case : received message %s in state %s",
                                         msgTypeToStr(p_womim->msg.type), stateToStr(automatonState));
            freeWomim(p_womim);
            break;
        }
        break;

    case WAIT:
        freeWomim(p_womim);
        break;

    case ALONE_INSERT_WAIT:
        switch (p_womim->msg.type) {
        case DISCONNECT_PRED:
        case DISCONNECT_SUCC:
            // May happen in case there are 2 processes on the circuit and one process dies
            // The other process receives DISCONNECT in SEVERAL state and switched to
            // ALONE_INSERT_WAIT state, where it receives the DISCONNECT corresponding
            // to the loss of the second connection
            freeWomim(p_womim);
            break;
        case INSERT:
            MUTEX_LOCK(mutexWagonToSend);
            sendOther(p_womim->msg.body.insert.sender, true, ACK_INSERT, myAddress);
            prec = p_womim->msg.body.insert.sender;
            freeWomim(p_womim);
            nextState(ALONE_CONNECTION_WAIT);
            MUTEX_UNLOCK(mutexWagonToSend);
            break;
        default:
            ERROR_AT_LINE_WITHOUT_ERRNUM(EXIT_FAILURE, __FILE__, __LINE__,
                                         "unexpected case : received message %s in state %s",
                                         msgTypeToStr(p_womim->msg.type), stateToStr(automatonState));
            freeWomim(p_womim);
            break;
        }
        break;

    case ALONE_CONNECTION_WAIT:
        switch (p_womim->msg.type) {
        case DISCONNECT_PRED:
            nextState(ALONE_INSERT_WAIT);
            freeWomim(p_womim);
            break;
        case INSERT:
            // In the PhD-thesis algorithm, we are supposed to do a
            // saveUntilNextstate(p_womim). Sending a NAK_INSERT is more simple.
            sendOther(p_womim->msg.body.insert.sender, true, NAK_INSERT, myAddress);
            freeWomim(p_womim);
            break;
        case NEWSUCC:
            succ = p_womim->msg.body.newSucc.sender;
            int i;
            for (i = 1; i <= ntr; i++) {
                int id = ((lis + i) % ntr);
                (lts[(int) id]).stamp.lc += 1;
                (lts[(int) id]).circuit = myAddress | prec;
                (lts[(int) id]).w.w_w.p_wagon = NULL;
                (lts[(int) id]).w.w_w.p_womim = NULL;
                (lts[(int) id]).w.len = 0;
                sendTrain(succ, false, lts[(int) id]);
            }
            freeWomim(p_womim);
            nextState(SEVERAL);
            break;
        default:
            ERROR_AT_LINE_WITHOUT_ERRNUM(EXIT_FAILURE, __FILE__, __LINE__,
                                         "unexpected case : received message %s in state %s",
                                         msgTypeToStr(p_womim->msg.type), stateToStr(automatonState));
            freeWomim(p_womim);
            break;
        }
        break;

    case SEVERAL:
        switch (p_womim->msg.type) {
        case TRAIN:
            if (addrIsMember(myAddress, p_womim->msg.body.train.circuit)) {
                if (isRecentTrain(p_womim->msg.body.train.stamp, lts, lis)) {
#ifdef INSERTION_TEST
                    if (theLostPrec != 0) {
                        if (recentlyLostMyPred) {
                            gettimeofday(&firstRecentTrainDate, NULL);
                            recentlyLostMyPred = false;
                        }
                        if (!isInLts(theLostPrec,lts)) {
                            gettimeofday(&firstNewCircuitDate, NULL);
                            theLostPrec = 0;

                            timersub(&firstRecentTrainDate, &discoPredDate, &recoveryRecentTrainDuration);
                            timersub(&firstNewCircuitDate, &discoPredDate, &recoveryNewCircuitDuration);

                            floatRecoveryRecentTrainDuration = ((double) recoveryRecentTrainDuration.tv_sec) * 1000
                                                               + ((double) recoveryRecentTrainDuration.tv_usec) / 1000;

                            floatRecoveryNewCircuitDuration = ((double) recoveryNewCircuitDuration.tv_sec) * 1000
                                                              + ((double) recoveryNewCircuitDuration.tv_usec) / 1000;

                            printf("Disconnection pred recovery :\n");
                            printf("\t- First recent train after %.3lfms\n", floatRecoveryRecentTrainDuration);
                            printf("\t- Up-to-date circuit received after %.3lfms\n", floatRecoveryNewCircuitDuration);

                        }
                    }
#endif /* INSERTION_TEST */
                    trainHandling(p_womim);
                    lis = p_womim->msg.body.train.stamp.id;
                    if (succ != 0)
                        sendTrain(succ, false, lts[lis]);
                }
            } else {
                ERROR_AT_LINE_WITHOUT_ERRNUM(EXIT_FAILURE, __FILE__, __LINE__,
                                             "myAddress not in the circuit ==> Suicide");
            }
            freeWomim(p_womim);
            break;
        case INSERT:
            closeConnection(prec, true);
            sendOther(p_womim->msg.body.insert.sender, true, ACK_INSERT, prec);
            prec = p_womim->msg.body.insert.sender;
            addrAppendArrived(&cameProc, prec);
            freeWomim(p_womim);
            break;
        case NEWSUCC:
            if (succ != 0)
                closeConnection(succ, false);
            succ = p_womim->msg.body.newSucc.sender;
            int i;
            for (i = 1; i <= ntr; i++) {
                sendTrain(succ, false, lts[(lis + i) % ntr]);
            }
            freeWomim(p_womim);
            break;
        case DISCONNECT_PRED:
#ifdef INSERTION_TEST
            gettimeofday(&discoPredDate, NULL);
            recentlyLostMyPred = true;
            theLostPrec = prec;
#endif /* INSERTION_TEST */
            MUTEX_LOCK(mutexWagonToSend);
            while (!(addrIsEqual(prec,myAddress))) {
                if (openConnection(prec, true) != (-1)) {
                    sendOther(prec, true, NEWSUCC, myAddress);
                    freeWomim(p_womim);
                    nextState(SEVERAL);
                    MUTEX_UNLOCK(stateMachineMutex);
                    MUTEX_UNLOCK(mutexWagonToSend);
                    return;
                }
                addrAppendGone(&cameProc, &goneProc, prec);
                prec = addrPrec(prec, lts[lis].circuit);
            }
            signalDepartures(goneProc, lts[lis].circuit, true);
            goneProc = 0;
            int aRound;
            for (aRound = 1; aRound <= NR; aRound++) {
                int i;
                for (i = 1; i <= ntr; i++) {
                    int id = (lis + i) % ntr;
                    int round = (lts[id].stamp.round + aRound) % NR;
                    bqueueExtend(wagonsToDeliver, unstableWagons[id][round]);
                    cleanList(unstableWagons[id][round]);
                }
            }
            bqueueEnqueue(wagonsToDeliver, wagonToSend);
            wagonToSend = newWiw();
            freeWomim(p_womim);
#ifdef INSERTION_TEST
            gettimeofday(&firstNewCircuitDate, NULL);
            timersub(&firstNewCircuitDate, &discoPredDate, &recoveryNewCircuitDuration);
            floatRecoveryNewCircuitDuration = ((double) recoveryNewCircuitDuration.tv_sec) * 1000
                                              + ((double) recoveryNewCircuitDuration.tv_usec) / 1000;
            printf("I am alone !\n"
                   "%.3lfms since the DISCONNECT_PRED message\n", floatRecoveryNewCircuitDuration);
#endif /* INSERTION_TEST */
            nextState(ALONE_INSERT_WAIT);
            MUTEX_UNLOCK(stateMachineMutex);
            MUTEX_UNLOCK(mutexWagonToSend);
            pthread_cond_signal(&condWagonToSend);
            break;
        case DISCONNECT_SUCC:
            succ = 0;
            freeWomim(p_womim);
            break;
        default:
            ERROR_AT_LINE_WITHOUT_ERRNUM(EXIT_FAILURE, __FILE__, __LINE__,
                                         "unexpected case : received message %s in state %s",
                                         msgTypeToStr(p_womim->msg.type), stateToStr(automatonState));
            break;
        }
        break;
    default:
        ERROR_AT_LINE_WITHOUT_ERRNUM(EXIT_FAILURE, __FILE__, __LINE__, "Unknown state : %d",
                                     automatonState);
        freeWomim(p_womim);
        break;
    }
    MUTEX_UNLOCK(stateMachineMutex);
}
Example #13
0
void trainHandling(womim *p_womim) {
    int id = p_womim->msg.body.train.stamp.id;
    int round = p_womim->msg.body.train.stamp.round;
    wagon *p_wag;

    counters.recent_trains_received++;
    counters.recent_trains_bytes_received += p_womim->msg.len;
    //printf("TRAIN id=%d\n", id);
    if (round == lts[id].stamp.round) {
        round = (round + 1) % nbRounds;
    }
    if (requiredOrder != CAUSAL_ORDER) {
        // Thus (requiredOrder == TOTAL_ORDER) || (requiredOrder == UNIFORM_TOTAL_ORDER))
        bqueueExtend(wagonsToDeliver, unstableWagons[id][(round + 1) % nbRounds]);
        cleanList(unstableWagons[id][(round + 1) % nbRounds]);
    }
    if (id == 0) {
        lts[0].circuit = addrUpdateCircuit(p_womim->msg.body.train.circuit,
                                           myAddress, cameProc, goneProc);
        cameProc = 0;
        signalDepartures(goneProc, lts[0].circuit, false);
        goneProc = 0;
    } else {
        lts[id].circuit = lts[0].circuit;
    }

    releaseWiw(&(lts[id].w.w_w));
    lts[id].w.len = 0;
    freeWiw(lts[id].p_wtosend);
    lts[id].p_wtosend = NULL;

    for (p_wag = firstWagon(&(p_womim->msg)); p_wag != NULL ;
            p_wag = nextWagon(p_womim, p_wag)) {
        if (addrIsMember(p_wag->header.sender, lts[id].circuit)
                && !(addrIsMember(p_wag->header.sender, goneProc))
                && !(addrIsMine(p_wag->header.sender))) {
            // We add a wiw (corresponding to this p_wag) to unstableWagons[id][round]
            // (in case of TOTAL_ORDER or UNIFORM_TOTAL_ORDER) or directly to
            // wagonsToDeliver (in case of CAUSAL_ORDER)
            wiw *wi = malloc(sizeof(wiw));
            assert(wi != NULL);
            wi->p_wagon = p_wag;
            wi->p_womim = p_womim;
            MUTEX_LOCK(p_womim->pfx.mutex);
            p_womim->pfx.counter++;
            MUTEX_UNLOCK(p_womim->pfx.mutex);
            if (requiredOrder != CAUSAL_ORDER) {
                // Thus (requiredOrder == TOTAL_ORDER) || (requiredOrder == UNIFORM_TOTAL_ORDER))
                listAppend(unstableWagons[id][round], wi);
            } else {
                bqueueEnqueue(wagonsToDeliver, wi);
            }

            // Shall this wagon be sent to our successor
            if (!addrIsEqual(succ,p_wag->header.sender)) {
                // Yes, it must sent
                if (lts[id].w.w_w.p_wagon == NULL ) {
                    // lts must be updated to point on the first wagon to be sent
                    lts[id].w.w_w.p_wagon = p_wag;
                    lts[id].w.w_w.p_womim = p_womim;
                    MUTEX_LOCK(lts[id].w.w_w.p_womim->pfx.mutex);
                    lts[id].w.w_w.p_womim->pfx.counter++;
                    MUTEX_UNLOCK(lts[id].w.w_w.p_womim->pfx.mutex);
                }
                // We adapt len
                lts[id].w.len += p_wag->header.len;
            }
        }
    }

    lts[id].stamp.round = (char) round;
    MUTEX_LOCK(mutexWagonToSend);
    if (firstMsg(wagonToSend->p_wagon) != NULL ) {
        wagonToSend->p_wagon->header.round = round;

        // We add a wiw (corresponding to this p_wag) to wagonToSend
        wiw *wi = malloc(sizeof(wiw));
        assert(wi != NULL);
        *wi = *wagonToSend;
        // We do not need to lock wagonToSend->p_wagon->pfx.mutex
        // as we are for the moment alone to access to
        // wagonToSend->p_wagon->pfx.counter
        wagonToSend->p_womim->pfx.counter++;
        if (requiredOrder != CAUSAL_ORDER) {
            // Thus (requiredOrder == TOTAL_ORDER) || (requiredOrder == UNIFORM_TOTAL_ORDER))
            listAppend(unstableWagons[id][round], wi);
        } else {
            bqueueEnqueue(wagonsToDeliver, wi);
        }

        lts[id].p_wtosend = wagonToSend;

        wagonToSend = newWiw();
    }
    MUTEX_UNLOCK(mutexWagonToSend);
    pthread_cond_signal(&condWagonToSend);

    lts[id].stamp.lc = p_womim->msg.body.train.stamp.lc + 1;
}
Example #14
0
PokedexData::~PokedexData()
{
    cleanList();
}
Example #15
0
bool DeckList::loadFromStream_Plain(QTextStream &in)
{
	cleanList();

	InnerDecklistNode *main = 0, *side = 0;
	bool inSideboard = false;

	int okRows = 0;
	while (!in.atEnd()) {
		QString line = in.readLine().simplified();
		if (line.startsWith("//"))
			continue;

		InnerDecklistNode *zone;
		if (line.startsWith("Sideboard", Qt::CaseInsensitive)) {
			inSideboard = true;
			continue;
		} else if (line.startsWith("SB:", Qt::CaseInsensitive)) {
			line = line.mid(3).trimmed();
			if (!side)
				side = new InnerDecklistNode("side", root);
			zone = side;
		} else if (inSideboard) {
			if (!side)
				side = new InnerDecklistNode("side", root);
			zone = side;
		} else {
			if (!main)
				main = new InnerDecklistNode("main", root);
			zone = main;
		}

		// Filter out MWS edition symbols and basic land extras
		QRegExp rx("\\[.*\\]");
		line.remove(rx);
		rx.setPattern("\\(.*\\)");
		line.remove(rx);
		//Filter out post card name editions
		rx.setPattern("\\|.*$");
		line.remove(rx);
		line = line.simplified();


		int i = line.indexOf(' ');
		bool ok;
		int number = line.left(i).toInt(&ok);
		if (!ok)
			continue;

		QString cardName = line.mid(i + 1);
        // Common differences between cockatrice's card names
        // and what's commonly used in decklists
		rx.setPattern("’");
        cardName.replace(rx, "'");
		rx.setPattern("Æ");
		cardName.replace(rx, "AE");
		rx.setPattern("^Aether");
		cardName.replace(rx, "AEther");
		rx.setPattern("\\s*[&|/]{1,2}\\s*");
		cardName.replace(rx, " // ");

		++okRows;
		new DecklistCardNode(cardName, number, zone);
	}
	updateDeckHash();
	return (okRows > 0);
}