utils.c 12 KB

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