Example #1
0
int DemosDataSource::GetNumRows( const String& table ) {
	// table name represents a relative demo path with a trailing "/":
	// "/" represents the root path inside the demo directory
	// "tutorials/" represents tutorials subdirectory, etc

	// if we haven't yet traversed the queried path, do it now
	if( demoPaths.find( table ) == demoPaths.end() ) {
		std::string pathStr( table.CString() );

		// chop off the trailing "/"
		if( pathStr.find_last_of( "/" ) + 1 == pathStr.length() ) {
			pathStr = pathStr.substr( 0, pathStr.length() - 1 );
		}

		// the helper will start sending updates the next frame
		demoPaths[table] = DemosDataSourceHelper( pathStr, demoExtension );
	}

	if( !lastQueryTable.Empty() ) {
		// reset cache on directory change
		if( lastQueryTable != table ) {
			demoPaths.erase( demoPaths.find( lastQueryTable ) );
			NotifyRowChange( lastQueryTable );
		}
	}

	lastQueryTable = table;
	const DemosDataSourceHelper &demoPath = demoPaths[table];
	return demoPath.GetUpdateIndex();
}
Example #2
0
void deleteRecursive(const char* path) {
    string pathStr(path);
    if (pathStr[pathStr.size()-1] != '/') {
        pathStr += '/';
    }

    DIR* dir = opendir(path);
    if (!dir) {
        PLOG(ERROR) << "opendir " << path << " failed";
        return;
    }

    struct dirent* entry;
    while ((entry = readdir(dir))) {
        const char* name = entry->d_name;

        // ignore "." and ".."
        if (name[0] == '.' && (name[1] == 0 || (name[1] == '.' && name[2] == 0))) {
            continue;
        }
        pathStr.append(name);
        if (entry->d_type == DT_DIR) {
            deleteRecursive(pathStr.c_str());
            rmdir(pathStr.c_str());
        } else {
            unlink(pathStr.c_str());
        }
    }
    closedir(dir);
}
Example #3
0
bool FileUtils::isRelative(const char* path)
{
#ifdef PLATFORM_UNIX
	return strlen(path) == 0 || path[0] != '/';
#else
	// on Windows, a path is relative if it does not start with:
	// - '\\' (a UNC name)
	// - '[Drive Letter]:\'
	// - A single backslash
	//
	// the input path is assumed to have already been converted to use
	// Unix-style path separators

	std::string pathStr(path);

	if ((!pathStr.empty() && pathStr.at(0) == '/') ||
	    (startsWith(pathStr,"//")) ||
	    (startsWithDriveLetter(pathStr.c_str())))
	{
		return false;
	}
	else
	{
		return true;
	}
#endif
}
LRESULT HandleDropFiles(HDROP hDrop, CefRefPtr<ClientHandler> handler, CefRefPtr<CefBrowser> browser) {
    UINT fileCount = DragQueryFile(hDrop, 0xFFFFFFFF, NULL, 0);
    for (UINT i = 0; i < fileCount; i++) {
        wchar_t filename[MAX_PATH];
        DragQueryFile(hDrop, i, filename, MAX_PATH);
        std::wstring pathStr(filename);
        replace(pathStr.begin(), pathStr.end(), '\\', '/');
        handler->SendOpenFileCommand(browser, CefString(pathStr));
    }
    return 0;
}
nsresult
nsSubscribableServer::FindAndCreateNode(const nsACString &aPath,
                                        SubscribeTreeNode **aResult)
{
  nsresult rv = NS_OK;
  NS_ASSERTION(aResult, "no result");
  if (!aResult) return NS_ERROR_NULL_POINTER;

  if (!mTreeRoot) {
      nsCString serverUri;
      rv = mIncomingServer->GetServerURI(serverUri);
      NS_ENSURE_SUCCESS(rv,rv);
      // the root has no parent, and its name is server uri
      rv = CreateNode(nsnull, serverUri.get(), &mTreeRoot);
      NS_ENSURE_SUCCESS(rv,rv);
  }

  if (aPath.IsEmpty()) {
      *aResult = mTreeRoot;
      return NS_OK;
  }

  char *token = nsnull;
  nsCString pathStr(aPath);
  char *rest = pathStr.BeginWriting();

  // todo do this only once
  char delimstr[2];
  delimstr[0] = mDelimiter;
  delimstr[1] = '\0';

  *aResult = nsnull;

  SubscribeTreeNode *parent = mTreeRoot;
  SubscribeTreeNode *child = nsnull;

  token = NS_strtok(delimstr, &rest); 
  // special case paths that start with the hierarchy delimiter.
  // We want to include that delimiter in the first token name.
  if (token && pathStr[0] == mDelimiter)
    --token;
  while (token && *token) {
    rv = AddChildNode(parent, token, &child);
    if (NS_FAILED(rv))
      return rv;
    token = NS_strtok(delimstr, &rest);
    parent = child;
  }

  // the last child we add is the result
  *aResult = child;
  return rv;
}
wxDirTraverseResult HeaderDirTraverser::OnDir(const wxString& dirname)
{
    // HeaderDirTraverser is used in a worker thread, so call TestDestroy() as often as it can to
    // quickly terminate the thread
    if (m_Thread->TestDestroy())
        return wxDIR_STOP;

    AddLock(false); // false means we are adding a dir

    wxString path(dirname);
    if (path.Last() != wxFILE_SEP_PATH)
        path.Append(wxFILE_SEP_PATH);

#ifndef _WIN32
    struct stat fileStats;
    if (lstat(dirname.mb_str(wxConvUTF8), &fileStats) != 0)
        return wxDIR_IGNORE;

    // If the path is a symbolic link, then try to resolve it.
    // This is needed to prevent infinite loops, when a folder is pointing to itself or its parent folder.
    if (S_ISLNK(fileStats.st_mode))
    {
        char buffer[4096];
        int result = readlink(dirname.mb_str(wxConvUTF8), buffer, WXSIZEOF(buffer) - 1);
        if (result != -1)
        {
            buffer[result] = '\0'; // readlink() doesn't NUL-terminate the buffer
            wxString pathStr(buffer, wxConvUTF8);
            wxFileName fileName(pathStr);

            // If this is a relative symbolic link, we need to make it absolute.
            if (!fileName.IsAbsolute())
            {
                wxFileName dirNamePath(path);
                dirNamePath.RemoveLastDir();
                // Make the new filename absolute relative to the parent folder.
                fileName.MakeAbsolute(dirNamePath.GetFullPath());
            }

            wxString fullPath = fileName.GetFullPath();
            if (fullPath.Last() == wxT('.')) // this case should be handled because of a bug in wxWidgets
                fullPath.RemoveLast();
            if (fullPath.Last() != wxFILE_SEP_PATH)
                fullPath.Append(wxFILE_SEP_PATH);
            return GetStatus(fullPath);
        }
    }
#endif // _WIN32

    return GetStatus(path);
}
bool cbResolveSymLinkedDirPath(wxString& dirpath)
{
#ifdef _WIN32
    return false;
#else
    if (dirpath.Last() == wxFILE_SEP_PATH)
        dirpath.RemoveLast();

    struct stat fileStats;
    if (lstat(dirpath.mb_str(wxConvUTF8), &fileStats) != 0)
        return false;

    // If the path is a symbolic link, then try to resolve it.
    // This is needed to prevent infinite loops, when a folder is pointing to itself or its parent folder.
    if (S_ISLNK(fileStats.st_mode))
    {
        char buffer[4096];
        int result = readlink(dirpath.mb_str(wxConvUTF8), buffer, WXSIZEOF(buffer) - 1);
        if (result != -1)
        {
            buffer[result] = '\0'; // readlink() doesn't NUL-terminate the buffer
            wxString pathStr(buffer, wxConvUTF8);
            wxFileName fileName = wxFileName::DirName(pathStr);

            // If this is a relative symbolic link, we need to make it absolute.
            if (!fileName.IsAbsolute())
            {
                wxFileName dirNamePath;
                if (dirpath.Last() == wxFILE_SEP_PATH)
                    dirNamePath = wxFileName::DirName(dirpath);
                else
                    dirNamePath = wxFileName::DirName(dirpath + wxFILE_SEP_PATH);
                dirNamePath.RemoveLastDir();
                // Make the new filename absolute relative to the parent folder.
                fileName.MakeAbsolute(dirNamePath.GetFullPath());
            }

            wxString fullPath = fileName.GetFullPath();
            if (fullPath.Last() == wxT('.')) // this case should be handled because of a bug in wxWidgets
                fullPath.RemoveLast();
            if (fullPath.Last() == wxFILE_SEP_PATH)
                fullPath.RemoveLast();
            dirpath = fullPath;
            return true;
        }
    }

    return false;
#endif // _WIN32
}
Example #8
0
	static boost::filesystem::path convertCFUrlToPath(CFURLRef url)
	{
		CFStringRef str = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);
		CFIndex size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingASCII) + 1;

		char* cstr = new char[size];
		CFStringGetCString(str, cstr, size, kCFStringEncodingASCII);

		CFRelease(str);
		CFRelease(url);

		std::string pathStr(cstr);
		delete[] cstr;

		return boost::filesystem::path(pathStr);
	}
