//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
void CtrlrLuaMethodEditArea::mouseDoubleClick (const MouseEvent &e)
{
	// LUA compile error: ERROR: [string "function myNewMethod()..."]:4: '=' expected near 'end'
	// Search result: SEARCH: [method]:3 position:43-46

	const String line = output->getLineAtPosition (output->getTextIndexAt (e.x, e.y)).trim();

	//_DBG(line);

	if (line.startsWithIgnoreCase("ERROR"))
	{
		const int errorInLine = line.fromFirstOccurrenceOf ("]:", false, true).getIntValue();

		if (errorInLine > 0 && owner.getCurrentEditor())
		{
			owner.getCurrentEditor()->setErrorLine(errorInLine);
		}
	}
	else if (line.startsWithIgnoreCase("Method: "))
	{
		const String methodName	= line.fromFirstOccurrenceOf ("Method: ", false, false).upToFirstOccurrenceOf("line: ", false, true).trim();
		const int errorInLine	= line.fromFirstOccurrenceOf ("line: ", false, true).getIntValue();
		const int positionStart	= line.fromFirstOccurrenceOf ("start: ", false,true).getIntValue();
		const int positionEnd	= line.fromFirstOccurrenceOf ("end: ", false,true).getIntValue();

		owner.searchResultClicked (methodName, errorInLine, positionStart, positionEnd);
	}
}
    RegistryKeyWrapper (String name, const bool createForWriting, const DWORD wow64Flags)
        : key (0), wideCharValueName (nullptr)
    {
        HKEY rootKey = 0;

        if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))        rootKey = HKEY_CURRENT_USER;
        else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))  rootKey = HKEY_LOCAL_MACHINE;
        else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))   rootKey = HKEY_CLASSES_ROOT;

        if (rootKey != 0)
        {
            name = name.substring (name.indexOfChar ('\\') + 1);

            const int lastSlash = name.lastIndexOfChar ('\\');
            valueName = name.substring (lastSlash + 1);
            wideCharValueName = valueName.toWideCharPointer();

            name = name.substring (0, lastSlash);
            const wchar_t* const wideCharName = name.toWideCharPointer();
            DWORD result;

            if (createForWriting)
                RegCreateKeyEx (rootKey, wideCharName, 0, 0, REG_OPTION_NON_VOLATILE,
                                KEY_WRITE | KEY_QUERY_VALUE | wow64Flags, 0, &key, &result);
            else
                RegOpenKeyEx (rootKey, wideCharName, 0, KEY_READ | wow64Flags, &key);
        }
    }
