Ejemplo n.º 1
0
static int calculateAuth(Dict* message,
                         String* password,
                         String* cookieStr,
                         struct Allocator* alloc)
{
    // Calculate the hash of the password.
    String* hashHex = String_newBinary(NULL, 64, alloc);
    uint8_t passAndCookie[64];
    uint32_t cookie = (cookieStr != NULL) ? strtoll(cookieStr->bytes, NULL, 10) : 0;
    snprintf((char*) passAndCookie, 64, "%s%u", password->bytes, cookie);
    uint8_t hash[32];
    crypto_hash_sha256(hash, passAndCookie, strlen((char*) passAndCookie));
    Hex_encode((uint8_t*)hashHex->bytes, 64, hash, 32);

    Dict_putString(message, String_new("hash", alloc), hashHex, alloc);
    Dict_putString(message, String_new("cookie", alloc), cookieStr, alloc);

    // serialize the message with the password hash
    uint8_t buffer[AdminClient_MAX_MESSAGE_SIZE];
    struct Writer* writer = ArrayWriter_new(buffer, AdminClient_MAX_MESSAGE_SIZE, alloc);
    if (StandardBencSerializer_get()->serializeDictionary(writer, message)) {
        return -1;
    }
    int length = writer->bytesWritten;

    // calculate the hash of the message with the password hash
    crypto_hash_sha256(hash, buffer, length);

    // swap the hash of the message with the password hash into the location
    // where the password hash was.
    Hex_encode((uint8_t*)hashHex->bytes, 64, hash, 32);
    return 0;
}
Ejemplo n.º 2
0
int main(int ____c, char *____v[])
{
	setup_error_handlers();
	gc_begin_func();
	STRING(s1);
	STRING(s2);
	STRING(t);
	bool s1t;
	bool s2t;
	s1 = String_new("hellp");
	s2 = String_new("aello");
	t = String_new("hello");
	s1t = str_gt(s1,t);
	if (s1t) {
		gt_msg(s1,t);
	}
	else {
		le_msg(s1,t);
	}
	s2t = str_gt(s2,t);
	if (s2t) {
		gt_msg(s2,t);
	}
	else {
		le_msg(s2,t);
	}
	gc_end_func();

	gc();
	Heap_Info info = get_heap_info();
	if ( info.live!=0 ) fprintf(stderr, "%d objects remain after collection\n", info.live);
	gc_shutdown();
	return 0;
}
Ejemplo n.º 3
0
void f() {
	// var x = "cat" + "dog"
	String *tmp1;
	String *tmp2;
	String *x = String_add(tmp1=String_new("cat"), tmp2=String_new("dog"));

	// print(x)
	print_string(x);

	// print(x[1]+x[3])
	String *tmp3;
	String *tmp4;
	String *tmp5;
	print_string(
		   tmp5=String_add(
			   tmp3=String_from_char(x->str[(1)-1]),
			   tmp4=String_from_char(x->str[(3)-1])
		   )
	);

	// end of scope code; drop ref count by 1 for all [], string vars
	DEREF(x);
	DEREF(tmp1);
	DEREF(tmp2);
	DEREF(tmp3);
	DEREF(tmp4);
	DEREF(tmp5);
}
Ejemplo n.º 4
0
static int calculateAuth(Dict* message,
                         String* password,
                         String* cookieStr,
                         struct Allocator* alloc)
{
    // Calculate the hash of the password.
    String* hashHex = String_newBinary(NULL, 64, alloc);
    uint8_t passAndCookie[64];
    uint32_t cookie = (cookieStr != NULL) ? strtoll(cookieStr->bytes, NULL, 10) : 0;
    snprintf((char*) passAndCookie, 64, "%s%u", password->bytes, cookie);
    uint8_t hash[32];
    crypto_hash_sha256(hash, passAndCookie, CString_strlen((char*) passAndCookie));
    Hex_encode((uint8_t*)hashHex->bytes, 64, hash, 32);

    Dict_putString(message, String_new("hash", alloc), hashHex, alloc);
    Dict_putString(message, String_new("cookie", alloc), cookieStr, alloc);

    // serialize the message with the password hash
    struct Message* msg = Message_new(0, AdminClient_MAX_MESSAGE_SIZE, alloc);
    BencMessageWriter_write(message, msg, NULL);

    // calculate the hash of the message with the password hash
    crypto_hash_sha256(hash, msg->bytes, msg->length);

