util.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /*
  2. * AirConnect: Chromecast & UPnP to AirPlay
  3. *
  4. * (c) Philippe 2016-2017, philippe_44@outlook.com
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. #include "platform.h"
  21. #ifdef WIN32
  22. #include <iphlpapi.h>
  23. #else
  24. #include "tcpip_adapter.h"
  25. #include <ctype.h>
  26. #endif
  27. #include <stdarg.h>
  28. #include "pthread.h"
  29. #include "util.h"
  30. #include "log_util.h"
  31. /*----------------------------------------------------------------------------*/
  32. /* globals */
  33. /*----------------------------------------------------------------------------*/
  34. extern log_level util_loglevel;
  35. /*----------------------------------------------------------------------------*/
  36. /* locals */
  37. /*----------------------------------------------------------------------------*/
  38. static log_level *loglevel = &util_loglevel;
  39. static char *ltrim(char *s);
  40. static int read_line(int fd, char *line, int maxlen, int timeout);
  41. /*----------------------------------------------------------------------------*/
  42. /* */
  43. /* NETWORKING utils */
  44. /* */
  45. /*----------------------------------------------------------------------------*/
  46. /*---------------------------------------------------------------------------*/
  47. #define MAX_INTERFACES 256
  48. #define DEFAULT_INTERFACE 1
  49. #if !defined(WIN32)
  50. #define INVALID_SOCKET (-1)
  51. #endif
  52. in_addr_t get_localhost(char **name)
  53. {
  54. #ifdef WIN32
  55. char buf[256];
  56. struct hostent *h = NULL;
  57. struct sockaddr_in LocalAddr;
  58. memset(&LocalAddr, 0, sizeof(LocalAddr));
  59. gethostname(buf, 256);
  60. h = gethostbyname(buf);
  61. if (name) *name = strdup(buf);
  62. if (h != NULL) {
  63. memcpy(&LocalAddr.sin_addr, h->h_addr_list[0], 4);
  64. return LocalAddr.sin_addr.s_addr;
  65. }
  66. else return INADDR_ANY;
  67. #else
  68. tcpip_adapter_ip_info_t ipInfo;
  69. tcpip_adapter_if_t if_type = TCPIP_ADAPTER_IF_STA;
  70. // then get IP address
  71. tcpip_adapter_get_ip_info(if_type, &ipInfo);
  72. // we might be in AP mode
  73. if (ipInfo.ip.addr == INADDR_ANY) {
  74. if_type = TCPIP_ADAPTER_IF_AP;
  75. tcpip_adapter_get_ip_info(TCPIP_ADAPTER_IF_AP, &ipInfo);
  76. }
  77. // get hostname if required
  78. if (name) {
  79. const char *hostname;
  80. tcpip_adapter_get_hostname(if_type, &hostname);
  81. *name = strdup(hostname);
  82. }
  83. return ipInfo.ip.addr;
  84. #endif
  85. }
  86. /*----------------------------------------------------------------------------*/
  87. #ifdef WIN32
  88. void winsock_init(void) {
  89. WSADATA wsaData;
  90. WORD wVersionRequested = MAKEWORD(2, 2);
  91. int WSerr = WSAStartup(wVersionRequested, &wsaData);
  92. if (WSerr != 0) {
  93. LOG_ERROR("Bad winsock version", NULL);
  94. exit(1);
  95. }
  96. }
  97. /*----------------------------------------------------------------------------*/
  98. void winsock_close(void) {
  99. WSACleanup();
  100. }
  101. #endif
  102. /*----------------------------------------------------------------------------*/
  103. int shutdown_socket(int sd)
  104. {
  105. if (sd <= 0) return -1;
  106. #ifdef WIN32
  107. shutdown(sd, SD_BOTH);
  108. #else
  109. shutdown(sd, SHUT_RDWR);
  110. #endif
  111. LOG_DEBUG("closed socket %d", sd);
  112. return closesocket(sd);
  113. }
  114. /*----------------------------------------------------------------------------*/
  115. int bind_socket(unsigned short *port, int mode)
  116. {
  117. int sock;
  118. socklen_t len = sizeof(struct sockaddr);
  119. struct sockaddr_in addr;
  120. if ((sock = socket(AF_INET, mode, 0)) < 0) {
  121. LOG_ERROR("cannot create socket %d", sock);
  122. return sock;
  123. }
  124. /* Populate socket address structure */
  125. memset(&addr, 0, sizeof(addr));
  126. addr.sin_family = AF_INET;
  127. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  128. addr.sin_port = htons(*port);
  129. #ifdef SIN_LEN
  130. si.sin_len = sizeof(si);
  131. #endif
  132. if (bind(sock, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
  133. closesocket(sock);
  134. LOG_ERROR("cannot bind socket %d", sock);
  135. return -1;
  136. }
  137. if (!*port) {
  138. getsockname(sock, (struct sockaddr *) &addr, &len);
  139. *port = ntohs(addr.sin_port);
  140. }
  141. LOG_DEBUG("socket binding %d on port %d", sock, *port);
  142. return sock;
  143. }
  144. /*----------------------------------------------------------------------------*/
  145. int conn_socket(unsigned short port)
  146. {
  147. struct sockaddr_in addr;
  148. int sd;
  149. sd = socket(AF_INET, SOCK_STREAM, 0);
  150. addr.sin_family = AF_INET;
  151. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  152. addr.sin_port = htons(port);
  153. if (sd < 0 || connect(sd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
  154. close(sd);
  155. return -1;
  156. }
  157. LOG_DEBUG("created socket %d", sd);
  158. return sd;
  159. }
  160. /*----------------------------------------------------------------------------*/
  161. /* */
  162. /* SYSTEM utils */
  163. /* */
  164. /*----------------------------------------------------------------------------*/
  165. #ifdef WIN32
  166. /*----------------------------------------------------------------------------*/
  167. void *dlopen(const char *filename, int flag) {
  168. SetLastError(0);
  169. return LoadLibrary((LPCTSTR)filename);
  170. }
  171. /*----------------------------------------------------------------------------*/
  172. void *dlsym(void *handle, const char *symbol) {
  173. SetLastError(0);
  174. return (void *)GetProcAddress(handle, symbol);
  175. }
  176. /*----------------------------------------------------------------------------*/
  177. char *dlerror(void) {
  178. static char ret[32];
  179. int last = GetLastError();
  180. if (last) {
  181. sprintf(ret, "code: %i", last);
  182. SetLastError(0);
  183. return ret;
  184. }
  185. return NULL;
  186. }
  187. #endif
  188. /*----------------------------------------------------------------------------*/
  189. /* */
  190. /* STDLIB extensions */
  191. /* */
  192. /*----------------------------------------------------------------------------*/
  193. #ifdef WIN32
  194. /*---------------------------------------------------------------------------*/
  195. char *strcasestr(const char *haystack, const char *needle) {
  196. size_t length_needle;
  197. size_t length_haystack;
  198. size_t i;
  199. if (!haystack || !needle)
  200. return NULL;
  201. length_needle = strlen(needle);
  202. length_haystack = strlen(haystack);
  203. if (length_haystack < length_needle) return NULL;
  204. length_haystack -= length_needle - 1;
  205. for (i = 0; i < length_haystack; i++)
  206. {
  207. size_t j;
  208. for (j = 0; j < length_needle; j++)
  209. {
  210. unsigned char c1;
  211. unsigned char c2;
  212. c1 = haystack[i+j];
  213. c2 = needle[j];
  214. if (toupper(c1) != toupper(c2))
  215. goto next;
  216. }
  217. return (char *) haystack + i;
  218. next:
  219. ;
  220. }
  221. return NULL;
  222. }
  223. /*---------------------------------------------------------------------------*/
  224. char* strsep(char** stringp, const char* delim)
  225. {
  226. char* start = *stringp;
  227. char* p;
  228. p = (start != NULL) ? strpbrk(start, delim) : NULL;
  229. if (p == NULL) {
  230. *stringp = NULL;
  231. } else {
  232. *p = '\0';
  233. *stringp = p + 1;
  234. }
  235. return start;
  236. }
  237. /*---------------------------------------------------------------------------*/
  238. char *strndup(const char *s, size_t n) {
  239. char *p = malloc(n + 1);
  240. strncpy(p, s, n);
  241. p[n] = '\0';
  242. return p;
  243. }
  244. #endif
  245. /*----------------------------------------------------------------------------*/
  246. char* strextract(char *s1, char *beg, char *end)
  247. {
  248. char *p1, *p2, *res;
  249. p1 = strcasestr(s1, beg);
  250. if (!p1) return NULL;
  251. p1 += strlen(beg);
  252. p2 = strcasestr(p1, end);
  253. if (!p2) return strdup(p1);
  254. res = malloc(p2 - p1 + 1);
  255. memcpy(res, p1, p2 - p1);
  256. res[p2 - p1] = '\0';
  257. return res;
  258. }
  259. #ifdef WIN32
  260. /*----------------------------------------------------------------------------*/
  261. int asprintf(char **strp, const char *fmt, ...)
  262. {
  263. va_list args, cp;
  264. int len, ret = 0;
  265. va_start(args, fmt);
  266. len = vsnprintf(NULL, 0, fmt, args);
  267. *strp = malloc(len + 1);
  268. if (*strp) ret = vsprintf(*strp, fmt, args);
  269. va_end(args);
  270. return ret;
  271. }
  272. #endif
  273. /*---------------------------------------------------------------------------*/
  274. static char *ltrim(char *s)
  275. {
  276. while(isspace((int) *s)) s++;
  277. return s;
  278. }
  279. /*----------------------------------------------------------------------------*/
  280. /* */
  281. /* HTTP management */
  282. /* */
  283. /*----------------------------------------------------------------------------*/
  284. /*----------------------------------------------------------------------------*/
  285. bool http_parse(int sock, char *method, key_data_t *rkd, char **body, int *len)
  286. {
  287. char line[256], *dp;
  288. unsigned j;
  289. int i, timeout = 100;
  290. rkd[0].key = NULL;
  291. if ((i = read_line(sock, line, sizeof(line), timeout)) <= 0) {
  292. if (i < 0) {
  293. LOG_ERROR("cannot read method", NULL);
  294. }
  295. return false;
  296. }
  297. if (!sscanf(line, "%s", method)) {
  298. LOG_ERROR("missing method", NULL);
  299. return false;
  300. }
  301. i = *len = 0;
  302. while (read_line(sock, line, sizeof(line), timeout) > 0) {
  303. LOG_SDEBUG("sock: %u, received %s", line);
  304. // line folding should be deprecated
  305. if (i && rkd[i].key && (line[0] == ' ' || line[0] == '\t')) {
  306. for(j = 0; j < strlen(line); j++) if (line[j] != ' ' && line[j] != '\t') break;
  307. rkd[i].data = realloc(rkd[i].data, strlen(rkd[i].data) + strlen(line + j) + 1);
  308. strcat(rkd[i].data, line + j);
  309. continue;
  310. }
  311. dp = strstr(line,":");
  312. if (!dp){
  313. LOG_ERROR("Request failed, bad header", NULL);
  314. kd_free(rkd);
  315. return false;
  316. }
  317. *dp = 0;
  318. rkd[i].key = strdup(line);
  319. rkd[i].data = strdup(ltrim(dp + 1));
  320. if (!strcasecmp(rkd[i].key, "Content-Length")) *len = atol(rkd[i].data);
  321. i++;
  322. rkd[i].key = NULL;
  323. }
  324. if (*len) {
  325. int size = 0;
  326. *body = malloc(*len + 1);
  327. while (*body && size < *len) {
  328. int bytes = recv(sock, *body + size, *len - size, 0);
  329. if (bytes <= 0) break;
  330. size += bytes;
  331. }
  332. (*body)[*len] = '\0';
  333. if (!*body || size != *len) {
  334. LOG_ERROR("content length receive error %d %d", *len, size);
  335. }
  336. }
  337. return true;
  338. }
  339. /*----------------------------------------------------------------------------*/
  340. static int read_line(int fd, char *line, int maxlen, int timeout)
  341. {
  342. int i,rval;
  343. int count=0;
  344. struct pollfd pfds;
  345. char ch;
  346. *line = 0;
  347. pfds.fd = fd;
  348. pfds.events = POLLIN;
  349. for(i = 0; i < maxlen; i++){
  350. if (poll(&pfds, 1, timeout)) rval=recv(fd, &ch, 1, 0);
  351. else return 0;
  352. if (rval == -1) {
  353. if (errno == EAGAIN) return 0;
  354. LOG_ERROR("fd: %d read error: %s", fd, strerror(errno));
  355. return -1;
  356. }
  357. if (rval == 0) {
  358. LOG_INFO("disconnected on the other end %u", fd);
  359. return 0;
  360. }
  361. if (ch == '\n') {
  362. *line=0;
  363. return count;
  364. }
  365. if (ch=='\r') continue;
  366. *line++=ch;
  367. count++;
  368. if (count >= maxlen-1) break;
  369. }
  370. *line = 0;
  371. return count;
  372. }
  373. /*----------------------------------------------------------------------------*/
  374. char *http_send(int sock, char *method, key_data_t *rkd)
  375. {
  376. unsigned sent, len;
  377. char *resp = kd_dump(rkd);
  378. char *data = malloc(strlen(method) + 2 + strlen(resp) + 2 + 1);
  379. len = sprintf(data, "%s\r\n%s\r\n", method, resp);
  380. NFREE(resp);
  381. sent = send(sock, data, len, 0);
  382. if (sent != len) {
  383. LOG_ERROR("HTTP send() error:%s %u (strlen=%u)", data, sent, len);
  384. NFREE(data);
  385. }
  386. return data;
  387. }
  388. /*----------------------------------------------------------------------------*/
  389. char *kd_lookup(key_data_t *kd, char *key)
  390. {
  391. int i = 0;
  392. while (kd && kd[i].key){
  393. if (!strcasecmp(kd[i].key, key)) return kd[i].data;
  394. i++;
  395. }
  396. return NULL;
  397. }
  398. /*----------------------------------------------------------------------------*/
  399. bool kd_add(key_data_t *kd, char *key, char *data)
  400. {
  401. int i = 0;
  402. while (kd && kd[i].key) i++;
  403. kd[i].key = strdup(key);
  404. kd[i].data = strdup(data);
  405. kd[i+1].key = NULL;
  406. return NULL;
  407. }
  408. /*----------------------------------------------------------------------------*/
  409. void kd_free(key_data_t *kd)
  410. {
  411. int i = 0;
  412. while (kd && kd[i].key){
  413. free(kd[i].key);
  414. if (kd[i].data) free(kd[i].data);
  415. i++;
  416. }
  417. kd[0].key = NULL;
  418. }
  419. /*----------------------------------------------------------------------------*/
  420. char *kd_dump(key_data_t *kd)
  421. {
  422. int i = 0;
  423. int pos = 0, size = 0;
  424. char *str = NULL;
  425. if (!kd || !kd[0].key) return strdup("\r\n");
  426. while (kd && kd[i].key) {
  427. char *buf;
  428. int len;
  429. len = asprintf(&buf, "%s: %s\r\n", kd[i].key, kd[i].data);
  430. while (pos + len >= size) {
  431. void *p = realloc(str, size + 1024);
  432. size += 1024;
  433. if (!p) {
  434. free(str);
  435. return NULL;
  436. }
  437. str = p;
  438. }
  439. memcpy(str + pos, buf, len);
  440. pos += len;
  441. free(buf);
  442. i++;
  443. }
  444. str[pos] = '\0';
  445. return str;
  446. }
  447. /*--------------------------------------------------------------------------*/
  448. void free_metadata(struct metadata_s *metadata)
  449. {
  450. NFREE(metadata->artist);
  451. NFREE(metadata->album);
  452. NFREE(metadata->title);
  453. NFREE(metadata->genre);
  454. NFREE(metadata->path);
  455. NFREE(metadata->artwork);
  456. NFREE(metadata->remote_title);
  457. }
  458. /*----------------------------------------------------------------------------*/
  459. int _fprintf(FILE *file, ...)
  460. {
  461. va_list args;
  462. char *fmt;
  463. int n;
  464. va_start(args, file);
  465. fmt = va_arg(args, char*);
  466. n = vfprintf(file, fmt, args);
  467. va_end(args);
  468. return n;
  469. }