//==============================================================================
bool Process::openDocument (const String& fileName, const String& parameters)
{
    String cmdString (fileName.replace (" ", "\\ ",false));
    cmdString << " " << parameters;

    if (URL::isProbablyAWebsiteURL (fileName)
         || cmdString.startsWithIgnoreCase ("file:")
         || URL::isProbablyAnEmailAddress (fileName))
    {
        // create a command that tries to launch a bunch of likely browsers
        const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };

        StringArray cmdLines;

        for (int i = 0; i < numElementsInArray (browserNames); ++i)
            cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());

        cmdString = cmdLines.joinIntoString (" || ");
    }

    const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };

    const int cpid = fork();

    if (cpid == 0)
    {
        setsid();

        // Child process
        execve (argv[0], (char**) argv, environ);
        exit (0);
    }

    return cpid >= 0;
}
Beispiel #4
0
bool XmlDocument::parseHeader()
{
    skipNextWhiteSpace();

    if (CharacterFunctions::compareUpTo (input, CharPointer_ASCII ("<?xml"), 5) == 0)
    {
        const String::CharPointerType headerEnd (CharacterFunctions::find (input, CharPointer_ASCII ("?>")));

        if (headerEnd.isEmpty())
            return false;

       #if JUCE_DEBUG
        const String encoding (String (input, headerEnd)
                                 .fromFirstOccurrenceOf ("encoding", false, true)
                                 .fromFirstOccurrenceOf ("=", false, false)
                                 .fromFirstOccurrenceOf ("\"", false, false)
                                 .upToFirstOccurrenceOf ("\"", false, false).trim());

        /* If you load an XML document with a non-UTF encoding type, it may have been
           loaded wrongly.. Since all the files are read via the normal juce file streams,
           they're treated as UTF-8, so by the time it gets to the parser, the encoding will
           have been lost. Best plan is to stick to utf-8 or if you have specific files to
           read, use your own code to convert them to a unicode String, and pass that to the
           XML parser.
        */
        jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
       #endif

        input = headerEnd + 2;
        skipNextWhiteSpace();
    }

    return true;
}
Beispiel #5
0
    void openHTTPConnection (URL_COMPONENTS& uc, URL::OpenStreamProgressCallback* progressCallback,
                             void* progressCallbackContext)
    {
        const TCHAR* mimeTypes[] = { _T("*/*"), 0 };

        DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;

        if (address.startsWithIgnoreCase ("https:"))
            flags |= INTERNET_FLAG_SECURE;  // (this flag only seems necessary if the OS is running IE6 -
                                            //  IE7 seems to automatically work out when it's https)

        request = HttpOpenRequest (connection, isPost ? _T("POST") : _T("GET"),
                                   uc.lpszUrlPath, 0, 0, mimeTypes, flags, 0);

        if (request != 0)
        {
            INTERNET_BUFFERS buffers = { 0 };
            buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
            buffers.lpcszHeader = headers.toWideCharPointer();
            buffers.dwHeadersLength = (DWORD) headers.length();
            buffers.dwBufferTotal = (DWORD) postData.getSize();

            if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
            {
                int bytesSent = 0;

                for (;;)
                {
                    const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
                    DWORD bytesDone = 0;

                    if (bytesToDo > 0
                         && ! InternetWriteFile (request,
                                                 static_cast <const char*> (postData.getData()) + bytesSent,
                                                 (DWORD) bytesToDo, &bytesDone))
                    {
                        break;
                    }

                    if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
                    {
                        if (HttpEndRequest (request, 0, 0, 0))
                            return;

                        break;
                    }

                    bytesSent += bytesDone;

                    if (progressCallback != nullptr
                          && ! progressCallback (progressCallbackContext, bytesSent, (int) postData.getSize()))
                        break;
                }
            }
        }

        close();
    }
 bool isAbsolutePath (const String& path)
 {
     return File::isAbsolutePath (path)
             || path.startsWithChar ('/') // (needed because File::isAbsolutePath will ignore forward-slashes on Windows)
             || path.startsWithChar ('$')
             || path.startsWithChar ('~')
             || (CharacterFunctions::isLetter (path[0]) && path[1] == ':')
             || path.startsWithIgnoreCase ("smb:");
 }
void XmlDocument::skipHeader()
{
    const int headerStart = input.indexOf (CharPointer_UTF8 ("<?xml"));

    if (headerStart >= 0)
    {
        const int headerEnd = (input + headerStart).indexOf (CharPointer_UTF8 ("?>"));
        if (headerEnd < 0)
            return;

       #if JUCE_DEBUG
        const String header (input + headerStart, (size_t) (headerEnd - headerStart));
        const String encoding (header.fromFirstOccurrenceOf ("encoding", false, true)
                                     .fromFirstOccurrenceOf ("=", false, false)
                                     .fromFirstOccurrenceOf ("\"", false, false)
                                     .upToFirstOccurrenceOf ("\"", false, false).trim());

        /* If you load an XML document with a non-UTF encoding type, it may have been
           loaded wrongly.. Since all the files are read via the normal juce file streams,
           they're treated as UTF-8, so by the time it gets to the parser, the encoding will
           have been lost. Best plan is to stick to utf-8 or if you have specific files to
           read, use your own code to convert them to a unicode String, and pass that to the
           XML parser.
        */
        jassert (encoding.isEmpty() || encoding.startsWithIgnoreCase ("utf-"));
       #endif

        input += headerEnd + 2;
    }

    skipNextWhiteSpace();

    const int docTypeIndex = input.indexOf (CharPointer_UTF8 ("<!DOCTYPE"));
    if (docTypeIndex < 0)
        return;

    input += docTypeIndex + 9;
    const String::CharPointerType docType (input);

    int n = 1;

    while (n > 0)
    {
        const juce_wchar c = readNextChar();

        if (outOfData)
            return;

        if (c == '<')
            ++n;
        else if (c == '>')
            --n;
    }

    dtdText = String (docType, (size_t) (input.getAddress() - (docType.getAddress() + 1))).trim();
}
Beispiel #8
0
void LocalisedStrings::loadFromText (const String& fileContents, bool ignoreCase)
{
    translations.setIgnoresCase (ignoreCase);

    StringArray lines;
    lines.addLines (fileContents);

    for (int i = 0; i < lines.size(); ++i)
    {
        String line (lines[i].trim());

        if (line.startsWithChar ('"'))
        {
            int closeQuote = findCloseQuote (line, 1);

            const String originalText (unescapeString (line.substring (1, closeQuote)));

            if (originalText.isNotEmpty())
            {
                const int openingQuote = findCloseQuote (line, closeQuote + 1);
                closeQuote = findCloseQuote (line, openingQuote + 1);

                const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));

                if (newText.isNotEmpty())
                    translations.set (originalText, newText);
            }
        }
        else if (line.startsWithIgnoreCase ("language:"))
        {
            languageName = line.substring (9).trim();
        }
        else if (line.startsWithIgnoreCase ("countries:"))
        {
            countryCodes.addTokens (line.substring (10).trim(), true);
            countryCodes.trim();
            countryCodes.removeEmptyStrings();
        }
    }

    translations.minimiseStorageOverheads();
}
    size_t curlHeaderCallback (char* ptr, size_t size, size_t nmemb)
    {
        if (curl == nullptr || lastError != CURLE_OK)
            return 0;

        size_t len = size * nmemb;

        String header (ptr, len);

        if (! header.contains (":") && header.startsWithIgnoreCase ("HTTP/"))
            responseHeaders.clear();
        else
            responseHeaders += header;

        return len;
    }