    // swap the hash of the message with the password hash into the location
    // where the password hash was.
    Hex_encode((uint8_t*)hashHex->bytes, 64, hash, 32);
    return 0;
}
Ejemplo n.º 5
0
static void getSomething(Dict* args,
                         struct RouteGen_admin_Ctx* ctx,
                         String* txid,
                         struct Allocator* requestAlloc,
                         Dict* genRoutes)
{
    int page = getIntVal(args, String_CONST("page"));
    List* routes;
    if (getIntVal(args, String_CONST("ip6"))) {
        routes = Dict_getList(genRoutes, String_CONST("ipv6"));
    } else {
        routes = Dict_getList(genRoutes, String_CONST("ipv4"));
    }
    Assert_true(routes);
    List* outList = List_new(requestAlloc);
    bool more = false;
    for (int i = page * ROUTES_PER_PAGE, j = 0; i < List_size(routes) && j < ROUTES_PER_PAGE; j++) {
        String* route = List_getString(routes, i);
        Assert_true(route);
        List_addString(outList, route, requestAlloc);
        if (++i >= List_size(routes)) {
            more = false;
            break;
        }
        more = true;
    }
    Dict* out = Dict_new(requestAlloc);
    if (more) {
        Dict_putInt(out, String_new("more", requestAlloc), 1, requestAlloc);
    }
    Dict_putList(out, String_new("routes", requestAlloc), outList, requestAlloc);
    Admin_sendMessage(out, txid, ctx->admin);
}
Ejemplo n.º 6
0
int main(int ____c, char *____v[])
{
    setup_error_handlers();
    print_string(becomeSuper(String_new("man")));
    print_string(becomeSuper(String_new("duper")));
    return 0;
}
Ejemplo n.º 7
0
Dict* Security_getUser(char* userName, struct Allocator* retAlloc)
{
    Dict* ret = Dict_new(retAlloc);
    Dict_putString(ret, String_new("error", retAlloc),
                        String_new("Not supported on windows", retAlloc),
                        retAlloc);
    return ret;
}
Ejemplo n.º 8
0
static int set_device(Instance *pi, const char *value)
{
  ALSAio_private *priv = (ALSAio_private *)pi;
  int rc = 0;
  int i;

  String_free(&priv->c.device);
  priv->c.device = String_new(value);

  if (priv->c.handle) {
    snd_pcm_close(priv->c.handle);
  }

  /* Try matching by description first... */
  Range available_alsa_devices = {};
  get_device_range(pi, &available_alsa_devices);
  for (i=0; i < available_alsa_devices.descriptions.count; i++) {
    if (strstr(available_alsa_devices.descriptions.items[i]->bytes, value)) {
      puts("found it!");
      priv->c.device = String_new(available_alsa_devices.strings.items[i]->bytes);
      break;
    }
  }

  Range_clear(&available_alsa_devices);

  if (String_is_none(priv->c.device)) {
    /* Not found, try value as supplied. */
    priv->c.device = String_new(value);
  }

  rc = snd_pcm_open(&priv->c.handle, s(priv->c.device), priv->c.mode, 0);
  if (rc < 0) {
    fprintf(stderr, "*** snd_pcm_open %s: %s\n", s(priv->c.device), snd_strerror(rc));
    goto out;
  }

  fprintf(stderr, "ALSA device %s opened, handle=%p\n", s(priv->c.device), priv->c.handle);

  /* Allocate hardware parameter structure, and call "any", and use
     the resulting hwparams in subsequent calls.  I had tried calling
     _any() in each get/set function, but recording failed, so it
     seems ALSA doesn't work that way. */
  snd_pcm_hw_params_malloc(&priv->c.hwparams);
  rc = snd_pcm_hw_params_any(priv->c.handle, priv->c.hwparams);

  /* Might as well set interleaved here, too. */
  rc = snd_pcm_hw_params_set_access(priv->c.handle, priv->c.hwparams,
                                    SND_PCM_ACCESS_RW_INTERLEAVED);
  if (rc != 0) {
    fprintf(stderr, "*** snd_pcm_hw_params_set_access %s: %s\n", s(priv->c.device), snd_strerror(rc));
  }

 out:
  return rc;
}
Ejemplo n.º 9
0
static Dict* makeLogMessage(struct Subscription* subscription,
                            struct AdminLog* logger,
                            enum Log_Level logLevel,
                            const char* fullFilePath,
                            uint32_t line,
                            const char* format,
                            va_list vaArgs,
                            struct Allocator* alloc)
{
    time_t now;
    time(&now);