Example #9
0
FileEnumerator* HDFSAccessor::getFolderContent(char* path)
{
    bool isNewEnv = false;
    JNIEnv* env = JVMState::instance()->getEnv(&isNewEnv);
    if (m_wfxPairObj != NULL)
    {
        jstring pathStr = env->NewStringUTF(path);
        jobjectArray contentArray = static_cast<jobjectArray>(env->CallObjectMethod(m_wfxPairObj, s_WfxPairMetIdGetFolderContent, pathStr));
        if (!JVMState::instance()->exceptionExists(env))
        {
            env->DeleteLocalRef(pathStr);
            if (contentArray != NULL)
            {
                set<string> contentItems;
                jsize len = env->GetArrayLength(contentArray);
                for (jsize i = 0; i < len; i++)
                {
                    jstring elem = static_cast<jstring>(env->GetObjectArrayElement(contentArray, i));
                    if (elem != NULL)
                    {
                        const char *str = env->GetStringUTFChars(elem, NULL);
                        string item(str);
                        contentItems.insert(item);
                        env->ReleaseStringUTFChars(elem, str);
                    }
                }
                string pathStr(path);
                jobject neObj = env->NewGlobalRef(m_wfxPairObj);
                if (isNewEnv)
                {
                    JVMState::instance()->releaseEnv();
                }
                return new FileEnumerator(neObj, pathStr, contentItems);
            }
        } else
        {
            env->DeleteLocalRef(pathStr);
        }
    }
    if (isNewEnv)
    {
        JVMState::instance()->releaseEnv();
    }

    return NULL;
}
Example #10
0
FILE* LogDebugEnabled()
{

    if (DebugLogOn(sServer))
    {
        static StrPtrLen statsFileNameStr("server_debug_status");    
    
        StrPtrLenDel pathStr(sServer->GetPrefs()->GetErrorLogDir());
        ResizeableStringFormatter pathBuffer(NULL,0);
        pathBuffer.PutFilePath(&pathStr,&statsFileNameStr);
        pathBuffer.PutTerminator();
        
        char*   filePath = pathBuffer.GetBufPtr();    
        return ::fopen(filePath, "a");
    }
    
    return NULL;
}
Example #11
0
FileLocation::FileLocation(const FileLocation &file, const char *path)
{
  if (file.IsZip()) {
    if (file.mBaseFile) {
      Init(file.mBaseFile, file.mPath.get());
    } else {
      Init(file.mBaseZip, file.mPath.get());
    }
    if (path) {
      PRInt32 i = mPath.RFindChar('/');
      if (kNotFound == i) {
        mPath.Truncate(0);
      } else {
        mPath.Truncate(i + 1);
      }
      mPath += path;
    }
  } else {
    if (path) {
      nsCOMPtr<nsIFile> cfile;
      file.mBaseFile->GetParent(getter_AddRefs(cfile));
      nsCOMPtr<nsILocalFile> clfile = do_QueryInterface(cfile);

#if defined(XP_WIN) || defined(XP_OS2)
      nsCAutoString pathStr(path);
      char *p;
      PRUint32 len = pathStr.GetMutableData(&p);
      for (; len; ++p, --len) {
        if ('/' == *p) {
            *p = '\\';
        }
      }
      clfile->AppendRelativeNativePath(pathStr);
#else
      clfile->AppendRelativeNativePath(nsDependentCString(path));
#endif
      Init(clfile);
    } else {
      Init(file.mBaseFile);
    }
  }
}
Example #12
0
FileLocation::FileLocation(const FileLocation& aFile, const char* aPath)
{
  if (aFile.IsZip()) {
    if (aFile.mBaseFile) {
      Init(aFile.mBaseFile, aFile.mPath.get());
    } else {
      Init(aFile.mBaseZip, aFile.mPath.get());
    }
    if (aPath) {
      int32_t i = mPath.RFindChar('/');
      if (kNotFound == i) {
        mPath.Truncate(0);
      } else {
        mPath.Truncate(i + 1);
      }
      mPath += aPath;
    }
  } else {
    if (aPath) {
      nsCOMPtr<nsIFile> cfile;
      aFile.mBaseFile->GetParent(getter_AddRefs(cfile));

#if defined(XP_WIN)
      nsAutoCString pathStr(aPath);
      char* p;
      uint32_t len = pathStr.GetMutableData(&p);
      for (; len; ++p, --len) {
        if ('/' == *p) {
          *p = '\\';
        }
      }
      cfile->AppendRelativeNativePath(pathStr);
#else
      cfile->AppendRelativeNativePath(nsDependentCString(aPath));
#endif
      Init(cfile);
    } else {
      Init(aFile.mBaseFile);
    }
  }
}
int OSCServer::genericHandler(
        const char *path, const char *types,
        lo_arg **argv, int argc, void *data)
{
    UNUSED(argc); UNUSED(types);

    if(!contacted) {
        firstContact(lo_message_get_source((lo_message)data));
        contacted = true;
    }

    //find out what this message is for (track bus or master)

    std::string pathStr(path);

    pathStr = pathStr.substr(1);
    pathStr = pathStr.substr(pathStr.find("/") + 1);

    std::string object = pathStr.substr(0,pathStr.find("/"));

    pathStr = pathStr.substr(pathStr.find("/") + 1);
    std::string controllable = pathStr.substr(0,pathStr.find("/"));

    if(object == "track") {
        if(controllable == "fader") {
            //get the track number
            pathStr= pathStr.substr(pathStr.find("/") + 1);
            //build a midi event from the fader value and track number
            char data[3];
            if(pthread_mutex_lock(&idMutex) == 0) {
                data[0] = (char) CC_MASK;
                data[1] = trackIds[atoi(pathStr.c_str()) - 1];
                data[2] = (char) ((int) argv[0]->f);

                pthread_mutex_unlock(&idMutex);
            }
            MidiEvent midiEvent(data,true);
            //Send it to the jack client to handle send to Ardour
            if(!((unsigned char)data[1] == 0xFF)){
                jack_ringbuffer_write(controllerBuffer, (char *) &midiEvent,sizeof(MidiEvent));
            }
        }

        if(controllable == "bank") {
            if (argv[0]->f > 0.5){
                pathStr= pathStr.substr(pathStr.find("/") + 1);
                if(pathStr == "up"){
                    int tb = getTrackBank();
                    if((tb+1) < numTrackBanks) {
                        sendTrackBank(tb+1);
                        setTrackBank(tb+1);
                    }
                }
                else if(pathStr == "down"){
                    int tb = getTrackBank();
                    if(tb > 0) {
                        sendTrackBank(tb-1);
                        setTrackBank(tb-1);
                    }
                }

            }
        }


    } else if (object == "bus") {

        if(controllable == "fader") {
            //get the bus number(void *)this
            pathStr= pathStr.substr(pathStr.find("/") + 1);
            char data[3];
            if(pthread_mutex_lock(&idMutex) == 0) {
                data[0] = (char) CC_MASK;
                data[1] = busIds[atoi(pathStr.c_str()) - 1];
                data[2] = (char) ((int) argv[0]->f);

                pthread_mutex_unlock(&idMutex);
            }
            MidiEvent midiEvent(data,true);
            //Send it to the jack client to handle send to Ardour
            //Send it to the jack client to handle send to Ardour
            if(!((unsigned char)data[1] == 0xFF)){
                jack_ringbuffer_write(controllerBuffer, (char *) &midiEvent,sizeof(MidiEvent));
            }
        }

        if(controllable == "bank") {
            if (argv[0]->f > 0.5){
                pathStr= pathStr.substr(pathStr.find("/") + 1);
                if(pathStr == "up"){
                    int bb = getBusBank();
                    if((bb+1) < numBusBanks) {
                        setBusBank(bb+1);
                        sendBusBank(bb+1);
                    }
                }
                else if(pathStr == "down"){
                    int bb = getBusBank();
                    if(bb > 0) {
                        setBusBank(bb-1);
                        sendBusBank(bb-1);
                    }
                }

            }
        }


    }
    else if (object == "master") {
        if(controllable == "fader") {
            //build a midi event from the fader value and track number
            char data[3] = {(char) CC_MASK,MASTER_CC,(char)((int) argv[0]->f)};
            MidiEvent midiEvent(data,true);
            //Send it to the jack client to handle send to Ardour
            jack_ringbuffer_write(controllerBuffer, (char *) &midiEvent,sizeof(MidiEvent));
        }

    }

    else if (object == "scene") {
    }

    return 0;
}
Example #14
0
JSObject*
Library::Create(JSContext* cx, jsval path_, JSCTypesCallbacks* callbacks)
{
  RootedValue path(cx, path_);
  RootedObject libraryObj(cx, JS_NewObject(cx, &sLibraryClass, NULL, NULL));
  if (!libraryObj)
    return NULL;

  // initialize the library
  JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PRIVATE_TO_JSVAL(NULL));

  // attach API functions
  if (!JS_DefineFunctions(cx, libraryObj, sLibraryFunctions))
    return NULL;

  if (!JSVAL_IS_STRING(path)) {
    JS_ReportError(cx, "open takes a string argument");
    return NULL;
  }

  PRLibSpec libSpec;
  RootedFlatString pathStr(cx, JS_FlattenString(cx, JSVAL_TO_STRING(path)));
  if (!pathStr)
    return NULL;
