api.c 117 KB

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