raop.c 27 KB

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