#ifdef XP_WIN
  // On Windows, converting to native charset may corrupt path string.
  // So, we have to use Unicode path directly.
  const PRUnichar* pathChars = JS_GetFlatStringChars(pathStr);
  if (!pathChars)
    return NULL;

  libSpec.value.pathname_u = pathChars;
  libSpec.type = PR_LibSpec_PathnameU;
#else
  // Convert to platform native charset if the appropriate callback has been
  // provided.
  char* pathBytes;
  if (callbacks && callbacks->unicodeToNative) {
    pathBytes = 
      callbacks->unicodeToNative(cx, pathStr->chars(), pathStr->length());
    if (!pathBytes)
      return NULL;

  } else {
    // Fallback: assume the platform native charset is UTF-8. This is true
    // for Mac OS X, Android, and probably Linux.
    size_t nbytes =
      GetDeflatedUTF8StringLength(cx, pathStr->chars(), pathStr->length());
    if (nbytes == (size_t) -1)
      return NULL;

    pathBytes = static_cast<char*>(JS_malloc(cx, nbytes + 1));
    if (!pathBytes)
      return NULL;

    ASSERT_OK(DeflateStringToUTF8Buffer(cx, pathStr->chars(),
                pathStr->length(), pathBytes, &nbytes));
    pathBytes[nbytes] = 0;
  }

  libSpec.value.pathname = pathBytes;
  libSpec.type = PR_LibSpec_Pathname;
#endif

  PRLibrary* library = PR_LoadLibraryWithFlags(libSpec, 0);

  if (!library) {
#ifdef XP_WIN
    JS_ReportError(cx, "couldn't open library %hs", pathChars);
#else
    JS_ReportError(cx, "couldn't open library %s", pathBytes);
    JS_free(cx, pathBytes);
#endif
    return NULL;
  }

#ifndef XP_WIN
  JS_free(cx, pathBytes);
