void unabto_prng_random_seed(uint8_t* buf, size_t bytes)
{
    unsigned long x;
    FILE *f;
    f = fopen("/dev/urandom", "rb");
    if (f == NULL)
       f = fopen("/dev/random", "rb");
    if (f == NULL) {
        NABTO_LOG_FATAL(("Could not open random source tried /dev/urandom and /dev/random"));
        return;
    }

    /* disable buffering */
    if (setvbuf(f, NULL, _IONBF, 0) != 0) {
       fclose(f);
       NABTO_LOG_FATAL(("Could not disable buffering"));
       return;
    }   
 
    x = (unsigned long)fread(buf, 1, bytes, f);
    fclose(f);

    if (x < bytes) {
        NABTO_LOG_FATAL(("Could not get enough random entropy"));
        return;
    }
}
Exemplo n.º 2
0
void tcp_provider_initialize(void)
{
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;

    /* Use the MAKEWORD(lowbyte, highbyte) macro declared in Windef.h */
    wVersionRequested = MAKEWORD(2, 2);

    err = WSAStartup(wVersionRequested, &wsaData);
    if (err != 0)
    {
        /* Tell the user that we could not find a usable */
        /* Winsock DLL.                                  */
        
        NABTO_LOG_FATAL(("WSAStartup failed with error: %d\n", err));
    }

    /* Confirm that the WinSock DLL supports 2.2.*/
    /* Note that if the DLL supports versions greater    */
    /* than 2.2 in addition to 2.2, it will still return */
    /* 2.2 in wVersion since that is the version we      */
    /* requested.                                        */

    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
    {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        NABTO_LOG_FATAL(("Could not find a usable version of Winsock.dll\n"));
    }
}
Exemplo n.º 3
0
bool test_if_lo_exists() {
    bool foundLoopback = false;

    struct ifaddrs *addrs,*tmp;

    getifaddrs(&addrs);
    tmp = addrs;

    while (tmp)
    {
        const char* lo = "lo";
        if (tmp->ifa_addr) {
            if (strncmp(tmp->ifa_name, lo, strlen(lo)) == 0) {
                if (! (tmp->ifa_flags & (IFF_UP))) {
                    NABTO_LOG_FATAL(("Loopback interface exists but it's not up"));
                } else if (! (tmp->ifa_flags & (IFF_UP))) {
                    NABTO_LOG_FATAL(("Loopback interface exists but it's not running"));
                } else {
                    foundLoopback = true;
                }
            }
        }

        tmp = tmp->ifa_next;
    }

    freeifaddrs(addrs);

    if (!foundLoopback) {
        NABTO_LOG_FATAL(("No loopback interface found, searched for an interface named lo. This is required if the tunnel should be able to connect to services on localhost."));
    }
    return foundLoopback;
}
Exemplo n.º 4
0
void tunnel_loop_epoll() {

    struct epoll_event events[MAX_EPOLL_EVENTS];
    int timeout;
    nabto_stamp_t ne;
    nabto_stamp_t now;
    int nfds;

    if (!unabto_init()) {
        NABTO_LOG_FATAL(("Failed to initialize unabto"));
    }

    if (!init_tunnel_module()) {
        NABTO_LOG_FATAL(("Cannot initialize tunnel module"));
        return;
    }

    unabto_time_auto_update(false);
    // time is updated here and after the select since that's the only blocking point.
    unabto_time_update_stamp();

    while (true) {
        int i;
        unabto_next_event(&ne);
        now = nabtoGetStamp();
        timeout = nabtoStampDiff2ms(nabtoStampDiff(&ne, &now));
        if (timeout < 0) {
            timeout = 0;
        }
        
        nfds = epoll_wait(unabto_epoll_fd, events, MAX_EPOLL_EVENTS, timeout);
        unabto_time_update_stamp();
        
        for (i = 0; i < nfds; i++) {
            
            unabto_epoll_event_handler* handler = (unabto_epoll_event_handler*)events[i].data.ptr;

            if (handler->epollEventType == UNABTO_EPOLL_TYPE_UDP) {
                unabto_network_epoll_read(&events[i]);
            }
#if NABTO_ENABLE_TCP_FALLBACK
            unabto_tcp_fallback_epoll_event(&events[i]);
#endif
            unabto_tunnel_epoll_event(&events[i]);
        }

        unabto_time_event();
    }
    deinit_tunnel_module();
    unabto_close();
}
void unabto_tcp_fallback_handle_write(nabto_connect* con) {
	ssize_t status;
    int dataToSend;
    unabto_tcp_fallback_connection* fbConn = &fbConns[nabto_connection_index(con)];
    UNABTO_ASSERT(fbConn->sendBufferSent <= fbConn->sendBufferLength); 
    dataToSend = fbConn->sendBufferLength - fbConn->sendBufferSent;
    
    status = send(fbConn->socket, fbConn->sendBuffer + fbConn->sendBufferSent, dataToSend, MSG_NOSIGNAL);
    if (status > 0) {
        fbConn->sendBufferSent += status;
    } else if (status < 0) {
        int err = errno;
        if ((err == EAGAIN) || err == EWOULDBLOCK) {
        } else {
            NABTO_LOG_ERROR((PRI_tcp_fb "Send of tcp packet failed", TCP_FB_ARGS(con)));
            close_tcp_socket(con);
            return; 
        }
    }

    if (fbConn->sendBufferSent > fbConn->sendBufferLength) {
        NABTO_LOG_FATAL(("fbConn->sendBufferSent(%" PRIsize ") > fbConn->sendBufferLength(%" PRIsize "), that should not be possible", fbConn->sendBufferSent, fbConn->sendBufferLength));
    }
    
    if (fbConn->sendBufferSent == fbConn->sendBufferLength) {
        fbConn->sendBufferLength = 0;
    }
}
Exemplo n.º 6
0
/* Release the event handle returned by framework_event_query.
 * In the ASYNC model we must remove the event handle from the FIFO request
 * queue. */
