main.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. //replace IP on line 283 with ASTERISK_IP
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include "freertos/FreeRTOS.h"
  6. #include "freertos/task.h"
  7. #include "esp_wifi.h"
  8. #include "esp_event.h"
  9. #include "esp_log.h"
  10. #include "nvs_flash.h"
  11. #include "lwip/sockets.h"
  12. #include <stdbool.h>
  13. #include "mbedtls/md5.h"
  14. #define ESP32_IP "10.0.0.15"
  15. #define RTP_PORT 4000
  16. #define WIFI_SSID "TOCHTECH"
  17. #define WIFI_PASS "Smarturns2017"
  18. #define ASTERISK_IP "192.168.68.64"
  19. #define SIP_PORT 5060
  20. static const char *TAG = "SIP";
  21. static volatile bool wifi_ready = false;
  22. /* ================= WIFI ================= */
  23. static void wifi_event_handler(void *arg, esp_event_base_t event_base,
  24. int32_t event_id, void *event_data)
  25. {
  26. if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
  27. esp_wifi_connect();
  28. }
  29. else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
  30. ESP_LOGI(TAG, "WiFi disconnected, retrying...");
  31. wifi_ready = false;
  32. esp_wifi_connect();
  33. }
  34. else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
  35. ESP_LOGI(TAG, "WiFi connected!");
  36. wifi_ready = true;
  37. }
  38. }
  39. void wifi_init(void)
  40. {
  41. nvs_flash_init();
  42. esp_netif_init();
  43. esp_event_loop_create_default();
  44. esp_netif_create_default_wifi_sta();
  45. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  46. esp_wifi_init(&cfg);
  47. esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL);
  48. esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL);
  49. wifi_config_t wifi_config = {
  50. .sta = {
  51. .ssid = WIFI_SSID,
  52. .password = WIFI_PASS,
  53. },
  54. };
  55. esp_wifi_set_mode(WIFI_MODE_STA);
  56. esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
  57. esp_wifi_start();
  58. }
  59. /* ================= MD5 HELPERS ================= */
  60. static void md5_calc(const unsigned char *input, size_t len, unsigned char output[16])
  61. {
  62. mbedtls_md5_context ctx;
  63. mbedtls_md5_init(&ctx);
  64. mbedtls_md5_starts(&ctx);
  65. mbedtls_md5_update(&ctx, input, len);
  66. mbedtls_md5_finish(&ctx, output);
  67. mbedtls_md5_free(&ctx);
  68. }
  69. static void md5_to_hex(unsigned char *md5, char *out)
  70. {
  71. for (int i = 0; i < 16; i++) {
  72. sprintf(out + i * 2, "%02x", md5[i]);
  73. }
  74. }
  75. /* ================= SIP DIGEST ================= */
  76. void sip_compute_response(
  77. const char *username,
  78. const char *realm,
  79. const char *password,
  80. const char *nonce,
  81. const char *uri,
  82. char *out_response)
  83. {
  84. unsigned char ha1_md5[16], ha2_md5[16], final_md5[16];
  85. char ha1_hex[64], ha2_hex[64], final_str[256];
  86. char ha1[128], ha2[128];
  87. snprintf(ha1, sizeof(ha1), "%s:%s:%s", username, realm, password);
  88. md5_calc((unsigned char*)ha1, strlen(ha1), ha1_md5);
  89. md5_to_hex(ha1_md5, ha1_hex);
  90. snprintf(ha2, sizeof(ha2), "REGISTER:%s", uri);
  91. md5_calc((unsigned char*)ha2, strlen(ha2), ha2_md5);
  92. md5_to_hex(ha2_md5, ha2_hex);
  93. snprintf(final_str, sizeof(final_str),
  94. "%s:%s:%s", ha1_hex, nonce, ha2_hex);
  95. md5_calc((unsigned char*)final_str, strlen(final_str), final_md5);
  96. md5_to_hex(final_md5, out_response);
  97. }
  98. /* ================= SIP TASK ================= */
  99. void sip_register_task(void *pvParameters)
  100. {
  101. struct sockaddr_in server = {0};
  102. server.sin_family = AF_INET;
  103. server.sin_port = htons(SIP_PORT);
  104. server.sin_addr.s_addr = inet_addr(ASTERISK_IP);
  105. int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  106. struct sockaddr_in local_addr = {0};
  107. local_addr.sin_family = AF_INET;
  108. local_addr.sin_port = htons(5062);
  109. local_addr.sin_addr.s_addr = INADDR_ANY;
  110. if (bind(sock,
  111. (struct sockaddr *)&local_addr,
  112. sizeof(local_addr)) < 0) {
  113. ESP_LOGE(TAG, "Failed to bind SIP port 5062");
  114. close(sock);
  115. vTaskDelete(NULL);
  116. return;
  117. }
  118. ESP_LOGI(TAG, "SIP listening on UDP 5062");
  119. if (sock < 0) {
  120. ESP_LOGE(TAG, "Socket failed");
  121. vTaskDelete(NULL);
  122. return;
  123. }
  124. struct timeval timeout = {
  125. .tv_sec = 300,
  126. .tv_usec = 0
  127. };
  128. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
  129. /* ================= FIRST REGISTER ================= */
  130. char register_msg[512];
  131. snprintf(register_msg, sizeof(register_msg),
  132. "REGISTER sip:%s SIP/2.0\r\n"
  133. "Via: SIP/2.0/UDP 0.0.0.0:5062\r\n"
  134. "From: <sip:1001@%s>;tag=1234\r\n"
  135. "To: <sip:1001@%s>\r\n"
  136. "Call-ID: esp32-0001\r\n"
  137. "CSeq: 1 REGISTER\r\n"
  138. "Contact: <sip:1001@0.0.0.0:5062>\r\n"
  139. "Expires: 300\r\n"
  140. "Content-Length: 0\r\n"
  141. "\r\n",
  142. ASTERISK_IP,
  143. ASTERISK_IP,
  144. ASTERISK_IP);
  145. ESP_LOGI(TAG, "Sending REGISTER...");
  146. sendto(sock, register_msg, strlen(register_msg), 0,
  147. (struct sockaddr*)&server, sizeof(server));
  148. /* ================= RECEIVE 401 ================= */
  149. char response[1024];
  150. socklen_t addr_len = sizeof(server);
  151. int len = recvfrom(sock, response, sizeof(response) - 1, 0,
  152. (struct sockaddr*)&server, &addr_len);
  153. if (len <= 0) {
  154. ESP_LOGE(TAG, "No response");
  155. close(sock);
  156. vTaskDelete(NULL);
  157. return;
  158. }
  159. response[len] = '\0';
  160. printf("401 RESPONSE:\n%s\n", response);
  161. if (!strstr(response, "401")) {
  162. ESP_LOGE(TAG, "Expected 401 Unauthorized");
  163. close(sock);
  164. vTaskDelete(NULL);
  165. return;
  166. }
  167. /* ================= EXTRACT NONCE ================= */
  168. char sip_nonce[256] = {0};
  169. char *n = strstr(response, "nonce=\"");
  170. if (!n) {
  171. ESP_LOGE(TAG, "No nonce found");
  172. close(sock);
  173. vTaskDelete(NULL);
  174. return;
  175. }
  176. n += 7;
  177. char *end = strchr(n, '"');
  178. if (!end) {
  179. ESP_LOGE(TAG, "Bad nonce format");
  180. close(sock);
  181. vTaskDelete(NULL);
  182. return;
  183. }
  184. size_t nlen = end - n;
  185. if (nlen >= sizeof(sip_nonce)) {
  186. ESP_LOGE(TAG, "Nonce too long");
  187. close(sock);
  188. vTaskDelete(NULL);
  189. return;
  190. }
  191. strncpy(sip_nonce, n, nlen);
  192. sip_nonce[nlen] = '\0';
  193. ESP_LOGI(TAG, "Nonce: %s", sip_nonce);
  194. /* ================= EXTRACT REALM ================= */
  195. char sip_realm[128] = {0};
  196. char *r = strstr(response, "realm=\"");
  197. if (r) {
  198. r += 7;
  199. char *rend = strchr(r, '"');
  200. if (rend) {
  201. size_t rlen = rend - r;
  202. if (rlen < sizeof(sip_realm)) {
  203. strncpy(sip_realm, r, rlen);
  204. sip_realm[rlen] = '\0';
  205. }
  206. }
  207. }
  208. if (sip_realm[0] == '\0') {
  209. ESP_LOGE(TAG, "Realm not found");
  210. close(sock);
  211. vTaskDelete(NULL);
  212. return;
  213. }
  214. ESP_LOGI(TAG, "Realm: %s", sip_realm);
  215. /* ================= AUTH DIGEST ================= */
  216. char response_hash[64];
  217. sip_compute_response(
  218. "1001",
  219. sip_realm,
  220. "secret123",
  221. sip_nonce,
  222. "sip:192.168.68.64", // replace this 192.168.68.64 with ASTERISK_IP
  223. response_hash
  224. );
  225. /* ================= AUTH REGISTER ================= */
  226. char auth[1024];
  227. snprintf(auth, sizeof(auth),
  228. "REGISTER sip:%s SIP/2.0\r\n"
  229. "Via: SIP/2.0/UDP 0.0.0.0:5062\r\n"
  230. "From: <sip:1001@%s>;tag=1234\r\n"
  231. "To: <sip:1001@%s>\r\n"
  232. "Call-ID: esp32-0001\r\n"
  233. "CSeq: 2 REGISTER\r\n"
  234. "Contact: <sip:1001@0.0.0.0:5062>\r\n"
  235. "Authorization: Digest username=\"1001\", realm=\"%s\", nonce=\"%s\", uri=\"sip:%s\", response=\"%s\"\r\n"
  236. "Expires: 300\r\n"
  237. "Content-Length: 0\r\n"
  238. "\r\n",
  239. ASTERISK_IP,
  240. ASTERISK_IP,
  241. ASTERISK_IP,
  242. sip_realm,
  243. sip_nonce,
  244. ASTERISK_IP,
  245. response_hash);
  246. ESP_LOGI(TAG, "Sending AUTH REGISTER...");
  247. sendto(sock, auth, strlen(auth), 0,
  248. (struct sockaddr*)&server, sizeof(server));
  249. /* ================= FINAL RESPONSE ================= */
  250. /* ================= FINAL RESPONSE ================= */
  251. char final_resp[1024];
  252. int len2 = recvfrom(sock,
  253. final_resp,
  254. sizeof(final_resp) - 1,
  255. 0,
  256. (struct sockaddr *)&server,
  257. &addr_len);
  258. if (len2 <= 0) {
  259. ESP_LOGW(TAG, "No final response");
  260. close(sock);
  261. vTaskDelete(NULL);
  262. return;
  263. }
  264. final_resp[len2] = '\0';
  265. printf("FINAL RESPONSE:\n%s\n", final_resp);
  266. if (!strstr(final_resp, "200 OK")) {
  267. ESP_LOGW(TAG, "REGISTER FAILED");
  268. close(sock);
  269. vTaskDelete(NULL);
  270. return;
  271. }
  272. ESP_LOGI(TAG, "🎉 SIP REGISTER SUCCESS");
  273. /* =====================================================
  274. * KEEP SOCKET OPEN AND WAIT FOR SIP REQUESTS
  275. * ===================================================== */
  276. ESP_LOGI(TAG, "Waiting for incoming SIP requests...");
  277. while (1) {
  278. char rx_buf[2048];
  279. int rx_len = recvfrom(sock,
  280. rx_buf,
  281. sizeof(rx_buf) - 1,
  282. 0,
  283. (struct sockaddr *)&server,
  284. &addr_len);
  285. if (rx_len <= 0) {
  286. continue;
  287. }
  288. rx_buf[rx_len] = '\0';
  289. printf("\n========================================\n");
  290. printf("SIP MESSAGE RECEIVED:\n");
  291. printf("%s\n", rx_buf);
  292. printf("========================================\n");
  293. if (strstr(rx_buf, "INVITE")) {
  294. ESP_LOGI(TAG, "📞 Incoming INVITE");
  295. /* ================= EXTRACT SIP HEADERS ================= */
  296. char via[512] = {0};
  297. char from[256] = {0};
  298. char to[256] = {0};
  299. char callid[256] = {0};
  300. char cseq[128] = {0};
  301. sscanf(strstr(rx_buf, "Via:"),
  302. "Via: %[^\r\n]",
  303. via);
  304. sscanf(strstr(rx_buf, "From:"),
  305. "From: %[^\r\n]",
  306. from);
  307. sscanf(strstr(rx_buf, "To:"),
  308. "To: %[^\r\n]",
  309. to);
  310. sscanf(strstr(rx_buf, "Call-ID:"),
  311. "Call-ID: %[^\r\n]",
  312. callid);
  313. sscanf(strstr(rx_buf, "CSeq:"),
  314. "CSeq: %[^\r\n]",
  315. cseq);
  316. /* ================= SEND 100 TRYING ================= */
  317. char trying[4096];
  318. snprintf(trying, sizeof(trying),
  319. "SIP/2.0 100 Trying\r\n"
  320. "Via: %s\r\n"
  321. "From: %s\r\n"
  322. "To: %s\r\n"
  323. "Call-ID: %s\r\n"
  324. "CSeq: %s\r\n"
  325. "Content-Length: 0\r\n"
  326. "\r\n",
  327. via,
  328. from,
  329. to,
  330. callid,
  331. cseq);
  332. sendto(sock,
  333. trying,
  334. strlen(trying),
  335. 0,
  336. (struct sockaddr *)&server,
  337. sizeof(server));
  338. ESP_LOGI(TAG, "100 Trying sent");
  339. char ringing[2048];
  340. snprintf(ringing, sizeof(ringing),
  341. "SIP/2.0 180 Ringing\r\n"
  342. "Via: %s\r\n"
  343. "From: %s\r\n"
  344. "To: %s\r\n"
  345. "Call-ID: %s\r\n"
  346. "CSeq: %s\r\n"
  347. "Contact: <sip:1001@10.0.0.15:5062>\r\n"
  348. "Content-Length: 0\r\n"
  349. "\r\n",
  350. via,
  351. from,
  352. to,
  353. callid,
  354. cseq);
  355. sendto(sock,
  356. ringing,
  357. strlen(ringing),
  358. 0,
  359. (struct sockaddr *)&server,
  360. sizeof(server));
  361. ESP_LOGI(TAG, "180 Ringing sent");
  362. char ok[2048];
  363. const char *sdp =
  364. "v=0\r\n"
  365. "o=ESP32 1234 1234 IN IP4 " ESP32_IP "\r\n"
  366. "s=ESP32 SIP Call\r\n"
  367. "c=IN IP4 " ESP32_IP "\r\n"
  368. "t=0 0\r\n"
  369. "m=audio 4000 RTP/AVP 0 101\r\n"
  370. "a=rtpmap:0 PCMU/8000\r\n"
  371. "a=rtpmap:101 telephone-event/8000\r\n"
  372. "a=fmtp:101 0-16\r\n"
  373. "a=ptime:20\r\n"
  374. "a=sendrecv\r\n";
  375. snprintf(ok, sizeof(ok),
  376. "SIP/2.0 200 OK\r\n"
  377. "Via: %s\r\n"
  378. "From: %s\r\n"
  379. "To: %s;tag=esp32\r\n"
  380. "Call-ID: %s\r\n"
  381. "CSeq: %s\r\n"
  382. "Contact: <sip:1001@" ESP32_IP ":5062>\r\n"
  383. "Content-Type: application/sdp\r\n"
  384. "Content-Length: %d\r\n"
  385. "\r\n"
  386. "%s",
  387. via,
  388. from,
  389. to,
  390. callid,
  391. cseq,
  392. strlen(sdp),
  393. sdp);
  394. sendto(sock,
  395. ok,
  396. strlen(ok),
  397. 0,
  398. (struct sockaddr *)&server,
  399. sizeof(server));
  400. ESP_LOGI(TAG, "200 OK sent");
  401. }
  402. else if (strstr(rx_buf, "OPTIONS")) {
  403. ESP_LOGI(TAG, "Received OPTIONS");
  404. }
  405. else if (strstr(rx_buf, "ACK")) {
  406. ESP_LOGI(TAG, "Received ACK");
  407. }
  408. else if (strstr(rx_buf, "BYE")) {
  409. ESP_LOGI(TAG, "Received BYE");
  410. }
  411. else {
  412. ESP_LOGI(TAG, "Unknown SIP message");
  413. }
  414. }
  415. close(sock);
  416. vTaskDelete(NULL);
  417. }
  418. /* ================= MAIN ================= */
  419. void app_main(void)
  420. {
  421. ESP_LOGI(TAG, "Starting SIP client...");
  422. wifi_init();
  423. while (!wifi_ready) {
  424. vTaskDelay(pdMS_TO_TICKS(500));
  425. }
  426. xTaskCreate(sip_register_task,
  427. "sip_register",
  428. 20480,
  429. NULL,
  430. 5,
  431. NULL);
  432. }