Beispiel #10
0
//==============================================================================
bool URL::isProbablyAWebsiteURL (const String& possibleURL)
{
    static const char* validProtocols[] = { "http:", "ftp:", "https:" };

    for (auto* protocol : validProtocols)
        if (possibleURL.startsWithIgnoreCase (protocol))
            return true;

    if (possibleURL.containsChar ('@')
        || possibleURL.containsChar (' '))
        return false;

    const String topLevelDomain (possibleURL.upToFirstOccurrenceOf ("/", false, false)
                                 .fromLastOccurrenceOf (".", false, false));

    return topLevelDomain.isNotEmpty() && topLevelDomain.length() <= 3;
}
Beispiel #11
0
    void openConnection (URL_COMPONENTS& uc, HINTERNET sessionHandle,
                         URL::OpenStreamProgressCallback* progressCallback,
                         void* progressCallbackContext)
    {
        int disable = 1;
        InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));

        if (timeOutMs == 0)
            timeOutMs = 30000;
        else if (timeOutMs < 0)
            timeOutMs = -1;

        InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));

        const bool isFtp = address.startsWithIgnoreCase ("ftp:");

      #if WORKAROUND_TIMEOUT_BUG
        connection = 0;

        {
            InternetConnectThread connectThread (uc, sessionHandle, connection, isFtp);
            connectThread.wait (timeOutMs);

            if (connection == 0)
            {
                InternetCloseHandle (sessionHandle);
                sessionHandle = 0;
            }
        }
      #else
        connection = InternetConnect (sessionHandle, uc.lpszHostName, uc.nPort,
                                      uc.lpszUserName, uc.lpszPassword,
                                      isFtp ? (DWORD) INTERNET_SERVICE_FTP
                                            : (DWORD) INTERNET_SERVICE_HTTP,
                                      0, 0);
      #endif

        if (connection != 0)
        {
            if (isFtp)
                request = FtpOpenFile (connection, uc.lpszUrlPath, GENERIC_READ,
                                       FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE, 0);
            else
                openHTTPConnection (uc, progressCallback, progressCallbackContext);
        }
    }
Beispiel #12
0
bool Process::openDocument (const String& fileName, const String& parameters)
{
    String cmdString (fileName.replace (" ", "\\ ",false));
    cmdString << " " << parameters;

    if (/*URL::isProbablyAWebsiteURL (fileName)
          ||*/ cmdString.startsWithIgnoreCase ("file:")
         /*|| URL::isProbablyAnEmailAddress (fileName)*/
         || File::createFileWithoutCheckingPath (fileName).isDirectory()
         || ! isFileExecutable (fileName))
    {
        // create a command that tries to launch a bunch of likely browsers
        static const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla",
                                                    "google-chrome", "chromium-browser", "opera", "konqueror" };
        StringArray cmdLines;

        for (int i = 0; i < numElementsInArray (browserNames); ++i)
            cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());

        cmdString = cmdLines.joinIntoString (" || ");
    }

    const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), nullptr };

#if JUCE_USE_VFORK
    const int cpid = vfork();
#else
    const int cpid = fork();
