KiCad PCB EDA Suite
Loading...
Searching...
No Matches
api_server.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2023 Jon Evans <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <fmt/format.h>
22#include <wx/app.h>
23#include <wx/datetime.h>
24#include <wx/event.h>
25#include <wx/stdpaths.h>
26
27#include <advanced_config.h>
28#include <api/api_handler.h>
30#include <api/api_utils.h> // traceApi
31#include <api/api_server.h>
32#include <kiid.h>
33#include <kinng.h>
34#include <paths.h>
35#include <pgm_base.h>
37#include <string_utils.h>
38
39#include <api/common/envelope.pb.h>
40
41#ifdef __UNIX__
42#include <sys/file.h>
43#endif
44
45using kiapi::common::ApiRequest, kiapi::common::ApiResponse, kiapi::common::ApiStatusCode;
46
47
48wxString KICAD_API_SERVER::s_logFileName = "api.log";
49
50
52
53
55 wxEvtHandler(),
56 m_token( KIID().AsStdString() ),
57 m_readyToReply( false )
58{
59 if( !aAutoStart )
60 return;
61
62 if( !Pgm().GetCommonSettings()->m_Api.enable_server )
63 {
64 wxLogTrace( traceApi, "Server: disabled by user preferences." );
65 return;
66 }
67
68 Start();
69}
70
71
76
77
79{
80 wxFileName socket;
81
82#ifdef __WXMAC__
83 socket.AssignDir( wxS( "/tmp" ) );
84#else
85 socket.AssignDir( wxStandardPaths::Get().GetTempDir() );
86#endif
87
88 socket.AppendDir( wxS( "kicad" ) );
89 socket.SetFullName( wxS( "api.sock" ) );
90
91 return socket;
92}
93
94
96{
97 return fmt::format( "ipc://{}", StandardSocketPath().GetFullPath().ToUTF8().data() );
98}
99
100
102{
103 if( Running() )
104 return;
105
106 wxFileName socket;
107
108 if( m_socketPathOverride.IsEmpty() )
109 {
110 socket = StandardSocketPath();
111 }
112 else
113 {
114 socket.Assign( m_socketPathOverride );
115
116 if( !socket.IsAbsolute() )
117 socket.MakeAbsolute();
118 }
119
120 if( !PATHS::EnsurePathExists( socket.GetPath() ) )
121 {
122 wxLogTrace( traceApi, wxString::Format( "Server: socket path %s could not be created",
123 socket.GetPath() ) );
124 return;
125 }
126
127#ifndef __WINDOWS__
128 // We use non-abstract sockets because macOS and some other non-Linux platforms don't support
129 // abstract sockets, which means there might be an old socket to unlink. In order to try to
130 // recover this, we lock a file (which will be unlocked on process exit) and if we get the lock,
131 // we know the old socket is orphaned and can be removed.
132 wxFileName lockFilePath( socket.GetPath(), wxS( "api.lock" ) );
133
134 int lockFile = open( lockFilePath.GetFullPath().c_str(), O_RDONLY | O_CREAT, 0600 );
135
136 if( lockFile >= 0 && flock( lockFile, LOCK_EX | LOCK_NB ) == 0 )
137 {
138 if( socket.Exists() )
139 {
140 wxLogTrace( traceApi, wxString::Format( "Server: cleaning up stale socket path %s",
141 socket.GetFullPath() ) );
142 wxRemoveFile( socket.GetFullPath() );
143 }
144 }
145#endif
146
147 if( socket.Exists() )
148 {
149 socket.SetFullName( wxString::Format( wxS( "api-%lu.sock" ), ::wxGetProcessId() ) );
150
151 if( socket.Exists() )
152 {
153 wxLogTrace( traceApi, wxString::Format( "Server: PID socket path %s already exists!",
154 socket.GetFullPath() ) );
155 return;
156 }
157 }
158
159 m_server = std::make_unique<KINNG_REQUEST_SERVER>(
160 fmt::format( "ipc://{}", socket.GetFullPath().ToStdString() ) );
161 m_server->SetCallback( [&]( std::string* aRequest ) { onApiRequest( aRequest ); } );
162
163 if( !m_server->Start() )
164 {
165 wxLogTrace( traceApi, "Server: failed to start KINNG listener thread" );
166 m_server.reset( nullptr );
167 return;
168 }
169
170 m_logFilePath.AssignDir( PATHS::GetLogsPath() );
171 m_logFilePath.SetName( s_logFileName );
172
173 if( ADVANCED_CFG::GetCfg().m_EnableAPILogging )
174 {
176 log( fmt::format( "--- KiCad API server started at {} ---\n", SocketPath() ) );
177 }
178
179 wxLogTrace( traceApi, wxString::Format( "Server: listening at %s", SocketPath() ) );
180 Bind( API_REQUEST_EVENT, &KICAD_API_SERVER::handleApiEvent, this );
181}
182
183
185{
186 if( !Running() )
187 return;
188
189 wxLogTrace( traceApi, "Stopping server" );
190 Unbind( API_REQUEST_EVENT, &KICAD_API_SERVER::handleApiEvent, this );
191
192 m_server->Stop();
193 m_server.reset( nullptr );
194}
195
196
198{
199 return m_server && m_server->Running();
200}
201
202
204{
205 wxCHECK( aHandler, /* void */ );
206
207 aHandler->setApiServer( this );
208 m_handlers.insert( aHandler );
209}
210
211
213{
214 if( aHandler )
215 aHandler->setApiServer( nullptr );
216
217 m_handlers.erase( aHandler );
218}
219
220
222{
223 for( API_HANDLER* handler : m_handlers )
224 handler->onNetSettingsChanged();
225}
226
227
228void KICAD_API_SERVER::NotifyDocumentRenamed( kiapi::common::types::DocumentType aType,
229 const wxString& aOldPath, const wxString& aNewPath )
230{
231 if( m_renameListener )
232 m_renameListener( aType, aOldPath, aNewPath );
233}
234
235
237{
238 return m_server ? m_server->SocketPath() : "";
239}
240
241
242void KICAD_API_SERVER::onApiRequest( std::string* aRequest )
243{
244 if( !m_readyToReply.load( std::memory_order_acquire ) )
245 {
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." );
251 return;
252 }
253
254 KICAD_API_REQUEST_EVENT* evt = new KICAD_API_REQUEST_EVENT( API_REQUEST_EVENT );
255
256 // We don't actually need write access to this string, but client data is non-const
257 evt->SetClientData( static_cast<void*>( aRequest ) );
258
259 // Takes ownership and frees the wxCommandEvent
260 QueueEvent( evt );
261}
262
263
264void KICAD_API_SERVER::handleApiEvent( wxCommandEvent& aEvent )
265{
266 std::string& requestString = *static_cast<std::string*>( aEvent.GetClientData() );
267 handleApiRequestString( requestString );
268}
269
270
271void KICAD_API_SERVER::handleApiRequestString( std::string& aRequestString )
272{
273 ApiRequest request;
274
275 if( !request.ParseFromString( aRequestString ) )
276 {
277 ApiResponse error;
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() );
282
283 if( ADVANCED_CFG::GetCfg().m_EnableAPILogging )
284 log( "Response (ERROR): " + error.Utf8DebugString() );
285
286 return;
287 }
288
289 if( ADVANCED_CFG::GetCfg().m_EnableAPILogging )
290 log( "Request: " + request.Utf8DebugString() );
291
292 if( !request.header().kicad_token().empty() &&
293 request.header().kicad_token().compare( m_token ) != 0 )
294 {
295 ApiResponse error;
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() );
301
302 if( ADVANCED_CFG::GetCfg().m_EnableAPILogging )
303 log( "Response (ERROR): " + error.Utf8DebugString() );
304
305 return;
306 }
307
308 // Only allow-listed API requests can be handled while a task is running; anything else
309 // is assumed to possible mess with state that the task might be depending on not changing.
310 if( request.has_message() && API_TASK_SCHEDULER::Instance().AnyTaskRunning() )
311 {
312 std::string requestType;
313
314 if( google::protobuf::Any::ParseAnyTypeUrl( request.message().type_url(), &requestType ) )
315 {
316 bool typeHandled = false;
317 bool allowedDuringTask = false;
318
319 for( API_HANDLER* handler : m_handlers )
320 {
321 if( handler->CanHandle( requestType ) )
322 {
323 typeHandled = true;
324 allowedDuringTask = handler->AllowsDuringTask( requestType );
325 break;
326 }
327 }
328
329 if( typeHandled && !allowedDuringTask )
330 {
331 ApiResponse error;
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() );
337
338 if( ADVANCED_CFG::GetCfg().m_EnableAPILogging )
339 log( "Response (ERROR): " + error.Utf8DebugString() );
340
341 return;
342 }
343 }
344 }
345
347 bool notifyNetSettings = false;
348
349 for( API_HANDLER* handler : m_handlers )
350 {
351 result = handler->Handle( request );
352 notifyNetSettings |= handler->clearNetSettingsNotification();
353
354 if( result.has_value() )
355 break;
356 else if( result.error().status() != ApiStatusCode::AS_UNHANDLED )
357 break;
358 }
359
360 if( notifyNetSettings )
362
363 // Note: at the point we call Reply(), we no longer own requestString.
364
365 if( result.has_value() )
366 {
367 result->mutable_header()->set_kicad_token( m_token );
368 m_server->Reply( result->SerializeAsString() );
369
370 if( ADVANCED_CFG::GetCfg().m_EnableAPILogging )
371 log( "Response: " + result->Utf8DebugString() );
372 }
373 else
374 {
375 ApiResponse error;
376 error.mutable_status()->CopyFrom( result.error() );
377 error.mutable_header()->set_kicad_token( m_token );
378
379 if( result.error().status() == ApiStatusCode::AS_UNHANDLED )
380 {
381 std::string type;
382
383 if( !google::protobuf::Any::ParseAnyTypeUrl( request.message().type_url(), &type ) )
384 type = "<unparseable Any>";
385
386 std::string msg = fmt::format( "no handler available for request of type {}", type );
387 error.mutable_status()->set_error_message( msg );
388 }
389
390 m_server->Reply( error.SerializeAsString() );
391
392 if( ADVANCED_CFG::GetCfg().m_EnableAPILogging )
393 log( "Response (ERROR): " + error.Utf8DebugString() );
394 }
395}
396
397
398void KICAD_API_SERVER::log( const std::string& aOutput )
399{
400 FILE* fp = wxFopen( m_logFilePath.GetFullPath(), wxT( "a" ) );
401
402 if( !fp )
403 return;
404
405 wxString out;
406 wxDateTime now = wxDateTime::Now();
407
408 fprintf( fp, "%s", TO_UTF8( out.Format( wxS( "%s: %s" ),
409 now.FormatISOCombined(), aOutput ) ) );
410 fclose( fp );
411}
tl::expected< ApiResponse, ApiResponseStatus > API_RESULT
Definition api_handler.h:44
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.
Definition api_server.h:42
std::string m_token
Definition api_server.h:154
bool Running() const
void handleApiEvent(wxCommandEvent &aEvent)
Event handler that receives the event on the main thread sent by onApiRequest.
wxFileName m_logFilePath
Definition api_server.h:164
std::function< void(kiapi::common::types::DocumentType, const wxString &, const wxString &)> m_renameListener
Definition api_server.h:158
static wxString s_logFileName
Definition api_server.h:162
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
Definition api_server.h:160
std::set< API_HANDLER * > m_handlers
Definition api_server.h:152
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
Definition api_server.h:156
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
Definition api_server.h:150
Definition kiid.h:46
static wxString GetLogsPath()
Gets a path to use for user-visible log files.
Definition paths.cpp:459
static bool EnsurePathExists(const wxString &aPath, bool aPathToFile=false)
Attempts to create a given path if it does not exist.
Definition paths.cpp:470
const wxChar *const traceApi
Flag to enable debug output related to the IPC API and its plugin system.
Definition api_utils.cpp:33
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
#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.