#endif

  // stash the library
  JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PRIVATE_TO_JSVAL(library));

  return libraryObj;
}
Example #15
0
void LogStatus(QTSS_ServerState theServerState)
{
    static QTSS_ServerState lastServerState = 0;
    static char *sPLISTHeader[] =
    {     "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
#if __MacOSX__
        "<!DOCTYPE plist SYSTEM \"file://localhost/System/Library/DTDs/PropertyList.dtd\">",
#else
        "<!ENTITY % plistObject \"(array | data | date | dict | real | integer | string | true | false )\">",
        "<!ELEMENT plist %plistObject;>",
        "<!ATTLIST plist version CDATA \"0.9\">",
        "",
        "<!-- Collections -->",
        "<!ELEMENT array (%plistObject;)*>",
        "<!ELEMENT dict (key, %plistObject;)*>",
        "<!ELEMENT key (#PCDATA)>",
        "",
        "<!--- Primitive types -->",
        "<!ELEMENT string (#PCDATA)>",
        "<!ELEMENT data (#PCDATA)> <!-- Contents interpreted as Base-64 encoded -->",
        "<!ELEMENT date (#PCDATA)> <!-- Contents should conform to a subset of ISO 8601 (in particular, YYYY '-' MM '-' DD 'T' HH ':' MM ':' SS 'Z'.  Smaller units may be omitted with a loss of precision) -->",
        "",
        "<!-- Numerical primitives -->",
        "<!ELEMENT true EMPTY>  <!-- Boolean constant true -->",
        "<!ELEMENT false EMPTY> <!-- Boolean constant false -->",
        "<!ELEMENT real (#PCDATA)> <!-- Contents should represent a floating point number matching (\"+\" | \"-\")? d+ (\".\"d*)? (\"E\" (\"+\" | \"-\") d+)? where d is a digit 0-9.  -->",
        "<!ELEMENT integer (#PCDATA)> <!-- Contents should represent a (possibly signed) integer number in base 10 -->",
        "]>",
#endif
    };

    static int numHeaderLines = sizeof(sPLISTHeader) / sizeof(char*);

    static char*    sPlistStart = "<plist version=\"0.9\">";
    static char*    sPlistEnd = "</plist>";
    static char*    sDictStart = "<dict>";
    static char*    sDictEnd = "</dict>";
    
    static char*    sKey    = "     <key>%s</key>\n";
    static char*    sValue  = "     <string>%s</string>\n";
    
    static char *sAttributes[] =
    {
        "qtssSvrServerName",
        "qtssSvrServerVersion",
        "qtssSvrServerBuild",
        "qtssSvrServerPlatform",
        "qtssSvrRTSPServerComment",
        "qtssSvrServerBuildDate",
        "qtssSvrStartupTime",
        "qtssSvrCurrentTimeMilliseconds",
        "qtssSvrCPULoadPercent",
         "qtssSvrState",
        "qtssRTPSvrCurConn",
        "qtssRTSPCurrentSessionCount",
        "qtssRTSPHTTPCurrentSessionCount",
        "qtssRTPSvrCurBandwidth",
        "qtssRTPSvrCurPackets",
        "qtssRTPSvrTotalConn",
        "qtssRTPSvrTotalBytes",
        "qtssMP3SvrCurConn",
        "qtssMP3SvrTotalConn",
        "qtssMP3SvrCurBandwidth",
        "qtssMP3SvrTotalBytes"
    };
    static int numAttributes = sizeof(sAttributes) / sizeof(char*);
        
    static StrPtrLen statsFileNameStr("server_status");    
    
    if (false == sServer->GetPrefs()->ServerStatFileEnabled())
        return;
        
    UInt32 interval = sServer->GetPrefs()->GetStatFileIntervalSec();
    if (interval == 0 || (OS::UnixTime_Secs() % interval) > 0 ) 
        return;
    
    // If the total number of RTSP sessions is 0  then we 
    // might not need to update the "server_status" file.
    char* thePrefStr = NULL;
    // We start lastRTSPSessionCount off with an impossible value so that
    // we force the "server_status" file to be written at least once.
    static int lastRTSPSessionCount = -1; 
    // Get the RTSP session count from the server.
    (void)QTSS_GetValueAsString(sServer, qtssRTSPCurrentSessionCount, 0, &thePrefStr);
    int currentRTSPSessionCount = ::atoi(thePrefStr);
    delete [] thePrefStr; thePrefStr = NULL;
    if (currentRTSPSessionCount == 0 && currentRTSPSessionCount == lastRTSPSessionCount)
    {
        // we don't need to update the "server_status" file except the
        // first time we are in the idle state.
        if (theServerState == qtssIdleState && lastServerState == qtssIdleState)
        {
            lastRTSPSessionCount = currentRTSPSessionCount;
            lastServerState = theServerState;
            return;
        }
    }
    else
    {
        // save the RTSP session count for the next time we execute.
        lastRTSPSessionCount = currentRTSPSessionCount;
    }

    StrPtrLenDel pathStr(sServer->GetPrefs()->GetErrorLogDir());
    StrPtrLenDel fileNameStr(sServer->GetPrefs()->GetStatsMonitorFileName());
    ResizeableStringFormatter pathBuffer(NULL,0);
    pathBuffer.PutFilePath(&pathStr,&fileNameStr);
    pathBuffer.PutTerminator();
    
    char*   filePath = pathBuffer.GetBufPtr();    
    FILE*   statusFile = ::fopen(filePath, "w");
    char*   theAttributeValue = NULL;
    int     i;
    
    if (statusFile != NULL)
    {
        ::chmod(filePath, 0640);
        for ( i = 0; i < numHeaderLines; i++)
        {    
            qtss_fprintf(statusFile, "%s\n",sPLISTHeader[i]);    
        }

        qtss_fprintf(statusFile, "%s\n", sPlistStart);
        qtss_fprintf(statusFile, "%s\n", sDictStart);    

          // show each element value
         for ( i = 0; i < numAttributes; i++)
        {
            (void)QTSS_GetValueAsString(sServer, QTSSModuleUtils::GetAttrID(sServer,sAttributes[i]), 0, &theAttributeValue);
            if (theAttributeValue != NULL)
             {
                qtss_fprintf(statusFile, sKey, sAttributes[i]);    
               qtss_fprintf(statusFile, sValue, theAttributeValue);    
                delete [] theAttributeValue;
                theAttributeValue = NULL;
             }
         }
                  
        qtss_fprintf(statusFile, "%s\n", sDictEnd);
        qtss_fprintf(statusFile, "%s\n\n", sPlistEnd);    
         
          ::fclose(statusFile);
    }
    lastServerState = theServerState;
}
void CHttpCacheManager::ApplyCacheOverridesL(CRepository& aRepository, const TUint32& aSecIdInt, TBool& aCacheEnabled, TInt& aCacheSize, TBool& aOpCacheEnabled, TBool& aVssCacheEnabled, TDes& aPath, const TDesC& aDefaultDrive)
    {
    TDriveUnit drive(aDefaultDrive);
    
    // set defaults
    if(aSecIdInt == KUIDBROWSERNG)       // for the browser, force use of Operator and VSS caches
        {
        aOpCacheEnabled = ETrue;
        aVssCacheEnabled = ETrue;
        }
    
    // read override string from centrep
    HBufC16 *overrideBuf = HBufC16::NewLC(64);
    TPtr overrideStr(overrideBuf->Des());
    TInt strLen;
    TInt err = aRepository.Get(KCacheManagerHttpCacheProcessOverride, overrideStr, strLen);
    if(strLen > overrideBuf->Length())
        {
        overrideBuf = overrideBuf->ReAllocL(strLen);
        // make sure cleanup stack contains correct pointer since ReAllocL always allocates a new des for larger space.
        CleanupStack::Pop();
        CleanupStack::PushL(overrideBuf);
        // reassign the TPtr
        overrideStr.Set(overrideBuf->Des());
        // pull in the whole string
        aRepository.Get(KCacheManagerHttpCacheProcessOverride, overrideStr, strLen);
        }
    // if we failed to load an override string, use the default.
    if( overrideStr.Length() == 0 )
        {
        CleanupStack::PopAndDestroy( overrideBuf );
        overrideBuf = KDefaultOverrideString().AllocLC();
        overrideStr.Set( overrideBuf->Des() );
        }
    // Built in Lex likes white space to separate strings, but easier to enter with ; separators.  Replace all ; with spaces.
    TInt pos=0;
    do{
        if(overrideStr[pos] == ';')
            {
            overrideStr[pos] = ' ';
            }
        pos++;
    }while(pos < overrideStr.Length());
    
    TLex overrideLex(overrideStr);
    do{
        TUint32 tempId;
        User::LeaveIfError(overrideLex.BoundedVal(tempId,EHex,KMaxTUint32));
        if(overrideLex.TokenLength() != 8)  // if we're not pointing at an SID in the string, we are incorrect and the override is broken.
            User::Leave(KErrCorrupt);
        overrideLex.SkipSpace();
        TInt32 tempCacheEnabled;
        User::LeaveIfError(overrideLex.BoundedVal(tempCacheEnabled,KMaxTInt32));
        overrideLex.SkipSpace();
        TInt32 tempCacheSize;
        User::LeaveIfError(overrideLex.BoundedVal(tempCacheSize,KMaxTInt32));
        overrideLex.SkipSpace();
        TDriveUnit tempDrive(overrideLex.NextToken());
        overrideLex.SkipSpaceAndMark();
        // found a hex SID matching ours, use the parameters.
        if(tempId == aSecIdInt)
            {
            aCacheEnabled = tempCacheEnabled;
            aCacheSize = tempCacheSize * 1024; // conf is in KB
            drive = tempDrive;
            break;
            }
    }while(!overrideLex.Eos());

    // Modify drive letter on aPath to match
    TParsePtr parsePath(aPath);
    TPtrC pathStr(parsePath.Path());
    TPath tempPath;
    tempPath.Format(_L("%c:%S"), TInt(drive)+'A', &pathStr);
    aPath.Copy(tempPath);
    HttpCacheUtil::EnsureTrailingSlash( aPath );
    
    CleanupStack::PopAndDestroy(overrideBuf);
    }