void framework_release_handle(naf_handle handle)
{
    queue_entry* entry;

    if (!handle) {
        return;
    }
    if (queue_empty()) {
        /* Why do the application try to release a handle on an empty queue? */
        NABTO_LOG_FATAL(("SW error: Calling framework_release_handle on an empty queue"));
        return;
    }

    /* Find the entry containing the handle */
    entry = queue_find_entry(handle);
    /* The given handle must belong to the queue */
    UNABTO_ASSERT(entry);

    entry->state = APPREQ_FREE;
    LOG_APPREQ_WHERE("framework_release_handle", entry);

    /* Remove top entry from FIFO queue - and remove all consecutive
     * entries that have expired/finished in the mean time. */
    while (!queue_empty()) {
        if (queue_top()->state != APPREQ_FREE)
            break;
        queue_pop();
    }

    LOG_APPREQ_QUEUE();
}
Exemplo n.º 7
0
Arquivo: main.c Projeto: nabto/unabto
int main(int argc, char** argv)
{
    nabto_main_setup* nms = unabto_init_context();

    platform_checks();
        
#if NABTO_ENABLE_EPOLL
    unabto_epoll_init();
#endif

    if (!tunnel_parse_args(argc, argv, nms)) {
        NABTO_LOG_FATAL(("failed to parse commandline args"));
    }

#if HANDLE_SIGNALS
#ifdef WIN32
    signal_event = CreateEvent(NULL, FALSE, FALSE, NULL);
#endif
    signal(SIGTERM, handle_signal);
    signal(SIGINT, handle_signal);
#endif

#if NABTO_ENABLE_EPOLL
    if (useSelectBased) {
        tunnel_loop_select();
    } else {
        tunnel_loop_epoll();
    }
#else
    tunnel_loop_select();
#endif
    return 0;
}
int main(int argc, char** argv) {
    char dnsid[250];
    int i, count;
    pthread_t* nt;
    int val;
    struct timespec tv;

    if (!parse_args(argc, argv)) {
        help();
        exit(1);
    }
    
    sprintf(dnsid, "foo.%s", base_name);

    count = range_end - range_start;
    if (count <= 0) {
        help();
        printf("end_range < begin_range\n");
        exit(1);
    }
    nt = (pthread_t*) calloc(count, sizeof(pthread_t));
    if (nt == NULL) {
        NABTO_LOG_FATAL(("failed to allocate memory for array of threads"));
    }

    resolve_dns(dnsid);

    for (i = 0; i < count; i++) {
        char* name = (char*) malloc(20 + strlen(base_name));
        if (name == NULL) {
            NABTO_LOG_FATAL(("failed to allocate memory for thread %d (%d.%s)", i, range_start + i, base_name));
        }

        sprintf(name, "%d.%s", range_start + i, base_name);
        val = pthread_create(nt + i, NULL, main_routine, name);
        if (val != 0) {          
            NABTO_LOG_FATAL(("failed to create thread %d (%d.%s), val: %d, err: %d", i, range_start + i, base_name, val, errno));
        }
    }

    while(1) {
        getchar();
    }

}
application_event_result application_poll(application_request* request, buffer_read_t* r_b, buffer_write_t* w_b)
{
    application_event_result res = AER_REQ_SYSTEM_ERROR;
    if (saved_app_req == 0) {
        NABTO_LOG_FATAL(("No queued request"));
    } else if (request != saved_app_req) {
        NABTO_LOG_FATAL(("queued request and parameters doesn't match"));
    } else {
        UNABTO_ASSERT(r_b == 0);
        r_b = &saved_params.r_b;
        UNABTO_ASSERT(r_b != 0);
        res = weather_station_application(saved_app_req, r_b, w_b);
        PGR_LOG_APPREQ_RES(application_poll, (int)res);
        // hand the saved application request to the caller with the resulting response
        saved_app_req = 0;
    }
    return res;
}
Exemplo n.º 10
0
static uart_channel* look_up_uart_channel(uint8_t channel)
{
  if (channel >= UART_NUMBER_OF_CHANNELS)
  {
    NABTO_LOG_FATAL(("Invalid UART channel specified!"));
    return NULL;
  }

  return &channels[channel];
}
Exemplo n.º 11
0
bool unabto_tcp_fallback_module_init()
{
#if NABTO_ENABLE_DYNAMIC_MEMORY
    fbConns = (unabto_tcp_fallback_connection*)malloc(sizeof(unabto_tcp_fallback_connection) * NABTO_MEMORY_CONNECTIONS_SIZE);
    if (fbConns == 0) {
        NABTO_LOG_FATAL(("Could not allocate memory for fallback connections"));
        return false;
    }
#endif
    return true;
}
Exemplo n.º 12
0
ssize_t nabto_read(nabto_socket_t socket, uint8_t* buffer, size_t length, uint32_t* address, uint16_t* port)
{
  OS_ERR osErr;
  uint8_t* receiveBuffer;
  uint16_t receiveBufferLength;
  RAK_SOCKET_ADDR socketInfo;
 
  if(socket > NUMBER_OF_SOCKETS)
  {
    NABTO_LOG_FATAL(("Read on invalid socket!"));
    return 0;
  }
  
  if(sockets[socket].isOpen == false)
  {
    NABTO_LOG_ERROR(("Read on closed socket!"));
    return 0;
  }
  
  while(poll_task_event_queue());
  
  OSSemPend(&sockets[socket].receiverSemaphore, 0, OS_OPT_PEND_NON_BLOCKING, NULL, &osErr);
  if(osErr != OS_ERR_NONE)
  {
    return 0;
  }
  
  NABTO_LOG_TRACE(("nabto_read=%u receiving...", socket));
  
  if (RAK_RecvData(socket, &receiveBuffer, &receiveBufferLength) != RAK_OK)
  {
    return 0;
  }
  
  if(receiveBufferLength > length)
  {
    NABTO_LOG_TRACE(("nabto_read=%u oversize frame", socket));
    RAK_RecvFree(buffer);
    return 0;
  }
  
  memcpy(buffer, receiveBuffer, receiveBufferLength);
  
  RAK_RecvFree(receiveBuffer);

  RAK_GetSocketInfo(socket, &socketInfo);

  *address = socketInfo.dest_addr;
  *port = socketInfo.dest_port;
  
  NABTO_LOG_TRACE(("Received UDP packet from " PRI_IP ":%u length=%u", PRI_IP_FORMAT(*address), *port, receiveBufferLength));
  
  return receiveBufferLength;
}
Exemplo n.º 13
0
/**
 * Entry point.
 * @param argc  number of parameters
 * @param argv  the parameters
 * - 1 ip-address
 * - 2 serverid | - 
 * - 3 log
 * @return      the result
 */
