raop.c 27 KB

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