Example #1
0
int init(int n,
         int k,
         int p,
         int x1,
         int y1,
         int x2,
         int y2) {
    /// Validates initialization.
    if (!validInitialization(n, k, p, x1, y1, x2, y2)) {
        return ERROR;
    }

    /// Checks if first player initialized game already.
    if (currentGame.isInitialized) {
        return ERROR;
    }

    if (!currentGame.isInitialized) {
        currentGame.mapSize = n;
        currentGame.maxRound = k;
        currentGame.startingX1 = x1;
        currentGame.startingY1 = y1;
        currentGame.startingX2 = x2;
        currentGame.startingY2 = y2;

        /// Initializes last round to 0, so pawns can move immediately.
        /// Places them on 4 fields next to each other in same row, starting from king.
        pawn *kingA = newPawn(x1, y1, currentGame.currentRound - 1, KING_PLAYER_A_ID);
        pawn *peasantA = newPawn(x1 + 1, y1, currentGame.currentRound - 1, PEASANT_PLAYER_A_ID);
        pawn *knight1A = newPawn(x1 + 2, y1, currentGame.currentRound - 1, KNIGHT_PLAYER_A_ID);
        pawn *knight2A = newPawn(x1 + 3, y1, currentGame.currentRound - 1, KNIGHT_PLAYER_A_ID);

        hashmapPut(currentGame.gameMap, kingA);
        hashmapPut(currentGame.gameMap, peasantA);
        hashmapPut(currentGame.gameMap, knight1A);
        hashmapPut(currentGame.gameMap, knight2A);

        pawn *kingB = newPawn(x2, y2, currentGame.currentRound - 1, KING_PLAYER_B_ID);
        pawn *peasantB = newPawn(x2 + 1, y2, currentGame.currentRound - 1, PEASANT_PLAYER_B_ID);
        pawn *knight1B = newPawn(x2 + 2, y2, currentGame.currentRound - 1, KNIGHT_PLAYER_B_ID);
        pawn *knight2B = newPawn(x2 + 3, y2, currentGame.currentRound - 1, KNIGHT_PLAYER_B_ID);

        hashmapPut(currentGame.gameMap, kingB);
        hashmapPut(currentGame.gameMap, peasantB);
        hashmapPut(currentGame.gameMap, knight1B);
        hashmapPut(currentGame.gameMap, knight2B);
    }

    if (!currentGame.isInitialized) {
        currentGame.isInitialized = true;
    }

    if (p != 1 && p != 2) { ///< Wrong player initialization.
        return ERROR;
    }

    return GAME_OK;
}
Example #2
0
/**
* lockNodes:<p>
* Provide the possibility to lock new entities during the transaction
*/
int transactionLockNodes(Transaction transaction,int lock, int force, Node nodes[] ,int nodesLenght){
    TransactionInternal*internal=(TransactionInternal*)transaction;
    if(nodes==NULL){
        return NULL_NODE;
    }
    if(nodesLenght<=0){
        return NULL_NODE;
    }
    if (internal->transaction!=NULL){
        transactionLockNodes(internal->transaction,lock,force,nodes,nodesLenght);
    }else{
        if(lock==TRUE){
            // Lock the entities in the server
            schemaAdapterLockNodes(internal->scheamAdapter,lock, force, nodes,nodesLenght);
            // Now that this schema owns the entities we can add them to the transaction
            int i;
            Node node;
            for (i=0;i<nodesLenght;i++){
               node=nodes[i];
               hashmapPut(internal->transactionEntities,node->id,node);
            }
        }else{
            return CAN_NOT_UNLOCK_ENTITIES_DURING_TRANSACTION;
        }
    }
}
Example #3
0
char *tboot_config_set(char *key, char *value)
{
	int i;
	int valid_key;

	if (!tboot_config) {
		pr_error("tboot config wasn't init.\n");
		return NULL;
	}

	valid_key = 0;
	for (i = 0; tc_keys[i]; i++) {
		if (!strcmp(key, tc_keys[i])) {
			valid_key = 1;
			break;
		}
	}

	if (!valid_key) {
		pr_error("invalid tboot config keyword:%s\n", key);
		return NULL;
	}

	return hashmapPut(tboot_config, (void *)key, (void *)value);
}
Example #4
0
    /**
     * createNode method<p>
     * create node inside transaction<p>
     * Like the non transactional schemaAdapter in create new entity,<p>
     * but unlike the non transactional schemaAdapter, the change doesn't the effect in the server until they will be commited
     */
    int transactionCreateNode(Transaction transaction,StringHashMap attributes,Node *node){
    TransactionInternal*internal=(TransactionInternal*)transaction;
    int result;
    if(internal->transaction!=NULL){
        result=transactionCreateNode(internal->transaction,attributes,node);
    }else{
        int schemaId=internal->sessionMetaData->schemaId;
        int coreManagerId=internal->sessionMetaData->coreManagerId;
        int sessionId=internal->sessionMetaData->id;
        int lockTimeout=schemaAdapterGetLockTimeout(internal->scheamAdapter);
        Command command = commandBuilderBuildCreateNode(TRUE, schemaId, coreManagerId, sessionId, lockTimeout, attributes);
        int entityId=idProviderGetTempId(internal->idProvider);
        int true=TRUE;
        commandPush(command,ENTITY_ID, INTEGER,&entityId);
        commandPush(command,TRANSACTION, INTEGER, &true);
        commandPush(command,COPY_OF_ENTITY_ID, INTEGER, &entityId);
        commandPush(command,LOCK, INTEGER, true);
        
        result=commandExecuterConsume(internal->commandExecutor,command);
        registryGetNode(internal->registry,entityId,node);
        hashmapPut(internal->transactionEntities,entityId,node);
        arrayListAddAll(internal->commandList,command);
    }
    return result;
}
Example #5
0
static bool read(Hashmap *m, FILE *f) {
    struct entry *e = malloc(sizeof (struct entry));
    if (!e)
        return false;

    fread(e, sizeof (struct entry), 1, f);
    hashmapPut(m, &e->id, &e->sid);
    return true;
}
Example #6
0
void texture_cache_unload(struct texture_cache* self, const char* key)
{
    struct texture* tex = hashmapGet(self->cache, (void*)key);
    if (!tex) {
        hashmapPut(self->cache, (void*)key, NULL);
        texture_unload(tex);
    } else {
        fprintf(stderr, "texture %s has already been removed", key);
    }
}
Example #7
0
// TODO : export load from binary data in Lua.
struct texture* texture_cache_load(struct texture_cache* self,
                                   const char* key)
{
    struct texture* tex = hashmapGet(self->cache, (void*)key);
    if (!tex) {
        tex = texture_load_from_png(key);
        strncpy(tex->name, key, strlen(key));
        printf("texture load key = %s, tex = %p\n", key, tex);
        hashmapPut(self->cache, (void*)tex->name, (void*)tex);
    } else {
        tex->ref++;
    }
    return tex;
}
Example #8
0
int validationManagerValidateRefferance(ValidationManager validationManager,int entityId){
    ValidationManagerStruct* internal=(ValidationManagerStruct*)validationManager;
    ValidationDataStructure * data;
    HashMap chidrenMap;
    hashmapGet(internal->parentChildrenRelationEntities,entityId,&chidrenMap);
    if(chidrenMap==NULL){
       chidrenMap = stringHashmapCreate(SMALL_CONTAINER_SIZE);
       hashmapPut(internal->parentChildrenRelationEntities,entityId,chidrenMap);
    }
    ArrayList parents;
     hashmapGet(internal->childrenParentRelationEntities,entityId,&parents);
    if(parents==NULL){
       parents = arrayListCreate();
       hashmapPut(internal->childrenParentRelationEntities,entityId,parents);
    }
    int parentSize=arrayListSize(parents);
    int childrenSize=stringHashmapLength(chidrenMap);
    if(parentSize>0||childrenSize>0){
      return VALID;
    }else{
        return NO_CHILD_PARENT_RELATION;
    }
}
Example #9
0
void ttref_add_activity(Hashmap *map, long dr) {
    if (dr) {
        long t = dr;
        for (int i = 0; i < 6; i++) {
            long v = t&MASK;
            t = t >> 6;
            if (v) {
                // -1 as 0 means no-activity
                v = (v - 1) << 1;
                if (!hashmapContainsKey(map, (void *) data[v]))
                    hashmapPut(map, (void *) data[v], (void *) data[v + 1]);
            }
        }
    }
}
Example #10
0
int validationManagerValidateParentOfChild(ValidationManager validationManager,int entityId,int childEntityId,char* arcName,int arcLength){
    ValidationManagerStruct* internal=(ValidationManagerStruct*)validationManager;
    ValidationDataStructure * data;
    StringHashMap childrenMap;
    hashmapGet(internal->parentChildrenRelationEntities,entityId,&childrenMap);
    if(childrenMap==NULL){
       childrenMap = stringHashmapCreate(SMALL_CONTAINER_SIZE);
       hashmapPut(internal->parentChildrenRelationEntities,entityId,childrenMap);
    }
    stringHashmapGet(childrenMap,arcName,arcLength,(Object*)&data);
    if(data==NULL||data->id!=childEntityId){
        return NO_CHILD_PARENT_RELATION;
    }else{
        return VALID;
    }
}
Example #11
0
/*
 * Create node.
 */