int main(int argc, char* argv[])
{
    nabto_main_setup* nms;
    nabto_endpoint localEp;

    // flush stdout
    setvbuf(stdout, NULL, _IONBF, 0);

    nms = unabto_init_context();

    /**
     * Overwrite default values with command line args
     */
    if (!check_args(argc, argv, nms)) {
        return 1;
    }

    if (!unabto_init()) {
        NABTO_LOG_FATAL(("Failed at nabto_main_init"));
    }

	localEp.addr=nms->ipAddress;
	localEp.port=nms->localPort;
	
	if (nms->ipAddress != INADDR_ANY) NABTO_LOG_INFO(("Own IP address: " PRIep, MAKE_EP_PRINTABLE(localEp)));
    else NABTO_LOG_INFO(("Own IP address, local IP is set to INADDR_ANY: " PRIep, MAKE_EP_PRINTABLE(localEp)));

    while (true) {
        /*
         * Here the main application should do it's work
         * and then whenever time is left for Nabto (but at least regularly)
         * the nabto_main_tick() should be called.
         *
         * nabto_main_tick()
         * - polls the socket for incoming messages
         * - administers timers to do its own timer based work
         */
        unabto_tick();
#if NABTO_ENABLE_STREAM
        nabto_stream_test_tick();
#endif
#if (_POSIX_C_SOURCE >= 199309L)
        struct timespec sleepTime;
        sleepTime.tv_sec = 0;
        sleepTime.tv_nsec = 10*1000000;
        nanosleep(&sleepTime, NULL);
#endif
    }

    unabto_close();
	return 0;
}
Exemplo n.º 14
0
/**
 *  main using gopt to check command line arguments
 *  -h for help
 */
