21#include <fmt/format.h>
23#include <wx/datetime.h>
25#include <wx/stdpaths.h>
39#include <api/common/envelope.pb.h>
45using kiapi::common::ApiRequest, kiapi::common::ApiResponse, kiapi::common::ApiStatusCode;
62 if( !
Pgm().GetCommonSettings()->m_Api.enable_server )
64 wxLogTrace( traceApi,
"Server: disabled by user preferences." );
83 socket.AssignDir( wxS(
"/tmp" ) );
85 socket.AssignDir( wxStandardPaths::Get().GetTempDir() );
88 socket.AppendDir( wxS(
"kicad" ) );
89 socket.SetFullName( wxS(
"api.sock" ) );
116 if( !socket.IsAbsolute() )
117 socket.MakeAbsolute();
122 wxLogTrace(
traceApi, wxString::Format(
"Server: socket path %s could not be created",
123 socket.GetPath() ) );
132 wxFileName lockFilePath( socket.GetPath(), wxS(
"api.lock" ) );
134 int lockFile = open( lockFilePath.GetFullPath().c_str(), O_RDONLY | O_CREAT, 0600 );
136 if( lockFile >= 0 && flock( lockFile, LOCK_EX | LOCK_NB ) == 0 )
138 if( socket.Exists() )
140 wxLogTrace(
traceApi, wxString::Format(
"Server: cleaning up stale socket path %s",
141 socket.GetFullPath() ) );
142 wxRemoveFile( socket.GetFullPath() );
147 if( socket.Exists() )
149 socket.SetFullName( wxString::Format( wxS(
"api-%lu.sock" ), ::wxGetProcessId() ) );
151 if( socket.Exists() )
153 wxLogTrace(
traceApi, wxString::Format(
"Server: PID socket path %s already exists!",
154 socket.GetFullPath() ) );
159 m_server = std::make_unique<KINNG_REQUEST_SERVER>(
160 fmt::format(
"ipc://{}", socket.GetFullPath().ToStdString() ) );
165 wxLogTrace(
traceApi,
"Server: failed to start KINNG listener thread" );
176 log( fmt::format(
"--- KiCad API server started at {} ---\n",
SocketPath() ) );
189 wxLogTrace(
traceApi,
"Stopping server" );
205 wxCHECK( aHandler, );
224 handler->onNetSettingsChanged();
229 const wxString& aOldPath,
const wxString& aNewPath )
246 ApiResponse notHandled;
247 notHandled.mutable_status()->set_status( ApiStatusCode::AS_NOT_READY );
248 notHandled.mutable_status()->set_error_message(
"KiCad is not ready to reply" );
249 m_server->Reply( notHandled.SerializeAsString() );
250 log(
"Got incoming request but was not yet ready to reply." );
257 evt->SetClientData(
static_cast<void*
>( aRequest ) );
266 std::string& requestString = *
static_cast<std::string*
>( aEvent.GetClientData() );
275 if( !request.ParseFromString( aRequestString ) )
278 error.mutable_header()->set_kicad_token(
m_token );
279 error.mutable_status()->set_status( ApiStatusCode::AS_BAD_REQUEST );
280 error.mutable_status()->set_error_message(
"request could not be parsed" );
281 m_server->Reply( error.SerializeAsString() );
284 log(
"Response (ERROR): " + error.Utf8DebugString() );
290 log(
"Request: " + request.Utf8DebugString() );
292 if( !request.header().kicad_token().empty() &&
293 request.header().kicad_token().compare(
m_token ) != 0 )
296 error.mutable_header()->set_kicad_token(
m_token );
297 error.mutable_status()->set_status( ApiStatusCode::AS_TOKEN_MISMATCH );
298 error.mutable_status()->set_error_message(
299 "the provided kicad_token did not match this KiCad instance's token" );
300 m_server->Reply( error.SerializeAsString() );
303 log(
"Response (ERROR): " + error.Utf8DebugString() );
312 std::string requestType;
314 if( google::protobuf::Any::ParseAnyTypeUrl( request.message().type_url(), &requestType ) )
316 bool typeHandled =
false;
317 bool allowedDuringTask =
false;
321 if( handler->CanHandle( requestType ) )
324 allowedDuringTask = handler->AllowsDuringTask( requestType );
329 if( typeHandled && !allowedDuringTask )
332 error.mutable_header()->set_kicad_token(
m_token );
333 error.mutable_status()->set_status( ApiStatusCode::AS_BUSY );
334 error.mutable_status()->set_error_message(
335 "a task is running; only task status and result queries are available until it completes" );
336 m_server->Reply( error.SerializeAsString() );
339 log(
"Response (ERROR): " + error.Utf8DebugString() );
347 bool notifyNetSettings =
false;
351 result = handler->Handle( request );
352 notifyNetSettings |= handler->clearNetSettingsNotification();
356 else if(
result.error().status() != ApiStatusCode::AS_UNHANDLED )
360 if( notifyNetSettings )
371 log(
"Response: " +
result->Utf8DebugString() );
376 error.mutable_status()->CopyFrom(
result.error() );
377 error.mutable_header()->set_kicad_token(
m_token );
379 if(
result.error().status() == ApiStatusCode::AS_UNHANDLED )
383 if( !google::protobuf::Any::ParseAnyTypeUrl( request.message().type_url(), &type ) )
384 type =
"<unparseable Any>";
386 std::string msg = fmt::format(
"no handler available for request of type {}", type );
387 error.mutable_status()->set_error_message( msg );
390 m_server->Reply( error.SerializeAsString() );
393 log(
"Response (ERROR): " + error.Utf8DebugString() );
400 FILE* fp = wxFopen(
m_logFilePath.GetFullPath(), wxT(
"a" ) );
406 wxDateTime now = wxDateTime::Now();
408 fprintf( fp,
"%s",
TO_UTF8( out.Format( wxS(
"%s: %s" ),
409 now.FormatISOCombined(), aOutput ) ) );
tl::expected< ApiResponse, ApiResponseStatus > API_RESULT
wxDEFINE_EVENT(API_REQUEST_EVENT, KICAD_API_REQUEST_EVENT)
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
void setApiServer(KICAD_API_SERVER *aServer)
Set by KICAD_API_SERVER::RegisterHandler; null when the handler is not registered.
static API_TASK_SCHEDULER & Instance()
Event carrying an incoming API request from the listener thread to the main thread.
void handleApiEvent(wxCommandEvent &aEvent)
Event handler that receives the event on the main thread sent by onApiRequest.
std::function< void(kiapi::common::types::DocumentType, const wxString &, const wxString &)> m_renameListener
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
void NotifyDocumentRenamed(kiapi::common::types::DocumentType aType, const wxString &aOldPath, const wxString &aNewPath)
Notifies the host application that a document was saved to a new path.
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).
void NotifyNetSettingsChanged()
Calls onNetSettingsChanged() on every registered handler, so that editors can update state derived fr...
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.