Exemple #1
0
void Database_create(struct Connection *conn)
{
  int i;

  for(i = 0; i < MAX_ROWS; i++) {
    // make a prototype to initialize it
    struct Address addr = {.id = i, .set = 0};
    // then assign it
    conn->db->rows[i] = addr;
  }
}

void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{
  struct Address *addr = &conn->db->rows[id];
  if(addr->set) die(conn, "Already set, delete it first");

  addr->set = 1;

  strncpy(addr->name, name, MAX_DATA);
  addr->name[MAX_DATA - 1]  = '\0';

  strncpy(addr->email, email, MAX_DATA);
  addr->email[MAX_DATA - 1]  = '\0';
}

void Database_get(struct Connection *conn, int id)
{
  struct Address *addr = &conn->db->rows[id];

  if(addr->set) {
    Address_print(addr);
  } else {
    die(conn, "ID is not set");
  }
}

void Database_find(struct Connection *conn, const char *name)
{
  int i;
  int found = 0;
  struct Database *db = conn->db;

  for(i = 0; i < MAX_ROWS; i++) {
    struct Address *addr = &db->rows[i];

    if(strcmp(addr->name, name) == 0) {
      Address_print(addr);
      found = 1;
      break;
    }
  }

  if(!found) {
    printf("%s was not found\n", name);
  }
}
Exemple #2
0
void Database_create(struct Connection *conn)
{
	int i = 0;
	for(i = 0; i< MAX_ROWS; i++) {
		//make a prototype to initialize it
		struct Address addr= {.id=i, .set= 0};
		//then just assing it
		conn->db->rows[i] = addr;
	}
}


void Database_set(struct Connection *conn, int id, const char *name, const char *email)
{

	struct Address *addr = &conn->db->rows[id];
	if(addr->set) die("Already set, delete it first");

	addr->set = 1;
	//Warning: bug, read the "How to Break It" and fix this
	char *res = strncpy(addr->name, name, MAX_DATA);
	//demonstrate the strncpy bug
	if(!res) die("Name copy failed");

	res = strncpy(addr->email, email, MAX_DATA);
	if(!res) die("Email copy failed");
}

void Database_get(struct Connection *conn, int id)
{
	struct Address *addr = &conn->db->rows[id];

	if(addr->set){
		Address_print(addr);
	} else{
		die("ID is not set");
	}
}

