util.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #define _GNU_SOURCE
  11. #include "config.h"
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <ctype.h>
  15. #include <stdarg.h>
  16. #include <string.h>
  17. #include <jansson.h>
  18. #include <curl/curl.h>
  19. #include <time.h>
  20. #include <curses.h>
  21. #include <errno.h>
  22. #include <unistd.h>
  23. #include <sys/types.h>
  24. #ifndef WIN32
  25. # include <sys/socket.h>
  26. # include <netinet/in.h>
  27. # include <netinet/tcp.h>
  28. #else
  29. # include <winsock2.h>
  30. # include <mstcpip.h>
  31. #endif
  32. #include "miner.h"
  33. #include "elist.h"
  34. #if JANSSON_MAJOR_VERSION >= 2
  35. #define JSON_LOADS(str, err_ptr) json_loads((str), 0, (err_ptr))
  36. #else
  37. #define JSON_LOADS(str, err_ptr) json_loads((str), (err_ptr))
  38. #endif
  39. bool successful_connect = false;
  40. struct timeval nettime;
  41. struct data_buffer {
  42. void *buf;
  43. size_t len;
  44. };
  45. struct upload_buffer {
  46. const void *buf;
  47. size_t len;
  48. };
  49. struct header_info {
  50. char *lp_path;
  51. bool has_rolltime;
  52. char *reason;
  53. };
  54. struct tq_ent {
  55. void *data;
  56. struct list_head q_node;
  57. };
  58. void vapplog(int prio, const char *fmt, va_list ap)
  59. {
  60. extern bool use_curses;
  61. if (!opt_debug && prio == LOG_DEBUG)
  62. return;
  63. #ifdef HAVE_SYSLOG_H
  64. if (use_syslog) {
  65. vsyslog(prio, fmt, ap);
  66. }
  67. #else
  68. if (0) {}
  69. #endif
  70. else if (opt_log_output || prio <= LOG_NOTICE) {
  71. char *f;
  72. int len;
  73. struct timeval tv = { };
  74. struct tm *tm;
  75. gettimeofday(&tv, NULL);
  76. tm = localtime(&tv.tv_sec);
  77. len = 40 + strlen(fmt) + 22;
  78. f = alloca(len);
  79. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d] %s\n",
  80. tm->tm_year + 1900,
  81. tm->tm_mon + 1,
  82. tm->tm_mday,
  83. tm->tm_hour,
  84. tm->tm_min,
  85. tm->tm_sec,
  86. fmt);
  87. /* Only output to stderr if it's not going to the screen as well */
  88. if (!isatty(fileno((FILE *)stderr))) {
  89. va_list apc;
  90. va_copy(apc, ap);
  91. vfprintf(stderr, f, apc); /* atomic write to stderr */
  92. fflush(stderr);
  93. }
  94. if (use_curses)
  95. log_curses(prio, f, ap);
  96. else {
  97. int len = strlen(f);
  98. strcpy(f + len - 1, " \n");
  99. log_curses(prio, f, ap);
  100. }
  101. }
  102. }
  103. void applog(int prio, const char *fmt, ...)
  104. {
  105. va_list ap;
  106. va_start(ap, fmt);
  107. vapplog(prio, fmt, ap);
  108. va_end(ap);
  109. }
  110. static void databuf_free(struct data_buffer *db)
  111. {
  112. if (!db)
  113. return;
  114. free(db->buf);
  115. memset(db, 0, sizeof(*db));
  116. }
  117. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  118. void *user_data)
  119. {
  120. struct data_buffer *db = user_data;
  121. size_t len = size * nmemb;
  122. size_t oldlen, newlen;
  123. void *newmem;
  124. static const unsigned char zero = 0;
  125. oldlen = db->len;
  126. newlen = oldlen + len;
  127. newmem = realloc(db->buf, newlen + 1);
  128. if (!newmem)
  129. return 0;
  130. db->buf = newmem;
  131. db->len = newlen;
  132. memcpy(db->buf + oldlen, ptr, len);
  133. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  134. return len;
  135. }
  136. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  137. void *user_data)
  138. {
  139. struct upload_buffer *ub = user_data;
  140. int len = size * nmemb;
  141. if (len > ub->len)
  142. len = ub->len;
  143. if (len) {
  144. memcpy(ptr, ub->buf, len);
  145. ub->buf += len;
  146. ub->len -= len;
  147. }
  148. return len;
  149. }
  150. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  151. {
  152. struct header_info *hi = user_data;
  153. size_t remlen, slen, ptrlen = size * nmemb;
  154. char *rem, *val = NULL, *key = NULL;
  155. void *tmp;
  156. val = calloc(1, ptrlen);
  157. key = calloc(1, ptrlen);
  158. if (!key || !val)
  159. goto out;
  160. tmp = memchr(ptr, ':', ptrlen);
  161. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  162. goto out;
  163. slen = tmp - ptr;
  164. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  165. goto out;
  166. memcpy(key, ptr, slen); /* store & nul term key */
  167. key[slen] = 0;
  168. rem = ptr + slen + 1; /* trim value's leading whitespace */
  169. remlen = ptrlen - slen - 1;
  170. while ((remlen > 0) && (isspace(*rem))) {
  171. remlen--;
  172. rem++;
  173. }
  174. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  175. val[remlen] = 0;
  176. while ((*val) && (isspace(val[strlen(val) - 1]))) {
  177. val[strlen(val) - 1] = 0;
  178. }
  179. if (!*val) /* skip blank value */
  180. goto out;
  181. if (opt_protocol)
  182. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  183. if (!strcasecmp("X-Roll-Ntime", key)) {
  184. if (!strncasecmp("N", val, 1)) {
  185. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  186. } else {
  187. applog(LOG_DEBUG, "X-Roll-Ntime found");
  188. hi->has_rolltime = true;
  189. }
  190. }
  191. if (!strcasecmp("X-Long-Polling", key)) {
  192. hi->lp_path = val; /* steal memory reference */
  193. val = NULL;
  194. }
  195. if (!strcasecmp("X-Reject-Reason", key)) {
  196. hi->reason = val; /* steal memory reference */
  197. val = NULL;
  198. }
  199. out:
  200. free(key);
  201. free(val);
  202. return ptrlen;
  203. }
  204. #ifdef CURL_HAS_SOCKOPT
  205. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  206. curlsocktype __maybe_unused purpose)
  207. {
  208. int keepalive = 1;
  209. int tcp_keepcnt = 5;
  210. int tcp_keepidle = 120;
  211. int tcp_keepintvl = 120;
  212. #ifndef WIN32
  213. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  214. return 1;
  215. # ifdef __linux
  216. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  217. return 1;
  218. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  219. return 1;
  220. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  221. return 1;
  222. # endif /* __linux */
  223. # ifdef __APPLE_CC__
  224. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  225. return 1;
  226. # endif /* __APPLE_CC__ */
  227. #else /* WIN32 */
  228. struct tcp_keepalive vals;
  229. vals.onoff = 1;
  230. vals.keepalivetime = tcp_keepidle * 1000;
  231. vals.keepaliveinterval = tcp_keepintvl * 1000;
  232. DWORD outputBytes;
  233. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  234. return 1;
  235. #endif /* WIN32 */
  236. return 0;
  237. }
  238. #endif
  239. static void last_nettime(struct timeval *last)
  240. {
  241. rd_lock(&netacc_lock);
  242. last->tv_sec = nettime.tv_sec;
  243. last->tv_usec = nettime.tv_usec;
  244. rd_unlock(&netacc_lock);
  245. }
  246. static void set_nettime(void)
  247. {
  248. wr_lock(&netacc_lock);
  249. gettimeofday(&nettime, NULL);
  250. wr_unlock(&netacc_lock);
  251. }
  252. json_t *json_rpc_call(CURL *curl, const char *url,
  253. const char *userpass, const char *rpc_req,
  254. bool probe, bool longpoll, bool *rolltime,
  255. struct pool *pool, bool share)
  256. {
  257. json_t *val, *err_val, *res_val;
  258. int rc;
  259. struct data_buffer all_data = { };
  260. struct upload_buffer upload_data;
  261. json_error_t err = { };
  262. struct curl_slist *headers = NULL;
  263. char len_hdr[64], user_agent_hdr[128];
  264. char curl_err_str[CURL_ERROR_SIZE];
  265. long timeout = longpoll ? (60 * 60) : 60;
  266. struct header_info hi = { };
  267. bool probing = false;
  268. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  269. if (probe)
  270. probing = !pool->probed;
  271. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  272. #if 0 /* Disable curl debugging since it spews to stderr */
  273. if (opt_protocol)
  274. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  275. #endif
  276. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  277. curl_easy_setopt(curl, CURLOPT_URL, url);
  278. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  279. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  280. /* Shares are staggered already and delays in submission can be costly
  281. * so do not delay them */
  282. if (!opt_delaynet || share)
  283. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  284. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  285. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  286. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  287. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  288. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  289. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  290. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  291. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  292. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  293. if (opt_socks_proxy) {
  294. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  295. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  296. }
  297. if (userpass) {
  298. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  299. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  300. }
  301. #ifdef CURL_HAS_SOCKOPT
  302. if (longpoll)
  303. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  304. #endif
  305. curl_easy_setopt(curl, CURLOPT_POST, 1);
  306. if (opt_protocol)
  307. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  308. upload_data.buf = rpc_req;
  309. upload_data.len = strlen(rpc_req);
  310. sprintf(len_hdr, "Content-Length: %lu",
  311. (unsigned long) upload_data.len);
  312. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  313. headers = curl_slist_append(headers,
  314. "Content-type: application/json");
  315. headers = curl_slist_append(headers,
  316. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  317. headers = curl_slist_append(headers, len_hdr);
  318. headers = curl_slist_append(headers, user_agent_hdr);
  319. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  320. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  321. if (opt_delaynet) {
  322. /* Don't delay share submission, but still track the nettime */
  323. if (!share) {
  324. long long now_msecs, last_msecs;
  325. struct timeval now, last;
  326. gettimeofday(&now, NULL);
  327. last_nettime(&last);
  328. now_msecs = (long long)now.tv_sec * 1000;
  329. now_msecs += now.tv_usec / 1000;
  330. last_msecs = (long long)last.tv_sec * 1000;
  331. last_msecs += last.tv_usec / 1000;
  332. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  333. struct timespec rgtp;
  334. rgtp.tv_sec = 0;
  335. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  336. nanosleep(&rgtp, NULL);
  337. }
  338. }
  339. set_nettime();
  340. }
  341. rc = curl_easy_perform(curl);
  342. if (rc) {
  343. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  344. goto err_out;
  345. }
  346. if (!all_data.buf) {
  347. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  348. goto err_out;
  349. }
  350. if (probing) {
  351. pool->probed = true;
  352. /* If X-Long-Polling was found, activate long polling */
  353. if (hi.lp_path)
  354. pool->hdr_path = hi.lp_path;
  355. else
  356. pool->hdr_path = NULL;
  357. }
  358. *rolltime = hi.has_rolltime;
  359. val = JSON_LOADS(all_data.buf, &err);
  360. if (!val) {
  361. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  362. if (opt_protocol)
  363. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  364. goto err_out;
  365. }
  366. if (opt_protocol) {
  367. char *s = json_dumps(val, JSON_INDENT(3));
  368. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  369. free(s);
  370. }
  371. /* JSON-RPC valid response returns a non-null 'result',
  372. * and a null 'error'.
  373. */
  374. res_val = json_object_get(val, "result");
  375. err_val = json_object_get(val, "error");
  376. if (!res_val || json_is_null(res_val) ||
  377. (err_val && !json_is_null(err_val))) {
  378. char *s;
  379. if (err_val)
  380. s = json_dumps(err_val, JSON_INDENT(3));
  381. else
  382. s = strdup("(unknown reason)");
  383. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  384. free(s);
  385. goto err_out;
  386. }
  387. if (hi.reason)
  388. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  389. successful_connect = true;
  390. databuf_free(&all_data);
  391. curl_slist_free_all(headers);
  392. curl_easy_reset(curl);
  393. return val;
  394. err_out:
  395. databuf_free(&all_data);
  396. curl_slist_free_all(headers);
  397. curl_easy_reset(curl);
  398. if (!successful_connect)
  399. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  400. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  401. return NULL;
  402. }
  403. char *bin2hex(const unsigned char *p, size_t len)
  404. {
  405. int i;
  406. char *s = malloc((len * 2) + 1);
  407. if (!s)
  408. return NULL;
  409. for (i = 0; i < len; i++)
  410. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  411. return s;
  412. }
  413. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  414. {
  415. while (*hexstr && len) {
  416. char hex_byte[3];
  417. unsigned int v;
  418. if (!hexstr[1]) {
  419. applog(LOG_ERR, "hex2bin str truncated");
  420. return false;
  421. }
  422. hex_byte[0] = hexstr[0];
  423. hex_byte[1] = hexstr[1];
  424. hex_byte[2] = 0;
  425. if (sscanf(hex_byte, "%x", &v) != 1) {
  426. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  427. return false;
  428. }
  429. *p = (unsigned char) v;
  430. p++;
  431. hexstr += 2;
  432. len--;
  433. }
  434. return (len == 0 && *hexstr == 0) ? true : false;
  435. }
  436. /* Subtract the `struct timeval' values X and Y,
  437. storing the result in RESULT.
  438. Return 1 if the difference is negative, otherwise 0. */
  439. int
  440. timeval_subtract (
  441. struct timeval *result, struct timeval *x, struct timeval *y)
  442. {
  443. /* Perform the carry for the later subtraction by updating Y. */
  444. if (x->tv_usec < y->tv_usec) {
  445. int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
  446. y->tv_usec -= 1000000 * nsec;
  447. y->tv_sec += nsec;
  448. }
  449. if (x->tv_usec - y->tv_usec > 1000000) {
  450. int nsec = (x->tv_usec - y->tv_usec) / 1000000;
  451. y->tv_usec += 1000000 * nsec;
  452. y->tv_sec -= nsec;
  453. }
  454. /* Compute the time remaining to wait.
  455. `tv_usec' is certainly positive. */
  456. result->tv_sec = x->tv_sec - y->tv_sec;
  457. result->tv_usec = x->tv_usec - y->tv_usec;
  458. /* Return 1 if result is negative. */
  459. return x->tv_sec < y->tv_sec;
  460. }
  461. bool fulltest(const unsigned char *hash, const unsigned char *target)
  462. {
  463. unsigned char hash_swap[32], target_swap[32];
  464. uint32_t *hash32 = (uint32_t *) hash_swap;
  465. uint32_t *target32 = (uint32_t *) target_swap;
  466. int i;
  467. bool rc = true;
  468. char *hash_str, *target_str;
  469. swap256(hash_swap, hash);
  470. swap256(target_swap, target);
  471. for (i = 0; i < 32/4; i++) {
  472. uint32_t h32tmp = swab32(hash32[i]);
  473. uint32_t t32tmp = target32[i];
  474. target32[i] = swab32(target32[i]); /* for printing */
  475. if (h32tmp > t32tmp) {
  476. rc = false;
  477. break;
  478. }
  479. if (h32tmp < t32tmp) {
  480. rc = true;
  481. break;
  482. }
  483. }
  484. if (opt_debug) {
  485. hash_str = bin2hex(hash_swap, 32);
  486. target_str = bin2hex(target_swap, 32);
  487. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  488. hash_str,
  489. target_str,
  490. rc ? "YES (hash < target)" :
  491. "no (false positive; hash > target)");
  492. free(hash_str);
  493. free(target_str);
  494. }
  495. return rc;
  496. }
  497. struct thread_q *tq_new(void)
  498. {
  499. struct thread_q *tq;
  500. tq = calloc(1, sizeof(*tq));
  501. if (!tq)
  502. return NULL;
  503. INIT_LIST_HEAD(&tq->q);
  504. pthread_mutex_init(&tq->mutex, NULL);
  505. pthread_cond_init(&tq->cond, NULL);
  506. return tq;
  507. }
  508. void tq_free(struct thread_q *tq)
  509. {
  510. struct tq_ent *ent, *iter;
  511. if (!tq)
  512. return;
  513. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  514. list_del(&ent->q_node);
  515. free(ent);
  516. }
  517. pthread_cond_destroy(&tq->cond);
  518. pthread_mutex_destroy(&tq->mutex);
  519. memset(tq, 0, sizeof(*tq)); /* poison */
  520. free(tq);
  521. }
  522. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  523. {
  524. mutex_lock(&tq->mutex);
  525. tq->frozen = frozen;
  526. pthread_cond_signal(&tq->cond);
  527. mutex_unlock(&tq->mutex);
  528. }
  529. void tq_freeze(struct thread_q *tq)
  530. {
  531. tq_freezethaw(tq, true);
  532. }
  533. void tq_thaw(struct thread_q *tq)
  534. {
  535. tq_freezethaw(tq, false);
  536. }
  537. bool tq_push(struct thread_q *tq, void *data)
  538. {
  539. struct tq_ent *ent;
  540. bool rc = true;
  541. ent = calloc(1, sizeof(*ent));
  542. if (!ent)
  543. return false;
  544. ent->data = data;
  545. INIT_LIST_HEAD(&ent->q_node);
  546. mutex_lock(&tq->mutex);
  547. if (!tq->frozen) {
  548. list_add_tail(&ent->q_node, &tq->q);
  549. } else {
  550. free(ent);
  551. rc = false;
  552. }
  553. pthread_cond_signal(&tq->cond);
  554. mutex_unlock(&tq->mutex);
  555. return rc;
  556. }
  557. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  558. {
  559. struct tq_ent *ent;
  560. void *rval = NULL;
  561. int rc;
  562. mutex_lock(&tq->mutex);
  563. if (!list_empty(&tq->q))
  564. goto pop;
  565. if (abstime)
  566. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  567. else
  568. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  569. if (rc)
  570. goto out;
  571. if (list_empty(&tq->q))
  572. goto out;
  573. pop:
  574. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  575. rval = ent->data;
  576. list_del(&ent->q_node);
  577. free(ent);
  578. out:
  579. mutex_unlock(&tq->mutex);
  580. return rval;
  581. }
  582. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  583. {
  584. int ret;
  585. ret = pthread_create(&thr->pth, attr, start, arg);
  586. return ret;
  587. }
  588. void thr_info_cancel(struct thr_info *thr)
  589. {
  590. if (!thr)
  591. return;
  592. if (thr->q)
  593. tq_freeze(thr->q);
  594. if (PTH(thr) != 0L) {
  595. pthread_cancel(thr->pth);
  596. PTH(thr) = 0L;
  597. }
  598. }