api.c 117 KB

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