api.c 116 KB

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