int main(int argc, char* argv[])
{

    // Set nabto to default values
    nabto_main_setup* nms = unabto_init_context();


    // Initialise application
    if (!application_init()){
        NABTO_LOG_FATAL(("Unable to initialise serial connection"));
    }

    // Optionally set alternative url to html device driver
    //nmc.nabtoMainSetup.url = "https://dl.dropbox.com/u/15998645/html_dd_demo.zip";

    // Overwrite default values with command line args
    if (!check_args(argc, argv, nms)) {
        return 1;
    }
    NABTO_LOG_INFO(("Identity: '%s'", nms->id));
    NABTO_LOG_INFO(("Program Release %" PRIu32 ".%" PRIu32, RELEASE_MAJOR, RELEASE_MINOR));
    NABTO_LOG_INFO(("Buffer size: %d" , nms->bufsize));

    // Initialize nabto
    if (!unabto_init()) {
        NABTO_LOG_FATAL(("Failed at nabto_main_init"));
    }

    // The main loop gives nabto a tick from time to time.
    // Everything else is taken care of behind the scenes.
    while (true) {
        unabto_tick();
        nabto_yield(10);
    }

    unabto_close();

    return 0;
}
Exemplo n.º 15
0
void nabto_random(uint8_t* buf, size_t len) {
    static bool isInitialized = false;
    size_t bytes;
    if (!isInitialized) {
        int wprng;
        int status;
        register_prng(&fortuna_desc);
        wprng = find_prng("fortuna");

        status = rng_make_prng(128, wprng, &unabto_prng_state, NULL);
        if (status != CRYPT_OK) {
            NABTO_LOG_FATAL(("Could not initialize random function"));
            return;
        }
        isInitialized = true;
    }
    bytes = fortuna_desc.read(buf, len, &unabto_prng_state);

    if (bytes != len) {
        NABTO_LOG_FATAL(("Random function did not give required bytes"));
    }
}
Exemplo n.º 16
0
int main(int argc, char** argv)
{
#if USE_TEST_WEBSERVER
#ifdef WIN32
    HANDLE testWebserverThread;
#else
    pthread_t testWebserverThread;
#endif
#endif

    nabto_main_setup* nms = unabto_init_context();

    platform_checks();
    
#if NABTO_ENABLE_EPOLL
    unabto_epoll_init();
#endif

    if (!tunnel_parse_args(argc, argv, nms)) {
        NABTO_LOG_FATAL(("failed to parse commandline args"));
    }

#if USE_TEST_WEBSERVER
    if (testWebserver) {
#ifdef WIN32
        testWebserverThread = CreateThread(NULL, 0, test_webserver, (void*)testWebserverPortStr, NULL, NULL);
#else
        pthread_create(&testWebserverThread, NULL, test_webserver, (void*)testWebserverPortStr);
#endif
    }
#endif

#if HANDLE_SIGNALS
#ifdef WIN32
    signal_event = CreateEvent(NULL, FALSE, FALSE, NULL);
#endif
    signal(SIGTERM, handle_signal);
    signal(SIGINT, handle_signal);
#endif

#if NABTO_ENABLE_EPOLL
    if (useSelectBased) {
        tunnel_loop_select();
    } else {
        tunnel_loop_epoll();
    }
#else
    tunnel_loop_select();
#endif
    return 0;
}
Exemplo n.º 17
0
bool configuration_store_write(uint16_t offset, const void* data, uint16_t length)
{
  if((offset + length) > sizeof(store))
  {
    NABTO_LOG_FATAL(("Out of bounds write in configuration store."));
    return false;
  }

  memcpy(&store[offset], data, length);
  
  NABTO_LOG_TRACE(("Wrote %u bytes starting at offset %x", (int) length, (int)offset));

  return true;
}
Exemplo n.º 18
0
bool configuration_store_read(uint16_t offset, void* data, uint16_t length)
{
  if((offset + length) > sizeof(store))
  {
    NABTO_LOG_FATAL(("Out of bounds read in configuration store."));
    return false;
  }

  memcpy(data, &store[offset], length);
  
  NABTO_LOG_TRACE(("Read %u bytes starting at offset %x", (int) length, (int)offset));

  return true;
}
Exemplo n.º 19
0
bool configuration_store_set(uint16_t offset, uint8_t value, uint16_t length)
{
  if((offset + length) > sizeof(store))
  {
    NABTO_LOG_FATAL(("Out of bounds write in configuration store."));
    return false;
  }

  memset(&store[offset], value, length);

  NABTO_LOG_TRACE(("Set %u bytes to %u starting at offset %x", (int) length, (int)value, (int)offset));

  return true;
}
// Retrieve the response from a queued request
application_event_result application_poll(application_request* request, buffer_read_t* r_b, buffer_write_t* w_b)
{
    application_event_result res;

    if (saved_app_req == 0) {
        NABTO_LOG_FATAL(("No queued request"));
        return AER_REQ_SYSTEM_ERROR;
    }

    res = demo_application(request, r_b, w_b);
    if (res == AER_REQ_RESPONSE_READY) {
        NABTO_LOG_INFO(("Application poll: Response delivered"));
    }
    saved_app_req = 0;
    return res;
}
/**
 * create a thread which runs the unabto instance.
 */
