API, HTTP, and Monitoring Interfaces
Overview
This area owns BFGMiner's runtime control and monitoring surfaces: the TCP RPC API in api.c, the optional embedded libmicrohttpd server in httpsrv.c/httpsrv.h, the sample socket clients in api-example.c, api-example.py, api-example.php, and api-example.rb, the PHP monitoring UI in miner.php, and the external API contract in README.RPC.
The primary RPC entry point is api() in api.c. It only starts when opt_api_listen is set, binds to opt_api_port, accepts one TCP connection per request, reads up to TMPBUFSIZ - 1 bytes, writes a single NUL-terminated response, and closes the socket. Access control is evaluated before request parsing: check_connect() allows localhost by default, all networks when opt_api_network is enabled, or the first matching --api-allow entry parsed by setup_ipaccess(). setup_groups() builds command allow-lists for read-only group R, privileged group W, and any custom API groups. Commands marked iswritemode in the cmds[] table require privileged access unless explicitly included in a custom group.
Requests are routed by format. Plain text requests use command|parameter with | as the separator. JSON requests are detected by a leading { and parsed with Jansson as {"command":"CMD","parameter":"PARAM"}; string, integer, and real parameters are converted to the same internal char *param shape. api() then looks up cmd in the cmds[] dispatch table and invokes the command handler with the shared struct io_data, client socket, parameter, JSON/text flag, and access group. API v3.1 multi-report requests are handled by splitting commands on +; only cmds[] entries marked joinable can be used in joined requests, duplicate joined commands are skipped, and each joined result is wrapped under its command name.
Every normal response starts with a STATUS section produced by message() in api.c, with fields STATUS, When, Code, Msg, and Description. Data sections are built as circular struct api_data lists with api_add_*() helpers and serialized by print_data(). Text replies look like STATUS=...,Msg=...|SUMMARY=...|; JSON replies look like {"STATUS":[{...}],"SUMMARY":[...],"id":1}. escape_string() escapes user-controlled values differently for text (|, ,, =, \) and JSON (", \) so pool URLs, usernames, filenames, and other operator input do not break parsing. send_result() appends JSON closing structure when needed, adds the terminating NUL byte, flushes through io_flush(), and logs a warning if the 50 ms completion flush leaves bytes unsent.
Monitoring data is sourced directly from miner runtime state in api.c. summary() snapshots global counters such as total_secs, total_mhashes_done, accepted/rejected/share difficulty totals, and best share while holding hash_lock. Device-oriented commands (devs, procs, pga, proc, devdetails, notify, stats) iterate total_devices via get_devices(), respect the module-global per_proc switch for full-device versus per-processor views, and read struct cgpu_info fields such as enablement, alive status, temperatures, rolling hashrate, share counters, last-share metadata, hardware error counters, and driver-provided API extras. Pool commands (pools, switchpool, addpool, enablepool, disablepool, removepool, poolpriority, poolquota) use total_pools, pools[], current pool state, and pool stats fields such as URL, user, priority, quota, long-poll/stratum state, share counters, and best share. Config/control commands read or mutate global options (opt_queue, opt_scantime, opt_expiry, opt_fail_only, debug flags, strategy settings, and loaded config filenames), pool ordering, device enablement, device restart, and miner quit/restart flags.
The control path is intentionally synchronous at the API layer. Commands like pgaenable, pgadisable, pgarestart, procset, and legacy GPU/CPU control handlers validate IDs, update cgpu_info state or call driver hooks such as proc_enable(), reinit_device(), identify_device(), and proc_set_device(), then return only a STATUS section. quit and restart set bye and do_a_quit/do_a_restart; after the API accept loop exits, api() starts a detached quit_thread() or restart_thread() that calls kill_work() or app_restart() outside the main request-processing loop.
api.c also implements multicast discovery. When opt_api_mcast is enabled, mcast_init() starts api_mcast, which joins opt_api_mcast_addr:opt_api_mcast_port, accepts discovery datagrams of the form cgminer-<code>-<reply-port>, reuses check_connect() for access filtering, and replies by UDP with cgm-<code>-<api-port>-<description>. miner.php has matching discovery logic in mcastrigs(): it sends cgminer-$mcastcode-$mcastlistport, collects cgm-... replies, and populates $rigs with ip:port[:description] entries.
The optional embedded HTTP server is separate from the TCP API. httpsrv_start() in httpsrv.c starts a libmicrohttpd daemon on a configured port, httpsrv_handle_access() buffers upload data in a bytes_t per request, and httpsrv_handle_req() currently delegates every URL and method to the external handle_getwork() entry point. httpsrv_prepare_resp() adds the BFGMiner Server header to libmicrohttpd responses. The RPC API can restart this server at runtime through setconfig|http-port,N in api.c, which calls httpsrv_stop(), updates httpsrv_port, and calls httpsrv_start() when the port is not disabled.
The example clients demonstrate the wire protocol. api-example.c sends a raw text command to host:port, receives until close, and optionally parses text sections by |, ,, and =. api-example.php similarly sends text commands to 127.0.0.1:4028, reads until the response NUL byte, decodes JSON if the reply starts with {, otherwise converts text sections into PHP arrays. api-example.py and api-example.rb send JSON command objects and parse the JSON response after stripping the terminating NUL/whitespace.
miner.php is a full PHP monitoring/control UI on top of the text RPC API. api() opens a TCP socket with send/receive timeouts, optionally rewrites devs/pga* requests to procs/proc* when $per_proc is true, sends a text command, reads until NUL, converts escaped separators with api_convert_escape(), and returns section-indexed arrays. The UI displays single-rig details through doOne() (devs, summary, pools, optional notify, config), multi-rig summaries through doforeach(), and custom pages through $customsummarypages plus processcustompage(). Mutating controls are only rendered after htmlhead() successfully checks the API privileged command unless $readonly or user-level login forces read-only mode.
Coverage
Owned globs for this document:
- api.c
- httpsrv.c
- httpsrv.h
- api-example.c
- api-example.py
- api-example.php
- api-example.rb
- miner.php
README.RPC
Coupling
- If a command is added, renamed, made privileged, or made joinable in api.c, update both the
cmds[]table andREADME.RPC. miner.php hard-codes command names in$sectionmap,doOne(), pool/device buttons, and custom-page joins, so UI coverage and custom pages silently break if the API command table changes without corresponding PHP updates. - If response field names change in api.c, verify miner.php formatting and joins. miner.php keys display logic on exact section/field strings such as
DEVS.Last Share Time,POOL.Status,Name/ID/ProcID,STATS.ID, and joined names likePOOL+STATS; it does not consume a schema from the miner. - If text escaping in
escape_string()orprint_data()changes in api.c, update miner.php (api_convert_escape()/revert()), api-example.c, and api-example.php. These clients split text replies before interpreting fields, so any separator or escape-rule drift corrupts pool URLs, users, passwords, filenames, or other values containing|,,,=, or\. - If the JSON envelope changes in api.c, update api-example.py, api-example.rb, api-example.php, and
README.RPC. The Python and Ruby examples expect one JSON object terminated by socket close/NUL and access only the documentedcommand/parameterrequest keys. - If multicast discovery strings or defaults change in api.c, update miner.php and
README.RPC. api.c expectscgminer-<code>-<reply-port>and repliescgm-<code>-<api-port>-<description>, while miner.php currently sends and filters using$mcastcode/FTW-style tokens. - If
setconfighandling forhttp-portchanges in api.c, verify httpsrv.c startup/shutdown behavior. The RPC command directly stops and restarts the libmicrohttpd daemon, so invalid port handling or lifetime bugs affect both the TCP control plane and embedded HTTP getwork service.
Risks
- miner.php allows generated custom-page fields through
genfld(), which performs string substitution and theneval()when$allowgenis true. If a displayed API field from an untrusted miner contains PHP code and is referenced by a generated expression, the web server can execute that code;README.RPCdocuments this as a security risk. - api.c receives each TCP request into a fixed
TMPBUFSIZbuffer once and parses only that read. If a JSON or text command exceeds that buffer or arrives fragmented before the firstrecv()completes, the request can be truncated and routed as invalid JSON, an invalid command, or the wrong parameter. - api-example.php, api-example.c, and miner.php are text-protocol parsers that split on separators after applying only their own escape logic. If server-side text escaping is missed for a new user-controlled field in api.c, clients can misparse fields into new sections or columns rather than failing loudly.