void Database_find(struct Connection *conn, char *name)
{
	int i = 0;
	for (i = 0; i < MAX_ROWS; i++){
		struct Address *addr = &conn->db->rows[i];
		if (strcmp(addr->name, name) == 0){
			Address_print(addr);
			return;
		}
	}
	die("Record not found");
}			
Exemple #3
0
static uint8_t serverFirstIncoming(struct Message* msg, struct Interface* iface)
{
    struct UDPInterfaceContext* uictx = (struct UDPInterfaceContext*) iface->receiverContext;

    struct Interface* udpDefault = UDPInterface_getDefaultInterface(uictx->udpContext);
    assert(udpDefault);
    UDPInterface_bindToCurrentEndpoint(udpDefault);

    struct User* u = CryptoAuth_getUser(iface);
    assert(u);
    // Add it to the switch, this will change the receiveMessage for this interface.
    struct Address addr;
    memset(&addr, 0, sizeof(struct Address));
    SwitchCore_addInterface(iface, u->trust, &addr.networkAddress_be, uictx->context->switchCore);

    uint8_t* herKey = CryptoAuth_getHerPublicKey(iface);
    memcpy(addr.key, herKey, 32);
    uint8_t printedAddr[60];
    Address_print(printedAddr, &addr);
    Log_info1(uictx->context->logger,
              "Node %s has connected to us.\n",
              printedAddr);

    // Prepare for the next connection.
    struct Interface* newUdpDefault = UDPInterface_getDefaultInterface(uictx->udpContext);
    struct Interface* newAuthedUdpDefault =
        CryptoAuth_wrapInterface(newUdpDefault, NULL, true, true, uictx->context->ca);
    newAuthedUdpDefault->receiveMessage = serverFirstIncoming;
    newAuthedUdpDefault->receiverContext = uictx;

    // Send the message on to the switch so the first message isn't lost.
    return iface->receiveMessage(msg, iface);
}
static void showActiveSearch(Dict* args, void* vctx, String* txid, struct Allocator* alloc)
{
    struct Context* ctx = Identity_check((struct Context*) vctx);
    int number = *(Dict_getIntC(args, "number"));

    struct SearchRunner_SearchData* search =
        SearchRunner_showActiveSearch(ctx->runner, number, alloc);

    Dict* dict = Dict_new(alloc);

    // Nothing is an error
    Dict_putString(dict, String_new("error", alloc), String_new("none", alloc), alloc);

    if (number < search->activeSearches) {
        uint8_t target[40];
        AddrTools_printIp(target, search->target);
        Dict_putString(dict, String_new("target", alloc), String_new((char*)target, alloc), alloc);

        uint8_t lastNodeAsked[60];
        Address_print(lastNodeAsked, &search->lastNodeAsked);
        Dict_putString(dict,
                       String_new("lastNodeAsked", alloc),
                       String_new((char*)lastNodeAsked, alloc),
                       alloc);

        Dict_putInt(dict, String_new("totalRequests", alloc), search->totalRequests, alloc);
    }
    Dict_putInt(dict, String_new("activeSearches", alloc), search->activeSearches, alloc);

    Admin_sendMessage(dict, txid, ctx->admin);
}
void Keywords_find(struct Connection *connsrch, char **keywords, int counter)
{
    int rescntr = 0;                // counts findings
    struct Address *cur = connsrch->db->rows;
    int kwrd_index = counter + 2;   // gives the keyword index( 3 are the initial arguments of which we are totaly un-inderested so 2 their max index)
    int i;
        
    for( i = 0; i < counter; i++, kwrd_index--)
    {  
        printf("_Search term: \"%s\" \n",keywords[kwrd_index]);    	                  
        
        for(int j = 0; j < connsrch->db->MAX_ROWS; j++)
        {   
            if(cur[j].set)
            {
                if(Check_data(keywords[kwrd_index], &cur[j]))
                {
                    Address_print(&cur[j]);
                    rescntr++; 
                }
            }                              
        }
    }
    printf("\n	Search proccess returns %d result(s).\n\n", rescntr);
    printf("----------------------------------------------------------------------------------------------------------------------------------------\n");          
}
Exemple #6
0
int main() {
    int max_rows = 10;
    int max_data = 10;

    printf("bananas\n");
    
    struct Database *db = malloc(sizeof(struct Database));
    db->rows = malloc(sizeof(struct Address) * max_rows);
    
    for (int i = 0; i < max_rows; i++) {
        struct Address addr = {.id=i, .set=1};
        addr.name = malloc(max_data);
        addr.email = malloc(max_data);
        db->rows[i] = addr;
    }
    
    struct Address *addr = &db->rows[2];
    strncpy(addr->name, "Bananas", max_data);

    for (int i = 0; i < max_rows; i++) {
        Address_print(&db->rows[i]);
    }
    

    for (int i = 0; i < max_rows; i++) {
        free(db->rows[i].name);
        free(db->rows[i].email);
    }
    free(db->rows);
    free(db);

    return 0;
}
Exemple #7
0
void Database_get(struct Connection *conn, int id) {
	struct Address *addr = &conn->db->rows[id];
	if (addr->set)
		Address_print(addr);
	else
		die("ID is not set.");
}
Exemple #8
0
void RumorMill__addNode(struct RumorMill* mill, struct Address* addr, const char* file, int line)
{
    struct RumorMill_pvt* rm = Identity_check((struct RumorMill_pvt*) mill);

    Address_getPrefix(addr);

    for (int i = 0; i < rm->pub.count; i++) {
        if (rm->pub.addresses[i].path == addr->path &&
                !Bits_memcmp(rm->pub.addresses[i].key, addr->key, 32))
        {
            return;
        }
    }

    if (!Bits_memcmp(addr->key, rm->selfAddr->key, 32)) {
        return;
    }

    struct Address* replace;
    if (rm->pub.count < rm->capacity) {
        replace = &rm->pub.addresses[rm->pub.count++];
    } else {
        replace = getWorst(rm);
    }
    Bits_memcpyConst(replace, addr, sizeof(struct Address));

    if (Defined(Log_DEBUG)) {
        uint8_t addrStr[60];
        Address_print(addrStr, addr);
        Log_debug(rm->log, "[%s] addNode(%s) count[%d] from [%s:%d]",
                  rm->pub.name, addrStr, rm->pub.count, file, line);
    }
}
Exemple #9
0
static inline uint8_t incomingDHT(struct Message* message,
                                  struct Address* addr,
                                  struct Ducttape_pvt* context)
{
    struct DHTMessage dht;
    Bits_memset(&dht, 0, sizeof(struct DHTMessage));

