#include "xz_protocol.h" #include "xz_settings.h" #include "xz_http.h" #include "mqtt_probe.h" #include "cJSON.h" #include "mbedtls/base64.h" #include "mbedtls/sha1.h" #include #include #include #include #include #include #define TAG "xiaozhi" #define BODY_CAP 8192 static const char ws_hello[] = "{\"type\":\"hello\",\"version\":1,\"transport\":\"websocket\"," "\"audio_params\":{\"format\":\"opus\",\"sample_rate\":16000,\"channels\":1,\"frame_duration\":60}}"; static const char *json_string(const cJSON *obj, const char *key) { return cJSON_GetStringValue(cJSON_GetObjectItemCaseSensitive(obj, key)); } /* Small outgoing frames suffice for client hello, pong and close. */ static int ws_send(xz_tls_t *tls, unsigned opcode, const void *data, size_t len) { uint8_t packet[8 + sizeof(ws_hello)], mask[4]; if (len > sizeof(ws_hello) || bk_fill_rand(mask, sizeof(mask))) return -1; size_t p = 0; packet[p++] = 0x80 | opcode; if (len >= 126) { packet[p++] = 0xfe; packet[p++] = (uint8_t)(len >> 8); packet[p++] = (uint8_t)len; } else packet[p++] = 0x80 | (uint8_t)len; memcpy(packet + p, mask, 4); p += 4; for (size_t i = 0; i < len; ++i) packet[p++] = ((const uint8_t *)data)[i] ^ mask[i % 4]; return xz_tls_write_all(tls, packet, p); } static int ws_read_hello(xz_tls_t *tls) { char *text = malloc(BODY_CAP); if (!text) return -1; size_t used = 0; int fragment = 0, result = -1; for (;;) { uint8_t h[2]; if (xz_tls_read_exact(tls, h, 2) || (h[0] & 0x70) || (h[1] & 0x80)) break; unsigned fin = h[0] >> 7, opcode = h[0] & 15; size_t len = h[1] & 127; if (opcode >= 8 && (!fin || len > 125)) break; if (len == 127) break; /* Server hello is bounded to BODY_CAP. */ if (len == 126) { if (xz_tls_read_exact(tls, h, 2)) break; len = ((size_t)h[0] << 8) | h[1]; if (len < 126) break; } if (opcode >= 8) { uint8_t payload[125]; if (xz_tls_read_exact(tls, payload, len)) break; if (opcode == 9 && ws_send(tls, 10, payload, len)) break; if (opcode != 9 && opcode != 10) break; continue; } if (opcode != (fragment ? 0 : 1) || len >= BODY_CAP - used || xz_tls_read_exact(tls, text + used, len)) break; used += len; fragment = !fin; if (fragment) continue; text[used] = 0; cJSON *root = memchr(text, 0, used) ? NULL : cJSON_ParseWithLengthOpts(text, used + 1, NULL, 1); const char *type = json_string(root, "type"); const char *transport = json_string(root, "transport"); if (type && !strcmp(type, "hello") && transport && !strcmp(transport, "websocket")) result = 0; cJSON_Delete(root); if (!result) break; used = 0; } free(text); return result; } static int ws_probe(const char *address, const char *token, int version, const char *mac, const char *uuid) { xz_url_t url; if (version != 1 || xz_parse_url(address, "wss://", &url)) { BK_LOGE(TAG, "requires WSS and protocol version 1\r\n"); return -1; } if (!token) token = ""; for (const unsigned char *p = (const unsigned char *)token; *p; ++p) if (*p < 32 || *p > 126) return -1; unsigned char nonce[16], key[25], digest[20], expected[29]; size_t n; if (bk_fill_rand(nonce, sizeof(nonce)) || mbedtls_base64_encode(key, sizeof(key), &n, nonce, sizeof(nonce))) return -1; char challenge[64]; int len = snprintf(challenge, sizeof(challenge), "%s258EAFA5-E914-47DA-95CA-C5AB0DC85B11", key); if (mbedtls_sha1((unsigned char *)challenge, len, digest) || mbedtls_base64_encode(expected, sizeof(expected), &n, digest, sizeof(digest))) return -1; xz_tls_t *tls; if (xz_tls_open(url.host, url.port, &tls)) return -1; char *request = malloc(4096); int result = -1; if (!request) goto done; len = snprintf(request, 4096, "GET %s HTTP/1.1\r\nHost: %s:%u\r\nUpgrade: websocket\r\n" "Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: %s\r\n" "Protocol-Version: 1\r\nDevice-Id: %s\r\nClient-Id: %s\r\n%s%s%s%s\r\n", url.path, url.host, url.port, key, mac, uuid, *token ? "Authorization: " : "", *token && !strchr(token, ' ') ? "Bearer " : "", token, *token ? "\r\n" : ""); if (len < 0 || len >= 4096 || xz_tls_write_all(tls, request, len)) goto done; xz_response_t head; if (xz_read_headers(tls, &head)) goto done; if (head.status != 101 || !head.connection_upgrade || !head.websocket || strcmp(head.accept, (const char *)expected)) { BK_LOGE(TAG, "WebSocket upgrade rejected status=%u\r\n", head.status); goto done; } xz_tls_start_deadline(tls, 10000); if (ws_send(tls, 1, ws_hello, sizeof(ws_hello) - 1) || ws_read_hello(tls)) goto done; BK_LOGI(TAG, "SERVER_HELLO transport=websocket\r\n"); const uint8_t close_code[] = {0x03, 0xe8}; ws_send(tls, 8, close_code, sizeof(close_code)); result = 0; done: free(request); xz_tls_close(tls); return result; } static cJSON *ota_request(const char *mac, const char *uuid, int activate, unsigned *status) { *status = 0; xz_url_t url; if (xz_parse_url(XZ_OTA_URL, "https://", &url)) return NULL; xz_tls_t *tls; if (xz_tls_open(url.host, url.port, &tls)) return NULL; char body[512], headers[1280]; int body_len = snprintf(body, sizeof(body), "{\"version\":2,\"language\":\"zh-CN\",\"chip_model_name\":\"bk7258\"," "\"mac_address\":\"%s\",\"uuid\":\"%s\",\"application\":{\"name\":\"bk7258-xiaozhi\"," "\"version\":\"1.0.0\"},\"board\":{\"type\":\"bk7258\",\"name\":\"lckfb-bk7258\"}}", mac, uuid); if (activate) { strcpy(body, "{}"); /* Activation-Version 1 has no serial-number signing key. */ body_len = 2; } const char *suffix = activate ? (url.path[strlen(url.path) - 1] == '/' ? "activate" : "/activate") : ""; int len = snprintf(headers, sizeof(headers), "POST %s%s HTTP/1.1\r\nHost: %s:%u\r\nContent-Type: application/json\r\n" "Device-Id: %s\r\nClient-Id: %s\r\nActivation-Version: 1\r\nAccept-Language: zh-CN\r\n" "User-Agent: lckfb-bk7258/1.0.0\r\nConnection: close\r\nContent-Length: %d\r\n\r\n", url.path, suffix, url.host, url.port, mac, uuid, body_len); cJSON *json = NULL; char *response = malloc(BODY_CAP); xz_response_t head; if (!response || len <= 0 || (size_t)len >= sizeof(headers) || body_len <= 0 || (size_t)body_len >= sizeof(body)) goto done; if (xz_tls_write_all(tls, headers, len) || xz_tls_write_all(tls, body, body_len) || xz_read_headers(tls, &head)) goto done; *status = head.status; BK_LOGI(TAG, "%s response status=%u\r\n", activate ? "activation" : "OTA", head.status); if (activate || head.status != 200) goto done; int size = xz_read_body(tls, &head, response, BODY_CAP); if (size > 0 && !memchr(response, 0, size)) json = cJSON_ParseWithLengthOpts(response, size + 1, NULL, 1); done: free(response); xz_tls_close(tls); return json; } int xz_probe(const char *mac, const char *uuid) { if (XZ_DIRECT_WSS[0]) return ws_probe(XZ_DIRECT_WSS, XZ_DIRECT_TOKEN, 1, mac, uuid); unsigned status; cJSON *ota = ota_request(mac, uuid, 0, &status); if (!ota) { BK_LOGE(TAG, "OTA TLS, HTTP or JSON failure\r\n"); return -1; } cJSON *activation = cJSON_GetObjectItemCaseSensitive(ota, "activation"); cJSON *mqtt = cJSON_GetObjectItemCaseSensitive(ota, "mqtt"); cJSON *ws = cJSON_GetObjectItemCaseSensitive(ota, "websocket"); int result = -1; const char *binding_code = json_string(activation, "code"); if (binding_code || json_string(activation, "challenge")) { BK_LOGW(TAG, "ACTIVATION_PENDING (use your private binding console)\r\n"); #if XZ_SHOW_BINDING_CODE static int code_shown; if (!code_shown && binding_code && strlen(binding_code) == 6 && strspn(binding_code, "0123456789") == 6) { code_shown = 1; BK_LOGW(TAG, "XZ_PRIVATE_BIND_CODE=%s\r\n", binding_code); } #endif result = 1; if (json_string(activation, "challenge")) { ota_request(mac, uuid, 1, &status); if (status != 200 && status != 202) { BK_LOGW(TAG, "activation request not accepted; waiting for updated OTA configuration\r\n"); } } } else if (cJSON_IsObject(mqtt)) { result = xiaozhi_mqtt_probe(mqtt); } else if (cJSON_IsObject(ws)) { cJSON *version = cJSON_GetObjectItemCaseSensitive(ws, "version"); result = ws_probe(json_string(ws, "url"), json_string(ws, "token"), cJSON_IsNumber(version) ? version->valueint : 1, mac, uuid); } else BK_LOGE(TAG, "OTA has no MQTT or WSS settings\r\n"); cJSON_Delete(ota); return result; }