api.c 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429
  1. /*
  2. * Copyright 2011-2014 Andrew Smith
  3. * Copyright 2011-2014 Con Kolivas
  4. * Copyright 2012-2017 Luke Dashjr
  5. *
  6. * This program is free software; you can redistribute it and/or modify it
  7. * under the terms of the GNU General Public License as published by the Free
  8. * Software Foundation; either version 3 of the License, or (at your option)
  9. * any later version. See COPYING for more details.
  10. *
  11. * Note: the code always includes GPU support even if there are no GPUs
  12. * this simplifies handling multiple other device code being included
  13. * depending on compile options
  14. */
  15. #define _MEMORY_DEBUG_MASTER 1
  16. #include "config.h"
  17. #include <math.h>
  18. #include <stdio.h>
  19. #include <ctype.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <stdbool.h>
  23. #include <stdint.h>
  24. #include <unistd.h>
  25. #include <sys/types.h>
  26. #include <uthash.h>
  27. #include <utlist.h>
  28. #include "compat.h"
  29. #include "deviceapi.h"
  30. #ifdef USE_LIBMICROHTTPD
  31. #include "httpsrv.h"
  32. #endif
  33. #include "miner.h"
  34. #include "util.h"
  35. #include "driver-cpu.h" /* for algo_names[], TODO: re-factor dependency */
  36. #include "driver-opencl.h"
  37. #define HAVE_AN_FPGA 1
  38. // Max amount of data to buffer before sending on the socket
  39. #define RPC_SOCKBUFSIZ 0x10000
  40. // BUFSIZ varies on Windows and Linux
  41. #define TMPBUFSIZ 8192
  42. // Number of requests to queue - normally would be small
  43. // However lots of PGA's may mean more
  44. #define QUEUE 100
  45. static const char *UNAVAILABLE = " - API will not be available";
  46. static const char *MUNAVAILABLE = " - API multicast listener will not be available";
  47. static const char *BLANK = "";
  48. static const char *COMMA = ",";
  49. #define COMSTR ","
  50. static const char SEPARATOR = '|';
  51. #define SEPSTR "|"
  52. static const char GPUSEP = ',';
  53. #define CMDJOIN '+'
  54. #define JOIN_CMD "CMD="
  55. #define BETWEEN_JOIN SEPSTR
  56. static const char *APIVERSION = "3.1";
  57. static const char *DEAD = "Dead";
  58. static const char *SICK = "Sick";
  59. static const char *NOSTART = "NoStart";
  60. static const char *INIT = "Initialising";
  61. static const char *WAIT = "Waiting";
  62. static const char *DISABLED = "Disabled";
  63. static const char *ALIVE = "Alive";
  64. static const char *REJECTING = "Rejecting";
  65. static const char *UNKNOWN = "Unknown";
  66. #define _DYNAMIC "D"
  67. #ifdef USE_OPENCL
  68. static const char *DYNAMIC = _DYNAMIC;
  69. #endif
  70. static const char *YES = "Y";
  71. static const char *NO = "N";
  72. static const char *NULLSTR = "(null)";
  73. static const char *TRUESTR = "true";
  74. static const char *FALSESTR = "false";
  75. #ifdef USE_SCRYPT
  76. static const char *SCRYPTSTR = "scrypt";
  77. #endif
  78. #ifdef USE_SHA256D
  79. static const char *SHA256STR = "sha256";
  80. #endif
  81. static const char *OSINFO =
  82. #if defined(__linux)
  83. "Linux";
  84. #else
  85. #if defined(__APPLE__)
  86. "Apple";
  87. #else
  88. #if defined (__CYGWIN__)
  89. "Cygwin";
  90. #elif defined (WIN32)
  91. "Windows";
  92. #else
  93. #if defined(unix)
  94. "Unix";
  95. #else
  96. "Unknown";
  97. #endif
  98. #endif
  99. #endif
  100. #endif
  101. #define _DEVS "DEVS"
  102. #define _POOLS "POOLS"
  103. #define _SUMMARY "SUMMARY"
  104. #define _STATUS "STATUS"
  105. #define _VERSION "VERSION"
  106. #define _MINECONFIG "CONFIG"
  107. #define _GPU "GPU"
  108. #ifdef HAVE_AN_FPGA
  109. #define _PGA "PGA"
  110. #endif
  111. #ifdef USE_CPUMINING
  112. #define _CPU "CPU"
  113. #endif
  114. #define _GPUS "GPUS"
  115. #define _PGAS "PGAS"
  116. #define _CPUS "CPUS"
  117. #define _NOTIFY "NOTIFY"
  118. #define _DEVDETAILS "DEVDETAILS"
  119. #define _BYE "BYE"
  120. #define _RESTART "RESTART"
  121. #define _MINESTATS "STATS"
  122. #define _CHECK "CHECK"
  123. #define _MINECOIN "COIN"
  124. #define _DEBUGSET "DEBUG"
  125. #define _SETCONFIG "SETCONFIG"
  126. static const char ISJSON = '{';
  127. #define JSON0 "{"
  128. #define JSON1 "\""
  129. #define JSON2 "\":["
  130. #define JSON3 "]"
  131. #define JSON4 ",\"id\":1"
  132. // If anyone cares, id=0 for truncated output
  133. #define JSON4_TRUNCATED ",\"id\":0"
  134. #define JSON5 "}"
  135. #define JSON_START JSON0
  136. #define JSON_DEVS JSON1 _DEVS JSON2
  137. #define JSON_POOLS JSON1 _POOLS JSON2
  138. #define JSON_SUMMARY JSON1 _SUMMARY JSON2
  139. #define JSON_STATUS JSON1 _STATUS JSON2
  140. #define JSON_VERSION JSON1 _VERSION JSON2
  141. #define JSON_MINECONFIG JSON1 _MINECONFIG JSON2
  142. #define JSON_GPU JSON1 _GPU JSON2
  143. #ifdef HAVE_AN_FPGA
  144. #define JSON_PGA JSON1 _PGA JSON2
  145. #endif
  146. #ifdef USE_CPUMINING
  147. #define JSON_CPU JSON1 _CPU JSON2
  148. #endif
  149. #define JSON_GPUS JSON1 _GPUS JSON2
  150. #define JSON_PGAS JSON1 _PGAS JSON2
  151. #define JSON_CPUS JSON1 _CPUS JSON2
  152. #define JSON_NOTIFY JSON1 _NOTIFY JSON2
  153. #define JSON_CLOSE JSON3
  154. #define JSON_MINESTATS JSON1 _MINESTATS JSON2
  155. #define JSON_CHECK JSON1 _CHECK JSON2
  156. #define JSON_DEBUGSET JSON1 _DEBUGSET JSON2
  157. #define JSON_SETCONFIG JSON1 _SETCONFIG JSON2
  158. #define JSON_END JSON4 JSON5
  159. #define JSON_END_TRUNCATED JSON4_TRUNCATED JSON5
  160. #define JSON_BETWEEN_JOIN ","
  161. static const char *JSON_COMMAND = "command";
  162. static const char *JSON_PARAMETER = "parameter";
  163. #define MSG_INVGPU 1
  164. #define MSG_ALRENA 2
  165. #define MSG_ALRDIS 3
  166. #define MSG_GPUMRE 4
  167. #define MSG_GPUREN 5
  168. #define MSG_GPUNON 6
  169. #define MSG_POOL 7
  170. #define MSG_NOPOOL 8
  171. #define MSG_DEVS 9
  172. #define MSG_NODEVS 10
  173. #define MSG_SUMM 11
  174. #define MSG_GPUDIS 12
  175. #define MSG_GPUREI 13
  176. #define MSG_INVCMD 14
  177. #define MSG_MISID 15
  178. #define MSG_GPUDEV 17
  179. #ifdef USE_CPUMINING
  180. #define MSG_CPUNON 16
  181. #define MSG_CPUDEV 18
  182. #define MSG_INVCPU 19
  183. #define MSG_ALRENAC 98
  184. #define MSG_ALRDISC 99
  185. #define MSG_CPUMRE 100
  186. #define MSG_CPUREN 101
  187. #define MSG_CPUDIS 102
  188. #define MSG_CPUREI 103
  189. #endif
  190. #define MSG_NUMGPU 20
  191. #define MSG_NUMCPU 21
  192. #define MSG_VERSION 22
  193. #define MSG_INVJSON 23
  194. #define MSG_MISCMD 24
  195. #define MSG_MISPID 25
  196. #define MSG_INVPID 26
  197. #define MSG_SWITCHP 27
  198. #define MSG_MISVAL 28
  199. #define MSG_NOADL 29
  200. #define MSG_NOGPUADL 30
  201. #define MSG_INVINT 31
  202. #define MSG_GPUINT 32
  203. #define MSG_MINECONFIG 33
  204. #define MSG_GPUMERR 34
  205. #define MSG_GPUMEM 35
  206. #define MSG_GPUEERR 36
  207. #define MSG_GPUENG 37
  208. #define MSG_GPUVERR 38
  209. #define MSG_GPUVDDC 39
  210. #define MSG_GPUFERR 40
  211. #define MSG_GPUFAN 41
  212. #define MSG_MISFN 42
  213. #define MSG_BADFN 43
  214. #define MSG_SAVED 44
  215. #define MSG_ACCDENY 45
  216. #define MSG_ACCOK 46
  217. #define MSG_ENAPOOL 47
  218. #define MSG_DISPOOL 48
  219. #define MSG_ALRENAP 49
  220. #define MSG_ALRDISP 50
  221. #define MSG_DISLASTP 51
  222. #define MSG_MISPDP 52
  223. #define MSG_INVPDP 53
  224. #define MSG_TOOMANYP 54
  225. #define MSG_ADDPOOL 55
  226. #ifdef HAVE_AN_FPGA
  227. #define MSG_PGANON 56
  228. #define MSG_PGADEV 57
  229. #define MSG_INVPGA 58
  230. #endif
  231. #define MSG_NUMPGA 59
  232. #define MSG_NOTIFY 60
  233. #ifdef HAVE_AN_FPGA
  234. #define MSG_PGALRENA 61
  235. #define MSG_PGALRDIS 62
  236. #define MSG_PGAENA 63
  237. #define MSG_PGADIS 64
  238. #define MSG_PGAREI 0x101
  239. #define MSG_PGAUNW 65
  240. #endif
  241. #define MSG_REMLASTP 66
  242. #define MSG_ACTPOOL 67
  243. #define MSG_REMPOOL 68
  244. #define MSG_DEVDETAILS 69
  245. #define MSG_MINESTATS 70
  246. #define MSG_MISCHK 71
  247. #define MSG_CHECK 72
  248. #define MSG_POOLPRIO 73
  249. #define MSG_DUPPID 74
  250. #define MSG_MISBOOL 75
  251. #define MSG_INVBOOL 76
  252. #define MSG_FOO 77
  253. #define MSG_MINECOIN 78
  254. #define MSG_DEBUGSET 79
  255. #define MSG_PGAIDENT 80
  256. #define MSG_PGANOID 81
  257. #define MSG_SETCONFIG 82
  258. #define MSG_UNKCON 83
  259. #define MSG_INVNUM 84
  260. #define MSG_CONPAR 85
  261. #define MSG_CONVAL 86
  262. #ifdef HAVE_AN_FPGA
  263. #define MSG_MISPGAOPT 89
  264. #define MSG_PGANOSET 90
  265. #define MSG_PGAHELP 91
  266. #define MSG_PGASETOK 92
  267. #define MSG_PGASETERR 93
  268. #endif
  269. #define MSG_ZERMIS 94
  270. #define MSG_ZERINV 95
  271. #define MSG_ZERSUM 96
  272. #define MSG_ZERNOSUM 97
  273. #define MSG_DEVSCAN 0x100
  274. #define MSG_BYE 0x101
  275. #define MSG_INVNEG 121
  276. #define MSG_SETQUOTA 122
  277. #define MSG_INVSTRATEGY 0x102
  278. #define MSG_FAILPORT 0x103
  279. #define USE_ALTMSG 0x4000
  280. enum code_severity {
  281. SEVERITY_ERR,
  282. SEVERITY_WARN,
  283. SEVERITY_INFO,
  284. SEVERITY_SUCC,
  285. SEVERITY_FAIL
  286. };
  287. enum code_parameters {
  288. PARAM_COUNT,
  289. PARAM_GPU,
  290. PARAM_PGA,
  291. PARAM_CPU,
  292. PARAM_PID,
  293. PARAM_GPUMAX,
  294. PARAM_PGAMAX,
  295. PARAM_CPUMAX,
  296. PARAM_PMAX,
  297. PARAM_POOLMAX,
  298. // Single generic case: have the code resolve it - see below
  299. PARAM_DMAX,
  300. PARAM_CMD,
  301. PARAM_POOL,
  302. PARAM_STR,
  303. PARAM_BOTH,
  304. PARAM_BOOL,
  305. PARAM_SET,
  306. PARAM_NONE
  307. };
  308. struct CODES {
  309. const enum code_severity severity;
  310. const int code;
  311. const enum code_parameters params;
  312. const char *description;
  313. } codes[] = {
  314. #ifdef USE_OPENCL
  315. { SEVERITY_ERR, MSG_INVGPU, PARAM_GPUMAX, "Invalid GPU id %d - range is 0 - %d" },
  316. { SEVERITY_INFO, MSG_ALRENA, PARAM_GPU, "GPU %d already enabled" },
  317. { SEVERITY_INFO, MSG_ALRDIS, PARAM_GPU, "GPU %d already disabled" },
  318. { SEVERITY_WARN, MSG_GPUMRE, PARAM_GPU, "GPU %d must be restarted first" },
  319. { SEVERITY_INFO, MSG_GPUREN, PARAM_GPU, "GPU %d sent enable message" },
  320. #endif
  321. { SEVERITY_ERR, MSG_GPUNON, PARAM_NONE, "No GPUs" },
  322. { SEVERITY_SUCC, MSG_POOL, PARAM_PMAX, "%d Pool(s)" },
  323. { SEVERITY_ERR, MSG_NOPOOL, PARAM_NONE, "No pools" },
  324. { SEVERITY_SUCC, MSG_DEVS, PARAM_DMAX,
  325. "%d PGA(s)"
  326. },
  327. { SEVERITY_ERR, MSG_NODEVS, PARAM_NONE, "No PGAs"
  328. },
  329. { SEVERITY_SUCC, MSG_SUMM, PARAM_NONE, "Summary" },
  330. #ifdef USE_OPENCL
  331. { SEVERITY_INFO, MSG_GPUDIS, PARAM_GPU, "GPU %d set disable flag" },
  332. { SEVERITY_INFO, MSG_GPUREI, PARAM_GPU, "GPU %d restart attempted" },
  333. #endif
  334. { SEVERITY_ERR, MSG_INVCMD, PARAM_NONE, "Invalid command" },
  335. { SEVERITY_ERR, MSG_MISID, PARAM_NONE, "Missing device id parameter" },
  336. #ifdef USE_OPENCL
  337. { SEVERITY_SUCC, MSG_GPUDEV, PARAM_GPU, "GPU%d" },
  338. #endif
  339. #ifdef HAVE_AN_FPGA
  340. { SEVERITY_ERR, MSG_PGANON, PARAM_NONE, "No PGAs" },
  341. { SEVERITY_SUCC, MSG_PGADEV, PARAM_PGA, "PGA%d" },
  342. { SEVERITY_ERR, MSG_INVPGA, PARAM_PGAMAX, "Invalid PGA id %d - range is 0 - %d" },
  343. { SEVERITY_INFO, MSG_PGALRENA,PARAM_PGA, "PGA %d already enabled" },
  344. { SEVERITY_INFO, MSG_PGALRDIS,PARAM_PGA, "PGA %d already disabled" },
  345. { SEVERITY_INFO, MSG_PGAENA, PARAM_PGA, "PGA %d sent enable message" },
  346. { SEVERITY_INFO, MSG_PGADIS, PARAM_PGA, "PGA %d set disable flag" },
  347. { SEVERITY_ERR, MSG_PGAUNW, PARAM_PGA, "PGA %d is not flagged WELL, cannot enable" },
  348. #endif
  349. #ifdef USE_CPUMINING
  350. { SEVERITY_ERR, MSG_CPUNON, PARAM_NONE, "No CPUs" },
  351. { SEVERITY_SUCC, MSG_CPUDEV, PARAM_CPU, "CPU%d" },
  352. { SEVERITY_ERR, MSG_INVCPU, PARAM_CPUMAX, "Invalid CPU id %d - range is 0 - %d" },
  353. { SEVERITY_INFO, MSG_ALRENAC, PARAM_CPU, "CPU %d already enabled" },
  354. { SEVERITY_INFO, MSG_ALRDISC, PARAM_CPU, "CPU %d already disabled" },
  355. { SEVERITY_WARN, MSG_CPUMRE, PARAM_CPU, "CPU %d must be restarted first" },
  356. { SEVERITY_INFO, MSG_CPUREN, PARAM_CPU, "CPU %d sent enable message" },
  357. { SEVERITY_INFO, MSG_CPUDIS, PARAM_CPU, "CPU %d set disable flag" },
  358. { SEVERITY_INFO, MSG_CPUREI, PARAM_CPU, "CPU %d restart attempted" },
  359. #endif
  360. { SEVERITY_SUCC, MSG_NUMGPU, PARAM_NONE, "GPU count" },
  361. { SEVERITY_SUCC, MSG_NUMPGA, PARAM_NONE, "PGA count" },
  362. { SEVERITY_SUCC, MSG_NUMCPU, PARAM_NONE, "CPU count" },
  363. { SEVERITY_SUCC, MSG_VERSION, PARAM_NONE, "BFGMiner versions" },
  364. { SEVERITY_ERR, MSG_INVJSON, PARAM_NONE, "Invalid JSON" },
  365. { SEVERITY_ERR, MSG_MISCMD, PARAM_CMD, "Missing JSON '%s'" },
  366. { SEVERITY_ERR, MSG_MISPID, PARAM_NONE, "Missing pool id parameter" },
  367. { SEVERITY_ERR, MSG_INVPID, PARAM_POOLMAX, "Invalid pool id %d - range is 0 - %d" },
  368. { SEVERITY_SUCC, MSG_SWITCHP, PARAM_POOL, "Switching to pool %d:'%s'" },
  369. { SEVERITY_ERR, MSG_MISVAL, PARAM_NONE, "Missing comma after GPU number" },
  370. { SEVERITY_ERR, MSG_NOADL, PARAM_NONE, "ADL is not available" },
  371. { SEVERITY_ERR, MSG_NOGPUADL,PARAM_GPU, "GPU %d does not have ADL" },
  372. { SEVERITY_ERR, MSG_INVINT, PARAM_STR, "Invalid intensity (%s) - must be '" _DYNAMIC "' or range -10 - 31" },
  373. { SEVERITY_INFO, MSG_GPUINT, PARAM_BOTH, "GPU %d set new intensity to %s" },
  374. { SEVERITY_SUCC, MSG_MINECONFIG,PARAM_NONE, "BFGMiner config" },
  375. #ifdef USE_OPENCL
  376. { SEVERITY_ERR, MSG_GPUMERR, PARAM_BOTH, "Setting GPU %d memoryclock to (%s) reported failure" },
  377. { SEVERITY_SUCC, MSG_GPUMEM, PARAM_BOTH, "Setting GPU %d memoryclock to (%s) reported success" },
  378. { SEVERITY_ERR, MSG_GPUEERR, PARAM_BOTH, "Setting GPU %d clock to (%s) reported failure" },
  379. { SEVERITY_SUCC, MSG_GPUENG, PARAM_BOTH, "Setting GPU %d clock to (%s) reported success" },
  380. { SEVERITY_ERR, MSG_GPUVERR, PARAM_BOTH, "Setting GPU %d vddc to (%s) reported failure" },
  381. { SEVERITY_SUCC, MSG_GPUVDDC, PARAM_BOTH, "Setting GPU %d vddc to (%s) reported success" },
  382. { SEVERITY_ERR, MSG_GPUFERR, PARAM_BOTH, "Setting GPU %d fan to (%s) reported failure" },
  383. { SEVERITY_SUCC, MSG_GPUFAN, PARAM_BOTH, "Setting GPU %d fan to (%s) reported success" },
  384. #endif
  385. { SEVERITY_ERR, MSG_MISFN, PARAM_NONE, "Missing save filename parameter" },
  386. { SEVERITY_ERR, MSG_BADFN, PARAM_STR, "Can't open or create save file '%s'" },
  387. { SEVERITY_SUCC, MSG_SAVED, PARAM_STR, "Configuration saved to file '%s'" },
  388. { SEVERITY_ERR, MSG_ACCDENY, PARAM_STR, "Access denied to '%s' command" },
  389. { SEVERITY_SUCC, MSG_ACCOK, PARAM_NONE, "Privileged access OK" },
  390. { SEVERITY_SUCC, MSG_ENAPOOL, PARAM_POOL, "Enabling pool %d:'%s'" },
  391. { SEVERITY_SUCC, MSG_POOLPRIO,PARAM_NONE, "Changed pool priorities" },
  392. { SEVERITY_ERR, MSG_DUPPID, PARAM_PID, "Duplicate pool specified %d" },
  393. { SEVERITY_SUCC, MSG_DISPOOL, PARAM_POOL, "Disabling pool %d:'%s'" },
  394. { SEVERITY_INFO, MSG_ALRENAP, PARAM_POOL, "Pool %d:'%s' already enabled" },
  395. { SEVERITY_INFO, MSG_ALRDISP, PARAM_POOL, "Pool %d:'%s' already disabled" },
  396. { SEVERITY_ERR, MSG_DISLASTP,PARAM_POOL, "Cannot disable last active pool %d:'%s'" },
  397. { SEVERITY_ERR, MSG_MISPDP, PARAM_NONE, "Missing addpool details" },
  398. { SEVERITY_ERR, MSG_INVPDP, PARAM_STR, "Invalid addpool details '%s'" },
  399. { SEVERITY_ERR, MSG_TOOMANYP,PARAM_NONE, "Reached maximum number of pools (%d)" },
  400. { SEVERITY_SUCC, MSG_ADDPOOL, PARAM_STR, "Added pool '%s'" },
  401. { SEVERITY_ERR, MSG_REMLASTP,PARAM_POOL, "Cannot remove last pool %d:'%s'" },
  402. { SEVERITY_ERR, MSG_ACTPOOL, PARAM_POOL, "Cannot remove active pool %d:'%s'" },
  403. { SEVERITY_SUCC, MSG_REMPOOL, PARAM_BOTH, "Removed pool %d:'%s'" },
  404. { SEVERITY_SUCC, MSG_NOTIFY, PARAM_NONE, "Notify" },
  405. { SEVERITY_SUCC, MSG_DEVDETAILS,PARAM_NONE, "Device Details" },
  406. { SEVERITY_SUCC, MSG_MINESTATS,PARAM_NONE, "BFGMiner stats" },
  407. { SEVERITY_ERR, MSG_MISCHK, PARAM_NONE, "Missing check cmd" },
  408. { SEVERITY_SUCC, MSG_CHECK, PARAM_NONE, "Check command" },
  409. { SEVERITY_ERR, MSG_MISBOOL, PARAM_NONE, "Missing parameter: true/false" },
  410. { SEVERITY_ERR, MSG_INVBOOL, PARAM_NONE, "Invalid parameter should be true or false" },
  411. { SEVERITY_SUCC, MSG_FOO, PARAM_BOOL, "Failover-Only set to %s" },
  412. { SEVERITY_SUCC, MSG_MINECOIN,PARAM_NONE, "BFGMiner coin" },
  413. { SEVERITY_SUCC, MSG_DEBUGSET,PARAM_NONE, "Debug settings" },
  414. #ifdef HAVE_AN_FPGA
  415. { SEVERITY_SUCC, MSG_PGAIDENT,PARAM_PGA, "Identify command sent to PGA%d" },
  416. { SEVERITY_WARN, MSG_PGANOID, PARAM_PGA, "PGA%d does not support identify" },
  417. #endif
  418. { SEVERITY_SUCC, MSG_SETCONFIG,PARAM_SET, "Set config '%s' to %d" },
  419. { SEVERITY_ERR, MSG_UNKCON, PARAM_STR, "Unknown config '%s'" },
  420. { SEVERITY_ERR, MSG_INVNUM, PARAM_BOTH, "Invalid number (%d) for '%s' range is 0-9999" },
  421. { SEVERITY_ERR, MSG_INVNEG, PARAM_BOTH, "Invalid negative number (%d) for '%s'" },
  422. { SEVERITY_ERR, MSG_INVSTRATEGY, PARAM_STR, "Invalid strategy for '%s'" },
  423. { SEVERITY_ERR, MSG_FAILPORT, PARAM_BOTH, "Failed to set port (%d) for '%s'" },
  424. { SEVERITY_SUCC, MSG_SETQUOTA,PARAM_SET, "Set pool '%s' to quota %d'" },
  425. { SEVERITY_ERR, MSG_CONPAR, PARAM_NONE, "Missing config parameters 'name,N'" },
  426. { SEVERITY_ERR, MSG_CONVAL, PARAM_STR, "Missing config value N for '%s,N'" },
  427. #ifdef HAVE_AN_FPGA
  428. { SEVERITY_ERR, MSG_MISPGAOPT, PARAM_NONE, "Missing option after PGA number" },
  429. { SEVERITY_WARN, MSG_PGANOSET, PARAM_PGA, "PGA %d does not support pgaset" },
  430. { SEVERITY_INFO, MSG_PGAHELP, PARAM_BOTH, "PGA %d set help: %s" },
  431. { SEVERITY_SUCC, MSG_PGASETOK, PARAM_PGA, "PGA %d set OK" },
  432. { SEVERITY_SUCC, MSG_PGASETOK | USE_ALTMSG, PARAM_BOTH, "PGA %d set OK: %s" },
  433. { SEVERITY_ERR, MSG_PGASETERR, PARAM_BOTH, "PGA %d set failed: %s" },
  434. #endif
  435. { SEVERITY_ERR, MSG_ZERMIS, PARAM_NONE, "Missing zero parameters" },
  436. { SEVERITY_ERR, MSG_ZERINV, PARAM_STR, "Invalid zero parameter '%s'" },
  437. { SEVERITY_SUCC, MSG_ZERSUM, PARAM_STR, "Zeroed %s stats with summary" },
  438. { SEVERITY_SUCC, MSG_ZERNOSUM, PARAM_STR, "Zeroed %s stats without summary" },
  439. { SEVERITY_SUCC, MSG_DEVSCAN, PARAM_COUNT, "Added %d new device(s)" },
  440. { SEVERITY_SUCC, MSG_BYE, PARAM_STR, "%s" },
  441. { SEVERITY_FAIL, 0, 0, NULL }
  442. };
  443. static const char *localaddr = "127.0.0.1";
  444. static int my_thr_id = 0;
  445. static bool bye;
  446. // Used to control quit restart access to shutdown variables
  447. static pthread_mutex_t quit_restart_lock;
  448. static bool do_a_quit;
  449. static bool do_a_restart;
  450. static time_t when = 0; // when the request occurred
  451. static bool per_proc;
  452. struct IP4ACCESS {
  453. in_addr_t ip;
  454. in_addr_t mask;
  455. char group;
  456. };
  457. #define GROUP(g) (toupper(g))
  458. #define PRIVGROUP GROUP('W')
  459. #define NOPRIVGROUP GROUP('R')
  460. #define ISPRIVGROUP(g) (GROUP(g) == PRIVGROUP)
  461. #define GROUPOFFSET(g) (GROUP(g) - GROUP('A'))
  462. #define VALIDGROUP(g) (GROUP(g) >= GROUP('A') && GROUP(g) <= GROUP('Z'))
  463. #define COMMANDS(g) (apigroups[GROUPOFFSET(g)].commands)
  464. #define DEFINEDGROUP(g) (ISPRIVGROUP(g) || COMMANDS(g) != NULL)
  465. struct APIGROUPS {
  466. // This becomes a string like: "|cmd1|cmd2|cmd3|" so it's quick to search
  467. char *commands;
  468. } apigroups['Z' - 'A' + 1]; // only A=0 to Z=25 (R: noprivs, W: allprivs)
  469. static struct IP4ACCESS *ipaccess = NULL;
  470. static int ips = 0;
  471. struct io_data {
  472. bytes_t data;
  473. SOCKETTYPE sock;
  474. // Whether to add various things
  475. bool close;
  476. };
  477. static struct io_data *rpc_io_data;
  478. static void io_reinit(struct io_data *io_data)
  479. {
  480. bytes_reset(&io_data->data);
  481. io_data->close = false;
  482. }
  483. static
  484. struct io_data *sock_io_new()
  485. {
  486. struct io_data *io_data = malloc(sizeof(struct io_data));
  487. bytes_init(&io_data->data);
  488. io_data->sock = INVSOCK;
  489. io_reinit(io_data);
  490. return io_data;
  491. }
  492. static
  493. size_t io_flush(struct io_data *io_data, bool complete)
  494. {
  495. size_t sent = 0, tosend = bytes_len(&io_data->data);
  496. ssize_t n;
  497. struct timeval timeout = {0, complete ? 50000: 0}, tv;
  498. fd_set wd;
  499. int count = 0;
  500. while (tosend)
  501. {
  502. FD_ZERO(&wd);
  503. FD_SET(io_data->sock, &wd);
  504. tv = timeout;
  505. if (select(io_data->sock + 1, NULL, &wd, NULL, &tv) < 1)
  506. break;
  507. n = send(io_data->sock, (void*)&bytes_buf(&io_data->data)[sent], tosend, 0);
  508. if (SOCKETFAIL(n))
  509. {
  510. if (!sock_blocks())
  511. applog(LOG_WARNING, "API: send (%lu) failed: %s", (unsigned long)tosend, SOCKERRMSG);
  512. break;
  513. }
  514. if (count <= 1)
  515. {
  516. if (n == tosend)
  517. applog(LOG_DEBUG, "API: sent all of %lu first go", (unsigned long)tosend);
  518. else
  519. applog(LOG_DEBUG, "API: sent %ld of %lu first go", (long)n, (unsigned long)tosend);
  520. }
  521. else
  522. {
  523. if (n == tosend)
  524. applog(LOG_DEBUG, "API: sent all of remaining %lu (count=%d)", (unsigned long)tosend, count);
  525. else
  526. applog(LOG_DEBUG, "API: sent %ld of remaining %lu (count=%d)", (long)n, (unsigned long)tosend, count);
  527. }
  528. sent += n;
  529. tosend -= n;
  530. }
  531. bytes_shift(&io_data->data, sent);
  532. return sent;
  533. }
  534. static bool io_add(struct io_data *io_data, char *buf)
  535. {
  536. size_t len = strlen(buf);
  537. if (bytes_len(&io_data->data) + len > RPC_SOCKBUFSIZ)
  538. io_flush(io_data, false);
  539. bytes_append(&io_data->data, buf, len);
  540. return true;
  541. }
  542. static void io_close(struct io_data *io_data)
  543. {
  544. io_data->close = true;
  545. }
  546. static void io_free()
  547. {
  548. bytes_free(&rpc_io_data->data);
  549. free(rpc_io_data);
  550. rpc_io_data = NULL;
  551. }
  552. // This is only called when expected to be needed (rarely)
  553. // i.e. strings outside of the codes control (input from the user)
  554. static char *escape_string(char *str, bool isjson)
  555. {
  556. char *buf, *ptr;
  557. int count;
  558. count = 0;
  559. for (ptr = str; *ptr; ptr++) {
  560. switch (*ptr) {
  561. case ',':
  562. case '|':
  563. case '=':
  564. if (!isjson)
  565. count++;
  566. break;
  567. case '"':
  568. if (isjson)
  569. count++;
  570. break;
  571. case '\\':
  572. count++;
  573. break;
  574. }
  575. }
  576. if (count == 0)
  577. return str;
  578. buf = malloc(strlen(str) + count + 1);
  579. if (unlikely(!buf))
  580. quit(1, "Failed to malloc escape buf");
  581. ptr = buf;
  582. while (*str)
  583. switch (*str) {
  584. case ',':
  585. case '|':
  586. case '=':
  587. if (!isjson)
  588. *(ptr++) = '\\';
  589. *(ptr++) = *(str++);
  590. break;
  591. case '"':
  592. if (isjson)
  593. *(ptr++) = '\\';
  594. *(ptr++) = *(str++);
  595. break;
  596. case '\\':
  597. *(ptr++) = '\\';
  598. *(ptr++) = *(str++);
  599. break;
  600. default:
  601. *(ptr++) = *(str++);
  602. break;
  603. }
  604. *ptr = '\0';
  605. return buf;
  606. }
  607. static struct api_data *api_add_extra(struct api_data *root, struct api_data *extra)
  608. {
  609. struct api_data *tmp;
  610. if (root) {
  611. if (extra) {
  612. // extra tail
  613. tmp = extra->prev;
  614. // extra prev = root tail
  615. extra->prev = root->prev;
  616. // root tail next = extra
  617. root->prev->next = extra;
  618. // extra tail next = root
  619. tmp->next = root;
  620. // root prev = extra tail
  621. root->prev = tmp;
  622. }
  623. } else
  624. root = extra;
  625. return root;
  626. }
  627. static
  628. struct api_data *api_add_data_full(struct api_data *root, const char * const name, enum api_data_type type, const void *data, bool copy_data)
  629. {
  630. struct api_data *api_data;
  631. api_data = (struct api_data *)malloc(sizeof(struct api_data));
  632. api_data->name = strdup(name);
  633. api_data->type = type;
  634. if (root == NULL) {
  635. root = api_data;
  636. root->prev = root;
  637. root->next = root;
  638. }
  639. else {
  640. api_data->prev = root->prev;
  641. root->prev = api_data;
  642. api_data->next = root;
  643. api_data->prev->next = api_data;
  644. }
  645. api_data->data_was_malloc = copy_data;
  646. // Avoid crashing on bad data
  647. if (data == NULL) {
  648. api_data->type = type = API_CONST;
  649. data = NULLSTR;
  650. api_data->data_was_malloc = copy_data = false;
  651. }
  652. if (!copy_data)
  653. {
  654. api_data->data = data;
  655. if (type == API_JSON)
  656. json_incref((json_t *)data);
  657. }
  658. else
  659. {
  660. size_t datalen = 0;
  661. switch(type) {
  662. case API_ESCAPE:
  663. case API_STRING:
  664. case API_CONST:
  665. datalen = strlen(data) + 1;
  666. break;
  667. case API_UINT8:
  668. datalen = sizeof(uint8_t);
  669. break;
  670. case API_INT16:
  671. datalen = sizeof(int16_t);
  672. break;
  673. case API_UINT16:
  674. datalen = sizeof(uint16_t);
  675. break;
  676. case API_INT:
  677. datalen = sizeof(int);
  678. break;
  679. case API_UINT:
  680. datalen = sizeof(unsigned int);
  681. break;
  682. case API_UINT32:
  683. datalen = sizeof(uint32_t);
  684. break;
  685. case API_UINT64:
  686. datalen = sizeof(uint64_t);
  687. break;
  688. case API_DOUBLE:
  689. case API_ELAPSED:
  690. case API_MHS:
  691. case API_MHTOTAL:
  692. case API_UTILITY:
  693. case API_FREQ:
  694. case API_HS:
  695. case API_DIFF:
  696. case API_PERCENT:
  697. datalen = sizeof(double);
  698. break;
  699. case API_BOOL:
  700. datalen = sizeof(bool);
  701. break;
  702. case API_TIMEVAL:
  703. datalen = sizeof(struct timeval);
  704. break;
  705. case API_TIME:
  706. datalen = sizeof(time_t);
  707. break;
  708. case API_VOLTS:
  709. case API_TEMP:
  710. datalen = sizeof(float);
  711. break;
  712. case API_JSON:
  713. api_data->data_was_malloc = false;
  714. api_data->data = json_deep_copy((json_t *)data);
  715. break;
  716. default:
  717. applog(LOG_ERR, "API: unknown1 data type %d ignored", type);
  718. api_data->type = API_STRING;
  719. api_data->data_was_malloc = false;
  720. api_data->data = UNKNOWN;
  721. break;
  722. }
  723. if (datalen)
  724. {
  725. void * const copied_data = malloc(datalen);
  726. memcpy(copied_data, data, datalen);
  727. api_data->data = copied_data;
  728. }
  729. }
  730. return root;
  731. }
  732. struct api_data *api_add_escape(struct api_data * const root, const char * const name, const char * const data, const bool copy_data)
  733. {
  734. return api_add_data_full(root, name, API_ESCAPE, data, copy_data);
  735. }
  736. struct api_data *api_add_string(struct api_data * const root, const char * const name, const char * const data, const bool copy_data)
  737. {
  738. return api_add_data_full(root, name, API_STRING, data, copy_data);
  739. }
  740. struct api_data *api_add_const(struct api_data * const root, const char * const name, const char * const data, const bool copy_data)
  741. {
  742. return api_add_data_full(root, name, API_CONST, data, copy_data);
  743. }
  744. struct api_data *api_add_uint8(struct api_data * const root, const char * const name, const uint8_t * const data, const bool copy_data)
  745. {
  746. return api_add_data_full(root, name, API_UINT8, data, copy_data);
  747. }
  748. struct api_data *api_add_int16(struct api_data * const root, const char * const name, const uint16_t * const data, const bool copy_data)
  749. {
  750. return api_add_data_full(root, name, API_INT16, data, copy_data);
  751. }
  752. struct api_data *api_add_uint16(struct api_data * const root, const char * const name, const uint16_t * const data, const bool copy_data)
  753. {
  754. return api_add_data_full(root, name, API_UINT16, data, copy_data);
  755. }
  756. struct api_data *api_add_int(struct api_data * const root, const char * const name, const int * const data, const bool copy_data)
  757. {
  758. return api_add_data_full(root, name, API_INT, data, copy_data);
  759. }
  760. struct api_data *api_add_uint(struct api_data * const root, const char * const name, const unsigned int * const data, const bool copy_data)
  761. {
  762. return api_add_data_full(root, name, API_UINT, data, copy_data);
  763. }
  764. struct api_data *api_add_uint32(struct api_data * const root, const char * const name, const uint32_t * const data, const bool copy_data)
  765. {
  766. return api_add_data_full(root, name, API_UINT32, data, copy_data);
  767. }
  768. struct api_data *api_add_uint64(struct api_data * const root, const char * const name, const uint64_t * const data, const bool copy_data)
  769. {
  770. return api_add_data_full(root, name, API_UINT64, data, copy_data);
  771. }
  772. struct api_data *api_add_double(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  773. {
  774. return api_add_data_full(root, name, API_DOUBLE, data, copy_data);
  775. }
  776. struct api_data *api_add_elapsed(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  777. {
  778. return api_add_data_full(root, name, API_ELAPSED, data, copy_data);
  779. }
  780. struct api_data *api_add_bool(struct api_data * const root, const char * const name, const bool * const data, const bool copy_data)
  781. {
  782. return api_add_data_full(root, name, API_BOOL, data, copy_data);
  783. }
  784. struct api_data *api_add_timeval(struct api_data * const root, const char * const name, const struct timeval * const data, const bool copy_data)
  785. {
  786. return api_add_data_full(root, name, API_TIMEVAL, data, copy_data);
  787. }
  788. struct api_data *api_add_time(struct api_data * const root, const char * const name, const time_t * const data, const bool copy_data)
  789. {
  790. return api_add_data_full(root, name, API_TIME, data, copy_data);
  791. }
  792. struct api_data *api_add_mhs(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  793. {
  794. return api_add_data_full(root, name, API_MHS, data, copy_data);
  795. }
  796. struct api_data *api_add_mhtotal(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  797. {
  798. return api_add_data_full(root, name, API_MHTOTAL, data, copy_data);
  799. }
  800. struct api_data *api_add_temp(struct api_data * const root, const char * const name, const float * const data, const bool copy_data)
  801. {
  802. return api_add_data_full(root, name, API_TEMP, data, copy_data);
  803. }
  804. struct api_data *api_add_utility(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  805. {
  806. return api_add_data_full(root, name, API_UTILITY, data, copy_data);
  807. }
  808. struct api_data *api_add_freq(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  809. {
  810. return api_add_data_full(root, name, API_FREQ, data, copy_data);
  811. }
  812. struct api_data *api_add_volts(struct api_data * const root, const char * const name, const float * const data, const bool copy_data)
  813. {
  814. return api_add_data_full(root, name, API_VOLTS, data, copy_data);
  815. }
  816. struct api_data *api_add_hs(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  817. {
  818. return api_add_data_full(root, name, API_HS, data, copy_data);
  819. }
  820. struct api_data *api_add_diff(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  821. {
  822. return api_add_data_full(root, name, API_DIFF, data, copy_data);
  823. }
  824. // json_t is not const since we generally increase the refcount
  825. struct api_data *api_add_json(struct api_data * const root, const char * const name, json_t * const data, const bool copy_data)
  826. {
  827. return api_add_data_full(root, name, API_JSON, data, copy_data);
  828. }
  829. struct api_data *api_add_percent(struct api_data * const root, const char * const name, const double * const data, const bool copy_data)
  830. {
  831. return api_add_data_full(root, name, API_PERCENT, data, copy_data);
  832. }
  833. static struct api_data *print_data(struct api_data *root, char *buf, bool isjson, bool precom)
  834. {
  835. struct api_data *tmp;
  836. bool first = true;
  837. char *original, *escape;
  838. char *quote;
  839. *buf = '\0';
  840. if (precom) {
  841. *(buf++) = *COMMA;
  842. *buf = '\0';
  843. }
  844. if (isjson) {
  845. strcpy(buf, JSON0);
  846. buf = strchr(buf, '\0');
  847. quote = JSON1;
  848. } else
  849. quote = (char *)BLANK;
  850. while (root) {
  851. if (!first)
  852. *(buf++) = *COMMA;
  853. else
  854. first = false;
  855. sprintf(buf, "%s%s%s%s", quote, root->name, quote, isjson ? ":" : "=");
  856. buf = strchr(buf, '\0');
  857. switch(root->type) {
  858. case API_STRING:
  859. case API_CONST:
  860. sprintf(buf, "%s%s%s", quote, (char *)(root->data), quote);
  861. break;
  862. case API_ESCAPE:
  863. original = (char *)(root->data);
  864. escape = escape_string((char *)(root->data), isjson);
  865. sprintf(buf, "%s%s%s", quote, escape, quote);
  866. if (escape != original)
  867. free(escape);
  868. break;
  869. case API_UINT8:
  870. sprintf(buf, "%u", *(uint8_t *)root->data);
  871. break;
  872. case API_INT16:
  873. sprintf(buf, "%d", *(int16_t *)root->data);
  874. break;
  875. case API_UINT16:
  876. sprintf(buf, "%u", *(uint16_t *)root->data);
  877. break;
  878. case API_INT:
  879. sprintf(buf, "%d", *((int *)(root->data)));
  880. break;
  881. case API_UINT:
  882. sprintf(buf, "%u", *((unsigned int *)(root->data)));
  883. break;
  884. case API_UINT32:
  885. sprintf(buf, "%"PRIu32, *((uint32_t *)(root->data)));
  886. break;
  887. case API_UINT64:
  888. sprintf(buf, "%"PRIu64, *((uint64_t *)(root->data)));
  889. break;
  890. case API_TIME:
  891. sprintf(buf, "%lu", *((unsigned long *)(root->data)));
  892. break;
  893. case API_DOUBLE:
  894. sprintf(buf, "%f", *((double *)(root->data)));
  895. break;
  896. case API_ELAPSED:
  897. sprintf(buf, "%.0f", *((double *)(root->data)));
  898. break;
  899. case API_UTILITY:
  900. case API_FREQ:
  901. case API_MHS:
  902. sprintf(buf, "%.3f", *((double *)(root->data)));
  903. break;
  904. case API_VOLTS:
  905. sprintf(buf, "%.3f", *((float *)(root->data)));
  906. break;
  907. case API_MHTOTAL:
  908. sprintf(buf, "%.4f", *((double *)(root->data)));
  909. break;
  910. case API_HS:
  911. sprintf(buf, "%.15f", *((double *)(root->data)));
  912. break;
  913. case API_DIFF:
  914. {
  915. const double *fp = root->data;
  916. if (fmod(*fp, 1.))
  917. sprintf(buf, "%.8f", *fp);
  918. else
  919. sprintf(buf, "%.0f", *fp);
  920. break;
  921. }
  922. case API_BOOL:
  923. sprintf(buf, "%s", *((bool *)(root->data)) ? TRUESTR : FALSESTR);
  924. break;
  925. case API_TIMEVAL:
  926. sprintf(buf, "%"PRIu64".%06lu",
  927. (uint64_t)((struct timeval *)(root->data))->tv_sec,
  928. (unsigned long)((struct timeval *)(root->data))->tv_usec);
  929. break;
  930. case API_TEMP:
  931. sprintf(buf, "%.2f", *((float *)(root->data)));
  932. break;
  933. case API_JSON:
  934. escape = json_dumps((json_t *)(root->data), JSON_COMPACT);
  935. strcpy(buf, escape);
  936. free(escape);
  937. break;
  938. case API_PERCENT:
  939. sprintf(buf, "%.4f", *((double *)(root->data)) * 100.0);
  940. break;
  941. default:
  942. applog(LOG_ERR, "API: unknown2 data type %d ignored", root->type);
  943. sprintf(buf, "%s%s%s", quote, UNKNOWN, quote);
  944. break;
  945. }
  946. buf = strchr(buf, '\0');
  947. free(root->name);
  948. if (root->type == API_JSON)
  949. json_decref((json_t *)root->data);
  950. if (root->data_was_malloc)
  951. free((void*)root->data);
  952. if (root->next == root) {
  953. free(root);
  954. root = NULL;
  955. } else {
  956. tmp = root;
  957. root = tmp->next;
  958. root->prev = tmp->prev;
  959. root->prev->next = root;
  960. free(tmp);
  961. }
  962. }
  963. strcpy(buf, isjson ? JSON5 : SEPSTR);
  964. return root;
  965. }
  966. #ifdef HAVE_AN_FPGA
  967. static int numpgas()
  968. {
  969. int count = 0;
  970. int i;
  971. rd_lock(&devices_lock);
  972. for (i = 0; i < total_devices; i++) {
  973. if (devices[i]->device != devices[i] && !per_proc)
  974. continue;
  975. ++count;
  976. }
  977. rd_unlock(&devices_lock);
  978. return count;
  979. }
  980. static int pgadevice(int pgaid)
  981. {
  982. int count = 0;
  983. int i;
  984. rd_lock(&devices_lock);
  985. for (i = 0; i < total_devices; i++) {
  986. if (devices[i]->device != devices[i] && !per_proc)
  987. continue;
  988. ++count;
  989. if (count == (pgaid + 1))
  990. goto foundit;
  991. }
  992. rd_unlock(&devices_lock);
  993. return -1;
  994. foundit:
  995. rd_unlock(&devices_lock);
  996. return i;
  997. }
  998. #endif
  999. // All replies (except BYE and RESTART) start with a message
  1000. // thus for JSON, message() inserts JSON_START at the front
  1001. // and send_result() adds JSON_END at the end
  1002. static void message(struct io_data * const io_data, const int messageid2, const int paramid, const char * const param2, const bool isjson)
  1003. {
  1004. struct api_data *root = NULL;
  1005. char buf[TMPBUFSIZ];
  1006. char buf2[TMPBUFSIZ];
  1007. char severity[2];
  1008. #ifdef HAVE_AN_FPGA
  1009. int pga;
  1010. #endif
  1011. #ifdef USE_CPUMINING
  1012. int cpu;
  1013. #endif
  1014. int i;
  1015. int messageid = messageid2 & ~USE_ALTMSG;
  1016. if (isjson)
  1017. io_add(io_data, JSON_START JSON_STATUS);
  1018. for (i = 0; codes[i].severity != SEVERITY_FAIL; i++) {
  1019. if (codes[i].code == messageid2) {
  1020. switch (codes[i].severity) {
  1021. case SEVERITY_WARN:
  1022. severity[0] = 'W';
  1023. break;
  1024. case SEVERITY_INFO:
  1025. severity[0] = 'I';
  1026. break;
  1027. case SEVERITY_SUCC:
  1028. severity[0] = 'S';
  1029. break;
  1030. case SEVERITY_ERR:
  1031. default:
  1032. severity[0] = 'E';
  1033. break;
  1034. }
  1035. severity[1] = '\0';
  1036. switch(codes[i].params) {
  1037. case PARAM_COUNT:
  1038. case PARAM_GPU:
  1039. case PARAM_PGA:
  1040. case PARAM_CPU:
  1041. case PARAM_PID:
  1042. sprintf(buf, codes[i].description, paramid);
  1043. break;
  1044. case PARAM_POOL:
  1045. sprintf(buf, codes[i].description, paramid, pools[paramid]->rpc_url);
  1046. break;
  1047. #ifdef USE_OPENCL
  1048. case PARAM_GPUMAX:
  1049. sprintf(buf, codes[i].description, paramid, nDevs - 1);
  1050. break;
  1051. #endif
  1052. #ifdef HAVE_AN_FPGA
  1053. case PARAM_PGAMAX:
  1054. pga = numpgas();
  1055. sprintf(buf, codes[i].description, paramid, pga - 1);
  1056. break;
  1057. #endif
  1058. #ifdef USE_CPUMINING
  1059. case PARAM_CPUMAX:
  1060. if (opt_n_threads > 0)
  1061. cpu = num_processors;
  1062. else
  1063. cpu = 0;
  1064. sprintf(buf, codes[i].description, paramid, cpu - 1);
  1065. break;
  1066. #endif
  1067. case PARAM_PMAX:
  1068. sprintf(buf, codes[i].description, total_pools);
  1069. break;
  1070. case PARAM_POOLMAX:
  1071. sprintf(buf, codes[i].description, paramid, total_pools - 1);
  1072. break;
  1073. case PARAM_DMAX:
  1074. pga = numpgas();
  1075. sprintf(buf, codes[i].description
  1076. , pga
  1077. );
  1078. break;
  1079. case PARAM_CMD:
  1080. sprintf(buf, codes[i].description, JSON_COMMAND);
  1081. break;
  1082. case PARAM_STR:
  1083. sprintf(buf, codes[i].description, param2);
  1084. break;
  1085. case PARAM_BOTH:
  1086. sprintf(buf, codes[i].description, paramid, param2);
  1087. break;
  1088. case PARAM_BOOL:
  1089. sprintf(buf, codes[i].description, paramid ? TRUESTR : FALSESTR);
  1090. break;
  1091. case PARAM_SET:
  1092. sprintf(buf, codes[i].description, param2, paramid);
  1093. break;
  1094. case PARAM_NONE:
  1095. default:
  1096. strcpy(buf, codes[i].description);
  1097. }
  1098. root = api_add_string(root, _STATUS, severity, false);
  1099. root = api_add_time(root, "When", &when, false);
  1100. root = api_add_int(root, "Code", &messageid, false);
  1101. root = api_add_escape(root, "Msg", buf, false);
  1102. root = api_add_escape(root, "Description", opt_api_description, false);
  1103. root = print_data(root, buf2, isjson, false);
  1104. io_add(io_data, buf2);
  1105. if (isjson)
  1106. io_add(io_data, JSON_CLOSE);
  1107. return;
  1108. }
  1109. }
  1110. root = api_add_string(root, _STATUS, "F", false);
  1111. root = api_add_time(root, "When", &when, false);
  1112. int id = -1;
  1113. root = api_add_int(root, "Code", &id, false);
  1114. sprintf(buf, "%d", messageid);
  1115. root = api_add_escape(root, "Msg", buf, false);
  1116. root = api_add_escape(root, "Description", opt_api_description, false);
  1117. root = print_data(root, buf2, isjson, false);
  1118. io_add(io_data, buf2);
  1119. if (isjson)
  1120. io_add(io_data, JSON_CLOSE);
  1121. }
  1122. static void apiversion(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1123. {
  1124. struct api_data *root = NULL;
  1125. char buf[TMPBUFSIZ];
  1126. bool io_open;
  1127. message(io_data, MSG_VERSION, 0, NULL, isjson);
  1128. io_open = io_add(io_data, isjson ? COMSTR JSON_VERSION : _VERSION COMSTR);
  1129. root = api_add_string(root, "Miner", bfgminer_name_space_ver, false);
  1130. root = api_add_string(root, "CGMiner", bfgminer_ver, false);
  1131. root = api_add_const(root, "API", APIVERSION, false);
  1132. root = print_data(root, buf, isjson, false);
  1133. io_add(io_data, buf);
  1134. if (isjson && io_open)
  1135. io_close(io_data);
  1136. }
  1137. static void minerconfig(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1138. {
  1139. struct api_data *root = NULL;
  1140. char buf[TMPBUFSIZ];
  1141. bool io_open;
  1142. struct driver_registration *reg;
  1143. int pgacount = 0;
  1144. char *adlinuse = (char *)NO;
  1145. int i;
  1146. #ifdef HAVE_ADL
  1147. const char *adl = YES;
  1148. for (i = 0; i < nDevs; i++) {
  1149. struct opencl_device_data * const data = gpus[i].device_data;
  1150. if (data->has_adl) {
  1151. adlinuse = (char *)YES;
  1152. break;
  1153. }
  1154. }
  1155. #else
  1156. const char *adl = NO;
  1157. #endif
  1158. #ifdef HAVE_AN_FPGA
  1159. pgacount = numpgas();
  1160. #endif
  1161. message(io_data, MSG_MINECONFIG, 0, NULL, isjson);
  1162. io_open = io_add(io_data, isjson ? COMSTR JSON_MINECONFIG : _MINECONFIG COMSTR);
  1163. root = api_add_int(root, "PGA Count", &pgacount, false);
  1164. root = api_add_int(root, "Pool Count", &total_pools, false);
  1165. root = api_add_const(root, "ADL", (char *)adl, false);
  1166. root = api_add_string(root, "ADL in use", adlinuse, false);
  1167. root = api_add_const(root, "Strategy", strategies[pool_strategy].s, false);
  1168. if (pool_strategy == POOL_ROTATE)
  1169. root = api_add_int(root, "Rotate Period", &opt_rotate_period, false);
  1170. root = api_add_int(root, "Log Interval", &opt_log_interval, false);
  1171. strcpy(buf, ""
  1172. #ifdef USE_LIBMICROHTTPD
  1173. " SGW"
  1174. #endif
  1175. #ifdef USE_LIBEVENT
  1176. " SSM"
  1177. #endif
  1178. );
  1179. BFG_FOREACH_DRIVER_BY_DNAME(reg)
  1180. {
  1181. const struct device_drv * const drv = reg->drv;
  1182. tailsprintf(buf, sizeof(buf), " %s", drv->name);
  1183. }
  1184. root = api_add_const(root, "Device Code", &buf[1], true);
  1185. root = api_add_const(root, "OS", OSINFO, false);
  1186. root = api_add_bool(root, "Failover-Only", &opt_fail_only, false);
  1187. root = api_add_int(root, "ScanTime", &opt_scantime, false);
  1188. root = api_add_int(root, "Queue", &opt_queue, false);
  1189. root = api_add_int(root, "Expiry", &opt_expiry, false);
  1190. #if BLKMAKER_VERSION > 0
  1191. root = api_add_string(root, "Coinbase-Sig", opt_coinbase_sig, true);
  1192. #endif
  1193. struct bfg_loaded_configfile *configfile;
  1194. i = 0;
  1195. LL_FOREACH(bfg_loaded_configfiles, configfile)
  1196. {
  1197. snprintf(buf, sizeof(buf), "ConfigFile%d", i++);
  1198. root = api_add_string(root, buf, configfile->filename, false);
  1199. }
  1200. root = print_data(root, buf, isjson, false);
  1201. io_add(io_data, buf);
  1202. if (isjson && io_open)
  1203. io_close(io_data);
  1204. }
  1205. static const char*
  1206. bool2str(bool b)
  1207. {
  1208. return b ? YES : NO;
  1209. }
  1210. static const char *status2str(enum alive status)
  1211. {
  1212. switch (status) {
  1213. case LIFE_WELL:
  1214. return ALIVE;
  1215. case LIFE_SICK:
  1216. return SICK;
  1217. case LIFE_DEAD:
  1218. case LIFE_DEAD2:
  1219. return DEAD;
  1220. case LIFE_NOSTART:
  1221. return NOSTART;
  1222. case LIFE_INIT:
  1223. case LIFE_INIT2:
  1224. return INIT;
  1225. case LIFE_WAIT:
  1226. return WAIT;
  1227. case LIFE_MIXED:
  1228. return "Mixed";
  1229. default:
  1230. return UNKNOWN;
  1231. }
  1232. }
  1233. static
  1234. struct api_data *api_add_device_identifier(struct api_data *root, struct cgpu_info *cgpu)
  1235. {
  1236. root = api_add_string(root, "Name", cgpu->drv->name, false);
  1237. root = api_add_int(root, "ID", &(cgpu->device_id), false);
  1238. if (per_proc)
  1239. root = api_add_int(root, "ProcID", &(cgpu->proc_id), false);
  1240. return root;
  1241. }
  1242. static
  1243. int find_index_by_cgpu(struct cgpu_info *cgpu)
  1244. {
  1245. if (per_proc)
  1246. return cgpu->cgminer_id;
  1247. int n = 0, i;
  1248. // Quickly traverse the devices array backward until we reach the 0th device, counting as we go
  1249. rd_lock(&devices_lock);
  1250. while (true)
  1251. {
  1252. i = cgpu->device->cgminer_id;
  1253. if (!i)
  1254. break;
  1255. cgpu = devices[--i];
  1256. ++n;
  1257. }
  1258. rd_unlock(&devices_lock);
  1259. return n;
  1260. }
  1261. static void devdetail_an(struct io_data *io_data, struct cgpu_info *cgpu, bool isjson, bool precom)
  1262. {
  1263. struct api_data *root = NULL;
  1264. char buf[TMPBUFSIZ];
  1265. int n;
  1266. cgpu_utility(cgpu);
  1267. n = find_index_by_cgpu(cgpu);
  1268. root = api_add_int(root, "DEVDETAILS", &n, true);
  1269. root = api_add_device_identifier(root, cgpu);
  1270. if (!per_proc)
  1271. root = api_add_int(root, "Processors", &cgpu->procs, false);
  1272. root = api_add_string(root, "Driver", cgpu->drv->dname, false);
  1273. if (cgpu->kname)
  1274. root = api_add_string(root, "Kernel", cgpu->kname, false);
  1275. if (cgpu->name)
  1276. root = api_add_string(root, "Model", cgpu->name, false);
  1277. if (cgpu->dev_manufacturer)
  1278. root = api_add_string(root, "Manufacturer", cgpu->dev_manufacturer, false);
  1279. if (cgpu->dev_product)
  1280. root = api_add_string(root, "Product", cgpu->dev_product, false);
  1281. if (cgpu->dev_serial)
  1282. root = api_add_string(root, "Serial", cgpu->dev_serial, false);
  1283. if (cgpu->device_path)
  1284. root = api_add_string(root, "Device Path", cgpu->device_path, false);
  1285. root = api_add_int(root, "Target Temperature", &cgpu->targettemp, false);
  1286. root = api_add_int(root, "Cutoff Temperature", &cgpu->cutofftemp, false);
  1287. if ((per_proc || cgpu->procs <= 1) && cgpu->drv->get_api_extra_device_detail)
  1288. root = api_add_extra(root, cgpu->drv->get_api_extra_device_detail(cgpu));
  1289. root = print_data(root, buf, isjson, precom);
  1290. io_add(io_data, buf);
  1291. }
  1292. static
  1293. void devstatus_an(struct io_data *io_data, struct cgpu_info *cgpu, bool isjson, bool precom)
  1294. {
  1295. struct cgpu_info *proc;
  1296. struct api_data *root = NULL;
  1297. char buf[TMPBUFSIZ];
  1298. int n;
  1299. n = find_index_by_cgpu(cgpu);
  1300. double runtime = cgpu_runtime(cgpu);
  1301. bool enabled = false;
  1302. double total_mhashes = 0, rolling = 0, utility = 0;
  1303. enum alive status = cgpu->status;
  1304. float temp = -1;
  1305. int accepted = 0, rejected = 0, stale = 0, hw_errors = 0;
  1306. double diff1 = 0, bad_diff1 = 0;
  1307. double diff_accepted = 0, diff_rejected = 0, diff_stale = 0;
  1308. int last_share_pool = -1;
  1309. time_t last_share_pool_time = -1, last_device_valid_work = -1;
  1310. double last_share_diff = -1;
  1311. int procs = per_proc ? 1 : cgpu->procs, i;
  1312. for (i = 0, proc = cgpu; i < procs; ++i, proc = proc->next_proc)
  1313. {
  1314. cgpu_utility(proc);
  1315. if (proc->deven != DEV_DISABLED)
  1316. enabled = true;
  1317. total_mhashes += proc->total_mhashes;
  1318. rolling += proc->drv->get_proc_rolling_hashrate ? proc->drv->get_proc_rolling_hashrate(proc) : proc->rolling;
  1319. utility += proc->utility;
  1320. accepted += proc->accepted;
  1321. rejected += proc->rejected;
  1322. stale += proc->stale;
  1323. hw_errors += proc->hw_errors;
  1324. diff1 += proc->diff1;
  1325. diff_accepted += proc->diff_accepted;
  1326. diff_rejected += proc->diff_rejected;
  1327. diff_stale += proc->diff_stale;
  1328. bad_diff1 += proc->bad_diff1;
  1329. if (status != proc->status)
  1330. status = LIFE_MIXED;
  1331. if (proc->temp > temp)
  1332. temp = proc->temp;
  1333. if (proc->last_share_pool_time > last_share_pool_time)
  1334. {
  1335. last_share_pool_time = proc->last_share_pool_time;
  1336. last_share_pool = proc->last_share_pool;
  1337. last_share_diff = proc->last_share_diff;
  1338. }
  1339. if (proc->last_device_valid_work > last_device_valid_work)
  1340. last_device_valid_work = proc->last_device_valid_work;
  1341. if (per_proc)
  1342. break;
  1343. }
  1344. root = api_add_int(root, "PGA", &n, true);
  1345. root = api_add_device_identifier(root, cgpu);
  1346. root = api_add_string(root, "Enabled", bool2str(enabled), false);
  1347. root = api_add_string(root, "Status", status2str(status), false);
  1348. if (temp > 0)
  1349. root = api_add_temp(root, "Temperature", &temp, false);
  1350. root = api_add_elapsed(root, "Device Elapsed", &runtime, false);
  1351. double mhs = total_mhashes / runtime;
  1352. root = api_add_mhs(root, "MHS av", &mhs, false);
  1353. char mhsname[27];
  1354. sprintf(mhsname, "MHS %ds", opt_log_interval);
  1355. root = api_add_mhs(root, mhsname, &rolling, false);
  1356. root = api_add_mhs(root, "MHS rolling", &rolling, false);
  1357. root = api_add_int(root, "Accepted", &accepted, false);
  1358. root = api_add_int(root, "Rejected", &rejected, false);
  1359. root = api_add_int(root, "Hardware Errors", &hw_errors, false);
  1360. root = api_add_utility(root, "Utility", &utility, false);
  1361. root = api_add_int(root, "Stale", &stale, false);
  1362. if (last_share_pool != -1)
  1363. {
  1364. root = api_add_int(root, "Last Share Pool", &last_share_pool, false);
  1365. root = api_add_time(root, "Last Share Time", &last_share_pool_time, false);
  1366. }
  1367. root = api_add_mhtotal(root, "Total MH", &total_mhashes, false);
  1368. double work_utility = diff1 / runtime * 60;
  1369. root = api_add_diff(root, "Diff1 Work", &diff1, false);
  1370. root = api_add_utility(root, "Work Utility", &work_utility, false);
  1371. root = api_add_diff(root, "Difficulty Accepted", &diff_accepted, false);
  1372. root = api_add_diff(root, "Difficulty Rejected", &diff_rejected, false);
  1373. root = api_add_diff(root, "Difficulty Stale", &diff_stale, false);
  1374. if (last_share_diff > 0)
  1375. root = api_add_diff(root, "Last Share Difficulty", &last_share_diff, false);
  1376. if (last_device_valid_work != -1)
  1377. root = api_add_time(root, "Last Valid Work", &last_device_valid_work, false);
  1378. double hwp = (bad_diff1 + diff1) ?
  1379. (double)(bad_diff1) / (double)(bad_diff1 + diff1) : 0;
  1380. root = api_add_percent(root, "Device Hardware%", &hwp, false);
  1381. double rejp = diff1 ?
  1382. (double)(diff_rejected) / (double)(diff1) : 0;
  1383. root = api_add_percent(root, "Device Rejected%", &rejp, false);
  1384. if ((per_proc || cgpu->procs <= 1) && cgpu->drv->get_api_extra_device_status)
  1385. root = api_add_extra(root, cgpu->drv->get_api_extra_device_status(cgpu));
  1386. root = print_data(root, buf, isjson, precom);
  1387. io_add(io_data, buf);
  1388. }
  1389. #ifdef USE_OPENCL
  1390. static void gpustatus(struct io_data *io_data, int gpu, bool isjson, bool precom)
  1391. {
  1392. if (gpu < 0 || gpu >= nDevs)
  1393. return;
  1394. devstatus_an(io_data, &gpus[gpu], isjson, precom);
  1395. }
  1396. #endif
  1397. #ifdef HAVE_AN_FPGA
  1398. static void pgastatus(struct io_data *io_data, int pga, bool isjson, bool precom)
  1399. {
  1400. int dev = pgadevice(pga);
  1401. if (dev < 0) // Should never happen
  1402. return;
  1403. devstatus_an(io_data, get_devices(dev), isjson, precom);
  1404. }
  1405. #endif
  1406. #ifdef USE_CPUMINING
  1407. static void cpustatus(struct io_data *io_data, int cpu, bool isjson, bool precom)
  1408. {
  1409. if (opt_n_threads <= 0 || cpu < 0 || cpu >= num_processors)
  1410. return;
  1411. devstatus_an(io_data, &cpus[cpu], isjson, precom);
  1412. }
  1413. #endif
  1414. static void
  1415. devinfo_internal(void (*func)(struct io_data *, struct cgpu_info*, bool, bool), int msg, struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1416. {
  1417. struct cgpu_info *cgpu;
  1418. bool io_open = false;
  1419. int i;
  1420. if (total_devices == 0) {
  1421. message(io_data, MSG_NODEVS, 0, NULL, isjson);
  1422. return;
  1423. }
  1424. message(io_data, msg, 0, NULL, isjson);
  1425. if (isjson)
  1426. io_open = io_add(io_data, COMSTR JSON_DEVS);
  1427. for (i = 0; i < total_devices; ++i) {
  1428. cgpu = get_devices(i);
  1429. if (per_proc || cgpu->device == cgpu)
  1430. func(io_data, cgpu, isjson, isjson && i > 0);
  1431. }
  1432. if (isjson && io_open)
  1433. io_close(io_data);
  1434. }
  1435. static void devdetail(struct io_data *io_data, SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1436. {
  1437. return devinfo_internal(devdetail_an, MSG_DEVDETAILS, io_data, c, param, isjson, group);
  1438. }
  1439. static void devstatus(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1440. {
  1441. return devinfo_internal(devstatus_an, MSG_DEVS, io_data, c, param, isjson, group);
  1442. }
  1443. #ifdef USE_OPENCL
  1444. static void gpudev(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1445. {
  1446. bool io_open = false;
  1447. int id;
  1448. if (nDevs == 0) {
  1449. message(io_data, MSG_GPUNON, 0, NULL, isjson);
  1450. return;
  1451. }
  1452. if (param == NULL || *param == '\0') {
  1453. message(io_data, MSG_MISID, 0, NULL, isjson);
  1454. return;
  1455. }
  1456. id = atoi(param);
  1457. if (id < 0 || id >= nDevs) {
  1458. message(io_data, MSG_INVGPU, id, NULL, isjson);
  1459. return;
  1460. }
  1461. message(io_data, MSG_GPUDEV, id, NULL, isjson);
  1462. if (isjson)
  1463. io_open = io_add(io_data, COMSTR JSON_GPU);
  1464. gpustatus(io_data, id, isjson, false);
  1465. if (isjson && io_open)
  1466. io_close(io_data);
  1467. }
  1468. #endif
  1469. static void devscan(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1470. {
  1471. int n;
  1472. bool io_open = false;
  1473. applog(LOG_DEBUG, "RPC: request to scan %s for devices",
  1474. param);
  1475. if (param && !param[0])
  1476. param = NULL;
  1477. n = scan_serial(param);
  1478. message(io_data, MSG_DEVSCAN, n, NULL, isjson);
  1479. io_open = io_add(io_data, isjson ? COMSTR JSON_DEVS : _DEVS COMSTR);
  1480. n = total_devices - n;
  1481. for (int i = n; i < total_devices; ++i)
  1482. devdetail_an(io_data, get_devices(i), isjson, i > n);
  1483. if (isjson && io_open)
  1484. io_close(io_data);
  1485. }
  1486. #ifdef HAVE_AN_FPGA
  1487. static
  1488. struct cgpu_info *get_pga_cgpu(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group, int *id_p, int *dev_p)
  1489. {
  1490. int numpga = numpgas();
  1491. if (numpga == 0) {
  1492. message(io_data, MSG_PGANON, 0, NULL, isjson);
  1493. return NULL;
  1494. }
  1495. if (param == NULL || *param == '\0') {
  1496. message(io_data, MSG_MISID, 0, NULL, isjson);
  1497. return NULL;
  1498. }
  1499. *id_p = atoi(param);
  1500. if (*id_p < 0 || *id_p >= numpga) {
  1501. message(io_data, MSG_INVPGA, *id_p, NULL, isjson);
  1502. return NULL;
  1503. }
  1504. *dev_p = pgadevice(*id_p);
  1505. if (*dev_p < 0) { // Should never happen
  1506. message(io_data, MSG_INVPGA, *id_p, NULL, isjson);
  1507. return NULL;
  1508. }
  1509. return get_devices(*dev_p);
  1510. }
  1511. static void pgadev(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1512. {
  1513. bool io_open = false;
  1514. int id, dev;
  1515. if (!get_pga_cgpu(io_data, c, param, isjson, group, &id, &dev))
  1516. return;
  1517. message(io_data, MSG_PGADEV, id, NULL, isjson);
  1518. if (isjson)
  1519. io_open = io_add(io_data, COMSTR JSON_PGA);
  1520. pgastatus(io_data, id, isjson, false);
  1521. if (isjson && io_open)
  1522. io_close(io_data);
  1523. }
  1524. static void pgaenable(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1525. {
  1526. struct cgpu_info *cgpu, *proc;
  1527. int id, dev;
  1528. bool already;
  1529. cgpu = get_pga_cgpu(io_data, c, param, isjson, group, &id, &dev);
  1530. if (!cgpu)
  1531. return;
  1532. applog(LOG_DEBUG, "API: request to pgaenable %s id %d device %d %s",
  1533. per_proc ? "proc" : "dev", id, dev, cgpu->proc_repr_ns);
  1534. already = true;
  1535. int procs = per_proc ? 1 : cgpu->procs, i;
  1536. for (i = 0, proc = cgpu; i < procs; ++i, proc = proc->next_proc)
  1537. {
  1538. if (proc->deven == DEV_DISABLED)
  1539. {
  1540. proc_enable(proc);
  1541. already = false;
  1542. }
  1543. }
  1544. if (already)
  1545. {
  1546. message(io_data, MSG_PGALRENA, id, NULL, isjson);
  1547. return;
  1548. }
  1549. #if 0 /* A DISABLED device wont change status FIXME: should disabling make it WELL? */
  1550. if (cgpu->status != LIFE_WELL) {
  1551. message(io_data, MSG_PGAUNW, id, NULL, isjson);
  1552. return;
  1553. }
  1554. #endif
  1555. message(io_data, MSG_PGAENA, id, NULL, isjson);
  1556. }
  1557. static void pgadisable(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1558. {
  1559. struct cgpu_info *cgpu, *proc;
  1560. int id, dev;
  1561. bool already;
  1562. cgpu = get_pga_cgpu(io_data, c, param, isjson, group, &id, &dev);
  1563. if (!cgpu)
  1564. return;
  1565. applog(LOG_DEBUG, "API: request to pgadisable %s id %d device %d %s",
  1566. per_proc ? "proc" : "dev", id, dev, cgpu->proc_repr_ns);
  1567. already = true;
  1568. int procs = per_proc ? 1 : cgpu->procs, i;
  1569. for (i = 0, proc = cgpu; i < procs; ++i, proc = proc->next_proc)
  1570. {
  1571. if (proc->deven != DEV_DISABLED)
  1572. {
  1573. cgpu->deven = DEV_DISABLED;
  1574. already = false;
  1575. }
  1576. }
  1577. if (already)
  1578. {
  1579. message(io_data, MSG_PGALRDIS, id, NULL, isjson);
  1580. return;
  1581. }
  1582. message(io_data, MSG_PGADIS, id, NULL, isjson);
  1583. }
  1584. static void pgarestart(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1585. {
  1586. struct cgpu_info *cgpu;
  1587. int id, dev;
  1588. cgpu = get_pga_cgpu(io_data, c, param, isjson, group, &id, &dev);
  1589. if (!cgpu)
  1590. return;
  1591. applog(LOG_DEBUG, "API: request to pgarestart dev id %d device %d %s",
  1592. id, dev, cgpu->dev_repr);
  1593. reinit_device(cgpu);
  1594. message(io_data, MSG_PGAREI, id, NULL, isjson);
  1595. }
  1596. static void pgaidentify(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1597. {
  1598. struct cgpu_info *cgpu;
  1599. struct device_drv *drv;
  1600. int id, dev;
  1601. cgpu = get_pga_cgpu(io_data, c, param, isjson, group, &id, &dev);
  1602. if (!cgpu)
  1603. return;
  1604. drv = cgpu->drv;
  1605. if (drv->identify_device && drv->identify_device(cgpu))
  1606. message(io_data, MSG_PGAIDENT, id, NULL, isjson);
  1607. else
  1608. message(io_data, MSG_PGANOID, id, NULL, isjson);
  1609. }
  1610. #endif
  1611. #ifdef USE_CPUMINING
  1612. static void cpudev(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1613. {
  1614. bool io_open = false;
  1615. int id;
  1616. if (opt_n_threads <= 0)
  1617. {
  1618. message(io_data, MSG_CPUNON, 0, NULL, isjson);
  1619. return;
  1620. }
  1621. if (param == NULL || *param == '\0') {
  1622. message(io_data, MSG_MISID, 0, NULL, isjson);
  1623. return;
  1624. }
  1625. id = atoi(param);
  1626. if (id < 0 || id >= num_processors) {
  1627. message(io_data, MSG_INVCPU, id, NULL, isjson);
  1628. return;
  1629. }
  1630. message(io_data, MSG_CPUDEV, id, NULL, isjson);
  1631. if (isjson)
  1632. io_open = io_add(io_data, COMSTR JSON_CPU);
  1633. cpustatus(io_data, id, isjson, false);
  1634. if (isjson && io_open)
  1635. io_close(io_data);
  1636. }
  1637. #endif
  1638. static void poolstatus(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1639. {
  1640. struct api_data *root = NULL;
  1641. char buf[TMPBUFSIZ];
  1642. bool io_open = false;
  1643. char *status, *lp;
  1644. int i;
  1645. if (total_pools == 0) {
  1646. message(io_data, MSG_NOPOOL, 0, NULL, isjson);
  1647. return;
  1648. }
  1649. message(io_data, MSG_POOL, 0, NULL, isjson);
  1650. if (isjson)
  1651. io_open = io_add(io_data, COMSTR JSON_POOLS);
  1652. for (i = 0; i < total_pools; i++) {
  1653. struct pool *pool = pools[i];
  1654. if (pool->removed)
  1655. continue;
  1656. switch (pool->enabled) {
  1657. case POOL_DISABLED:
  1658. status = (char *)DISABLED;
  1659. break;
  1660. case POOL_REJECTING:
  1661. status = (char *)REJECTING;
  1662. break;
  1663. case POOL_ENABLED:
  1664. if (pool->idle)
  1665. status = (char *)DEAD;
  1666. else
  1667. if (pool->failover_only)
  1668. status = "Failover";
  1669. else
  1670. status = (char *)ALIVE;
  1671. break;
  1672. default:
  1673. status = (char *)UNKNOWN;
  1674. break;
  1675. }
  1676. if (pool->hdr_path)
  1677. lp = (char *)YES;
  1678. else
  1679. lp = (char *)NO;
  1680. root = api_add_int(root, "POOL", &i, false);
  1681. root = api_add_escape(root, "URL", pool->rpc_url, false);
  1682. root = api_add_string(root, "Status", status, false);
  1683. root = api_add_int(root, "Priority", &(pool->prio), false);
  1684. root = api_add_int(root, "Quota", &pool->quota, false);
  1685. root = api_add_string(root, "Mining Goal", pool->goal->name, false);
  1686. root = api_add_string(root, "Long Poll", lp, false);
  1687. root = api_add_uint(root, "Getworks", &(pool->getwork_requested), false);
  1688. root = api_add_int(root, "Accepted", &(pool->accepted), false);
  1689. root = api_add_int(root, "Rejected", &(pool->rejected), false);
  1690. root = api_add_int(root, "Works", &pool->works, false);
  1691. root = api_add_uint(root, "Discarded", &(pool->discarded_work), false);
  1692. root = api_add_uint(root, "Stale", &(pool->stale_shares), false);
  1693. root = api_add_uint(root, "Get Failures", &(pool->getfail_occasions), false);
  1694. root = api_add_uint(root, "Remote Failures", &(pool->remotefail_occasions), false);
  1695. root = api_add_escape(root, "User", pool->rpc_user, false);
  1696. root = api_add_time(root, "Last Share Time", &(pool->last_share_time), false);
  1697. root = api_add_diff(root, "Diff1 Shares", &(pool->diff1), false);
  1698. if (pool->rpc_proxy) {
  1699. root = api_add_escape(root, "Proxy", pool->rpc_proxy, false);
  1700. } else {
  1701. root = api_add_const(root, "Proxy", BLANK, false);
  1702. }
  1703. root = api_add_diff(root, "Difficulty Accepted", &(pool->diff_accepted), false);
  1704. root = api_add_diff(root, "Difficulty Rejected", &(pool->diff_rejected), false);
  1705. root = api_add_diff(root, "Difficulty Stale", &(pool->diff_stale), false);
  1706. root = api_add_diff(root, "Last Share Difficulty", &(pool->last_share_diff), false);
  1707. root = api_add_bool(root, "Has Stratum", &(pool->has_stratum), false);
  1708. root = api_add_bool(root, "Stratum Active", &(pool->stratum_active), false);
  1709. if (pool->stratum_active)
  1710. root = api_add_escape(root, "Stratum URL", pool->stratum_url, false);
  1711. else
  1712. root = api_add_const(root, "Stratum URL", BLANK, false);
  1713. root = api_add_diff(root, "Best Share", &(pool->best_diff), true);
  1714. if (pool->admin_msg)
  1715. root = api_add_escape(root, "Message", pool->admin_msg, true);
  1716. double rejp = (pool->diff_accepted + pool->diff_rejected + pool->diff_stale) ?
  1717. (double)(pool->diff_rejected) / (double)(pool->diff_accepted + pool->diff_rejected + pool->diff_stale) : 0;
  1718. root = api_add_percent(root, "Pool Rejected%", &rejp, false);
  1719. double stalep = (pool->diff_accepted + pool->diff_rejected + pool->diff_stale) ?
  1720. (double)(pool->diff_stale) / (double)(pool->diff_accepted + pool->diff_rejected + pool->diff_stale) : 0;
  1721. root = api_add_percent(root, "Pool Stale%", &stalep, false);
  1722. root = print_data(root, buf, isjson, isjson && (i > 0));
  1723. io_add(io_data, buf);
  1724. }
  1725. if (isjson && io_open)
  1726. io_close(io_data);
  1727. }
  1728. static void summary(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1729. {
  1730. struct api_data *root = NULL;
  1731. char buf[TMPBUFSIZ];
  1732. bool io_open;
  1733. double utility, mhs, work_utility;
  1734. message(io_data, MSG_SUMM, 0, NULL, isjson);
  1735. io_open = io_add(io_data, isjson ? COMSTR JSON_SUMMARY : _SUMMARY COMSTR);
  1736. // stop hashmeter() changing some while copying
  1737. mutex_lock(&hash_lock);
  1738. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1739. mhs = total_mhashes_done / total_secs;
  1740. work_utility = total_diff1 / ( total_secs ? total_secs : 1 ) * 60;
  1741. root = api_add_elapsed(root, "Elapsed", &(total_secs), true);
  1742. #if defined(USE_CPUMINING) && defined(USE_SHA256D)
  1743. if (opt_n_threads > 0)
  1744. root = api_add_string(root, "Algorithm", (algo_names[opt_algo] ?: NULLSTR), false);
  1745. #endif
  1746. root = api_add_mhs(root, "MHS av", &(mhs), false);
  1747. char mhsname[27];
  1748. sprintf(mhsname, "MHS %ds", opt_log_interval);
  1749. root = api_add_mhs(root, mhsname, &(total_rolling), false);
  1750. root = api_add_uint(root, "Found Blocks", &(found_blocks), true);
  1751. root = api_add_int(root, "Getworks", &(total_getworks), true);
  1752. root = api_add_int(root, "Accepted", &(total_accepted), true);
  1753. root = api_add_int(root, "Rejected", &(total_rejected), true);
  1754. root = api_add_int(root, "Hardware Errors", &(hw_errors), true);
  1755. root = api_add_utility(root, "Utility", &(utility), false);
  1756. root = api_add_int(root, "Discarded", &(total_discarded), true);
  1757. root = api_add_int(root, "Stale", &(total_stale), true);
  1758. root = api_add_uint(root, "Get Failures", &(total_go), true);
  1759. root = api_add_uint(root, "Local Work", &(local_work), true);
  1760. root = api_add_uint(root, "Remote Failures", &(total_ro), true);
  1761. root = api_add_uint(root, "Network Blocks", &(new_blocks), true);
  1762. root = api_add_mhtotal(root, "Total MH", &(total_mhashes_done), true);
  1763. root = api_add_diff(root, "Diff1 Work", &total_diff1, true);
  1764. root = api_add_utility(root, "Work Utility", &(work_utility), false);
  1765. root = api_add_diff(root, "Difficulty Accepted", &(total_diff_accepted), true);
  1766. root = api_add_diff(root, "Difficulty Rejected", &(total_diff_rejected), true);
  1767. root = api_add_diff(root, "Difficulty Stale", &(total_diff_stale), true);
  1768. root = api_add_diff(root, "Best Share", &(best_diff), true);
  1769. double hwp = (total_bad_diff1 + total_diff1) ?
  1770. (double)(total_bad_diff1) / (double)(total_bad_diff1 + total_diff1) : 0;
  1771. root = api_add_percent(root, "Device Hardware%", &hwp, false);
  1772. double rejp = total_diff1 ?
  1773. (double)(total_diff_rejected) / (double)(total_diff1) : 0;
  1774. root = api_add_percent(root, "Device Rejected%", &rejp, false);
  1775. double prejp = (total_diff_accepted + total_diff_rejected + total_diff_stale) ?
  1776. (double)(total_diff_rejected) / (double)(total_diff_accepted + total_diff_rejected + total_diff_stale) : 0;
  1777. root = api_add_percent(root, "Pool Rejected%", &prejp, false);
  1778. double stalep = (total_diff_accepted + total_diff_rejected + total_diff_stale) ?
  1779. (double)(total_diff_stale) / (double)(total_diff_accepted + total_diff_rejected + total_diff_stale) : 0;
  1780. root = api_add_percent(root, "Pool Stale%", &stalep, false);
  1781. root = api_add_time(root, "Last getwork", &last_getwork, false);
  1782. mutex_unlock(&hash_lock);
  1783. root = print_data(root, buf, isjson, false);
  1784. io_add(io_data, buf);
  1785. if (isjson && io_open)
  1786. io_close(io_data);
  1787. }
  1788. #ifdef USE_OPENCL
  1789. static void gpuenable(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1790. {
  1791. int id;
  1792. if (!nDevs) {
  1793. message(io_data, MSG_GPUNON, 0, NULL, isjson);
  1794. return;
  1795. }
  1796. if (param == NULL || *param == '\0') {
  1797. message(io_data, MSG_MISID, 0, NULL, isjson);
  1798. return;
  1799. }
  1800. id = atoi(param);
  1801. if (id < 0 || id >= nDevs) {
  1802. message(io_data, MSG_INVGPU, id, NULL, isjson);
  1803. return;
  1804. }
  1805. applog(LOG_DEBUG, "API: request to gpuenable gpuid %d %s",
  1806. id, gpus[id].proc_repr_ns);
  1807. if (gpus[id].deven != DEV_DISABLED) {
  1808. message(io_data, MSG_ALRENA, id, NULL, isjson);
  1809. return;
  1810. }
  1811. if (gpus[id].status != LIFE_WELL)
  1812. {
  1813. message(io_data, MSG_GPUMRE, id, NULL, isjson);
  1814. return;
  1815. }
  1816. proc_enable(&gpus[id]);
  1817. message(io_data, MSG_GPUREN, id, NULL, isjson);
  1818. }
  1819. static void gpudisable(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1820. {
  1821. int id;
  1822. if (nDevs == 0) {
  1823. message(io_data, MSG_GPUNON, 0, NULL, isjson);
  1824. return;
  1825. }
  1826. if (param == NULL || *param == '\0') {
  1827. message(io_data, MSG_MISID, 0, NULL, isjson);
  1828. return;
  1829. }
  1830. id = atoi(param);
  1831. if (id < 0 || id >= nDevs) {
  1832. message(io_data, MSG_INVGPU, id, NULL, isjson);
  1833. return;
  1834. }
  1835. applog(LOG_DEBUG, "API: request to gpudisable gpuid %d %s",
  1836. id, gpus[id].proc_repr_ns);
  1837. if (gpus[id].deven == DEV_DISABLED) {
  1838. message(io_data, MSG_ALRDIS, id, NULL, isjson);
  1839. return;
  1840. }
  1841. gpus[id].deven = DEV_DISABLED;
  1842. message(io_data, MSG_GPUDIS, id, NULL, isjson);
  1843. }
  1844. static void gpurestart(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1845. {
  1846. int id;
  1847. if (nDevs == 0) {
  1848. message(io_data, MSG_GPUNON, 0, NULL, isjson);
  1849. return;
  1850. }
  1851. if (param == NULL || *param == '\0') {
  1852. message(io_data, MSG_MISID, 0, NULL, isjson);
  1853. return;
  1854. }
  1855. id = atoi(param);
  1856. if (id < 0 || id >= nDevs) {
  1857. message(io_data, MSG_INVGPU, id, NULL, isjson);
  1858. return;
  1859. }
  1860. reinit_device(&gpus[id]);
  1861. message(io_data, MSG_GPUREI, id, NULL, isjson);
  1862. }
  1863. #endif
  1864. static void gpucount(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1865. {
  1866. struct api_data *root = NULL;
  1867. char buf[TMPBUFSIZ];
  1868. bool io_open;
  1869. int numgpu = 0;
  1870. #ifdef USE_OPENCL
  1871. numgpu = nDevs;
  1872. #endif
  1873. message(io_data, MSG_NUMGPU, 0, NULL, isjson);
  1874. io_open = io_add(io_data, isjson ? COMSTR JSON_GPUS : _GPUS COMSTR);
  1875. root = api_add_int(root, "Count", &numgpu, false);
  1876. root = print_data(root, buf, isjson, false);
  1877. io_add(io_data, buf);
  1878. if (isjson && io_open)
  1879. io_close(io_data);
  1880. }
  1881. static void pgacount(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1882. {
  1883. struct api_data *root = NULL;
  1884. char buf[TMPBUFSIZ];
  1885. bool io_open;
  1886. int count = 0;
  1887. #ifdef HAVE_AN_FPGA
  1888. count = numpgas();
  1889. #endif
  1890. message(io_data, MSG_NUMPGA, 0, NULL, isjson);
  1891. io_open = io_add(io_data, isjson ? COMSTR JSON_PGAS : _PGAS COMSTR);
  1892. root = api_add_int(root, "Count", &count, false);
  1893. root = print_data(root, buf, isjson, false);
  1894. io_add(io_data, buf);
  1895. if (isjson && io_open)
  1896. io_close(io_data);
  1897. }
  1898. #ifdef USE_CPUMINING
  1899. static void cpuenable(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1900. {
  1901. int id;
  1902. if (opt_n_threads <= 0)
  1903. {
  1904. message(io_data, MSG_CPUNON, 0, NULL, isjson);
  1905. return;
  1906. }
  1907. if (param == NULL || *param == '\0') {
  1908. message(io_data, MSG_MISID, 0, NULL, isjson);
  1909. return;
  1910. }
  1911. id = atoi(param);
  1912. if (id < 0 || id >= opt_n_threads) {
  1913. message(io_data, MSG_INVCPU, id, NULL, isjson);
  1914. return;
  1915. }
  1916. applog(LOG_DEBUG, "API: request to cpuenable cpuid %d %s",
  1917. id, cpus[id].proc_repr_ns);
  1918. if (cpus[id].deven != DEV_DISABLED) {
  1919. message(io_data, MSG_ALRENAC, id, NULL, isjson);
  1920. return;
  1921. }
  1922. if (cpus[id].status != LIFE_WELL)
  1923. {
  1924. message(io_data, MSG_CPUMRE, id, NULL, isjson);
  1925. return;
  1926. }
  1927. proc_enable(&cpus[id]);
  1928. message(io_data, MSG_CPUREN, id, NULL, isjson);
  1929. }
  1930. static void cpudisable(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1931. {
  1932. int id;
  1933. if (opt_n_threads <= 0)
  1934. {
  1935. message(io_data, MSG_CPUNON, 0, NULL, isjson);
  1936. return;
  1937. }
  1938. if (param == NULL || *param == '\0') {
  1939. message(io_data, MSG_MISID, 0, NULL, isjson);
  1940. return;
  1941. }
  1942. id = atoi(param);
  1943. if (id < 0 || id >= opt_n_threads) {
  1944. message(io_data, MSG_INVCPU, id, NULL, isjson);
  1945. return;
  1946. }
  1947. applog(LOG_DEBUG, "API: request to cpudisable cpuid %d %s",
  1948. id, cpus[id].proc_repr_ns);
  1949. if (cpus[id].deven == DEV_DISABLED) {
  1950. message(io_data, MSG_ALRDISC, id, NULL, isjson);
  1951. return;
  1952. }
  1953. cpus[id].deven = DEV_DISABLED;
  1954. message(io_data, MSG_CPUDIS, id, NULL, isjson);
  1955. }
  1956. static void cpurestart(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1957. {
  1958. int id;
  1959. if (opt_n_threads <= 0)
  1960. {
  1961. message(io_data, MSG_CPUNON, 0, NULL, isjson);
  1962. return;
  1963. }
  1964. if (param == NULL || *param == '\0') {
  1965. message(io_data, MSG_MISID, 0, NULL, isjson);
  1966. return;
  1967. }
  1968. id = atoi(param);
  1969. if (id < 0 || id >= opt_n_threads) {
  1970. message(io_data, MSG_INVCPU, id, NULL, isjson);
  1971. return;
  1972. }
  1973. reinit_device(&cpus[id]);
  1974. message(io_data, MSG_CPUREI, id, NULL, isjson);
  1975. }
  1976. #endif
  1977. static void cpucount(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  1978. {
  1979. struct api_data *root = NULL;
  1980. char buf[TMPBUFSIZ];
  1981. bool io_open;
  1982. int count = 0;
  1983. #ifdef USE_CPUMINING
  1984. count = opt_n_threads > 0 ? num_processors : 0;
  1985. #endif
  1986. message(io_data, MSG_NUMCPU, 0, NULL, isjson);
  1987. io_open = io_add(io_data, isjson ? COMSTR JSON_CPUS : _CPUS COMSTR);
  1988. root = api_add_int(root, "Count", &count, false);
  1989. root = print_data(root, buf, isjson, false);
  1990. io_add(io_data, buf);
  1991. if (isjson && io_open)
  1992. io_close(io_data);
  1993. }
  1994. static void switchpool(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  1995. {
  1996. struct pool *pool;
  1997. int id;
  1998. if (total_pools == 0) {
  1999. message(io_data, MSG_NOPOOL, 0, NULL, isjson);
  2000. return;
  2001. }
  2002. if (param == NULL || *param == '\0') {
  2003. message(io_data, MSG_MISPID, 0, NULL, isjson);
  2004. return;
  2005. }
  2006. id = atoi(param);
  2007. cg_rlock(&control_lock);
  2008. if (id < 0 || id >= total_pools) {
  2009. cg_runlock(&control_lock);
  2010. message(io_data, MSG_INVPID, id, NULL, isjson);
  2011. return;
  2012. }
  2013. pool = pools[id];
  2014. manual_enable_pool(pool);
  2015. cg_runlock(&control_lock);
  2016. switch_pools(pool);
  2017. message(io_data, MSG_SWITCHP, id, NULL, isjson);
  2018. }
  2019. static void copyadvanceafter(char ch, char **param, char **buf)
  2020. {
  2021. #define src_p (*param)
  2022. #define dst_b (*buf)
  2023. while (*src_p && *src_p != ch) {
  2024. if (*src_p == '\\' && *(src_p+1) != '\0')
  2025. src_p++;
  2026. *(dst_b++) = *(src_p++);
  2027. }
  2028. if (*src_p)
  2029. src_p++;
  2030. *(dst_b++) = '\0';
  2031. }
  2032. static bool pooldetails(char *param, char **url, char **user, char **pass, char **goalname)
  2033. {
  2034. char *ptr, *buf;
  2035. ptr = buf = malloc(strlen(param)+1);
  2036. if (unlikely(!buf))
  2037. quit(1, "Failed to malloc pooldetails buf");
  2038. *url = buf;
  2039. // copy url
  2040. copyadvanceafter(',', &param, &buf);
  2041. if (!(*param)) // missing user
  2042. goto exitsama;
  2043. *user = buf;
  2044. // copy user
  2045. copyadvanceafter(',', &param, &buf);
  2046. if (!*param) // missing pass
  2047. goto exitsama;
  2048. *pass = buf;
  2049. // copy pass
  2050. copyadvanceafter(',', &param, &buf);
  2051. if (*param)
  2052. *goalname = buf;
  2053. // copy goalname
  2054. copyadvanceafter(',', &param, &buf);
  2055. return true;
  2056. exitsama:
  2057. free(ptr);
  2058. return false;
  2059. }
  2060. static void addpool(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2061. {
  2062. char *url, *user, *pass, *goalname = "default";
  2063. struct pool *pool;
  2064. char *ptr;
  2065. if (param == NULL || *param == '\0') {
  2066. message(io_data, MSG_MISPDP, 0, NULL, isjson);
  2067. return;
  2068. }
  2069. if (!pooldetails(param, &url, &user, &pass, &goalname))
  2070. {
  2071. ptr = escape_string(param, isjson);
  2072. message(io_data, MSG_INVPDP, 0, ptr, isjson);
  2073. if (ptr != param)
  2074. free(ptr);
  2075. ptr = NULL;
  2076. return;
  2077. }
  2078. struct mining_goal_info * const goal = get_mining_goal(goalname);
  2079. pool = add_pool2(goal);
  2080. detect_stratum(pool, url);
  2081. add_pool_details(pool, true, url, user, pass);
  2082. ptr = escape_string(url, isjson);
  2083. message(io_data, MSG_ADDPOOL, 0, ptr, isjson);
  2084. if (ptr != url)
  2085. free(ptr);
  2086. ptr = NULL;
  2087. }
  2088. static void enablepool(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2089. {
  2090. struct pool *pool;
  2091. int id;
  2092. if (total_pools == 0) {
  2093. message(io_data, MSG_NOPOOL, 0, NULL, isjson);
  2094. return;
  2095. }
  2096. if (param == NULL || *param == '\0') {
  2097. message(io_data, MSG_MISPID, 0, NULL, isjson);
  2098. return;
  2099. }
  2100. id = atoi(param);
  2101. if (id < 0 || id >= total_pools) {
  2102. message(io_data, MSG_INVPID, id, NULL, isjson);
  2103. return;
  2104. }
  2105. pool = pools[id];
  2106. if (pool->enabled == POOL_ENABLED && !pool->failover_only) {
  2107. message(io_data, MSG_ALRENAP, id, NULL, isjson);
  2108. return;
  2109. }
  2110. manual_enable_pool(pool);
  2111. message(io_data, MSG_ENAPOOL, id, NULL, isjson);
  2112. }
  2113. static void poolpriority(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2114. {
  2115. int i;
  2116. switch (prioritize_pools(param, &i)) {
  2117. case MSG_NOPOOL:
  2118. message(io_data, MSG_NOPOOL, 0, NULL, isjson);
  2119. return;
  2120. case MSG_MISPID:
  2121. message(io_data, MSG_MISPID, 0, NULL, isjson);
  2122. return;
  2123. case MSG_INVPID:
  2124. message(io_data, MSG_INVPID, i, NULL, isjson);
  2125. return;
  2126. case MSG_DUPPID:
  2127. message(io_data, MSG_DUPPID, i, NULL, isjson);
  2128. return;
  2129. case MSG_POOLPRIO:
  2130. default:
  2131. message(io_data, MSG_POOLPRIO, 0, NULL, isjson);
  2132. return;
  2133. }
  2134. }
  2135. static void poolquota(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2136. {
  2137. struct pool *pool;
  2138. int quota, id;
  2139. char *comma;
  2140. if (total_pools == 0) {
  2141. message(io_data, MSG_NOPOOL, 0, NULL, isjson);
  2142. return;
  2143. }
  2144. if (param == NULL || *param == '\0') {
  2145. message(io_data, MSG_MISPID, 0, NULL, isjson);
  2146. return;
  2147. }
  2148. comma = strchr(param, ',');
  2149. if (!comma) {
  2150. message(io_data, MSG_CONVAL, 0, param, isjson);
  2151. return;
  2152. }
  2153. *(comma++) = '\0';
  2154. id = atoi(param);
  2155. if (id < 0 || id >= total_pools) {
  2156. message(io_data, MSG_INVPID, id, NULL, isjson);
  2157. return;
  2158. }
  2159. pool = pools[id];
  2160. quota = atoi(comma);
  2161. if (quota < 0) {
  2162. message(io_data, MSG_INVNEG, quota, pool->rpc_url, isjson);
  2163. return;
  2164. }
  2165. pool->quota = quota;
  2166. adjust_quota_gcd();
  2167. message(io_data, MSG_SETQUOTA, quota, pool->rpc_url, isjson);
  2168. }
  2169. static void disablepool(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2170. {
  2171. struct pool *pool;
  2172. int id;
  2173. if (total_pools == 0) {
  2174. message(io_data, MSG_NOPOOL, 0, NULL, isjson);
  2175. return;
  2176. }
  2177. if (param == NULL || *param == '\0') {
  2178. message(io_data, MSG_MISPID, 0, NULL, isjson);
  2179. return;
  2180. }
  2181. id = atoi(param);
  2182. if (id < 0 || id >= total_pools) {
  2183. message(io_data, MSG_INVPID, id, NULL, isjson);
  2184. return;
  2185. }
  2186. pool = pools[id];
  2187. if (pool->enabled == POOL_DISABLED) {
  2188. message(io_data, MSG_ALRDISP, id, NULL, isjson);
  2189. return;
  2190. }
  2191. if (enabled_pools <= 1) {
  2192. message(io_data, MSG_DISLASTP, id, NULL, isjson);
  2193. return;
  2194. }
  2195. disable_pool(pool, POOL_DISABLED);
  2196. message(io_data, MSG_DISPOOL, id, NULL, isjson);
  2197. }
  2198. static void removepool(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2199. {
  2200. struct pool *pool;
  2201. char *rpc_url;
  2202. bool dofree = false;
  2203. int id;
  2204. if (total_pools == 0) {
  2205. message(io_data, MSG_NOPOOL, 0, NULL, isjson);
  2206. return;
  2207. }
  2208. if (param == NULL || *param == '\0') {
  2209. message(io_data, MSG_MISPID, 0, NULL, isjson);
  2210. return;
  2211. }
  2212. id = atoi(param);
  2213. if (id < 0 || id >= total_pools) {
  2214. message(io_data, MSG_INVPID, id, NULL, isjson);
  2215. return;
  2216. }
  2217. if (total_pools <= 1) {
  2218. message(io_data, MSG_REMLASTP, id, NULL, isjson);
  2219. return;
  2220. }
  2221. pool = pools[id];
  2222. if (pool == current_pool())
  2223. switch_pools(NULL);
  2224. if (pool == current_pool()) {
  2225. message(io_data, MSG_ACTPOOL, id, NULL, isjson);
  2226. return;
  2227. }
  2228. rpc_url = escape_string(pool->rpc_url, isjson);
  2229. if (rpc_url != pool->rpc_url)
  2230. dofree = true;
  2231. remove_pool(pool);
  2232. message(io_data, MSG_REMPOOL, id, rpc_url, isjson);
  2233. if (dofree)
  2234. free(rpc_url);
  2235. rpc_url = NULL;
  2236. }
  2237. #ifdef USE_OPENCL
  2238. static bool splitgpuvalue(struct io_data *io_data, char *param, int *gpu, char **value, bool isjson)
  2239. {
  2240. int id;
  2241. char *gpusep;
  2242. if (nDevs == 0) {
  2243. message(io_data, MSG_GPUNON, 0, NULL, isjson);
  2244. return false;
  2245. }
  2246. if (param == NULL || *param == '\0') {
  2247. message(io_data, MSG_MISID, 0, NULL, isjson);
  2248. return false;
  2249. }
  2250. gpusep = strchr(param, GPUSEP);
  2251. if (gpusep == NULL) {
  2252. message(io_data, MSG_MISVAL, 0, NULL, isjson);
  2253. return false;
  2254. }
  2255. *(gpusep++) = '\0';
  2256. id = atoi(param);
  2257. if (id < 0 || id >= nDevs) {
  2258. message(io_data, MSG_INVGPU, id, NULL, isjson);
  2259. return false;
  2260. }
  2261. *gpu = id;
  2262. *value = gpusep;
  2263. return true;
  2264. }
  2265. static void gpuintensity(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2266. {
  2267. int id;
  2268. char *value;
  2269. char intensitystr[7];
  2270. char buf[TMPBUFSIZ];
  2271. if (!splitgpuvalue(io_data, param, &id, &value, isjson))
  2272. return;
  2273. struct cgpu_info * const cgpu = &gpus[id];
  2274. struct opencl_device_data * const data = gpus[id].device_data;
  2275. enum bfg_set_device_replytype success;
  2276. proc_set_device(cgpu, "intensity", value, buf, &success);
  2277. if (success == SDR_OK)
  2278. {
  2279. if (data->dynamic)
  2280. strcpy(intensitystr, DYNAMIC);
  2281. else
  2282. {
  2283. const char *iunit;
  2284. float intensity = opencl_proc_get_intensity(cgpu, &iunit);
  2285. snprintf(intensitystr, sizeof(intensitystr), "%s%g", iunit, intensity);
  2286. }
  2287. }
  2288. else
  2289. {
  2290. message(io_data, MSG_INVINT, 0, value, isjson);
  2291. return;
  2292. }
  2293. message(io_data, MSG_GPUINT, id, intensitystr, isjson);
  2294. }
  2295. static void gpumem(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2296. {
  2297. #ifdef HAVE_ADL
  2298. int id;
  2299. char *value;
  2300. char buf[TMPBUFSIZ];
  2301. if (!splitgpuvalue(io_data, param, &id, &value, isjson))
  2302. return;
  2303. struct cgpu_info * const cgpu = &gpus[id];
  2304. enum bfg_set_device_replytype success;
  2305. proc_set_device(cgpu, "memclock", value, buf, &success);
  2306. if (success != SDR_OK)
  2307. message(io_data, MSG_GPUMERR, id, value, isjson);
  2308. else
  2309. message(io_data, MSG_GPUMEM, id, value, isjson);
  2310. #else
  2311. message(io_data, MSG_NOADL, 0, NULL, isjson);
  2312. #endif
  2313. }
  2314. static void gpuengine(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2315. {
  2316. #ifdef HAVE_ADL
  2317. int id;
  2318. char *value;
  2319. char buf[TMPBUFSIZ];
  2320. if (!splitgpuvalue(io_data, param, &id, &value, isjson))
  2321. return;
  2322. struct cgpu_info * const cgpu = &gpus[id];
  2323. enum bfg_set_device_replytype success;
  2324. proc_set_device(cgpu, "clock", value, buf, &success);
  2325. if (success != SDR_OK)
  2326. message(io_data, MSG_GPUEERR, id, value, isjson);
  2327. else
  2328. message(io_data, MSG_GPUENG, id, value, isjson);
  2329. #else
  2330. message(io_data, MSG_NOADL, 0, NULL, isjson);
  2331. #endif
  2332. }
  2333. static void gpufan(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2334. {
  2335. #ifdef HAVE_ADL
  2336. int id;
  2337. char *value;
  2338. char buf[TMPBUFSIZ];
  2339. if (!splitgpuvalue(io_data, param, &id, &value, isjson))
  2340. return;
  2341. struct cgpu_info * const cgpu = &gpus[id];
  2342. enum bfg_set_device_replytype success;
  2343. proc_set_device(cgpu, "fan", value, buf, &success);
  2344. if (success != SDR_OK)
  2345. message(io_data, MSG_GPUFERR, id, value, isjson);
  2346. else
  2347. message(io_data, MSG_GPUFAN, id, value, isjson);
  2348. #else
  2349. message(io_data, MSG_NOADL, 0, NULL, isjson);
  2350. #endif
  2351. }
  2352. static void gpuvddc(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2353. {
  2354. #ifdef HAVE_ADL
  2355. int id;
  2356. char *value;
  2357. char buf[TMPBUFSIZ];
  2358. if (!splitgpuvalue(io_data, param, &id, &value, isjson))
  2359. return;
  2360. struct cgpu_info * const cgpu = &gpus[id];
  2361. enum bfg_set_device_replytype success;
  2362. proc_set_device(cgpu, "voltage", value, buf, &success);
  2363. if (success != SDR_OK)
  2364. message(io_data, MSG_GPUVERR, id, value, isjson);
  2365. else
  2366. message(io_data, MSG_GPUVDDC, id, value, isjson);
  2367. #else
  2368. message(io_data, MSG_NOADL, 0, NULL, isjson);
  2369. #endif
  2370. }
  2371. #endif
  2372. void doquit(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2373. {
  2374. message(io_data, MSG_BYE, 0, _BYE, isjson);
  2375. bye = true;
  2376. do_a_quit = true;
  2377. }
  2378. void dorestart(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2379. {
  2380. message(io_data, MSG_BYE, 0, _RESTART, isjson);
  2381. bye = true;
  2382. do_a_restart = true;
  2383. }
  2384. void privileged(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2385. {
  2386. message(io_data, MSG_ACCOK, 0, NULL, isjson);
  2387. }
  2388. void notifystatus(struct io_data *io_data, int device, struct cgpu_info *cgpu, bool isjson, __maybe_unused char group)
  2389. {
  2390. struct cgpu_info *proc;
  2391. struct api_data *root = NULL;
  2392. char buf[TMPBUFSIZ];
  2393. char *reason;
  2394. time_t last_not_well = 0;
  2395. enum dev_reason uninitialised_var(enum_reason);
  2396. int thread_fail_init_count = 0, thread_zero_hash_count = 0, thread_fail_queue_count = 0;
  2397. int dev_sick_idle_60_count = 0, dev_dead_idle_600_count = 0;
  2398. int dev_nostart_count = 0, dev_over_heat_count = 0, dev_thermal_cutoff_count = 0, dev_comms_error_count = 0, dev_throttle_count = 0;
  2399. int procs = per_proc ? 1 : cgpu->procs, i;
  2400. for (i = 0, proc = cgpu; i < procs; ++i, proc = proc->next_proc)
  2401. {
  2402. if (proc->device_last_not_well > last_not_well)
  2403. {
  2404. last_not_well = proc->device_last_not_well;
  2405. enum_reason = proc->device_not_well_reason;
  2406. thread_fail_init_count += proc->thread_fail_init_count;
  2407. thread_zero_hash_count += proc->thread_zero_hash_count;
  2408. thread_fail_queue_count += proc->thread_fail_queue_count;
  2409. dev_sick_idle_60_count += proc->dev_sick_idle_60_count;
  2410. dev_dead_idle_600_count += proc->dev_dead_idle_600_count;
  2411. dev_nostart_count += proc->dev_nostart_count;
  2412. dev_over_heat_count += proc->dev_over_heat_count;
  2413. dev_thermal_cutoff_count += proc->dev_thermal_cutoff_count;
  2414. dev_comms_error_count += proc->dev_comms_error_count;
  2415. dev_throttle_count += proc->dev_throttle_count;
  2416. }
  2417. if (per_proc)
  2418. break;
  2419. }
  2420. if (last_not_well == 0)
  2421. reason = REASON_NONE;
  2422. else
  2423. switch (enum_reason)
  2424. {
  2425. case REASON_THREAD_FAIL_INIT:
  2426. reason = REASON_THREAD_FAIL_INIT_STR;
  2427. break;
  2428. case REASON_THREAD_ZERO_HASH:
  2429. reason = REASON_THREAD_ZERO_HASH_STR;
  2430. break;
  2431. case REASON_THREAD_FAIL_QUEUE:
  2432. reason = REASON_THREAD_FAIL_QUEUE_STR;
  2433. break;
  2434. case REASON_DEV_SICK_IDLE_60:
  2435. reason = REASON_DEV_SICK_IDLE_60_STR;
  2436. break;
  2437. case REASON_DEV_DEAD_IDLE_600:
  2438. reason = REASON_DEV_DEAD_IDLE_600_STR;
  2439. break;
  2440. case REASON_DEV_NOSTART:
  2441. reason = REASON_DEV_NOSTART_STR;
  2442. break;
  2443. case REASON_DEV_OVER_HEAT:
  2444. reason = REASON_DEV_OVER_HEAT_STR;
  2445. break;
  2446. case REASON_DEV_THERMAL_CUTOFF:
  2447. reason = REASON_DEV_THERMAL_CUTOFF_STR;
  2448. break;
  2449. case REASON_DEV_COMMS_ERROR:
  2450. reason = REASON_DEV_COMMS_ERROR_STR;
  2451. break;
  2452. default:
  2453. reason = REASON_UNKNOWN_STR;
  2454. break;
  2455. }
  2456. // ALL counters (and only counters) must start the name with a '*'
  2457. // Simplifies future external support for identifying new counters
  2458. root = api_add_int(root, "NOTIFY", &device, false);
  2459. root = api_add_device_identifier(root, cgpu);
  2460. if (per_proc)
  2461. root = api_add_time(root, "Last Well", &(cgpu->device_last_well), false);
  2462. root = api_add_time(root, "Last Not Well", &last_not_well, false);
  2463. root = api_add_string(root, "Reason Not Well", reason, false);
  2464. root = api_add_int(root, "*Thread Fail Init", &thread_fail_init_count, false);
  2465. root = api_add_int(root, "*Thread Zero Hash", &thread_zero_hash_count, false);
  2466. root = api_add_int(root, "*Thread Fail Queue", &thread_fail_queue_count, false);
  2467. root = api_add_int(root, "*Dev Sick Idle 60s", &dev_sick_idle_60_count, false);
  2468. root = api_add_int(root, "*Dev Dead Idle 600s", &dev_dead_idle_600_count, false);
  2469. root = api_add_int(root, "*Dev Nostart", &dev_nostart_count, false);
  2470. root = api_add_int(root, "*Dev Over Heat", &dev_over_heat_count, false);
  2471. root = api_add_int(root, "*Dev Thermal Cutoff", &dev_thermal_cutoff_count, false);
  2472. root = api_add_int(root, "*Dev Comms Error", &dev_comms_error_count, false);
  2473. root = api_add_int(root, "*Dev Throttle", &dev_throttle_count, false);
  2474. root = print_data(root, buf, isjson, isjson && (device > 0));
  2475. io_add(io_data, buf);
  2476. }
  2477. static
  2478. void notify(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, char group)
  2479. {
  2480. struct cgpu_info *cgpu;
  2481. bool io_open = false;
  2482. int i, n = 0;
  2483. if (total_devices == 0) {
  2484. message(io_data, MSG_NODEVS, 0, NULL, isjson);
  2485. return;
  2486. }
  2487. message(io_data, MSG_NOTIFY, 0, NULL, isjson);
  2488. if (isjson)
  2489. io_open = io_add(io_data, COMSTR JSON_NOTIFY);
  2490. for (i = 0; i < total_devices; i++) {
  2491. cgpu = get_devices(i);
  2492. if (cgpu->device == cgpu || per_proc)
  2493. notifystatus(io_data, n++, cgpu, isjson, group);
  2494. }
  2495. if (isjson && io_open)
  2496. io_close(io_data);
  2497. }
  2498. void dosave(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2499. {
  2500. char filename[PATH_MAX];
  2501. FILE *fcfg;
  2502. char *ptr;
  2503. if (param == NULL || *param == '\0') {
  2504. default_save_file(filename);
  2505. param = filename;
  2506. }
  2507. fcfg = fopen(param, "w");
  2508. if (!fcfg) {
  2509. ptr = escape_string(param, isjson);
  2510. message(io_data, MSG_BADFN, 0, ptr, isjson);
  2511. if (ptr != param)
  2512. free(ptr);
  2513. ptr = NULL;
  2514. return;
  2515. }
  2516. write_config(fcfg);
  2517. fclose(fcfg);
  2518. ptr = escape_string(param, isjson);
  2519. message(io_data, MSG_SAVED, 0, ptr, isjson);
  2520. if (ptr != param)
  2521. free(ptr);
  2522. ptr = NULL;
  2523. }
  2524. static int itemstats(struct io_data *io_data, int i, char *id, struct cgminer_stats *stats, struct cgminer_pool_stats *pool_stats, struct api_data *extra, bool isjson)
  2525. {
  2526. struct api_data *root = NULL;
  2527. char buf[TMPBUFSIZ];
  2528. double elapsed;
  2529. root = api_add_int(root, "STATS", &i, false);
  2530. root = api_add_string(root, "ID", id, false);
  2531. elapsed = stats_elapsed(stats);
  2532. root = api_add_elapsed(root, "Elapsed", &elapsed, false);
  2533. root = api_add_uint32(root, "Calls", &(stats->getwork_calls), false);
  2534. root = api_add_timeval(root, "Wait", &(stats->getwork_wait), false);
  2535. root = api_add_timeval(root, "Max", &(stats->getwork_wait_max), false);
  2536. root = api_add_timeval(root, "Min", &(stats->getwork_wait_min), false);
  2537. if (pool_stats) {
  2538. root = api_add_uint32(root, "Pool Calls", &(pool_stats->getwork_calls), false);
  2539. root = api_add_uint32(root, "Pool Attempts", &(pool_stats->getwork_attempts), false);
  2540. root = api_add_timeval(root, "Pool Wait", &(pool_stats->getwork_wait), false);
  2541. root = api_add_timeval(root, "Pool Max", &(pool_stats->getwork_wait_max), false);
  2542. root = api_add_timeval(root, "Pool Min", &(pool_stats->getwork_wait_min), false);
  2543. root = api_add_double(root, "Pool Av", &(pool_stats->getwork_wait_rolling), false);
  2544. root = api_add_bool(root, "Work Had Roll Time", &(pool_stats->hadrolltime), false);
  2545. root = api_add_bool(root, "Work Can Roll", &(pool_stats->canroll), false);
  2546. root = api_add_bool(root, "Work Had Expire", &(pool_stats->hadexpire), false);
  2547. root = api_add_uint32(root, "Work Roll Time", &(pool_stats->rolltime), false);
  2548. root = api_add_diff(root, "Work Diff", &(pool_stats->last_diff), false);
  2549. root = api_add_diff(root, "Min Diff", &(pool_stats->min_diff), false);
  2550. root = api_add_diff(root, "Max Diff", &(pool_stats->max_diff), false);
  2551. root = api_add_uint32(root, "Min Diff Count", &(pool_stats->min_diff_count), false);
  2552. root = api_add_uint32(root, "Max Diff Count", &(pool_stats->max_diff_count), false);
  2553. root = api_add_uint64(root, "Times Sent", &(pool_stats->times_sent), false);
  2554. root = api_add_uint64(root, "Bytes Sent", &(pool_stats->bytes_sent), false);
  2555. root = api_add_uint64(root, "Times Recv", &(pool_stats->times_received), false);
  2556. root = api_add_uint64(root, "Bytes Recv", &(pool_stats->bytes_received), false);
  2557. root = api_add_uint64(root, "Net Bytes Sent", &(pool_stats->net_bytes_sent), false);
  2558. root = api_add_uint64(root, "Net Bytes Recv", &(pool_stats->net_bytes_received), false);
  2559. }
  2560. if (extra)
  2561. root = api_add_extra(root, extra);
  2562. root = print_data(root, buf, isjson, isjson && (i > 0));
  2563. io_add(io_data, buf);
  2564. return ++i;
  2565. }
  2566. static void minerstats(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2567. {
  2568. struct cgpu_info *cgpu;
  2569. bool io_open = false;
  2570. struct api_data *extra;
  2571. char id[20];
  2572. int i, j;
  2573. message(io_data, MSG_MINESTATS, 0, NULL, isjson);
  2574. if (isjson)
  2575. io_open = io_add(io_data, COMSTR JSON_MINESTATS);
  2576. i = 0;
  2577. for (j = 0; j < total_devices; j++) {
  2578. cgpu = get_devices(j);
  2579. if (cgpu && cgpu->drv) {
  2580. if (cgpu->drv->get_api_stats)
  2581. extra = cgpu->drv->get_api_stats(cgpu);
  2582. else
  2583. extra = NULL;
  2584. i = itemstats(io_data, i, cgpu->proc_repr_ns, &(cgpu->cgminer_stats), NULL, extra, isjson);
  2585. }
  2586. }
  2587. for (j = 0; j < total_pools; j++) {
  2588. struct pool *pool = pools[j];
  2589. sprintf(id, "POOL%d", j);
  2590. i = itemstats(io_data, i, id, &(pool->cgminer_stats), &(pool->cgminer_pool_stats), NULL, isjson);
  2591. }
  2592. if (isjson && io_open)
  2593. io_close(io_data);
  2594. }
  2595. static void failoveronly(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2596. {
  2597. if (param == NULL || *param == '\0') {
  2598. message(io_data, MSG_MISBOOL, 0, NULL, isjson);
  2599. return;
  2600. }
  2601. *param = tolower(*param);
  2602. if (*param != 't' && *param != 'f') {
  2603. message(io_data, MSG_INVBOOL, 0, NULL, isjson);
  2604. return;
  2605. }
  2606. bool tf = (*param == 't');
  2607. opt_fail_only = tf;
  2608. message(io_data, MSG_FOO, tf, NULL, isjson);
  2609. }
  2610. static void minecoin(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2611. {
  2612. struct api_data *root = NULL;
  2613. char buf[TMPBUFSIZ];
  2614. message(io_data, MSG_MINECOIN, 0, NULL, isjson);
  2615. struct mining_goal_info *goal, *tmpgoal;
  2616. bool precom = false;
  2617. HASH_ITER(hh, mining_goals, goal, tmpgoal)
  2618. {
  2619. if (goal->is_default)
  2620. io_add(io_data, isjson ? COMSTR JSON1 _MINECOIN JSON2 : _MINECOIN COMSTR);
  2621. else
  2622. {
  2623. sprintf(buf, isjson ? COMSTR JSON1 _MINECOIN "%u" JSON2 : _MINECOIN "%u" COMSTR, goal->id);
  2624. io_add(io_data, buf);
  2625. }
  2626. switch (goal->malgo->algo)
  2627. {
  2628. #ifdef USE_SCRYPT
  2629. case POW_SCRYPT:
  2630. root = api_add_const(root, "Hash Method", SCRYPTSTR, false);
  2631. break;
  2632. #endif
  2633. #ifdef USE_SHA256D
  2634. case POW_SHA256D:
  2635. root = api_add_const(root, "Hash Method", SHA256STR, false);
  2636. break;
  2637. #endif
  2638. default:
  2639. root = api_add_const(root, "Hash Method", goal->malgo->name, false);
  2640. break;
  2641. }
  2642. cg_rlock(&ch_lock);
  2643. struct blockchain_info * const blkchain = goal->blkchain;
  2644. struct block_info * const blkinfo = blkchain->currentblk;
  2645. root = api_add_time(root, "Current Block Time", &blkinfo->first_seen_time, true);
  2646. char fullhash[(sizeof(blkinfo->prevblkhash) * 2) + 1];
  2647. blkhashstr(fullhash, blkinfo->prevblkhash);
  2648. root = api_add_string(root, "Current Block Hash", fullhash, true);
  2649. cg_runlock(&ch_lock);
  2650. root = api_add_bool(root, "LP", &goal->have_longpoll, false);
  2651. root = api_add_diff(root, "Network Difficulty", &goal->current_diff, true);
  2652. root = api_add_diff(root, "Difficulty Accepted", &goal->diff_accepted, false);
  2653. root = print_data(root, buf, isjson, precom);
  2654. io_add(io_data, buf);
  2655. if (isjson)
  2656. io_add(io_data, JSON_CLOSE);
  2657. }
  2658. }
  2659. static void debugstate(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2660. {
  2661. struct api_data *root = NULL;
  2662. char buf[TMPBUFSIZ];
  2663. bool io_open;
  2664. if (param == NULL)
  2665. param = (char *)BLANK;
  2666. else
  2667. *param = tolower(*param);
  2668. switch(*param) {
  2669. case 's':
  2670. opt_realquiet = true;
  2671. break;
  2672. case 'q':
  2673. opt_quiet ^= true;
  2674. break;
  2675. case 'v':
  2676. opt_log_output ^= true;
  2677. if (opt_log_output)
  2678. opt_quiet = false;
  2679. break;
  2680. case 'd':
  2681. opt_debug ^= true;
  2682. opt_log_output = opt_debug;
  2683. if (opt_debug)
  2684. opt_quiet = false;
  2685. break;
  2686. case 'r':
  2687. opt_protocol ^= true;
  2688. if (opt_protocol)
  2689. opt_quiet = false;
  2690. break;
  2691. case 'p':
  2692. want_per_device_stats ^= true;
  2693. opt_log_output = want_per_device_stats;
  2694. break;
  2695. case 'n':
  2696. opt_log_output = false;
  2697. opt_debug = false;
  2698. opt_quiet = false;
  2699. opt_protocol = false;
  2700. want_per_device_stats = false;
  2701. opt_worktime = false;
  2702. break;
  2703. case 'w':
  2704. opt_worktime ^= true;
  2705. break;
  2706. #ifdef _MEMORY_DEBUG
  2707. case 'y':
  2708. cgmemspeedup();
  2709. break;
  2710. case 'z':
  2711. cgmemrpt();
  2712. break;
  2713. #endif
  2714. default:
  2715. // anything else just reports the settings
  2716. break;
  2717. }
  2718. message(io_data, MSG_DEBUGSET, 0, NULL, isjson);
  2719. io_open = io_add(io_data, isjson ? COMSTR JSON_DEBUGSET : _DEBUGSET COMSTR);
  2720. root = api_add_bool(root, "Silent", &opt_realquiet, false);
  2721. root = api_add_bool(root, "Quiet", &opt_quiet, false);
  2722. root = api_add_bool(root, "Verbose", &opt_log_output, false);
  2723. root = api_add_bool(root, "Debug", &opt_debug, false);
  2724. root = api_add_bool(root, "RPCProto", &opt_protocol, false);
  2725. root = api_add_bool(root, "PerDevice", &want_per_device_stats, false);
  2726. root = api_add_bool(root, "WorkTime", &opt_worktime, false);
  2727. root = print_data(root, buf, isjson, false);
  2728. io_add(io_data, buf);
  2729. if (isjson && io_open)
  2730. io_close(io_data);
  2731. }
  2732. extern bool stratumsrv_change_port(unsigned);
  2733. static void setconfig(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2734. {
  2735. char *comma;
  2736. long value;
  2737. if (param == NULL || *param == '\0') {
  2738. message(io_data, MSG_CONPAR, 0, NULL, isjson);
  2739. return;
  2740. }
  2741. comma = strchr(param, ',');
  2742. if (!comma) {
  2743. message(io_data, MSG_CONVAL, 0, param, isjson);
  2744. return;
  2745. }
  2746. *(comma++) = '\0';
  2747. #if BLKMAKER_VERSION > 0
  2748. if (strcasecmp(param, "coinbase-sig") == 0) {
  2749. free(opt_coinbase_sig);
  2750. opt_coinbase_sig = strdup(comma);
  2751. message(io_data, MSG_SETCONFIG, 1, param, isjson);
  2752. return;
  2753. }
  2754. else
  2755. #endif
  2756. if (strcasecmp(param, "strategy") == 0) {
  2757. char * const strategy_name = comma;
  2758. comma = strchr(strategy_name, ',');
  2759. if (comma) {
  2760. *(comma++) = '\0';
  2761. }
  2762. value = bfg_strategy_parse(strategy_name);
  2763. if (value < 0) {
  2764. message(io_data, MSG_INVSTRATEGY, 0, param, isjson);
  2765. return;
  2766. }
  2767. if (!bfg_strategy_change(value, comma)) {
  2768. message(io_data, MSG_INVNUM, atoi(comma), param, isjson);
  2769. return;
  2770. }
  2771. message(io_data, MSG_SETCONFIG, value, param, isjson);
  2772. return;
  2773. }
  2774. value = atol(comma);
  2775. if (value < 0 || value > 9999) {
  2776. message(io_data, MSG_INVNUM, value, param, isjson);
  2777. return;
  2778. }
  2779. if (strcasecmp(param, "queue") == 0)
  2780. opt_queue = value;
  2781. else if (strcasecmp(param, "scantime") == 0)
  2782. opt_scantime = value;
  2783. else if (strcasecmp(param, "expiry") == 0)
  2784. opt_expiry = value;
  2785. #ifdef USE_LIBMICROHTTPD
  2786. else if (strcasecmp(param, "http-port") == 0)
  2787. {
  2788. httpsrv_stop();
  2789. httpsrv_port = value;
  2790. if (httpsrv_port != -1)
  2791. httpsrv_start(httpsrv_port);
  2792. }
  2793. #endif
  2794. #ifdef USE_LIBEVENT
  2795. else if (strcasecmp(param, "stratum-port") == 0)
  2796. {
  2797. if (!stratumsrv_change_port(value)) {
  2798. message(io_data, MSG_FAILPORT, value, param, isjson);
  2799. return;
  2800. }
  2801. }
  2802. #endif
  2803. else {
  2804. message(io_data, MSG_UNKCON, 0, param, isjson);
  2805. return;
  2806. }
  2807. message(io_data, MSG_SETCONFIG, value, param, isjson);
  2808. }
  2809. #ifdef HAVE_AN_FPGA
  2810. static void pgaset(struct io_data *io_data, __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson, __maybe_unused char group)
  2811. {
  2812. struct cgpu_info *cgpu;
  2813. char buf[TMPBUFSIZ];
  2814. int numpga = numpgas();
  2815. if (numpga == 0) {
  2816. message(io_data, MSG_PGANON, 0, NULL, isjson);
  2817. return;
  2818. }
  2819. if (param == NULL || *param == '\0') {
  2820. message(io_data, MSG_MISID, 0, NULL, isjson);
  2821. return;
  2822. }
  2823. char *opt = strchr(param, ',');
  2824. if (opt)
  2825. *(opt++) = '\0';
  2826. if (!opt || !*opt) {
  2827. message(io_data, MSG_MISPGAOPT, 0, NULL, isjson);
  2828. return;
  2829. }
  2830. int id = atoi(param);
  2831. if (id < 0 || id >= numpga) {
  2832. message(io_data, MSG_INVPGA, id, NULL, isjson);
  2833. return;
  2834. }
  2835. int dev = pgadevice(id);
  2836. if (dev < 0) { // Should never happen
  2837. message(io_data, MSG_INVPGA, id, NULL, isjson);
  2838. return;
  2839. }
  2840. cgpu = get_devices(dev);
  2841. char *set = strchr(opt, ',');
  2842. if (set)
  2843. *(set++) = '\0';
  2844. enum bfg_set_device_replytype success;
  2845. const char *ret = proc_set_device(cgpu, opt, set, buf, &success);
  2846. switch (success)
  2847. {
  2848. case SDR_HELP:
  2849. message(io_data, MSG_PGAHELP, id, ret, isjson);
  2850. break;
  2851. case SDR_OK:
  2852. if (ret)
  2853. message(io_data, MSG_PGASETOK | USE_ALTMSG, id, ret, isjson);
  2854. else
  2855. message(io_data, MSG_PGASETOK, id, NULL, isjson);
  2856. break;
  2857. case SDR_UNKNOWN:
  2858. case SDR_ERR:
  2859. message(io_data, MSG_PGASETERR, id, ret, isjson);
  2860. break;
  2861. case SDR_AUTO:
  2862. case SDR_NOSUPP:
  2863. message(io_data, MSG_PGANOSET, id, NULL, isjson);
  2864. }
  2865. }
  2866. #endif
  2867. static void dozero(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, __maybe_unused char group)
  2868. {
  2869. if (param == NULL || *param == '\0') {
  2870. message(io_data, MSG_ZERMIS, 0, NULL, isjson);
  2871. return;
  2872. }
  2873. char *sum = strchr(param, ',');
  2874. if (sum)
  2875. *(sum++) = '\0';
  2876. if (!sum || !*sum) {
  2877. message(io_data, MSG_MISBOOL, 0, NULL, isjson);
  2878. return;
  2879. }
  2880. bool all = false;
  2881. bool bs = false;
  2882. if (strcasecmp(param, "all") == 0)
  2883. all = true;
  2884. else if (strcasecmp(param, "bestshare") == 0)
  2885. bs = true;
  2886. if (all == false && bs == false) {
  2887. message(io_data, MSG_ZERINV, 0, param, isjson);
  2888. return;
  2889. }
  2890. *sum = tolower(*sum);
  2891. if (*sum != 't' && *sum != 'f') {
  2892. message(io_data, MSG_INVBOOL, 0, NULL, isjson);
  2893. return;
  2894. }
  2895. bool dosum = (*sum == 't');
  2896. if (dosum)
  2897. print_summary();
  2898. if (all)
  2899. zero_stats();
  2900. if (bs)
  2901. zero_bestshare();
  2902. if (dosum)
  2903. message(io_data, MSG_ZERSUM, 0, all ? "All" : "BestShare", isjson);
  2904. else
  2905. message(io_data, MSG_ZERNOSUM, 0, all ? "All" : "BestShare", isjson);
  2906. }
  2907. static void checkcommand(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, char group);
  2908. struct CMDS {
  2909. char *name;
  2910. void (*func)(struct io_data *, SOCKETTYPE, char *, bool, char);
  2911. bool iswritemode;
  2912. bool joinable;
  2913. } cmds[] = {
  2914. { "version", apiversion, false, true },
  2915. { "config", minerconfig, false, true },
  2916. { "devscan", devscan, true, false },
  2917. { "devs", devstatus, false, true },
  2918. { "procs", devstatus, false, true },
  2919. { "pools", poolstatus, false, true },
  2920. { "summary", summary, false, true },
  2921. #ifdef USE_OPENCL
  2922. { "gpuenable", gpuenable, true, false },
  2923. { "gpudisable", gpudisable, true, false },
  2924. { "gpurestart", gpurestart, true, false },
  2925. { "gpu", gpudev, false, false },
  2926. #endif
  2927. #ifdef HAVE_AN_FPGA
  2928. { "pga", pgadev, false, false },
  2929. { "pgaenable", pgaenable, true, false },
  2930. { "pgadisable", pgadisable, true, false },
  2931. { "pgarestart", pgarestart, true, false },
  2932. { "pgaidentify", pgaidentify, true, false },
  2933. { "proc", pgadev, false, false },
  2934. { "procenable", pgaenable, true, false },
  2935. { "procdisable", pgadisable, true, false },
  2936. { "procidentify", pgaidentify, true, false },
  2937. #endif
  2938. #ifdef USE_CPUMINING
  2939. { "cpuenable", cpuenable, true, false },
  2940. { "cpudisable", cpudisable, true, false },
  2941. { "cpurestart", cpurestart, true, false },
  2942. { "cpu", cpudev, false, false },
  2943. #endif
  2944. { "gpucount", gpucount, false, true },
  2945. { "pgacount", pgacount, false, true },
  2946. { "proccount", pgacount, false, true },
  2947. { "cpucount", cpucount, false, true },
  2948. { "switchpool", switchpool, true, false },
  2949. { "addpool", addpool, true, false },
  2950. { "poolpriority", poolpriority, true, false },
  2951. { "poolquota", poolquota, true, false },
  2952. { "enablepool", enablepool, true, false },
  2953. { "disablepool", disablepool, true, false },
  2954. { "removepool", removepool, true, false },
  2955. #ifdef USE_OPENCL
  2956. { "gpuintensity", gpuintensity, true, false },
  2957. { "gpumem", gpumem, true, false },
  2958. { "gpuengine", gpuengine, true, false },
  2959. { "gpufan", gpufan, true, false },
  2960. { "gpuvddc", gpuvddc, true, false },
  2961. #endif
  2962. { "save", dosave, true, false },
  2963. { "quit", doquit, true, false },
  2964. { "privileged", privileged, true, false },
  2965. { "notify", notify, false, true },
  2966. { "procnotify", notify, false, true },
  2967. { "devdetails", devdetail, false, true },
  2968. { "procdetails", devdetail, false, true },
  2969. { "restart", dorestart, true, false },
  2970. { "stats", minerstats, false, true },
  2971. { "check", checkcommand, false, false },
  2972. { "failover-only", failoveronly, true, false },
  2973. { "coin", minecoin, false, true },
  2974. { "debug", debugstate, true, false },
  2975. { "setconfig", setconfig, true, false },
  2976. #ifdef HAVE_AN_FPGA
  2977. { "pgaset", pgaset, true, false },
  2978. { "procset", pgaset, true, false },
  2979. #endif
  2980. { "zero", dozero, true, false },
  2981. { NULL, NULL, false, false }
  2982. };
  2983. static void checkcommand(struct io_data *io_data, __maybe_unused SOCKETTYPE c, char *param, bool isjson, char group)
  2984. {
  2985. struct api_data *root = NULL;
  2986. char buf[TMPBUFSIZ];
  2987. bool io_open;
  2988. char cmdbuf[100];
  2989. bool found, access;
  2990. int i;
  2991. if (param == NULL || *param == '\0') {
  2992. message(io_data, MSG_MISCHK, 0, NULL, isjson);
  2993. return;
  2994. }
  2995. found = false;
  2996. access = false;
  2997. for (i = 0; cmds[i].name != NULL; i++) {
  2998. if (strcmp(cmds[i].name, param) == 0) {
  2999. found = true;
  3000. sprintf(cmdbuf, "|%s|", param);
  3001. if (ISPRIVGROUP(group) || strstr(COMMANDS(group), cmdbuf))
  3002. access = true;
  3003. break;
  3004. }
  3005. }
  3006. message(io_data, MSG_CHECK, 0, NULL, isjson);
  3007. io_open = io_add(io_data, isjson ? COMSTR JSON_CHECK : _CHECK COMSTR);
  3008. root = api_add_const(root, "Exists", found ? YES : NO, false);
  3009. root = api_add_const(root, "Access", access ? YES : NO, false);
  3010. root = print_data(root, buf, isjson, false);
  3011. io_add(io_data, buf);
  3012. if (isjson && io_open)
  3013. io_close(io_data);
  3014. }
  3015. static void head_join(struct io_data *io_data, char *cmdptr, bool isjson, bool *firstjoin)
  3016. {
  3017. char *ptr;
  3018. if (*firstjoin) {
  3019. if (isjson)
  3020. io_add(io_data, JSON0);
  3021. *firstjoin = false;
  3022. } else {
  3023. if (isjson)
  3024. io_add(io_data, JSON_BETWEEN_JOIN);
  3025. }
  3026. // External supplied string
  3027. ptr = escape_string(cmdptr, isjson);
  3028. if (isjson) {
  3029. io_add(io_data, JSON1);
  3030. io_add(io_data, ptr);
  3031. io_add(io_data, JSON2);
  3032. } else {
  3033. io_add(io_data, JOIN_CMD);
  3034. io_add(io_data, ptr);
  3035. io_add(io_data, BETWEEN_JOIN);
  3036. }
  3037. if (ptr != cmdptr)
  3038. free(ptr);
  3039. }
  3040. static void tail_join(struct io_data *io_data, bool isjson)
  3041. {
  3042. if (io_data->close) {
  3043. io_add(io_data, JSON_CLOSE);
  3044. io_data->close = false;
  3045. }
  3046. if (isjson) {
  3047. io_add(io_data, JSON_END);
  3048. io_add(io_data, JSON3);
  3049. }
  3050. }
  3051. static void send_result(struct io_data *io_data, SOCKETTYPE c, bool isjson)
  3052. {
  3053. if (io_data->close)
  3054. io_add(io_data, JSON_CLOSE);
  3055. if (isjson)
  3056. io_add(io_data, JSON_END);
  3057. // Null-terminate reply, including sending the \0 on the socket
  3058. bytes_append(&io_data->data, "", 1);
  3059. applog(LOG_DEBUG, "API: send reply: (%ld) '%.10s%s'",
  3060. (long)bytes_len(&io_data->data),
  3061. bytes_buf(&io_data->data),
  3062. bytes_len(&io_data->data) > 10 ? "..." : BLANK);
  3063. io_flush(io_data, true);
  3064. if (bytes_len(&io_data->data))
  3065. applog(LOG_WARNING, "RPC: Timed out with %ld bytes left to send",
  3066. (long)bytes_len(&io_data->data));
  3067. }
  3068. static
  3069. void _tidyup_socket(SOCKETTYPE * const sockp)
  3070. {
  3071. if (*sockp != INVSOCK) {
  3072. shutdown(*sockp, SHUT_RDWR);
  3073. CLOSESOCKET(*sockp);
  3074. *sockp = INVSOCK;
  3075. free(sockp);
  3076. }
  3077. }
  3078. static
  3079. void tidyup_socket(void * const arg)
  3080. {
  3081. mutex_lock(&quit_restart_lock);
  3082. _tidyup_socket(arg);
  3083. mutex_unlock(&quit_restart_lock);
  3084. }
  3085. static void tidyup(__maybe_unused void *arg)
  3086. {
  3087. mutex_lock(&quit_restart_lock);
  3088. SOCKETTYPE *apisock = (SOCKETTYPE *)arg;
  3089. bye = true;
  3090. _tidyup_socket(apisock);
  3091. if (ipaccess != NULL) {
  3092. free(ipaccess);
  3093. ipaccess = NULL;
  3094. }
  3095. io_free();
  3096. mutex_unlock(&quit_restart_lock);
  3097. }
  3098. /*
  3099. * Interpret --api-groups G:cmd1:cmd2:cmd3,P:cmd4,*,...
  3100. */
  3101. static void setup_groups()
  3102. {
  3103. char *api_groups = opt_api_groups ? opt_api_groups : (char *)BLANK;
  3104. char *buf, *ptr, *next, *colon;
  3105. char group;
  3106. char commands[TMPBUFSIZ];
  3107. char cmdbuf[100];
  3108. char *cmd;
  3109. bool addstar, did;
  3110. int i;
  3111. buf = malloc(strlen(api_groups) + 1);
  3112. if (unlikely(!buf))
  3113. quit(1, "Failed to malloc ipgroups buf");
  3114. strcpy(buf, api_groups);
  3115. next = buf;
  3116. // for each group defined
  3117. while (next && *next) {
  3118. ptr = next;
  3119. next = strchr(ptr, ',');
  3120. if (next)
  3121. *(next++) = '\0';
  3122. // Validate the group
  3123. if (*(ptr+1) != ':') {
  3124. colon = strchr(ptr, ':');
  3125. if (colon)
  3126. *colon = '\0';
  3127. quit(1, "API invalid group name '%s'", ptr);
  3128. }
  3129. group = GROUP(*ptr);
  3130. if (!VALIDGROUP(group))
  3131. quit(1, "API invalid group name '%c'", *ptr);
  3132. if (group == PRIVGROUP)
  3133. quit(1, "API group name can't be '%c'", PRIVGROUP);
  3134. if (group == NOPRIVGROUP)
  3135. quit(1, "API group name can't be '%c'", NOPRIVGROUP);
  3136. if (apigroups[GROUPOFFSET(group)].commands != NULL)
  3137. quit(1, "API duplicate group name '%c'", *ptr);
  3138. ptr += 2;
  3139. // Validate the command list (and handle '*')
  3140. cmd = &(commands[0]);
  3141. *(cmd++) = SEPARATOR;
  3142. *cmd = '\0';
  3143. addstar = false;
  3144. while (ptr && *ptr) {
  3145. colon = strchr(ptr, ':');
  3146. if (colon)
  3147. *(colon++) = '\0';
  3148. if (strcmp(ptr, "*") == 0)
  3149. addstar = true;
  3150. else {
  3151. did = false;
  3152. for (i = 0; cmds[i].name != NULL; i++) {
  3153. if (strcasecmp(ptr, cmds[i].name) == 0) {
  3154. did = true;
  3155. break;
  3156. }
  3157. }
  3158. if (did) {
  3159. // skip duplicates
  3160. sprintf(cmdbuf, "|%s|", cmds[i].name);
  3161. if (strstr(commands, cmdbuf) == NULL) {
  3162. strcpy(cmd, cmds[i].name);
  3163. cmd += strlen(cmds[i].name);
  3164. *(cmd++) = SEPARATOR;
  3165. *cmd = '\0';
  3166. }
  3167. } else {
  3168. quit(1, "API unknown command '%s' in group '%c'", ptr, group);
  3169. }
  3170. }
  3171. ptr = colon;
  3172. }
  3173. // * = allow all non-iswritemode commands
  3174. if (addstar) {
  3175. for (i = 0; cmds[i].name != NULL; i++) {
  3176. if (cmds[i].iswritemode == false) {
  3177. // skip duplicates
  3178. sprintf(cmdbuf, "|%s|", cmds[i].name);
  3179. if (strstr(commands, cmdbuf) == NULL) {
  3180. strcpy(cmd, cmds[i].name);
  3181. cmd += strlen(cmds[i].name);
  3182. *(cmd++) = SEPARATOR;
  3183. *cmd = '\0';
  3184. }
  3185. }
  3186. }
  3187. }
  3188. ptr = apigroups[GROUPOFFSET(group)].commands = malloc(strlen(commands) + 1);
  3189. if (unlikely(!ptr))
  3190. quit(1, "Failed to malloc group commands buf");
  3191. strcpy(ptr, commands);
  3192. }
  3193. // Now define R (NOPRIVGROUP) as all non-iswritemode commands
  3194. cmd = &(commands[0]);
  3195. *(cmd++) = SEPARATOR;
  3196. *cmd = '\0';
  3197. for (i = 0; cmds[i].name != NULL; i++) {
  3198. if (cmds[i].iswritemode == false) {
  3199. strcpy(cmd, cmds[i].name);
  3200. cmd += strlen(cmds[i].name);
  3201. *(cmd++) = SEPARATOR;
  3202. *cmd = '\0';
  3203. }
  3204. }
  3205. ptr = apigroups[GROUPOFFSET(NOPRIVGROUP)].commands = malloc(strlen(commands) + 1);
  3206. if (unlikely(!ptr))
  3207. quit(1, "Failed to malloc noprivgroup commands buf");
  3208. strcpy(ptr, commands);
  3209. // W (PRIVGROUP) is handled as a special case since it simply means all commands
  3210. free(buf);
  3211. return;
  3212. }
  3213. /*
  3214. * Interpret [W:]IP[/Prefix][,[R|W:]IP2[/Prefix2][,...]] --api-allow option
  3215. * special case of 0/0 allows /0 (means all IP addresses)
  3216. */
  3217. #define ALLIP4 "0/0"
  3218. /*
  3219. * N.B. IP4 addresses are by Definition 32bit big endian on all platforms
  3220. */
  3221. static void setup_ipaccess()
  3222. {
  3223. char *buf, *ptr, *comma, *slash, *dot;
  3224. int ipcount, mask, octet, i;
  3225. char group;
  3226. buf = malloc(strlen(opt_api_allow) + 1);
  3227. if (unlikely(!buf))
  3228. quit(1, "Failed to malloc ipaccess buf");
  3229. strcpy(buf, opt_api_allow);
  3230. ipcount = 1;
  3231. ptr = buf;
  3232. while (*ptr)
  3233. if (*(ptr++) == ',')
  3234. ipcount++;
  3235. // possibly more than needed, but never less
  3236. ipaccess = calloc(ipcount, sizeof(struct IP4ACCESS));
  3237. if (unlikely(!ipaccess))
  3238. quit(1, "Failed to calloc ipaccess");
  3239. ips = 0;
  3240. ptr = buf;
  3241. while (ptr && *ptr) {
  3242. while (*ptr == ' ' || *ptr == '\t')
  3243. ptr++;
  3244. if (*ptr == ',') {
  3245. ptr++;
  3246. continue;
  3247. }
  3248. comma = strchr(ptr, ',');
  3249. if (comma)
  3250. *(comma++) = '\0';
  3251. group = NOPRIVGROUP;
  3252. if (VALIDGROUP(*ptr) && *(ptr+1) == ':') {
  3253. if (DEFINEDGROUP(*ptr))
  3254. group = GROUP(*ptr);
  3255. ptr += 2;
  3256. }
  3257. ipaccess[ips].group = group;
  3258. if (strcmp(ptr, ALLIP4) == 0)
  3259. ipaccess[ips].ip = ipaccess[ips].mask = 0;
  3260. else {
  3261. slash = strchr(ptr, '/');
  3262. if (!slash)
  3263. ipaccess[ips].mask = 0xffffffff;
  3264. else {
  3265. *(slash++) = '\0';
  3266. mask = atoi(slash);
  3267. if (mask < 1 || mask > 32)
  3268. goto popipo; // skip invalid/zero
  3269. ipaccess[ips].mask = 0;
  3270. while (mask-- >= 0) {
  3271. octet = 1 << (mask % 8);
  3272. ipaccess[ips].mask |= (octet << (24 - (8 * (mask >> 3))));
  3273. }
  3274. }
  3275. ipaccess[ips].ip = 0; // missing default to '.0'
  3276. for (i = 0; ptr && (i < 4); i++) {
  3277. dot = strchr(ptr, '.');
  3278. if (dot)
  3279. *(dot++) = '\0';
  3280. octet = atoi(ptr);
  3281. if (octet < 0 || octet > 0xff)
  3282. goto popipo; // skip invalid
  3283. ipaccess[ips].ip |= (octet << (24 - (i * 8)));
  3284. ptr = dot;
  3285. }
  3286. ipaccess[ips].ip &= ipaccess[ips].mask;
  3287. }
  3288. ips++;
  3289. popipo:
  3290. ptr = comma;
  3291. }
  3292. free(buf);
  3293. }
  3294. static void *quit_thread(__maybe_unused void *userdata)
  3295. {
  3296. RenameThread("rpc_quit");
  3297. // allow thread creator to finish whatever it's doing
  3298. mutex_lock(&quit_restart_lock);
  3299. mutex_unlock(&quit_restart_lock);
  3300. if (opt_debug)
  3301. applog(LOG_DEBUG, "API: killing BFGMiner");
  3302. kill_work();
  3303. return NULL;
  3304. }
  3305. static void *restart_thread(__maybe_unused void *userdata)
  3306. {
  3307. RenameThread("rpc_restart");
  3308. // allow thread creator to finish whatever it's doing
  3309. mutex_lock(&quit_restart_lock);
  3310. mutex_unlock(&quit_restart_lock);
  3311. if (opt_debug)
  3312. applog(LOG_DEBUG, "API: restarting BFGMiner");
  3313. app_restart();
  3314. return NULL;
  3315. }
  3316. static bool check_connect(struct sockaddr_in *cli, char **connectaddr, char *group)
  3317. {
  3318. bool addrok = false;
  3319. int i;
  3320. *connectaddr = inet_ntoa(cli->sin_addr);
  3321. *group = NOPRIVGROUP;
  3322. if (opt_api_allow) {
  3323. int client_ip = htonl(cli->sin_addr.s_addr);
  3324. for (i = 0; i < ips; i++) {
  3325. if ((client_ip & ipaccess[i].mask) == ipaccess[i].ip) {
  3326. addrok = true;
  3327. *group = ipaccess[i].group;
  3328. break;
  3329. }
  3330. }
  3331. } else {
  3332. if (opt_api_network)
  3333. addrok = true;
  3334. else
  3335. addrok = (strcmp(*connectaddr, localaddr) == 0);
  3336. }
  3337. return addrok;
  3338. }
  3339. static void mcast()
  3340. {
  3341. struct sockaddr_in listen;
  3342. struct ip_mreq grp;
  3343. struct sockaddr_in came_from;
  3344. struct timeval bindstart;
  3345. const char *binderror;
  3346. SOCKETTYPE *mcastsock;
  3347. SOCKETTYPE reply_sock;
  3348. socklen_t came_from_siz;
  3349. char *connectaddr;
  3350. ssize_t rep;
  3351. int bound;
  3352. int count;
  3353. int reply_port;
  3354. bool addrok;
  3355. char group;
  3356. char expect[] = "cgminer-"; // first 8 bytes constant
  3357. char *expect_code;
  3358. size_t expect_code_len;
  3359. char buf[1024];
  3360. char replybuf[1024];
  3361. memset(&grp, 0, sizeof(grp));
  3362. grp.imr_multiaddr.s_addr = inet_addr(opt_api_mcast_addr);
  3363. if (grp.imr_multiaddr.s_addr == INADDR_NONE)
  3364. quit(1, "Invalid Multicast Address");
  3365. grp.imr_interface.s_addr = INADDR_ANY;
  3366. mcastsock = malloc(sizeof(*mcastsock));
  3367. *mcastsock = INVSOCK;
  3368. pthread_cleanup_push(tidyup_socket, mcastsock);
  3369. *mcastsock = bfg_socket(AF_INET, SOCK_DGRAM, 0);
  3370. int optval = 1;
  3371. if (SOCKETFAIL(setsockopt(*mcastsock, SOL_SOCKET, SO_REUSEADDR, (void *)(&optval), sizeof(optval)))) {
  3372. applog(LOG_ERR, "API mcast setsockopt SO_REUSEADDR failed (%s)%s", SOCKERRMSG, MUNAVAILABLE);
  3373. goto die;
  3374. }
  3375. memset(&listen, 0, sizeof(listen));
  3376. listen.sin_family = AF_INET;
  3377. listen.sin_addr.s_addr = INADDR_ANY;
  3378. listen.sin_port = htons(opt_api_mcast_port);
  3379. // try for more than 1 minute ... in case the old one hasn't completely gone yet
  3380. bound = 0;
  3381. timer_set_now(&bindstart);
  3382. while (bound == 0) {
  3383. if (SOCKETFAIL(bind(*mcastsock, (struct sockaddr *)(&listen), sizeof(listen)))) {
  3384. binderror = SOCKERRMSG;
  3385. if (timer_elapsed(&bindstart, NULL) > 61)
  3386. break;
  3387. else
  3388. cgsleep_ms(30000);
  3389. } else
  3390. bound = 1;
  3391. }
  3392. if (bound == 0) {
  3393. applog(LOG_ERR, "API mcast bind to port %d failed (%s)%s", opt_api_port, binderror, MUNAVAILABLE);
  3394. goto die;
  3395. }
  3396. if (SOCKETFAIL(setsockopt(*mcastsock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void *)(&grp), sizeof(grp)))) {
  3397. applog(LOG_ERR, "API mcast join failed (%s)%s", SOCKERRMSG, MUNAVAILABLE);
  3398. goto die;
  3399. }
  3400. expect_code_len = sizeof(expect) + strlen(opt_api_mcast_code);
  3401. expect_code = malloc(expect_code_len+1);
  3402. if (!expect_code)
  3403. quit(1, "Failed to malloc mcast expect_code");
  3404. snprintf(expect_code, expect_code_len+1, "%s%s-", expect, opt_api_mcast_code);
  3405. count = 0;
  3406. while (80085) {
  3407. cgsleep_ms(1000);
  3408. count++;
  3409. came_from_siz = sizeof(came_from);
  3410. if (SOCKETFAIL(rep = recvfrom(*mcastsock, buf, sizeof(buf) - 1,
  3411. 0, (struct sockaddr *)(&came_from), &came_from_siz))) {
  3412. applog(LOG_DEBUG, "API mcast failed count=%d (%s) (%d)",
  3413. count, SOCKERRMSG, (int)*mcastsock);
  3414. continue;
  3415. }
  3416. addrok = check_connect(&came_from, &connectaddr, &group);
  3417. applog(LOG_DEBUG, "API mcast from %s - %s",
  3418. connectaddr, addrok ? "Accepted" : "Ignored");
  3419. if (!addrok)
  3420. continue;
  3421. buf[rep] = '\0';
  3422. if (rep > 0 && buf[rep-1] == '\n')
  3423. buf[--rep] = '\0';
  3424. applog(LOG_DEBUG, "API mcast request rep=%d (%s) from %s:%d",
  3425. (int)rep, buf,
  3426. inet_ntoa(came_from.sin_addr),
  3427. ntohs(came_from.sin_port));
  3428. if ((size_t)rep > expect_code_len && memcmp(buf, expect_code, expect_code_len) == 0) {
  3429. reply_port = atoi(&buf[expect_code_len]);
  3430. if (reply_port < 1 || reply_port > 65535) {
  3431. applog(LOG_DEBUG, "API mcast request ignored - invalid port (%s)",
  3432. &buf[expect_code_len]);
  3433. } else {
  3434. applog(LOG_DEBUG, "API mcast request OK port %s=%d",
  3435. &buf[expect_code_len], reply_port);
  3436. came_from.sin_port = htons(reply_port);
  3437. reply_sock = bfg_socket(AF_INET, SOCK_DGRAM, 0);
  3438. snprintf(replybuf, sizeof(replybuf),
  3439. "cgm-%s-%d-%s",
  3440. opt_api_mcast_code,
  3441. opt_api_port, opt_api_mcast_des);
  3442. rep = sendto(reply_sock, replybuf, strlen(replybuf)+1,
  3443. 0, (struct sockaddr *)(&came_from),
  3444. sizeof(came_from));
  3445. if (SOCKETFAIL(rep)) {
  3446. applog(LOG_DEBUG, "API mcast send reply failed (%s) (%d)",
  3447. SOCKERRMSG, (int)reply_sock);
  3448. } else {
  3449. applog(LOG_DEBUG, "API mcast send reply (%s) succeeded (%d) (%d)",
  3450. replybuf, (int)rep, (int)reply_sock);
  3451. }
  3452. shutdown(reply_sock, SHUT_RDWR);
  3453. CLOSESOCKET(reply_sock);
  3454. }
  3455. } else
  3456. applog(LOG_DEBUG, "API mcast request was no good");
  3457. }
  3458. die:
  3459. ; // statement in case pthread_cleanup_pop doesn't start with one
  3460. pthread_cleanup_pop(true);
  3461. }
  3462. static void *mcast_thread(void *userdata)
  3463. {
  3464. pthread_detach(pthread_self());
  3465. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3466. RenameThread("api_mcast");
  3467. mcast();
  3468. return NULL;
  3469. }
  3470. void mcast_init()
  3471. {
  3472. struct thr_info *thr;
  3473. thr = calloc(1, sizeof(*thr));
  3474. if (!thr)
  3475. quit(1, "Failed to calloc mcast thr");
  3476. if (thr_info_create(thr, NULL, mcast_thread, thr))
  3477. quit(1, "API mcast thread create failed");
  3478. }
  3479. void api(int api_thr_id)
  3480. {
  3481. struct io_data *io_data;
  3482. struct thr_info bye_thr;
  3483. char buf[TMPBUFSIZ];
  3484. char param_buf[TMPBUFSIZ];
  3485. SOCKETTYPE c;
  3486. int n, bound;
  3487. char *connectaddr;
  3488. const char *binderror;
  3489. struct timeval bindstart;
  3490. short int port = opt_api_port;
  3491. struct sockaddr_in serv;
  3492. struct sockaddr_in cli;
  3493. socklen_t clisiz;
  3494. char cmdbuf[100];
  3495. char *cmd = NULL, *cmdptr, *cmdsbuf;
  3496. char *param;
  3497. bool addrok;
  3498. char group;
  3499. json_error_t json_err;
  3500. json_t *json_config = NULL;
  3501. json_t *json_val;
  3502. bool isjson;
  3503. bool did, isjoin, firstjoin;
  3504. int i;
  3505. SOCKETTYPE *apisock;
  3506. if (!opt_api_listen) {
  3507. applog(LOG_DEBUG, "API not running%s", UNAVAILABLE);
  3508. return;
  3509. }
  3510. apisock = malloc(sizeof(*apisock));
  3511. *apisock = INVSOCK;
  3512. rpc_io_data =
  3513. io_data = sock_io_new();
  3514. mutex_init(&quit_restart_lock);
  3515. pthread_cleanup_push(tidyup, (void *)apisock);
  3516. my_thr_id = api_thr_id;
  3517. setup_groups();
  3518. if (opt_api_allow) {
  3519. setup_ipaccess();
  3520. if (ips == 0) {
  3521. applog(LOG_WARNING, "API not running (no valid IPs specified)%s", UNAVAILABLE);
  3522. pthread_exit(NULL);
  3523. }
  3524. }
  3525. *apisock = bfg_socket(AF_INET, SOCK_STREAM, 0);
  3526. if (*apisock == INVSOCK) {
  3527. applog(LOG_ERR, "API1 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  3528. pthread_exit(NULL);
  3529. }
  3530. memset(&serv, 0, sizeof(serv));
  3531. serv.sin_family = AF_INET;
  3532. if (!opt_api_allow && !opt_api_network) {
  3533. serv.sin_addr.s_addr = inet_addr(localaddr);
  3534. if (serv.sin_addr.s_addr == (in_addr_t)INVINETADDR) {
  3535. applog(LOG_ERR, "API2 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  3536. pthread_exit(NULL);
  3537. }
  3538. }
  3539. serv.sin_port = htons(port);
  3540. #ifndef WIN32
  3541. // On linux with SO_REUSEADDR, bind will get the port if the previous
  3542. // socket is closed (even if it is still in TIME_WAIT) but fail if
  3543. // another program has it open - which is what we want
  3544. int optval = 1;
  3545. // If it doesn't work, we don't really care - just show a debug message
  3546. if (SOCKETFAIL(setsockopt(*apisock, SOL_SOCKET, SO_REUSEADDR, (void *)(&optval), sizeof(optval))))
  3547. applog(LOG_DEBUG, "API setsockopt SO_REUSEADDR failed (ignored): %s", SOCKERRMSG);
  3548. #else
  3549. // On windows a 2nd program can bind to a port>1024 already in use unless
  3550. // SO_EXCLUSIVEADDRUSE is used - however then the bind to a closed port
  3551. // in TIME_WAIT will fail until the timeout - so we leave the options alone
  3552. #endif
  3553. // try for more than 1 minute ... in case the old one hasn't completely gone yet
  3554. bound = 0;
  3555. cgtime(&bindstart);
  3556. while (bound == 0) {
  3557. if (SOCKETFAIL(bind(*apisock, (struct sockaddr *)(&serv), sizeof(serv)))) {
  3558. binderror = SOCKERRMSG;
  3559. if (timer_elapsed(&bindstart, NULL) > 61)
  3560. break;
  3561. else {
  3562. applog(LOG_WARNING, "API bind to port %d failed - trying again in 30sec", port);
  3563. cgsleep_ms(30000);
  3564. }
  3565. } else
  3566. bound = 1;
  3567. }
  3568. if (bound == 0) {
  3569. applog(LOG_ERR, "API bind to port %d failed (%s)%s", port, binderror, UNAVAILABLE);
  3570. pthread_exit(NULL);
  3571. }
  3572. if (SOCKETFAIL(listen(*apisock, QUEUE))) {
  3573. applog(LOG_ERR, "API3 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  3574. pthread_exit(NULL);
  3575. }
  3576. if (opt_api_allow)
  3577. applog(LOG_WARNING, "API running in IP access mode on port %d", port);
  3578. else {
  3579. if (opt_api_network)
  3580. applog(LOG_WARNING, "API running in UNRESTRICTED read access mode on port %d", port);
  3581. else
  3582. applog(LOG_WARNING, "API running in local read access mode on port %d", port);
  3583. }
  3584. if (opt_api_mcast)
  3585. mcast_init();
  3586. while (!bye) {
  3587. clisiz = sizeof(cli);
  3588. if (SOCKETFAIL(c = accept(*apisock, (struct sockaddr *)(&cli), &clisiz))) {
  3589. applog(LOG_ERR, "API failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  3590. goto die;
  3591. }
  3592. addrok = check_connect(&cli, &connectaddr, &group);
  3593. applog(LOG_DEBUG, "API: connection from %s - %s",
  3594. connectaddr, addrok ? "Accepted" : "Ignored");
  3595. if (addrok) {
  3596. n = recv(c, &buf[0], TMPBUFSIZ-1, 0);
  3597. if (SOCKETFAIL(n))
  3598. buf[0] = '\0';
  3599. else
  3600. buf[n] = '\0';
  3601. if (opt_debug) {
  3602. if (SOCKETFAIL(n))
  3603. applog(LOG_DEBUG, "API: recv failed: %s", SOCKERRMSG);
  3604. else
  3605. applog(LOG_DEBUG, "API: recv command: (%d) '%s'", n, buf);
  3606. }
  3607. firstjoin = isjoin = false;
  3608. if (!SOCKETFAIL(n)) {
  3609. // the time of the request in now
  3610. when = time(NULL);
  3611. io_reinit(io_data);
  3612. io_data->sock = c;
  3613. did = false;
  3614. if (*buf != ISJSON) {
  3615. isjson = false;
  3616. param = strchr(buf, SEPARATOR);
  3617. if (param != NULL)
  3618. *(param++) = '\0';
  3619. cmd = buf;
  3620. }
  3621. else {
  3622. isjson = true;
  3623. param = NULL;
  3624. #if JANSSON_MAJOR_VERSION > 2 || (JANSSON_MAJOR_VERSION == 2 && JANSSON_MINOR_VERSION > 0)
  3625. json_config = json_loadb(buf, n, 0, &json_err);
  3626. #elif JANSSON_MAJOR_VERSION > 1
  3627. json_config = json_loads(buf, 0, &json_err);
  3628. #else
  3629. json_config = json_loads(buf, &json_err);
  3630. #endif
  3631. if (!json_is_object(json_config)) {
  3632. message(io_data, MSG_INVJSON, 0, NULL, isjson);
  3633. send_result(io_data, c, isjson);
  3634. did = true;
  3635. }
  3636. else {
  3637. json_val = json_object_get(json_config, JSON_COMMAND);
  3638. if (json_val == NULL) {
  3639. message(io_data, MSG_MISCMD, 0, NULL, isjson);
  3640. send_result(io_data, c, isjson);
  3641. did = true;
  3642. }
  3643. else {
  3644. if (!json_is_string(json_val)) {
  3645. message(io_data, MSG_INVCMD, 0, NULL, isjson);
  3646. send_result(io_data, c, isjson);
  3647. did = true;
  3648. }
  3649. else {
  3650. cmd = (char *)json_string_value(json_val);
  3651. json_val = json_object_get(json_config, JSON_PARAMETER);
  3652. if (json_is_string(json_val))
  3653. param = (char *)json_string_value(json_val);
  3654. else if (json_is_integer(json_val)) {
  3655. sprintf(param_buf, "%d", (int)json_integer_value(json_val));
  3656. param = param_buf;
  3657. } else if (json_is_real(json_val)) {
  3658. sprintf(param_buf, "%f", (double)json_real_value(json_val));
  3659. param = param_buf;
  3660. }
  3661. }
  3662. }
  3663. }
  3664. }
  3665. if (!did) {
  3666. if (strchr(cmd, CMDJOIN)) {
  3667. firstjoin = isjoin = true;
  3668. // cmd + leading+tailing '|' + '\0'
  3669. cmdsbuf = malloc(strlen(cmd) + 3);
  3670. if (!cmdsbuf)
  3671. quithere(1, "OOM cmdsbuf");
  3672. strcpy(cmdsbuf, "|");
  3673. param = NULL;
  3674. }
  3675. cmdptr = cmd;
  3676. do {
  3677. did = false;
  3678. if (isjoin) {
  3679. cmd = strchr(cmdptr, CMDJOIN);
  3680. if (cmd)
  3681. *(cmd++) = '\0';
  3682. if (!*cmdptr)
  3683. goto inochi;
  3684. }
  3685. for (i = 0; cmds[i].name != NULL; i++) {
  3686. if (strcmp(cmdptr, cmds[i].name) == 0) {
  3687. sprintf(cmdbuf, "|%s|", cmdptr);
  3688. if (isjoin) {
  3689. if (strstr(cmdsbuf, cmdbuf)) {
  3690. did = true;
  3691. break;
  3692. }
  3693. strcat(cmdsbuf, cmdptr);
  3694. strcat(cmdsbuf, "|");
  3695. head_join(io_data, cmdptr, isjson, &firstjoin);
  3696. if (!cmds[i].joinable) {
  3697. message(io_data, MSG_ACCDENY, 0, cmds[i].name, isjson);
  3698. did = true;
  3699. tail_join(io_data, isjson);
  3700. break;
  3701. }
  3702. }
  3703. if (ISPRIVGROUP(group) || strstr(COMMANDS(group), cmdbuf))
  3704. {
  3705. per_proc = !strncmp(cmds[i].name, "proc", 4);
  3706. (cmds[i].func)(io_data, c, param, isjson, group);
  3707. }
  3708. else {
  3709. message(io_data, MSG_ACCDENY, 0, cmds[i].name, isjson);
  3710. applog(LOG_DEBUG, "API: access denied to '%s' for '%s' command", connectaddr, cmds[i].name);
  3711. }
  3712. did = true;
  3713. if (!isjoin)
  3714. send_result(io_data, c, isjson);
  3715. else
  3716. tail_join(io_data, isjson);
  3717. break;
  3718. }
  3719. }
  3720. if (!did) {
  3721. if (isjoin)
  3722. head_join(io_data, cmdptr, isjson, &firstjoin);
  3723. message(io_data, MSG_INVCMD, 0, NULL, isjson);
  3724. if (isjoin)
  3725. tail_join(io_data, isjson);
  3726. else
  3727. send_result(io_data, c, isjson);
  3728. }
  3729. inochi:
  3730. if (isjoin)
  3731. cmdptr = cmd;
  3732. } while (isjoin && cmdptr);
  3733. }
  3734. if (isjson)
  3735. json_decref(json_config);
  3736. if (isjoin)
  3737. send_result(io_data, c, isjson);
  3738. }
  3739. }
  3740. shutdown(c, SHUT_RDWR);
  3741. CLOSESOCKET(c);
  3742. }
  3743. die:
  3744. /* Blank line fix for older compilers since pthread_cleanup_pop is a
  3745. * macro that gets confused by a label existing immediately before it
  3746. */
  3747. ;
  3748. pthread_cleanup_pop(true);
  3749. if (opt_debug)
  3750. applog(LOG_DEBUG, "API: terminating due to: %s",
  3751. do_a_quit ? "QUIT" : (do_a_restart ? "RESTART" : (bye ? "BYE" : "UNKNOWN!")));
  3752. mutex_lock(&quit_restart_lock);
  3753. if (do_a_restart) {
  3754. if (thr_info_create(&bye_thr, NULL, restart_thread, &bye_thr)) {
  3755. mutex_unlock(&quit_restart_lock);
  3756. quit(1, "API failed to initiate a restart - aborting");
  3757. }
  3758. pthread_detach(bye_thr.pth);
  3759. } else if (do_a_quit) {
  3760. if (thr_info_create(&bye_thr, NULL, quit_thread, &bye_thr)) {
  3761. mutex_unlock(&quit_restart_lock);
  3762. quit(1, "API failed to initiate a clean quit - aborting");
  3763. }
  3764. pthread_detach(bye_thr.pth);
  3765. }
  3766. mutex_unlock(&quit_restart_lock);
  3767. }