示例#1
0
void testInsert()
{
    printf("###########################\n");
    printf("Test 6. insert: ");
    BTree *tree = malloc(sizeof(BTree));
    tree->root = NULL;
    tree->arity = 4;
    tree->height = 0;

    insertBTree(tree, 1);
    int a1[1] = {1};
    if ((tree->root == NULL) || (!compareKeys(tree->root->keys,a1, 1))){
        printf("NOK - vkladani do prazdneho B-stromu stupne 2\n");
    }else{
        insertBTree(tree, 7);
        insertBTree(tree, 2);
        int a2[3] = {1,2,7};
        if((tree->root == NULL) || (!compareKeys(tree->root->keys,a2, 3))){
            printf("NOK - vkladani do B-stromu bez stepeni\n");
        }else{
            int a3_1[1] = {2}; int a3_2[1] = {1}; int a3_3[2] = {5, 7};
            insertBTree(tree,5);
            if(tree->root == NULL ||
                    (!compareKeys(tree->root->keys,a3_1, 1)) ||
                    (!compareKeys(tree->root->children[0]->keys,a3_2, 1)) ||
                    (!compareKeys(tree->root->children[1]->keys,a3_3, 2))){
                printf("NOK - vkladani se stepenim korene\n");
            }else{
                insertBTree(tree, 12);
                insertBTree(tree, 8);
                int a4_1[2] = {2,7}; int a4_2[1] = {1}; int a4_3[1] = {5}; int a4_4[2] = {8, 12};
                if(tree->root == NULL ||
                        (!compareKeys(tree->root->keys,a4_1, 2)) ||
                        (!compareKeys(tree->root->children[0]->keys,a4_2, 1)) ||
                        (!compareKeys(tree->root->children[1]->keys,a4_3, 1)) ||
                        (!compareKeys(tree->root->children[2]->keys,a4_4, 2))){
                    printf("NOK - vkladani se stepenim listu\n");
                }else{
                    insertBTree(tree, 4);
                    insertBTree(tree, 3);
                    insertBTree(tree, 6);
                    int a5_1[3] = {2,4,7}; int a5_2[1] = {3}; int a5_3[2] = {5, 6}; int a5_4[2] = {8, 12};
                    if(tree->root == NULL ||
                            (!compareKeys(tree->root->keys,a5_1, 3)) ||
                            (!compareKeys(tree->root->children[1]->keys,a5_2, 1)) ||
                            (!compareKeys(tree->root->children[2]->keys,a5_3, 2)) ||
                            (!compareKeys(tree->root->children[3]->keys,a5_4, 2))){
                        printf("NOK - vkladani se stepenim listu\n");
                    }else{
                        insertBTree(tree, 11);
                        int a6_1[1] = {4}; int a6_2[1] = {2}; int a6_3[1] = {7}; int a6_4[2] = {5, 6}; int a6_5[3] = {8, 11, 12};
                        if(tree->root == NULL ||
                                (!compareKeys(tree->root->keys,a6_1, 1)) ||
                                (!compareKeys(tree->root->children[0]->keys,a6_2, 1)) ||
                                (!compareKeys(tree->root->children[1]->keys,a6_3, 1)) ||
                                (!compareKeys(tree->root->children[1]->children[0]->keys,a6_4, 2)) ||
                                (!compareKeys(tree->root->children[1]->children[1]->keys,a6_5, 3))){
                            printf("NOK - vkladani se stepenim korene\n");
                        }else{
                            printf("OK\n");
                        }
                    }
                }
            }
        }
    }
    makeGraph(tree, "insert.dot");
    printf("Vykresleny B-strom najdete v souboru insert.dot\n");
    freeTree(tree);
}
void test_compareKeys() {
	Key key1 = {100, 10};
	Key key2 = {100, 10};
	assertLongEquals("Compare should eq", 0,
					 compareKeys(&key1, &key2));

	key1.ip = 99;
	assertLongEquals("Firs Keyk is less (ip less)",
					 -1, compareKeys(&key1, &key2));

	key1.port = 9;
	assertLongEquals("Firs Keyk is less (ip less port less)",
					 -1, compareKeys(&key1, &key2));

	key1.port = 11;
	assertLongEquals("Firs Keyk is less (ip less port greater)",
					 -1, compareKeys(&key1, &key2));

	key1.ip = 100;
	key1.port = 10;
	assertLongEquals("Compare should eq", 0,
					 compareKeys(&key1, &key2));

	key1.port = 9;
	assertLongEquals("Firs Keyk is less (ip eq port less)",
					 -1, compareKeys(&key1, &key2));

	key1.ip = 100;
	key1.port = 10;
	assertLongEquals("Compare should eq", 0,
					 compareKeys(&key1, &key2));

	key1.port = 11;
	assertLongEquals("Firs Keyk is greater (ip eq port greater)",
					 1, compareKeys(&key1, &key2));

	key1.ip = 101;
	key1.port = 11;
	assertLongEquals("Firs Keyk is greater (ip greater port greater)",
					 1, compareKeys(&key1, &key2));

	key1.port = 10;
	assertLongEquals("Firs Keyk is greater (ip greater port eq)",
					 1, compareKeys(&key1, &key2));

	key1.port = 9;
	assertLongEquals("Firs Keyk is greater (ip greater port less)",
					 1, compareKeys(&key1, &key2));
}
示例#3
0
void testPostOrderPrint()
{
    printf("###########################\n");
    printf("Test 3. post_order_print: ");

    int res1[5] = {1, 8, 12, 16, 25};
    int res2[21] = {0, 1, 3, 2, 6, 7, 9, 10, 12, 8, 14, 15, 17, 25, 55, 75, 16,
                    18, 50, 5, 13};
    int res3[42] = {1, 3, 8, 13, 15, 16, 18, 19, 20, 21, 23, 24, 27, 29, 31, 32,
                    33, 34, 36, 37, 38, 40, 42, 47, 48, 50, 52, 56, 66, 67, 68,
                    69, 70, 73, 79, 12, 17, 22, 28, 35, 39, 65};

    BTree *tree = testTree1();

    int* res = postOrderPrintBTree(tree);

    if (!compareKeys(res1, res, 5)) {
        printf("NOK\n");
        printf("vysledek:\t   ");
        if (res != NULL) {
            for(int i = 0; i < 5; i++) printf("%d ",res[i]); putchar('\n');
        }else{
            printf("[]\n");
        }
        printf("ocekavany vysledek:");
        for(int i = 0; i < 5; i++) printf("%d ",res1[i]); putchar('\n');
    } else {
        free(res);
        freeTree(tree);
        tree = testTree2();
        res = postOrderPrintBTree(tree);
        if (!compareKeys(res2, res, 21)){
            printf("NOK\n");
            printf("vysledek:\t   ");
            if (res != NULL) {
                for(int i = 0; i < 21; i++) printf("%d ",res[i]); putchar('\n');
            }else{
                printf("[]\n");
            }
            printf("ocekavany vysledek:");
            for(int i = 0; i < 21; i++) printf("%d ",res2[i]); putchar('\n');
        }else{
            free(res);
            freeTree(tree);
            tree = testTree3();
            res = postOrderPrintBTree(tree);
            if (!compareKeys(res3, res, 42)){
                printf("NOK\n");
                printf("vysledek:\t   ");
                if (res != NULL) {
                    for(int i = 0; i < 42; i++) printf("%d ",res[i]); putchar('\n');
                }else{
                    printf("[]\n");
                }
                printf("ocekavany vysledek:");
                for(int i = 0; i < 42; i++) printf("%d ",res3[i]); putchar('\n');
            }else{
                printf("OK\n");
            }
        }
    }

    makeGraph(tree, "post_order_print.dot");
    printf("Vykresleny B-strom najdete v souboru post_order_print.dot\n");
    free(res);
    freeTree(tree);
}
示例#4
0
bool GridWorld::computeShortestPath(){
	if (open.empty()){
		std::cout << "ERROR: No tiles to expand on... can't do anything" << std::endl;
		return false;
	}


	while (!open.empty() && (compareKeys(open.front()->key, goal->key = calculateKey(goal)) || goal->rhs != goal->g)){
		Tile* current = open.front();
		//Notice that CURRENT wasn't pop/removed yet

		//std::cout << "Expanding:";
		//current->info();
		//std::cout << std::endl;
		KeyPair k_new = calculateKey(current);

		if (compareKeys(current->key, k_new)){
			//Tiles under this branch will have to be updated as incremental search has happened
			current->key = k_new;
			make_heap(open.begin(), open.end(), GridWorld::compareTiles);

		}
		else if (current->g > current->rhs){
			//Majority of the tiles will fall under this conditional branch as
			//it undergoes normal A* pathfinding

			current->g = current->rhs;

			open.erase(open.begin());
			make_heap(open.begin(), open.end(), GridWorld::compareTiles);
			current->isOpen = false;

			std::vector<Tile*> neighbours(getNeighbours(current));
			for (int i = 0; i < neighbours.size(); i++){
				if (neighbours[i] != start && neighbours[i]->rhs > current->g + calculateC(current, neighbours[i])){
					neighbours[i]->successor = current;
					neighbours[i]->rhs = current->g + calculateC(current, neighbours[i]);
					updateVertex(neighbours[i]);
				}
			}

		}
		else {
			//Tiles under this branch will need to be updated during incremental search
			current->g = PF_INFINITY;

			//Update CURRENT
			if (current != start && current->successor == current){
				TilePair minSucc(getMinSuccessor(current));
				current->rhs = minSucc.second;
				current->successor = current->rhs == PF_INFINITY ? 0 : minSucc.first;
			}
			updateVertex(current);

			//Update NEIGHBOURS
			std::vector<Tile*> neighbours(getNeighbours(current));
			for (int i = 0; i < neighbours.size(); i++){
				if (neighbours[i] != start && neighbours[i]->successor == current){
					TilePair minSucc(getMinSuccessor(neighbours[i]));
					neighbours[i]->rhs = minSucc.second;
					neighbours[i]->successor = neighbours[i]->rhs == PF_INFINITY ? 0 : minSucc.first;
				}
				updateVertex(neighbours[i]);
			}

		}
		//Uncomment this to see CURRENT'S new values
		//std::cout << "Expanded:";
		//current->info();
		//std::cout << std::endl;
	}
	return true;
}
示例#5
0
int main(int argc, char *argv[]) {
  int i, j;
  int record_count = 400;
  int range = record_count/10;
  uint8_t len = 5;
  AttributeType type[len];
  const char hans[] = "hans";
  Index *index;
  Iterator **iterator = (Iterator**) malloc(sizeof(Iterator*));
  Transaction *t;
  Record recs[record_count];
  Key keys[record_count];
  Key minkey;
  Key maxkey;
  Record *currentResult;
  Attribute attr;
  Block blocks[record_count];
  time_t tm;
  
  for (j = 0; j < record_count; j++) {
    blocks[j].size = 5;
    blocks[j].data = malloc(5);
    sprintf((char*)blocks[j].data, "%i", j);
    attr.type = kInt;
    keys[j].value = (Attribute**) malloc(len*sizeof(Attribute*));
    keys[j].attribute_count = len;
//     printf("Key number %i: \n", j);
    for (i = 0; i < len; i++) {
      type[i] = kInt;
      keys[j].value[i] = (Attribute*) malloc(sizeof(Attribute));
      keys[j].value[i]->type = kInt;
      keys[j].value[i]->int_value = randInt(range);
//       printf("key.value[%i] = %ld \n", i, keys[j].value[i]->int_value);
    }
//     printf("\n");
    recs[j].key = keys[j];
    recs[j].payload = blocks[j];
  }
  // generate min and max keys
  minkey.value = (Attribute**) malloc(len*sizeof(Attribute*));
  minkey.attribute_count = len;
  maxkey.value = (Attribute**) malloc(len*sizeof(Attribute*));
  maxkey.attribute_count = len;
  for (i = 0; i < len; i++) {
    minkey.value[i] = (Attribute*) malloc(sizeof(Attribute));
    minkey.value[i]->type = kInt;
    minkey.value[i]->int_value = 0.3*range;
    maxkey.value[i] = (Attribute*) malloc(sizeof(Attribute));
    maxkey.value[i]->type = kInt;
    maxkey.value[i]->int_value = 0.8*range;
  }
  printf("Done with generating data. \n");
  
  tm = time(NULL);
  CreateIndex(hans, len, type); // len
  OpenIndex(hans, &index);
  BeginTransaction(&t);
  for (i = 0; i < record_count; i++) { //record_count
    InsertRecord(t, index, recs+i);
    if (i % 1000 == 0) 
      printf("i = %i / %i \n", i, record_count);
  }
  printf("finished inserting, took %is \n", time(NULL)-tm);
  tm = time(NULL);
//   for (i = 0; i < record_count; i+=2) { // record_count
//     if (i == 398) {
//       printf("deleting record %i \n", i);
//     }
    DeleteRecord(t, index, recs+4, 0);
//   }
//   if (DeleteRecord(t, index, recs+398, 0) != kErrorNotFound) {
//     printf(";_; \n ");
//   }
  printf("deleted half of the records, took %is \n", time(NULL)-tm);
  GetRecords(t, index, minkey, maxkey, iterator);
  while (GetNext(*iterator, &currentResult) != kErrorNotFound) {
    printf("%i \t(%i\t%i\t%i\t%i\t%i)\t%s \n", currentResult->key.value[0]->int_value, currentResult->key.value[0]->int_value, currentResult->key.value[1]->int_value, currentResult->key.value[2]->int_value, currentResult->key.value[3]->int_value, currentResult->key.value[4]->int_value, currentResult->payload.data);
  }
  printf("just to be sure: \n");
  for (i = 0; i < record_count; i++) {
    for (j = 0; j < len; j++) { // len
//       if (!(compareKeys(minkey, keys[i], j, true) <= 0 && compareKeys(keys[i], maxkey, j, true) < 0)) {
	if (!((minkey.value[j] == 0 || compareKeys(minkey, keys[i], j, true) <= 0) && (maxkey.value[j] == 0 || compareKeys(keys[i], maxkey, j, true) < 0))) {
	break;
      }
    }
    if (j == len) { // len
      printf("so: %i \n", keys[i].value[0]->int_value);
    }
  }
//   printf("committing \n");
  CommitTransaction(&t);
//   printf("closing \n");
  CloseIndex(&index);
//   printf("deleting \n");
  DeleteIndex(hans);
//   printf("should be zero: %i \n", all_indices["hans"]);
  return 0;
}
示例#6
0
int TCBinaryObjectTree::setObjectForKey(TCObject *object, const char* key)
{
	if (rootNode)
	{
		TCBinaryObjectTreeNode* spot = rootNode;
		int currentDepth = 0;

		while (1)
		{
			int result = compareKeys(key, spot->key);

			currentDepth++;
			if (result < 0)
			{
				if (spot->left)
				{
					spot = spot->left;
				}
				else
				{
					spot->left = new TCBinaryObjectTreeNode(key, object);
					count++;
					break;
				}
			}
			else if (result > 0)
			{
				if (spot->right)
				{
					spot = spot->right;
				}
				else
				{
					spot->right = new TCBinaryObjectTreeNode(key, object);
					count++;
					break;
				}
			}
			else
			{
				TCObject *oldObject = spot->value;

				// already exists, so replace, and return 0 to indicate this.
				spot->value = object->retain();
				oldObject->release();
				return 0;
			}
		}
		if (currentDepth > depth)
		{
			depth = currentDepth;
		}
	}
	else
	{
		rootNode = new TCBinaryObjectTreeNode(key, object);
		depth = 1;
		count = 1;
	}
	return 1;
}
asmlinkage long xcrypt(void *arg)
{
    if (arg == NULL) {
	printk("User level argument is NULL\n");
	return -EINVAL;
    } else {
	struct myargs *arguments;
	int result, paddedresult, padvalue, preambleWritten, temp, paddingWritten, paddingRead;
	struct file *filp=NULL, *filp1=NULL;
	struct dentry *dentry=NULL, *olddentry=NULL, *newdentry=NULL;
	long int inputFileLen=-1, outputFileLen=-1, keyLen=-1;
	char *srcbuffer, *destbuffer, *padding, *keyFromFile=NULL, *md5_hash=NULL, *tempOutFile;
	umode_t inputFileMode, outputFileMode;
	bool outFileCreated=false, renamed=false, success = false;
	int err=0;	
	arguments = (struct myargs *)kmalloc(sizeof(struct myargs), GFP_KERNEL);
	if (arguments==NULL) {
	    printk("Failed to allocate kernel memory\n");
	    err = -ENOMEM;
	    goto out1;
	}
	result = copy_from_user((void *)arguments, arg, sizeof(struct myargs));
	if(result!=0) {
	    printk("Copying from user failed\n");
	    err = -EFAULT;
	    goto out2;
	}
	if (((struct myargs*)arg)->inputFile == NULL) { /*Checking whether user passed NULL input File*/
	    printk("user level input file argument is NULL\n");
	    err = -EINVAL;
	    goto out2;
	}
	inputFileLen = strnlen_user(((struct myargs*)arg)->inputFile, 32767); //TODO get the maximum value from getname 
	if (inputFileLen == -1) {
	    printk("Finding User inputFile string length Failed\n");
	    err = -EFAULT;
	    goto out2;
	}
	arguments->inputFile = (char *)kmalloc(inputFileLen*sizeof(char), GFP_KERNEL);
	if ((arguments->inputFile)==NULL) {
            printk("Failed to allocate kernel memory for input file\n");
            err = -ENOMEM;
	    goto out2;
        }
	result = strncpy_from_user(arguments->inputFile, ((struct myargs*)arg)->inputFile, inputFileLen);
	if(result!=(inputFileLen-1)) {
            printk("Copying input file string from user failed\n");
            err = -EFAULT;
	    goto out3;
        }
	if((arguments->inputFile)==NULL) {
	    printk("Copying input file string from user failed\n");
	    err = -EFAULT;
	    goto out3;
	}
	if (((struct myargs*)arg)->outputFile == NULL) {
            printk("user level output file argument is NULL\n");
            err = -EINVAL;
	    goto out3;
        }
	outputFileLen = strnlen_user(((struct myargs*)arg)->outputFile, 32767); //TODO get the maximum value from getname
	if (outputFileLen == -1) {
            printk("Finding User outputFile string length Failed\n");
            err = -EFAULT;
	    goto out3;
        }
	arguments->outputFile = (char *)kmalloc(outputFileLen*sizeof(char), GFP_KERNEL);
	if ((arguments->outputFile)==NULL) {
            printk("Failed to allocate kernel memory for outputfile\n");
            err = -ENOMEM;
	    goto out3;
        }
	result = strncpy_from_user(arguments->outputFile, ((struct myargs*)arg)->outputFile, outputFileLen);
	if(result!=(outputFileLen-1)) {
            printk("Copying output file string from user failed\n");
            err = -EFAULT;
	    goto out4;
        }
	if((arguments->outputFile)==NULL) {
            printk("Copying output file string from user failed\n");
            err = -EFAULT;
	    goto out4;
        }
	if (((struct myargs*)arg)->keyBuf == NULL) {
            printk("user level key buffer argument is NULL\n");
            err = -EINVAL;
            goto out4;
        }
	keyLen = strnlen_user(((struct myargs*)arg)->keyBuf, 32767); //TODO get the maximum value from getname
        if (keyLen == -1) {
            printk("Finding User keyBuf string length Failed\n");
            err = -EFAULT;
	    goto out4;
        }
	arguments->keyBuf = (char *)kmalloc(keyLen*sizeof(char), GFP_KERNEL);
	if ((arguments->keyBuf)==NULL) {
            printk("Failed to allocate kernel memory\n");
            err = -ENOMEM;
	    goto out4;
        }
	result = strncpy_from_user(arguments->keyBuf, ((struct myargs*)arg)->keyBuf, keyLen);
	if(result!=(keyLen-1)) {
            printk("Copying key buf string from user failed\n");
            err = -EFAULT;
	    goto out5;
        }
	if((arguments->keyBuf)==NULL) {
            printk("Copying key buf string from user failed\n");
            err = -EFAULT;
	    goto out5;
        }

	if (strlen(arguments->keyBuf) != arguments->keyLen) {
	    printk("User key buffer length and kernel key buffer lengths differ\n");
	    err = -EINVAL;
	    goto out5;
	}

	if((arguments->flags)!=0 && (arguments->flags)!=1) {
	    printk("Invalid values for flag argument, it should be either 1 or 0\n");
	    err = -EINVAL;
	    goto out5;
	}

	srcbuffer = (char *)kmalloc((PAGE_SIZE+1)*sizeof(char), GFP_KERNEL);
	if (srcbuffer==NULL) {
	    printk("Failed to allocate kernel memory for srcbuffer\n");
            err = -ENOMEM;
	    goto out5;
	}
        
        destbuffer = (char *)kmalloc((PAGE_SIZE+1)*sizeof(char), GFP_KERNEL);
        if (destbuffer==NULL) {
            printk("Failed to allocate kernel memory for destbuffer\n");
            err = -ENOMEM;
	    goto out6;
        }

	padding = (char *)kmalloc(4*sizeof(char), GFP_KERNEL);
	if (padding==NULL) {
	    printk("Failed to allocate kernel memory for padding\n");
            err = -ENOMEM;
	    goto out7;
	}

        initialisePadding(padding); /*Initialising the padding array to all 0's */
        
	result=PAGE_SIZE;

	filp = filp_open(arguments->inputFile, O_RDONLY, 0);
	if (PTR_ERR(filp)==-ENOENT) {
	    printk("Input File doesnot exists\n");
	    err = -ENOENT; 
	    goto out8;
	} else {
	    printk("Input File exists\n");
	}
	
        if (!filp || IS_ERR(filp)) {
            printk("Read error for input file %d\n", (int) PTR_ERR(filp));
            err = PTR_ERR(filp);
	    goto out8;
        }

	inputFileMode = filp->f_inode->i_mode;

	if(!S_ISREG(inputFileMode)) {
	    printk("Input File is not a regular file\n");
	    err = -EISDIR;
	    goto out9;
	}

	if (!filp->f_op->read) {
	    printk("Error in reading input file\n");
            err = PTR_ERR(filp);
	    goto out9;
	}

	filp1 = filp_open(arguments->outputFile, O_WRONLY, 0);
	if (PTR_ERR(filp1)==-ENOENT) {
            printk("Output File doesnot exists, creating it\n");
	    filp1 = filp_open(arguments->outputFile, O_CREAT, inputFileMode); /*Creating output file if it doesnot exists with input file permissions*/
	    if(!filp1 || IS_ERR(filp1)) {
		printk("Error in creating output file\n");
		err = PTR_ERR(filp1);
		goto out8_1;
	    } else {
		printk("Output File created succesfully\n");
		outFileCreated = true;
	    }
        } else {
            printk("Output File exists\n");
        }

	if(!outFileCreated) {
	    if(!filp1 || IS_ERR(filp1)) {
		printk("Error in opening output file\n");
		err = PTR_ERR(filp1);
                goto out8_1;
	    }
	}

	if(!outFileCreated) {
	    outputFileMode = filp1->f_inode->i_mode;
	
	    if(!S_ISREG(outputFileMode)) {
                printk("Output File is not a regular file\n");
                err = -EISDIR;
		goto out9;
            }
	}

	if(!outFileCreated) {
	    if (filp->f_inode->i_ino == filp1->f_inode->i_ino) {
	        printk("Both input and output files are same, they should be different\n");
	        err = -EPERM;
		goto out9;
 	    }
	}
	
	if(!outFileCreated) {
	    olddentry = filp1->f_path.dentry;
            filp_close(filp1, NULL);
	    tempOutFile =  (char *)kmalloc((strlen(arguments->outputFile)+5)*sizeof(char), GFP_KERNEL);
	    strncpy(tempOutFile, arguments->outputFile, strlen(arguments->outputFile));
	    strcat(tempOutFile, ".tmp");
	    tempOutFile[(strlen(arguments->outputFile)+5)]='\0';
	    filp1 = filp_open(tempOutFile, O_WRONLY, 0);
            if (PTR_ERR(filp1)==-ENOENT || IS_ERR(filp1)) {
                printk("temp Output File doesnot exists, creating it\n");
            } else {
                printk("temp output File exists, truncating and creating new one\n");
		dentry = filp1->f_path.dentry;
		filp_close(filp1, NULL);
		err = file_unlink(dentry->d_parent->d_inode, dentry);
		if(err != 0) {
		    printk("unlink of already existing temporary file failed\n");
		    err = -EBUSY;
		    goto out9;
		}
		printk("unlink function returned : %d\n", err);
            }
            filp1 = filp_open(tempOutFile, O_CREAT, outputFileMode);
            if(!filp1 || IS_ERR(filp1)) {
                printk("Error in creating temp output file\n");
                err = PTR_ERR(filp1);
		goto out8_1;
            } else {
                printk("temp output File created succesfully\n");
            }
	}
	
	newdentry = filp1->f_path.dentry;

	if (!filp1 || IS_ERR(filp1)) {
            printk("Write error for output file %d\n", (int) PTR_ERR(filp1));
            err = PTR_ERR(filp1);
	    goto out10;
        }

        if (!filp1->f_op->write) {
	    printk("Error in writing to temp output file\n");
            err = PTR_ERR(filp1);
	    goto out10;
	}

	md5_hash = kmalloc(17*sizeof(char), GFP_KERNEL);
	if (md5_hash==NULL) {
            printk("Failed to allocate kernel memory for key from file\n");
            err = -ENOMEM;
	    goto out10;
        }
        err = generate_md5(arguments->keyBuf, md5_hash, strlen(arguments->keyBuf));
	if(err != 0) {
	    printk("kernel MD5 generation failed\n");
	    goto out11;
	}
	md5_hash[strlen(arguments->keyBuf)] = '\0';
        
	if (arguments->flags) { //ENCRYPTION
	    preambleWritten = wrapfs_write_file(filp1, (void *)(md5_hash), strlen(md5_hash)); /*Writing Key hash to the file*/	   
	    if(preambleWritten < 0) {
		printk("Writing preamble failed\n");
		err = -EFAULT;
		goto out11;
	    }
	    paddingWritten = wrapfs_write_file(filp1, (void *)(padding), 4); /*Writing Inital Padding to the file*/
	    if (paddingWritten < 0) {
		printk("Writing padding failed\n");
                err = -EFAULT;
		goto out11;
	    }
	    while(result==PAGE_SIZE) {
	        result = wrapfs_read_file(filp, (void *)srcbuffer, PAGE_SIZE);
		if(result < 0) {
		    printk("Reading from input file failed\n");
                    err = -EFAULT;
		    goto out11;
		}
	        err = encrypt_Cipher(arguments->keyBuf, srcbuffer, destbuffer, result, &paddedresult);
		if (err < 0) {
		    printk("Error occured while encrypting\n");
		    goto out11;
		}
	        if(paddedresult!=result) {
		    padvalue = paddedresult - result;
		    buildPadding(padding, padvalue);
		    result = paddedresult;
	        }
	        result = wrapfs_write_file(filp1, (void *)destbuffer, result);
		if (result < 0) {
		    printk("Writing to output file failed\n");
                    err = -EFAULT;
		    goto out11;
		}
	    }
	    paddingWritten = wrapfs_write_file_pos(filp1, (void *)padding, 4, preambleWritten);
	    if (paddingWritten < 0) {
                printk("Writing padding failed\n");
                err = -EFAULT;
		goto out11;
            }
	} else {  //DECRYPTION
	    keyFromFile = kmalloc(16*sizeof(char), GFP_KERNEL);
	    if (keyFromFile==NULL) {
                printk("Failed to allocate kernel memory for key from file\n");
                err = -ENOMEM;
		goto out11;
            }
	    temp = wrapfs_read_file(filp, (void *)keyFromFile, strlen(md5_hash));
	    if (temp != strlen(md5_hash)) {
		printk("reading key from file failed\n");
		err = -EFAULT;
		goto out12;
	    }
	    if (compareKeys(md5_hash, keyFromFile, temp)) {
		printk("Both Keys Match\n");
	    } else {
		printk("Both keys doesnot match\n");
		err = -EINVAL; //TODO : Return proper error Value.
		goto out12;
	    }
	    paddingRead = wrapfs_read_file(filp, (void *)padding, 4);
	    if(paddingRead < 0) {
		printk("Reading padding failed\n");
                err = -EFAULT;
		goto out12;
	    }
	    padvalue = reconstructPadding(padding);
	    if (padvalue < 0) {
		printk("Reconstructing padding value failed(negative value not acceptable)\n");
                err = -EFAULT;
		goto out12;
	    }
	    printk("Pad value returned : %d\n", padvalue);
	    while(result==PAGE_SIZE) {
                result = wrapfs_read_file(filp, (void *)srcbuffer, PAGE_SIZE);
		if (result < 0) {
		    printk("Reading from input file failed\n");
                    err = -EFAULT;
		    goto out12;
		}
                printk("result read from file : %u\n", result);
                err = decrypt_Cipher(arguments->keyBuf, srcbuffer, destbuffer, result);
		if (err < 0) {
                    printk("Error occured while encrypting\n");
                    goto out12;
                }	
		if (result<PAGE_SIZE) {
		    result = result - padvalue;
		}
                result = wrapfs_write_file(filp1, (void *)destbuffer, result);
		if(result < 0) {
		    printk("writing to output file failed\n");
                    err = -EFAULT; //TODO goto
		    goto out12;
		}
            }
	}
	if(!outFileCreated) {
	    err = file_rename(newdentry->d_parent->d_inode, newdentry, olddentry->d_parent->d_inode, olddentry);
	    if(err!=0) {
		printk("renaming of tempfile to output file failed\n");
                err = -EBUSY;
		goto out12;
	    } else
		renamed = true;
        } else
	    success = true;

out12:
	if(keyFromFile)
	    kfree(keyFromFile);
out11:
	kfree(md5_hash);
out10:
	if(filp1)
	    filp_close(filp1, NULL);
	if((!renamed && !outFileCreated)||(!success && outFileCreated))
	    file_unlink(newdentry->d_parent->d_inode, newdentry);
out9:
	if(filp1)
	    filp_close(filp1, NULL);
out8_1:
	if(filp)
	    filp_close(filp, NULL);
out8:
	kfree(padding);
out7:
	kfree(destbuffer);
out6:
	kfree(srcbuffer);
out5:
	kfree(arguments->keyBuf);
out4:
	kfree(arguments->outputFile);
out3:
	kfree(arguments->inputFile);
out2:
 	kfree(arguments);
out1:
	return err;
    }
}
示例#8
0
bool GridWorld::computeShortestPath(){
	if (open.empty()){
		std::cout << "ERROR: No tiles to expand on... can't do anything" << std::endl;
		return false;
	}

	double currentRHS, otherG, previousG;

	while (!open.empty() && (compareKeys(open.front()->key, start->key = calculateKey(start)) || start->rhs != start->g)){
		Tile* current = open.front();
		//Notice that CURRENT wasn't pop/removed yet..

		KeyPair k_old = current->key;
		KeyPair k_new = calculateKey(current);

		currentRHS = current->rhs;
		otherG = current->g;

		/*std::cout << "Expanding:";
		current->info();
		std::cout << std::endl;*/

		if (compareKeys(k_old, k_new)){
			//This branch updates tile that were already in the OPEN list originally
			//This branch tends to execute AFTER the else branch
			current->key = k_new;
			make_heap(open.begin(), open.end(), GridWorld::compareTiles);

		}
		else if (otherG > currentRHS){
			//Majority of the execution will fall under this conditional branch as
			//it is undergoing normal A* pathfinding

			current->g = current->rhs;
			otherG = currentRHS;

			open.erase(open.begin());
			make_heap(open.begin(), open.end(), GridWorld::compareTiles);
			current->isOpen = false;

			std::vector<Tile*> neighbours(getNeighbours(current));
			for (int i = 0; i < neighbours.size(); i++){
				if (neighbours[i] != 0){
					if (neighbours[i] != goal){
						neighbours[i]->rhs = std::min(neighbours[i]->rhs, calculateC(current, neighbours[i]) + otherG);
					}
					updateVertex(neighbours[i]);
				}
			}

		}
		else {
			//Execution of this branch updates the tile during incremental search

			previousG = otherG;
			current->g = PF_INFINITY;

			//Update CURRENT'S RHS
			if (current != goal){
				current->rhs = getMinSuccessor(current).second;
			}
			updateVertex(current);

			//Update NEIGHBOUR'S RHS to their minimum successor
			std::vector<Tile*> neighbours(getNeighbours(current));
			for (int i = 0; i < neighbours.size(); i++){
				if (neighbours[i] != 0){
					if (neighbours[i]->rhs == (calculateC(current, neighbours[i]) + previousG) && neighbours[i] != goal){
						neighbours[i]->rhs = getMinSuccessor(neighbours[i]).second;
					}
					updateVertex(neighbours[i]);
				}
			}

		}
		//Uncomment this to see CURRENT'S new values
		//std::cout << "Expanded:";
		//current->info();
		//std::cout << std::endl;
	}
	return true;
}