unabto_api_status_t unabto_api_platform_start() {
    if (running) {
        return UNABTO_API_FAIL;
    }

    if (!unabto_init()) {
        return UNABTO_API_FAIL;
    }

    running = true;
    if (unabto_thread_create(&tick_thread, tick_thread_func, NULL) != 0) {
        NABTO_LOG_FATAL(("Failed to create tick_thread"));
    }

    return UNABTO_API_OK;
}
Exemplo n.º 22
0
bool unabto_tcp_fallback_handle_write(nabto_connect* con) {
    ssize_t status;
    int dataToSend;
    bool canMaybeSendMoreData = false;
    unabto_tcp_fallback_connection* fbConn = &fbConns[nabto_connection_index(con)];
    UNABTO_ASSERT(fbConn->sendBufferSent <= fbConn->sendBufferLength); 
    dataToSend = fbConn->sendBufferLength - fbConn->sendBufferSent;

    if (dataToSend == 0) {
        return false;
    }
    
    NABTO_LOG_TRACE(("data to send %i, sendBufferLength %i, sendBufferSent %i", dataToSend, fbConn->sendBufferLength, fbConn->sendBufferSent));
    
    status = send(fbConn->socket, fbConn->sendBuffer + fbConn->sendBufferSent, dataToSend, MSG_NOSIGNAL);
    NABTO_LOG_TRACE(("tcp send status: %i", status));
    if (status > 0) {
        fbConn->sendBufferSent += status;
        canMaybeSendMoreData = true;
    } else if (status < 0) {
        int err = errno;
        if ((err == EAGAIN) || err == EWOULDBLOCK) {
            canMaybeSendMoreData = false;
        } else {
            NABTO_LOG_ERROR((PRI_tcp_fb "Send of tcp packet failed", TCP_FB_ARGS(con)));
            close_tcp_socket(con);
            canMaybeSendMoreData = false;
            return canMaybeSendMoreData; 
        }
    }

    if (fbConn->sendBufferSent > fbConn->sendBufferLength) {
        NABTO_LOG_FATAL(("fbConn->sendBufferSent(%" PRIsize ") > fbConn->sendBufferLength(%" PRIsize "), that should not be possible", fbConn->sendBufferSent, fbConn->sendBufferLength));
    }
    
    if (fbConn->sendBufferSent == fbConn->sendBufferLength) {
        fbConn->sendBufferLength = 0;
        fbConn->sendBufferSent = 0;
        canMaybeSendMoreData = false;
    }

    NABTO_LOG_TRACE(("state after send, sendBufferLength %i, sendBufferSent %i", fbConn->sendBufferLength, fbConn->sendBufferSent));
    
    return canMaybeSendMoreData;
}
Exemplo n.º 23
0
// move as much data as possible from the UART OS buffer to the UART driver receive buffer.
static bool low_level_read_from_uart(uart_channel* uartChannel)
{
  uint8_t buffer[1024];
  DWORD count;
  uint16_t length;

  count = queue_free(&uartChannel->receiveQueue);

  if (count == 0) // room for more bytes in the driver receive queue?
  {
    return false; // no
  }

  if (count > sizeof(buffer)) // limit count
  {
    count = sizeof(buffer);
  }

  // try to read as many bytes as there is room for in the driver receive queue
  if (ReadFile(uartChannel->hPort, buffer, count, &count, 0) == false)
  {
    return false; // read failed for some reason
  }

  // no bytes received?
  if (count == 0)
  {
    return false; // no bytes received
  }

  // no bytes received?
  if (count > 0xffff)
  {
    NABTO_LOG_FATAL(("Received an exorbitant amount of data from the UART!"));
    return false; // something is totally wrong
  }

  length = (uint16_t)count;

  NABTO_LOG_TRACE(("Queued %u bytes in UART driver receive buffer.", length));

  queue_enqueue_array(&uartChannel->receiveQueue, buffer, length);

  return true;
}
Exemplo n.º 24
0
Arquivo: main.c Projeto: nabto/unabto
/**
 *  main using gopt to check command line arguments
 *  -h for help
 */