    // TODO: These copies are not necessary at all.
    const uint32_t length = (message->length < DHTMessage_MAX_SIZE)
        ? message->length
        : DHTMessage_MAX_SIZE;
    Bits_memcpy(dht.bytes, message->bytes, length);

    dht.address = addr;

    uint8_t buffer[PER_MESSAGE_BUF_SZ];
    dht.allocator = BufferAllocator_new(buffer, PER_MESSAGE_BUF_SZ);

    struct Jmp j;
    Jmp_try(j) {
        BufferAllocator_onOOM(dht.allocator, &j.handler);
        DHTModuleRegistry_handleIncoming(&dht, context->registry);
    } Jmp_catch {
        uint8_t printed[60];
        Address_print(printed, addr);
        Log_warn(context->logger, "Parsing message from [%s] failed; out of memory.", printed);
    }

    // TODO: return something meaningful.
    return Error_NONE;
}
Exemple #10
0
static void lookup(Dict* args, void* vcontext, String* txid, struct Allocator* requestAlloc)
{
    struct Context* ctx = vcontext;
    String* addrStr = Dict_getString(args, String_CONST("address"));
    char* err = NULL;
    uint8_t addr[16];
    uint8_t resultBuff[60];
    char* result = (char*) resultBuff;
    if (addrStr->len != 39) {
        err = "address wrong length";
    } else if (AddrTools_parseIp(addr, (uint8_t*) addrStr->bytes)) {
        err = "failed to parse address";
    } else {
        struct Node_Two* n = Router_lookup(ctx->router, addr);
        if (!n) {
            result = "not found";
        } else if (Bits_memcmp(addr, n->address.ip6.bytes, 16)) {
            Address_print(resultBuff, &n->address);
        } else {
            AddrTools_printPath(resultBuff, n->address.path);
        }
    }
    Dict response = Dict_CONST(
        String_CONST("error"), String_OBJ(String_CONST((err) ? err : "none")), Dict_CONST(
        String_CONST("result"), String_OBJ(String_CONST(result)), NULL
    ));
    Admin_sendMessage(&response, txid, ctx->admin);
}
Exemple #11
0
/*
 * Zeros object at id. It's possible that create can just call this
 * as in it's for loop
 */
void Database_delete(struct Connection *conn, int id)
{
    //TODO this might need to change to deal with the new structure
    struct Address addr = {.id = id, .set = 0};
    conn->db->rows[id] = addr;
}

/*
 * Loop though the DB and if something is set print it
 */