#endif

    if (cpid == 0)
    {
#if ! JUCE_USE_VFORK
        setsid();
#endif
        // Child process
        if (execvp (argv[0], (char**) argv) < 0)
            _exit (0);
    }

    return cpid >= 0;
}
    //==============================================================================
    static String readResponse (const int socketHandle, const uint32 timeOutTime)
    {
        int bytesRead = 0, numConsecutiveLFs  = 0;
        MemoryBlock buffer (1024, true);

        while (numConsecutiveLFs < 2 && bytesRead < 32768
                && Time::getMillisecondCounter() <= timeOutTime)
        {
            fd_set readbits;
            FD_ZERO (&readbits);
            FD_SET (socketHandle, &readbits);

            struct timeval tv;
            tv.tv_sec = jmax (1, (int) (timeOutTime - Time::getMillisecondCounter()) / 1000);
            tv.tv_usec = 0;

            if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
                return String::empty;  // (timeout)

            buffer.ensureSize (bytesRead + 8, true);
            char* const dest = (char*) buffer.getData() + bytesRead;

            if (recv (socketHandle, dest, 1, 0) == -1)
                return String::empty;

            const char lastByte = *dest;
            ++bytesRead;

            if (lastByte == '\n')
                ++numConsecutiveLFs;
            else if (lastByte != '\r')
                numConsecutiveLFs = 0;
        }

        const String header (CharPointer_UTF8 ((const char*) buffer.getData()));

        if (header.startsWithIgnoreCase ("HTTP/"))
            return header.trimEnd();

        return String::empty;
    }
    static String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
    {
        String result (getMidiObjectName (endpoint));

        MIDIEntityRef entity = 0;  // NB: don't attempt to use nullptr for refs - it fails in some types of build.
        MIDIEndpointGetEntity (endpoint, &entity);

        if (entity == 0)
            return result; // probably virtual

        if (result.isEmpty())
            result = getMidiObjectName (entity);  // endpoint name is empty - try the entity

        // now consider the device's name
        MIDIDeviceRef device = 0;
        MIDIEntityGetDevice (entity, &device);

        if (device != 0)
        {
            const String deviceName (getMidiObjectName (device));

            if (deviceName.isNotEmpty())
            {
                // if an external device has only one entity, throw away
                // the endpoint name and just use the device name
                if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
                {
                    result = deviceName;
                }
                else if (! result.startsWithIgnoreCase (deviceName))
                {
                    // prepend the device name to the entity name
                    result = (deviceName + " " + result).trimEnd();
                }
            }
        }

        return result;
    }