    Dict* out = Dict_new(alloc);
    char* buff = Allocator_malloc(alloc, 20);
    Hex_encode((uint8_t*)buff, 20, subscription->streamId, 8);
    Dict_putString(out, String_new("streamId", alloc), String_new(buff, alloc), alloc);
    Dict_putInt(out, String_new("time", alloc), now, alloc);
    Dict_putString(out,
                   String_new("level", alloc),
                   String_new(Log_nameForLevel(logLevel), alloc),
                   alloc);
    const char* shortName = getShortName(fullFilePath);
    Dict_putString(out, String_new("file", alloc), String_new((char*)shortName, alloc), alloc);
    Dict_putInt(out, String_new("line", alloc), line, alloc);
    String* message = String_vprintf(alloc, format, vaArgs);

    // Strip all of the annoying \n marks in the log entries.
    if (message->len > 0 && message->bytes[message->len - 1] == '\n') {
        message->len--;
    }
    Dict_putString(out, String_new("message", alloc), message, alloc);

    return out;
}
Ejemplo n.º 10
0
static void adminPeerStats(Dict* args, void* vcontext, String* txid)
{
    struct Context* context = vcontext;
    struct Allocator* alloc = Allocator_child(context->alloc);
    struct InterfaceController_peerStats* stats = NULL;

    int64_t* page = Dict_getInt(args, String_CONST("page"));
    int i = (page) ? *page * ENTRIES_PER_PAGE : 0;

    int count = context->ic->getPeerStats(context->ic, alloc, &stats);

    String* bytesIn = String_CONST("bytesIn");
    String* bytesOut = String_CONST("bytesOut");
    String* pubKey = String_CONST("publicKey");
    String* state = String_CONST("state");
    String* last = String_CONST("last");
    String* switchLabel = String_CONST("switchLabel");
    String* isIncoming = String_CONST("isIncoming");

    List* list = NULL;
    for (int counter=0; i < count && counter++ < ENTRIES_PER_PAGE; i++) {
        Dict* d = Dict_new(alloc);
        Dict_putInt(d, bytesIn, stats[i].bytesIn, alloc);
        Dict_putInt(d, bytesOut, stats[i].bytesOut, alloc);
        Dict_putString(d, pubKey, Key_stringify(stats[i].pubKey, alloc), alloc);

        String* stateString = String_new(InterfaceController_stateString(stats[i].state), alloc);
        Dict_putString(d, state, stateString, alloc);

        Dict_putInt(d, last, stats[i].timeOfLastMessage, alloc);

        uint8_t labelStack[20];
        AddrTools_printPath(labelStack, stats[i].switchLabel);
        Dict_putString(d, switchLabel, String_new((char*)labelStack, alloc), alloc);

        Dict_putInt(d, isIncoming, stats[i].isIncomingConnection, alloc);

        list = List_addDict(list, d, alloc);
    }

    Dict response = Dict_CONST(
        String_CONST("peers"), List_OBJ(list), Dict_CONST(
        String_CONST("total"), Int_OBJ(count), NULL
    ));

    if (i < count) {
      response = Dict_CONST(
        String_CONST("more"), Int_OBJ(1), response
      );
    }

    Admin_sendMessage(&response, txid, context->admin);

    Allocator_free(alloc);
}
Ejemplo n.º 11
0
static String* getExpectedResponse(struct Sockaddr* sa4, int prefix4, int alloc4,
                                   struct Sockaddr* sa6, int prefix6, int alloc6,
                                   struct Allocator* allocator)
{
    Assert_true(alloc6 >= prefix6);
    Assert_true(alloc4 >= prefix4);
    struct Allocator* alloc = Allocator_child(allocator);
    Dict* addresses = Dict_new(alloc);
    if (sa4) {
        uint8_t* addr = NULL;
        Assert_true(Sockaddr_getAddress(sa4, &addr) == 4);
        String* addrStr = String_newBinary(addr, 4, alloc);
        Dict_putString(addresses, String_new("ip4", alloc), addrStr, alloc);
        Dict_putInt(addresses, String_new("ip4Prefix", alloc), prefix4, alloc);
        Dict_putInt(addresses, String_new("ip4Alloc", alloc), alloc4, alloc);
    }
    if (sa6) {
        uint8_t* addr = NULL;
        Assert_true(Sockaddr_getAddress(sa6, &addr) == 16);
        String* addrStr = String_newBinary(addr, 16, alloc);
        Dict_putString(addresses, String_new("ip6", alloc), addrStr, alloc);
        Dict_putInt(addresses, String_new("ip6Prefix", alloc), prefix6, alloc);
        Dict_putInt(addresses, String_new("ip6Alloc", alloc), alloc6, alloc);
    }
    Dict* output = Dict_new(alloc);
    Dict_putDict(output, String_new("addresses", alloc), addresses, alloc);
    Dict_putString(output, String_new("txid", alloc), String_new("abcd", alloc), alloc);
    struct Message* msg = Message_new(0, 512, alloc);
    BencMessageWriter_write(output, msg, NULL);

