api.c 132 KB

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