/[svn]/linuxsampler/trunk/src/network/lscpserver.cpp
ViewVC logotype

Diff of /linuxsampler/trunk/src/network/lscpserver.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1399 by schoenebeck, Thu Oct 11 18:53:29 2007 UTC revision 1537 by senoner, Mon Dec 3 18:30:47 2007 UTC
# Line 25  Line 25 
25  #include "lscpresultset.h"  #include "lscpresultset.h"
26  #include "lscpevent.h"  #include "lscpevent.h"
27    
28    #if defined(WIN32)
29    #include <windows.h>
30    #else
31  #include <fcntl.h>  #include <fcntl.h>
32    #endif
33    
34  #if ! HAVE_SQLITE3  #if ! HAVE_SQLITE3
35  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."  #define DOESNT_HAVE_SQLITE3 "No database support. SQLITE3 was not installed when linuxsampler was built."
# Line 58  static String _escapeLscpResponse(String Line 62  static String _escapeLscpResponse(String
62              !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&              !(c == '*') && !(c == '+') && !(c == ',') && !(c == '-') &&
63              !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&              !(c == '.') && !(c == '/') && !(c == ':') && !(c == ';') &&
64              !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&              !(c == '<') && !(c == '=') && !(c == '>') && !(c == '?') &&
65              !(c == '@') && !(c == '[') && !(c == '\\') && !(c == ']') &&              !(c == '@') && !(c == '[') && !(c == ']') &&
66              !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&              !(c == '^') && !(c == '_') && !(c == '`') && !(c == '{') &&
67              !(c == '|') && !(c == '}') && !(c == '~')              !(c == '|') && !(c == '}') && !(c == '~')
68          ) {          ) {
# Line 129  LSCPServer::LSCPServer(Sampler* pSampler Line 133  LSCPServer::LSCPServer(Sampler* pSampler
133  }  }
134    
135  LSCPServer::~LSCPServer() {  LSCPServer::~LSCPServer() {
136    #if defined(WIN32)
137        if (hSocket >= 0) closesocket(hSocket);
138    #else
139      if (hSocket >= 0) close(hSocket);      if (hSocket >= 0) close(hSocket);
140    #endif
141  }  }
142    
143  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {  void LSCPServer::EventHandler::ChannelCountChanged(int NewCount) {
# Line 230  int LSCPServer::WaitUntilInitialized(lon Line 238  int LSCPServer::WaitUntilInitialized(lon
238  }  }
239    
240  int LSCPServer::Main() {  int LSCPServer::Main() {
241            #if defined(WIN32)
242            WSADATA wsaData;
243            int iResult;
244            iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
245            if (iResult != 0) {
246                    std::cerr << "LSCPServer: WSAStartup failed: " << iResult << "\n";
247                    exit(EXIT_FAILURE);
248            }
249            #endif
250      hSocket = socket(AF_INET, SOCK_STREAM, 0);      hSocket = socket(AF_INET, SOCK_STREAM, 0);
251      if (hSocket < 0) {      if (hSocket < 0) {
252          std::cerr << "LSCPServer: Could not create server socket." << std::endl;          std::cerr << "LSCPServer: Could not create server socket." << std::endl;
# Line 243  int LSCPServer::Main() { Line 260  int LSCPServer::Main() {
260              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {              if (bind(hSocket, (sockaddr*) &SocketAddress, sizeof(sockaddr_in)) < 0) {
261                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {                  if (trial > LSCP_SERVER_BIND_TIMEOUT) {
262                      std::cerr << "gave up!" << std::endl;                      std::cerr << "gave up!" << std::endl;
263                        #if defined(WIN32)
264                        closesocket(hSocket);
265                        #else
266                      close(hSocket);                      close(hSocket);
267                        #endif
268                      //return -1;                      //return -1;
269                      exit(EXIT_FAILURE);                      exit(EXIT_FAILURE);
270                  }                  }
# Line 325  int LSCPServer::Main() { Line 346  int LSCPServer::Main() {
346                  continue; //Nothing try again                  continue; //Nothing try again
347          if (retval == -1) {          if (retval == -1) {
348                  std::cerr << "LSCPServer: Socket select error." << std::endl;                  std::cerr << "LSCPServer: Socket select error." << std::endl;
349                    #if defined(WIN32)
350                    closesocket(hSocket);
351                    #else
352                  close(hSocket);                  close(hSocket);
353                    #endif
354                  exit(EXIT_FAILURE);                  exit(EXIT_FAILURE);
355          }          }
356    
# Line 337  int LSCPServer::Main() { Line 362  int LSCPServer::Main() {
362                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
363                  }                  }
364    
365                    #if defined(WIN32)
366                    u_long nonblock_io = 1;
367                    if( ioctlsocket(socket, FIONBIO, &nonblock_io) ) {
368                      std::cerr << "LSCPServer: ioctlsocket: set FIONBIO failed. Error " << WSAGetLastError() << std::endl;
369                      exit(EXIT_FAILURE);
370                    }
371            #else
372                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {                  if (fcntl(socket, F_SETFL, O_NONBLOCK)) {
373                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;                          std::cerr << "LSCPServer: F_SETFL O_NONBLOCK failed." << std::endl;
374                          exit(EXIT_FAILURE);                          exit(EXIT_FAILURE);
375                  }                  }
376                    #endif
377    
378                  // Parser initialization                  // Parser initialization
379                  yyparse_param_t yyparse_param;                  yyparse_param_t yyparse_param;
# Line 399  void LSCPServer::CloseConnection( std::v Line 432  void LSCPServer::CloseConnection( std::v
432          NotifyMutex.Lock();          NotifyMutex.Lock();
433          bufferedCommands.erase(socket);          bufferedCommands.erase(socket);
434          bufferedNotifies.erase(socket);          bufferedNotifies.erase(socket);
435            #if defined(WIN32)
436            closesocket(socket);
437            #else
438          close(socket);          close(socket);
439            #endif
440          NotifyMutex.Unlock();          NotifyMutex.Unlock();
441  }  }
442    
# Line 478  bool LSCPServer::GetLSCPCommand( std::ve Line 515  bool LSCPServer::GetLSCPCommand( std::ve
515          char c;          char c;
516          int i = 0;          int i = 0;
517          while (true) {          while (true) {
518                    #if defined(WIN32)
519                    int result = recv(socket, (char *)&c, 1, 0); //Read one character at a time for now
520                    #else
521                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now                  int result = recv(socket, (void *)&c, 1, 0); //Read one character at a time for now
522                    #endif
523                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection                  if (result == 0) { //socket was selected, so 0 here means client has closed the connection
524                          CloseConnection(iter);                          CloseConnection(iter);
525                          break;                          break;
# Line 493  bool LSCPServer::GetLSCPCommand( std::ve Line 534  bool LSCPServer::GetLSCPCommand( std::ve
534                          }                          }
535                          bufferedCommands[socket] += c;                          bufferedCommands[socket] += c;
536                  }                  }
537                    #if defined(WIN32)
538                    if (result == SOCKET_ERROR) {
539                        int wsa_lasterror = WSAGetLastError();
540                            if (wsa_lasterror == WSAEWOULDBLOCK) //Would block, try again later.
541                                    return false;
542                            dmsg(2,("LSCPScanner: Socket error after recv() Error %d.\n", wsa_lasterror));
543                            CloseConnection(iter);
544                            break;
545                    }
546                    #else
547                  if (result == -1) {                  if (result == -1) {
548                          if (errno == EAGAIN) //Would block, try again later.                          if (errno == EAGAIN) //Would block, try again later.
549                                  return false;                                  return false;
# Line 531  bool LSCPServer::GetLSCPCommand( std::ve Line 582  bool LSCPServer::GetLSCPCommand( std::ve
582                          CloseConnection(iter);                          CloseConnection(iter);
583                          break;                          break;
584                  }                  }
585                    #endif
586          }          }
587          return false;          return false;
588  }  }
# Line 877  String LSCPServer::GetChannelInfo(uint u Line 929  String LSCPServer::GetChannelInfo(uint u
929          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");          if (pSamplerChannel->GetMidiInputChannel() == midi_chan_all) result.Add("MIDI_INPUT_CHANNEL", "ALL");
930          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());          else result.Add("MIDI_INPUT_CHANNEL", pSamplerChannel->GetMidiInputChannel());
931    
932          result.Add("INSTRUMENT_FILE",          // convert the filename into the correct encoding as defined for LSCP
933                     (InstrumentFileName != "NONE" && InstrumentFileName != "") ?          // (especially in terms of special characters -> escape sequences)
934                          Path::fromPosix(InstrumentFileName).toLscp() : // TODO: assuming POSIX          if (InstrumentFileName != "NONE" && InstrumentFileName != "") {
935                          InstrumentFileName  #if WIN32
936          );              InstrumentFileName = Path::fromWindows(InstrumentFileName).toLscp();
937    #else
938                // assuming POSIX
939                InstrumentFileName = Path::fromPosix(InstrumentFileName).toLscp();
940    #endif
941            }
942    
943            result.Add("INSTRUMENT_FILE", InstrumentFileName);
944          result.Add("INSTRUMENT_NR", InstrumentIndex);          result.Add("INSTRUMENT_NR", InstrumentIndex);
945          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));          result.Add("INSTRUMENT_NAME", _escapeLscpResponse(InstrumentName));
946          result.Add("INSTRUMENT_STATUS", InstrumentStatus);          result.Add("INSTRUMENT_STATUS", InstrumentStatus);
# Line 1825  String LSCPServer::GetMidiInstrumentMapp Line 1884  String LSCPServer::GetMidiInstrumentMapp
1884          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);          std::map<midi_prog_index_t,MidiInstrumentMapper::entry_t>::iterator iter = mappings.find(idx);
1885          if (iter == mappings.end()) result.Error("there is no map entry with that index");          if (iter == mappings.end()) result.Error("there is no map entry with that index");
1886          else { // found          else { // found
1887    
1888                // convert the filename into the correct encoding as defined for LSCP
1889                // (especially in terms of special characters -> escape sequences)
1890    #if WIN32
1891                const String instrumentFileName = Path::fromWindows(iter->second.InstrumentFile).toLscp();
1892    #else
1893                // assuming POSIX
1894                const String instrumentFileName = Path::fromPosix(iter->second.InstrumentFile).toLscp();
1895    #endif
1896    
1897              result.Add("NAME", _escapeLscpResponse(iter->second.Name));              result.Add("NAME", _escapeLscpResponse(iter->second.Name));
1898              result.Add("ENGINE_NAME", iter->second.EngineName);              result.Add("ENGINE_NAME", iter->second.EngineName);
1899              result.Add("INSTRUMENT_FILE", Path::fromPosix(iter->second.InstrumentFile).toLscp()); //TODO: assuming POSIX              result.Add("INSTRUMENT_FILE", instrumentFileName);
1900              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);              result.Add("INSTRUMENT_NR", (int) iter->second.InstrumentIndex);
1901              String instrumentName;              String instrumentName;
1902              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);              Engine* pEngine = EngineFactory::Create(iter->second.EngineName);
# Line 2315  String LSCPServer::SetGlobalVolume(doubl Line 2384  String LSCPServer::SetGlobalVolume(doubl
2384      return result.Produce();      return result.Produce();
2385  }  }
2386    
2387    String LSCPServer::GetFileInstruments(String Filename) {
2388        dmsg(2,("LSCPServer: GetFileInstruments(String Filename=%s)\n",Filename.c_str()));
2389        LSCPResultSet result;
2390        try {
2391            VerifyFile(Filename);
2392        } catch (Exception e) {
2393            result.Error(e);
2394            return result.Produce();
2395        }
2396        // try to find a sampler engine that can handle the file
2397        bool bFound = false;
2398        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2399        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2400            Engine* pEngine = NULL;
2401            try {
2402                pEngine = EngineFactory::Create(engineTypes[i]);
2403                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2404                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2405                if (pManager) {
2406                    std::vector<InstrumentManager::instrument_id_t> IDs =
2407                        pManager->GetInstrumentFileContent(Filename);
2408                    // return the amount of instruments in the file
2409                    result.Add(IDs.size());
2410                    // no more need to ask other engine types
2411                    bFound = true;
2412                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2413            } catch (Exception e) {
2414                // NOOP, as exception is thrown if engine doesn't support file
2415            }
2416            if (pEngine) EngineFactory::Destroy(pEngine);
2417        }
2418    
2419        if (!bFound) result.Error("Unknown file format");
2420        return result.Produce();
2421    }
2422    
2423    String LSCPServer::ListFileInstruments(String Filename) {
2424        dmsg(2,("LSCPServer: ListFileInstruments(String Filename=%s)\n",Filename.c_str()));
2425        LSCPResultSet result;
2426        try {
2427            VerifyFile(Filename);
2428        } catch (Exception e) {
2429            result.Error(e);
2430            return result.Produce();
2431        }
2432        // try to find a sampler engine that can handle the file
2433        bool bFound = false;
2434        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2435        for (int i = 0; !bFound && i < engineTypes.size(); i++) {
2436            Engine* pEngine = NULL;
2437            try {
2438                pEngine = EngineFactory::Create(engineTypes[i]);
2439                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2440                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2441                if (pManager) {
2442                    std::vector<InstrumentManager::instrument_id_t> IDs =
2443                        pManager->GetInstrumentFileContent(Filename);
2444                    // return a list of IDs of the instruments in the file
2445                    String s;
2446                    for (int j = 0; j < IDs.size(); j++) {
2447                        if (s.size()) s += ",";
2448                        s += ToString(IDs[j].Index);
2449                    }
2450                    result.Add(s);
2451                    // no more need to ask other engine types
2452                    bFound = true;
2453                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2454            } catch (Exception e) {
2455                // NOOP, as exception is thrown if engine doesn't support file
2456            }
2457            if (pEngine) EngineFactory::Destroy(pEngine);
2458        }
2459    
2460        if (!bFound) result.Error("Unknown file format");
2461        return result.Produce();
2462    }
2463    
2464    String LSCPServer::GetFileInstrumentInfo(String Filename, uint InstrumentID) {
2465        dmsg(2,("LSCPServer: GetFileInstrumentInfo(String Filename=%s, InstrumentID=%d)\n",Filename.c_str(),InstrumentID));
2466        LSCPResultSet result;
2467        try {
2468            VerifyFile(Filename);
2469        } catch (Exception e) {
2470            result.Error(e);
2471            return result.Produce();
2472        }
2473        InstrumentManager::instrument_id_t id;
2474        id.FileName = Filename;
2475        id.Index    = InstrumentID;
2476        // try to find a sampler engine that can handle the file
2477        bool bFound = false;
2478        bool bFatalErr = false;
2479        std::vector<String> engineTypes = EngineFactory::AvailableEngineTypes();
2480        for (int i = 0; !bFound && !bFatalErr && i < engineTypes.size(); i++) {
2481            Engine* pEngine = NULL;
2482            try {
2483                pEngine = EngineFactory::Create(engineTypes[i]);
2484                if (!pEngine) throw Exception("Internal error: could not create '" + engineTypes[i] + "' engine");
2485                InstrumentManager* pManager = pEngine->GetInstrumentManager();
2486                if (pManager) {
2487                    // check if the instrument index is valid
2488                    // FIXME: this won't work if an engine only supports parts of the instrument file
2489                    std::vector<InstrumentManager::instrument_id_t> IDs =
2490                        pManager->GetInstrumentFileContent(Filename);
2491                    if (std::find(IDs.begin(), IDs.end(), id) == IDs.end()) {
2492                        std::stringstream ss;
2493                        ss << "Invalid instrument index " << InstrumentID << " for instrument file '" << Filename << "'";
2494                        bFatalErr = true;
2495                        throw Exception(ss.str());
2496                    }
2497                    // get the info of the requested instrument
2498                    InstrumentManager::instrument_info_t info =
2499                        pManager->GetInstrumentInfo(id);
2500                    // return detailed informations about the file
2501                    result.Add("NAME", info.InstrumentName);
2502                    result.Add("FORMAT_FAMILY", engineTypes[i]);
2503                    result.Add("FORMAT_VERSION", info.FormatVersion);
2504                    result.Add("PRODUCT", info.Product);
2505                    result.Add("ARTISTS", info.Artists);
2506                    // no more need to ask other engine types
2507                    bFound = true;
2508                } else dmsg(1,("Warning: engine '%s' does not provide an instrument manager\n", engineTypes[i].c_str()));
2509            } catch (Exception e) {
2510                // usually NOOP, as exception is thrown if engine doesn't support file
2511                if (bFatalErr) result.Error(e);
2512            }
2513            if (pEngine) EngineFactory::Destroy(pEngine);
2514        }
2515    
2516        if (!bFound && !bFatalErr) result.Error("Unknown file format");
2517        return result.Produce();
2518    }
2519    
2520    void LSCPServer::VerifyFile(String Filename) {
2521        #if WIN32
2522        WIN32_FIND_DATA win32FileAttributeData;
2523        BOOL res = GetFileAttributesEx( Filename.c_str(), GetFileExInfoStandard, &win32FileAttributeData );
2524        if (!res) {
2525            std::stringstream ss;
2526            ss << "File does not exist, GetFileAttributesEx failed `" << Filename << "`: Error " << GetLastError();
2527            throw Exception(ss.str());
2528        }
2529        if ( win32FileAttributeData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
2530            throw Exception("Directory is specified");
2531        }
2532        #else    
2533        struct stat statBuf;
2534        int res = stat(Filename.c_str(), &statBuf);
2535        if (res) {
2536            std::stringstream ss;
2537            ss << "Fail to stat `" << Filename << "`: " << strerror(errno);
2538            throw Exception(ss.str());
2539        }
2540    
2541        if (S_ISDIR(statBuf.st_mode)) {
2542            throw Exception("Directory is specified");
2543        }
2544        #endif
2545    }
2546    
2547  /**  /**
2548   * Will be called by the parser to subscribe a client (frontend) on the   * Will be called by the parser to subscribe a client (frontend) on the
2549   * server for receiving event messages.   * server for receiving event messages.
# Line 2416  String LSCPServer::GetDbInstrumentDirect Line 2645  String LSCPServer::GetDbInstrumentDirect
2645      try {      try {
2646          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);          DbDirectory info = InstrumentsDb::GetInstrumentsDb()->GetDirectoryInfo(Dir);
2647    
2648          result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2649          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2650          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2651      } catch (Exception e) {      } catch (Exception e) {
# Line 2600  String LSCPServer::GetDbInstrumentInfo(S Line 2829  String LSCPServer::GetDbInstrumentInfo(S
2829          result.Add("SIZE", (int)info.Size);          result.Add("SIZE", (int)info.Size);
2830          result.Add("CREATED", info.Created);          result.Add("CREATED", info.Created);
2831          result.Add("MODIFIED", info.Modified);          result.Add("MODIFIED", info.Modified);
2832          result.Add("DESCRIPTION", InstrumentsDb::toEscapedText(info.Description));          result.Add("DESCRIPTION", _escapeLscpResponse(info.Description));
2833          result.Add("IS_DRUM", info.IsDrum);          result.Add("IS_DRUM", info.IsDrum);
2834          result.Add("PRODUCT", InstrumentsDb::toEscapedText(info.Product));          result.Add("PRODUCT", _escapeLscpResponse(info.Product));
2835          result.Add("ARTISTS", InstrumentsDb::toEscapedText(info.Artists));          result.Add("ARTISTS", _escapeLscpResponse(info.Artists));
2836          result.Add("KEYWORDS", InstrumentsDb::toEscapedText(info.Keywords));          result.Add("KEYWORDS", _escapeLscpResponse(info.Keywords));
2837      } catch (Exception e) {      } catch (Exception e) {
2838           result.Error(e);           result.Error(e);
2839      }      }

Legend:
Removed from v.1399  
changed lines
  Added in v.1537

  ViewVC Help
Powered by ViewVC