    String* outStr = String_newBinary(msg->bytes, msg->length, allocator);
    Allocator_free(alloc);
    return outStr;
}
Ejemplo n.º 12
0
void f()
{
    ENTER();
    STRING(x);
    x = String_add(String_new("cat"),String_new("dog"));
    REF((void *)x);
    print_string(x);
    print_string(String_add(String_from_char(x->str[(1)-1]),String_from_char(x->str[(3)-1])));

    EXIT();
}
Ejemplo n.º 13
0
static void addRemoveSomething(Dict* args,
                               void* vcontext,
                               String* txid,
                               struct Allocator* requestAlloc,
                               enum addRemoveSomething_What what)
{
    struct RouteGen_admin_Ctx* ctx = Identity_check((struct RouteGen_admin_Ctx*) vcontext);
    String* route = Dict_getString(args, String_CONST("route"));
    char* error = NULL;

    struct Sockaddr_storage ss;
    if (route->len > 63) {
        error = "parse_failed";
    }
    if (!error) {
        if (Sockaddr_parse(route->bytes, &ss)) {
            error = "parse_failed";
        } else {
            int family = Sockaddr_getFamily(&ss.addr);
            if (family != Sockaddr_AF_INET && family != Sockaddr_AF_INET6) {
                error = "unexpected_af";
            }
        }
    }
    int retVal = -1;
    Dict* out = Dict_new(requestAlloc);
    if (!error) {
        switch (what) {
            case addRemoveSomething_What_ADD_EXCEPTION:
                RouteGen_addException(ctx->rg, &ss.addr); break;
            case addRemoveSomething_What_ADD_PREFIX:
                RouteGen_addPrefix(ctx->rg, &ss.addr); break;
            case addRemoveSomething_What_ADD_LOCALPREFIX:
                RouteGen_addLocalPrefix(ctx->rg, &ss.addr); break;
            case addRemoveSomething_What_RM_EXCEPTION:
                retVal = RouteGen_removeException(ctx->rg, &ss.addr); break;
            case addRemoveSomething_What_RM_PREFIX:
                retVal = RouteGen_removePrefix(ctx->rg, &ss.addr); break;
            case addRemoveSomething_What_RM_LOCALPREFIX:
                retVal = RouteGen_removeLocalPrefix(ctx->rg, &ss.addr); break;
            default: Assert_failure("invalid op");
        }
        if (!retVal) {
            error = "no_such_route";
        } else {
            error = "none";
        }
    }
    Dict_putString(out,
                   String_new("error", requestAlloc),
                   String_new(error, requestAlloc),
                   requestAlloc);
    Admin_sendMessage(out, txid, ctx->admin);
}
Ejemplo n.º 14
0
static void sessionStats(Dict* args,
                         void* vcontext,
                         String* txid,
                         struct Allocator* alloc)
{
    struct Context* context = Identity_check((struct Context*) vcontext);
    int64_t* handleP = Dict_getInt(args, String_CONST("handle"));
    uint32_t handle = *handleP;

    struct SessionManager_Session* session = SessionManager_sessionForHandle(handle, context->sm);

    Dict* r = Dict_new(alloc);
    if (!session) {
        Dict_putString(r, String_CONST("error"), String_CONST("no such session"), alloc);
        Admin_sendMessage(r, txid, context->admin);
        return;
    }

    uint8_t printedAddr[40];
    AddrTools_printIp(printedAddr, session->caSession->herIp6);
    Dict_putString(r, String_CONST("ip6"), String_new(printedAddr, alloc), alloc);