int nodeCreate(Registry registry,int nodeId,int schemaId,int lock,Node * result){        
	// Create the new node and update data
	RegistryInternal* internal=(RegistryInternal*)registry;
	NodeInternal* node = (NodeInternal*) memoryAlloc(sizeof(NodeInternal));
	node->id=nodeId;
	node->phantom=FALSE;
	node->locked=FALSE;
	node->children=stringHashmapCreate(SMALL_CONTAINER_SIZE);
	node->schemaId=schemaId;
	node->phantom=FALSE;
	node->lockOwnerSessionId=lock;
        node->attributes=stringHashmapCreate(SMALL_CONTAINER_SIZE);
	hashmapPut(internal->nodes,nodeId,node);
	// Update result only if it doesn't refer to NULL;
	if(result!=NULL){
		*result =(Node)node;
	}
        return VALID;
}
Example #12
0
Properties propertiesCreate(char *filePath) {
    PropertiesInternal *m = (PropertiesInternal *) memoryAlloc(sizeof(PropertiesInternal));
    m->map = hashmapCreate(SMALL_CONTAINER_SIZE);
    FILE *fp;
    long len;
    char *buf;
    fp = fopen(filePath, "rt");
    if (fp == NULL) {
        printf("couldn't open the properties file");
    };
    fseek(fp, 0, SEEK_END);            //go to end
    len = ftell(fp);                    //get position at end (length)
    fseek(fp, 0, SEEK_SET);            //go to beg.
    buf = (char *) memoryAlloc(len + 1);        //malloc buffer
    long result = fread(buf, (size_t) (len + 1), 1, fp);            //read into buffer
    if (result < 0) {
        printf("Fail to read properties file .");
    }
    fclose(fp);
    buf[len] = 0;
    char *key;
    char *value;
    const char newLineDelimiter[] = "\n";
    const char spaseDelimiter[] = "=";
    char *token;
    token = strtok(buf, newLineDelimiter);
    LinkedList linkedList = linkedListCreate();
    while (token != NULL) {
        linkedListAddFirst(linkedList, token);
        token = strtok(NULL, newLineDelimiter);
    }
    while (linkedListSize(linkedList) > 0) {
        char *token = (char *) linkedListRemoveFirst(linkedList);
        key = strtok(token, spaseDelimiter);
        value = strtok(NULL, spaseDelimiter);
        unsigned int keyId = stringTransformToInt(key, strlen(key));
        hashmapPut(m->map, keyId, value);
    }
    linkedListFree(linkedList);

    return m;
}
Example #13
0
void commandContainerPushCommand(CommandContainer commandContainer,Command command){
	CommandContainerInternal* internal=(CommandContainerInternal*)commandContainer;
        lockLock(internal->lock);
        time_t currentTime;       // Stores seconds elapsed since 01-01-1970
        time(&currentTime);
        int type=commandGetInt(command,COMMAND_TYPE);
        if(type==ATOMIC_MODEL_COMMAND){
            commandPush(command,SERVER_HANDLING_TIME,INTEGER,&currentTime);
            linkedListAddLast(internal->atomicCommands,command);
        }else{
            int version=commandGetInt(command,VERSION);
            int* intBuffer=memoryAlloc(SIZE_OF_INT);
            memcpy(intBuffer,&version,SIZE_OF_INT);
            commandPush(command,SERVER_HANDLING_TIME,INTEGER,&currentTime);
            // Update version Map;
            hashmapPut(internal->versionMap,version,command);
            // Update version list
            linkedListAddLast(internal->versions,intBuffer);
        }
        
        lockUnlock(internal->lock);
}
Example #14
0
static PeerProxy* peerProxyCreate(Peer* peer, Credentials credentials) {
    PeerProxy* peerProxy = calloc(1, sizeof(PeerProxy));
    if (peerProxy == NULL) {
        return NULL;
    }
   
    peerProxy->inputBuffer = bufferCreate(sizeof(Header));
    if (peerProxy->inputBuffer == NULL) {
        free(peerProxy);
        return NULL;
    }

    peerProxy->peer = peer;
    peerProxy->credentials = credentials;

    // Initial state == expecting a header.
    peerProxyExpectHeader(peerProxy); 
  
    // Add this proxy to the map. Make sure the key points to the stable memory
    // inside of the peer proxy itself.
    pid_t* pid = &(peerProxy->credentials.pid);
    hashmapPut(peer->peerProxies, pid, peerProxy);
    return peerProxy;
}
Example #15
0
static int load_config(const char *config)
{
	struct config_parser *cp;
	char *value;
	int i;

	if (!config || strlen(config) == 0)
		cp = config_parser_init(TBOOT_CONFIG);
	else
		cp = config_parser_init(config);

	if (!cp)
		goto err;

	/* init config with default values */
	tboot_config = hashmapCreate(array_size(tc_keys), strhash, strcompare);
	if (!tboot_config)
		goto err;

	for (i = 0; tc_keys[i]; i++)
		hashmapPut(tboot_config, (void *)tc_keys[i], (void *)tc_values[i]);

	/* parse config file */
	value = config_parser_get(cp, UI_CONF_KEY);
	if (value)
		tboot_config_set(UI_CONF_KEY, value);

	value = config_parser_get(cp, DISK_CONFIG_KEY);
	if (value)
		tboot_config_set(DISK_CONFIG_KEY, value);

	value = config_parser_get(cp, PUSH_DIR_KEY);
	if (value)
		tboot_config_set(PUSH_DIR_KEY, value);

	value = config_parser_get(cp, ROOTFS_KEY);
	if (value)
		tboot_config_set(ROOTFS_KEY, value);

	value = config_parser_get(cp, ENABLE_NFS_KEY);
	if (value)
		tboot_config_set(ENABLE_NFS_KEY, value);

	value = config_parser_get(cp, NFSURL_KEY);
	if (value)
		tboot_config_set(NFSURL_KEY, value);

	value = config_parser_get(cp, DISK_FORCE_KEY);
	if (value)
		tboot_config_set(DISK_FORCE_KEY, value);

	value = config_parser_get(cp, BAT_THRESHOLD_KEY);
	if (value)
		tboot_config_set(BAT_THRESHOLD_KEY, value);

	value = config_parser_get(cp, LCD_DIM_TIMEOUT_KEY);
	if (value)
		tboot_config_set(LCD_DIM_TIMEOUT_KEY, value);

	value = config_parser_get(cp, LCD_OFF_TIMEOUT_KEY);
	if (value)
		tboot_config_set(LCD_OFF_TIMEOUT_KEY, value);

	value = config_parser_get(cp, LCD_DIM_BRIGHTNESS_KEY);
	if (value)
		tboot_config_set(LCD_DIM_BRIGHTNESS_KEY, value);

	config_parser_free(cp);
	tboot_config_dump();
	return 0;

err:
	if (cp)
		config_parser_free(cp);
	if (tboot_config)
		hashmapFree(tboot_config);
	return -1;
}
Example #16
0
static int produceUnit(int x1,
                       int y1,
                       int x2,
                       int y2,
                       int unitId) {
    /// Validates initialization.
    if (!isValidField(currentGame.mapSize, x1, y1) ||
        !isValidField(currentGame.mapSize, x2, y2)) {
        return ERROR;
    }

    if (currentGame.isInitialized == false) {
        return ERROR;
    }

    /// Validates distance.
    if (distMax(x1, y1, x2, y2) != 1) {
        return ERROR;
    }

    /// Picks pawn from board.
    pawn *currentPawn = hashmapGet(currentGame.gameMap, x1, y1);

    /// Checks if pawn was picked.
    if (currentPawn == NULL) {
        return ERROR;
    }

    /// Checks if pawn is able to produce.
    if (currentPawn->lastMove >= currentGame.currentRound - 2) {
        return ERROR;
    }

    /// Checks if pawn belongs to current player.
    if (currentGame.playerTurn != getPawnAdherence(currentPawn)) {
        return ERROR;
    }

    if (isPeasant(currentPawn)) {
        pawn *targetPawn = hashmapGet(currentGame.gameMap, x2, y2);
        if (getPawnId(targetPawn) == EMPTY_SPACE_ID) {
            pawn *createdPawn;
            currentPawn->lastMove = currentGame.currentRound;
            if (unitId == PEASANT_PRODUCE_ID) {
                int newPawnId = currentGame.playerTurn == PLAYER_A_TURN ?
                                PEASANT_PLAYER_A_ID : PEASANT_PLAYER_B_ID;
                createdPawn = newPawn(x2, y2, currentGame.currentRound - 1, newPawnId);
            } else if (unitId == KNIGHT_PRODUCE_ID) {
                int newPawnId = currentGame.playerTurn == PLAYER_A_TURN ?
                                KNIGHT_PLAYER_A_ID : KNIGHT_PLAYER_B_ID;
                createdPawn = newPawn(x2, y2, currentGame.currentRound - 1, newPawnId);
            } else { ///< Tried to produce wrong unit.
                return ERROR;
            }
            hashmapPut(currentGame.gameMap, createdPawn);
            return GAME_OK;
        } else { ///< Field was not empty.
            return ERROR;
        }
    } else { ///< Unit that tried to produce was not peasant.
        return ERROR;
    }
}
Example #17
0
int move(int x1,
         int y1,
         int x2,
         int y2) {
    /// Validates fields.
    if (!isValidField(currentGame.mapSize, x1, y1) ||
        !isValidField(currentGame.mapSize, x2, y2)) {
        return ERROR;
    }

    /// Validates initialization.
    if (currentGame.isInitialized == false) {
        return ERROR;
    }

    /// Validates distance between fields.
    if (distMax(x1, y1, x2, y2) != 1) {
        return ERROR;
    }

    /// Picks pawn from board.
    pawn *currentPawn = hashmapRemove(currentGame.gameMap, x1, y1);

    /// Checks if any pawn was picked.
    if (currentPawn == NULL) {
        return ERROR;
    }

    /// Checks if pawn is able to move.
    if (currentPawn->lastMove >= currentGame.currentRound) {
        free(currentPawn);
        return ERROR;
    }

    /// Checks if pawn belong to current player.
    if (currentGame.playerTurn != getPawnAdherence(currentPawn)) {
        free(currentPawn);
        return ERROR;
    }

    currentPawn->lastMove = currentGame.currentRound;

    pawn *targetPawn = hashmapRemove(currentGame.gameMap, x2, y2);

    if (getPawnAdherence(currentPawn) == getPawnAdherence(targetPawn)) {
        ///< Player wants to move onto his own pawn.
        free(currentPawn);
        if (targetPawn != NULL) {
            free(targetPawn);
        }
        return ERROR;
    } else {
        int actionResult = performAction(currentPawn, targetPawn);
        switch (actionResult) {
            /// Frees pawn that was killed.
            /// Puts pawn that survived.
            case UNIT_MOVED:
                currentPawn->x = (unsigned int) x2 - 1; ///< 1-based to 0-based.
                currentPawn->y = (unsigned int) y2 - 1;
                hashmapPut(currentGame.gameMap, currentPawn);
                break;
            case ATTACKER_KILLED:
                currentPawn->x = (unsigned int) x2 - 1;
                currentPawn->y = (unsigned int) y2 - 1;
                hashmapPut(currentGame.gameMap, currentPawn);
                free(targetPawn);
                break;
            case DEFENDER_KILLED:
                hashmapPut(currentGame.gameMap, targetPawn);
                free(currentPawn);
                break;
            case ATTACKER_KILLED_KING:
                currentPawn->x = (unsigned int) x2 - 1;
                currentPawn->y = (unsigned int) y2 - 1;
                hashmapPut(currentGame.gameMap, currentPawn);
                free(targetPawn);
                /// Player that made move is victorious.
                return currentGame.playerTurn == PLAYER_A_TURN ? PLAYER_A_WON : PLAYER_B_WON;
            case DEFENDER_KILLED_KING:
                free(currentPawn);
                hashmapPut(currentGame.gameMap, targetPawn);
                /// Player that made move is beaten.
                return currentGame.playerTurn == PLAYER_A_TURN ? PLAYER_B_WON : PLAYER_A_WON;
            case BOTH_UNITS_DIED:
                if (isKing(currentPawn)) {
                    free(currentPawn);
                    free(targetPawn);
                    return DRAW; ///< Kings killed each other.
                } else {
                    free(currentPawn);
                    free(targetPawn);
                }
                break;
            default:
                return ERROR;
        }
    }

    return GAME_OK;
}
Example #18
0
void fileHelperConsume(FileHelper fileHelper, Command command) {
    FileHelperInternal *m = (FileHelperInternal *) fileHelper;
    PageManager pageManager = NULL;
    int schemaId = commandGetInt(command, SCHEMA_ID);
    int entityId = commandGetInt(command, ENTITY_ID);
    hashmapGet(m->managers, schemaId, &pageManager);
    char schemaIdString[10];
    if (pageManager == NULL) {
        stringConvertInt(schemaIdString, schemaId);
        char *pageDir = (char *) memoryAlloc(strlen(m->filePath) + strlen(schemaIdString) + 1);
        strcpy(pageDir, m->filePath);
        strcat(pageDir, "/");
        strcat(pageDir, schemaIdString);
        mkdir(pageDir, S_IRWXU | S_IRGRP | S_IXGRP);
        pageManager = pageManagerCreate(schemaId, pageDir);
        hashmapPut(m->managers, schemaId, pageManager);
    }
    Registry registry;
    hashmapGet(m->registryMap, schemaId, &registry);
    if (registry == NULL) {
        Throw(Fatal, 1, "FileHelper unsupported state failed to find registry for schemaId ");
    }
    char *buf = NULL;
    int type = commandGetInt(command, COMMAND_TYPE);
    switch (type) {
        case CREATE_NEW_ENTITY: {
            int lenght = commandGetByteArray(command, SERIALIZED_NODE, &buf);
            pageManagerAdd(pageManager, entityId, buf, lenght);
            return;
        }
        case DELETE_ENTITY: {
            pageManagerDelete(pageManager, entityId);
            return;
        }
        case ADD_CHILD_ENTITY_TO_PARENT_ENTITY: {
            int lenght = commandGetByteArray(command, SERIALIZED_NODE, &buf);
            pageManagerUpdate(pageManager, entityId, buf, lenght);
            return;
        }
        case REMOVE_CHILD_ENTITY_FROM_PARENT_ENTITY: {
            int lenght = commandGetByteArray(command, SERIALIZED_NODE, &buf);
            pageManagerUpdate(pageManager, entityId, buf, lenght);
            return;
        }
        case UPDATE_ENTITY: {
            int lenght = commandGetByteArray(command, SERIALIZED_NODE, &buf);
            pageManagerUpdate(pageManager, entityId, buf, lenght);
            return;
        }
        case ADD_ATTRIBUTE: {
            int lenght = commandGetByteArray(command, SERIALIZED_NODE, &buf);
            pageManagerUpdate(pageManager, entityId, buf, lenght);
            return;
        }
        case REMOVE_ATTRIBUTE: {
            int lenght = commandGetByteArray(command, SERIALIZED_NODE, &buf);
            pageManagerUpdate(pageManager, entityId, buf, lenght);
            return;
        }
    }

}
Example #19
0
void fileHelperLoad(FileHelper fileHelper) {
    FileHelperInternal *m = (FileHelperInternal *) fileHelper;
    fileHelperCheckCreate(m->filePath);
    int sizeOfInt = sizeof(int);
    struct direct **schemasIds = {0};
    struct direct *schenaId;
    int size = scandir(m->filePath, &schemasIds, 0, alphasort);
    // loop all schemas
    int i;
    for (i = 0; i < size; i++) {
        schenaId = (struct direct *) schemasIds[i];
        char *schemaIdString = schenaId->d_name;
        int schemaId = atoi(schemaIdString);
        if (schemaId != 0) {
            printf("schema %s\n", schenaId->d_name);
            struct direct **pagesIds = {0};
            struct direct *pageStruct;
            char endOdString = '\0';
            int pageDirLength = strlen(m->filePath);
            int schemaIdStringLength = strlen(schemaIdString);
            char slesh = '/';
            char *pageDir = (char *) memoryAlloc(pageDirLength + 1 + schemaIdStringLength + 1);
            memcpy(pageDir, m->filePath, pageDirLength);
            memcpy(pageDir + pageDirLength, &slesh, 1);
            memcpy(pageDir + pageDirLength + 1, schemaIdString, schemaIdStringLength);
            memcpy(pageDir + pageDirLength + 1 + schemaIdStringLength, &endOdString, 1);


//			cleanBuffer(pageDir);
//			strcat(pageDir,m->filePath);
//			strcat(pageDir,"/");
//			strcat(pageDir,schemaIdString);
            HashMap childrenRelations = hashmapCreate(SMALL_CONTAINER_SIZE);
            Registry registry = registryCreate();
            hashmapPut(m->registryMap, schemaId, registry);
            PageManager pageManager = pageManagerCreate(schemaId, pageDir);
            hashmapPut(m->managers, schemaId, pageManager);
            int size = scandir(pageDir, &pagesIds, 0, alphasort);
            int h;
            //loop pages
            for (h = 0; h < size; h++) {
                //scandir (pageDir, &pagesIds, 0, alphasort);
                pageStruct = (struct direct *) pagesIds[h];
                char *pageString = pageStruct->d_name;
                int pageId = atoi(pageString);
                if (pageId != 0) {
                    printf("page %s\n", pageStruct->d_name);
                    // create file path.

                    //int i=0;
                    int pageDirLength = strlen(pageDir);
                    int pageStringLength = strlen(pageString);
                    char slesh = '/';
                    char *filePath = (char *) memoryAlloc(pageDirLength + 1 + pageStringLength + 1);
                    memcpy(filePath, pageDir, pageDirLength);
                    memcpy(filePath + pageDirLength, &slesh, 1);
                    memcpy(filePath + pageDirLength + 1, pageString, pageStringLength);
                    memcpy(filePath + pageDirLength + 1 + pageStringLength, &endOdString, 1);
                    FILE *fp;
                    long len;
                    // Create pointer to file.
                    fp = fopen(filePath, "rb");
                    if (fp == NULL) {
                        printf("couldn't open the properties file");
                    }
                    fseek(fp, 0, SEEK_END);                // Go to end
                    len = ftell(fp);                        // Get position at end (length)
                    // Read data to buffer
                    char *buffer = memoryAlloc(sizeof(char) * len); // Create buffer
                    char *pointerToFreeBuffer = buffer;
                    fseek(fp, 0, SEEK_SET);                // Go to the beginning.
                    int result = fread(buffer, len, 1, fp);                // Read into buffer
                    if (result < 0) {
                        printf("Fail to read file : %s", buffer);
                    }
                    fclose(fp);
                    int order = 0;
                    long index = 0;
                    long step = 0;
                    while (index < len) {
                        char *start = buffer;
                        int id;
                        int schemaId;
                        int numberOfAttributes;
                        int childrenSize;
                        int attributeSize;
                        memcpy(&schemaId, buffer + SIZE_OF_INT * 0, SIZE_OF_INT);
                        memcpy(&id, buffer + SIZE_OF_INT * 1, SIZE_OF_INT);
                        memcpy(&numberOfAttributes, buffer + SIZE_OF_INT * 2, SIZE_OF_INT);
                        buffer += SIZE_OF_INT * 3;
                        Node node;
                        nodeCreate(registry, id, schemaId, FALSE, &node);
                        int h;
                        for (h = 0; h < numberOfAttributes; h++) {
                            memcpy(&attributeSize, buffer, SIZE_OF_INT);
                            Attribute attribute = attributeDeserializeLocal(buffer);
                            buffer += attributeSize;
                            stringHashmapPut(node->attributes, attribute->name, attribute->nameLength, attribute);
                        }
                        memcpy(&childrenSize, buffer, SIZE_OF_INT);
                        Array children = arrayCreate(childrenSize);
                        hashmapPut(childrenRelations, id, children);
                        int i;
                        buffer += SIZE_OF_INT;
                        int childrenIdBuffer;
                        for (i = 0; i < childrenSize; i++) {
                            memcpy(&childrenIdBuffer, buffer + SIZE_OF_INT, SIZE_OF_INT);
                            void *bufferElement = memoryAlloc(childrenIdBuffer + SIZE_OF_INT * 2);
                            memcpy(bufferElement, buffer, SIZE_OF_INT * 2 + childrenIdBuffer);
                            arrayInsertObject(children, bufferElement);
                            buffer += SIZE_OF_INT * 2 + childrenIdBuffer;
                        }
                        step = buffer - start;
                        index += step;
                        pageManagerRegister(pageManager, pageId, id, index - step, index, order, filePath);
                        order++;
                    }
                    // Free the file buffer
                    memoryFree(pointerToFreeBuffer);
                }
            }
            if (size > 0) {
                while (size) {
                    size = size - 1;
                    free(pagesIds[size]);
                }
                free(pagesIds);
            }
            hashmapIterate(childrenRelations, &updateChildren, registry);
            hashmapFree(childrenRelations);
        }
    }
    if (size > 0) {
        while (size) {
            size = size - 1;
            free(schemasIds[size]);
        }
        free(schemasIds);
    }

}
Example #20
0
void massdns_scan(lookup_context_t *context)
{
    memset(&stats, 0, sizeof(dns_stats_t));
    size_t line_buflen = 4096;
    char *line = safe_malloc(line_buflen);
    size_t line_len = 0;
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = 0;
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    int socketbuf = 1024 * 1024 * 100;
    if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &socketbuf, sizeof(socketbuf)) != 0)
    {
        perror("Failed to adjust socket send buffer size.");
    }
    if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &socketbuf, sizeof(socketbuf)) != 0)
    {
        perror("Failed to adjust socket receive buffer size.");
    }
    bind(sock, (sockaddr_t *) &server_addr, sizeof(server_addr));

    fcntl(sock, F_SETFL, fcntl(sock, F_GETFL, 0) | O_NONBLOCK);

    if (sock < 0)
    {
        perror("Failed to create socket");
        exit(1);
    }
    FILE *f;
    if(context->cmd_args.show_progress)
    {
        f = fopen(context->cmd_args.domains, "r");
        if (f == NULL)
        {
            perror("Failed to open domain file");
            exit(1);
        }
        while(!feof(f))
        {
            if (0 <= getline(&line, &line_buflen, f))
            {
                trim_end(line);
                strtolower(line);
                if (strcmp(line, "") != 0)
                {
                    context->total_domains++;
                }
            }
        }
        fclose(f);
    }
    f = fopen(context->cmd_args.domains, "r");
    if (f == NULL)
    {
        perror("Failed to open domain file");
        exit(1);
    }
    if (geteuid() == 0)
    {
        fprintf(stderr, "You have started the program with root privileges.\n");
        struct passwd *nobody = getpwnam(UNPRIVILEGED_USER);
        if (!context->cmd_args.root)
        {
            if (nobody && setuid(nobody->pw_uid) == 0)
            {
                fprintf(stderr, "Privileges have been dropped to \"%s\" for security reasons.\n\n", UNPRIVILEGED_USER);
            }
            else if (!context->cmd_args.root)
            {
                fprintf(stderr, "Privileges could not be dropped to \"%s\".\n"
                        "For security reasons, this program will only run as root user when supplied with --root"
                        "which is not recommended.\n"
                        "It is better practice to run this program as a different user.\n", UNPRIVILEGED_USER);
                exit(1);
            }
        }
        else
        {
            fprintf(stderr, "[WARNING] Privileges were not dropped. This is not recommended.\n\n");
        }
    }
    FILE *randomness = fopen("/dev/urandom", "r");
    if (!randomness)
    {
        fprintf(stderr, "Failed to open /dev/urandom.\n");
        exit(1);
    }
    context->current_rate = 0;
    context->sock = sock;
    context->resolvers = massdns_resolvers_from_file(context->cmd_args.resolvers);
    context->map = hashmapCreate(context->cmd_args.hashmap_size, hash_string, cmp_lookup);
    context->initial = true;
    gettimeofday(&context->start_time, NULL);
    context->next_update = context->start_time;
    while (true)
    {
        while (hashmapSize(context->map) < context->cmd_args.hashmap_size && !feof(f))
        {
            if (0 <= getline(&line, &line_buflen, f))
            {
                trim_end(line);
                line_len = strlen(line);
                strtolower(line);
                if(strcmp(line, "") == 0)
                {
                    continue;
                }
                if (line_len > 0 && line[line_len - 1] == '.')
                {
                    // Remove trailing dot from FQDN
                    line[line_len] = 0;
                }
                lookup_t *lookup = hashmapGet(context->map, line);
                if (lookup == NULL)
                {
                    char *value = safe_malloc(line_len + 1);
                    strcpy(value, line);
                    lookup = safe_malloc(sizeof(*lookup));
                    lookup->domain = value;
                    lookup->tries = 0;
                    if (fread(&lookup->transaction, 1, sizeof(lookup->transaction), randomness) !=
                        sizeof(lookup->transaction))
                    {
                        fprintf(stderr, "Failed to get randomness for transaction id.\n");
                        exit(1);
                    }
                    gettimeofday(&lookup->next_lookup, NULL);
                    hashmapPut(context->map, value, lookup);
                }

            }
        }
        if(!context->cooldown && hashmapSize(context->map) < context->cmd_args.hashmap_size)
        {
            context->cooldown = true;
            gettimeofday(&context->cooldown_time, NULL);
        }
        while (massdns_receive_packet(sock, massdns_handle_packet, context));
        if (feof(f) && hashmapSize(context->map) == 0)
        {
            break;
        }
        hashmapForEach(context->map, handle_domain, context);
    }
    for (size_t i = 0; i < context->resolvers.len; i++)
    {
        free(((sockaddr_in_t **) context->resolvers.data)[i]);
        ((sockaddr_in_t **) context->resolvers.data)[i] = NULL;
    }
    free(line);
    free(context->resolvers.data);
    context->resolvers.data = NULL;
    print_stats(context);
    hashmapFree(context->map);
    context->map = NULL;
    fclose(f);
    fclose(randomness);
}
Example #21
0
/*
 * Handler to handle both TI (Insert) and TU (update) records.
 * 
 * These records are identical except for update has possible additional entry for renaming a tiploc
 */
