Exemple #1
0
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;
}
static AJ_Status DoConnectWifi(AJOBS_Info* connectInfo)
{
    AJ_Status status = AJ_OK;
    AJ_WiFiSecurityType secType = AJ_WIFI_SECURITY_NONE;
    AJ_WiFiCipherType cipherType = AJ_WIFI_CIPHER_NONE;
    AJOBS_AuthType fallback = AJOBS_AUTH_TYPE_OPEN;
    AJOBS_AuthType fallbackUntil = AJOBS_AUTH_TYPE_OPEN;
    uint8_t retries = 0;
    AJ_WiFiConnectState wifiConnectState;

    AJ_InfoPrintf(("Attempting to connect to %s with passcode=%s and auth=%d\n", connectInfo->ssid, connectInfo->pc, connectInfo->authType));

    switch (connectInfo->authType) {
    case AJOBS_AUTH_TYPE_ANY:
        if (strlen(connectInfo->pc) == 0) {
            break;
        }
        fallback = AJOBS_AUTH_TYPE_WPA2_CCMP;
        fallbackUntil = AJOBS_AUTH_TYPE_OPEN;
        break;

    case AJOBS_AUTH_TYPE_WPA_AUTO:
        if (strlen(connectInfo->pc) == 0) {
            break;
        }
        fallback = AJOBS_AUTH_TYPE_WPA_CCMP;
        fallbackUntil = AJOBS_AUTH_TYPE_WPA_TKIP;
        break;

    case AJOBS_AUTH_TYPE_WPA2_AUTO:
        if (strlen(connectInfo->pc) == 0) {
            break;
        }
        fallback = AJOBS_AUTH_TYPE_WPA2_CCMP;
        fallbackUntil = AJOBS_AUTH_TYPE_WPA2_TKIP;
        break;

    default:
        fallback = connectInfo->authType;
    }

    secType = GetSecType(fallback);
    cipherType = GetCipherType(fallback);
    AJ_InfoPrintf(("Trying to connect with auth=%d (secType=%d, cipherType=%d)\n", fallback, secType, cipherType));

    while (1) {
        if (connectInfo->state == AJOBS_STATE_CONFIGURED_NOT_VALIDATED) {
            connectInfo->state = AJOBS_STATE_CONFIGURED_VALIDATING;
        }

        uint8_t raw[(AJOBS_PASSCODE_MAX_LENGTH / 2) + 1];
        char* password = connectInfo->pc;
        if (AJ_WIFI_CIPHER_WEP != cipherType) {
            size_t hexLen = strlen(connectInfo->pc);
            AJ_HexToRaw(connectInfo->pc, hexLen, raw, (AJOBS_PASSCODE_MAX_LENGTH / 2) + 1);
            password = (char*)raw;
            password[hexLen / 2] = '\0';
        }

        status = AJ_ConnectWiFi(connectInfo->ssid, secType, cipherType, password);
        AJ_InfoPrintf(("AJ_ConnectWifi returned %s\n", AJ_StatusText(status)));

        wifiConnectState = AJ_GetWifiConnectState();

        // Set last error and state
        if ((status == AJ_OK) /* (wifiConnectState == AJ_WIFI_CONNECT_OK)*/) {
            obLastError.code = AJOBS_STATE_LAST_ERROR_VALIDATED;
            obLastError.message[0] = '\0';
            obState = AJOBS_STATE_CONFIGURED_VALIDATED;
            connectInfo->authType = fallback;
        } else if ((status == AJ_ERR_CONNECT) /* (wifiConnectState == AJ_WIFI_CONNECT_FAILED)*/) {
            obLastError.code = AJOBS_STATE_LAST_ERROR_UNREACHABLE;
            strncpy(obLastError.message, "Network unreachable!", AJOBS_ERROR_MESSAGE_LEN);
            if (connectInfo->state == AJOBS_STATE_CONFIGURED_VALIDATED || connectInfo->state == AJOBS_STATE_CONFIGURED_RETRY) {
                obState = AJOBS_STATE_CONFIGURED_RETRY;
            } else {
                obState = AJOBS_STATE_CONFIGURED_ERROR;
            }
        } else if ((status == AJ_ERR_SECURITY) /* (wifiConnectState == AJ_WIFI_AUTH_FAILED)*/) {
            obLastError.code = AJOBS_STATE_LAST_ERROR_UNAUTHORIZED;
            strncpy(obLastError.message, "Authorization failed!", AJOBS_ERROR_MESSAGE_LEN);
            if (connectInfo->state == AJOBS_STATE_CONFIGURED_VALIDATED || connectInfo->state == AJOBS_STATE_CONFIGURED_RETRY) {
                obState = AJOBS_STATE_CONFIGURED_RETRY;
            } else {
                obState = AJOBS_STATE_CONFIGURED_ERROR;
            }
        } else if (status == AJ_ERR_DRIVER) {
            obLastError.code = AJOBS_STATE_LAST_ERROR_ERROR_MESSAGE;
            strncpy(obLastError.message, "Driver error", AJOBS_ERROR_MESSAGE_LEN);
            obState = AJOBS_STATE_CONFIGURED_ERROR;
        } else if (status == AJ_ERR_DHCP) {
            obLastError.code = AJOBS_STATE_LAST_ERROR_ERROR_MESSAGE;
            strncpy(obLastError.message, "Failed to establish IP!", AJOBS_ERROR_MESSAGE_LEN);
            if (connectInfo->state == AJOBS_STATE_CONFIGURED_VALIDATED || connectInfo->state == AJOBS_STATE_CONFIGURED_RETRY) {
                obState = AJOBS_STATE_CONFIGURED_RETRY;
            } else {
                obState = AJOBS_STATE_CONFIGURED_ERROR;
            }
        } else {
            obLastError.code = AJOBS_STATE_LAST_ERROR_ERROR_MESSAGE;
            strncpy(obLastError.message, "Failed to connect! Unexpected error", AJOBS_ERROR_MESSAGE_LEN);
            obState = AJOBS_STATE_CONFIGURED_ERROR;
        }

        if (obState == AJOBS_STATE_CONFIGURED_VALIDATED) {
            break;
        }
        AJ_WarnPrintf(("Warning - DoConnectWifi wifiConnectState = %s\n", AJ_WiFiConnectStateText(wifiConnectState)));
        AJ_WarnPrintf(("Last error set to \"%s\" (code=%d)\n", obLastError.message, obLastError.code));

        if (obState == AJOBS_STATE_CONFIGURED_ERROR || obState == AJOBS_STATE_CONFIGURED_RETRY) {
            if (retries++ >= obSettings->AJOBS_MAX_RETRIES) {
                if (obState == AJOBS_STATE_CONFIGURED_ERROR && connectInfo->state == AJOBS_STATE_CONFIGURED_VALIDATING) {
                    if (connectInfo->authType < 0 && fallback > fallbackUntil) {
                        obLastError.code = AJOBS_STATE_LAST_ERROR_UNSUPPORTED_PROTOCOL;
                        strncpy(obLastError.message, "Unsupported protocol", AJOBS_ERROR_MESSAGE_LEN);
                        fallback--; // Try next authentication protocol
                        secType = GetSecType(fallback);
                        cipherType = GetCipherType(fallback);
                        retries = 0;
                        AJ_InfoPrintf(("Trying to connect with fallback auth=%d (secType=%d, cipherType=%d)\n", fallback, secType, cipherType));
                        continue;
                    }
                }
                break;
            }
            AJ_InfoPrintf(("Retry number %d out of %d\n", retries, obSettings->AJOBS_MAX_RETRIES));
        }
    }

    connectInfo->state = obState;
    status = (*obWriteInfo)(connectInfo);
    return status;
}
Exemple #3
0
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);
    }
}
Exemple #4
0
AJ_Status ConfigureWifi() {
	if (AJ_ResetWiFi() == AJ_OK) {
		return AJ_ConnectWiFi("Teleperse", 0, 0, "sg15gu25");
	}
	return AJ_ERR_NULL;
}