    String* state =
        String_new(CryptoAuth_stateString(CryptoAuth_getState(session->caSession)), alloc);
    Dict_putString(r, String_CONST("state"), state, alloc);

    struct ReplayProtector* rp = &session->caSession->replayProtector;
    Dict_putInt(r, String_CONST("duplicates"), rp->duplicates, alloc);
    Dict_putInt(r, String_CONST("lostPackets"), rp->lostPackets, alloc);
    Dict_putInt(r, String_CONST("receivedOutOfRange"), rp->receivedOutOfRange, alloc);

    struct Address addr;
    Bits_memcpyConst(addr.key, session->caSession->herPublicKey, 32);
    addr.path = session->sendSwitchLabel;
    addr.protocolVersion = session->version;

    Dict_putString(r, String_CONST("addr"), Address_toString(&addr, alloc), alloc);

    Dict_putString(r, String_CONST("publicKey"),
                      Key_stringify(session->caSession->herPublicKey, alloc), alloc);
    Dict_putInt(r, String_CONST("version"), session->version, alloc);
    Dict_putInt(r, String_CONST("handle"), session->receiveHandle, alloc);
    Dict_putInt(r, String_CONST("sendHandle"), session->sendHandle, alloc);

    Dict_putInt(r, String_CONST("timeOfLastIn"), session->timeOfLastIn, alloc);
    Dict_putInt(r, String_CONST("timeOfLastOut"), session->timeOfLastOut, alloc);

    Dict_putString(r, String_CONST("deprecation"),
        String_CONST("publicKey,version will soon be removed"), alloc);

    Admin_sendMessage(r, txid, context->admin);
    return;
}
Ejemplo n.º 15
0
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);
}
Ejemplo n.º 16
0
void Admin_registerFunctionWithArgCount(char* name,
                                        Admin_FUNCTION(callback),
                                        void* callbackContext,
                                        bool needsAuth,
                                        struct Admin_FunctionArg* arguments,
                                        int argCount,
                                        struct Admin* admin)
{
    if (!admin) {
        return;
    }
    String* str = String_new(name, admin->allocator);
    if (!admin->functionCount) {
        admin->functions = admin->allocator->malloc(sizeof(struct Function), admin->allocator);
    } else {
        admin->functions =
            admin->allocator->realloc(admin->functions,
                                      sizeof(struct Function) * (admin->functionCount + 1),
                                      admin->allocator);
    }
    struct Function* fu = &admin->functions[admin->functionCount];
    admin->functionCount++;

    fu->name = str;
    fu->call = callback;
    fu->context = callbackContext;
    fu->needsAuth = needsAuth;
    fu->args = Dict_new(admin->allocator);
    for (int i = 0; arguments && i < argCount; i++) {
        // "type" must be one of: [ "String", "Int", "Dict", "List" ]
        String* type = NULL;
        if (!strcmp(arguments[i].type, STRING->bytes)) {
            type = STRING;
        } else if (!strcmp(arguments[i].type, INT->bytes)) {
            type = INT;
        } else if (!strcmp(arguments[i].type, DICT->bytes)) {
            type = DICT;
        } else if (!strcmp(arguments[i].type, LIST->bytes)) {
            type = LIST;
        } else {
            abort();
        }
        Dict* arg = Dict_new(admin->allocator);
        Dict_putString(arg, TYPE, type, admin->allocator);
        Dict_putInt(arg, REQUIRED, arguments[i].required, admin->allocator);
        String* name = String_new(arguments[i].name, admin->allocator);
        Dict_putDict(fu->args, name, arg, admin->allocator);
    }
}
Ejemplo n.º 17
0
static void sessionStats(Dict* args,
                         void* vcontext,
                         String* txid,
                         struct Allocator* alloc)
{
    struct Context* context = vcontext;
    int64_t* handleP = Dict_getInt(args, String_CONST("handle"));
    uint32_t handle = *handleP;

    struct SessionManager_Session* session = SessionManager_sessionForHandle(handle, context->sm);
    uint8_t* ip6 = SessionManager_getIp6(handle, context->sm);

    Dict* r = Dict_new(alloc);
    if (!session) {
        Dict_putString(r, String_CONST("error"), String_CONST("no such session"), alloc);
        Admin_sendMessage(r, txid, context->admin);
        return;
    }
    // both or neither
    Assert_true(ip6);

