utils.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. /*
  2. * Squeezelite - lightweight headless squeezebox emulator
  3. *
  4. * (c) Adrian Smith 2012-2015, triode1@btinternet.com
  5. * Ralph Irving 2015-2017, ralph_irving@hotmail.com
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. */
  21. #include "squeezelite.h"
  22. #if LINUX || OSX || FREEBSD || EMBEDDED
  23. #include <sys/ioctl.h>
  24. #include <net/if.h>
  25. #include <netdb.h>
  26. #if FREEBSD
  27. #include <ifaddrs.h>
  28. #include <net/if_dl.h>
  29. #include <net/if_types.h>
  30. #endif
  31. #endif
  32. #if SUN
  33. #include <sys/socket.h>
  34. #include <sys/sockio.h>
  35. #include <arpa/inet.h>
  36. #include <netinet/in.h>
  37. #include <net/if.h>
  38. #include <net/if_arp.h>
  39. #include <net/if_dl.h>
  40. #include <net/if_types.h>
  41. #endif
  42. #if WIN
  43. #include <iphlpapi.h>
  44. #if USE_SSL
  45. #include <stdlib.h>
  46. #include <string.h>
  47. #include <ctype.h>
  48. #endif
  49. #endif
  50. #if OSX
  51. #include <net/if_dl.h>
  52. #include <net/if_types.h>
  53. #include <ifaddrs.h>
  54. #include <netdb.h>
  55. #endif
  56. #include <fcntl.h>
  57. // logging functions
  58. const char *logtime(void) {
  59. static char buf[100];
  60. #if WIN
  61. SYSTEMTIME lt;
  62. GetLocalTime(&lt);
  63. sprintf(buf, "[%02d:%02d:%02d.%03d]", lt.wHour, lt.wMinute, lt.wSecond, lt.wMilliseconds);
  64. #else
  65. struct timeval tv;
  66. gettimeofday(&tv, NULL);
  67. strftime(buf, sizeof(buf), "[%T.", localtime(&tv.tv_sec));
  68. #ifdef EMBEDDED
  69. sprintf(buf+strlen(buf), "%03ld]", (long)tv.tv_usec/1000);
  70. #else
  71. sprintf(buf+strlen(buf), "%06ld]", (long)tv.tv_usec);
  72. #endif
  73. #endif
  74. return buf;
  75. }
  76. void logprint(const char *fmt, ...) {
  77. va_list args;
  78. va_start(args, fmt);
  79. vfprintf(stderr, fmt, args);
  80. va_end(args);
  81. fflush(stderr);
  82. }
  83. // cmdline parsing
  84. char *next_param(char *src, char c) {
  85. static char *str = NULL;
  86. char *ptr, *ret;
  87. if (src) str = src;
  88. if (str && (ptr = strchr(str, c))) {
  89. ret = str;
  90. *ptr = '\0';
  91. str = ptr + 1;
  92. } else {
  93. ret = str;
  94. str = NULL;
  95. }
  96. return ret && ret[0] ? ret : NULL;
  97. }
  98. // clock
  99. #if !defined(gettime_ms)
  100. u32_t gettime_ms(void) {
  101. #if WIN
  102. return GetTickCount();
  103. #else
  104. #if LINUX || FREEBSD || EMBEDDED
  105. struct timespec ts;
  106. #ifdef CLOCK_MONOTONIC
  107. if (!clock_gettime(CLOCK_MONOTONIC, &ts)) {
  108. #else
  109. if (!clock_gettime(CLOCK_REALTIME, &ts)) {
  110. #endif
  111. return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
  112. }
  113. #endif
  114. struct timeval tv;
  115. gettimeofday(&tv, NULL);
  116. return tv.tv_sec * 1000 + tv.tv_usec / 1000;
  117. #endif
  118. }
  119. #endif
  120. // mac address
  121. #if LINUX && !defined(SUN)
  122. // search first 4 interfaces returned by IFCONF
  123. void get_mac(u8_t mac[]) {
  124. char *utmac;
  125. struct ifconf ifc;
  126. struct ifreq *ifr, *ifend;
  127. struct ifreq ifreq;
  128. struct ifreq ifs[4];
  129. utmac = getenv("UTMAC");
  130. if (utmac)
  131. {
  132. if ( strlen(utmac) == 17 )
  133. {
  134. if (sscanf(utmac,"%2hhx:%2hhx:%2hhx:%2hhx:%2hhx:%2hhx",
  135. &mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]) == 6)
  136. {
  137. return;
  138. }
  139. }
  140. }
  141. mac[0] = mac[1] = mac[2] = mac[3] = mac[4] = mac[5] = 0;
  142. int s = socket(AF_INET, SOCK_DGRAM, 0);
  143. ifc.ifc_len = sizeof(ifs);
  144. ifc.ifc_req = ifs;
  145. if (ioctl(s, SIOCGIFCONF, &ifc) == 0) {
  146. ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
  147. for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
  148. if (ifr->ifr_addr.sa_family == AF_INET) {
  149. strncpy(ifreq.ifr_name, ifr->ifr_name, sizeof(ifreq.ifr_name));
  150. if (ioctl (s, SIOCGIFHWADDR, &ifreq) == 0) {
  151. memcpy(mac, ifreq.ifr_hwaddr.sa_data, 6);
  152. if (mac[0]+mac[1]+mac[2] != 0) {
  153. break;
  154. }
  155. }
  156. }
  157. }
  158. }
  159. close(s);
  160. }
  161. #endif
  162. #if SUN
  163. void get_mac(u8_t mac[]) {
  164. struct arpreq parpreq;
  165. struct sockaddr_in *psa;
  166. struct in_addr inaddr;
  167. struct hostent *phost;
  168. char hostname[MAXHOSTNAMELEN];
  169. char **paddrs;
  170. char *utmac;
  171. int sock;
  172. int status=0;
  173. utmac = getenv("UTMAC");
  174. if (utmac)
  175. {
  176. if ( strlen(utmac) == 17 )
  177. {
  178. if (sscanf(utmac,"%2hhx:%2hhx:%2hhx:%2hhx:%2hhx:%2hhx",
  179. &mac[0],&mac[1],&mac[2],&mac[3],&mac[4],&mac[5]) == 6)
  180. {
  181. return;
  182. }
  183. }
  184. }
  185. mac[0] = mac[1] = mac[2] = mac[3] = mac[4] = mac[5] = 0;
  186. gethostname(hostname, MAXHOSTNAMELEN);
  187. phost = gethostbyname(hostname);
  188. paddrs = phost->h_addr_list;
  189. memcpy(&inaddr.s_addr, *paddrs, sizeof(inaddr.s_addr));
  190. sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  191. if(sock == -1)
  192. {
  193. mac[5] = 1;
  194. return;
  195. }
  196. memset(&parpreq, 0, sizeof(struct arpreq));
  197. psa = (struct sockaddr_in *) &parpreq.arp_pa;
  198. memset(psa, 0, sizeof(struct sockaddr_in));
  199. psa->sin_family = AF_INET;
  200. memcpy(&psa->sin_addr, *paddrs, sizeof(struct in_addr));
  201. status = ioctl(sock, SIOCGARP, &parpreq);
  202. if(status == -1)
  203. {
  204. mac[5] = 2;
  205. return;
  206. }
  207. mac[0] = (unsigned char) parpreq.arp_ha.sa_data[0];
  208. mac[1] = (unsigned char) parpreq.arp_ha.sa_data[1];
  209. mac[2] = (unsigned char) parpreq.arp_ha.sa_data[2];
  210. mac[3] = (unsigned char) parpreq.arp_ha.sa_data[3];
  211. mac[4] = (unsigned char) parpreq.arp_ha.sa_data[4];
  212. mac[5] = (unsigned char) parpreq.arp_ha.sa_data[5];
  213. }
  214. #endif
  215. #if OSX || FREEBSD
  216. void get_mac(u8_t mac[]) {
  217. struct ifaddrs *addrs, *ptr;
  218. const struct sockaddr_dl *dlAddr;
  219. const unsigned char *base;
  220. mac[0] = mac[1] = mac[2] = mac[3] = mac[4] = mac[5] = 0;
  221. if (getifaddrs(&addrs) == 0) {
  222. ptr = addrs;
  223. while (ptr) {
  224. if (ptr->ifa_addr->sa_family == AF_LINK && ((const struct sockaddr_dl *) ptr->ifa_addr)->sdl_type == IFT_ETHER) {
  225. dlAddr = (const struct sockaddr_dl *)ptr->ifa_addr;
  226. base = (const unsigned char*) &dlAddr->sdl_data[dlAddr->sdl_nlen];
  227. memcpy(mac, base, min(dlAddr->sdl_alen, 6));
  228. break;
  229. }
  230. ptr = ptr->ifa_next;
  231. }
  232. freeifaddrs(addrs);
  233. }
  234. }
  235. #endif
  236. #if WIN
  237. #pragma comment(lib, "IPHLPAPI.lib")
  238. void get_mac(u8_t mac[]) {
  239. IP_ADAPTER_INFO AdapterInfo[16];
  240. DWORD dwBufLen = sizeof(AdapterInfo);
  241. DWORD dwStatus = GetAdaptersInfo(AdapterInfo, &dwBufLen);
  242. mac[0] = mac[1] = mac[2] = mac[3] = mac[4] = mac[5] = 0;
  243. if (GetAdaptersInfo(AdapterInfo, &dwBufLen) == ERROR_SUCCESS) {
  244. memcpy(mac, AdapterInfo[0].Address, 6);
  245. }
  246. }
  247. #endif
  248. void set_nonblock(sockfd s) {
  249. #if WIN
  250. u_long iMode = 1;
  251. ioctlsocket(s, FIONBIO, &iMode);
  252. #else
  253. int flags = fcntl(s, F_GETFL,0);
  254. fcntl(s, F_SETFL, flags | O_NONBLOCK);
  255. #endif
  256. }
  257. // connect for socket already set to non blocking with timeout in seconds
  258. int connect_timeout(sockfd sock, const struct sockaddr *addr, socklen_t addrlen, int timeout) {
  259. fd_set w, e;
  260. struct timeval tval;
  261. if (connect(sock, addr, addrlen) < 0) {
  262. #if !WIN
  263. if (last_error() != EINPROGRESS) {
  264. #else
  265. if (last_error() != WSAEWOULDBLOCK) {
  266. #endif
  267. return -1;
  268. }
  269. }
  270. FD_ZERO(&w);
  271. FD_SET(sock, &w);
  272. e = w;
  273. tval.tv_sec = timeout;
  274. tval.tv_usec = 0;
  275. // only return 0 if w set and sock error is zero, otherwise return error code
  276. if (select(sock + 1, NULL, &w, &e, timeout ? &tval : NULL) == 1 && FD_ISSET(sock, &w)) {
  277. int error = 0;
  278. socklen_t len = sizeof(error);
  279. getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *)&error, &len);
  280. return error;
  281. }
  282. return -1;
  283. }
  284. void server_addr(char *server, in_addr_t *ip_ptr, unsigned *port_ptr) {
  285. struct addrinfo *res = NULL;
  286. struct addrinfo hints;
  287. const char *port = NULL;
  288. if (strtok(server, ":")) {
  289. port = strtok(NULL, ":");
  290. if (port) {
  291. *port_ptr = atoi(port);
  292. }
  293. }
  294. memset(&hints, 0, sizeof(struct addrinfo));
  295. hints.ai_family = AF_INET;
  296. getaddrinfo(server, NULL, &hints, &res);
  297. if (res && res->ai_addr) {
  298. *ip_ptr = ((struct sockaddr_in*)res->ai_addr)->sin_addr.s_addr;
  299. }
  300. if (res) {
  301. freeaddrinfo(res);
  302. }
  303. }
  304. void set_readwake_handles(event_handle handles[], sockfd s, event_event e) {
  305. #if WINEVENT
  306. handles[0] = WSACreateEvent();
  307. handles[1] = e;
  308. WSAEventSelect(s, handles[0], FD_READ | FD_CLOSE);
  309. #elif SELFPIPE || LOOPBACK
  310. handles[0].fd = s;
  311. handles[1].fd = e.fds[0];
  312. handles[0].events = POLLIN;
  313. handles[1].events = POLLIN;
  314. #else
  315. handles[0].fd = s;
  316. handles[1].fd = e;
  317. handles[0].events = POLLIN;
  318. handles[1].events = POLLIN;
  319. #endif
  320. }
  321. event_type wait_readwake(event_handle handles[], int timeout) {
  322. #if WINEVENT
  323. int wait = WSAWaitForMultipleEvents(2, handles, FALSE, timeout, FALSE);
  324. if (wait == WSA_WAIT_EVENT_0) {
  325. WSAResetEvent(handles[0]);
  326. return EVENT_READ;
  327. } else if (wait == WSA_WAIT_EVENT_0 + 1) {
  328. return EVENT_WAKE;
  329. } else {
  330. return EVENT_TIMEOUT;
  331. }
  332. #else
  333. if (poll(handles, 2, timeout) > 0) {
  334. if (handles[0].revents) {
  335. return EVENT_READ;
  336. }
  337. if (handles[1].revents) {
  338. wake_clear(handles[1].fd);
  339. return EVENT_WAKE;
  340. }
  341. }
  342. return EVENT_TIMEOUT;
  343. #endif
  344. }
  345. #if LOOPBACK
  346. void _wake_create(event_event* e) {
  347. struct sockaddr_in addr;
  348. short port;
  349. socklen_t len;
  350. e->mfds = e->fds[0] = e->fds[1] = -1;
  351. addr.sin_family = AF_INET;
  352. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  353. // create sending socket - will wait for connections
  354. addr.sin_port = 0;
  355. e->mfds = socket(AF_INET, SOCK_STREAM, 0);
  356. bind(e->mfds, (struct sockaddr*) &addr, sizeof(addr));
  357. len = sizeof(struct sockaddr);
  358. // get assigned port & listen
  359. getsockname(e->mfds, (struct sockaddr *) &addr, &len);
  360. port = addr.sin_port;
  361. listen(e->mfds, 1);
  362. // create receiving socket
  363. addr.sin_port = 0;
  364. e->fds[0] = socket(AF_INET, SOCK_STREAM, 0);
  365. bind(e->fds[0], (struct sockaddr*) &addr, sizeof(addr));
  366. // connect to sender (we listen so it can be blocking)
  367. addr.sin_port = port;
  368. connect(e->fds[0], (struct sockaddr*) &addr, sizeof(addr));
  369. // this one will work or fail, but not block
  370. len = sizeof(struct sockaddr);
  371. e->fds[1] = accept(e->mfds, (struct sockaddr*) &addr, &len);
  372. }
  373. #endif
  374. // pack/unpack to network byte order
  375. void packN(u32_t *dest, u32_t val) {
  376. u8_t *ptr = (u8_t *)dest;
  377. *(ptr) = (val >> 24) & 0xFF; *(ptr+1) = (val >> 16) & 0xFF; *(ptr+2) = (val >> 8) & 0xFF; *(ptr+3) = val & 0xFF;
  378. }
  379. void packn(u16_t *dest, u16_t val) {
  380. u8_t *ptr = (u8_t *)dest;
  381. *(ptr) = (val >> 8) & 0xFF; *(ptr+1) = val & 0xFF;
  382. }
  383. u32_t unpackN(u32_t *src) {
  384. u8_t *ptr = (u8_t *)src;
  385. return *(ptr) << 24 | *(ptr+1) << 16 | *(ptr+2) << 8 | *(ptr+3);
  386. }
  387. u16_t unpackn(u16_t *src) {
  388. u8_t *ptr = (u8_t *)src;
  389. return *(ptr) << 8 | *(ptr+1);
  390. }
  391. #if OSX
  392. void set_nosigpipe(sockfd s) {
  393. int set = 1;
  394. setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int));
  395. }
  396. #endif
  397. #if WIN
  398. void winsock_init(void) {
  399. WSADATA wsaData;
  400. WORD wVersionRequested = MAKEWORD(2, 2);
  401. int WSerr = WSAStartup(wVersionRequested, &wsaData);
  402. if (WSerr != 0) {
  403. LOG_ERROR("Bad winsock version");
  404. exit(1);
  405. }
  406. }
  407. void winsock_close(void) {
  408. WSACleanup();
  409. }
  410. void *dlopen(const char *filename, int flag) {
  411. SetLastError(0);
  412. return LoadLibrary((LPCTSTR)filename);
  413. }
  414. void *dlsym(void *handle, const char *symbol) {
  415. SetLastError(0);
  416. return (void *)GetProcAddress(handle, symbol);
  417. }
  418. char *dlerror(void) {
  419. static char ret[32];
  420. int last = GetLastError();
  421. if (last) {
  422. sprintf(ret, "code: %i", last);
  423. SetLastError(0);
  424. return ret;
  425. }
  426. return NULL;
  427. }
  428. int poll(struct pollfd *fds, unsigned long numfds, int timeout) {
  429. fd_set r, w;
  430. struct timeval tv;
  431. int ret, i, max_fds = fds[0].fd;
  432. FD_ZERO(&r);
  433. FD_ZERO(&w);
  434. for (i = 0; i < numfds; i++) {
  435. if (fds[i].events & POLLIN) FD_SET(fds[i].fd, &r);
  436. if (fds[i].events & POLLOUT) FD_SET(fds[i].fd, &w);
  437. if (max_fds < fds[i].fd) max_fds = fds[i].fd;
  438. }
  439. tv.tv_sec = timeout / 1000;
  440. tv.tv_usec = 1000 * (timeout % 1000);
  441. ret = select(max_fds + 1, &r, &w, NULL, &tv);
  442. if (ret < 0) return ret;
  443. for (i = 0; i < numfds; i++) {
  444. fds[i].revents = 0;
  445. if (FD_ISSET(fds[i].fd, &r)) fds[i].revents |= POLLIN;
  446. if (FD_ISSET(fds[i].fd, &w)) fds[i].revents |= POLLOUT;
  447. }
  448. return ret;
  449. }
  450. #endif
  451. #if LINUX || FREEBSD
  452. void touch_memory(u8_t *buf, size_t size) {
  453. u8_t *ptr;
  454. for (ptr = buf; ptr < buf + size; ptr += sysconf(_SC_PAGESIZE)) {
  455. *ptr = 0;
  456. }
  457. }
  458. #endif
  459. #if WIN && USE_SSL
  460. char *strcasestr(const char *haystack, const char *needle) {
  461. size_t length_needle;
  462. size_t length_haystack;
  463. size_t i;
  464. if (!haystack || !needle)
  465. return NULL;
  466. length_needle = strlen(needle);
  467. length_haystack = strlen(haystack) - length_needle + 1;
  468. for (i = 0; i < length_haystack; i++)
  469. {
  470. size_t j;
  471. for (j = 0; j < length_needle; j++)
  472. {
  473. unsigned char c1;
  474. unsigned char c2;
  475. c1 = haystack[i+j];
  476. c2 = needle[j];
  477. if (toupper(c1) != toupper(c2))
  478. goto next;
  479. }
  480. return (char *) haystack + i;
  481. next:
  482. ;
  483. }
  484. return NULL;
  485. }
  486. #endif