21#include <fmt/format.h>
23#include <wx/datetime.h>
25#include <wx/stdpaths.h>
38#include <api/common/envelope.pb.h>
44using kiapi::common::ApiRequest, kiapi::common::ApiResponse, kiapi::common::ApiStatusCode;
61 if( !
Pgm().GetCommonSettings()->m_Api.enable_server )
63 wxLogTrace( traceApi,
"Server: disabled by user preferences." );
82 socket.AssignDir( wxS(
"/tmp" ) );
84 socket.AssignDir( wxStandardPaths::Get().GetTempDir() );
87 socket.AppendDir( wxS(
"kicad" ) );
88 socket.SetFullName( wxS(
"api.sock" ) );
115 if( !socket.IsAbsolute() )
116 socket.MakeAbsolute();
121 wxLogTrace(
traceApi, wxString::Format(
"Server: socket path %s could not be created",
122 socket.GetPath() ) );
131 wxFileName lockFilePath( socket.GetPath(), wxS(
"api.lock" ) );
133 int lockFile = open( lockFilePath.GetFullPath().c_str(), O_RDONLY | O_CREAT, 0600 );
135 if( lockFile >= 0 && flock( lockFile, LOCK_EX | LOCK_NB ) == 0 )
137 if( socket.Exists() )
139 wxLogTrace(
traceApi, wxString::Format(
"Server: cleaning up stale socket path %s",
140 socket.GetFullPath() ) );
141 wxRemoveFile( socket.GetFullPath() );
146 if( socket.Exists() )
148 socket.SetFullName( wxString::Format( wxS(
"api-%lu.sock" ), ::wxGetProcessId() ) );
150 if( socket.Exists() )
152 wxLogTrace(
traceApi, wxString::Format(
"Server: PID socket path %s already exists!",
153 socket.GetFullPath() ) );
158 m_server = std::make_unique<KINNG_REQUEST_SERVER>(
159 fmt::format(
"ipc://{}", socket.GetFullPath().ToStdString() ) );
164 wxLogTrace(
traceApi,
"Server: failed to start KINNG listener thread" );
175 log( fmt::format(
"--- KiCad API server started at {} ---\n",
SocketPath() ) );
188 wxLogTrace(
traceApi,
"Stopping server" );
204 wxCHECK( aHandler, );
225 ApiResponse notHandled;
226 notHandled.mutable_status()->set_status( ApiStatusCode::AS_NOT_READY );
227 notHandled.mutable_status()->set_error_message(
"KiCad is not ready to reply" );
228 m_server->Reply( notHandled.SerializeAsString() );
229 log(
"Got incoming request but was not yet ready to reply." );
233 wxCommandEvent* evt =
new wxCommandEvent( API_REQUEST_EVENT );
236 evt->SetClientData(
static_cast<void*
>( aRequest ) );
245 std::string& requestString = *
static_cast<std::string*
>( aEvent.GetClientData() );
254 if( !request.ParseFromString( aRequestString ) )
257 error.mutable_header()->set_kicad_token(
m_token );
258 error.mutable_status()->set_status( ApiStatusCode::AS_BAD_REQUEST );
259 error.mutable_status()->set_error_message(
"request could not be parsed" );
260 m_server->Reply( error.SerializeAsString() );
263 log(
"Response (ERROR): " + error.Utf8DebugString() );
269 log(
"Request: " + request.Utf8DebugString() );
271 if( !request.header().kicad_token().empty() &&
272 request.header().kicad_token().compare(
m_token ) != 0 )
275 error.mutable_header()->set_kicad_token(
m_token );
276 error.mutable_status()->set_status( ApiStatusCode::AS_TOKEN_MISMATCH );
277 error.mutable_status()->set_error_message(
278 "the provided kicad_token did not match this KiCad instance's token" );
279 m_server->Reply( error.SerializeAsString() );
282 log(
"Response (ERROR): " + error.Utf8DebugString() );
291 result = handler->Handle( request );
295 else if(
result.error().status() != ApiStatusCode::AS_UNHANDLED )
307 log(
"Response: " +
result->Utf8DebugString() );
312 error.mutable_status()->CopyFrom(
result.error() );
313 error.mutable_header()->set_kicad_token(
m_token );
315 if(
result.error().status() == ApiStatusCode::AS_UNHANDLED )
317 std::string type =
"<unparseable Any>";
318 google::protobuf::Any::ParseAnyTypeUrl( request.message().type_url(), &type );
319 std::string msg = fmt::format(
"no handler available for request of type {}", type );
320 error.mutable_status()->set_error_message( msg );
323 m_server->Reply( error.SerializeAsString() );
326 log(
"Response (ERROR): " + error.Utf8DebugString() );
333 FILE* fp = wxFopen(
m_logFilePath.GetFullPath(), wxT(
"a" ) );
339 wxDateTime now = wxDateTime::Now();
341 fprintf( fp,
"%s",
TO_UTF8( out.Format( wxS(
"%s: %s" ),
342 now.FormatISOCombined(), aOutput ) ) );
tl::expected< ApiResponse, ApiResponseStatus > API_RESULT
wxDEFINE_EVENT(API_REQUEST_EVENT, wxCommandEvent)
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
void handleApiEvent(wxCommandEvent &aEvent)
Event handler that receives the event on the main thread sent by onApiRequest.
static wxString s_logFileName
void RegisterHandler(API_HANDLER *aHandler)
Adds a new request handler to the server.
void onApiRequest(std::string *aRequest)
Callback that executes on the server thread and generates an event that will be handled by the wxWidg...
wxString m_socketPathOverride
std::set< API_HANDLER * > m_handlers
std::atomic< bool > m_readyToReply
std::string SocketPath() const
void handleApiRequestString(std::string &aRequestString)
static std::string StandardSocketUrl()
Return the default API socket URL (including the ipc:// scheme).
void log(const std::string &aOutput)
KICAD_API_SERVER(bool aAutoStart=true)
void DeregisterHandler(API_HANDLER *aHandler)
static wxFileName StandardSocketPath()
Return the default API socket path (without the ipc:// scheme).
std::unique_ptr< KINNG_REQUEST_SERVER > m_server
static wxString GetLogsPath()
Gets a path to use for user-visible log files.
static bool EnsurePathExists(const wxString &aPath, bool aPathToFile=false)
Attempts to create a given path if it does not exist.
const wxChar *const traceApi
Flag to enable debug output related to the IPC API and its plugin system.
PGM_BASE & Pgm()
The global program "get" accessor.
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
wxString result
Test unit parsing edge cases and error handling.