api.c 116 KB

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