コード例 #1
0
ファイル: NetworkAndBus.c プロジェクト: fonlabs/ajtcl
int AJ_Main(void)
{
#ifdef AJ_CONFIGURE_WIFI_UPON_START
# error This sample cannot be built with AJ_CONFIGURE_WIFI_UPON_START defined
#endif

    AJ_Status status = AJ_OK;
    AJ_BusAttachment bus;
    int32_t dhcp_attempts = 5;

    /*
     * One time initialization before calling any other AllJoyn APIs
     */
    AJ_Initialize();

    AJ_PrintXML(AppObjects);
    AJ_RegisterObjects(AppObjects, NULL);

    SetBusAuthPwdCallback(MyBusAuthPwdCB);

// Windows, Linux and Arduino are already connected to the network when we get to this point.
#if !(defined(ARDUINO) || defined(__linux) || defined(_WIN32) || defined(__MACH__))
#define AJ_DHCP_TIMEOUT 10000

    // Step 1: connect to a WIFI network.
    // This will also attempt to acquire an IP from DHCP
    status = AJ_ConnectWiFi(ssid, secType, AJ_WIFI_CIPHER_CCMP, passphrase);

    // if DHCP timed out, try it again for up to five attempts
    while (status == AJ_ERR_TIMEOUT && --dhcp_attempts) {
        uint32_t ip, mask, gw;
        status = AJ_AcquireIPAddress(&ip, &mask, &gw, AJ_DHCP_TIMEOUT);

        if (status != AJ_OK) {
            AJ_ErrPrintf(("AJ_Net_Up(): AJ_AcquireIPAddress Failed\n"));
        }
    }


    if (status != AJ_OK) {
        printf("Unable to connect to wifi and acquire IP\n");
        return status;
    }

#endif

    //Now we need to find a daemon, connect to it and authenticate
    // see the ConnectToBus for an explanation.
    status = ConnectToBus(&bus);

    AJ_Sleep(10000);

    AJ_Disconnect(&bus);

    return status;
}
コード例 #2
0
ファイル: aj_connect.cpp プロジェクト: CasyWang/Triton
// TODO: deprecate this function; replace it with AJ_FindBusAndConnect
AJ_Status AJ_Connect(AJ_BusAttachment* bus, const char* serviceName, uint32_t timeout)
{
    AJ_Status status;
    AJ_Service service;

#ifdef AJ_SERIAL_CONNECTION
    AJ_Time start, now;
    AJ_InitTimer(&start);
#endif

    AJ_InfoPrintf(("AJ_Connect(bus=0x%p, serviceName=\"%s\", timeout=%d.)\n", bus, serviceName, timeout));

    /*
     * Clear the bus struct
     */
    memset(bus, 0, sizeof(AJ_BusAttachment));
    /*
     * Clear stale name->GUID mappings
     */
    AJ_GUID_ClearNameMap();

#if !(defined(ARDUINO) || defined(__linux) || defined(_WIN32))
    /*
     * Get an IP address.  We don't want to break this older version
     * of AJ_Connect, so acquire an IP if we don't already have one.
     *
     * This does not work on non-embedded platforms!
     */
    {
        uint32_t ip, mask, gw;
        status = AJ_AcquireIPAddress(&ip, &mask, &gw, AJ_DHCP_TIMEOUT);

        if (status != AJ_OK) {
            AJ_ErrPrintf(("AJ_Net_Up(): AJ_AcquireIPAddress Failed\n"));
        }
    }
#endif

    /*
     * Discover a daemon or service to connect to
     */
    if (!serviceName) {
        serviceName = daemonService;
    }
#if AJ_CONNECT_LOCALHOST
    service.ipv4port = 9955;
#if HOST_IS_LITTLE_ENDIAN
    service.ipv4 = 0x0100007F; // 127.0.0.1
#endif
#if HOST_IS_BIG_ENDIAN
    service.ipv4 = 0x7f000001; // 127.0.0.1
#endif
    service.addrTypes = AJ_ADDR_IPV4;
#elif defined ARDUINO
    service.ipv4port = 9955;
    service.ipv4 = 0x6501A8C0; // 192.168.1.101
    service.addrTypes = AJ_ADDR_IPV4;
    status = AJ_Discover(serviceName, &service, timeout);
    if (status != AJ_OK) {
        AJ_InfoPrintf(("AJ_Connect(): AJ_Discover status=%s\n", AJ_StatusText(status)));
        goto ExitConnect;
    }
#elif defined AJ_SERIAL_CONNECTION
    // don't bother with discovery, we are connected to a daemon.
    // however, take this opportunity to bring up the serial connection
    // in a way that depends on the target
    status = AJ_Serial_Up();
    if (status != AJ_OK) {
        AJ_InfoPrintf(("AJ_Connect(): AJ_Serial_Up status=%s\n", AJ_StatusText(status)));
    }
#else
    status = AJ_Discover(serviceName, &service, timeout);
    if (status != AJ_OK) {
        AJ_InfoPrintf(("AJ_Connect(): AJ_Discover status=%s\n", AJ_StatusText(status)));
        goto ExitConnect;
    }
#endif
    status = AJ_Net_Connect(&bus->sock, service.ipv4port, service.addrTypes & AJ_ADDR_IPV4, &service.ipv4);
    if (status != AJ_OK) {
        AJ_InfoPrintf(("AJ_Connect(): AJ_Net_Connect status=%s\n", AJ_StatusText(status)));
        goto ExitConnect;
    }

#ifdef AJ_SERIAL_CONNECTION
    // run the state machine for long enough to (hopefully) do the SLAP handshake
    do {
        AJ_StateMachine();
        AJ_InitTimer(&now);
    } while (AJ_SerialLinkParams.linkState != AJ_LINK_ACTIVE && AJ_GetTimeDifference(&now, &start) < timeout);

    if (AJ_SerialLinkParams.linkState != AJ_LINK_ACTIVE) {
        AJ_InfoPrintf(("Failed to establish active SLAP connection in %u msec\n", timeout));
        AJ_SerialShutdown();
        return AJ_ERR_TIMEOUT;
    }
#endif

    status = AJ_Authenticate(bus);
    if (status != AJ_OK) {
        AJ_InfoPrintf(("AJ_Connect(): AJ_Authenticate status=%s\n", AJ_StatusText(status)));
        goto ExitConnect;
    }

    // subscribe to the signal NameOwnerChanged and wait for the response
    status = AJ_BusSetSignalRule(bus, "type='signal',member='NameOwnerChanged',interface='org.freedesktop.DBus'", AJ_BUS_SIGNAL_ALLOW);

ExitConnect:

    if (status != AJ_OK) {
        AJ_InfoPrintf(("AJ_Connect(): status=%s\n", AJ_StatusText(status)));
        AJ_Disconnect(bus);
    }
    return status;
}
コード例 #3
0
ファイル: scan-n-con.c プロジェクト: durake/core-ajtcl
void AJ_Main(void)
{
    uint8_t i = 0;
    AJ_Status status = AJ_ERR_FAILURE; /* the glass is half-empty */
    AJ_BusAttachment bus;

    /* these variables are used when kicking off DHCP */
    uint32_t current_ip_address = 0;
    uint32_t current_subnet_mask = 0;
    uint32_t current_default_gateway = 0;
    AJ_Time dhcpTimer;
    uint32_t timeTakenForDhcp = 0;

    AJ_Initialize();

    AJ_Printf("\nAllJoyn Release: %s\n\n", AJ_GetVersion());

    AJ_Printf("INFO: The parameter RUN_NEGATIVE_TESTS is %s\n", (RUN_NEGATIVE_TESTS ? "true" : "false"));
    AJ_Printf("INFO: The parameter DELAY_BETWEEN_SCANS is %u ms\n", DELAY_BETWEEN_SCANS);
    AJ_Printf("INFO: The parameter DELAY_BETWEEN_ASSOCIATIONS is %u ms\n", DELAY_BETWEEN_ASSOCIATIONS);
    AJ_Printf("INFO: The parameter DHCP_TIMEOUT is %u ms\n", DHCP_TIMEOUT);
    AJ_Printf("INFO: The parameter DISCOVER_TIMEOUT is %u ms\n", DISCOVER_TIMEOUT);

    /* reset the wifi to start with a clean slate */
    status = AJ_ResetWiFi();
    if (AJ_OK != status) {
        AJ_Printf("WARN: AJ_ResetWiFi returned %s (code: %u).\n", AJ_StatusText(status), status);
    }

    /*
     * Repeatedly do the following:
     * a. scan for access points in the vicinity
     * b. For each open access point in the returned results:
     *      i.   associate using AJ_ConnectWiFi
     *      ii.  acquire an ip address using AJ_AcquireIPAddress
     *      iii. perform a short-lived discovery on some random node prefix
     *           using AJ_FindBusAndConnect
     *      iv.  disassociate using AJ_DisconnectWiFi
     * c. For each secured access point in the returned results:
     *      i. Connect to it with intentionally incorrect parameters
     *         (Negative test)
     */
    while (TRUE) {
        AJ_RandBytes(&currentContext, sizeof(currentContext));

        uint8_t currentMaxAps = 0;
        AJ_RandBytes(&currentMaxAps, sizeof(currentMaxAps));

        /* Reset numValidScanEntries, before every scan attempt. */
        numValidScanEntries = 0;

        status = AJ_WiFiScan((void*) (sentinelForWifiScanContext + currentContext), wifiScanResultCallback, currentMaxAps);

        if (AJ_OK != status) {
            if (AJ_ERR_FAILURE == status && 0 != currentMaxAps) {
                scanStats.numFailed++;
            } else if (AJ_ERR_RESOURCES == status) {
                scanStats.numFailed++;
            }

            AJ_Printf("Failed to scan: %s (code: %u)\n", AJ_StatusText(status), status);

            /* No point in attempting to do wifi operations, when scan failed */
            continue;
        } else {
            /*
             * A success was returned from AJ_WiFiScan. Were any results
             * returned after all??
             */
            if (0 < numValidScanEntries) {
                scanStats.numSuccessful++;
            } else {
                AJ_Printf("WARN: AJ_WiFiScan returned %s (code: %u), but returned ZERO scan results...\n", AJ_StatusText(status), status);
                scanStats.numFailed++;

                /* When num of scan results is zero, there is nothing to do */
                continue;
            }
        }

        /* numValidScanEntries is an index into the array. Hence +1. */
        if (currentMaxAps < numValidScanEntries + 1) {
            AJ_Printf("WARN: Scan returned more results (%u) than requested (%u).\n", numValidScanEntries + 1, currentMaxAps);
        } else {
            AJ_Printf("Wifi scan successful (got %u results).\n", numValidScanEntries);
        }

        for (i = 0; i < numValidScanEntries; i++) {
            if (AJ_WIFI_SECURITY_NONE != wifiScanInfo[i].secType) {
                /* On some targets, it is not possible to check for 802.11
                 * authentication failure when security type is WEP.
                 * Hence, run negative tests only for WPA/WPA2-based APs.
                 */
                if (RUN_NEGATIVE_TESTS && AJ_WIFI_SECURITY_WEP != wifiScanInfo[i].secType) {
                    /* Run a negative test for wifi association */
                    AJ_Printf("RUN (negative test): Attempting to associate with %s using a randomly generated passphrase...", wifiScanInfo[i].ssid);
                    char random_passphrase[128 + 1];
                    AJ_RandHex(random_passphrase, sizeof(random_passphrase), (sizeof(random_passphrase) - 1) / 2);

                    /* Set a random passphrase length based on security type */
                    uint8_t randomPassphraseLen = 0;
                    /* WPA / WPA2 - assuming min len is 8 and max is 64 */
                    AJ_RandBytes(&randomPassphraseLen, sizeof(randomPassphraseLen));
                    randomPassphraseLen = 8 + randomPassphraseLen % (64 - 8 + 1);
                    random_passphrase[randomPassphraseLen] = '\0';
                    status = AJ_ConnectWiFi(wifiScanInfo[i].ssid, wifiScanInfo[i].secType, wifiScanInfo[i].cipherType, random_passphrase);
                    if (AJ_OK == status) {
                        /* negative test failed */
                        AJ_Printf("FAIL (negative test): Associated with SSID: %s BSSID: %x:%x:%x:%x:%x:%x Security: %s(%s) Passphrase: %s RSSI: %u ...\n", wifiScanInfo[i].ssid, wifiScanInfo[i].bssid[0], wifiScanInfo[i].bssid[1], wifiScanInfo[i].bssid[2], wifiScanInfo[i].bssid[3], wifiScanInfo[i].bssid[4], wifiScanInfo[i].bssid[5], secStr[wifiScanInfo[i].secType], ciphStr[wifiScanInfo[i].cipherType], random_passphrase, wifiScanInfo[i].rssi);

                        /* negative test failed - don't go any further */
                        AJ_ASSERT(0);
                    } else {
                        AJ_Printf("Done (negative test).\n");
                    }
                    status = AJ_DisconnectWiFi();
                    AJ_Sleep(DELAY_BETWEEN_ASSOCIATIONS);
                }

                continue;
            } else {
                AJ_Printf("Attempting to associate with SSID: %s BSSID: %x:%x:%x:%x:%x:%x Security: %s(%s) RSSI: %u ...\n",
                          wifiScanInfo[i].ssid,
                          wifiScanInfo[i].bssid[0], wifiScanInfo[i].bssid[1], wifiScanInfo[i].bssid[2], wifiScanInfo[i].bssid[3], wifiScanInfo[i].bssid[4], wifiScanInfo[i].bssid[5],
                          secStr[wifiScanInfo[i].secType], ciphStr[wifiScanInfo[i].cipherType],
                          wifiScanInfo[i].rssi);
                status = AJ_ConnectWiFi(wifiScanInfo[i].ssid, wifiScanInfo[i].secType, wifiScanInfo[i].cipherType, "");
                if (AJ_OK != status) {
                    associationStats.numFailed++;
                    AJ_Printf("Failed to associate : %s (code: %u)\n", AJ_StatusText(status), status);
                    /*
                     * No point in proceeding any further when WiFi association
                     * has failed
                     */
                    continue;
                } else {
                    associationStats.numSuccessful++;
                }

                AJ_Printf("Successfully associated. Attempting to get IP Address via DHCP...\n");

                AJ_InitTimer(&dhcpTimer);

                status = AJ_AcquireIPAddress(&current_ip_address, &current_subnet_mask, &current_default_gateway, DHCP_TIMEOUT);

                timeTakenForDhcp = AJ_GetElapsedTime(&dhcpTimer, FALSE);

                if (AJ_OK != status) {
                    if (AJ_ERR_TIMEOUT == status) {
                        dhcpStats.numTimedout++;
                        AJ_Printf("Timedout (%u ms) while trying to get IP Address via DHCP\n", timeTakenForDhcp);
                        /*
                         * Discovery timed out.
                         * Check whether the API returned in a timely manner.
                         * See whether the actual duration is off by +/- 500ms.
                         * Delay beyond that is unusual.
                         */
                        if (500 < abs(DHCP_TIMEOUT - timeTakenForDhcp)) {
                            AJ_Printf("WARN: AJ_AcquireIPAddress API did not return in a timely manner. Timeout parameter: %u Actual time elapsed: %u\n",
                                      DHCP_TIMEOUT,
                                      timeTakenForDhcp);
                        }
                    } else {
                        dhcpStats.numFailed++;
                        AJ_Printf("Failed to get IP Address via DHCP : %s (code: %u)\n", AJ_StatusText(status), status);
                    }
                    /*
                     * No point in proceeding any further when IP address was
                     * not acquired
                     */
                    continue;
                } else {
                    dhcpStats.numSuccessful++;
                    AJ_Printf("Successfully obtained\n");
                    AJ_Printf("\tIP Addresss    : %s\n", TestAddrStr(current_ip_address));
                    AJ_Printf("\tSubnet Mask    : %s\n", TestAddrStr(current_subnet_mask));
                    AJ_Printf("\tDefault Gateway: %s\n", TestAddrStr(current_default_gateway));
                }

                /* Generate a random name using routingNodePrefix */
                char currentRoutingNodeName[32 + 1];
                strncpy(currentRoutingNodeName, routingNodePrefix, sizeof(routingNodePrefix));
                AJ_RandHex(currentRoutingNodeName + strlen(routingNodePrefix), sizeof(currentRoutingNodeName) - sizeof(routingNodePrefix), (sizeof(currentRoutingNodeName) - sizeof(routingNodePrefix) - 1) / 2);
                currentRoutingNodeName[32] = '\0'; /* just to be safe */

                AJ_Printf("Attempting to discover routing node: %s...", currentRoutingNodeName);

                status = AJ_FindBusAndConnect(&bus, currentRoutingNodeName, DISCOVER_TIMEOUT);

                if (AJ_ERR_TIMEOUT == status) {
                    /* this is the expected result */
                    discoverStats.numTimedout++;
                    AJ_Printf("Done (discovery of routing node).\n");
                } else if (AJ_OK != status) {
                    discoverStats.numFailed++;
                    AJ_Printf("Failed to connect to routing node: %s (code: %u)\n", AJ_StatusText(status), status);
                } else if (AJ_OK == status) {
                    /*
                     * the test attempted to discovery a randomly generated
                     * routing node prefix and it worked - highly unlikely event
                     */
                    AJ_Printf("FATAL: Was able to discover and connect to routing node with prefix %s. Got unique address %s.", currentRoutingNodeName, AJ_GetUniqueName(&bus));
                    AJ_ASSERT(0);
                }

                status = AJ_DisconnectWiFi();

                if (AJ_OK != status) {
                    disassociationStats.numFailed++;
                    AJ_Printf("Failed to disassociate: %s (code: %u)\n", AJ_StatusText(status), status);
                } else {
                    disassociationStats.numSuccessful++;
                    AJ_Printf("Disassociated from access point. ");
                }
                AJ_Sleep(DELAY_BETWEEN_ASSOCIATIONS);
            }
        }

        PrintStats();

        AJ_Sleep(DELAY_BETWEEN_SCANS);
    }
}