int main(int argc, char* argv[])
{
    // Set nabto to default values

    nabto_main_setup* nms = unabto_init_context();

    // Overwrite default values with command line args
    if (!check_args(argc, argv, nms)) {
        return 1;
    }
    NABTO_LOG_INFO(("Identity: '%s'", nms->id));
    NABTO_LOG_INFO(("Program Release %i.%i", RELEASE_MAJOR, RELEASE_MINOR));
    NABTO_LOG_INFO(("Buffer size: %i", nms->bufsize));

    // Initialize nabto
    if (!unabto_init()) {
        NABTO_LOG_FATAL(("Failed at nabto_main_init"));
    }

    nabto_stamp_t attachExpireStamp;
    // 20 seconds
    nabtoSetFutureStamp(&attachExpireStamp, 1000*20);
        
    // The main loop gives nabto a tick from time to time.
    // Everything else is taken care of behind the scenes.
    while (true) {
        unabto_tick();
        nabto_yield(10);
        if (nabtoIsStampPassed(&attachExpireStamp)) {
            NABTO_LOG_ERROR(("Attach took too long."));
            exit(4);
        }
        if (unabto_is_connected_to_gsp()) {
            NABTO_LOG_INFO(("Successfully attached to the gsp, now exiting."));
            exit(0);
        }
    }

    NABTO_LOG_ERROR(("we should not end here"));
    exit(5);
    
    unabto_close();
    return 0;
}
Exemplo n.º 25
0
/* Update the state of the queue entry after calling application. */
application_event_result framework_update_state(queue_entry* entry, application_event_result ret)
{
    if (entry->state != APPREQ_WAITING) {
        LOG_APPREQ_QUEUE();
        NABTO_LOG_FATAL(("SW error: handle should be in 'WAIT' state"));
    }
    switch (ret) {
        case AER_REQ_RESPONSE_READY:
              entry->state = APPREQ_FREE;
              break;
        case AER_REQ_ACCEPTED:
              entry->state = APPREQ_IN_APP;
              break;
        default:
              //error
              entry->state = APPREQ_FREE;
              break;
    }
    return ret;
}
Exemplo n.º 26
0
bool nabto_init_socket(uint32_t localAddr, uint16_t* localPort, nabto_socket_t* socket)
{
  uint8_t i;
  OS_ERR osErr;
  
  NABTO_NOT_USED(localAddr);
  
  for(i = 0; i < lengthof(sockets); i++)
  {
    if(sockets[i].isOpen == false)
    {
      uint16_t port = *localPort;
      if(port == 0)
      {
        port = 30000 + i;
      }
      
      if(RAK_UDPServer(mainTcb, port, i) == RAK_OK)
      {
        sockets[i].isOpen = true;
        
        OSSemCreate(&sockets[i].receiverSemaphore, NULL, 0, &osErr);
        if(osErr != OS_ERR_NONE)
        {
          NABTO_LOG_FATAL(("Unable to create receiver semaphore %u: %i", i, osErr));
        }

        *localPort = port;
        *socket = (nabto_socket_t)i;
        
        NABTO_LOG_TRACE(("nabto_init_socket %u: port=%u", *socket, *localPort));
        
        return true;
      }
    }
  }
  
  return false;
}
Exemplo n.º 27
0
void wait_event()
{
    int timeout;
    nabto_stamp_t ne;
    nabto_stamp_t now;
    int nfds;
    int max_read_fd = 0;
    int max_write_fd = 0;
    fd_set read_fds;
    fd_set write_fds;
    struct timeval timeout_val;
    
    unabto_next_event(&ne);
    now = nabtoGetStamp();
    timeout = nabtoStampDiff2ms(nabtoStampDiff(&ne, &now));
    if (timeout < 0) timeout = 0;

    FD_ZERO(&read_fds);
    FD_ZERO(&write_fds);

    
    unabto_network_select_add_to_read_fd_set(&read_fds, &max_read_fd);
    
#if NABTO_ENABLE_TCP_FALLBACK
    unabto_tcp_fallback_select_add_to_read_fd_set(&read_fds, &max_read_fd);
    unabto_tcp_fallback_select_add_to_write_fd_set(&write_fds, &max_write_fd);
#endif

    timeout_val.tv_sec = (timeout/1000);
    timeout_val.tv_usec = ((timeout)%1000)*1000;

    nfds = select(MAX(max_read_fd+1, max_write_fd+1), &read_fds, &write_fds, NULL, &timeout_val);

    NABTO_LOG_TRACE(("foobar %i", nfds));
    if (nfds < 0) NABTO_LOG_FATAL(("Error in epoll_wait: %d", errno));
    unabto_network_select_read_sockets(&read_fds);
    
    unabto_time_event();
}
Exemplo n.º 28
0
void nabto_close_socket(nabto_socket_t* socket)
{
  NABTO_LOG_FATAL(("Socket shutdown not supported!"));
  //printf("RAK_ShutDown(%u)=%u", *socket, RAK_ShutDown(*socket));
  //sockets[*socket].inUse = false;
}
Exemplo n.º 29
0
Arquivo: main.c Projeto: nabto/unabto
static bool test_parse_args(const char * progname, int argc, char* argv[], nabto_main_setup* nms)
{
    const char *x1[] = { "help", 0 };
    const char *x2[] = { "version", 0 };
    const char *x3[] = { "config", 0 };
    const char *x4[] = { "size", 0 };
    const char *x5[] = { "deviceName", 0 };
    const char *x6[] = { "use_encryption", 0 };
    const char *x7[] = { "encryption_key", 0 };
    const char *x8[] = { "localport", 0 };
    const char *x11[] = { "nice_exit", 0};

    const struct { int k; int f; const char *s; const char*const* l; } opts[] = {
        { 'h', GOPT_NOARG,   "h?", x1 },
        { 'V', GOPT_NOARG,   "V",  x2 },
        { 'C', GOPT_NOARG,   "C",  x3 },
        { 'S', GOPT_NOARG,   "S",  x4 },
        { 'd', GOPT_ARG,     "d",  x5 },
        { 's', GOPT_NOARG,   "s",  x6 },
        { 'k', GOPT_ARG,     "k",  x7 },
        { 'p', GOPT_ARG,     "p",  x8 },
        { 'x', GOPT_NOARG,   "x",  x11 },
        { 0,0,0,0 }
    };

    void *options = gopt_sort(&argc, (const char**)argv, opts);

    if (gopt(options, 'h')) {
        printf("Usage: %s [options]\n", progname);
        printf("   -h  Print this help.\n");
        printf("   -V  Print release version.\n");
        printf("   -C  Print configuration (unabto_config.h).\n");
        printf("   -S  Print size (in bytes) of structures (memory usage).\n");
        exit(0);
    }
    
    if (gopt(options, 'V')) {
        printf("%s: %d.%d\n", progname, RELEASE_MAJOR, RELEASE_MINOR);
        exit(0);
    }
    
    if (gopt(options, 'C')) {
        unabto_printf_unabto_config(stdout, progname);
        exit(0);
    }
    
    if (gopt(options, 'S')) {
        unabto_printf_memory_sizes(stdout, progname);
        exit(0);
    }

    if (!gopt_arg(options, 'd', &nms->id)) {
        NABTO_LOG_FATAL(("Specify a serverId with -d"));
    }
    
    if (gopt(options, 's')) {
        const char* preSharedKey;
        if ( gopt_arg( options, 'k', &preSharedKey)) {
            if (!unabto_read_psk_from_hex(preSharedKey, nms->presharedKey, 16)) {
                NABTO_LOG_FATAL(("Cannot read presharedkey");
            }
        }
#if NABTO_ENABLE_CONNECTIONS
        nms->cryptoSuite = CRYPT_W_AES_CBC_HMAC_SHA256;
#endif
    }
Exemplo n.º 30
0
bool platform_initialize(void* tcb)
{
  OS_ERR osErr;
  
  mainTcb = tcb;
  
  SYS_Init();
  
  GPIO_SetBit(LED_LINK_PORT, LED_LINK_PIN);
  GPIO_Open(LED_LINK_PORT, GPIO_PMD_PMD8_OUTPUT, GPIO_PMD_PMD8_MASK);
  
#if NABTO_ENABLE_LOGGING
  uart_initialize(115200);
#endif
  
  // Initialize OS tick system
  OS_CPU_SysTickInit(SYS_GetHCLKFreq() / OS_CFG_TICK_RATE_HZ);
  
  OSSemCreate(&loggingSemaphore, NULL, 1, &osErr);
  if(osErr != OS_ERR_NONE)
  {
    NABTO_LOG_FATAL(("Unable to create logging semaphore"));
  }
  
  NABTO_LOG_INFO(("Initializing..."));
    
  if (RAK_DriverInit() != RAK_OK)
  {
    NABTO_LOG_FATAL(("Platform initialize failed!"));
  }

  {
    char mac[6];
    if (RAK_GetMacAddr(mac) != RAK_OK)
    {
      NABTO_LOG_FATAL(("RAK_GetMacAddr() failed!"));
    }
    NABTO_LOG_INFO(("MAC: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]));
  }
  
  {
    RAK_CONNECT param;
    param.mode = NET_MODE_STA;
    param.sec_mode = PSK_MODE_SEC;
    param.ssid = wifiSsid;
    param.psk = wifiKey;
    param.conn_handle = wifi_callback;
    if (RAK_ConnectAP(&param) != RAK_OK)
    {
      NABTO_LOG_FATAL(("Wifi connect error!"));
    }
  }

  while(linkIsUp == false); // wait for callback to set connection status

  {
    RAK_IPCONFIG dhcp;
    
    if (RAK_IPConfigDHCP(&dhcp) != RAK_OK)
    {
      NABTO_LOG_FATAL(("DHCP error!"));
    }
    
    localAddress = dhcp.addr;
    localMask = dhcp.mask;
    gateway = dhcp.gw;
    dnsServer = dhcp.dnsrv1;
    NABTO_LOG_TRACE(("DHCP: Address=" PRI_IP " mask=" PRI_IP " gateway=" PRI_IP " DNS=" PRI_IP, PRI_IP_FORMAT(localAddress), PRI_IP_FORMAT(localMask), PRI_IP_FORMAT(gateway), PRI_IP_FORMAT(dnsServer)));
  }
  
  memset(sockets, 0, sizeof(sockets));
  
  sendBuffer = RAK_SendMalloc(SEND_BUFFER_SIZE);
  
  return true;
}