static void writePluginFile(const NativePluginDescriptor* const pluginDesc)
{
    const String pluginLabel(pluginDesc->label);
    const String pluginFile("carla-native.lv2/" + pluginLabel + ".ttl");

    uint32_t portIndex = 0;
    String text;

    gUsedSymbols.clear();

    carla_stdout("Generating data for %s...", pluginDesc->name);

    // -------------------------------------------------------------------
    // Init plugin

    NativeHostDescriptor hostDesc;
    hostDesc.handle      = nullptr;
    hostDesc.resourceDir = "";
    hostDesc.uiName      = "";
    hostDesc.get_buffer_size  = host_getBufferSize;
    hostDesc.get_sample_rate  = host_getSampleRate;
    hostDesc.is_offline       = host_isOffline;
    hostDesc.get_time_info    = nullptr;
    hostDesc.write_midi_event = nullptr;
    hostDesc.ui_parameter_changed    = nullptr;
    hostDesc.ui_midi_program_changed = nullptr;
    hostDesc.ui_custom_data_changed  = nullptr;
    hostDesc.ui_closed               = nullptr;
    hostDesc.ui_open_file = nullptr;
    hostDesc.ui_save_file = nullptr;
    hostDesc.dispatcher   = host_dispatcher;

    NativePluginHandle pluginHandle = nullptr;

    if (! pluginLabel.startsWithIgnoreCase("carla-"))
    {
        pluginHandle = pluginDesc->instantiate(&hostDesc);
        CARLA_SAFE_ASSERT_RETURN(pluginHandle != nullptr,)
    }
    static bool decomposeURL (const String& url, String& host, String& path, int& port)
    {
        if (! url.startsWithIgnoreCase ("http://"))
            return false;

        const int nextSlash = url.indexOfChar (7, '/');
        int nextColon = url.indexOfChar (7, ':');
        if (nextColon > nextSlash && nextSlash > 0)
            nextColon = -1;

        if (nextColon >= 0)
        {
            host = url.substring (7, nextColon);

            if (nextSlash >= 0)
                port = url.substring (nextColon + 1, nextSlash).getIntValue();
            else
                port = url.substring (nextColon + 1).getIntValue();
        }
        else
        {
            port = 0; // indicates the default port

            if (nextSlash >= 0)
                host = url.substring (7, nextSlash);
            else
                host = url.substring (7);
        }

        if (nextSlash >= 0)
            path = url.substring (nextSlash);
        else
            path = "/";

        return true;
    }
Beispiel #17
0
  ParsedInclude parseInclude (String const& line, String const& trimmed)
  {
    ParsedInclude parsed;

    if (trimmed.startsWithChar ('#'))
    {
      const String removed = trimmed.removeCharacters (" \t");

      if (removed.startsWithIgnoreCase ("#include\""))
      {
        parsed.endOfInclude = line.indexOfChar (line.indexOfChar ('\"') + 1, '\"') + 1;
        parsed.filename = line.fromFirstOccurrenceOf ("\"", false, false)
                              .upToLastOccurrenceOf ("\"", false, false);

        parsed.isIncludeLine = true;

        parsed.preventReinclude = m_preventReincludes.contains (parsed.filename);
        parsed.forceReinclude = m_forceReincludes.contains (parsed.filename);
      }
      else if (removed.startsWithIgnoreCase ("#include<"))
      {
        if (m_checkSystemIncludes) {
          parsed.endOfInclude = line.indexOfChar (line.indexOfChar ('<') + 1, '>') + 1;
          parsed.filename = line.fromFirstOccurrenceOf ("<", false, false)
                                .upToLastOccurrenceOf (">", false, false);
          parsed.isIncludeLine = true;

          parsed.preventReinclude = m_preventReincludes.contains (parsed.filename);
          parsed.forceReinclude = m_forceReincludes.contains (parsed.filename);
        }
      }
      else if (removed.startsWithIgnoreCase ("#include"))
      {
        String name;

#if 1 
        if (line.contains ("/*"))
          name = line.fromFirstOccurrenceOf ("#include", false, false)
                     .upToFirstOccurrenceOf ("/*", false, false).trim ();
        else
          name = line.fromFirstOccurrenceOf ("#include", false, false).trim ();

        parsed.endOfInclude = line.upToFirstOccurrenceOf (name, true, false).length ();
#else
        name = line.fromFirstOccurrenceOf ("#include", false, false).trim ();
#endif

        String value = m_macrosDefined [name];

        if (m_verbose)
          std::cout << "name = " << name << "\n";

        if (value.startsWithIgnoreCase ("\""))
        {
          parsed.endOfInclude = line.trimEnd().length () + 1;
          parsed.filename = value.fromFirstOccurrenceOf ("\"", false, false)
                                .upToLastOccurrenceOf ("\"", false, false);

          parsed.isIncludeLine = true;
        }
        else if (value.startsWithIgnoreCase ("<") && m_checkSystemIncludes)
        {
          parsed.endOfInclude = line.trimEnd().length () + 1;
          parsed.filename = value.fromFirstOccurrenceOf ("<", false, false)
                                .upToLastOccurrenceOf (">", false, false);
          parsed.isIncludeLine = true;
        }

        parsed.preventReinclude = parsed.isIncludeLine && m_preventReincludes.contains (name);
        parsed.forceReinclude = parsed.isIncludeLine && m_forceReincludes.contains (name);
      }
    }

    return parsed;
  }
Beispiel #18
0
    //==============================================================================
    const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
    {
        String result;
        CFStringRef str = 0;

        MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);

        if (str != 0)
        {
            result = PlatformUtilities::cfStringToJuceString (str);
            CFRelease (str);
            str = 0;
        }

        MIDIEntityRef entity = 0;
        MIDIEndpointGetEntity (endpoint, &entity);

        if (entity == 0)
            return result; // probably virtual

        if (result.isEmpty())
        {
            // endpoint name has zero length - try the entity
            MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);

            if (str != 0)
            {
                result += PlatformUtilities::cfStringToJuceString (str);
                CFRelease (str);
                str = 0;
            }
        }

        // now consider the device's name
        MIDIDeviceRef device = 0;
        MIDIEntityGetDevice (entity, &device);
        if (device == 0)
            return result;

        MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);

        if (str != 0)
        {
            const String s (PlatformUtilities::cfStringToJuceString (str));
            CFRelease (str);

            // if an external device has only one entity, throw away
            // the endpoint name and just use the device name
            if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
            {
                result = s;
            }
            else if (! result.startsWithIgnoreCase (s))
            {
                // prepend the device name to the entity name
                result = (s + " " + result).trimEnd();
            }
        }

        return result;
    }
    void createConnection (URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext)
    {
        closeSocket();

        uint32 timeOutTime = Time::getMillisecondCounter();

        if (timeOutMs == 0)
            timeOutTime += 60000;
        else if (timeOutMs < 0)
            timeOutTime = 0xffffffff;
        else
            timeOutTime += timeOutMs;

        String hostName, hostPath;
        int hostPort;
        if (! decomposeURL (address, hostName, hostPath, hostPort))
            return;

        String serverName, proxyName, proxyPath;
        int proxyPort = 0;
        int port = 0;

        const String proxyURL (getenv ("http_proxy"));
        if (proxyURL.startsWithIgnoreCase ("http://"))
        {
            if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
                return;

            serverName = proxyName;
            port = proxyPort;
        }
        else
        {
            serverName = hostName;
            port = hostPort;
        }

        struct addrinfo hints = { 0 };
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_NUMERICSERV;

        struct addrinfo* result = nullptr;
        if (getaddrinfo (serverName.toUTF8(), String (port).toUTF8(), &hints, &result) != 0 || result == 0)
            return;

        socketHandle = socket (result->ai_family, result->ai_socktype, 0);

        if (socketHandle == -1)
        {
            freeaddrinfo (result);
            return;
        }

        int receiveBufferSize = 16384;
        setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
        setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);

      #if JUCE_MAC
        setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
      #endif

        if (connect (socketHandle, result->ai_addr, result->ai_addrlen) == -1)
        {
            closeSocket();
            freeaddrinfo (result);
            return;
        }

        freeaddrinfo (result);

        {
            const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort, proxyName, proxyPort,
                                                                  hostPath, address, headers, postData, isPost));

            if (! sendHeader (socketHandle, requestHeader, timeOutTime, progressCallback, progressCallbackContext))
            {
                closeSocket();
                return;
            }
        }

        String responseHeader (readResponse (socketHandle, timeOutTime));

        if (responseHeader.isNotEmpty())
        {
            headerLines.clear();
            headerLines.addLines (responseHeader);

            const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
                                                 .substring (0, 3).getIntValue();

            //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
            //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");

            String location (findHeaderItem (headerLines, "Location:"));

            if (statusCode >= 300 && statusCode < 400 && location.isNotEmpty())
            {
                if (! location.startsWithIgnoreCase ("http://"))
                    location = "http://" + location;

                if (++levelsOfRedirection <= 3)
                {
                    address = location;
                    createConnection (progressCallback, progressCallbackContext);
                    return;
                }
            }
            else
            {
                levelsOfRedirection = 0;
                return;
            }
        }

        closeSocket();
    }