    uint8_t printedAddr[40];
    AddrTools_printIp(printedAddr, ip6);
    Dict_putString(r, String_CONST("ip6"), String_new(printedAddr, alloc), alloc);

    Dict_putString(r,
                   String_CONST("state"),
                   String_new(CryptoAuth_stateString(session->cryptoAuthState), alloc),
                   alloc);

    struct ReplayProtector* rp = CryptoAuth_getReplayProtector(session->internal);
    Dict_putInt(r, String_CONST("duplicates"), rp->duplicates, alloc);
    Dict_putInt(r, String_CONST("lostPackets"), rp->lostPackets, alloc);
    Dict_putInt(r, String_CONST("receivedOutOfRange"), rp->receivedOutOfRange, alloc);

    uint8_t* key = CryptoAuth_getHerPublicKey(session->internal);
    Dict_putString(r, String_CONST("publicKey"), Key_stringify(key, alloc), alloc);
    Dict_putInt(r, String_CONST("version"), session->version, alloc);
    Dict_putInt(r, String_CONST("handle"),
                Endian_bigEndianToHost32(session->receiveHandle_be), alloc);
    Dict_putInt(r, String_CONST("sendHandle"),
                Endian_bigEndianToHost32(session->sendHandle_be), alloc);

    Dict_putInt(r, String_CONST("timeOfLastIn"), session->timeOfLastIn, alloc);
    Dict_putInt(r, String_CONST("timeOfLastOut"), session->timeOfLastOut, alloc);