int tt_parse_ttinsert(struct CIFParser *parser) {
    struct TimeTable *p = (struct TimeTable *) parser;

    int insert = 0;

    // Lookup for existing entry (update) or insert)
    char tiploc[8];
    cif_readString(parser->buf, 2, tiploc, 7);
    struct TTTiploc *tpl = (struct TTTiploc *) hashmapGet(p->loc, tiploc);
    if (!tpl) {
        tpl = (struct TTTiploc *) malloc(sizeof (struct TTTiploc));

        if (tpl) {
            memset(tpl, 0, sizeof (struct TTTiploc));
            insert = 1;
        }
    }

    // Still no tpl then fail - out of memory most likely
    if (!tpl)
        return EXIT_FAILURE;

    int ofs = 2;

    ofs = cif_readString(parser->buf, ofs, tpl->tiploc, 7);

    // ignore caps?
    ofs += 2;

    ofs = cif_readInt_r(parser->buf, ofs, &tpl->nlc, 6);
    tpl->nlc_check = parser->buf[ofs++];

    ofs = cif_readString(parser->buf, ofs, tpl->desc, 26);

    ofs = cif_readInt_r(parser->buf, ofs, &tpl->stanox, 5);

    // PO MCP code ignored
    ofs += 4;

    ofs = cif_readString(parser->buf, ofs, tpl->crs, 3);
    
    ofs = cif_readString(parser->buf, ofs, tpl->nlcdesc, 16);

    if (insert || parser->buf[ofs] == ' ') {
        struct TTTiploc *old = (struct TTTiploc *) hashmapPut(p->loc, tpl->tiploc, tpl);
        if (old) {
            tpl->id = old->id;
            free(old);
        } else {
            tpl->id = p->locSeq++;
        }
    } else {
        char newt[8];
        cif_readString(parser->buf, ofs, newt, 7);
        logconsole("Tiploc change from '%s' to '%s'", tpl->tiploc, newt);

        // Remove old entry from the map
        struct TTTiploc *old = (struct TTTiploc *) hashmapRemove(p->loc, tpl->tiploc);
        if (old) {
            tpl->id = old->id;
            free(old);
        } else {
            tpl->id = p->locSeq++;
        }

        // Replace new tiploc & re-insert
        cif_readString(parser->buf, ofs, tpl->tiploc, 7);
        old = (struct TTTiploc *) hashmapPut(p->loc, tpl->tiploc, tpl);
        if (old)
            free(old);
    }

    return EXIT_SUCCESS;
}
Example #22
0
void sprite_frame_cache_add(struct sprite_frame_cache* self, struct sprite_frame* frame) {
    hashmapPut(self->cache, frame->key, frame);
}