Beispiel #20
0
    WebInputStream (const String& address_, bool isPost_, const MemoryBlock& postData_,
                    URL::OpenStreamProgressCallback* progressCallback, void* progressCallbackContext,
                    const String& headers_, int timeOutMs_, StringPairArray* responseHeaders,
                    int numRedirectsToFollow, const String& httpRequestCmd_)
      : statusCode (0), connection (0), request (0),
        address (address_), headers (headers_), postData (postData_), position (0),
        finished (false), isPost (isPost_), timeOutMs (timeOutMs_), httpRequestCmd (httpRequestCmd_)
    {
        while (numRedirectsToFollow-- >= 0)
        {
            createConnection (progressCallback, progressCallbackContext);

            if (! isError())
            {
                DWORD bufferSizeBytes = 4096;
                StringPairArray dataHeaders (false);

                for (;;)
                {
                    HeapBlock<char> buffer ((size_t) bufferSizeBytes);

                    if (HttpQueryInfo (request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
                    {
                        StringArray headersArray;
                        headersArray.addLines (String (reinterpret_cast<const WCHAR*> (buffer.getData())));

                        for (int i = 0; i < headersArray.size(); ++i)
                        {
                            const String& header = headersArray[i];
                            const String key   (header.upToFirstOccurrenceOf (": ", false, false));
                            const String value (header.fromFirstOccurrenceOf (": ", false, false));
                            const String previousValue (dataHeaders[key]);
                            dataHeaders.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
                        }

                        break;
                    }

                    if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
                        break;

                    bufferSizeBytes += 4096;
                }

                DWORD status = 0;
                DWORD statusSize = sizeof (status);

                if (HttpQueryInfo (request, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &status, &statusSize, 0))
                {
                    statusCode = (int) status;

                    if (numRedirectsToFollow >= 0
                         && (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307))
                    {
                        String newLocation (dataHeaders["Location"]);

                        // Check whether location is a relative URI - this is an incomplete test for relative path,
                        // but we'll use it for now (valid protocols for this implementation are http, https & ftp)
                        if (! (newLocation.startsWithIgnoreCase ("http://")
                                || newLocation.startsWithIgnoreCase ("https://")
                                || newLocation.startsWithIgnoreCase ("ftp://")))
                        {
                            if (newLocation.startsWithChar ('/'))
                                newLocation = URL (address).withNewSubPath (newLocation).toString (true);
                            else
                                newLocation = address + "/" + newLocation;
                        }

                        if (newLocation.isNotEmpty() && newLocation != address)
                        {
                            address = newLocation;
                            continue;
                        }
                    }
                }

                if (responseHeaders != nullptr)
                    responseHeaders->addArray (dataHeaders);
            }

            break;
        }
    }
/**
 * Process the command line arguments and build the parameter list for the desktop action
 *
 * @param alfresco AlfrescoInterface&
 * @param paths StringList&
 * @param actionInfo AlfrescoActionInfo&
 * @param params DesktopParams&
 * @return bool
 */
bool CAlfrescoApp::buildDesktopParameters( AlfrescoInterface& alfresco, StringList& paths, AlfrescoActionInfo& actionInfo,
										    DesktopParams& params) {

	// If there are no paths then just return a success

    if ( paths.numberOfStrings() == 0)
	    return true;

	// Process the list of files and either check in the file if it is a working copy or check out
	// the file

	for ( unsigned int i = 0; i < paths.numberOfStrings(); i++) {

		// Get the current file name

		String curFile = paths.getStringAt( i);

		// DEBUG

		DBGOUT_TS << "Parameter: " << curFile << endl;

		// Check if the path is on an Alfresco mapped drive

		if ( alfresco.isMappedDrive() && curFile.startsWithIgnoreCase( alfresco.getDrivePath())) {

			// Convert the path to a UNC path

			String uncPath = alfresco.getRootPath();
			uncPath.append( curFile.substring(3));

			curFile = uncPath;
		}

		// Check if the path is to a file/folder, and whether it is a local path

		bool copyFile = false;
		DWORD attr = GetFileAttributes( curFile);

		if ( attr != INVALID_FILE_ATTRIBUTES) {
			
			// Check if the action supports the file/folder type

			bool isDir = (attr & FILE_ATTRIBUTE_DIRECTORY) != 0 ? true : false;

			if ( isDir && actionInfo.supportsFolders() == false) {
				AfxMessageBox(L"Action does not support folders", MB_OK | MB_ICONSTOP);
				DBGOUT_TS << "Error, action does not support folders" << endl;
				return false;
			}
			else if ( actionInfo.supportsFiles() == false) {
				AfxMessageBox(L"Action does not support files", MB_OK | MB_ICONSTOP);
				DBGOUT_TS << "Error, action does not support files" << endl;
				return false;
			}

			// Get the file name from the path

			StringList nameParts = FileName::splitPath( curFile);
			String curName = nameParts.getStringAt( 1);

			// If the path is to a file that is not on the Alfresco share the file will need to be copied,
			// after checking the status of a matching file in the Alfresco folder

			if ( curFile.length() >= 3 && curFile.substring(1,3).equals( L":\\") &&
				(alfresco.isMappedDrive() == false || curFile.startsWithIgnoreCase( alfresco.getDrivePath()) == false)) {

				// Check if the action supports local files

				if ( isDir == false && actionInfo.hasAttribute(AttrClientFiles) == false) {
					AfxMessageBox(L"Action does not support local files", MB_OK | MB_ICONSTOP);
					DBGOUT_TS << "Error, action does not support local files" << endl;
					return false;
				}
				else if ( isDir == true && actionInfo.hasAttribute(AttrClientFolders) == false) {
					AfxMessageBox(L"Action does not support local folders", MB_OK | MB_ICONSTOP);
					DBGOUT_TS << "Error, action does not support local folders" << endl;
					return false;
				}

				// Check if there is an existing file in the Alfresco with the same name, check if the file is locked
				
				PTR_AlfrescoFileInfo fInfo = alfresco.getFileInformation( curName);
				if ( fInfo.get() != NULL) {

					// There is an existing file in the Alfresco folder with the same name, check if it is locked

					if ( fInfo->getLockType() != LockNone) {
						AfxMessageBox( L"Cannot copy file to Alfresco folder, destination file is locked", MB_OK | MB_ICONEXCLAMATION);
						DBGOUT_TS << "Error, cannot copy to Alfresco folder, destination file is locked" << endl;
						return false;
					}
					else if ( actionInfo.hasPreProcessAction(PreLocalToWorkingCopy) == true && fInfo->isWorkingCopy() == false) {
						AfxMessageBox( L"Cannot copy to Alfresco folder, destination must overwrite a working copy", MB_OK | MB_ICONEXCLAMATION);
						DBGOUT_TS << "Error, cannot copy to Alfresco folder, destination must overwrite a working copy" << endl;
						return false;
					}
				}
				else if ( actionInfo.hasPreProcessAction(PreLocalToWorkingCopy) == true) {

					// Target folder does not contain a matching working copy of the local file

					CString msg;
					msg.FormatMessage( L"No matching working copy for %1", curName.data());
					AfxMessageBox( msg, MB_OK | MB_ICONEXCLAMATION);
					DBGOUT_TS << "Error, no matching working copy for " << curName << endl;
					return false;
				}

				// Copy the files/folders using the Windows shell

				bool copyAborted = false;

				if ( copyFilesUsingShell( curFile, alfresco.getUNCPath(), copyAborted) == false) {

					// Check if the copy failed or the user aborted the copy

					if ( copyAborted == false) {

						// File copy failed

						CString msg;
						msg.FormatMessage( isDir ? L"Failed to copy folder %1" : L"Failed to copy file %1", curFile.data());

						AfxMessageBox( msg, MB_OK | MB_ICONSTOP);
						DBGOUT_TS << "Error, copy failed for " << curName << endl;
						return false;
					}
					else {

						// User aborted the file copy

						CString msg;
						msg.FormatMessage( L"Copy aborted for %1", curFile.data());
						AfxMessageBox( msg, MB_OK | MB_ICONSTOP);
						DBGOUT_TS << "Error, copy aborted by user, " << curName << endl;
						return false;
					}
				}

				// DEBUG

				DBGOUT_TS << "Added target " << curName << endl;

				// Add a desktop target for the copied file

				params.addTarget( new DesktopTarget(isDir ? TargetCopiedFolder : TargetCopiedFile, curName));
			}
			else {

				//	Path is a UNC path, check if the file/folder is in the same folder as the action

				DesktopTarget* pTarget = NULL;

				if ( curFile.startsWith( alfresco.getUNCPath())) {

					// Path is in the same folder as the application, or in a sub-folder

					String relPath = curFile.substring( alfresco.getUNCPath().length() + 1);

					if ( relPath.indexOf( L"\\") == -1) {

						// Create a target using the file name only

						pTarget = new DesktopTarget( isDir ? TargetFolder : TargetFile, relPath);
					}
				}

				// If the target is not valid the file/folder is not in the same folder as the client-side application,
				// copy the files/folders to the target folder or use the root relative path to the file/folder

				if ( pTarget == NULL) {

					// Check if Alfresco files/folders should be copied to the target folder

					if ( actionInfo.hasPreProcessAction(PreCopyToTarget)) {

						// Copy the files/folders using the Windows shell

						bool copyAborted = false;

						if ( copyFilesUsingShell( curFile, alfresco.getUNCPath(), copyAborted) == false) {

							// Check if the copy failed or the user aborted the copy

							if ( copyAborted == false) {

								// File copy failed

								CString msg;
								msg.FormatMessage( isDir ? L"Failed to copy folder %1" : L"Failed to copy file %1", curFile.data());

								AfxMessageBox( msg, MB_OK | MB_ICONSTOP);
								DBGOUT_TS << "Error, copy failed for " << curName << endl;
								return false;
							}
							else {

								// User aborted the file copy

								CString msg;
								msg.FormatMessage( L"Copy aborted for %1", curFile.data());
								AfxMessageBox( msg, MB_OK | MB_ICONSTOP);
								DBGOUT_TS << "Error, copy aborted for " << curName << endl;
								return false;
							}
						}

						// Add a desktop target for the copied file

						pTarget= new DesktopTarget(isDir ? TargetCopiedFolder : TargetCopiedFile, curName);
					}
					else {

						// Get the root relative path to the file/folder

						String rootRelPath = curFile.substring(alfresco.getRootPath().length());
						pTarget = new DesktopTarget( isDir ? TargetFolder : TargetFile, rootRelPath);
					}
				}

				// DEBUG

				DBGOUT_TS << "Added target " << pTarget->getTarget() << endl;

				// Add the desktop target

				params.addTarget( pTarget);
			}
		}
	}

	// Return status

	return true;
}