raop.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. /*
  2. *
  3. * (c) Philippe 2019, philippe_44@outlook.com
  4. *
  5. * This software is released under the MIT License.
  6. * https://opensource.org/licenses/MIT
  7. *
  8. */
  9. #include <stdio.h>
  10. #include "platform.h"
  11. #ifdef WIN32
  12. #include <openssl/err.h>
  13. #include <openssl/rand.h>
  14. #include <openssl/rsa.h>
  15. #include <openssl/pem.h>
  16. #include <openssl/engine.h>
  17. #include "mdns.h"
  18. #include "mdnsd.h"
  19. #include "mdnssd-itf.h"
  20. #else
  21. #include "esp_pthread.h"
  22. #include "mdns.h"
  23. #include "mbedtls/version.h"
  24. #include <mbedtls/x509.h>
  25. #endif
  26. #include "util.h"
  27. #include "raop.h"
  28. #include "rtp.h"
  29. #include "dmap_parser.h"
  30. #include "log_util.h"
  31. #define RTSP_STACK_SIZE (8*1024)
  32. #define SEARCH_STACK_SIZE (3*1024)
  33. typedef struct raop_ctx_s {
  34. #ifdef WIN32
  35. struct mdns_service *svc;
  36. struct mdnsd *svr;
  37. #endif
  38. struct in_addr host; // IP of bridge
  39. short unsigned port; // RTSP port for AirPlay
  40. int sock; // socket of the above
  41. struct in_addr peer; // IP of the iDevice (airplay sender)
  42. bool running;
  43. #ifdef WIN32
  44. pthread_t thread;
  45. #else
  46. TaskHandle_t thread, joiner;
  47. StaticTask_t *xTaskBuffer;
  48. StackType_t xStack[RTSP_STACK_SIZE] __attribute__ ((aligned (4)));
  49. #endif
  50. /*
  51. Compiler/Execution bug: if this bool is next to 'running', the rtsp_thread
  52. loop sees 'running' being set to false from at first execution ...
  53. */
  54. bool abort;
  55. unsigned char mac[6];
  56. int latency;
  57. struct {
  58. char *aesiv, *aeskey;
  59. char *fmtp;
  60. } rtsp;
  61. struct rtp_s *rtp;
  62. raop_cmd_cb_t cmd_cb;
  63. raop_data_cb_t data_cb;
  64. struct {
  65. char DACPid[32], id[32];
  66. struct in_addr host;
  67. u16_t port;
  68. bool running;
  69. #ifdef WIN32
  70. struct mDNShandle_s *handle;
  71. pthread_t thread;
  72. #else
  73. TaskHandle_t thread;
  74. StaticTask_t *xTaskBuffer;
  75. StackType_t xStack[SEARCH_STACK_SIZE] __attribute__ ((aligned (4)));;
  76. SemaphoreHandle_t destroy_mutex;
  77. #endif
  78. } active_remote;
  79. void *owner;
  80. } raop_ctx_t;
  81. extern struct mdnsd* glmDNSServer;
  82. extern log_level raop_loglevel;
  83. static log_level *loglevel = &raop_loglevel;
  84. #ifdef WIN32
  85. static void* rtsp_thread(void *arg);
  86. static void* search_remote(void *args);
  87. #else
  88. static void rtsp_thread(void *arg);
  89. static void search_remote(void *args);
  90. #endif
  91. static void cleanup_rtsp(raop_ctx_t *ctx, bool abort);
  92. static bool handle_rtsp(raop_ctx_t *ctx, int sock);
  93. static char* rsa_apply(unsigned char *input, int inlen, int *outlen, int mode);
  94. static int base64_pad(char *src, char **padded);
  95. static int base64_encode(const void *data, int size, char **str);
  96. static int base64_decode(const char *str, void *data);
  97. extern char private_key[];
  98. enum { RSA_MODE_KEY, RSA_MODE_AUTH };
  99. static void on_dmap_string(void *ctx, const char *code, const char *name, const char *buf, size_t len);
  100. /*----------------------------------------------------------------------------*/
  101. struct raop_ctx_s *raop_create(uint32_t host, char *name,
  102. unsigned char mac[6], int latency,
  103. raop_cmd_cb_t cmd_cb, raop_data_cb_t data_cb) {
  104. struct raop_ctx_s *ctx = malloc(sizeof(struct raop_ctx_s));
  105. struct sockaddr_in addr;
  106. char id[64];
  107. #ifdef WIN32
  108. socklen_t nlen = sizeof(struct sockaddr);
  109. char *txt[] = { "am=airesp32", "tp=UDP", "sm=false", "sv=false", "ek=1",
  110. "et=0,1", "md=0,1,2", "cn=0,1", "ch=2",
  111. "ss=16", "sr=44100", "vn=3", "txtvers=1",
  112. NULL };
  113. #else
  114. const mdns_txt_item_t txt[] = {
  115. {"am", "airesp32"},
  116. {"tp", "UDP"},
  117. {"sm","false"},
  118. {"sv","false"},
  119. {"ek","1"},
  120. {"et","0,1"},
  121. {"md","0,1,2"},
  122. {"cn","0,1"},
  123. {"ch","2"},
  124. {"ss","16"},
  125. {"sr","44100"},
  126. {"vn","3"},
  127. {"txtvers","1"},
  128. };
  129. #endif
  130. if (!ctx) return NULL;
  131. // make sure we have a clean context
  132. memset(ctx, 0, sizeof(raop_ctx_t));
  133. #ifdef WIN32
  134. ctx->svr = glmDNSServer;
  135. #endif
  136. ctx->host.s_addr = host;
  137. ctx->sock = socket(AF_INET, SOCK_STREAM, 0);
  138. ctx->cmd_cb = cmd_cb;
  139. ctx->data_cb = data_cb;
  140. ctx->latency = min(latency, 88200);
  141. if (ctx->sock == -1) {
  142. LOG_ERROR("Cannot create listening socket", NULL);
  143. free(ctx);
  144. return NULL;
  145. }
  146. memset(&addr, 0, sizeof(addr));
  147. addr.sin_addr.s_addr = host;
  148. addr.sin_family = AF_INET;
  149. #ifdef WIN32
  150. ctx->port = 0;
  151. addr.sin_port = htons(ctx->port);
  152. #else
  153. ctx->port = 5000;
  154. addr.sin_port = htons(ctx->port);
  155. #endif
  156. if (bind(ctx->sock, (struct sockaddr *) &addr, sizeof(addr)) < 0 || listen(ctx->sock, 1)) {
  157. LOG_ERROR("Cannot bind or listen RTSP listener: %s", strerror(errno));
  158. closesocket(ctx->sock);
  159. free(ctx);
  160. return NULL;
  161. }
  162. #ifdef WIN32
  163. getsockname(ctx->sock, (struct sockaddr *) &addr, &nlen);
  164. ctx->port = ntohs(addr.sin_port);
  165. #endif
  166. ctx->running = true;
  167. memcpy(ctx->mac, mac, 6);
  168. snprintf(id, 64, "%02X%02X%02X%02X%02X%02X@%s", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5], name);
  169. #ifdef WIN32
  170. // seems that Windows snprintf does not add NULL char if actual size > max
  171. id[63] = '\0';
  172. ctx->svc = mdnsd_register_svc(ctx->svr, id, "_raop._tcp.local", ctx->port, NULL, (const char**) txt);
  173. pthread_create(&ctx->thread, NULL, &rtsp_thread, ctx);
  174. #else
  175. LOG_INFO("starting mDNS with %s", id);
  176. mdns_service_add(id, "_raop", "_tcp", ctx->port, (mdns_txt_item_t*) txt, sizeof(txt) / sizeof(mdns_txt_item_t));
  177. ctx->xTaskBuffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  178. ctx->thread = xTaskCreateStaticPinnedToCore( (TaskFunction_t) rtsp_thread, "RTSP", RTSP_STACK_SIZE, ctx,
  179. ESP_TASK_PRIO_MIN + 2, ctx->xStack, ctx->xTaskBuffer, CONFIG_PTHREAD_TASK_CORE_DEFAULT);
  180. #endif
  181. return ctx;
  182. }
  183. /*----------------------------------------------------------------------------*/
  184. void raop_abort(struct raop_ctx_s *ctx) {
  185. LOG_INFO("[%p]: aborting RTSP session at next select() wakeup", ctx);
  186. ctx->abort = true;
  187. }
  188. /*----------------------------------------------------------------------------*/
  189. void raop_delete(struct raop_ctx_s *ctx) {
  190. #ifdef WIN32
  191. int sock;
  192. struct sockaddr addr;
  193. socklen_t nlen = sizeof(struct sockaddr);
  194. #endif
  195. if (!ctx) return;
  196. #ifdef WIN32
  197. ctx->running = false;
  198. // wake-up thread by connecting socket, needed for freeBSD
  199. sock = socket(AF_INET, SOCK_STREAM, 0);
  200. getsockname(ctx->sock, (struct sockaddr *) &addr, &nlen);
  201. connect(sock, (struct sockaddr*) &addr, sizeof(addr));
  202. closesocket(sock);
  203. pthread_join(ctx->thread, NULL);
  204. rtp_end(ctx->rtp);
  205. shutdown(ctx->sock, SD_BOTH);
  206. closesocket(ctx->sock);
  207. // terminate search, but do not reclaim memory of pthread if never launched
  208. if (ctx->active_remote.handle) {
  209. close_mDNS(ctx->active_remote.handle);
  210. pthread_join(ctx->active_remote.thread, NULL);
  211. }
  212. // stop broadcasting devices
  213. mdns_service_remove(ctx->svr, ctx->svc);
  214. mdnsd_stop(ctx->svr);
  215. #else
  216. // then the RTSP task
  217. ctx->joiner = xTaskGetCurrentTaskHandle();
  218. ctx->running = false;
  219. // brute-force exit of accept()
  220. shutdown(ctx->sock, SHUT_RDWR);
  221. closesocket(ctx->sock);
  222. // wait to make sure LWIP if scheduled (avoid issue with NotifyTake)
  223. vTaskDelay(100 / portTICK_PERIOD_MS);
  224. ulTaskNotifyTake(pdFALSE, portMAX_DELAY);
  225. vTaskDelete(ctx->thread);
  226. SAFE_PTR_FREE(ctx->xTaskBuffer);
  227. // cleanup all session-created items
  228. cleanup_rtsp(ctx, true);
  229. mdns_service_remove("_raop", "_tcp");
  230. #endif
  231. NFREE(ctx->rtsp.aeskey);
  232. NFREE(ctx->rtsp.aesiv);
  233. NFREE(ctx->rtsp.fmtp);
  234. free(ctx);
  235. }
  236. /*----------------------------------------------------------------------------*/
  237. bool raop_cmd(struct raop_ctx_s *ctx, raop_event_t event, void *param) {
  238. struct sockaddr_in addr;
  239. int sock;
  240. char *command = NULL;
  241. bool success = false;
  242. // first notify the remote controller (if any)
  243. switch(event) {
  244. case RAOP_REW:
  245. command = strdup("beginrew");
  246. break;
  247. case RAOP_FWD:
  248. command = strdup("beginff");
  249. break;
  250. case RAOP_PREV:
  251. command = strdup("previtem");
  252. break;
  253. case RAOP_NEXT:
  254. command = strdup("nextitem");
  255. break;
  256. case RAOP_TOGGLE:
  257. command = strdup("playpause");
  258. break;
  259. case RAOP_PAUSE:
  260. command = strdup("pause");
  261. break;
  262. case RAOP_PLAY:
  263. command = strdup("play");
  264. break;
  265. case RAOP_RESUME:
  266. command = strdup("playresume");
  267. break;
  268. case RAOP_STOP:
  269. command = strdup("stop");
  270. break;
  271. case RAOP_VOLUME_UP:
  272. command = strdup("volumeup");
  273. break;
  274. case RAOP_VOLUME_DOWN:
  275. command = strdup("volumedown");
  276. break;
  277. case RAOP_VOLUME: {
  278. float Volume = *((float*) param);
  279. Volume = Volume ? (Volume - 1) * 30 : -144;
  280. asprintf(&command,"setproperty?dmcp.device-volume=%0.4lf", Volume);
  281. break;
  282. }
  283. default:
  284. break;
  285. }
  286. // no command to send to remote or no remote found yet
  287. if (!command || !ctx->active_remote.port) {
  288. NFREE(command);
  289. return success;
  290. }
  291. sock = socket(AF_INET, SOCK_STREAM, 0);
  292. memset(&addr, 0, sizeof(addr));
  293. addr.sin_family = AF_INET;
  294. addr.sin_addr.s_addr = S_ADDR(ctx->active_remote.host);
  295. addr.sin_port = htons(ctx->active_remote.port);
  296. if (!connect(sock, (struct sockaddr*) &addr, sizeof(addr))) {
  297. char *method, *buf, resp[512] = "";
  298. int len;
  299. key_data_t headers[4] = { {NULL, NULL} };
  300. asprintf(&method, "GET /ctrl-int/1/%s HTTP/1.0", command);
  301. kd_add(headers, "Active-Remote", ctx->active_remote.id);
  302. kd_add(headers, "Connection", "close");
  303. buf = http_send(sock, method, headers);
  304. len = recv(sock, resp, 512, 0);
  305. if (len > 0) resp[len-1] = '\0';
  306. LOG_INFO("[%p]: sending airplay remote\n%s<== received ==>\n%s", ctx, buf, resp);
  307. NFREE(method);
  308. NFREE(buf);
  309. kd_free(headers);
  310. success = true;
  311. } else {
  312. LOG_INFO("[%p]: can't connect to remote for %s", ctx, command);
  313. }
  314. free(command);
  315. closesocket(sock);
  316. return success;
  317. }
  318. /*----------------------------------------------------------------------------*/
  319. #ifdef WIN32
  320. static void *rtsp_thread(void *arg) {
  321. #else
  322. static void rtsp_thread(void *arg) {
  323. #endif
  324. raop_ctx_t *ctx = (raop_ctx_t*) arg;
  325. int sock = -1;
  326. while (ctx->running) {
  327. fd_set rfds;
  328. struct timeval timeout = {0, 100*1000};
  329. int n;
  330. bool res = false;
  331. if (sock == -1) {
  332. struct sockaddr_in peer;
  333. socklen_t addrlen = sizeof(struct sockaddr_in);
  334. sock = accept(ctx->sock, (struct sockaddr*) &peer, &addrlen);
  335. ctx->peer.s_addr = peer.sin_addr.s_addr;
  336. ctx->abort = false;
  337. if (sock != -1 && ctx->running) {
  338. LOG_INFO("got RTSP connection %u", sock);
  339. } else continue;
  340. }
  341. FD_ZERO(&rfds);
  342. FD_SET(sock, &rfds);
  343. n = select(sock + 1, &rfds, NULL, NULL, &timeout);
  344. if (!n && !ctx->abort) continue;
  345. if (n > 0) res = handle_rtsp(ctx, sock);
  346. if (n < 0 || !res || ctx->abort) {
  347. cleanup_rtsp(ctx, true);
  348. closesocket(sock);
  349. LOG_INFO("RTSP close %u", sock);
  350. sock = -1;
  351. }
  352. }
  353. if (sock != -1) closesocket(sock);
  354. #ifndef WIN32
  355. xTaskNotifyGive(ctx->joiner);
  356. vTaskSuspend(NULL);
  357. #else
  358. return NULL;
  359. #endif
  360. }
  361. /*----------------------------------------------------------------------------*/
  362. static bool handle_rtsp(raop_ctx_t *ctx, int sock)
  363. {
  364. char *buf = NULL, *body = NULL, method[16] = "";
  365. key_data_t headers[16], resp[8] = { {NULL, NULL} };
  366. int len;
  367. bool success = true;
  368. if (!http_parse(sock, method, headers, &body, &len)) {
  369. NFREE(body);
  370. kd_free(headers);
  371. return false;
  372. }
  373. if (strcmp(method, "OPTIONS")) {
  374. LOG_INFO("[%p]: received %s", ctx, method);
  375. }
  376. if ((buf = kd_lookup(headers, "Apple-Challenge")) != NULL) {
  377. int n;
  378. char *buf_pad, *p, *data_b64 = NULL, data[32];
  379. LOG_INFO("[%p]: challenge %s", ctx, buf);
  380. // try to re-acquire IP address if we were missing it
  381. if (S_ADDR(ctx->host) == INADDR_ANY) {
  382. S_ADDR(ctx->host) = get_localhost(NULL);
  383. LOG_INFO("[%p]: IP was missing, trying to get it %s", ctx, inet_ntoa(ctx->host));
  384. }
  385. // need to pad the base64 string as apple device don't
  386. base64_pad(buf, &buf_pad);
  387. p = data + min(base64_decode(buf_pad, data), 32-10);
  388. p = (char*) memcpy(p, &S_ADDR(ctx->host), 4) + 4;
  389. p = (char*) memcpy(p, ctx->mac, 6) + 6;
  390. memset(p, 0, 32 - (p - data));
  391. p = rsa_apply((unsigned char*) data, 32, &n, RSA_MODE_AUTH);
  392. n = base64_encode(p, n, &data_b64);
  393. // remove padding as well (seems to be optional now)
  394. for (n = strlen(data_b64) - 1; n > 0 && data_b64[n] == '='; data_b64[n--] = '\0');
  395. kd_add(resp, "Apple-Response", data_b64);
  396. NFREE(p);
  397. NFREE(buf_pad);
  398. NFREE(data_b64);
  399. }
  400. if (!strcmp(method, "OPTIONS")) {
  401. kd_add(resp, "Public", "ANNOUNCE, SETUP, RECORD, PAUSE, FLUSH, TEARDOWN, OPTIONS, GET_PARAMETER, SET_PARAMETER");
  402. } else if (!strcmp(method, "ANNOUNCE")) {
  403. char *padded, *p;
  404. NFREE(ctx->rtsp.aeskey);
  405. NFREE(ctx->rtsp.aesiv);
  406. NFREE(ctx->rtsp.fmtp);
  407. if ((p = strcasestr(body, "rsaaeskey")) != NULL) {
  408. unsigned char *aeskey;
  409. int len, outlen;
  410. p = strextract(p, ":", "\r\n");
  411. base64_pad(p, &padded);
  412. aeskey = malloc(strlen(padded));
  413. len = base64_decode(padded, aeskey);
  414. ctx->rtsp.aeskey = rsa_apply(aeskey, len, &outlen, RSA_MODE_KEY);
  415. NFREE(p);
  416. NFREE(aeskey);
  417. NFREE(padded);
  418. }
  419. if ((p = strcasestr(body, "aesiv")) != NULL) {
  420. p = strextract(p, ":", "\r\n");
  421. base64_pad(p, &padded);
  422. ctx->rtsp.aesiv = malloc(strlen(padded));
  423. base64_decode(padded, ctx->rtsp.aesiv);
  424. NFREE(p);
  425. NFREE(padded);
  426. }
  427. if ((p = strcasestr(body, "fmtp")) != NULL) {
  428. p = strextract(p, ":", "\r\n");
  429. ctx->rtsp.fmtp = strdup(p);
  430. NFREE(p);
  431. }
  432. // on announce, search remote
  433. if ((buf = kd_lookup(headers, "DACP-ID")) != NULL) strcpy(ctx->active_remote.DACPid, buf);
  434. if ((buf = kd_lookup(headers, "Active-Remote")) != NULL) strcpy(ctx->active_remote.id, buf);
  435. #ifdef WIN32
  436. ctx->active_remote.handle = init_mDNS(false, ctx->host);
  437. pthread_create(&ctx->active_remote.thread, NULL, &search_remote, ctx);
  438. #else
  439. ctx->active_remote.running = true;
  440. ctx->active_remote.destroy_mutex = xSemaphoreCreateBinary();
  441. ctx->active_remote.xTaskBuffer = (StaticTask_t*) heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  442. ctx->active_remote.thread = xTaskCreateStaticPinnedToCore( (TaskFunction_t) search_remote, "search_remote", SEARCH_STACK_SIZE, ctx,
  443. ESP_TASK_PRIO_MIN + 2, ctx->active_remote.xStack, ctx->active_remote.xTaskBuffer,
  444. CONFIG_PTHREAD_TASK_CORE_DEFAULT );
  445. #endif
  446. } else if (!strcmp(method, "SETUP") && ((buf = kd_lookup(headers, "Transport")) != NULL)) {
  447. char *p;
  448. rtp_resp_t rtp = { 0 };
  449. short unsigned tport = 0, cport = 0;
  450. uint8_t *buffer = NULL;
  451. size_t size = 0;
  452. // we are about to stream, do something if needed and optionally give buffers to play with
  453. success = ctx->cmd_cb(RAOP_SETUP, &buffer, &size);
  454. if ((p = strcasestr(buf, "timing_port")) != NULL) sscanf(p, "%*[^=]=%hu", &tport);
  455. if ((p = strcasestr(buf, "control_port")) != NULL) sscanf(p, "%*[^=]=%hu", &cport);
  456. rtp = rtp_init(ctx->peer, ctx->latency, ctx->rtsp.aeskey, ctx->rtsp.aesiv,
  457. ctx->rtsp.fmtp, cport, tport, buffer, size, ctx->cmd_cb, ctx->data_cb);
  458. ctx->rtp = rtp.ctx;
  459. if ( (cport * tport * rtp.cport * rtp.tport * rtp.aport) != 0 && rtp.ctx) {
  460. char *transport;
  461. asprintf(&transport, "RTP/AVP/UDP;unicast;mode=record;control_port=%u;timing_port=%u;server_port=%u", rtp.cport, rtp.tport, rtp.aport);
  462. LOG_DEBUG("[%p]: audio=(%hu:%hu), timing=(%hu:%hu), control=(%hu:%hu)", ctx, 0, rtp.aport, tport, rtp.tport, cport, rtp.cport);
  463. kd_add(resp, "Transport", transport);
  464. kd_add(resp, "Session", "DEADBEEF");
  465. free(transport);
  466. } else {
  467. success = false;
  468. LOG_INFO("[%p]: cannot start session, missing ports", ctx);
  469. }
  470. } else if (!strcmp(method, "RECORD")) {
  471. unsigned short seqno = 0;
  472. unsigned rtptime = 0;
  473. char *p;
  474. if (ctx->latency) {
  475. char latency[6];
  476. snprintf(latency, 6, "%u", ctx->latency);
  477. kd_add(resp, "Audio-Latency", latency);
  478. }
  479. buf = kd_lookup(headers, "RTP-Info");
  480. if (buf && (p = strcasestr(buf, "seq")) != NULL) sscanf(p, "%*[^=]=%hu", &seqno);
  481. if (buf && (p = strcasestr(buf, "rtptime")) != NULL) sscanf(p, "%*[^=]=%u", &rtptime);
  482. if (ctx->rtp) rtp_record(ctx->rtp, seqno, rtptime);
  483. success = ctx->cmd_cb(RAOP_STREAM);
  484. } else if (!strcmp(method, "FLUSH")) {
  485. unsigned short seqno = 0;
  486. unsigned rtptime = 0;
  487. char *p;
  488. buf = kd_lookup(headers, "RTP-Info");
  489. if ((p = strcasestr(buf, "seq")) != NULL) sscanf(p, "%*[^=]=%hu", &seqno);
  490. if ((p = strcasestr(buf, "rtptime")) != NULL) sscanf(p, "%*[^=]=%u", &rtptime);
  491. // only send FLUSH if useful (discards frames above buffer head and top)
  492. if (ctx->rtp && rtp_flush(ctx->rtp, seqno, rtptime, true)) {
  493. success = ctx->cmd_cb(RAOP_FLUSH);
  494. rtp_flush_release(ctx->rtp);
  495. }
  496. } else if (!strcmp(method, "TEARDOWN")) {
  497. cleanup_rtsp(ctx, false);
  498. success = ctx->cmd_cb(RAOP_STOP);
  499. } else if (!strcmp(method, "SET_PARAMETER")) {
  500. char *p;
  501. if (body && (p = strcasestr(body, "volume")) != NULL) {
  502. float volume;
  503. sscanf(p, "%*[^:]:%f", &volume);
  504. LOG_INFO("[%p]: SET PARAMETER volume %f", ctx, volume);
  505. volume = (volume == -144.0) ? 0 : (1 + volume / 30);
  506. success = ctx->cmd_cb(RAOP_VOLUME, volume);
  507. } else if (body && (p = strcasestr(body, "progress")) != NULL) {
  508. int start, current, stop = 0;
  509. // we want ms, not s
  510. sscanf(p, "%*[^:]:%u/%u/%u", &start, &current, &stop);
  511. current = ((current - start) / 44100) * 1000;
  512. if (stop) stop = ((stop - start) / 44100) * 1000;
  513. LOG_INFO("[%p]: SET PARAMETER progress %d/%u %s", ctx, current, stop, p);
  514. success = ctx->cmd_cb(RAOP_PROGRESS, max(current, 0), stop);
  515. } else if (body && ((p = kd_lookup(headers, "Content-Type")) != NULL) && !strcasecmp(p, "application/x-dmap-tagged")) {
  516. struct metadata_s metadata;
  517. dmap_settings settings = {
  518. NULL, NULL, NULL, NULL, NULL, NULL, NULL, on_dmap_string, NULL,
  519. NULL
  520. };
  521. settings.ctx = &metadata;
  522. memset(&metadata, 0, sizeof(struct metadata_s));
  523. if (!dmap_parse(&settings, body, len)) {
  524. uint32_t timestamp = 0;
  525. if ((p = kd_lookup(headers, "RTP-Info")) != NULL) sscanf(p, "%*[^=]=%d", &timestamp);
  526. LOG_INFO("[%p]: received metadata (ts: %d)\n\tartist: %s\n\talbum: %s\n\ttitle: %s",
  527. ctx, timestamp, metadata.artist ? metadata.artist : "", metadata.album ? metadata.album : "",
  528. metadata.title ? metadata.title : "");
  529. success = ctx->cmd_cb(RAOP_METADATA, metadata.artist, metadata.album, metadata.title, timestamp);
  530. free_metadata(&metadata);
  531. }
  532. } else if (body && ((p = kd_lookup(headers, "Content-Type")) != NULL) && strcasestr(p, "image/jpeg")) {
  533. uint32_t timestamp = 0;
  534. if ((p = kd_lookup(headers, "RTP-Info")) != NULL) sscanf(p, "%*[^=]=%d", &timestamp);
  535. LOG_INFO("[%p]: received JPEG image of %d bytes (ts:%d)", ctx, len, timestamp);
  536. ctx->cmd_cb(RAOP_ARTWORK, body, len, timestamp);
  537. } else {
  538. char *dump = kd_dump(headers);
  539. LOG_INFO("Unhandled SET PARAMETER\n%s", dump);
  540. free(dump);
  541. }
  542. }
  543. // don't need to free "buf" because kd_lookup return a pointer, not a strdup
  544. kd_add(resp, "Audio-Jack-Status", "connected; type=analog");
  545. kd_add(resp, "CSeq", kd_lookup(headers, "CSeq"));
  546. if (success) {
  547. buf = http_send(sock, "RTSP/1.0 200 OK", resp);
  548. } else {
  549. buf = http_send(sock, "RTSP/1.0 503 ERROR", NULL);
  550. closesocket(sock);
  551. }
  552. if (strcmp(method, "OPTIONS")) {
  553. LOG_INFO("[%p]: responding:\n%s", ctx, buf ? buf : "<void>");
  554. }
  555. NFREE(body);
  556. NFREE(buf);
  557. kd_free(resp);
  558. kd_free(headers);
  559. return true;
  560. }
  561. /*----------------------------------------------------------------------------*/
  562. void cleanup_rtsp(raop_ctx_t *ctx, bool abort) {
  563. // first stop RTP process
  564. if (ctx->rtp) {
  565. rtp_end(ctx->rtp);
  566. ctx->rtp = NULL;
  567. if (abort) LOG_INFO("[%p]: RTP thread aborted", ctx);
  568. }
  569. if (ctx->active_remote.running) {
  570. #ifdef WIN32
  571. pthread_join(ctx->active_remote.thread, NULL);
  572. close_mDNS(ctx->active_remote.handle);
  573. #else
  574. // need to make sure no search is on-going and reclaim task memory
  575. ctx->active_remote.running = false;
  576. xSemaphoreTake(ctx->active_remote.destroy_mutex, portMAX_DELAY);
  577. vTaskDelete(ctx->active_remote.thread);
  578. SAFE_PTR_FREE(ctx->active_remote.xTaskBuffer);
  579. vSemaphoreDelete(ctx->active_remote.destroy_mutex);
  580. #endif
  581. memset(&ctx->active_remote, 0, sizeof(ctx->active_remote));
  582. LOG_INFO("[%p]: Remote search thread aborted", ctx);
  583. }
  584. NFREE(ctx->rtsp.aeskey);
  585. NFREE(ctx->rtsp.aesiv);
  586. NFREE(ctx->rtsp.fmtp);
  587. }
  588. /*----------------------------------------------------------------------------*/
  589. #ifdef WIN32
  590. bool search_remote_cb(mDNSservice_t *slist, void *cookie, bool *stop) {
  591. mDNSservice_t *s;
  592. raop_ctx_t *ctx = (raop_ctx_t*) cookie;
  593. // see if we have found an active remote for our ID
  594. for (s = slist; s; s = s->next) {
  595. if (strcasestr(s->name, ctx->active_remote.DACPid)) {
  596. ctx->active_remote.host = s->addr;
  597. ctx->active_remote.port = s->port;
  598. LOG_INFO("[%p]: found ActiveRemote for %s at %s:%u", ctx, ctx->active_remote.DACPid,
  599. inet_ntoa(ctx->active_remote.host), ctx->active_remote.port);
  600. *stop = true;
  601. break;
  602. }
  603. }
  604. // let caller clear list
  605. return false;
  606. }
  607. /*----------------------------------------------------------------------------*/
  608. static void* search_remote(void *args) {
  609. raop_ctx_t *ctx = (raop_ctx_t*) args;
  610. query_mDNS(ctx->active_remote.handle, "_dacp._tcp.local", 0, 0, &search_remote_cb, (void*) ctx);
  611. return NULL;
  612. }
  613. #else
  614. /*----------------------------------------------------------------------------*/
  615. static void search_remote(void *args) {
  616. raop_ctx_t *ctx = (raop_ctx_t*) args;
  617. bool found = false;
  618. LOG_INFO("starting remote search");
  619. while (ctx->active_remote.running && !found) {
  620. mdns_result_t *results = NULL;
  621. mdns_result_t *r;
  622. mdns_ip_addr_t *a;
  623. if (mdns_query_ptr("_dacp", "_tcp", 3000, 32, &results)) {
  624. LOG_ERROR("mDNS active remote query Failed");
  625. continue;
  626. }
  627. for (r = results; r && !strcasestr(r->instance_name, ctx->active_remote.DACPid); r = r->next);
  628. if (r) {
  629. for (a = r->addr; a && a->addr.type != IPADDR_TYPE_V4; a = a->next);
  630. if (a) {
  631. found = true;
  632. ctx->active_remote.host.s_addr = a->addr.u_addr.ip4.addr;
  633. ctx->active_remote.port = r->port;
  634. LOG_INFO("found remote %s %s:%hu", r->instance_name, inet_ntoa(ctx->active_remote.host), ctx->active_remote.port);
  635. }
  636. }
  637. mdns_query_results_free(results);
  638. }
  639. // can't use xNotifyGive as it seems LWIP is using it as well
  640. xSemaphoreGive(ctx->active_remote.destroy_mutex);
  641. vTaskSuspend(NULL);
  642. }
  643. #endif
  644. /*----------------------------------------------------------------------------*/
  645. static char *rsa_apply(unsigned char *input, int inlen, int *outlen, int mode)
  646. {
  647. const static char super_secret_key[] =
  648. "-----BEGIN RSA PRIVATE KEY-----\n"
  649. "MIIEpQIBAAKCAQEA59dE8qLieItsH1WgjrcFRKj6eUWqi+bGLOX1HL3U3GhC/j0Qg90u3sG/1CUt\n"
  650. "wC5vOYvfDmFI6oSFXi5ELabWJmT2dKHzBJKa3k9ok+8t9ucRqMd6DZHJ2YCCLlDRKSKv6kDqnw4U\n"
  651. "wPdpOMXziC/AMj3Z/lUVX1G7WSHCAWKf1zNS1eLvqr+boEjXuBOitnZ/bDzPHrTOZz0Dew0uowxf\n"
  652. "/+sG+NCK3eQJVxqcaJ/vEHKIVd2M+5qL71yJQ+87X6oV3eaYvt3zWZYD6z5vYTcrtij2VZ9Zmni/\n"
  653. "UAaHqn9JdsBWLUEpVviYnhimNVvYFZeCXg/IdTQ+x4IRdiXNv5hEewIDAQABAoIBAQDl8Axy9XfW\n"
  654. "BLmkzkEiqoSwF0PsmVrPzH9KsnwLGH+QZlvjWd8SWYGN7u1507HvhF5N3drJoVU3O14nDY4TFQAa\n"
  655. "LlJ9VM35AApXaLyY1ERrN7u9ALKd2LUwYhM7Km539O4yUFYikE2nIPscEsA5ltpxOgUGCY7b7ez5\n"
  656. "NtD6nL1ZKauw7aNXmVAvmJTcuPxWmoktF3gDJKK2wxZuNGcJE0uFQEG4Z3BrWP7yoNuSK3dii2jm\n"
  657. "lpPHr0O/KnPQtzI3eguhe0TwUem/eYSdyzMyVx/YpwkzwtYL3sR5k0o9rKQLtvLzfAqdBxBurciz\n"
  658. "aaA/L0HIgAmOit1GJA2saMxTVPNhAoGBAPfgv1oeZxgxmotiCcMXFEQEWflzhWYTsXrhUIuz5jFu\n"
  659. "a39GLS99ZEErhLdrwj8rDDViRVJ5skOp9zFvlYAHs0xh92ji1E7V/ysnKBfsMrPkk5KSKPrnjndM\n"
  660. "oPdevWnVkgJ5jxFuNgxkOLMuG9i53B4yMvDTCRiIPMQ++N2iLDaRAoGBAO9v//mU8eVkQaoANf0Z\n"
  661. "oMjW8CN4xwWA2cSEIHkd9AfFkftuv8oyLDCG3ZAf0vrhrrtkrfa7ef+AUb69DNggq4mHQAYBp7L+\n"
  662. "k5DKzJrKuO0r+R0YbY9pZD1+/g9dVt91d6LQNepUE/yY2PP5CNoFmjedpLHMOPFdVgqDzDFxU8hL\n"
  663. "AoGBANDrr7xAJbqBjHVwIzQ4To9pb4BNeqDndk5Qe7fT3+/H1njGaC0/rXE0Qb7q5ySgnsCb3DvA\n"
  664. "cJyRM9SJ7OKlGt0FMSdJD5KG0XPIpAVNwgpXXH5MDJg09KHeh0kXo+QA6viFBi21y340NonnEfdf\n"
  665. "54PX4ZGS/Xac1UK+pLkBB+zRAoGAf0AY3H3qKS2lMEI4bzEFoHeK3G895pDaK3TFBVmD7fV0Zhov\n"
  666. "17fegFPMwOII8MisYm9ZfT2Z0s5Ro3s5rkt+nvLAdfC/PYPKzTLalpGSwomSNYJcB9HNMlmhkGzc\n"
  667. "1JnLYT4iyUyx6pcZBmCd8bD0iwY/FzcgNDaUmbX9+XDvRA0CgYEAkE7pIPlE71qvfJQgoA9em0gI\n"
  668. "LAuE4Pu13aKiJnfft7hIjbK+5kyb3TysZvoyDnb3HOKvInK7vXbKuU4ISgxB2bB3HcYzQMGsz1qJ\n"
  669. "2gG0N5hvJpzwwhbhXqFKA4zaaSrw622wDniAK5MlIE0tIAKKP4yxNGjoD2QYjhBGuhvkWKY=\n"
  670. "-----END RSA PRIVATE KEY-----";
  671. #ifdef WIN32
  672. unsigned char *out;
  673. RSA *rsa;
  674. BIO *bmem = BIO_new_mem_buf(super_secret_key, -1);
  675. rsa = PEM_read_bio_RSAPrivateKey(bmem, NULL, NULL, NULL);
  676. BIO_free(bmem);
  677. out = malloc(RSA_size(rsa));
  678. switch (mode) {
  679. case RSA_MODE_AUTH:
  680. *outlen = RSA_private_encrypt(inlen, input, out, rsa,
  681. RSA_PKCS1_PADDING);
  682. break;
  683. case RSA_MODE_KEY:
  684. *outlen = RSA_private_decrypt(inlen, input, out, rsa,
  685. RSA_PKCS1_OAEP_PADDING);
  686. break;
  687. }
  688. RSA_free(rsa);
  689. return (char*) out;
  690. #else
  691. mbedtls_pk_context pkctx;
  692. mbedtls_rsa_context *trsa;
  693. size_t olen;
  694. /*
  695. we should do entropy initialization & pass a rng function but this
  696. consumes a ton of stack and there is no security concern here. Anyway,
  697. mbedtls takes a lot of stack, unfortunately ...
  698. */
  699. mbedtls_pk_init(&pkctx);
  700. mbedtls_pk_parse_key(&pkctx, (unsigned char *)super_secret_key,
  701. sizeof(super_secret_key), NULL, 0);
  702. uint8_t *outbuf = NULL;
  703. trsa = mbedtls_pk_rsa(pkctx);
  704. switch (mode) {
  705. case RSA_MODE_AUTH:
  706. mbedtls_rsa_set_padding(trsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_NONE);
  707. outbuf = malloc(trsa->len);
  708. mbedtls_rsa_pkcs1_encrypt(trsa, NULL, NULL, MBEDTLS_RSA_PRIVATE, inlen, input, outbuf);
  709. *outlen = trsa->len;
  710. break;
  711. case RSA_MODE_KEY:
  712. mbedtls_rsa_set_padding(trsa, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA1);
  713. outbuf = malloc(trsa->len);
  714. mbedtls_rsa_pkcs1_decrypt(trsa, NULL, NULL, MBEDTLS_RSA_PRIVATE, &olen, input, outbuf, trsa->len);
  715. *outlen = olen;
  716. break;
  717. }
  718. mbedtls_pk_free(&pkctx);
  719. return (char*) outbuf;
  720. #endif
  721. }
  722. #define DECODE_ERROR 0xffffffff
  723. const static char base64_chars[] =
  724. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  725. /*----------------------------------------------------------------------------*/
  726. static int base64_pad(char *src, char **padded)
  727. {
  728. int n;
  729. n = strlen(src) + strlen(src) % 4;
  730. *padded = malloc(n + 1);
  731. memset(*padded, '=', n);
  732. memcpy(*padded, src, strlen(src));
  733. (*padded)[n] = '\0';
  734. return strlen(*padded);
  735. }
  736. /*----------------------------------------------------------------------------*/
  737. static int pos(char c)
  738. {
  739. const char *p;
  740. for (p = base64_chars; *p; p++)
  741. if (*p == c)
  742. return p - base64_chars;
  743. return -1;
  744. }
  745. /*----------------------------------------------------------------------------*/
  746. static int base64_encode(const void *data, int size, char **str)
  747. {
  748. char *s, *p;
  749. int i;
  750. int c;
  751. const unsigned char *q;
  752. p = s = (char *) malloc(size * 4 / 3 + 4);
  753. if (p == NULL) return -1;
  754. q = (const unsigned char *) data;
  755. i = 0;
  756. for (i = 0; i < size;) {
  757. c = q[i++];
  758. c *= 256;
  759. if (i < size) c += q[i];
  760. i++;
  761. c *= 256;
  762. if (i < size) c += q[i];
  763. i++;
  764. p[0] = base64_chars[(c & 0x00fc0000) >> 18];
  765. p[1] = base64_chars[(c & 0x0003f000) >> 12];
  766. p[2] = base64_chars[(c & 0x00000fc0) >> 6];
  767. p[3] = base64_chars[(c & 0x0000003f) >> 0];
  768. if (i > size) p[3] = '=';
  769. if (i > size + 1) p[2] = '=';
  770. p += 4;
  771. }
  772. *p = 0;
  773. *str = s;
  774. return strlen(s);
  775. }
  776. /*----------------------------------------------------------------------------*/
  777. static unsigned int token_decode(const char *token)
  778. {
  779. int i;
  780. unsigned int val = 0;
  781. int marker = 0;
  782. if (strlen(token) < 4)
  783. return DECODE_ERROR;
  784. for (i = 0; i < 4; i++) {
  785. val *= 64;
  786. if (token[i] == '=')
  787. marker++;
  788. else if (marker > 0)
  789. return DECODE_ERROR;
  790. else
  791. val += pos(token[i]);
  792. }
  793. if (marker > 2)
  794. return DECODE_ERROR;
  795. return (marker << 24) | val;
  796. }
  797. /*----------------------------------------------------------------------------*/
  798. static int base64_decode(const char *str, void *data)
  799. {
  800. const char *p;
  801. unsigned char *q;
  802. q = data;
  803. for (p = str; *p && (*p == '=' || strchr(base64_chars, *p)); p += 4) {
  804. unsigned int val = token_decode(p);
  805. unsigned int marker = (val >> 24) & 0xff;
  806. if (val == DECODE_ERROR)
  807. return -1;
  808. *q++ = (val >> 16) & 0xff;
  809. if (marker < 2)
  810. *q++ = (val >> 8) & 0xff;
  811. if (marker < 1)
  812. *q++ = val & 0xff;
  813. }
  814. return q - (unsigned char *) data;
  815. }
  816. /*----------------------------------------------------------------------------*/
  817. static void on_dmap_string(void *ctx, const char *code, const char *name, const char *buf, size_t len) {
  818. struct metadata_s *metadata = (struct metadata_s *) ctx;
  819. // to gain space, most of the code have been removed from dmap_parser.c (define DMAP_FULL
  820. if (!strcasecmp(code, "asar")) metadata->artist = strndup(buf, len);
  821. else if (!strcasecmp(code, "asal")) metadata->album = strndup(buf, len);
  822. else if (!strcasecmp(code, "minm")) metadata->title = strndup(buf, len);
  823. }