    Admin_sendMessage(r, txid, context->admin);
    return;
}
Ejemplo n.º 18
0
int main(int ____c, char *____v[])
{
	setup_error_handlers();
	int x;
	bool y;
	x = 5;
	y = foo(x);
	if (y) {
	    print_string(String_new("happy"));
	}
	else {
	    print_string(String_new("sad"));
	}
	return 0;
}
Ejemplo n.º 19
0
static void adminPingOnResponse(struct SwitchPinger_Response* resp, void* vping)
{
    struct Allocator* pingAlloc = resp->ping->pingAlloc;
    struct Ping* ping = vping;

    Dict* rd = Dict_new(pingAlloc);

    if (resp->res == SwitchPinger_Result_LABEL_MISMATCH) {
        uint8_t path[20] = {0};
        AddrTools_printPath(path, resp->label);
        String* pathStr = String_new(path, pingAlloc);
        Dict_putString(rd, String_CONST("rpath"), pathStr, pingAlloc);
    }

    Dict_putInt(rd, String_CONST("version"), resp->version, pingAlloc);
    Dict_putInt(rd, String_CONST("ms"), resp->milliseconds, pingAlloc);
    Dict_putString(rd, String_CONST("result"), SwitchPinger_resultString(resp->res), pingAlloc);
    Dict_putString(rd, String_CONST("path"), ping->path, pingAlloc);
    if (resp->data) {
        Dict_putString(rd, String_CONST("data"), resp->data, pingAlloc);
    }

    if (!Bits_isZero(resp->key, 32)) {
        Dict_putString(rd, String_CONST("key"), Key_stringify(resp->key, pingAlloc), pingAlloc);
    }

    Admin_sendMessage(rd, ping->txid, ping->context->admin);
}
Ejemplo n.º 20
0
static void sendFirstMessageToCore(void* vcontext)
{
    struct NodeContext* ctx = Identity_check((struct NodeContext*) vcontext);
    struct Allocator* alloc = Allocator_child(ctx->alloc);
    struct Message* msg = Message_new(0, 512, alloc);

    Dict* d = Dict_new(alloc);
    Dict_putString(d, String_CONST("privateKey"), String_new(ctx->privateKeyHex, alloc), alloc);

    Dict* logging = Dict_new(alloc);
    {
        Dict_putString(logging, String_CONST("logTo"), String_CONST("stdout"), alloc);
    }
    Dict_putDict(d, String_CONST("logging"), logging, alloc);

    Dict* admin = Dict_new(alloc);
    {
        Dict_putString(admin, String_CONST("bind"), ctx->bind, alloc);
        Dict_putString(admin, String_CONST("pass"), ctx->pass, alloc);
    }
    Dict_putDict(d, String_CONST("admin"), admin, alloc);

    BencMessageWriter_write(d, msg, NULL);

    Iface_send(&ctx->angelIface, msg);
    Allocator_free(alloc);
}
Ejemplo n.º 21
0
static void tunInterface(Dict* ifaceConf, struct Allocator* tempAlloc, struct Context* ctx)
{
    String* ifaceType = Dict_getString(ifaceConf, String_CONST("type"));
    if (!String_equals(ifaceType, String_CONST("TUNInterface"))) {
        return;
    }

    // Setup the interface.
    String* tunfd = Dict_getString(ifaceConf, String_CONST("tunfd"));
    String* device = Dict_getString(ifaceConf, String_CONST("tunDevice"));

    Dict* args = Dict_new(tempAlloc);
    if (tunfd && device) {
        Dict_putString(args, String_CONST("path"), device, tempAlloc);
        Dict_putString(args, String_CONST("type"),
                       String_new(tunfd->bytes, tempAlloc), tempAlloc);
        Dict* res = NULL;
        rpcCall0(String_CONST("FileNo_import"), args, ctx, tempAlloc, &res, false);
        if (res) {
            Dict* args = Dict_new(tempAlloc);
            int64_t* tunfd = Dict_getInt(res, String_CONST("tunfd"));
            int64_t* type = Dict_getInt(res, String_CONST("type"));
            Dict_putInt(args, String_CONST("tunfd"), *tunfd, tempAlloc);
            Dict_putInt(args, String_CONST("type"), *type, tempAlloc);
            rpcCall0(String_CONST("Core_initTunfd"), args, ctx, tempAlloc, NULL, false);
        }
    } else {
        if (device) {
            Dict_putString(args, String_CONST("desiredTunName"), device, tempAlloc);
        }
        rpcCall0(String_CONST("Core_initTunnel"), args, ctx, tempAlloc, NULL, false);
    }
}
Ejemplo n.º 22
0
void le_msg(String * s,String * t)
{
	gc_begin_func();
	print_string(String_add(String_add(s,String_new(" is less than or equal to ")),t));

	gc_end_func();
}
Ejemplo n.º 23
0
void gt_msg(String * s,String * t)
{
	gc_begin_func();
	print_string(String_add(String_add(s,String_new(" is greater than ")),t));

	gc_end_func();
}
Ejemplo n.º 24
0
String *String_from_float(double value) {
	char *s = calloc(20, sizeof(char));
	char buf[50];
	sprintf(buf,"%1.2f",value);
	strcat(s, buf);
	return String_new(s);
}
Ejemplo n.º 25
0
struct CryptoAuth_Session* CryptoAuth_newSession(struct CryptoAuth* ca,
                                                 struct Allocator* alloc,
                                                 const uint8_t herPublicKey[32],
                                                 const uint8_t herIp6[16],
                                                 const bool requireAuth,
                                                 char* displayName)
{
    struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
    struct CryptoAuth_Session_pvt* session =
        Allocator_calloc(alloc, sizeof(struct CryptoAuth_Session_pvt), 1);
    Identity_set(session);
    session->context = context;
    session->requireAuth = requireAuth;
    session->pub.displayName = String_new(displayName, alloc);
    session->timeOfLastPacket = Time_currentTimeSeconds(context->eventBase);
    session->alloc = alloc;

    if (herPublicKey != NULL) {
        Bits_memcpyConst(session->pub.herPublicKey, herPublicKey, 32);
        uint8_t calculatedIp6[16];
        AddressCalc_addressForPublicKey(calculatedIp6, herPublicKey);
        Bits_memcpyConst(session->pub.herIp6, calculatedIp6, 16);
        if (herIp6 != NULL) {
            Assert_true(!Bits_memcmp(calculatedIp6, herIp6, 16));
        }
    } else if (herIp6) {
        Bits_memcpyConst(session->pub.herIp6, herIp6, 16);
    }

    return &session->pub;
}
Ejemplo n.º 26
0
static void checkRunningInstance(struct Allocator* allocator,
                                 struct EventBase* base,
                                 String* addr,
                                 String* password,
                                 struct Log* logger,
                                 struct Except* eh)
{
    struct Allocator* alloc = Allocator_child(allocator);
    struct Sockaddr_storage pingAddrStorage;
    if (Sockaddr_parse(addr->bytes, &pingAddrStorage)) {
        Except_raise(eh, -1, "Unable to parse [%s] as an ip address port, eg: 127.0.0.1:11234",
                     addr->bytes);
    }
    struct AdminClient* adminClient =
        AdminClient_new(&pingAddrStorage.addr, password, base, logger, alloc);

