api.c 119 KB

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