void Database_list(struct Connection *conn)
{
    //TODO this might need to change to deal with the new structure
    int i = 0;
    struct Database *db = conn->db; //conn->db is a pointer to the DB

    for(i = 0; i < db->size; i++){
        //but db->rows[i] is an actual struct, hence the need for the &
        struct Address *cur = &db->rows[i]; 

        if (cur->set){
            Address_print(cur);
        }
    }
}
Exemple #12
0
void Database_get(Connection* c, int id) {
        Address* addr = &(c->db->rows[id]);

        if(addr->set) {
                Address_print(addr);
        } else {
                die(c,"Attempted `get` on unset entry");
        }
}
static void onPingResponse(struct SwitchPinger_Response* resp, void* onResponseContext)
{
    if (SwitchPinger_Result_OK != resp->res) {
        return;
    }
    struct InterfaceController_Peer* ep =
        Identity_check((struct InterfaceController_Peer*) onResponseContext);
    struct InterfaceController_pvt* ic = ifcontrollerForPeer(ep);

    struct Address addr;
    Bits_memset(&addr, 0, sizeof(struct Address));
    Bits_memcpyConst(addr.key, CryptoAuth_getHerPublicKey(ep->cryptoAuthIf), 32);
    addr.path = ep->switchLabel;
    addr.protocolVersion = resp->version;

    #ifdef Log_DEBUG
        uint8_t addrStr[60];
        Address_print(addrStr, &addr);
        uint8_t key[56];
        Base32_encode(key, 56, CryptoAuth_getHerPublicKey(ep->cryptoAuthIf), 32);
    #endif

    if (!Version_isCompatible(Version_CURRENT_PROTOCOL, resp->version)) {
        Log_debug(ic->logger, "got switch pong from node [%s] with incompatible version [%d]",
                  key, resp->version);
    } else {
        Log_debug(ic->logger, "got switch pong from node [%s] with version [%d]",
                  key, resp->version);
    }

    if (!ep->timeOfLastPing) {
        // We've never heard from this machine before (or we've since forgotten about it)
        // This is here because we want the tests to function without the janitor present.
        // Other than that, it just makes a slightly more synchronous/guaranteed setup.
        Router_sendGetPeers(ic->router, &addr, 0, 0, ic->allocator);
    }

    struct Node_Link* link = Router_linkForPath(ic->router, resp->label);
    if (!link || !Node_getBestParent(link->child)) {
        RumorMill_addNode(ic->rumorMill, &addr);
    } else {
        Log_debug(ic->logger, "link exists");
    }

    ep->timeOfLastPing = Time_currentTimeMilliseconds(ic->eventBase);

    #ifdef Log_DEBUG
        // This will be false if it times out.
        //Assert_true(label == ep->switchLabel);
        uint8_t path[20];
        AddrTools_printPath(path, resp->label);
        uint8_t sl[20];
        AddrTools_printPath(sl, ep->switchLabel);
        Log_debug(ic->logger, "Received [%s] from lazy endpoint [%s]  [%s]",
                  SwitchPinger_resultString(resp->res)->bytes, path, sl);
    #endif
}
Exemple #14
0
void Database_get(int id)
{
    struct Address *addr = &conn->db->rows[id];

    if(addr->set) {
        Address_print(addr);
    } else {
        die("ID is not set");
    }
}
Exemple #15
0
void Database_get(struct Connection *conn, int id)
{
	struct Address *addr = conn->db->rows[id];

	if(addr->set) {
		Address_print(addr);
	} else {
		die("ID is not set", conn);
	}
}
Exemple #16
0
void Database_find(struct Connection *conn, char *name)
{
	int i = 0;
	for(i = 0; i < MAX_ROWS; i++) {
		struct Address *addr = &conn->db->rows[i];
		if(strcmp(addr->name, name) == 0) {
			Address_print(addr);
		}
	}
}
Exemple #17
0
void Database_get(struct Connection *conngt, int id)
{
    struct Address *tmp = &conngt->db->rows[id];

    if(tmp->set) {
        Address_print(tmp);
    } else {
        die(conngt, "ID is not set");
    }
}
Exemple #18
0
/*
 *Get basically prints the record
 */
void Database_get(struct Connection *conn, int id)
{
    //TODO this might need to change to deal with the new structure
    struct Address *addr = &conn->db->rows[id];

    if(addr->set){
        Address_print(addr);
    } else{
        die("ID is not set",conn);
    }
}
Exemple #19
0
void Database_find(struct Connection *conn, char *term) {
int i = 0;
for (i = 0; i < conn->db->max_rows; i++) {
	struct Address *addr = &conn->db->rows[i];
	if (strcmp(addr->name, term) == 0 || strcmp(addr->email, term) == 0) {
		Address_print(addr);
		return;
	}
}
printf("No records matching '%s'\n", term);
}
Exemple #20
0
void Database_list()
{
    int i = 0;

    for(i = 0; i < max_rows; i++) {
        struct Address *cur = &conn->db->rows[i];
    
        if(cur->set) {
            Address_print(cur);
        }
    }
}
Exemple #21
0
void Database_find_name(struct Connection *conn, const char *name)
{
  int i = 0;
  struct Database *db = conn->db;

  for (i = 0; i < MAX_ROWS; i++) {
    struct Address *cur = &db->rows[i];
    if (cur->set && strcmp(cur->name, name)) {
      Address_print(cur);
    }
  }
}
Exemple #22
0
void Database_find(char *email)
{
    int i;

    for (i = 0; i < max_rows; i++) {
        if (strcmp(conn->db->rows[i].email, email) == 0) {
            Address_print(&conn->db->rows[i]);
            return;
        } 
    }
    die("Email is not set");
}
Exemple #23
0
int main(int argc, char *argv[])
{
    Address *addr = (Address *)malloc(sizeof(Address));
    char *name = "frost";
    char *email = "*****@*****.**";
    addr->id = 10;
    addr->name = name;
    addr->email = email;

    Address_print(addr);
    return 0;
}
Exemple #24
0
void Database_list(struct Connection *conn) {
    int i = 0;
    struct Database *db = conn->db;

    for (i=0; i < MAX_ROWS; i++) {
        struct Address *cur = &db->rows[i];

        if (cur->set) {
            Address_print(cur);
        }
    }
}
Exemple #25
0
void Database_delete(struct Connection* conn, int id)
{
        struct Address addr = {.id = id, .set = 0};
        conn->db->rows[id] = addr;
}