bool ShinyFilesystemMediator::handleMessage( zmq::socket_t * sock, std::vector<zmq::message_t *> & msgList ) {
    zmq::message_t * fuseRoute = msgList[0];
    zmq::message_t * blankMsg = msgList[1];
    
    // Following the protocol (briefly) laid out in ShinyFuse.h;
    uint8_t type = parseTypeMsg(msgList[2]);
    switch( type ) {
        case ShinyFilesystemMediator::DESTROY: {
            // No actual response data, just sending response just to be polite
            sendACK( sock, fuseRoute );
            // return false as we're signaling to mediator that it's time to die.  >:}
            return false;
        }
        case ShinyFilesystemMediator::GETATTR: {
            // Let's actually get the data fuse wants!
            char * path = parseStringMsg( msgList[3] );
            
            // If the node even exists;
            ShinyMetaNode * node = fs->findNode( path );
            if( node ) {
                // we're just going to serialize it and send it on it's way!
                // Opportunity for zero-copy here!
                uint64_t len = node->serializedLen();
                char * buff = new char[len];
                node->serialize(buff);
                
                zmq::message_t ackMsg; buildTypeMsg( ShinyFilesystemMediator::ACK, &ackMsg );
                zmq::message_t nodeTypeMsg; buildTypeMsg( node->getNodeType(), &nodeTypeMsg );
                zmq::message_t nodeMsg; buildDataMsg( buff, len, &nodeMsg );
                
                sendMessages( sock, 5, fuseRoute, blankMsg, &ackMsg, &nodeTypeMsg, &nodeMsg );
                delete( buff );
            } else
                sendNACK( sock, fuseRoute );
            
            // cleanup after the parseStringMsg()
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::SETATTR: {
            char * path = parseStringMsg( msgList[3] );
            
            ShinyMetaNode * node = fs->findNode( path );
            if( node ) {
                const char * data = (const char *) msgList[4]->data();
                
                // Apply the data to the node
                node->unserialize( &data );
                
                // Send back ACK
                sendACK( sock, fuseRoute );
            } else
                sendNACK( sock, fuseRoute );
            
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::READDIR: {
            char * path = parseStringMsg( msgList[3] );
            
            // If the node even exists;
            ShinyMetaNode * node = fs->findNode( path );
            if( node && (node->getNodeType() == ShinyMetaNode::TYPE_DIR || node->getNodeType() == ShinyMetaNode::TYPE_ROOTDIR) ) {
                const std::vector<ShinyMetaNode *> * children = ((ShinyMetaDir *) node)->getNodes();
                
                // Here is my crucible, to hold data to be pummeled out of the networking autocannon, ZMQ
                std::vector<zmq::message_t *> list( 1 + 1 + 1 + children->size() );
                list[0] = fuseRoute;
                list[1] = blankMsg;
                
                zmq::message_t ackMsg; buildTypeMsg( ShinyFilesystemMediator::ACK, &ackMsg );
                list[2] = &ackMsg;
                
                for( uint64_t i=0; i<children->size(); ++i ) {
                    zmq::message_t * childMsg = new zmq::message_t(); buildStringMsg( (*children)[i]->getName(), childMsg );
                    list[3+i] = childMsg;
                }
                
                sendMessages( sock, list );
                
                // Free up those childMsg structures and ackMsg while we're at it (ackMsg is list[1])
                for( uint64_t i=3; i<list.size(); ++i ) {
                    delete( list[i] );
                }
            } else
                sendNACK( sock, fuseRoute );
            
            // cleanup, cleanup everybody everywhere!
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::OPEN: {
            // Grab the path, shove it into an std::string for searching openFiles
            char * path = parseStringMsg( msgList[3] );
            std::string pathStr( path );
            
            // This is our file that we'll eventually send back, or not, if we can't find the file
            ShinyMetaNode * node = NULL;
            
            // First, make sure that there is not already an OpenFileInfo corresponding to this path:
            std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );
            
            // If there isn't, let's get one! (if it exists)
            if( itty == this->openFiles.end() ) {
                node = fs->findNode( path );
                if( node && node->getNodeType() == ShinyMetaNode::TYPE_FILE ) {
                    // Create the new OpenFileInfo, initialize it to 1 opens, so only 1 close required to
                    // flush this data out of the map
                    OpenFileInfo * ofi = new OpenFileInfo();
                    ofi->file = (ShinyMetaFile *) node;
                    ofi->opens = 1;
                    
                    // Aaaand, put it into the list!
                    this->openFiles[pathStr] = ofi;
                }
            } else {
                // Check to make sure this guy isn't on death row 'cause of an unlink()
                if( !(*itty).second->shouldDelete ) {
                    // Otherwise, it's in the list, so let's return the cached copy!
                    node = (ShinyMetaNode *) (*itty).second->file;
                    
                    // Increment the number of times this file has been opened...
                    (*itty).second->opens++;
                    
                    // If it was going to be closed, let's stop that from happening now
                    (*itty).second->shouldClose = false;
                }
            }
            
            // If we were indeed able to find the file; write back an ACK, otherwise, NACK it up!
            if( node )
                sendACK( sock, fuseRoute );
            else
                sendNACK( sock, fuseRoute );
            
            // Don't forget this too!
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::CLOSE: {
            // Grab the path, just like in open
            char * path = parseStringMsg( msgList[3] );
            std::string pathStr( path );

            // This time, we _only_ check openFiles
            std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );
            
            // If it's there,
            if( itty != this->openFiles.end() ) {
                OpenFileInfo * ofi = (*itty).second;
                
                // decrement the opens!
                ofi->opens--;
                
                // Should we purge this ofi from the cache?
                if( ofi->opens == 0 ) {
                    // If we are currently write locked, or we have reads ongoing, we must
                    // wait 'till those are exuahsted, and so we will just mark ourselves as suicidal
                    if( ofi->writeLocked || ofi->reads > 0 ) {
                        // This will cause it to be closed once all READs and WRITEs are finished
                        ofi->shouldClose = true;
                    } else
                        this->closeOFI( itty );
                }
                
                // Aaaand, send an ACK, just for fun
                sendACK( sock, fuseRoute );
            } else {
                // NACK!  NACK I SAY!
                sendNACK( sock, fuseRoute );
            }
            
            // You just gotta free it up, fre-fre-free it all up now, 'come on!
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::READREQ:
        case ShinyFilesystemMediator::WRITEREQ:
        case ShinyFilesystemMediator::TRUNCREQ: {
            // Grab the path, and the itty
            char * path = parseStringMsg( msgList[3] );
            std::string pathStr( path );
            std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );
            
            // If it is in openFiles,
            if( itty != this->openFiles.end() ) {
                OpenFileInfo * ofi = (*itty).second;
                
                // first, we put it into our queue of file operations,
                zmq::message_t * savedRoute = new zmq::message_t();
                savedRoute->copy( fuseRoute );
                
                // Queue this request for later
                ofi->queuedFileOperations.push_back( QueuedFO( savedRoute, type ) );
                
                // Then, we try to start up more file operations. the subroutine will check to see
                // if we actually can or not.  It's amazing!  Magical, even.
                this->startQueuedFO( sock, ofi );
            } else
                sendNACK( sock, fuseRoute );
            
            // darn all these paths.  :P
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::READDONE:
        case ShinyFilesystemMediator::WRITEDONE:
        case ShinyFilesystemMediator::TRUNCDONE: {
            // Grab the path, and the itty
            char * path = parseStringMsg( msgList[3] );
            std::string pathStr( path );
            std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );

            // If it is in openFiles,
            if( itty != this->openFiles.end() ) {
                OpenFileInfo * ofi = (*itty).second;
                
                if( type == ShinyFilesystemMediator::WRITEDONE || type == ShinyFilesystemMediator::TRUNCDONE ) {
                    // We're not writelocked!  (at least, util we start writing again. XD)
                    ofi->writeLocked = false;
                } else if( type == ShinyFilesystemMediator::READDONE ) {
                    // Decrease the number of concurrently running READS!
                    ofi->reads--;
                }
                
                // Update the file with the serialized version sent back
                //LOG( "Updating %s due to a %s", path, (type == READDONE ? "READDONE" : (type == WRITEDONE ? "WRITEDONE" : "TRUNCDONE")) );
                const char * data = (const char *) msgList[4]->data();
                ofi->file->unserialize(&data);
                //delete( fs );
                
                if( !ofi->writeLocked || ofi->reads == 0 ) {
                    // Check to see if there's stuff queued, and if the conditions are right, start that queued stuff!
                    if( !ofi->queuedFileOperations.empty() )
                        this->startQueuedFO( sock, ofi );
                    else {
                        // If there is nothing queued, and we should close this file, CLOSE IT!
                        if( ofi->shouldClose )
                            this->closeOFI( itty );
                    }
                }
            }
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::CREATEFILE:
        case ShinyFilesystemMediator::CREATEDIR: {
            // Grab the path,
            char * path = parseStringMsg( msgList[3] );
            
            // See if the file already exists
            ShinyMetaNode * node = fs->findNode( path );
            if( node ) {
                // If it does, I can't very well create a file here, now can I?
                sendNACK( sock, fuseRoute );
            } else {
                // If not, check that the parent exists;
                ShinyMetaDir * parent = fs->findParentNode(path);
                
                if( !parent ) {
                    // If it doesn't, send a NACK!
                    sendNACK( sock, fuseRoute );
                } else {
                    // Otherwise, let's create the dir/file
                    if( type == ShinyFilesystemMediator::CREATEFILE )
                        node = new ShinyMetaFile( ShinyMetaNode::basename( path ), parent );
                    else
                        node = new ShinyMetaDir( ShinyMetaNode::basename( path), parent );
                    
                    // If they have included it, set the permissions away from the defaults
                    if( msgList.size() > 4 ) {
                        uint16_t mode = *((uint16_t *) parseDataMsg( msgList[4] ));
                        node->setPermissions( mode );
                    }
                    
                    // And send back an ACK
                    sendACK( sock, fuseRoute );
                }
            }
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::DELETE: {
            // Grab the path,
            char * path = parseStringMsg( msgList[3] );
            
            // Check to make sure the file exists
            ShinyMetaNode * node = fs->findNode( path );
            if( !node ) {
                // If it doesn'y, I can't very well delete it, can I?
                sendNACK( sock, fuseRoute );
            } else {
                // Since it exists, let's make sure it's not open right now
                std::string pathStr( path );
                std::map<std::string, OpenFileInfo *>::iterator itty = this->openFiles.find( pathStr );
                
                // If it is open, queue the deletion for later
                if( itty != this->openFiles.end() ) {
                    OpenFileInfo * ofi = (*itty).second;
                    ofi->shouldDelete = true;
                } else {
                    // Tell the db to delete him, if it's a file
                    if( node->getNodeType() == ShinyMetaNode::TYPE_FILE )
                        ((ShinyMetaFile *)node)->setLen( 0 );
                    
                    // actually delete the sucker
                    delete( node );
                }
            
                // AFFLACK.  AFFFFFLAACK.
                sendACK( sock, fuseRoute );
            }
            delete( path );
            break;
        }
        case ShinyFilesystemMediator::RENAME: {
            // Grab the path, and the new path
            char * path = parseStringMsg( msgList[3] );
            char * newPath = parseStringMsg( msgList[4] );
            
            // Check that their parents actually exist
            ShinyMetaDir * oldParent = fs->findParentNode( path );
            ShinyMetaDir * newParent = fs->findParentNode( newPath );
            
            if( oldParent && newParent ) {
                // Now that we know the parents are real, find the child
                const char * oldName = ShinyMetaNode::basename( path );
                const char * newName = ShinyMetaNode::basename( newPath );
                ShinyMetaNode * node = oldParent->findNode( oldName );
                
                if( node ) {
                    // Check to make sure we need to move it at all
                    if( oldParent != newParent ) {
                        oldParent->delNode( node );
                        newParent->addNode( node );
                    }
                    
                    // Don't setName to the same thing we had before, lol
                    if( strcmp( oldName, newName) != 0 )
                        node->setName( newName );
                    
                    // Send an ACK, for a job well done
                    sendACK( sock, fuseRoute );
                } else {
                    // We cannae faind tha node cap'n!
                    sendNACK( sock, fuseRoute );
                }

            } else {
                // Oh noes, we couldn't find oldParent or we couldn't find newParent!
                sendNACK( sock, fuseRoute );
            }
            
            delete( path );
            delete( newPath );
            break;
        }
        case ShinyFilesystemMediator::CHMOD: {
            // Grab the path, and the new path
            char * path = parseStringMsg( msgList[3] );
            uint16_t mode = *((uint16_t *) parseDataMsg( msgList[4] ));
            
            // Find node
            ShinyMetaNode * node = fs->findNode( path );
            if( node ) {
                // Set the permissionse
                node->setPermissions( mode );
                
                // ACK
                sendACK( sock, fuseRoute );
            } else
                sendNACK( sock, fuseRoute );

            delete( path );
            break;
        }
        default: {
            WARN( "Unknown ShinyFuse message type! (%d) Sending NACK:", type );
            sendNACK( sock, fuseRoute );
            break;
        }
    }
    
    return true;
}
static jlong
loadNativeCode_native(JNIEnv* env, jobject clazz, jstring path, jstring funcName,
        jobject messageQueue, jstring internalDataDir, jstring obbDir,
        jstring externalDataDir, jint sdkVersion, jobject jAssetMgr,
        jbyteArray savedState, jobject classLoader, jstring libraryPath) {
    if (kLogTrace) {
        ALOGD("loadNativeCode_native");
    }

    ScopedUtfChars pathStr(env, path);
    std::unique_ptr<NativeCode> code;
    bool needs_native_bridge = false;

    void* handle = OpenNativeLibrary(env,
                                     sdkVersion,
                                     pathStr.c_str(),
                                     classLoader,
                                     libraryPath,
                                     &needs_native_bridge,
                                     &g_error_msg);

    if (handle == nullptr) {
        ALOGW("NativeActivity LoadNativeLibrary(\"%s\") failed: %s",
              pathStr.c_str(),
              g_error_msg.c_str());
        return 0;
    }

    void* funcPtr = NULL;
    const char* funcStr = env->GetStringUTFChars(funcName, NULL);
    if (needs_native_bridge) {
        funcPtr = NativeBridgeGetTrampoline(handle, funcStr, NULL, 0);
    } else {
        funcPtr = dlsym(handle, funcStr);
    }

    code.reset(new NativeCode(handle, (ANativeActivity_createFunc*)funcPtr));
    env->ReleaseStringUTFChars(funcName, funcStr);

    if (code->createActivityFunc == NULL) {
        g_error_msg = needs_native_bridge ? NativeBridgeGetError() : dlerror();
        ALOGW("ANativeActivity_onCreate not found: %s", g_error_msg.c_str());
        return 0;
    }

    code->messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueue);
    if (code->messageQueue == NULL) {
        g_error_msg = "Unable to retrieve native MessageQueue";
        ALOGW("%s", g_error_msg.c_str());
        return 0;
    }

    int msgpipe[2];
    if (pipe(msgpipe)) {
        g_error_msg = android::base::StringPrintf("could not create pipe: %s", strerror(errno));
        ALOGW("%s", g_error_msg.c_str());
        return 0;
    }
    code->mainWorkRead = msgpipe[0];
    code->mainWorkWrite = msgpipe[1];
    int result = fcntl(code->mainWorkRead, F_SETFL, O_NONBLOCK);
    SLOGW_IF(result != 0, "Could not make main work read pipe "
            "non-blocking: %s", strerror(errno));
    result = fcntl(code->mainWorkWrite, F_SETFL, O_NONBLOCK);
    SLOGW_IF(result != 0, "Could not make main work write pipe "
            "non-blocking: %s", strerror(errno));
    code->messageQueue->getLooper()->addFd(
            code->mainWorkRead, 0, ALOOPER_EVENT_INPUT, mainWorkCallback, code.get());

    code->ANativeActivity::callbacks = &code->callbacks;
    if (env->GetJavaVM(&code->vm) < 0) {
        g_error_msg = "NativeActivity GetJavaVM failed";
        ALOGW("%s", g_error_msg.c_str());
        return 0;
    }
    code->env = env;
    code->clazz = env->NewGlobalRef(clazz);

    const char* dirStr = env->GetStringUTFChars(internalDataDir, NULL);
    code->internalDataPathObj = dirStr;
    code->internalDataPath = code->internalDataPathObj.string();
    env->ReleaseStringUTFChars(internalDataDir, dirStr);

    if (externalDataDir != NULL) {
        dirStr = env->GetStringUTFChars(externalDataDir, NULL);
        code->externalDataPathObj = dirStr;
        env->ReleaseStringUTFChars(externalDataDir, dirStr);
    }
    code->externalDataPath = code->externalDataPathObj.string();

    code->sdkVersion = sdkVersion;

    code->javaAssetManager = env->NewGlobalRef(jAssetMgr);
    code->assetManager = NdkAssetManagerForJavaObject(env, jAssetMgr);

    if (obbDir != NULL) {
        dirStr = env->GetStringUTFChars(obbDir, NULL);
        code->obbPathObj = dirStr;
        env->ReleaseStringUTFChars(obbDir, dirStr);
    }
    code->obbPath = code->obbPathObj.string();

    jbyte* rawSavedState = NULL;
    jsize rawSavedSize = 0;
    if (savedState != NULL) {
        rawSavedState = env->GetByteArrayElements(savedState, NULL);
        rawSavedSize = env->GetArrayLength(savedState);
    }

    code->createActivityFunc(code.get(), rawSavedState, rawSavedSize);

    if (rawSavedState != NULL) {
        env->ReleaseByteArrayElements(savedState, rawSavedState, 0);
    }

    return (jlong)code.release();
}
void FSGetSplitPath(const char *path, UniString *pDrive, UniString *pDir, UniString *fileTitle, UniString *exeName)
{
	UniString	pathStr(path);
	FSGetSplitPath(pathStr, pDrive, pDir, fileTitle, exeName);
}
Example #20
0
JSObject*
Library::Create(JSContext* cx, HandleValue path, const JSCTypesCallbacks* callbacks)
{
  RootedObject libraryObj(cx, JS_NewObject(cx, &sLibraryClass));
  if (!libraryObj)
    return nullptr;

  // initialize the library
  JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(nullptr));

  // attach API functions
  if (!JS_DefineFunctions(cx, libraryObj, sLibraryFunctions))
    return nullptr;

  if (!path.isString()) {
    JS_ReportErrorASCII(cx, "open takes a string argument");
    return nullptr;
  }

  PRLibSpec libSpec;
  RootedFlatString pathStr(cx, JS_FlattenString(cx, path.toString()));
  if (!pathStr)
    return nullptr;
  AutoStableStringChars pathStrChars(cx);
  if (!pathStrChars.initTwoByte(cx, pathStr))
    return nullptr;
#ifdef XP_WIN
  // On Windows, converting to native charset may corrupt path string.
  // So, we have to use Unicode path directly.
  char16ptr_t pathChars = pathStrChars.twoByteChars();
  libSpec.value.pathname_u = pathChars;
  libSpec.type = PR_LibSpec_PathnameU;
#else
  // Convert to platform native charset if the appropriate callback has been
  // provided.
  char* pathBytes;
  if (callbacks && callbacks->unicodeToNative) {
    pathBytes =
      callbacks->unicodeToNative(cx, pathStrChars.twoByteChars(), pathStr->length());
    if (!pathBytes)
      return nullptr;

  } else {
    // Fallback: assume the platform native charset is UTF-8. This is true
    // for Mac OS X, Android, and probably Linux.
    size_t nbytes =
      GetDeflatedUTF8StringLength(cx, pathStrChars.twoByteChars(), pathStr->length());
    if (nbytes == (size_t) -1)
      return nullptr;

    pathBytes = static_cast<char*>(JS_malloc(cx, nbytes + 1));
    if (!pathBytes)
      return nullptr;

    ASSERT_OK(DeflateStringToUTF8Buffer(cx, pathStrChars.twoByteChars(),
                pathStr->length(), pathBytes, &nbytes));
    pathBytes[nbytes] = 0;
  }

  libSpec.value.pathname = pathBytes;
  libSpec.type = PR_LibSpec_Pathname;
#endif

  PRLibrary* library = PR_LoadLibraryWithFlags(libSpec, PR_LD_NOW);

#ifndef XP_WIN
  JS_free(cx, pathBytes);
#endif

  if (!library) {
#define MAX_ERROR_LEN 1024
    char error[MAX_ERROR_LEN] = "Cannot get error from NSPR.";
    uint32_t errorLen = PR_GetErrorTextLength();
    if (errorLen && errorLen < MAX_ERROR_LEN)
      PR_GetErrorText(error);
#undef MAX_ERROR_LEN

    if (JS::StringIsASCII(error)) {
      JSAutoByteString pathCharsUTF8;
      if (pathCharsUTF8.encodeUtf8(cx, pathStr))
        JS_ReportErrorUTF8(cx, "couldn't open library %s: %s", pathCharsUTF8.ptr(), error);
    } else {
      JSAutoByteString pathCharsLatin1;
      if (pathCharsLatin1.encodeLatin1(cx, pathStr))
        JS_ReportErrorLatin1(cx, "couldn't open library %s: %s", pathCharsLatin1.ptr(), error);
    }
    return nullptr;
  }

  // stash the library
  JS_SetReservedSlot(libraryObj, SLOT_LIBRARY, PrivateValue(library));

  return libraryObj;
}
Example #21
0
wxArrayString FSOExecutable::GetBinariesFromRootFolder(const wxFileName& path, const wxString& globPattern, bool quiet) {
	wxArrayString files;

	// Check args because this function gets crap tossed at it to validate
	wxString pathStr(path.GetPath());
	if (pathStr.IsEmpty())
	{
		wxLogInfo(wxT("GetBinaries called with empty root folder"));
		return files;
	}

	wxDir folder(pathStr);
	if (!folder.IsOpened())
	{
		wxLogInfo(wxT("GetBinaries called on '%s' which cannot be opened"),
			pathStr.c_str());
		return files;
	}
	wxString filename;

#if IS_APPLE // Binaries are directories on OSX.
	bool cont = folder.GetFirst(&filename, globPattern, wxDIR_DIRS);
#else
	bool cont = folder.GetFirst(&filename, globPattern, wxDIR_FILES);
#endif

	while (cont) {
#if IS_LINUX
		if ( !IsFileToIgnore(filename) ) {
#endif
		files.Add(filename);
#if IS_LINUX
		}
#endif
		cont = folder.GetNext(&filename);
	}

	// filter out launcher binaries (at least on OSX)
	for (int i = files.GetCount() - 1; i >= 0; --i) {
		if (files[i].Lower().Find(_T("launcher")) != wxNOT_FOUND) {
			files.RemoveAt(i);
		}
	}
	
#if IS_APPLE
	// find actual (Unix) executable inside .app bundle and call the path to it the "executable"
	for (wxArrayString::iterator it = files.begin(), end = files.end(); it != end; ++it) {
		wxString pathToBin = 
			wxDir::FindFirst(path.GetPath(wxPATH_GET_SEPARATOR) + *it + _T("/Contents/MacOS"),
							 _T("*"),
							 wxDIR_FILES);
		pathToBin.Replace(path.GetPath(wxPATH_GET_SEPARATOR), _T(""));
		*it = pathToBin;
	}
#endif
	
	if (!quiet) {
		wxString execType = globPattern.Lower().Find(_T("fred")) == wxNOT_FOUND ? _T("FS2") : _T("FRED2");
		wxLogInfo(_T(" Found %d %s Open executables in '%s'"),
			files.GetCount(), execType.c_str(), path.GetPath().c_str());
		
		for (size_t i = 0, n = files.GetCount(); i < n; ++i) {
			wxLogDebug(_T("Found executable: %s"), files.Item(i).c_str());
		}
	}

	return files;
}
DirPath get_data_dir(){
  wxString pathStr(get_faint_dir_wx().GetFullPath());
  pathStr.Replace("\\", "/");
  return DirPath(pathStr);
}
Example #23
0
/*
=============
MD5Model::ValidMD5MeshExtension

	Checks if the path ends with md5mesh
=============
*/
bool MD5Model::ValidMD5MeshExtension( const char* path ) {
	std::string pathStr( path );
	return ( pathStr.length() > 7 &&
			 pathStr.substr( pathStr.length() - 7, 7 ).compare( "md5mesh" ) == 0 );
}