api.c 116 KB

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