Assists music production by grouping standalone programs into sessions. Community version of "Non Session Manager".
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2514 lines
64KB

  1. /*******************************************************************************/
  2. /* Copyright (C) 2008-2020 Jonathan Moore Liles (as "Non-Session-Manager") */
  3. /* Copyright (C) 2020- Nils Hilbricht */
  4. /* */
  5. /* This file is part of New-Session-Manager */
  6. /* */
  7. /* New-Session-Manager is free software: you can redistribute it and/or modify */
  8. /* it under the terms of the GNU General Public License as published by */
  9. /* the Free Software Foundation, either version 3 of the License, or */
  10. /* (at your option) any later version. */
  11. /* */
  12. /* New-Session-Manager is distributed in the hope that it will be useful, */
  13. /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
  14. /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
  15. /* GNU General Public License for more details. */
  16. /* */
  17. /* You should have received a copy of the GNU General Public License */
  18. /* along with New-Session-Manager. If not, see <https://www.gnu.org/licenses/>.*/
  19. /*******************************************************************************/
  20. #define __MODULE__ "nsmd"
  21. //debug.c has only one function that gets used multiple times by debug.h and for logging and printing
  22. #include "debug.h"
  23. #ifndef _GNU_SOURCE
  24. #define _GNU_SOURCE
  25. #endif
  26. #include <errno.h>
  27. #include <string.h>
  28. #include <list>
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <unistd.h>
  32. #include <sys/types.h>
  33. #include <signal.h>
  34. #include <sys/signalfd.h>
  35. #include <sys/stat.h>
  36. #include <sys/wait.h>
  37. #include <unistd.h>
  38. #include <time.h>
  39. #include <libgen.h>
  40. #include <dirent.h>
  41. #include <ftw.h>
  42. #include <list>
  43. #include <getopt.h>
  44. #include <sys/time.h>
  45. #include "Endpoint.hpp"
  46. /* for locking */
  47. #include "file.h"
  48. #include <map>
  49. #include <string>
  50. #include <algorithm>
  51. #pragma GCC diagnostic ignored "-Wunused-parameter"
  52. #pragma GCC diagnostic ignored "-Wunused-result"
  53. static OSC::Endpoint *osc_server;
  54. static lo_address gui_addr;
  55. static bool gui_is_active = false;
  56. static int signal_fd;
  57. static int session_lock_fd = 0;
  58. static char *session_root;
  59. #define NSM_API_VERSION_MAJOR 1
  60. #define NSM_API_VERSION_MINOR 2
  61. #define ERR_OK 0
  62. #define ERR_GENERAL_ERROR -1
  63. #define ERR_INCOMPATIBLE_API -2
  64. #define ERR_BLACKLISTED -3
  65. #define ERR_LAUNCH_FAILED -4
  66. #define ERR_NO_SUCH_FILE -5
  67. #define ERR_NO_SESSION_OPEN -6
  68. #define ERR_UNSAVED_CHANGES -7
  69. #define ERR_NOT_NOW -8
  70. #define ERR_BAD_PROJECT -9
  71. #define ERR_CREATE_FAILED -10
  72. #define ERR_SESSION_LOCKED -11
  73. #define ERR_OPERATION_PENDING -12
  74. #define APP_TITLE "New Session Manager"
  75. enum {
  76. COMMAND_NONE = 0,
  77. COMMAND_QUIT,
  78. COMMAND_KILL,
  79. COMMAND_SAVE,
  80. COMMAND_OPEN,
  81. COMMAND_START,
  82. COMMAND_CLOSE,
  83. COMMAND_DUPLICATE,
  84. COMMAND_NEW
  85. };
  86. static int pending_operation = COMMAND_NONE;
  87. static void wait ( long );
  88. #define GUIMSG( fmt, args... ) \
  89. { \
  90. MESSAGE( fmt, ## args ); \
  91. if ( gui_is_active ) \
  92. { \
  93. char *s;\
  94. asprintf( &s, fmt, ## args );\
  95. osc_server->send( gui_addr, "/nsm/gui/server/message", s);\
  96. free(s);\
  97. }\
  98. }
  99. struct Client
  100. {
  101. private:
  102. int _reply_errcode;
  103. char *_reply_message;
  104. int _pending_command;
  105. struct timeval _command_sent_time;
  106. bool _gui_visible;
  107. char *_label;
  108. public:
  109. lo_address addr; /* */
  110. char *name; /* client application name */
  111. char *executable_path; /* path to client executable */
  112. int pid; /* PID of client process */
  113. float progress; /* */
  114. bool active; /* NSM capable: client has registered via announce */
  115. //bool stopped; /* the client quit, but not because we told it to--user still has to decide to remove it from the session */
  116. char *client_id; /* short part of client ID */
  117. char *capabilities; /* client capabilities... will be null for dumb clients */
  118. bool dirty; /* flag for client self-reported dirtiness */
  119. bool pre_existing;
  120. const char *status;
  121. int launch_error; /* APIv1.2, leads to status for executable not found, permission denied etc. */
  122. const char *label ( void ) const { return _label; }
  123. void label ( const char *l )
  124. {
  125. if ( _label )
  126. free( _label );
  127. if ( l )
  128. _label = strdup( l );
  129. else
  130. _label = NULL;
  131. }
  132. bool gui_visible ( void ) const
  133. {
  134. return _gui_visible;
  135. }
  136. void gui_visible ( bool b )
  137. {
  138. _gui_visible = b;
  139. }
  140. bool
  141. has_error ( void ) const
  142. {
  143. return _reply_errcode != 0;
  144. }
  145. int
  146. error_code ( void ) const
  147. {
  148. return _reply_errcode;
  149. }
  150. const char * message ( void )
  151. {
  152. return _reply_message;
  153. }
  154. void
  155. set_reply ( int errcode, const char *message )
  156. {
  157. if ( _reply_message )
  158. free( _reply_message );
  159. _reply_message = strdup( message );
  160. _reply_errcode = errcode;
  161. }
  162. bool reply_pending ( void )
  163. {
  164. return _pending_command != COMMAND_NONE;
  165. }
  166. bool is_dumb_client ( void )
  167. {
  168. return capabilities == NULL;
  169. }
  170. void pending_command ( int command )
  171. {
  172. gettimeofday( &_command_sent_time, NULL );
  173. _pending_command = command;
  174. }
  175. double milliseconds_since_last_command ( void ) const
  176. {
  177. struct timeval now;
  178. gettimeofday( &now, NULL );
  179. double elapsedms = ( now.tv_sec - _command_sent_time.tv_sec ) * 1000.0;
  180. elapsedms += ( now.tv_usec - _command_sent_time.tv_usec ) / 1000.0;
  181. return elapsedms;
  182. }
  183. int pending_command ( void )
  184. {
  185. return _pending_command;
  186. }
  187. // capability should be enclosed in colons. I.e. ":switch:"
  188. bool
  189. is_capable_of ( const char *capability ) const
  190. {
  191. return capabilities &&
  192. strstr( capabilities, capability );
  193. }
  194. const char * name_with_id ( void ) const
  195. {
  196. char *full_client_id;
  197. asprintf( &full_client_id, "%s.%s", name, client_id );
  198. return full_client_id;
  199. }
  200. Client ( )
  201. {
  202. _label = 0;
  203. _gui_visible = true;
  204. addr = 0;
  205. _reply_errcode = 0;
  206. _reply_message = 0;
  207. pid = 0;
  208. progress = -0;
  209. _pending_command = 0;
  210. active = false;
  211. client_id = 0;
  212. capabilities = 0;
  213. name = 0;
  214. executable_path = 0;
  215. pre_existing = false;
  216. launch_error = 0;
  217. }
  218. ~Client ( )
  219. {
  220. if ( name )
  221. free(name);
  222. if (executable_path)
  223. free(executable_path);
  224. if (client_id)
  225. free(client_id);
  226. if (capabilities)
  227. free(capabilities);
  228. name = executable_path = client_id = capabilities = NULL;
  229. }
  230. };
  231. static std::list< Client* > client;
  232. /* helper macros for defining OSC handlers */
  233. #define OSC_NAME( name ) osc_ ## name
  234. // #define OSCDMSG() DMESSAGE( "Got OSC message: %s", path );
  235. #define OSC_HANDLER( name ) static int OSC_NAME( name ) ( const char *path, const char *types, lo_arg **argv, int argc, lo_message msg, void *user_data )
  236. static char *session_path = NULL;
  237. static char *session_name = NULL;
  238. bool
  239. clients_have_errors ( )
  240. {
  241. for ( std::list<Client*>::const_iterator i = client.begin();
  242. i != client.end();
  243. ++i )
  244. if ( (*i)->active && (*i)->has_error() )
  245. return true;
  246. return false;
  247. }
  248. Client *
  249. get_client_by_pid ( int pid )
  250. {
  251. std::list<Client*> *cl = &client;
  252. for ( std::list<Client*>::const_iterator i = cl->begin();
  253. i != cl->end();
  254. ++i )
  255. if ( (*i)->pid == pid )
  256. return *i;
  257. return NULL;
  258. }
  259. void clear_clients ( void )
  260. {
  261. std::list<Client*> *cl = &client;
  262. for ( std::list<Client*>::iterator i = cl->begin();
  263. i != cl->end();
  264. ++i )
  265. {
  266. delete *i;
  267. i = cl->erase( i );
  268. }
  269. }
  270. void
  271. handle_client_process_death ( int pid )
  272. {
  273. Client *c = get_client_by_pid( (int)pid );
  274. if ( c )
  275. {
  276. //There is a difference if a client quit on its own, e.g. via a menu or window manager,
  277. //or if the server send SIGTERM as quit signal. Both cases are equally valid.
  278. //We only check the case to print a different log message
  279. bool dead_because_we_said = ( c->pending_command() == COMMAND_KILL ||
  280. c->pending_command() == COMMAND_QUIT );
  281. if ( dead_because_we_said )
  282. {
  283. GUIMSG( "Client %s terminated by server instruction.", c->name_with_id() );
  284. }
  285. else
  286. {
  287. GUIMSG( "Client %s terminated itself.", c->name_with_id() );
  288. }
  289. //Decide if the client terminated or if removed from the session
  290. if ( c->pending_command() == COMMAND_QUIT )
  291. {
  292. if ( gui_is_active )
  293. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "removed" );
  294. client.remove(c); //This will not remove the clients save data
  295. delete c;
  296. }
  297. else
  298. {
  299. if ( gui_is_active )
  300. {
  301. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "stopped" );
  302. if ( c->launch_error )
  303. {
  304. /* NSM API treats the stopped status as switch. You can only remove stopped.
  305. * Furthermore the GUI will change its client-buttons.
  306. * In consequence we cannot add an arbitrary "launch-error" status.
  307. * Compatible compromise is to use the label field to relay info the user,
  308. * which was the goal. There is nothing we can do about a failed launch anyway.
  309. */
  310. GUIMSG("Client %s had a launch error.", c->name_with_id());
  311. osc_server->send( gui_addr, "/nsm/gui/client/label", c->client_id, "launch error!" ); //do not set the client objects label.
  312. }
  313. }
  314. }
  315. c->pending_command( COMMAND_NONE );
  316. c->active = false;
  317. c->pid = 0;
  318. }
  319. }
  320. void handle_sigchld ( )
  321. {
  322. // compare waitpid(2)
  323. for ( ;; )
  324. {
  325. int status = 1; // make it not NULL to enable information storage in status
  326. pid_t pid = waitpid(-1, &status, WNOHANG); //-1 meaning wait for any child process. pid_t is signed integer
  327. if (pid <= 0)
  328. {
  329. break; // no child process has ended this loop. Check again.
  330. }
  331. else
  332. {
  333. //One child process has stopped. Find which and figure out the stop-conditions
  334. Client *c;
  335. c = get_client_by_pid( pid );
  336. if ( c )
  337. {
  338. //The following will not trigger with normal crashes, e.g. segfaults or python tracebacks
  339. if ( WIFEXITED( status ) ) // returns true if the child terminated normally
  340. if ( WEXITSTATUS( status ) == 255 ) // as given by exit(-1) in launch()
  341. c->launch_error = true;
  342. }
  343. // Call even if Client was already null. This will check itself again and was expected
  344. // to be called for the majority of nsmds development
  345. handle_client_process_death( pid );
  346. }
  347. }
  348. }
  349. int
  350. path_is_valid ( const char *path )
  351. {
  352. char *s;
  353. asprintf( &s, "/%s/", path );
  354. int r = strstr( s, "/../" ) == NULL;
  355. free( s );
  356. return r;
  357. }
  358. int
  359. mkpath ( const char *path, bool create_final_directory )
  360. {
  361. char *p = strdup( path );
  362. char *i = p + 1;
  363. while ( ( i = index( i, '/' ) ) )
  364. {
  365. *i = 0;
  366. struct stat st;
  367. if ( stat( p, &st ) )
  368. {
  369. if ( mkdir( p, 0711 ) )
  370. {
  371. free( p );
  372. return -1;
  373. }
  374. }
  375. *i = '/';
  376. i++;
  377. }
  378. if ( create_final_directory )
  379. {
  380. if ( mkdir( p, 0711 ) )
  381. {
  382. free( p );
  383. return -1;
  384. }
  385. }
  386. free( p );
  387. return 0;
  388. }
  389. void
  390. set_name ( const char *name )
  391. {
  392. if ( session_name )
  393. free( session_name );
  394. char *s = strdup( name );
  395. session_name = strdup( basename( s ) );
  396. free( s );
  397. }
  398. bool
  399. address_matches ( lo_address addr1, lo_address addr2 )
  400. {
  401. /* char *url1 = lo_address_get_url( addr1 ); */
  402. /* char *url2 = lo_address_get_url( addr2 ); */
  403. char *url1 = strdup( lo_address_get_port( addr1 ) );
  404. char *url2 = strdup(lo_address_get_port( addr2 ) );
  405. bool r = !strcmp( url1, url2 );
  406. free( url1 );
  407. free( url2 );
  408. return r;
  409. }
  410. Client *
  411. get_client_by_id ( std::list<Client*> *cl, const char *id )
  412. {
  413. for ( std::list<Client*>::const_iterator i = cl->begin();
  414. i != cl->end();
  415. ++i )
  416. if ( !strcmp( (*i)->client_id, id ) )
  417. return *i;
  418. return NULL;
  419. }
  420. Client *
  421. get_client_by_name_and_id ( std::list<Client*> *cl, const char *name, const char *id )
  422. {
  423. for ( std::list<Client*>::const_iterator i = cl->begin();
  424. i != cl->end();
  425. ++i )
  426. if ( !strcmp( (*i)->client_id, id ) &&
  427. ! strcmp( (*i)->name, name ) )
  428. return *i;
  429. return NULL;
  430. }
  431. Client *
  432. get_client_by_address ( lo_address addr )
  433. {
  434. for ( std::list<Client*>::iterator i = client.begin();
  435. i != client.end();
  436. ++i )
  437. if ( (*i)->addr && address_matches( (*i)->addr, addr ) )
  438. return *i;
  439. return NULL;
  440. }
  441. char *
  442. generate_client_id ( void )
  443. {
  444. /* Before v1.4 this returned "n" + 4 random upper-case letters, which could lead to collisions.
  445. We changed behaviour to still generate 4 letters, but check for collision with existing IDs.
  446. Loaded client IDs are not checked, just copied from session.nsm because loading happens before
  447. any generation of new clients. Loaded clients are part of further checks of course.
  448. There is a theoretical limit when all 26^4 IDs are in use which will lead to an infinite loop
  449. of generation. We risk to leave this unhandled. */
  450. char id_str[6];
  451. id_str[0] = 'n';
  452. id_str[5] = 0;
  453. while ( true )
  454. {
  455. for ( int i = 1; i < 5; i++ )
  456. id_str[i] = 'A' + (rand() % 25);
  457. if ( get_client_by_id(&client, id_str )==NULL ) // found a free id
  458. break;
  459. }
  460. return strdup(id_str);
  461. }
  462. bool
  463. replies_still_pending ( void )
  464. {
  465. for ( std::list<Client*>::const_iterator i = client.begin();
  466. i != client.end();
  467. ++i )
  468. if ( (*i)->active && (*i)->reply_pending() )
  469. return true;
  470. return false;
  471. }
  472. int
  473. number_of_reponsive_clients ( void )
  474. {
  475. /* This was renamed from number_of_active_clients in version 1.4 to reflect
  476. * that not only active==true clients are in a state where waiting has ended, but also clients
  477. * that never started. It is used in wait_for_announce only, which added a 5000ms delay to startup
  478. *
  479. * We are sadly unable to distinguish between a client that has a slow announce and a client
  480. * without NSM-support. However, this is mitgated by nsm-proxy which is a reliable indicator
  481. * that this program will never announce (or rather nsm-proxy announces normally).
  482. */
  483. int responsive = 0;
  484. for ( std::list<Client*>::const_iterator i = client.begin(); i != client.end(); i++ )
  485. {
  486. //Optimisation: Clients that never launched (e.g. file not found) will be checked many times/seconds here. We skip them by counting them
  487. if ( (*i)->active || (*i)->launch_error )
  488. responsive++;
  489. }
  490. return responsive;
  491. }
  492. void
  493. wait_for_announce ( void )
  494. {
  495. GUIMSG( "Waiting for announce messages from clients" );
  496. int n = 5 * 1000;
  497. long unsigned int active;
  498. while ( n > 0 )
  499. {
  500. n -= 100;
  501. wait(100);
  502. active = number_of_reponsive_clients();
  503. if ( client.size() == active )
  504. break;
  505. }
  506. GUIMSG( "Done. %lu out of %lu clients announced (or failed to launch) within the initialization grace period",
  507. active, (long unsigned)client.size() );
  508. }
  509. void
  510. wait_for_replies ( void )
  511. {
  512. GUIMSG( "Waiting for clients to reply to commands" );
  513. int n = 60 * 1000; /* 60 seconds */
  514. while ( n )
  515. {
  516. n -= 100;
  517. wait(100);
  518. if ( ! replies_still_pending() )
  519. break;
  520. }
  521. GUIMSG( "Done waiting" );
  522. /* FIXME: do something about unresponsive clients */
  523. }
  524. char *
  525. get_client_project_path ( const char *session_path, Client *c )
  526. {
  527. char *client_project_path;
  528. asprintf( &client_project_path, "%s/%s.%s", session_path, c->name, c->client_id );
  529. return client_project_path;
  530. }
  531. bool
  532. launch ( const char *executable, const char *client_id )
  533. {
  534. Client *c;
  535. if ( !client_id || !( c = get_client_by_id( &client, client_id ) ) )
  536. {
  537. c = new Client();
  538. c->executable_path = strdup( executable );
  539. {
  540. char *s = strdup( c->executable_path );
  541. c->name = strdup( basename( s ) );
  542. free( s );
  543. }
  544. if ( client_id )
  545. c->client_id = strdup( client_id );
  546. else
  547. c->client_id = generate_client_id();
  548. client.push_back( c );
  549. }
  550. char * url = osc_server->url();
  551. int pid;
  552. if ( ! (pid = fork()) )
  553. {
  554. //This is code of the child process. It will be executed after launch() has finished
  555. GUIMSG( "Launching %s", executable );
  556. char *args[] = { strdup( executable ), NULL };
  557. setenv( "NSM_URL", url, 1 );
  558. /* Ensure the launched process can receive SIGCHLD */
  559. /* Unblocking SIGCHLD here does NOT unblock it for nsmd itself */
  560. sigset_t mask;
  561. sigemptyset( &mask );
  562. sigaddset( &mask, SIGCHLD );
  563. sigprocmask(SIG_UNBLOCK, &mask, NULL );
  564. if ( -1 == execvp( executable, args ) )
  565. {
  566. /* The program was not started. Causes: not installed on the current system, and the
  567. * session was transferred from another system, or permission denied (no executable flag)
  568. * Since we are running in a forked child process Client c does exist, but points to
  569. * a memory copy, not the real client. So we can't set any error code or status in the
  570. * client object. Instead we check the exit return code in handle_sigchld() and set the
  571. * bool client->launch_error to true.
  572. */
  573. WARNING( "Error starting process %s: %s", executable, strerror( errno ) );
  574. exit(-1); //-1 later parsed as 255
  575. }
  576. }
  577. //This is code of the parent process. It is executed right at this point, before the child.
  578. c->pending_command( COMMAND_START );
  579. c->pid = pid;
  580. MESSAGE( "Process %s has pid: %i", executable, pid ); //We do not have a name yet, use executable
  581. if ( gui_is_active )
  582. {
  583. //At this point we do not know if launched program will start or fail
  584. //And we do not know if it has nsm-support or not. This will be decided if it announces.
  585. osc_server->send( gui_addr, "/nsm/gui/client/new", c->client_id, c->name );
  586. osc_server->send( gui_addr, "/nsm/gui/client/label", c->client_id, "" ); //clear label from potential previous-and-fixed launch error
  587. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "launch" );
  588. }
  589. return true;
  590. }
  591. void
  592. command_client_to_save ( Client *c )
  593. {
  594. if ( c->active )
  595. {
  596. MESSAGE( "Telling %s to save", c->name_with_id() );
  597. osc_server->send( c->addr, "/nsm/client/save" );
  598. c->pending_command( COMMAND_SAVE );
  599. if ( gui_is_active )
  600. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "save" );
  601. }
  602. else if ( c->is_dumb_client() && c->pid )
  603. {
  604. // this is a dumb client...
  605. if ( gui_is_active )
  606. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "noop" );
  607. }
  608. }
  609. void command_client_to_switch ( Client *c, const char *new_client_id )
  610. {
  611. char *old_client_id = c->client_id;
  612. c->client_id = strdup( new_client_id );
  613. char *client_project_path = get_client_project_path( session_path, c );
  614. MESSAGE( "Commanding %s to switch \"%s\"", c->name_with_id(), client_project_path );
  615. char *full_client_id;
  616. asprintf( &full_client_id, "%s.%s", c->name, c->client_id );
  617. osc_server->send( c->addr, "/nsm/client/open", client_project_path, session_name, full_client_id );
  618. free( full_client_id );
  619. free( client_project_path );
  620. c->pending_command( COMMAND_OPEN );
  621. if ( gui_is_active )
  622. {
  623. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "switch" );
  624. osc_server->send( gui_addr, "/nsm/gui/client/switch", old_client_id, c->client_id );
  625. }
  626. free( old_client_id );
  627. }
  628. void
  629. purge_inactive_clients ( )
  630. {
  631. for ( std::list<Client*>::iterator i = client.begin();
  632. i != client.end();
  633. ++i )
  634. {
  635. if ( ! (*i)->active )
  636. {
  637. if ( gui_is_active )
  638. osc_server->send( gui_addr, "/nsm/gui/client/status", (*i)->client_id, (*i)->status = "removed" );
  639. delete *i;
  640. i = client.erase( i );
  641. }
  642. }
  643. }
  644. bool
  645. process_is_running ( int pid )
  646. {
  647. if ( 0 == kill( pid, 0 ) )
  648. {
  649. return true;
  650. }
  651. else if ( ESRCH == errno )
  652. {
  653. return false;
  654. }
  655. return false;
  656. }
  657. void
  658. purge_dead_clients ( )
  659. {
  660. std::list<Client*> tmp( client );
  661. for ( std::list<Client*>::const_iterator i = tmp.begin();
  662. i != tmp.end();
  663. ++i )
  664. {
  665. const Client *c = *i;
  666. if ( c->pid )
  667. {
  668. if ( ! process_is_running( c->pid ) )
  669. handle_client_process_death( c->pid );
  670. }
  671. }
  672. }
  673. /************************/
  674. /* OSC Message Handlers */
  675. /************************/
  676. OSC_HANDLER( add )
  677. {
  678. if ( ! session_path )
  679. {
  680. osc_server->send( lo_message_get_source( msg ), "/error", path,
  681. ERR_NO_SESSION_OPEN,
  682. "Cannot add to session because no session is loaded." );
  683. return 0;
  684. }
  685. if ( strchr( &argv[0]->s, '/' ) )
  686. {
  687. osc_server->send( lo_message_get_source( msg ), "/error", path,
  688. ERR_LAUNCH_FAILED,
  689. "Absolute paths are not permitted. Clients must be in $PATH" );
  690. return 0;
  691. }
  692. if ( ! launch( &argv[0]->s, NULL ) )
  693. {
  694. osc_server->send( lo_message_get_source( msg ), "/error", path,
  695. ERR_LAUNCH_FAILED,
  696. "Failed to launch process!" );
  697. }
  698. else
  699. {
  700. osc_server->send( lo_message_get_source( msg ), "/reply", path, "Launched." );
  701. }
  702. return 0;
  703. }
  704. OSC_HANDLER( announce )
  705. {
  706. const char *client_name = &argv[0]->s;
  707. const char *capabilities = &argv[1]->s;
  708. const char *executable_path = &argv[2]->s;
  709. int major = argv[3]->i;
  710. int minor = argv[4]->i;
  711. int pid = argv[5]->i;
  712. GUIMSG( "Got announce from %s", client_name );
  713. if ( ! session_path )
  714. {
  715. osc_server->send( lo_message_get_source( msg ), "/error",
  716. path,
  717. ERR_NO_SESSION_OPEN,
  718. "Sorry, but there's no session open for this application to join." );
  719. return 0;
  720. }
  721. bool expected_client = false;
  722. Client *c = NULL;
  723. for ( std::list<Client*>::iterator i = client.begin();
  724. i != client.end();
  725. ++i )
  726. {
  727. if ( ! strcmp( (*i)->executable_path, executable_path ) &&
  728. ! (*i)->active &&
  729. (*i)->pending_command() == COMMAND_START )
  730. {
  731. // I think we've found the slot we were looking for.
  732. MESSAGE( "Client %s was expected.", (*i)->name );
  733. c = *i;
  734. break;
  735. }
  736. }
  737. if ( ! c )
  738. {
  739. c = new Client();
  740. c->executable_path = strdup( executable_path );
  741. c->client_id = generate_client_id();
  742. }
  743. else
  744. expected_client = true;
  745. if ( major > NSM_API_VERSION_MAJOR )
  746. {
  747. MESSAGE( "Client %s is using incompatible and more recent API version %i.%i", c->name_with_id(), major, minor );
  748. osc_server->send( lo_message_get_source( msg ), "/error",
  749. path,
  750. ERR_INCOMPATIBLE_API,
  751. "Server is using an incompatible API version." );
  752. return 0;
  753. }
  754. c->pid = pid;
  755. c->capabilities = strdup( capabilities );
  756. c->addr = lo_address_new_from_url( lo_address_get_url( lo_message_get_source( msg ) ));
  757. c->name = strdup( client_name );
  758. c->active = true;
  759. MESSAGE( "Process %s has pid: %i", c->name_with_id(), pid );
  760. if ( ! expected_client )
  761. client.push_back( c );
  762. MESSAGE( "The client \"%s\" at \"%s\" informs us it's ready to receive commands.", &argv[0]->s, lo_address_get_url( c->addr ) );
  763. osc_server->send( lo_message_get_source( msg ), "/reply",
  764. path,
  765. expected_client ?
  766. "Howdy, what took you so long?" :
  767. "Well hello, stranger. Welcome to the party.",
  768. APP_TITLE,
  769. ":server-control:broadcast:optional-gui:" );
  770. if ( gui_is_active )
  771. {
  772. osc_server->send( gui_addr, "/nsm/gui/client/new", c->client_id, c->name );
  773. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "open" );
  774. if ( c->is_capable_of( ":optional-gui:" ) )
  775. osc_server->send( gui_addr, "/nsm/gui/client/has_optional_gui", c->client_id );
  776. }
  777. {
  778. char *full_client_id;
  779. asprintf( &full_client_id, "%s.%s", c->name, c->client_id );
  780. char *client_project_path = get_client_project_path( session_path, c );
  781. osc_server->send( lo_message_get_source( msg ), "/nsm/client/open", client_project_path, session_name, full_client_id );
  782. c->pending_command( COMMAND_OPEN );
  783. free( full_client_id );
  784. free( client_project_path );
  785. }
  786. return 0;
  787. }
  788. void
  789. save_session_file ( )
  790. {
  791. char *session_file = NULL;
  792. asprintf( &session_file, "%s/session.nsm", session_path );
  793. FILE *fp = fopen( session_file, "w+" );
  794. free( session_file );
  795. /* FIXME: handle errors. */
  796. for ( std::list<Client*>::iterator i = client.begin();
  797. i != client.end();
  798. ++i )
  799. {
  800. fprintf( fp, "%s:%s:%s\n", (*i)->name, (*i)->executable_path, (*i)->client_id );
  801. }
  802. fclose( fp );
  803. }
  804. Client *
  805. client_by_name ( const char *name,
  806. std::list<Client*> *cl )
  807. {
  808. for ( std::list<Client*>::iterator i = cl->begin();
  809. i != cl->end();
  810. ++i )
  811. {
  812. if ( !strcmp( name, (*i)->name ) )
  813. return *i;
  814. }
  815. return NULL;
  816. }
  817. bool
  818. dumb_clients_are_alive ( )
  819. {
  820. std::list<Client*> *cl = &client;
  821. for ( std::list<Client*>::iterator i = cl->begin();
  822. i != cl->end();
  823. ++i )
  824. {
  825. if ( (*i)->is_dumb_client() && (*i)->pid > 0 )
  826. {
  827. MESSAGE( "Waiting for %s", (*i)->name_with_id() ); //This replaced the Loop 1, Loop 2 ... 60 message from wait_for_dumb_clients_to_die where you couldn't see which client actually was hanging
  828. return true;
  829. }
  830. }
  831. return false;
  832. }
  833. void
  834. wait_for_dumb_clients_to_die ( )
  835. {
  836. struct signalfd_siginfo fdsi;
  837. GUIMSG( "Waiting for any dumb clients to die." );
  838. for ( int i = 0; i < 6; i++ )
  839. {
  840. if ( ! dumb_clients_are_alive() )
  841. break;
  842. ssize_t s = read(signal_fd, &fdsi, sizeof(struct signalfd_siginfo));
  843. if (s == sizeof(struct signalfd_siginfo))
  844. {
  845. if (fdsi.ssi_signo == SIGCHLD)
  846. handle_sigchld();
  847. }
  848. usleep( 50000 );
  849. }
  850. GUIMSG( "Done waiting" );
  851. /* FIXME: give up on remaining clients and purge them */
  852. }
  853. bool
  854. killed_clients_are_alive ( )
  855. {
  856. std::list<Client*> *cl = &client;
  857. for ( std::list<Client*>::iterator i = cl->begin();
  858. i != cl->end();
  859. ++i )
  860. {
  861. if ( ( (*i)->pending_command() == COMMAND_QUIT ||
  862. (*i)->pending_command() == COMMAND_KILL ) &&
  863. (*i)->pid > 0 )
  864. {
  865. MESSAGE( "Waiting for %s", (*i)->name_with_id() ); //This replaced the Loop 1, Loop 2 ... 60 message from wait_for_killed_clients_to_die where you couldn't see which client actually was hanging
  866. return true;
  867. }
  868. }
  869. return false;
  870. }
  871. void
  872. wait_for_killed_clients_to_die ( )
  873. {
  874. struct signalfd_siginfo fdsi;
  875. MESSAGE( "Waiting for killed clients to die." );
  876. for ( int i = 0; i < 60; i++ )
  877. {
  878. if ( ! killed_clients_are_alive() )
  879. goto done;
  880. ssize_t s = read(signal_fd, &fdsi, sizeof(struct signalfd_siginfo));
  881. if (s == sizeof(struct signalfd_siginfo))
  882. {
  883. if (fdsi.ssi_signo == SIGCHLD)
  884. handle_sigchld();
  885. }
  886. purge_dead_clients();
  887. /* check OSC so we can get /progress messages. */
  888. osc_server->check();
  889. sleep(1);
  890. }
  891. WARNING( "Killed clients are still alive" );
  892. return;
  893. done:
  894. MESSAGE( "All clients have died." );
  895. }
  896. void
  897. command_all_clients_to_save ( )
  898. {
  899. if ( session_path )
  900. {
  901. GUIMSG( "Commanding attached clients to save." );
  902. for ( std::list<Client*>::iterator i = client.begin();
  903. i != client.end();
  904. ++i )
  905. {
  906. command_client_to_save( *i );
  907. }
  908. wait_for_replies();
  909. save_session_file();
  910. }
  911. }
  912. void
  913. command_client_to_stop ( Client *c )
  914. {
  915. GUIMSG( "Stopping client %s", c->name_with_id() );
  916. if ( c->pid > 0 )
  917. {
  918. c->pending_command( COMMAND_KILL );
  919. kill( c->pid, SIGTERM );
  920. if ( gui_is_active )
  921. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "stopped" );
  922. }
  923. }
  924. void
  925. command_client_to_quit ( Client *c )
  926. {
  927. MESSAGE( "Commanding %s to quit", c->name_with_id() );
  928. if ( c->active )
  929. {
  930. c->pending_command( COMMAND_QUIT );
  931. kill( c->pid, SIGTERM );
  932. if ( gui_is_active )
  933. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "quit" );
  934. }
  935. else if ( c->is_dumb_client() )
  936. {
  937. if ( c->pid > 0 )
  938. {
  939. if ( gui_is_active )
  940. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "quit" );
  941. /* should be kill? */
  942. c->pending_command( COMMAND_QUIT );
  943. // this is a dumb client... try and kill it
  944. kill( c->pid, SIGTERM );
  945. }
  946. else
  947. {
  948. if ( gui_is_active )
  949. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "removed" );
  950. }
  951. }
  952. }
  953. void
  954. close_session ( )
  955. {
  956. if ( ! session_path )
  957. return;
  958. for ( std::list<Client*>::iterator i = client.begin();
  959. i != client.end();
  960. ++i )
  961. {
  962. command_client_to_quit( *i );
  963. }
  964. wait_for_killed_clients_to_die();
  965. purge_inactive_clients();
  966. clear_clients();
  967. if ( session_path )
  968. {
  969. char *session_lock;
  970. asprintf( &session_lock, "%s/.lock", session_path );
  971. release_lock( &session_lock_fd, session_lock );
  972. free(session_lock);
  973. free(session_path);
  974. session_path = NULL;
  975. free(session_name);
  976. session_name = NULL;
  977. }
  978. if ( gui_is_active )
  979. {
  980. osc_server->send( gui_addr, "/nsm/gui/session/name", "", "" );
  981. }
  982. }
  983. void
  984. tell_client_session_is_loaded( Client *c )
  985. {
  986. if ( c->active )
  987. //!c->is_dumb_client() )
  988. {
  989. MESSAGE( "Telling client %s that session is loaded.", c->name_with_id() );
  990. osc_server->send( c->addr, "/nsm/client/session_is_loaded" );
  991. }
  992. }
  993. void
  994. tell_all_clients_session_is_loaded ( void )
  995. {
  996. MESSAGE( "Telling all clients that session is loaded..." );
  997. for ( std::list<Client*>::iterator i = client.begin();
  998. i != client.end();
  999. ++i )
  1000. {
  1001. tell_client_session_is_loaded( *i );
  1002. }
  1003. }
  1004. int
  1005. load_session_file ( const char * path )
  1006. {
  1007. char *session_file = NULL;
  1008. asprintf( &session_file, "%s/session.nsm", path );
  1009. char *session_lock = NULL;
  1010. asprintf( &session_lock, "%s/.lock", path );
  1011. if ( ! acquire_lock( &session_lock_fd, session_lock ) )
  1012. {
  1013. free( session_file );
  1014. free( session_lock );
  1015. WARNING( "Session is locked by another process" );
  1016. return ERR_SESSION_LOCKED;
  1017. }
  1018. FILE *fp;
  1019. if ( ! ( fp = fopen( session_file, "r" ) ) )
  1020. {
  1021. free( session_file );
  1022. return ERR_CREATE_FAILED;
  1023. }
  1024. free( session_file );
  1025. session_path = strdup( path );
  1026. set_name( path );
  1027. std::list<Client*> new_clients;
  1028. {
  1029. char * client_name = NULL;
  1030. char * client_executable = NULL;
  1031. char * client_id = NULL;
  1032. // load the client list
  1033. while ( fscanf( fp, "%m[^:]:%m[^:]:%m[^:\n]\n", &client_name, &client_executable, &client_id ) > 0 )
  1034. {
  1035. Client *c = new Client();
  1036. c->name = client_name;
  1037. c->executable_path = client_executable;
  1038. c->client_id = client_id;
  1039. new_clients.push_back( c );
  1040. }
  1041. }
  1042. fclose(fp);
  1043. MESSAGE( "Commanding unneeded and dumb clients to quit" );
  1044. std::map<std::string,int> client_map;
  1045. /* count how many instances of each client are needed in the new session */
  1046. for ( std::list<Client*>::iterator i = new_clients.begin();
  1047. i != new_clients.end();
  1048. ++i )
  1049. {
  1050. if ( client_map.find( (*i)->name) != client_map.end() )
  1051. client_map[(*i)->name]++;
  1052. else
  1053. client_map[(*i)->name] = 1;
  1054. }
  1055. for ( std::list<Client*>::iterator i = client.begin();
  1056. i != client.end();
  1057. ++i )
  1058. {
  1059. if ( ! (*i)->is_capable_of( ":switch:" ) || client_map.find((*i)->name ) == client_map.end() )
  1060. {
  1061. /* client is not capable of switch, or is not wanted in the new session */
  1062. command_client_to_quit( *i );
  1063. }
  1064. else
  1065. {
  1066. /* client is switch capable and may be wanted in the new session */
  1067. if ( client_map[ (*i)->name ]-- <= 0 )
  1068. /* nope,, we already have as many as we need, stop this one */
  1069. command_client_to_quit( *i );
  1070. }
  1071. }
  1072. // wait_for_replies();
  1073. wait_for_killed_clients_to_die();
  1074. // wait_for_dumb_clients_to_die();
  1075. purge_inactive_clients();
  1076. for ( std::list<Client*>::iterator i = client.begin();
  1077. i != client.end();
  1078. ++i )
  1079. {
  1080. (*i)->pre_existing = true;
  1081. }
  1082. MESSAGE( "Commanding smart clients to switch" );
  1083. for ( std::list<Client*>::iterator i = new_clients.begin();
  1084. i != new_clients.end();
  1085. ++i )
  1086. {
  1087. Client *c = NULL;
  1088. /* in a duplicated session, clients will have the same
  1089. * IDs, so be sure to pick the right one to avoid race
  1090. * conditions in JACK name registration. */
  1091. c = get_client_by_name_and_id( &client, (*i)->name, (*i)->client_id );
  1092. if ( ! c )
  1093. c = client_by_name( (*i)->name, &client );
  1094. if ( c && c->pre_existing && !c->reply_pending() )
  1095. {
  1096. // since we already shutdown clients not capable of 'switch', we can assume that these are.
  1097. command_client_to_switch( c, (*i)->client_id );
  1098. }
  1099. else
  1100. {
  1101. /* sleep a little bit because liblo derives its sequence
  1102. * of port numbers from the system time (second
  1103. * resolution) and if too many clients start at once they
  1104. * won't be able to find a free port. */
  1105. usleep( 100 * 1000 );
  1106. launch( (*i)->executable_path, (*i)->client_id );
  1107. }
  1108. }
  1109. /* this part is a little tricky... the clients need some time to
  1110. * send their 'announce' messages before we can send them 'open'
  1111. * and know that a reply is pending and we should continue waiting
  1112. * until they finish. wait_for_replies() must check for OSC
  1113. * messages immediately, even if no replies seem to be pending
  1114. * yet. */
  1115. /* dumb clients will never send an 'announce message', so we need
  1116. * to give up waiting on them fairly soon. */
  1117. wait_for_announce();
  1118. wait_for_replies();
  1119. tell_all_clients_session_is_loaded();
  1120. MESSAGE( "Loaded." );
  1121. new_clients.clear();
  1122. if ( gui_is_active )
  1123. {
  1124. //Send two parameters to signal that the session was loaded. First is the direct session name,
  1125. //second is the full filepath.
  1126. //See function announce_gui for a full description where /nsm/gui/session/name is also send from
  1127. osc_server->send( gui_addr, "/nsm/gui/session/name", session_name, session_path + strlen( session_root ));
  1128. }
  1129. return ERR_OK;
  1130. }
  1131. OSC_HANDLER( save )
  1132. {
  1133. lo_address sender_addr;
  1134. sender_addr = lo_address_new_from_url( lo_address_get_url( lo_message_get_source( msg ) ));
  1135. if ( pending_operation != COMMAND_NONE )
  1136. {
  1137. osc_server->send( sender_addr, "/error", path,
  1138. ERR_OPERATION_PENDING,
  1139. "An operation pending." );
  1140. return 0;
  1141. }
  1142. if ( ! session_path )
  1143. {
  1144. osc_server->send( sender_addr, "/error", path,
  1145. ERR_NO_SESSION_OPEN,
  1146. "No session to save.");
  1147. goto done;
  1148. }
  1149. command_all_clients_to_save();
  1150. MESSAGE( "Done." );
  1151. osc_server->send( sender_addr, "/reply", path, "Saved." );
  1152. done:
  1153. pending_operation = COMMAND_NONE;
  1154. return 0;
  1155. }
  1156. OSC_HANDLER( duplicate )
  1157. {
  1158. lo_address sender_addr;
  1159. sender_addr = lo_address_new_from_url( lo_address_get_url( lo_message_get_source( msg ) ));
  1160. if ( pending_operation != COMMAND_NONE )
  1161. {
  1162. osc_server->send( sender_addr, "/error", path,
  1163. ERR_OPERATION_PENDING,
  1164. "An operation pending." );
  1165. return 0;
  1166. }
  1167. pending_operation = COMMAND_DUPLICATE;
  1168. if ( ! session_path )
  1169. {
  1170. osc_server->send( sender_addr, "/error", path,
  1171. ERR_NO_SESSION_OPEN,
  1172. "No session to duplicate.");
  1173. goto done;
  1174. }
  1175. if ( ! path_is_valid( &argv[0]->s ) )
  1176. {
  1177. osc_server->send( sender_addr, "/error", path,
  1178. ERR_CREATE_FAILED,
  1179. "Invalid session name." );
  1180. goto done;
  1181. }
  1182. command_all_clients_to_save();
  1183. if ( clients_have_errors() )
  1184. {
  1185. osc_server->send( sender_addr, "/error", path,
  1186. ERR_GENERAL_ERROR,
  1187. "Some clients could not save" );
  1188. goto done;
  1189. }
  1190. // save_session_file();
  1191. char *spath;
  1192. asprintf( &spath, "%s/%s", session_root, &argv[0]->s );
  1193. mkpath( spath, false );
  1194. /* FIXME: code a recursive copy instead of calling the shell */
  1195. char *cmd;
  1196. asprintf( &cmd, "cp -R \"%s\" \"%s\"", session_path, spath);
  1197. system( cmd );
  1198. free( cmd );
  1199. osc_server->send( gui_addr, "/nsm/gui/session/session", &argv[0]->s );
  1200. MESSAGE( "Attempting to open %s", spath );
  1201. if ( !load_session_file( spath ) )
  1202. {
  1203. MESSAGE( "Loaded" );
  1204. osc_server->send( sender_addr, "/reply", path,
  1205. "Loaded." );
  1206. }
  1207. else
  1208. {
  1209. MESSAGE( "Failed" );
  1210. osc_server->send( sender_addr, "/error", path,
  1211. ERR_NO_SUCH_FILE,
  1212. "No such file." );
  1213. free(spath);
  1214. return -1;
  1215. }
  1216. free( spath );
  1217. MESSAGE( "Done" );
  1218. osc_server->send( sender_addr, "/reply", path, "Duplicated." );
  1219. done:
  1220. pending_operation = COMMAND_NONE;
  1221. return 0;
  1222. }
  1223. OSC_HANDLER( new )
  1224. {
  1225. lo_address sender_addr;
  1226. sender_addr = lo_address_new_from_url( lo_address_get_url( lo_message_get_source( msg ) ));
  1227. if ( pending_operation != COMMAND_NONE )
  1228. {
  1229. osc_server->send( sender_addr, "/error", path,
  1230. ERR_OPERATION_PENDING,
  1231. "An operation pending." );
  1232. return 0;
  1233. }
  1234. pending_operation = COMMAND_NEW;
  1235. if ( ! path_is_valid( &argv[0]->s ) )
  1236. {
  1237. osc_server->send( sender_addr, "/error", path,
  1238. ERR_CREATE_FAILED,
  1239. "Invalid session name." );
  1240. pending_operation = COMMAND_NONE;
  1241. return 0;
  1242. }
  1243. if ( session_path )
  1244. {
  1245. command_all_clients_to_save();
  1246. close_session();
  1247. }
  1248. GUIMSG( "Creating new session \"%s\"", &argv[0]->s );
  1249. char *spath;
  1250. asprintf( &spath, "%s/%s", session_root, &argv[0]->s );
  1251. if ( mkpath( spath, true ) )
  1252. {
  1253. osc_server->send( sender_addr, "/error", path,
  1254. ERR_CREATE_FAILED,
  1255. "Could not create the session directory" );
  1256. free(spath);
  1257. pending_operation = COMMAND_NONE;
  1258. return 0;
  1259. }
  1260. session_path = strdup( spath );
  1261. set_name( session_path );
  1262. osc_server->send( sender_addr, "/reply", path, "Created." );
  1263. if ( gui_is_active )
  1264. {
  1265. osc_server->send( gui_addr, "/nsm/gui/session/session", &argv[0]->s );
  1266. osc_server->send( gui_addr, "/nsm/gui/session/name", &argv[0]->s, &argv[0]->s );
  1267. }
  1268. save_session_file();
  1269. free( spath );
  1270. osc_server->send( sender_addr, "/reply", path, "Session created" );
  1271. pending_operation = COMMAND_NONE;
  1272. return 0;
  1273. }
  1274. static lo_address list_response_address;
  1275. int
  1276. list_file ( const char *fpath, const struct stat *sb, int tflag )
  1277. {
  1278. char *s;
  1279. if ( tflag == FTW_F )
  1280. {
  1281. s = strdup( fpath );
  1282. if ( ! strcmp( "session.nsm", basename( s ) ) )
  1283. {
  1284. free( s );
  1285. s = strdup( fpath );
  1286. s = dirname( s );
  1287. memmove( s, s + strlen( session_root ) + 1, (strlen( s ) - strlen( session_root )) + 1);
  1288. osc_server->send( list_response_address, "/reply", "/nsm/server/list", s );
  1289. free( s );
  1290. }
  1291. else
  1292. free( s );
  1293. }
  1294. return 0;
  1295. }
  1296. OSC_HANDLER( list )
  1297. {
  1298. GUIMSG( "Listing sessions" );
  1299. list_response_address = lo_message_get_source( msg );
  1300. ftw( session_root, list_file, 20 );
  1301. // osc_server->send( lo_message_get_source( msg ), path, ERR_OK, "Done." );
  1302. // As marker that all sessions were sent reply with an empty string, which is impossible to conflict with a session name
  1303. osc_server->send( list_response_address, "/reply", "/nsm/server/list", "" );
  1304. return 0;
  1305. }
  1306. OSC_HANDLER( open )
  1307. {
  1308. lo_address sender_addr;
  1309. sender_addr = lo_address_new_from_url( lo_address_get_url( lo_message_get_source( msg ) ));
  1310. GUIMSG( "Opening session %s", &argv[0]->s );
  1311. if ( pending_operation != COMMAND_NONE )
  1312. {
  1313. osc_server->send( sender_addr, "/error", path,
  1314. ERR_OPERATION_PENDING,
  1315. "An operation pending." );
  1316. return 0;
  1317. }
  1318. pending_operation = COMMAND_OPEN;
  1319. if ( session_path )
  1320. {
  1321. command_all_clients_to_save();
  1322. if ( clients_have_errors() )
  1323. {
  1324. osc_server->send( sender_addr, "/error", path,
  1325. ERR_GENERAL_ERROR,
  1326. "Some clients could not save" );
  1327. pending_operation = COMMAND_NONE;
  1328. return 0;
  1329. }
  1330. // save_session_file();
  1331. }
  1332. char *spath;
  1333. asprintf( &spath, "%s/%s", session_root, &argv[0]->s );
  1334. MESSAGE( "Attempting to open %s", spath );
  1335. int err = load_session_file( spath );
  1336. if ( ! err )
  1337. {
  1338. MESSAGE( "Loaded" );
  1339. osc_server->send( sender_addr, "/reply", path,
  1340. "Loaded." );
  1341. }
  1342. else
  1343. {
  1344. MESSAGE( "Failed" );
  1345. const char *m = NULL;
  1346. switch ( err )
  1347. {
  1348. case ERR_CREATE_FAILED:
  1349. m = "Could not create session file!";
  1350. break;
  1351. case ERR_SESSION_LOCKED:
  1352. m = "Session is locked by another process!";
  1353. break;
  1354. case ERR_NO_SUCH_FILE:
  1355. m = "The named session does not exist.";
  1356. break;
  1357. default:
  1358. m = "Unknown error";
  1359. }
  1360. osc_server->send( sender_addr, "/error", path,
  1361. err,
  1362. m );
  1363. }
  1364. free( spath );
  1365. MESSAGE( "Done" );
  1366. pending_operation = COMMAND_NONE;
  1367. return 0;
  1368. }
  1369. OSC_HANDLER( quit )
  1370. {
  1371. close_session();
  1372. exit(0);
  1373. return 0;
  1374. }
  1375. OSC_HANDLER( abort )
  1376. {
  1377. lo_address sender_addr;
  1378. sender_addr = lo_address_new_from_url( lo_address_get_url( lo_message_get_source( msg ) ));
  1379. if ( pending_operation != COMMAND_NONE )
  1380. {
  1381. osc_server->send( sender_addr, "/error", path,
  1382. ERR_OPERATION_PENDING,
  1383. "An operation pending." );
  1384. return 0;
  1385. }
  1386. pending_operation = COMMAND_CLOSE;
  1387. if ( ! session_path )
  1388. {
  1389. osc_server->send( sender_addr, "/error", path,
  1390. ERR_NO_SESSION_OPEN,
  1391. "No session to abort." );
  1392. goto done;
  1393. }
  1394. GUIMSG( "Commanding attached clients to quit." );
  1395. close_session();
  1396. osc_server->send( sender_addr, "/reply", path,
  1397. "Aborted." );
  1398. MESSAGE( "Done" );
  1399. done:
  1400. pending_operation = COMMAND_NONE;
  1401. return 0;
  1402. }
  1403. OSC_HANDLER( close )
  1404. {
  1405. lo_address sender_addr;
  1406. sender_addr = lo_address_new_from_url( lo_address_get_url( lo_message_get_source( msg ) ));
  1407. if ( pending_operation != COMMAND_NONE )
  1408. {
  1409. osc_server->send( sender_addr, "/error", path,
  1410. ERR_OPERATION_PENDING,
  1411. "An operation pending." );
  1412. return 0;
  1413. }
  1414. pending_operation = COMMAND_CLOSE;
  1415. if ( ! session_path )
  1416. {
  1417. osc_server->send( sender_addr, "/error", path,
  1418. ERR_NO_SESSION_OPEN,
  1419. "No session to close." );
  1420. goto done;
  1421. }
  1422. command_all_clients_to_save();
  1423. GUIMSG( "Commanding attached clients to quit." );
  1424. close_session();
  1425. osc_server->send( sender_addr, "/reply", path, "Closed." );
  1426. MESSAGE( "Done" );
  1427. done:
  1428. pending_operation = COMMAND_NONE;
  1429. return 0;
  1430. }
  1431. OSC_HANDLER( broadcast )
  1432. {
  1433. const char *to_path = &argv[0]->s;
  1434. /* don't allow clients to broadcast NSM commands */
  1435. if ( ! strncmp( to_path, "/nsm/", strlen( "/nsm/" ) ) )
  1436. return 0;
  1437. std::list<OSC::OSC_Value> new_args;
  1438. for ( int i = 1; i < argc; ++i )
  1439. {
  1440. switch ( types[i] )
  1441. {
  1442. case 's':
  1443. new_args.push_back( OSC::OSC_String( &argv[i]->s ) );
  1444. break;
  1445. case 'i':
  1446. new_args.push_back( OSC::OSC_Int( argv[i]->i ) );
  1447. break;
  1448. case 'f':
  1449. new_args.push_back( OSC::OSC_Float( argv[i]->f ) );
  1450. break;
  1451. }
  1452. }
  1453. char *sender_url = lo_address_get_url( lo_message_get_source( msg ) );
  1454. for ( std::list<Client*>::iterator i = client.begin();
  1455. i != client.end();
  1456. ++i )
  1457. {
  1458. if ( ! (*i)->addr )
  1459. continue;
  1460. char *url = lo_address_get_url( (*i)->addr );
  1461. if ( strcmp( sender_url, url ) )
  1462. {
  1463. osc_server->send( (*i)->addr, to_path, new_args );
  1464. }
  1465. free( url );
  1466. }
  1467. /* also relay to attached GUI so that the broadcast can be
  1468. * propagated to another NSMD instance */
  1469. if ( gui_is_active )
  1470. {
  1471. char *u1 = lo_address_get_url( gui_addr );
  1472. if ( strcmp( u1, sender_url ) )
  1473. {
  1474. new_args.push_front( OSC::OSC_String( to_path ) );
  1475. osc_server->send( gui_addr, path, new_args );
  1476. }
  1477. free(u1);
  1478. }
  1479. free( sender_url );
  1480. return 0;
  1481. }
  1482. /*********************************/
  1483. /* Client Informational Messages */
  1484. /*********************************/
  1485. OSC_HANDLER( progress )
  1486. {
  1487. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1488. if ( c )
  1489. {
  1490. c->progress = argv[0]->f;
  1491. /* MESSAGE( "%s progress: %i%%", c->name, (int)(c->progress * 100.0f) ); */
  1492. if ( gui_is_active )
  1493. {
  1494. osc_server->send( gui_addr, "/nsm/gui/client/progress", c->client_id, (float)c->progress );
  1495. }
  1496. }
  1497. return 0;
  1498. }
  1499. OSC_HANDLER( is_dirty )
  1500. {
  1501. MESSAGE( "Client sends dirty" );
  1502. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1503. if ( ! c )
  1504. return 0;
  1505. c->dirty = 1;
  1506. if ( gui_is_active )
  1507. osc_server->send( gui_addr, "/nsm/gui/client/dirty", c->client_id, c->dirty );
  1508. return 0;
  1509. }
  1510. OSC_HANDLER( is_clean )
  1511. {
  1512. MESSAGE( "Client sends clean" );
  1513. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1514. if ( ! c )
  1515. return 0;
  1516. c->dirty = 0;
  1517. if ( gui_is_active )
  1518. osc_server->send( gui_addr, "/nsm/gui/client/dirty", c->client_id, c->dirty );
  1519. return 0;
  1520. }
  1521. OSC_HANDLER( gui_is_hidden )
  1522. {
  1523. MESSAGE( "Client sends gui hidden" );
  1524. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1525. if ( ! c )
  1526. return 0;
  1527. c->gui_visible( false );
  1528. if ( gui_is_active )
  1529. osc_server->send( gui_addr, "/nsm/gui/client/gui_visible", c->client_id, c->gui_visible() );
  1530. return 0;
  1531. }
  1532. OSC_HANDLER( gui_is_shown )
  1533. {
  1534. MESSAGE( "Client sends gui shown" );
  1535. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1536. if ( ! c )
  1537. return 0;
  1538. c->gui_visible( true );
  1539. if ( gui_is_active )
  1540. osc_server->send( gui_addr, "/nsm/gui/client/gui_visible", c->client_id, c->gui_visible() );
  1541. return 0;
  1542. }
  1543. OSC_HANDLER( message )
  1544. {
  1545. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1546. if ( ! c )
  1547. return 0;
  1548. if ( gui_is_active )
  1549. osc_server->send( gui_addr, "/nsm/gui/client/message", c->client_id, argv[0]->i, &argv[1]->s );
  1550. return 0;
  1551. }
  1552. OSC_HANDLER( label )
  1553. {
  1554. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1555. if ( ! c )
  1556. return 0;
  1557. if ( strcmp( types, "s" ) )
  1558. return -1;
  1559. c->label( &argv[0]->s );
  1560. if ( gui_is_active )
  1561. osc_server->send( gui_addr, "/nsm/gui/client/label", c->client_id, &argv[0]->s );
  1562. return 0;
  1563. }
  1564. /**********************/
  1565. /* Response Handlers */
  1566. /**********************/
  1567. OSC_HANDLER( error )
  1568. {
  1569. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1570. if ( ! c )
  1571. {
  1572. WARNING( "Error from unknown client" );
  1573. return 0;
  1574. }
  1575. // const char *rpath = &argv[0]->s;
  1576. int err_code = argv[1]->i;
  1577. const char *message = &argv[2]->s;
  1578. c->set_reply( err_code, message );
  1579. MESSAGE( "Client \"%s\" replied with error: %s (%i) in %fms", c->name_with_id(), message, err_code, c->milliseconds_since_last_command() );
  1580. c->pending_command( COMMAND_NONE );
  1581. if ( gui_is_active )
  1582. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "error" );
  1583. return 0;
  1584. }
  1585. OSC_HANDLER( reply )
  1586. {
  1587. Client *c = get_client_by_address( lo_message_get_source( msg ) );
  1588. // const char *rpath = &argv[0]->s;
  1589. const char *message = &argv[1]->s;
  1590. if ( c )
  1591. {
  1592. c->set_reply( ERR_OK, message );
  1593. MESSAGE( "Client \"%s\" replied with: %s in %fms", c->name_with_id(), message, c->milliseconds_since_last_command() );
  1594. c->pending_command( COMMAND_NONE );
  1595. if ( gui_is_active )
  1596. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "ready" );
  1597. }
  1598. else
  1599. MESSAGE( "Reply from unknown client" );
  1600. return 0;
  1601. }
  1602. /******************/
  1603. /* GUI operations */
  1604. /******************/
  1605. OSC_HANDLER( stop )
  1606. {
  1607. Client *c = get_client_by_id( &client, &argv[0]->s );
  1608. if ( c )
  1609. {
  1610. command_client_to_stop( c );
  1611. if ( gui_is_active )
  1612. osc_server->send( gui_addr, "/reply", "Client stopped." );
  1613. }
  1614. else
  1615. {
  1616. if ( gui_is_active )
  1617. osc_server->send( gui_addr, "/error", -10, "No such client." );
  1618. }
  1619. return 0;
  1620. }
  1621. OSC_HANDLER( remove )
  1622. {
  1623. Client *c = get_client_by_id( &client, &argv[0]->s );
  1624. if ( c )
  1625. {
  1626. if ( c->pid == 0 &&
  1627. ! c->active )
  1628. {
  1629. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status = "removed" );
  1630. client.remove( c );
  1631. delete c;
  1632. if ( gui_is_active )
  1633. osc_server->send( gui_addr, "/reply", "Client removed." );
  1634. }
  1635. }
  1636. else
  1637. {
  1638. if ( gui_is_active )
  1639. osc_server->send( gui_addr, "/error", -10, "No such client." );
  1640. }
  1641. return 0;
  1642. }
  1643. OSC_HANDLER( resume )
  1644. {
  1645. Client *c = get_client_by_id( &client, &argv[0]->s );
  1646. /* FIXME: return error if no such client? */
  1647. if ( c )
  1648. {
  1649. if ( c->pid == 0 &&
  1650. ! c->active )
  1651. {
  1652. if ( ! launch( c->executable_path, c->client_id ) )
  1653. {
  1654. }
  1655. }
  1656. }
  1657. return 0;
  1658. }
  1659. OSC_HANDLER( client_save )
  1660. {
  1661. Client *c = get_client_by_id( &client, &argv[0]->s );
  1662. /* FIXME: return error if no such client? */
  1663. if ( c )
  1664. {
  1665. if ( c->active )
  1666. {
  1667. command_client_to_save( c );
  1668. }
  1669. }
  1670. return 0;
  1671. }
  1672. OSC_HANDLER( client_show_optional_gui )
  1673. {
  1674. Client *c = get_client_by_id( &client, &argv[0]->s );
  1675. /* FIXME: return error if no such client? */
  1676. if ( c )
  1677. {
  1678. if ( c->active )
  1679. {
  1680. osc_server->send( c->addr, "/nsm/client/show_optional_gui" );
  1681. }
  1682. }
  1683. return 0;
  1684. }
  1685. OSC_HANDLER( client_hide_optional_gui )
  1686. {
  1687. Client *c = get_client_by_id( &client, &argv[0]->s );
  1688. /* FIXME: return error if no such client? */
  1689. if ( c )
  1690. {
  1691. if ( c->active )
  1692. {
  1693. osc_server->send( c->addr, "/nsm/client/hide_optional_gui" );
  1694. }
  1695. }
  1696. return 0;
  1697. }
  1698. void
  1699. announce_gui( const char *url, bool is_reply )
  1700. {
  1701. // This is send for a new and empty nsmd as well as already running, headless, ones.
  1702. // If a GUI connects to an existing server with a running session this will trigger a list of
  1703. // clients send to the new GUI.
  1704. gui_addr = lo_address_new_from_url( url );
  1705. gui_is_active = true; //global state
  1706. if ( is_reply )
  1707. // the default case. A GUI starts its own nsmd or connects to a running one
  1708. osc_server->send( gui_addr, "/nsm/gui/gui_announce", "hi" );
  1709. else
  1710. //The server was started directly and instructed to connect to a running GUI.
  1711. osc_server->send( gui_addr, "/nsm/gui/server_announce", "hi" );
  1712. osc_server->send( gui_addr, "/nsm/gui/session/root", session_root );
  1713. // Send a list of clients to the newly registered GUI in case there was already a session open
  1714. for ( std::list<Client*>::iterator i = client.begin();
  1715. i != client.end();
  1716. ++i )
  1717. {
  1718. Client *c = *i;
  1719. osc_server->send( gui_addr, "/nsm/gui/client/new", c->client_id, c->name );
  1720. osc_server->send( gui_addr, "/nsm/gui/client/status", c->client_id, c->status );
  1721. }
  1722. //Send two parameters. The first one is the short session name, which is the directory name.
  1723. //The second parameter is the full file path.
  1724. //If both are empty it signals that no session is currently open, which is the default state if
  1725. //a GUI started nsmd.
  1726. osc_server->send( gui_addr, "/nsm/gui/session/name", session_name ? session_name : "", session_path ? session_path : "" );
  1727. DMESSAGE( "Registered with GUI" );
  1728. }
  1729. OSC_HANDLER( gui_announce )
  1730. {
  1731. announce_gui( lo_address_get_url( lo_message_get_source( msg ) ), true );
  1732. return 0;
  1733. }
  1734. OSC_HANDLER( ping )
  1735. {
  1736. osc_server->send( lo_message_get_source( msg ), "/reply", path );
  1737. return 0;
  1738. }
  1739. OSC_HANDLER( null )
  1740. {
  1741. WARNING( "Unrecognized message with type signature \"%s\" at path \"%s\"", types, path );
  1742. return 0;
  1743. }
  1744. static void
  1745. wait ( long timeout )
  1746. {
  1747. struct signalfd_siginfo fdsi;
  1748. ssize_t s = read(signal_fd, &fdsi, sizeof(struct signalfd_siginfo));
  1749. if (s == sizeof(struct signalfd_siginfo))
  1750. {
  1751. if (fdsi.ssi_signo == SIGCHLD)
  1752. handle_sigchld();
  1753. }
  1754. osc_server->wait( timeout );
  1755. purge_dead_clients();
  1756. }
  1757. int main(int argc, char *argv[])
  1758. {
  1759. sigset_t mask;
  1760. sigemptyset( &mask );
  1761. sigaddset( &mask, SIGCHLD );
  1762. sigprocmask(SIG_BLOCK, &mask, NULL );
  1763. signal_fd = signalfd( -1, &mask, SFD_NONBLOCK );
  1764. /* generate random seed for client ids */
  1765. {
  1766. time_t seconds;
  1767. time(&seconds);
  1768. srand( (unsigned int) seconds );
  1769. }
  1770. //Command line parameters
  1771. char *osc_port = NULL;
  1772. const char *gui_url = NULL;
  1773. const char *load_session = NULL;
  1774. static struct option long_options[] =
  1775. {
  1776. { "detach", no_argument, 0, 'd' },
  1777. { "session-root", required_argument, 0, 's' },
  1778. { "osc-port", required_argument, 0, 'p' },
  1779. { "gui-url", required_argument, 0, 'g' },
  1780. { "help", no_argument, 0, 'h' },
  1781. { "version", no_argument, 0, 'v' },
  1782. { "load-session", required_argument, 0, 'l'},
  1783. { 0, 0, 0, 0 }
  1784. };
  1785. int option_index = 0;
  1786. int c = 0;
  1787. bool detach = false;
  1788. while ( ( c = getopt_long_only( argc, argv, "", long_options, &option_index ) ) != -1 )
  1789. {
  1790. switch ( c )
  1791. {
  1792. case 'd':
  1793. detach = true;
  1794. break;
  1795. case 's':
  1796. {
  1797. session_root = optarg;
  1798. /* get rid of trailing slash */
  1799. char *s = rindex(session_root,'/');
  1800. if ( s == &session_root[strlen(session_root) - 1] )
  1801. *s = '\0';
  1802. break;
  1803. }
  1804. case 'p':
  1805. DMESSAGE( "Using OSC port %s", optarg );
  1806. osc_port = optarg;
  1807. break;
  1808. case 'g':
  1809. DMESSAGE( "Going to connect to GUI at: %s", optarg );
  1810. gui_url = optarg;
  1811. break;
  1812. case 'l':
  1813. DMESSAGE( "Loading existing session file %s", optarg);
  1814. load_session = optarg;
  1815. break;
  1816. case 'v':
  1817. printf( "%s 1.4\n", argv[0] );
  1818. exit(0);
  1819. break;
  1820. case 'h':
  1821. //Print usage message according to POSIX.1-2017
  1822. const char *usage =
  1823. "%s\n\n"
  1824. "Usage:\n"
  1825. " %s\n"
  1826. " %s --help\n"
  1827. " %s --version\n"
  1828. "\n"
  1829. "Options:\n"
  1830. " --help Show this screen\n"
  1831. " --version Show version\n"
  1832. " --osc-port portnum OSC port number [Default: provided by system].\n"
  1833. " --session-root path Base path for sessions [Default: ~/NSM Sessions].\n"
  1834. " --load-session name Load existing session [Example: \"My Song\"].\n"
  1835. " --gui-url url Connect to running legacy-gui [Example: osc.udp://mycomputer.localdomain:38356/].\n"
  1836. " --detach Detach from console.\n"
  1837. "";
  1838. printf ( usage, argv[0], argv[0], argv[0], argv[0] );
  1839. exit(0);
  1840. break;
  1841. }
  1842. }
  1843. if ( !session_root )
  1844. asprintf( &session_root, "%s/%s", getenv( "HOME" ), "NSM Sessions" );
  1845. struct stat st;
  1846. if ( stat( session_root, &st ) )
  1847. {
  1848. if ( mkdir( session_root, 0771 ) )
  1849. {
  1850. FATAL( "Failed to create session directory: %s", strerror( errno ) );
  1851. }
  1852. }
  1853. MESSAGE( "Session root is: %s", session_root );
  1854. osc_server = new OSC::Endpoint();
  1855. if ( osc_server->init( LO_UDP, osc_port ) )
  1856. {
  1857. FATAL( "Failed to create OSC server." );
  1858. }
  1859. printf( "NSM_URL=%s\n", osc_server->url() );
  1860. if ( gui_url )
  1861. {
  1862. //The server was started directly and instructed to connect to a running GUI.
  1863. announce_gui( gui_url, false );
  1864. }
  1865. /* */
  1866. osc_server->add_method( "/nsm/server/announce", "sssiii", OSC_NAME( announce ), NULL, "client_name,capabilities,executable,api_version_major,api_version_minor,client_pid" );
  1867. /* response handlers */
  1868. osc_server->add_method( "/reply", "ss", OSC_NAME( reply ), NULL, "err_code,msg" );
  1869. osc_server->add_method( "/error", "sis", OSC_NAME( error ), NULL, "err_code,msg" );
  1870. osc_server->add_method( "/nsm/client/progress", "f", OSC_NAME( progress ), NULL, "progress" );
  1871. osc_server->add_method( "/nsm/client/is_dirty", "", OSC_NAME( is_dirty ), NULL, "dirtiness" );
  1872. osc_server->add_method( "/nsm/client/is_clean", "", OSC_NAME( is_clean ), NULL, "dirtiness" );
  1873. osc_server->add_method( "/nsm/client/message", "is", OSC_NAME( message ), NULL, "message" );
  1874. osc_server->add_method( "/nsm/client/gui_is_hidden", "", OSC_NAME( gui_is_hidden ), NULL, "message" );
  1875. osc_server->add_method( "/nsm/client/gui_is_shown", "", OSC_NAME( gui_is_shown ), NULL, "message" );
  1876. osc_server->add_method( "/nsm/client/label", "s", OSC_NAME( label ), NULL, "message" );
  1877. /* */
  1878. osc_server->add_method( "/nsm/gui/gui_announce", "", OSC_NAME( gui_announce ), NULL, "" );
  1879. osc_server->add_method( "/nsm/gui/client/stop", "s", OSC_NAME( stop ), NULL, "client_id" );
  1880. osc_server->add_method( "/nsm/gui/client/remove", "s", OSC_NAME( remove ), NULL, "client_id" );
  1881. osc_server->add_method( "/nsm/gui/client/resume", "s", OSC_NAME( resume ), NULL, "client_id" );
  1882. osc_server->add_method( "/nsm/gui/client/save", "s", OSC_NAME( client_save ), NULL, "client_id" );
  1883. osc_server->add_method( "/nsm/gui/client/show_optional_gui", "s", OSC_NAME( client_show_optional_gui ), NULL, "client_id" );
  1884. osc_server->add_method( "/nsm/gui/client/hide_optional_gui", "s", OSC_NAME( client_hide_optional_gui ), NULL, "client_id" );
  1885. osc_server->add_method( "/osc/ping", "", OSC_NAME( ping ), NULL, "" );
  1886. osc_server->add_method( "/nsm/server/broadcast", NULL, OSC_NAME( broadcast ), NULL, "" );
  1887. osc_server->add_method( "/nsm/server/duplicate", "s", OSC_NAME( duplicate ), NULL, "" );
  1888. osc_server->add_method( "/nsm/server/abort", "", OSC_NAME( abort ), NULL, "" );
  1889. osc_server->add_method( "/nsm/server/list", "", OSC_NAME( list ), NULL, "" );
  1890. osc_server->add_method( "/nsm/server/add", "s", OSC_NAME( add ), NULL, "executable_name" );
  1891. osc_server->add_method( "/nsm/server/new", "s", OSC_NAME( new ), NULL, "name" );
  1892. osc_server->add_method( "/nsm/server/save", "", OSC_NAME( save ), NULL, "" );
  1893. osc_server->add_method( "/nsm/server/open", "s", OSC_NAME( open ), NULL, "name" );
  1894. osc_server->add_method( "/nsm/server/close", "", OSC_NAME( close ), NULL, "" );
  1895. osc_server->add_method( "/nsm/server/quit", "", OSC_NAME( quit ), NULL, "" );
  1896. osc_server->add_method( NULL, NULL, OSC_NAME( null ),NULL, "" );
  1897. if ( load_session )
  1898. {
  1899. char *spath;
  1900. asprintf( &spath, "%s/%s", session_root, load_session); // Build the session path. --load-session works with --session-root
  1901. MESSAGE( "LOAD SESSION %s", spath);
  1902. load_session_file( spath );
  1903. }
  1904. if ( detach )
  1905. {
  1906. MESSAGE( "Detaching from console" );
  1907. if ( fork() )
  1908. {
  1909. exit( 0 );
  1910. }
  1911. else
  1912. {
  1913. fclose( stdin );
  1914. fclose( stdout );
  1915. fclose( stderr );
  1916. }
  1917. }
  1918. /* listen for sigchld signals and process OSC messages forever */
  1919. for ( ;; )
  1920. {
  1921. wait( 1000 );
  1922. }
  1923. // osc_server->run();
  1924. return 0;
  1925. }