raop.c 28 KB

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