void Database_list(struct Connection* conn)
{
        for(int i = 0; i < conn->db->MAX_ROWS; i++) {
                if(conn->db->rows[i].set) {
                        Address_print(&(conn->db->rows[i]));
                }
        }
}

void Database_find(struct Connection* conn, char* keyword) {
        int i=0;
        int count=0;

        while (i < conn->db->MAX_ROWS) {
                while ( i<conn->db->MAX_ROWS) {
                        if(conn->db->rows[i].set==1){
                                if(strstr(conn->db->rows[i].name, keyword) != NULL || strstr(conn->db->rows[i].email, keyword) != NULL){
                                        break;
                                }
                        }
                        i++;
                }

                if(i >= conn->db->MAX_ROWS) break;

                Address_print(&(conn->db->rows[i]));
                count++;
                i++;
        }

        if (count==0) {
                printf("Try some other words\n");
        }
}
Exemple #26
0
void Database_list(struct Connection *connlst)
{
    int i = 0;
    int MAX_ROWS = connlst->db->MAX_ROWS;

    for(i = 0; i < MAX_ROWS; i++) 
    {
        if(connlst->db->rows[i].set) 
        {
            Address_print(&(connlst->db->rows[i]));
        }
    }
}
Exemple #27
0
void Database_get(struct Connection* connection, long id)
{
     struct Address* row = &connection->db->rows[id];

    if(row->is_set)
    {
        Address_print(row);
    }
    else
    {
        die("ID is not set. \n");
    }
}
Exemple #28
0
void Database_list(struct Connection* connection)
{
    int i = 0;

    printf("The contents of the database are: \n");
    for(i = 0; i < MAX_ROWS; i++)
    {
        if(connection->db->rows[i].is_set)
        {
            Address_print(&connection->db->rows[i]);
            printf("\n");
        }
    }
}
Exemple #29
0
// Called by the TUN device.
static inline uint8_t ip6FromTun(struct Message* message,
                                 struct Interface* interface)
{
    struct Context* context = (struct Context*) interface->receiverContext;

    if (!validIP6(message)) {
        Log_debug(context->logger, "dropped message from TUN because it was not valid IPv6.\n");
        return Error_INVALID;
    }

    struct Headers_IP6Header* header = (struct Headers_IP6Header*) message->bytes;

    if (memcmp(header->sourceAddr, context->myAddr.ip6.bytes, 16)) {
        Log_warn(context->logger, "dropped message because only one address is allowed to be used "
                                  "and the source address was different.\n");
        return Error_INVALID;
    }

    context->switchHeader = NULL;

    struct Node* bestNext = RouterModule_getBest(header->destinationAddr, context->routerModule);
    if (bestNext) {
        context->forwardTo = &bestNext->address;
        if (!memcmp(header->destinationAddr, bestNext->address.ip6.bytes, 16)) {
            // Direct send, skip the innermost layer of encryption.
            header->hopLimit = 0;
            #ifdef Log_DEBUG
                uint8_t nhAddr[60];
                Address_print(nhAddr, &bestNext->address);
                Log_debug1(context->logger, "Forwarding data to %s (last hop)\n", nhAddr);
            #endif
            return sendToRouter(&bestNext->address, message, context);
        }
    }

    // Grab out the header so it doesn't get clobbered.
    struct Headers_IP6Header headerStore;
    memcpy(&headerStore, header, Headers_IP6Header_SIZE);
    context->ip6Header = &headerStore;

    // Shift over the content.
    Message_shift(message, -Headers_IP6Header_SIZE);

    struct Interface* session =
        SessionManager_getSession(headerStore.destinationAddr, NULL, context->sm);

    // This comes out at outgoingFromMe()
    context->layer = INNER_LAYER;
    return session->sendMessage(message, session);
}
Exemple #30
0
void Database_list(struct Connection *conn)
{
	int i = 0;
	struct Database *db = conn->db;

	printf("Max rows: %d\n", db->MAX_ROWS);
	printf("Max data: %d\n", db->MAX_DATA);

	for(i = 0; i < db->MAX_ROWS; i++) {
		struct Address *cur = db->rows[i];

		if(cur->set) {
			Address_print(cur);
		}
	}
}