util.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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. #ifdef HAVE_SYSLOG_H
  62. if (use_syslog) {
  63. vsyslog(prio, fmt, ap);
  64. }
  65. #else
  66. if (0) {}
  67. #endif
  68. else if (opt_log_output || prio <= LOG_NOTICE) {
  69. char *f;
  70. int len;
  71. struct timeval tv = { };
  72. struct tm *tm;
  73. gettimeofday(&tv, NULL);
  74. tm = localtime(&tv.tv_sec);
  75. len = 40 + strlen(fmt) + 22;
  76. f = alloca(len);
  77. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d] %s\n",
  78. tm->tm_year + 1900,
  79. tm->tm_mon + 1,
  80. tm->tm_mday,
  81. tm->tm_hour,
  82. tm->tm_min,
  83. tm->tm_sec,
  84. fmt);
  85. /* Only output to stderr if it's not going to the screen as well */
  86. if (!isatty(fileno((FILE *)stderr))) {
  87. va_list apc;
  88. va_copy(apc, ap);
  89. vfprintf(stderr, f, apc); /* atomic write to stderr */
  90. fflush(stderr);
  91. }
  92. if (use_curses)
  93. log_curses(prio, f, ap);
  94. else {
  95. int len = strlen(f);
  96. strcpy(f + len - 1, " \n");
  97. log_curses(prio, f, ap);
  98. }
  99. }
  100. }
  101. void applog(int prio, const char *fmt, ...)
  102. {
  103. va_list ap;
  104. va_start(ap, fmt);
  105. vapplog(prio, fmt, ap);
  106. va_end(ap);
  107. }
  108. static void databuf_free(struct data_buffer *db)
  109. {
  110. if (!db)
  111. return;
  112. free(db->buf);
  113. memset(db, 0, sizeof(*db));
  114. }
  115. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  116. void *user_data)
  117. {
  118. struct data_buffer *db = user_data;
  119. size_t len = size * nmemb;
  120. size_t oldlen, newlen;
  121. void *newmem;
  122. static const unsigned char zero = 0;
  123. oldlen = db->len;
  124. newlen = oldlen + len;
  125. newmem = realloc(db->buf, newlen + 1);
  126. if (!newmem)
  127. return 0;
  128. db->buf = newmem;
  129. db->len = newlen;
  130. memcpy(db->buf + oldlen, ptr, len);
  131. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  132. return len;
  133. }
  134. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  135. void *user_data)
  136. {
  137. struct upload_buffer *ub = user_data;
  138. int len = size * nmemb;
  139. if (len > ub->len)
  140. len = ub->len;
  141. if (len) {
  142. memcpy(ptr, ub->buf, len);
  143. ub->buf += len;
  144. ub->len -= len;
  145. }
  146. return len;
  147. }
  148. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  149. {
  150. struct header_info *hi = user_data;
  151. size_t remlen, slen, ptrlen = size * nmemb;
  152. char *rem, *val = NULL, *key = NULL;
  153. void *tmp;
  154. val = calloc(1, ptrlen);
  155. key = calloc(1, ptrlen);
  156. if (!key || !val)
  157. goto out;
  158. tmp = memchr(ptr, ':', ptrlen);
  159. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  160. goto out;
  161. slen = tmp - ptr;
  162. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  163. goto out;
  164. memcpy(key, ptr, slen); /* store & nul term key */
  165. key[slen] = 0;
  166. rem = ptr + slen + 1; /* trim value's leading whitespace */
  167. remlen = ptrlen - slen - 1;
  168. while ((remlen > 0) && (isspace(*rem))) {
  169. remlen--;
  170. rem++;
  171. }
  172. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  173. val[remlen] = 0;
  174. while ((*val) && (isspace(val[strlen(val) - 1]))) {
  175. val[strlen(val) - 1] = 0;
  176. }
  177. if (!*val) /* skip blank value */
  178. goto out;
  179. if (opt_protocol)
  180. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  181. if (!strcasecmp("X-Roll-Ntime", key)) {
  182. if (!strncasecmp("N", val, 1)) {
  183. if (opt_debug)
  184. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  185. } else {
  186. if (opt_debug)
  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. if (opt_debug)
  348. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  349. goto err_out;
  350. }
  351. if (probing) {
  352. pool->probed = true;
  353. /* If X-Long-Polling was found, activate long polling */
  354. if (hi.lp_path)
  355. pool->hdr_path = hi.lp_path;
  356. else
  357. pool->hdr_path = NULL;
  358. }
  359. *rolltime = hi.has_rolltime;
  360. val = JSON_LOADS(all_data.buf, &err);
  361. if (!val) {
  362. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  363. if (opt_protocol)
  364. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  365. goto err_out;
  366. }
  367. if (opt_protocol) {
  368. char *s = json_dumps(val, JSON_INDENT(3));
  369. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  370. free(s);
  371. }
  372. /* JSON-RPC valid response returns a non-null 'result',
  373. * and a null 'error'.
  374. */
  375. res_val = json_object_get(val, "result");
  376. err_val = json_object_get(val, "error");
  377. if (!res_val || json_is_null(res_val) ||
  378. (err_val && !json_is_null(err_val))) {
  379. char *s;
  380. if (err_val)
  381. s = json_dumps(err_val, JSON_INDENT(3));
  382. else
  383. s = strdup("(unknown reason)");
  384. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  385. free(s);
  386. goto err_out;
  387. }
  388. if (hi.reason)
  389. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  390. successful_connect = true;
  391. databuf_free(&all_data);
  392. curl_slist_free_all(headers);
  393. curl_easy_reset(curl);
  394. return val;
  395. err_out:
  396. databuf_free(&all_data);
  397. curl_slist_free_all(headers);
  398. curl_easy_reset(curl);
  399. if (!successful_connect)
  400. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  401. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  402. return NULL;
  403. }
  404. char *bin2hex(const unsigned char *p, size_t len)
  405. {
  406. int i;
  407. char *s = malloc((len * 2) + 1);
  408. if (!s)
  409. return NULL;
  410. for (i = 0; i < len; i++)
  411. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  412. return s;
  413. }
  414. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  415. {
  416. while (*hexstr && len) {
  417. char hex_byte[3];
  418. unsigned int v;
  419. if (!hexstr[1]) {
  420. applog(LOG_ERR, "hex2bin str truncated");
  421. return false;
  422. }
  423. hex_byte[0] = hexstr[0];
  424. hex_byte[1] = hexstr[1];
  425. hex_byte[2] = 0;
  426. if (sscanf(hex_byte, "%x", &v) != 1) {
  427. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  428. return false;
  429. }
  430. *p = (unsigned char) v;
  431. p++;
  432. hexstr += 2;
  433. len--;
  434. }
  435. return (len == 0 && *hexstr == 0) ? true : false;
  436. }
  437. /* Subtract the `struct timeval' values X and Y,
  438. storing the result in RESULT.
  439. Return 1 if the difference is negative, otherwise 0. */
  440. int
  441. timeval_subtract (
  442. struct timeval *result, struct timeval *x, struct timeval *y)
  443. {
  444. /* Perform the carry for the later subtraction by updating Y. */
  445. if (x->tv_usec < y->tv_usec) {
  446. int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
  447. y->tv_usec -= 1000000 * nsec;
  448. y->tv_sec += nsec;
  449. }
  450. if (x->tv_usec - y->tv_usec > 1000000) {
  451. int nsec = (x->tv_usec - y->tv_usec) / 1000000;
  452. y->tv_usec += 1000000 * nsec;
  453. y->tv_sec -= nsec;
  454. }
  455. /* Compute the time remaining to wait.
  456. `tv_usec' is certainly positive. */
  457. result->tv_sec = x->tv_sec - y->tv_sec;
  458. result->tv_usec = x->tv_usec - y->tv_usec;
  459. /* Return 1 if result is negative. */
  460. return x->tv_sec < y->tv_sec;
  461. }
  462. bool fulltest(const unsigned char *hash, const unsigned char *target)
  463. {
  464. unsigned char hash_swap[32], target_swap[32];
  465. uint32_t *hash32 = (uint32_t *) hash_swap;
  466. uint32_t *target32 = (uint32_t *) target_swap;
  467. int i;
  468. bool rc = true;
  469. char *hash_str, *target_str;
  470. swap256(hash_swap, hash);
  471. swap256(target_swap, target);
  472. for (i = 0; i < 32/4; i++) {
  473. uint32_t h32tmp = swab32(hash32[i]);
  474. uint32_t t32tmp = target32[i];
  475. target32[i] = swab32(target32[i]); /* for printing */
  476. if (h32tmp > t32tmp) {
  477. rc = false;
  478. break;
  479. }
  480. if (h32tmp < t32tmp) {
  481. rc = true;
  482. break;
  483. }
  484. }
  485. if (opt_debug) {
  486. hash_str = bin2hex(hash_swap, 32);
  487. target_str = bin2hex(target_swap, 32);
  488. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  489. hash_str,
  490. target_str,
  491. rc ? "YES (hash < target)" :
  492. "no (false positive; hash > target)");
  493. free(hash_str);
  494. free(target_str);
  495. }
  496. return rc;
  497. }
  498. struct thread_q *tq_new(void)
  499. {
  500. struct thread_q *tq;
  501. tq = calloc(1, sizeof(*tq));
  502. if (!tq)
  503. return NULL;
  504. INIT_LIST_HEAD(&tq->q);
  505. pthread_mutex_init(&tq->mutex, NULL);
  506. pthread_cond_init(&tq->cond, NULL);
  507. return tq;
  508. }
  509. void tq_free(struct thread_q *tq)
  510. {
  511. struct tq_ent *ent, *iter;
  512. if (!tq)
  513. return;
  514. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  515. list_del(&ent->q_node);
  516. free(ent);
  517. }
  518. pthread_cond_destroy(&tq->cond);
  519. pthread_mutex_destroy(&tq->mutex);
  520. memset(tq, 0, sizeof(*tq)); /* poison */
  521. free(tq);
  522. }
  523. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  524. {
  525. mutex_lock(&tq->mutex);
  526. tq->frozen = frozen;
  527. pthread_cond_signal(&tq->cond);
  528. mutex_unlock(&tq->mutex);
  529. }
  530. void tq_freeze(struct thread_q *tq)
  531. {
  532. tq_freezethaw(tq, true);
  533. }
  534. void tq_thaw(struct thread_q *tq)
  535. {
  536. tq_freezethaw(tq, false);
  537. }
  538. bool tq_push(struct thread_q *tq, void *data)
  539. {
  540. struct tq_ent *ent;
  541. bool rc = true;
  542. ent = calloc(1, sizeof(*ent));
  543. if (!ent)
  544. return false;
  545. ent->data = data;
  546. INIT_LIST_HEAD(&ent->q_node);
  547. mutex_lock(&tq->mutex);
  548. if (!tq->frozen) {
  549. list_add_tail(&ent->q_node, &tq->q);
  550. } else {
  551. free(ent);
  552. rc = false;
  553. }
  554. pthread_cond_signal(&tq->cond);
  555. mutex_unlock(&tq->mutex);
  556. return rc;
  557. }
  558. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  559. {
  560. struct tq_ent *ent;
  561. void *rval = NULL;
  562. int rc;
  563. mutex_lock(&tq->mutex);
  564. if (!list_empty(&tq->q))
  565. goto pop;
  566. if (abstime)
  567. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  568. else
  569. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  570. if (rc)
  571. goto out;
  572. if (list_empty(&tq->q))
  573. goto out;
  574. pop:
  575. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  576. rval = ent->data;
  577. list_del(&ent->q_node);
  578. free(ent);
  579. out:
  580. mutex_unlock(&tq->mutex);
  581. return rval;
  582. }
  583. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  584. {
  585. int ret;
  586. ret = pthread_create(&thr->pth, attr, start, arg);
  587. return ret;
  588. }
  589. void thr_info_cancel(struct thr_info *thr)
  590. {
  591. if (!thr)
  592. return;
  593. if (thr->q)
  594. tq_freeze(thr->q);
  595. if (PTH(thr) != 0L) {
  596. pthread_cancel(thr->pth);
  597. PTH(thr) = 0L;
  598. }
  599. }