api.c 116 KB

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