    // 100 milliseconds is plenty to wait for a process to respond on the same machine.
    adminClient->millisecondsToWait = 100;

    Dict* pingArgs = Dict_new(alloc);

    struct AdminClient_Result* pingResult =
        AdminClient_rpcCall(String_new("ping", alloc), pingArgs, adminClient, alloc);

    if (pingResult->err == AdminClient_Error_NONE) {
        Except_raise(eh, -1, "Startup failed: cjdroute is already running.");
    }
    Allocator_free(alloc);
}
Ejemplo n.º 27
0
int32_t CryptoAuth_addUser(String* password,
                           uint8_t authType,
                           String* user,
                           struct CryptoAuth* ca)
{
    struct CryptoAuth_pvt* context = Identity_check((struct CryptoAuth_pvt*) ca);
    if (authType != 1) {
        return CryptoAuth_addUser_INVALID_AUTHTYPE;
    }
    if (context->passwordCount == context->passwordCapacity) {
        // TODO(cjd): realloc password space and increase buffer.
        return CryptoAuth_addUser_OUT_OF_SPACE;
    }
    struct CryptoAuth_Auth a;
    hashPassword_sha256(&a, password);
    for (uint32_t i = 0; i < context->passwordCount; i++) {
        if (!Bits_memcmp(a.secret, context->passwords[i].secret, 32) ||
            String_equals(user, context->passwords[i].user)) {
            return CryptoAuth_addUser_DUPLICATE;
        }
    }
    a.user = String_new(user->bytes, context->allocator);
    Bits_memcpyConst(&context->passwords[context->passwordCount],
                     &a,
                     sizeof(struct CryptoAuth_Auth));
    context->passwordCount++;
    return 0;
}
Ejemplo n.º 28
0
char *test_print()
{
    object = Object_new();
    Object_print(object);
    Object_destroy(object);

    object = True_new();
    Object_print(object);
    Object_destroy_immortal(object);

    object = False_new();
    Object_print(object);
    Object_destroy_immortal(object);

    object = Nil_new();
    Object_print(object);
    Object_destroy_immortal(object);

    object = Integer_new(123);
    Object_print(object);
    Object_destroy(object);

    bstring hello = bfromcstr("hello");
    object = String_new(hello);
    Object_print(object);
    Object_destroy(object);

    return NULL;
}
Ejemplo n.º 29
0
void
State_bootstrap(STATE)
{
  DArray *filenames = kernel_files(state);
  int count = DArray_count(filenames);

  // Expose toplevel constants
  expose_VM(state, state->lobby);

  int reenable_debugger = 0;

  // Disable debugger while loading kernel files
  if(Debug) {
    reenable_debugger = 1;
    Debug = 0;
  }

  // Load all files.
  for(int i=0; i < count; i++) {
    bstring filename = (bstring)DArray_at(filenames, i);
    bstring path = bfromcstr("kernel/");
    bconcat(path, filename);
    Primitive_require(state, String_new(state, bdata(path)), NULL, NULL);

    bdestroy(path);
    bdestroy(filename);
  }

  DArray_destroy(filenames);

  // Reenable debugger if needed
  if(reenable_debugger) Debug = 1;
}
Ejemplo n.º 30
0
MenuEntry* MenuEntry_new(String* text, WindowMouseclickHandler click_action) {

    MenuEntry* menu_entry;

    if(!(menu_entry = (MenuEntry*)malloc(sizeof(MenuEntry))))
        return menu_entry;

    if(!(Window_init((Window*)menu_entry, 0, 0, 100, 14, WIN_NORAISE | WIN_NODECORATION, (Context*)0))) {

        Object_delete((Object*)menu_entry);
        return (MenuEntry*)0;
    }

    Object_init((Object*)menu_entry, MenuEntry_delete_function);

    if(!(menu_entry->text = String_new(text->buf))) {

        Object_delete((Object*)menu_entry);
        return (MenuEntry*)0;
    }

    menu_entry->mouse_over = 0;
    menu_entry->window.paint_function = MenuEntry_paint_handler;
    menu_entry->window.mouseclick_function = click_action;
    menu_entry->window.mouseover_function = MenuEntry_mouseover_handler;
    menu_entry->window.mouseout_function = MenuEntry_mouseout_handler;

    return menu_entry;
}