void InsertTextCommand::input(const String& text, bool selectInsertedText, RebalanceType whitespaceRebalance)
{
    
    ASSERT(text.find('\n') == notFound);

    if (!endingSelection().isNonOrphanedCaretOrRange())
        return;

    // Delete the current selection.
    // FIXME: This delete operation blows away the typing style.
    if (endingSelection().isRange()) {
        if (performTrivialReplace(text, selectInsertedText))
            return;
        deleteSelection(false, true, true, false);
    }

    Position startPosition(endingSelection().start());
    
    Position placeholder;
    // We want to remove preserved newlines and brs that will collapse (and thus become unnecessary) when content 
    // is inserted just before them.
    // FIXME: We shouldn't really have to do this, but removing placeholders is a workaround for 9661.
    // If the caret is just before a placeholder, downstream will normalize the caret to it.
    Position downstream(startPosition.downstream());
    if (lineBreakExistsAtPosition(downstream)) {
        // FIXME: This doesn't handle placeholders at the end of anonymous blocks.
        VisiblePosition caret(startPosition);
        if (isEndOfBlock(caret) && isStartOfParagraph(caret))
            placeholder = downstream;
        // Don't remove the placeholder yet, otherwise the block we're inserting into would collapse before
        // we get a chance to insert into it.  We check for a placeholder now, though, because doing so requires
        // the creation of a VisiblePosition, and if we did that post-insertion it would force a layout.
    }
    
    // Insert the character at the leftmost candidate.
    startPosition = startPosition.upstream();
    
    // It is possible for the node that contains startPosition to contain only unrendered whitespace,
    // and so deleteInsignificantText could remove it.  Save the position before the node in case that happens.
    Position positionBeforeStartNode(positionInParentBeforeNode(startPosition.containerNode()));
    deleteInsignificantText(startPosition.upstream(), startPosition.downstream());
    if (!startPosition.anchorNode()->inDocument())
        startPosition = positionBeforeStartNode;
    if (!startPosition.isCandidate())
        startPosition = startPosition.downstream();
    
    startPosition = positionAvoidingSpecialElementBoundary(startPosition);
    
    Position endPosition;
    
    if (text == "\t") {
        endPosition = insertTab(startPosition);
        startPosition = endPosition.previous();
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
    } else {
        // Make sure the document is set up to receive text
        startPosition = positionInsideTextNode(startPosition);
        ASSERT(startPosition.anchorType() == Position::PositionIsOffsetInAnchor);
        ASSERT(startPosition.containerNode());
        ASSERT(startPosition.containerNode()->isTextNode());
        if (placeholder.isNotNull())
            removePlaceholderAt(placeholder);
        RefPtr<Text> textNode = static_cast<Text*>(startPosition.containerNode());
        const unsigned offset = startPosition.offsetInContainerNode();

        insertTextIntoNode(textNode, offset, text);
        endPosition = Position(textNode, offset + text.length());

        if (whitespaceRebalance == RebalanceLeadingAndTrailingWhitespaces) {
            // The insertion may require adjusting adjacent whitespace, if it is present.
            rebalanceWhitespaceAt(endPosition);
            // Rebalancing on both sides isn't necessary if we've inserted only spaces.
            if (!shouldRebalanceLeadingWhitespaceFor(text))
                rebalanceWhitespaceAt(startPosition);
        } else {
            ASSERT(whitespaceRebalance == RebalanceAllWhitespaces);
            if (canRebalance(startPosition) && canRebalance(endPosition))
                rebalanceWhitespaceOnTextSubstring(textNode, startPosition.offsetInContainerNode(), endPosition.offsetInContainerNode());
        }
    }

    // We could have inserted a part of composed character sequence,
    // so we are basically treating ending selection as a range to avoid validation.
    // <http://bugs.webkit.org/show_bug.cgi?id=15781>
    VisibleSelection forcedEndingSelection;
    forcedEndingSelection.setWithoutValidation(startPosition, endPosition);
    setEndingSelection(forcedEndingSelection);

    // Handle the case where there is a typing style.
    if (RefPtr<EditingStyle> typingStyle = document()->frame()->selection()->typingStyle()) {
        typingStyle->prepareToApplyAt(endPosition, EditingStyle::PreserveWritingDirection);
        if (!typingStyle->isEmpty())
            applyStyle(typingStyle.get());
    }

    if (!selectInsertedText)
        setEndingSelection(VisibleSelection(endingSelection().end(), endingSelection().affinity()));
}
Example #2
0
bool ResourceHandle::start(Frame* frame)
{
    ref();
    if (url().isLocalFile()) {
        String path = url().path();
        // windows does not enjoy a leading slash on paths
        if (path[0] == '/')
            path = path.substring(1);
        // FIXME: This is wrong. Need to use wide version of this call.
        d->m_fileHandle = CreateFileA(path.utf8().data(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

        // FIXME: perhaps this error should be reported asynchronously for
        // consistency.
        if (d->m_fileHandle == INVALID_HANDLE_VALUE) {
            delete this;
            return false;
        }

        d->m_fileLoadTimer.startOneShot(0.0);
        return true;
    } else {
        static HINTERNET internetHandle = 0;
        if (!internetHandle) {
            String userAgentStr = frame->loader()->userAgent() + String("", 1);
            LPCWSTR userAgent = reinterpret_cast<const WCHAR*>(userAgentStr.characters());
            // leak the Internet for now
            internetHandle = InternetOpen(userAgent, INTERNET_OPEN_TYPE_PRECONFIG, 0, 0, INTERNET_FLAG_ASYNC);
        }
        if (!internetHandle) {
            delete this;
            return false;
        }
        static INTERNET_STATUS_CALLBACK callbackHandle = 
            InternetSetStatusCallback(internetHandle, transferJobStatusCallback);

        initializeOffScreenResourceHandleWindow();
        d->m_jobId = addToOutstandingJobs(this);

        DWORD flags =
            INTERNET_FLAG_KEEP_CONNECTION |
            INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
            INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP;

        // For form posting, we can't use InternetOpenURL.  We have to use
        // InternetConnect followed by HttpSendRequest.
        HINTERNET urlHandle;
        String referrer = frame->loader()->referrer();
        if (method() == "POST") {
            d->m_postReferrer = referrer;
            String host = url().host();
            urlHandle = InternetConnectA(internetHandle, host.latin1().data(),
                                         url().port(),
                                         NULL, // no username
                                         NULL, // no password
                                         INTERNET_SERVICE_HTTP,
                                         flags, (DWORD_PTR)d->m_jobId);
        } else {
            String urlStr = url().string();
            int fragmentIndex = urlStr.find('#');
            if (fragmentIndex != -1)
                urlStr = urlStr.left(fragmentIndex);
            String headers;
            if (!referrer.isEmpty())
                headers += String("Referer: ") + referrer + "\r\n";

            urlHandle = InternetOpenUrlA(internetHandle, urlStr.latin1().data(),
                                         headers.latin1().data(), headers.length(),
                                         flags, (DWORD_PTR)d->m_jobId);
        }

        if (urlHandle == INVALID_HANDLE_VALUE) {
            delete this;
            return false;
        }
        d->m_threadId = GetCurrentThreadId();

        return true;
    }
}
    bool InstrumentEditorFactory::LoadPlugins(String plugindir) {
        #if defined(WIN32)
        WIN32_FIND_DATA win32FindData;
        const String pluginpattern = plugindir + "\\*.dll";
        HANDLE hDir = FindFirstFile(pluginpattern.c_str(), &win32FindData);
        if (hDir == INVALID_HANDLE_VALUE) {
            if (GetLastError() != ERROR_FILE_NOT_FOUND) {
                return false;
            } else {
                dmsg(1,("None"));
                return true;
            }
        }

        do {
            // skip directory entries
            if (win32FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                continue;
            // dir entry name as full qualified path
            const String sPath = plugindir + "\\" + win32FindData.cFileName;
            // load the DLL
            HINSTANCE hinstLib;
            void* pDLL = hinstLib = LoadLibrary(sPath.c_str());
            if (!pDLL) {
                std::cerr << "Failed to load instrument editor plugin: "
                          << sPath << std::endl;
                continue;
            }

            InnerFactory* (*fn)() = (InnerFactory* (*)())
                GetProcAddress(hinstLib, "createInstrumentEditorInnerFactory");
            if (fn == NULL) {
                std::cerr << "ERROR: unable to find "
                             "createInstrumentEditorInnerFactory() "
                             "in DLL\n" << std::flush;
                FreeLibrary(hinstLib);
                continue;
            }

            // get the plugin instance and register it to the factory

            InnerFactory* pInnerFactory = fn();
            if (!pInnerFactory) {
                std::cerr << "ERROR: !pInnerFactory\n" << std::flush;
                FreeLibrary(hinstLib);
                continue;
            }
            InstrumentEditor* pEditor = pInnerFactory->Create();
            if (InnerFactories.count(pEditor->Name())) {
                std::cerr << "ERROR: a plugin with name '"
                          << pEditor->Name()
                          << "' already loaded (skipping)\n"
                          << std::flush;
                pInnerFactory->Destroy(pEditor);
                FreeLibrary(hinstLib);
                continue;
            }
            InnerFactories[pEditor->Name()] = pInnerFactory;
            pInnerFactory->Destroy(pEditor);

            LoadedDLLs.push_back(pDLL);
        } while (FindNextFile(hDir, &win32FindData));

        if (hDir != INVALID_HANDLE_VALUE) FindClose(hDir);

        #else // POSIX

        #if defined(__APPLE__)  /*  20071224 Toshi Nagata  */
        if (plugindir.find("~") == 0)
            plugindir.replace(0, 1, getenv("HOME"));
        #endif
        DIR* hDir = opendir(plugindir.c_str());
        if (!hDir) {
            return false;
        }
        for (dirent* pEntry = readdir(hDir); pEntry; pEntry = readdir(hDir)) {
            // dir entry name as full qualified path
            const String sPath = plugindir + "/" + pEntry->d_name;
            // skip entries that are not regular files
            struct stat entry_stat;
            if (lstat(sPath.c_str(), &entry_stat) != 0 ||
                (entry_stat.st_mode & S_IFMT) != S_IFREG)
                continue;
            // skip files that are not .so files
            if (sPath.length() < 3 ||
                (sPath.substr(sPath.length() - 3) != ".so" &&
                 sPath.find(".so.") == String::npos) )
                continue;
            // load the DLL (the plugins should register themselfes automatically)
            void* pDLL = dlopen(sPath.c_str(), RTLD_NOW);
            if (pDLL) LoadedDLLs.push_back(pDLL);
            else {
                std::cerr << "Failed to load instrument editor plugin: '"
                          << sPath << "', cause: " << dlerror() << std::endl;
            }
        }
        closedir(hDir);
        #endif
        return true;
    }
Example #4
0
void CIMClientRep::_connect()
{
    //
    // Test for Display optons of the form
    // Use Env variable PEGASUS_CLIENT_TRACE= <intrace> : <outtrace
    // intrace = "con" | "log" | "both"
    // outtrace = intrace
    // ex set PEGASUS_CLIENT_TRACE=BOTH:BOTH traces input and output
    // to console and log
    // Keywords are case insensitive.
    // PEP 90
    //
    Uint32 showOutput = 0;
    Uint32 showInput = 0;
#ifdef PEGASUS_CLIENT_TRACE_ENABLE
    String input;
    if (char * envVar = getenv("PEGASUS_CLIENT_TRACE"))
    {
        input = envVar;
        input.toLower();
        String io = String::EMPTY;
        Uint32 pos = input.find(':');
        if (pos == PEG_NOT_FOUND)
            pos = 0;
        else
            io = input.subString(0,pos);

        // some compilers do not allow temporaries to be passed to a
        // reference argument - so break into 2 lines
        String out = input.subString(pos + 1);
        showOutput = _getShowType(out);

        showInput = _getShowType(io);
    }
#endif

    //
    // Create response decoder:
    //
    AutoPtr<CIMOperationResponseDecoder> responseDecoder(new
            CIMOperationResponseDecoder(this, _requestEncoder.get(), &_authenticator
                                        , showInput));

    //
    // Attempt to establish a connection:
    //
    AutoPtr<HTTPConnection> httpConnection(_httpConnector->connect(
            _connectHost,
            _connectPortNumber,
            _connectSSLContext.get(),
            responseDecoder.get()));

    //
    // Create request encoder:
    //
    String connectHost = _connectHost;
    if (connectHost.size())
    {
        char portStr[32];
        sprintf(portStr, ":%u", _connectPortNumber);
        connectHost.append(portStr);
    }

    AutoPtr<CIMOperationRequestEncoder> requestEncoder(new CIMOperationRequestEncoder(
                httpConnection.get(), connectHost, &_authenticator, showOutput));

    _responseDecoder.reset(responseDecoder.release());
    _httpConnection = httpConnection.release();
    _requestEncoder.reset(requestEncoder.release());
    _responseDecoder->setEncoderQueue(_requestEncoder.get());
    _connected = true;
}
PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String& text)
{
    if (!context)
        return 0;

    Node* styleNode = context->firstNode();
    if (!styleNode) {
        styleNode = context->startPosition().deprecatedNode();
        if (!styleNode)
            return 0;
    }

    Document* document = styleNode->document();
    RefPtr<DocumentFragment> fragment = document->createDocumentFragment();
    
    if (text.isEmpty())
        return fragment.release();

    String string = text;
    string.replace("\r\n", "\n");
    string.replace('\r', '\n');

    RenderObject* renderer = styleNode->renderer();
    if (renderer && renderer->style()->preserveNewline()) {
        fragment->appendChild(document->createTextNode(string), ASSERT_NO_EXCEPTION);
        if (string.endsWith('\n')) {
            RefPtr<Element> element = createBreakElement(document);
            element->setAttribute(classAttr, AppleInterchangeNewline);            
            fragment->appendChild(element.release(), ASSERT_NO_EXCEPTION);
        }
        return fragment.release();
    }

    // A string with no newlines gets added inline, rather than being put into a paragraph.
    if (string.find('\n') == notFound) {
        fillContainerFromString(fragment.get(), string);
        return fragment.release();
    }

    // Break string into paragraphs. Extra line breaks turn into empty paragraphs.
    Node* blockNode = enclosingBlock(context->firstNode());
    Element* block = toElement(blockNode);
    bool useClonesOfEnclosingBlock = blockNode
        && blockNode->isElementNode()
        && !block->hasTagName(bodyTag)
        && !block->hasTagName(htmlTag)
        && block != editableRootForPosition(context->startPosition());
    bool useLineBreak = enclosingTextFormControl(context->startPosition());

    Vector<String> list;
    string.split('\n', true, list); // true gets us empty strings in the list
    size_t numLines = list.size();
    for (size_t i = 0; i < numLines; ++i) {
        const String& s = list[i];

        RefPtr<Element> element;
        if (s.isEmpty() && i + 1 == numLines) {
            // For last line, use the "magic BR" rather than a P.
            element = createBreakElement(document);
            element->setAttribute(classAttr, AppleInterchangeNewline);
        } else if (useLineBreak) {
            element = createBreakElement(document);
            fillContainerFromString(fragment.get(), s);
        } else {
            if (useClonesOfEnclosingBlock)
                element = block->cloneElementWithoutChildren();
            else
                element = createDefaultParagraphElement(document);
            fillContainerFromString(element.get(), s);
        }
        fragment->appendChild(element.release(), ASSERT_NO_EXCEPTION);
    }
    return fragment.release();
}
//-----------------------------------------------------------------------------
void GLSLProgramProcessor::bindSubShaders(Program* program, GpuProgramPtr pGpuProgram)
{
	if (program->getDependencyCount() > 0)
	{
		// Get all attached shaders so we do not attach shaders twice.
		// maybe GLSLProgram should take care of that ( prevent add duplicate shaders )
		String attachedShaders = pGpuProgram->getParameter("attach");
		String subShaderDef = "";

		for (unsigned int i=0; i < program->getDependencyCount(); ++i)
		{
			// Here we append _VS and _FS to the library shaders (so max each lib shader
			// is compiled twice once as vertex and once as fragment shader)
			String subShaderName = program->getDependency(i);
			if (program->getType() == GPT_VERTEX_PROGRAM)
			{
				subShaderName += "_VS";
			}
			else
			{
				subShaderName += "_FS";
			}					

			// Check if the library shader already compiled
			if(!HighLevelGpuProgramManager::getSingleton().resourceExists(subShaderName))
			{
				// Create the library shader
				HighLevelGpuProgramPtr pSubGpuProgram = HighLevelGpuProgramManager::getSingleton().createProgram(subShaderName,
					ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, TargetLanguage, program->getType());

				// Set the source name
				String sourceName = program->getDependency(i) + "." + TargetLanguage;
				pSubGpuProgram->setSourceFile(sourceName);

				// If we have compile errors than stop processing
				if (pSubGpuProgram->hasCompileError())
				{
					OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, 
						"Could not compile shader library from the source file: " + sourceName, 
						"GLSLProgramProcessor::bindSubShaders" );	
				}

				mLibraryPrograms.push_back(subShaderName);
			}

			// Check if the lib shader already attached to this shader
			if (attachedShaders.find(subShaderName) == String::npos)
			{
				// Append the shader name to subShaders
				subShaderDef += subShaderName + " ";
			}
		}

		// Check if we have something to attach
		if (subShaderDef.length() > 0)
		{
			pGpuProgram->setParameter("attach", subShaderDef);
		}
	}
	
}
Example #7
0
PassRefPtr<ParsedCookie> CookieManager::parseOneCookie(const URL& url, const String& cookie)
{
    unsigned start = 0;
    unsigned end = cookie.length();

    double curTime = currentTime();
    RefPtr<ParsedCookie> res = ParsedCookie::create(curTime);

    res->setProtocol(url.protocol());

    unsigned tokenEnd = start; // Token end contains the position of the '=' or the end of a token
    unsigned pairEnd = start; // Pair end contains always the position of the ';'

    // Find the first ';' which is not double-quoted and the '=' (if they exist).
    bool foundEqual = false;
    while (pairEnd < end && cookie[pairEnd] != ';') {
        if (cookie[pairEnd] == '=') {
            if (tokenEnd == start) {
                tokenEnd = pairEnd;
                foundEqual = true;
            }
        } else if (cookie[pairEnd] == '"') {
            size_t secondQuotePosition = cookie.find('"', pairEnd + 1);
            if (secondQuotePosition != notFound && secondQuotePosition <= end) {
                pairEnd = secondQuotePosition + 1;
                continue;
            }
        }
        pairEnd++;
    }

    unsigned tokenStart = start;

    bool hasName = false; // This is a hack to avoid changing too much in this brutally brittle code.
    if (tokenEnd != start) {
        // There is a '=' so parse the NAME
        unsigned nameEnd = tokenEnd;

        // The tokenEnd is the position of the '=' so the nameEnd is one less
        nameEnd--;

        // Remove lightweight spaces.
        while (nameEnd && isLightweightSpace(cookie[nameEnd]))
            nameEnd--;

        while (tokenStart < nameEnd && isLightweightSpace(cookie[tokenStart]))
            tokenStart++;

        if (nameEnd + 1 <= tokenStart)
            LOG_ERROR_AND_RETURN("Empty name. Rejecting the cookie");

        String name = cookie.substring(tokenStart, nameEnd + 1 - start);
        res->setName(name);
        hasName = true;
    }

    // Now parse the VALUE
    tokenStart = tokenEnd + 1;
    if (!hasName)
        --tokenStart;

    // Skip lightweight spaces in our token
    while (tokenStart < pairEnd && isLightweightSpace(cookie[tokenStart]))
        tokenStart++;

    tokenEnd = pairEnd;
    while (tokenEnd > tokenStart && isLightweightSpace(cookie[tokenEnd - 1]))
        tokenEnd--;

    String value;
    if (tokenEnd == tokenStart) {
        // Firefox accepts empty value so we will do the same
        value = String();
    } else
        value = cookie.substring(tokenStart, tokenEnd - tokenStart);

    if (hasName)
        res->setValue(value);
    else if (foundEqual)
        return ParsedCookie::create(curTime);
    else
        res->setName(value); // No NAME=VALUE, only NAME

    while (pairEnd < end) {
        // Switch to the next pair as pairEnd is on the ';' and fast-forward any lightweight spaces.
        pairEnd++;
        while (pairEnd < end && isLightweightSpace(cookie[pairEnd]))
            pairEnd++;

        tokenStart = pairEnd;
        tokenEnd = tokenStart; // initialize token end to catch first '='

        while (pairEnd < end && cookie[pairEnd] != ';') {
            if (tokenEnd == tokenStart && cookie[pairEnd] == '=')
                tokenEnd = pairEnd;
            pairEnd++;
        }

        // FIXME : should we skip lightweight spaces here ?

        unsigned length = tokenEnd - tokenStart;
        unsigned tokenStartSvg = tokenStart;

        String parsedValue;
        if (tokenStart != tokenEnd) {
            // There is an equal sign so remove lightweight spaces in VALUE
            tokenStart = tokenEnd + 1;
            while (tokenStart < pairEnd && isLightweightSpace(cookie[tokenStart]))
                tokenStart++;

            tokenEnd = pairEnd;
            while (tokenEnd > tokenStart && isLightweightSpace(cookie[tokenEnd - 1]))
                tokenEnd--;

            parsedValue = cookie.substring(tokenStart, tokenEnd - tokenStart);
        } else {
            // If the parsedValue is empty, initialise it in case we need it
            parsedValue = String();
            // Handle a token without value.
            length = pairEnd - tokenStart;
        }

        // Detect which "cookie-av" is parsed
        // Look at the first char then parse the whole for performance issue
        switch (cookie[tokenStartSvg]) {
        case 'P':
        case 'p' : {
            if (length >= 4 && ((cookie.find("ath", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                // We need the path to be decoded to match those returned from URL::path().
                // The path attribute may or may not include percent-encoded characters. Fortunately
                // if there are no percent-encoded characters, decoding the url is a no-op.
                res->setPath(curl_unescape(parsedValue.utf8().data(), parsedValue.length()));

                // We have to disable the following check because sites like Facebook and
                // Gmail currently do not follow the spec.

                // Check if path attribute is a prefix of the request URI.
                if (!url.path().startsWith(res->path()))
                    LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (path): it does not math the URL", cookie.ascii().data());
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (path)", cookie.ascii().data());
            break;
        }

        case 'D':
        case 'd' : {
            if (length >= 6 && ((cookie.find("omain", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                if (parsedValue.length() > 1 && parsedValue[0] == '"' && parsedValue[parsedValue.length() - 1] == '"')
                    parsedValue = parsedValue.substring(1, parsedValue.length() - 2);

                String host = url.host();

                // Check if the domain contains an embedded dot.
                size_t dotPosition = parsedValue.find(".", 1);
                if (dotPosition == notFound || dotPosition == parsedValue.length())
                    LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain): it does not contain an embedded dot", cookie.ascii().data());

                if (isValidIPAddress(host)) {
                    if (parsedValue != host)
                        LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain)", cookie.ascii().data());

                } else {
                    // If the domain does not start with a dot, add one for security checks and to distinguish it from host-only domains
                    // For example: ab.c.com dose not domain match b.c.com;
                    if (parsedValue[0] != '.')
                        parsedValue = "." + parsedValue;

                    host = "." + host;

                    if (!host.endsWith(parsedValue, false))
                        LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain): it does not domain match the host (%s)", cookie.ascii().data(), host.ascii().data());
                }

                res->setDomain(parsedValue);
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (domain)", cookie.ascii().data());
            break;
        }

        case 'E' :
        case 'e' : {
            if (length >= 7 && ((cookie.find("xpires", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setExpiry(parsedValue);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (expires)", cookie.ascii().data());
            break;
        }

        case 'M' :
        case 'm' : {
            if (length >= 7 && ((cookie.find("ax-age", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setMaxAge(parsedValue);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (max-age)", cookie.ascii().data());
            break;
        }

        case 'C' :
        case 'c' : {
            if (length >= 7 && ((cookie.find("omment", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                // We do not have room for the comment part (and so do Mozilla) so just log the comment.
                LOG(Network, "Comment %s for ParsedCookie : %s\n", parsedValue.ascii().data(), cookie.ascii().data());
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (comment)", cookie.ascii().data());
            break;
        }

        case 'V' :
        case 'v' : {
            if (length >= 7 && ((cookie.find("ersion", tokenStartSvg + 1, false) - tokenStartSvg) == 1)) {
                // Although the out-of-dated Cookie Spec(RFC2965, http://tools.ietf.org/html/rfc2965) defined
                // the value of version can only contain DIGIT, some random sites, e.g. https://devforums.apple.com
                // would use double quotation marks to quote the digit. So we need to get rid of them for compliance.
                if (parsedValue.length() > 1 && parsedValue[0] == '"' && parsedValue[parsedValue.length() - 1] == '"')
                    parsedValue = parsedValue.substring(1, parsedValue.length() - 2);

                if (parsedValue.toInt() != 1)
                    LOG_ERROR_AND_RETURN("ParsedCookie version %d not supported (only support version=1)", parsedValue.toInt());
            } else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (version)", cookie.ascii().data());
            break;
        }

        case 'S' :
        case 's' : {
            // Secure is a standalone token ("Secure;")
            if (length >= 6 && ((cookie.find("ecure", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setSecureFlag(true);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (secure)", cookie.ascii().data());
            break;
        }
        case 'H':
        case 'h': {
            // HttpOnly is a standalone token ("HttpOnly;")
            if (length >= 8 && ((cookie.find("ttpOnly", tokenStartSvg + 1, false) - tokenStartSvg) == 1))
                res->setIsHttpOnly(true);
            else
                LOG_ERROR_AND_RETURN("Invalid cookie attribute %s (HttpOnly)", cookie.ascii().data());
            break;
        }

        default : {
            // If length == 0, we should be at the end of the cookie (case : ";\r") so ignore it
            if (length)
                LOG_ERROR_AND_RETURN("Invalid token for cookie %s", cookie.ascii().data());
            break;
        }
        }
    }

    // Check if the cookie is valid with respect to the size limit.
    if (res->isOverSizeLimit())
        LOG_ERROR_AND_RETURN("ParsedCookie %s is above the 4kb in length : REJECTED", cookie.ascii().data());

    // If no domain was provided, set it to the host
    if (!res->domain())
        res->setDomain(url.host());

    // According to the Cookie Specificaiton (RFC6265, section 4.1.2.4 and 5.2.4, http://tools.ietf.org/html/rfc6265),
    // If no path was provided or the first character of the path value is not '/', set it to the host's path
    //
    // REFERENCE
    // 4.1.2.4. The Path Attribute
    //
    // The scope of each cookie is limited to a set of paths, controlled by
    // the Path attribute. If the server omits the Path attribute, the user
    // agent will use the "directory" of the request-uri's path component as
    // the default value. (See Section 5.1.4 for more details.)
    // ...........
    // 5.2.4. The Path Attribute
    //
    // If the attribute-name case-insensitively matches the string "Path",
    // the user agent MUST process the cookie-av as follows.
    //
    // If the attribute-value is empty or if the first character of the
    // attribute-value is not %x2F ("/"):
    //
    // Let cookie-path be the default-path.
    //
    // Otherwise:
    //
    // Let cookie-path be the attribute-value.
    //
    // Append an attribute to the cookie-attribute-list with an attribute-
    // name of Path and an attribute-value of cookie-path.
    if (!res->path() || !res->path().length() || !res->path().startsWith("/", false)) {
        String path = url.string().substring(url.pathStart(), url.pathAfterLastSlash() - url.pathStart() - 1);
        if (path.isEmpty())
            path = "/";
        // Since this is reading the raw url string, it could contain percent-encoded sequences. We
        // want it to be comparable to the return value of url.path(), which is not percent-encoded,
        // so we must remove the escape sequences.
        res->setPath(curl_unescape(path.utf8().data(), path.length()));
    }

    return res;
}
    //---------------------------------------------------------------------
    void GLSLProgramManagerCommon::extractConstantDefs(const String& src,
        GpuNamedConstants& defs, const String& filename)
    {
        // Parse the output string and collect all uniforms
        // NOTE this relies on the source already having been preprocessed
        // which is done in GLSLProgram::loadFromSource
        String line;
        String::size_type currPos = src.find("uniform");
        while (currPos != String::npos)
        {
            // Now check for using the word 'uniform' in a larger string & ignore
            bool inLargerString = false;
            if (currPos != 0)
            {
                char prev = src.at(currPos - 1);
                if (prev != ' ' && prev != '\t' && prev != '\r' && prev != '\n'
                    && prev != ';')
                    inLargerString = true;
            }
            if (!inLargerString && currPos + 7 < src.size())
            {
                char next = src.at(currPos + 7);
                if (next != ' ' && next != '\t' && next != '\r' && next != '\n')
                    inLargerString = true;
            }

            // skip 'uniform'
            currPos += 7;

            if (!inLargerString)
            {
                String::size_type endPos;
                GpuSharedParametersPtr blockSharedParams;

                // Check for a type. If there is one, then the semicolon is missing
                // otherwise treat as if it is a uniform block
                String::size_type lineEndPos = src.find_first_of("\n\r", currPos);
                line = src.substr(currPos, lineEndPos - currPos);
                StringVector parts = StringUtil::split(line, " \t");
                StringToEnumMap::iterator typei = mTypeEnumMap.find(parts.front());
                if (typei == mTypeEnumMap.end())
                {
                    // Gobble up the external name
                    String externalName = parts.front();

                    // Now there should be an opening brace
                    String::size_type openBracePos = src.find("{", currPos);
                    if (openBracePos != String::npos)
                    {
                        currPos = openBracePos + 1;
                    }
                    else
                    {
                        LogManager::getSingleton().logMessage("Missing opening brace in GLSL Uniform Block in file "
                                                              + filename);
                        break;
                    }

                    // First we need to find the internal name for the uniform block
                    String::size_type endBracePos = src.find("}", currPos);

                    // Find terminating semicolon
                    currPos = endBracePos + 1;
                    endPos = src.find(";", currPos);
                    if (endPos == String::npos)
                    {
                        // problem, missing semicolon, abort
                        break;
                    }

                    // TODO: We don't need the internal name. Just skip over to the end of the block
                    // But we do need to know if this is an array of blocks. Is that legal?

// Find the internal name.
// This can be an array.
//                    line = src.substr(currPos, endPos - currPos);
//                    StringVector internalParts = StringUtil::split(line, ", \t\r\n");
//                    String internalName = "";
//                    uint16 arraySize = 0;
//                    for (StringVector::iterator i = internalParts.begin(); i != internalParts.end(); ++i)
//                    {
//                        StringUtil::trim(*i);
//                        String::size_type arrayStart = i->find("[", 0);
//                        if (arrayStart != String::npos)
//                        {
//                            // potential name (if butted up to array)
//                            String name = i->substr(0, arrayStart);
//                            StringUtil::trim(name);
//                            if (!name.empty())
//                                internalName = name;
//
//                            String::size_type arrayEnd = i->find("]", arrayStart);
//                            String arrayDimTerm = i->substr(arrayStart + 1, arrayEnd - arrayStart - 1);
//                            StringUtil::trim(arrayDimTerm);
//                            arraySize = StringConverter::parseUnsignedInt(arrayDimTerm);
//                        }
//                        else
//                        {
//                            internalName = *i;
//                        }
//                    }
//
//                    // Ok, now rewind and parse the individual uniforms in this block
//                    currPos = openBracePos + 1;
//                    blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(externalName);
//                    if(blockSharedParams.isNull())
//                        blockSharedParams = GpuProgramManager::getSingleton().createSharedParameters(externalName);
//                    do
//                    {
//                        lineEndPos = src.find_first_of("\n\r", currPos);
//                        endPos = src.find(";", currPos);
//                        line = src.substr(currPos, endPos - currPos);
//
//                        // TODO: Give some sort of block id
//                        // Parse the normally structured uniform
//                        parseIndividualConstant(src, defs, currPos, filename, blockSharedParams);
//                        currPos = lineEndPos + 1;
//                    } while (endBracePos > currPos);
                }
                else
                {
                    // find terminating semicolon
                    endPos = src.find(";", currPos);
                    if (endPos == String::npos)
                    {
                        // problem, missing semicolon, abort
                        break;
                    }
                    
                    parseIndividualConstant(src, defs, currPos, filename, blockSharedParams);
                }
                line = src.substr(currPos, endPos - currPos);
            } // not commented or a larger symbol
            
            // Find next one
            currPos = src.find("uniform", currPos);
        }
    }
    //---------------------------------------------------------------------
    void GLSLProgramManagerCommon::parseIndividualConstant(const String& src, GpuNamedConstants& defs,
                                                             String::size_type currPos,
                                                             const String& filename, GpuSharedParametersPtr sharedParams)
    {
        GpuConstantDefinition def;
        String paramName = "";
        String::size_type endPos = src.find(";", currPos);
        String line = src.substr(currPos, endPos - currPos);

        // Remove spaces before opening square braces, otherwise
        // the following split() can split the line at inappropriate
        // places (e.g. "vec3 something [3]" won't work).
        for (String::size_type sqp = line.find (" ["); sqp != String::npos;
             sqp = line.find (" ["))
            line.erase (sqp, 1);
        // Split into tokens
        StringVector parts = StringUtil::split(line, ", \t\r\n");

        for (StringVector::iterator i = parts.begin(); i != parts.end(); ++i)
        {
            // Is this a type?
            StringToEnumMap::iterator typei = mTypeEnumMap.find(*i);
            if (typei != mTypeEnumMap.end())
            {
                completeDefInfo(typei->second, def);
            }
            else
            {
                // if this is not a type, and not empty, it should be a name
                StringUtil::trim(*i);
                if (i->empty()) continue;

                // Skip over precision keywords
                if(StringUtil::match((*i), "lowp") ||
                   StringUtil::match((*i), "mediump") ||
                   StringUtil::match((*i), "highp"))
                    continue;

                String::size_type arrayStart = i->find("[", 0);
                if (arrayStart != String::npos)
                {
                    // potential name (if butted up to array)
                    String name = i->substr(0, arrayStart);
                    StringUtil::trim(name);
                    if (!name.empty())
                        paramName = name;

                    String::size_type arrayEnd = i->find("]", arrayStart);
                    String arrayDimTerm = i->substr(arrayStart + 1, arrayEnd - arrayStart - 1);
                    StringUtil::trim(arrayDimTerm);
                    // the array term might be a simple number or it might be
                    // an expression (e.g. 24*3) or refer to a constant expression
                    // we'd have to evaluate the expression which could get nasty
                    // TODO
                    def.arraySize = StringConverter::parseInt(arrayDimTerm);
                }
                else
                {
                    paramName = *i;
                    def.arraySize = 1;
                }

                // Name should be after the type, so complete def and add
                // We do this now so that comma-separated params will do
                // this part once for each name mentioned
                if (def.constType == GCT_UNKNOWN)
                {
                    LogManager::getSingleton().logMessage("Problem parsing the following GLSL Uniform: '"
                                                          + line + "' in file " + filename);
                    // next uniform
                    break;
                }

                // Special handling for shared parameters
                if(sharedParams.isNull())
                {
                    // Complete def and add
                    // increment physical buffer location
                    def.logicalIndex = 0; // not valid in GLSL
                    if (def.isFloat())
                    {
                        def.physicalIndex = defs.floatBufferSize;
                        defs.floatBufferSize += def.arraySize * def.elementSize;
                    }
                    else
                    {
                        def.physicalIndex = defs.intBufferSize;
                        defs.intBufferSize += def.arraySize * def.elementSize;
                    }
                    defs.map.insert(GpuConstantDefinitionMap::value_type(paramName, def));

                    // Generate array accessors
                    defs.generateConstantDefinitionArrayEntries(paramName, def);
                }
                else
                {
                    try
                    {
                        const GpuConstantDefinition &sharedDef = sharedParams->getConstantDefinition(paramName);
                        (void)sharedDef;    // Silence warning
                    }
                    catch (Exception& e)
                    {
                        // This constant doesn't exist so we'll create a new one
                        sharedParams->addConstantDefinition(paramName, def.constType);
                    }
                }
            }
        }
    }
Example #10
0
bool parseToDoubleForNumberTypeWithDecimalPlaces(const String& string, double *result, unsigned *decimalPlaces)
{
    if (decimalPlaces)
        *decimalPlaces = 0;

    if (!parseToDoubleForNumberType(string, result))
        return false;

    if (!decimalPlaces)
        return true;

    size_t dotIndex = string.find('.');
    size_t eIndex = string.find('e');
    if (eIndex == notFound) 
        eIndex = string.find('E');

    unsigned baseDecimalPlaces = 0;
    if (dotIndex != notFound) {
        if (eIndex == notFound)
            baseDecimalPlaces = string.length() - dotIndex - 1;
        else
            baseDecimalPlaces = eIndex - dotIndex - 1;
    }

    int exponent = 0;
    if (eIndex != notFound) {
        unsigned cursor = eIndex + 1, cursorSaved;
        int digit, exponentSign;
        int32_t exponent32;
        size_t length = string.length();

        // Not using String.toInt() in order to perform the same computation as dtoa() does.
        exponentSign = 0;
        switch (digit = string[cursor]) {
        case '-':
            exponentSign = 1;
        case '+':
            digit = string[++cursor];
        }
        if (digit >= '0' && digit <= '9') {
            while (cursor < length && digit == '0')
                digit = string[++cursor];
            if (digit > '0' && digit <= '9') {
                exponent32 = digit - '0';
                cursorSaved = cursor;
                while (cursor < length && (digit = string[++cursor]) >= '0' && digit <= '9')
                    exponent32 = (10 * exponent32) + digit - '0';
                if (cursor - cursorSaved > 8 || exponent32 > 19999)
                    /* Avoid confusion from exponents
                     * so large that e might overflow.
                     */
                    exponent = 19999; /* safe for 16 bit ints */
                else
                    exponent = static_cast<int>(exponent32);
                if (exponentSign)
                    exponent = -exponent;
            } else
                exponent = 0;
        }
    }

    int intDecimalPlaces = baseDecimalPlaces - exponent;
    if (intDecimalPlaces < 0)
        *decimalPlaces = 0;
    else if (intDecimalPlaces > 19999)
        *decimalPlaces = 19999;
    else
        *decimalPlaces = static_cast<unsigned>(intDecimalPlaces);

    return true;
}
    //---------------------------------------------------------------------
    void GLSLProgramManagerCommon::extractUniforms(GLuint programObject, 
        const GpuConstantDefinitionMap* vertexConstantDefs,
        const GpuConstantDefinitionMap* geometryConstantDefs,
        const GpuConstantDefinitionMap* fragmentConstantDefs,
        const GpuConstantDefinitionMap* hullConstantDefs,
        const GpuConstantDefinitionMap* domainConstantDefs,
        const GpuConstantDefinitionMap* computeConstantDefs,
        GLUniformReferenceList& list, GLUniformBufferList& sharedList)
    {
        // Scan through the active uniforms and add them to the reference list
        GLint uniformCount = 0;
#define uniformLength 200
        //      GLint uniformLength = 0;
        //        glGetProgramiv(programObject, GL_ACTIVE_UNIFORM_MAX_LENGTH, &uniformLength);

        char uniformName[uniformLength];
        GLUniformReference newGLUniformReference;

        // Get the number of active uniforms
        OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORMS, &uniformCount));

        // Loop over each of the active uniforms, and add them to the reference container
        // only do this for user defined uniforms, ignore built in gl state uniforms
        for (int index = 0; index < uniformCount; index++)
        {
            GLint arraySize;
            GLenum glType;
            OGRE_CHECK_GL_ERROR(glGetActiveUniform(programObject, index, uniformLength, NULL,
                                                   &arraySize, &glType, uniformName));

            // Don't add built in uniforms
            OGRE_CHECK_GL_ERROR(newGLUniformReference.mLocation = glGetUniformLocation(programObject, uniformName));
            if (newGLUniformReference.mLocation >= 0)
            {
                // User defined uniform found, add it to the reference list
                String paramName = String( uniformName );

                // Current ATI drivers (Catalyst 7.2 and earlier) and older NVidia drivers will include all array elements as uniforms but we only want the root array name and location
                // Also note that ATI Catalyst 6.8 to 7.2 there is a bug with glUniform that does not allow you to update a uniform array past the first uniform array element
                // ie you can't start updating an array starting at element 1, must always be element 0.

                // If the uniform name has a "[" in it then its an array element uniform.
                String::size_type arrayStart = paramName.find("[");
                if (arrayStart != String::npos)
                {
                    // if not the first array element then skip it and continue to the next uniform
                    if (paramName.compare(arrayStart, paramName.size() - 1, "[0]") != 0) continue;
                    paramName = paramName.substr(0, arrayStart);
                }

                // Find out which params object this comes from
                bool foundSource = completeParamSource(paramName,
                                                       vertexConstantDefs, geometryConstantDefs,
                                                       fragmentConstantDefs, hullConstantDefs,
                                                       domainConstantDefs, computeConstantDefs, newGLUniformReference);

                // Only add this parameter if we found the source
                if (foundSource)
                {
                    assert(size_t (arraySize) == newGLUniformReference.mConstantDef->arraySize
                           && "GL doesn't agree with our array size!");
                    list.push_back(newGLUniformReference);
                }

                // Don't bother adding individual array params, they will be
                // picked up in the 'parent' parameter can copied all at once
                // anyway, individual indexes are only needed for lookup from
                // user params
            } // end if
        } // end for

        // Now deal with uniform blocks

        GLint blockCount = 0;

        OGRE_CHECK_GL_ERROR(glGetProgramiv(programObject, GL_ACTIVE_UNIFORM_BLOCKS, &blockCount));

        for (int index = 0; index < blockCount; index++)
        {
            OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockName(programObject, index, uniformLength, NULL, uniformName));

            GpuSharedParametersPtr blockSharedParams = GpuProgramManager::getSingleton().getSharedParameters(uniformName);

            GLint blockSize, blockBinding;
            OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockiv(programObject, index, GL_UNIFORM_BLOCK_DATA_SIZE, &blockSize));
            OGRE_CHECK_GL_ERROR(glGetActiveUniformBlockiv(programObject, index, GL_UNIFORM_BLOCK_BINDING, &blockBinding));
            HardwareUniformBufferSharedPtr newUniformBuffer = HardwareBufferManager::getSingleton().createUniformBuffer(blockSize, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY_DISCARDABLE, false, uniformName);

            GL3PlusHardwareUniformBuffer* hwGlBuffer = static_cast<GL3PlusHardwareUniformBuffer*>(newUniformBuffer.get());
            hwGlBuffer->setGLBufferBinding(blockBinding);
            sharedList.push_back(newUniformBuffer);
        }
    }
Example #12
0
static void CopyPathInfo(Array& server,
                         Transport *transport,
                         const RequestURI& r,
                         const VirtualHost *vhost) {
    server.set(s_REQUEST_URI, String(transport->getUrl(), CopyString));
    server.set(s_SCRIPT_URL, r.originalURL());
    String prefix(transport->isSSL() ? "https://" : "http://");

    // Need to append port
    assert(server.exists(s_SERVER_PORT));
    std::string serverPort = "80";
    if (server.exists(s_SERVER_PORT)) {
        Variant port = server[s_SERVER_PORT];
        always_assert(port.isInteger() || port.isString());
        if (port.isInteger()) {
            serverPort = folly::to<std::string>(port.toInt32());
        } else {
            serverPort = port.toString().data();
        }
    }

    String port_suffix("");
    if (!transport->isSSL() && serverPort != "80") {
        port_suffix = folly::format(":{}", serverPort).str();
    }

    string hostHeader;
    if (server.exists(s_HTTP_HOST)) {
        hostHeader = server[s_HTTP_HOST].toCStrRef().data();
    }
    String hostName;
    if (server.exists(s_SERVER_NAME)) {
        assert(server[s_SERVER_NAME].isString());
        hostName = server[s_SERVER_NAME].toCStrRef();
    }
    server.set(s_SCRIPT_URI,
               String(prefix + (hostHeader.empty() ? hostName + port_suffix :
                                String(hostHeader)) + r.originalURL()));

    if (r.rewritten()) {
        // when URL is rewritten, PHP decided to put original URL as SCRIPT_NAME
        String name = r.originalURL();
        if (!r.pathInfo().empty()) {
            int pos = name.find(r.pathInfo());
            if (pos >= 0) {
                name = name.substr(0, pos);
            }
        }
        if (r.defaultDoc()) {
            if (!name.empty() && name[name.length() - 1] != '/') {
                name += "/";
            }
            name += String(RuntimeOption::DefaultDocument);
        }
        server.set(s_SCRIPT_NAME, name);
    } else {
        server.set(s_SCRIPT_NAME, r.resolvedURL());
    }

    if (r.rewritten()) {
        server.set(s_PHP_SELF, r.originalURL());
    } else {
        server.set(s_PHP_SELF, r.resolvedURL() + r.origPathInfo());
    }

    String documentRoot = transport->getDocumentRoot();
    if (documentRoot.empty()) {
        // Right now this is just RuntimeOption::SourceRoot but mwilliams wants to
        // fix it so it is settable, so I'll leave this for now
        documentRoot = vhost->getDocumentRoot();
    }
    server.set(s_DOCUMENT_ROOT, documentRoot);
    server.set(s_SCRIPT_FILENAME, r.absolutePath());

    if (r.pathInfo().empty()) {
        server.set(s_PATH_TRANSLATED, r.absolutePath());
    } else {
        assert(server.exists(s_DOCUMENT_ROOT));
        assert(server[s_DOCUMENT_ROOT].isString());
        // reset path_translated back to the transport if it has it.
        auto const& pathTranslated = transport->getPathTranslated();
        if (!pathTranslated.empty()) {
            if (documentRoot == s_forwardslash) {
                // path outside document root or / is document root
                server.set(s_PATH_TRANSLATED, String(pathTranslated));
            } else {
                server.set(s_PATH_TRANSLATED,
                           String(server[s_DOCUMENT_ROOT].toCStrRef() +
                                  pathTranslated));
            }
        } else {
            server.set(s_PATH_TRANSLATED,
                       String(server[s_DOCUMENT_ROOT].toCStrRef() +
                              server[s_SCRIPT_NAME].toCStrRef() +
                              r.pathInfo().data()));
        }
        server.set(s_PATH_INFO, r.pathInfo());
    }

    switch (transport->getMethod()) {
    case Transport::Method::GET:
        server.set(s_REQUEST_METHOD, s_GET);
        break;
    case Transport::Method::HEAD:
        server.set(s_REQUEST_METHOD, s_HEAD);
        break;
    case Transport::Method::POST:
        if (transport->getExtendedMethod() == nullptr) {
            server.set(s_REQUEST_METHOD, s_POST);
        } else {
            server.set(s_REQUEST_METHOD, transport->getExtendedMethod());
        }
        break;
    default:
        server.set(s_REQUEST_METHOD, empty_string);
        break;
    }
    server.set(s_HTTPS, transport->isSSL() ? s_on : empty_string);
    server.set(s_QUERY_STRING, r.queryString());

    server.set(s_argv, make_packed_array(r.queryString()));
    server.set(s_argc, 1);
}
Example #13
0
void Feed::setAll(const char* allch) {
	if (strlen(allch) <= 0) {
		allch = "";
	}
	String all = allch;
	int indexof = all.find(",");
	if (indexof > -1) {
		setUsername(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setEncrypt(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setUnsuccessful(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setReplaceWhiteSpaces(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setReplaceSpecialCharacters(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setCredits(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setEmail(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setHandle(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setTouch(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setSeconds(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setRegistered(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		indexof = all.find(",");
		setNoteSeconds(all.substr(0,indexof++).c_str());
		all=all.substr(indexof);
		setLoaded(true);
		if ((getUsername().length() <= 0)||(getEncrypt().length() <= 0)) {
			setUsername("");
			setEncrypt("");
			setLoaded(false);
		}
	} else {
		setLoaded(false);
		setUsername("");
		setEncrypt("");
		setUnsuccessful("");
		setReplaceWhiteSpaces("");
		setReplaceSpecialCharacters("");
		setCredits("");
		setEmail("");
		setHandle("");
		setTouch("false");
		setRegistered("0");
		setNoteLoaded(false);
		setNoteSeconds("");
	}
}
/*
    goodServerAddress property retrieve server addresses array, if is NTP client
    method for the NTP Provider Test Client
    Checks the specified value against the expected value and
    returns TRUE if the same, else FALSE
*/
Boolean NTPTestClient::goodServerAddress(
    Array<String> & srvAddress,
    Boolean verbose)
{
    FILE *fp;
    int i, j, ps,
        count = 0;
    char buffer[5000];
    long lstPos = 0;
    Boolean ok = false,
            okRet = false;
    String strValue;
    String strKey;
    String strHost;
    String strBuffer;
    Array<String> srvAddr;

    if (verbose)
        cout << "Checking ServerAddress array ... " << endl;

    // Open NTP file configuration
    if ((fp = fopen(FILE_CONFIG.getCString(), "r")) == NULL)
        return ok;

    srvAddr.clear();
    memset(buffer, 0, sizeof(buffer));
    while(fgets(buffer, sizeof(buffer), fp) != NULL)
    {
        int bufferLength = strlen(buffer);
        if (bufferLength > 0)
        {
            buffer[bufferLength - 1] = 0;
        }
        strBuffer.assign(buffer);

        ps = strBuffer.find(ROLE_CLIENT);
        okRet = true;

        if (ps == 0)
        {
            okRet = true;
            fseek(fp, lstPos, SEEK_SET);
            fscanf(fp, "%4999s", buffer);
            strBuffer.assign(buffer);
            ps = strBuffer.find(ROLE_CLIENT);
            if(ps < 0) {
                lstPos = ftell(fp);
                continue;
            }

            fscanf(fp, "%4999s", buffer);
            strHost.assign(buffer);

            ok = false;
            okRet = true;
            for(i=0; i < srvAddr.size(); i++)
            {
                if (String::equalNoCase(srvAddr[i], strHost))
                {
                    ok = true;
                    break;
                }
            }
            if (!ok)
                srvAddr.append(strHost);
        }
        lstPos = ftell(fp);
    }
    fclose(fp);

    if (okRet && srvAddr.size() != srvAddress.size())
        okRet = false;

    if (okRet)
    {
        count = 0;
        for(i=0; i < srvAddress.size(); i++)
        {
            for(j=0; j < srvAddr.size(); j++)
            {
                if(String::equalNoCase(srvAddress[i], srvAddr[j]))
                {
                    if (verbose)
                        cout << "ServerAddress[" << i << "]: " <<
                            srvAddress[i] << endl;
                    count++;
                }
            }
        }
        okRet = (count == srvAddr.size());
    }
    return okRet;
}
static bool isValid(const String& constraint)
{
    return isSupported(constraint) || notFound != constraint.find("valid_");
}
// See the specifications for more details about the algorithm to follow.
// http://www.w3.org/TR/2013/WD-html-srcset-20130228/#processing-the-image-candidates.
static void parseImagesWithScaleFromSrcsetAttribute(const String& srcsetAttribute, ImageCandidates& imageCandidates)
{
    ASSERT(imageCandidates.isEmpty());

    size_t imageCandidateStart = 0;
    unsigned srcsetAttributeLength = srcsetAttribute.length();

    while (imageCandidateStart < srcsetAttributeLength) {
        float imageScaleFactor = 1;
        size_t separator;

        // 4. Splitting loop: Skip whitespace.
        size_t imageURLStart = srcsetAttribute.find(isNotHTMLSpace, imageCandidateStart);
        if (imageURLStart == notFound)
            break;
        // If The current candidate is either totally empty or only contains space, skipping.
        if (srcsetAttribute[imageURLStart] == ',') {
            imageCandidateStart = imageURLStart + 1;
            continue;
        }
        // 5. Collect a sequence of characters that are not space characters, and let that be url.
        size_t imageURLEnd = srcsetAttribute.find(isHTMLSpace, imageURLStart + 1);
        if (imageURLEnd == notFound) {
            imageURLEnd = srcsetAttributeLength;
            separator = srcsetAttributeLength;
        } else if (srcsetAttribute[imageURLEnd - 1] == ',') {
            --imageURLEnd;
            separator = imageURLEnd;
        } else {
            // 7. Collect a sequence of characters that are not "," (U+002C) characters, and let that be descriptors.
            size_t imageScaleStart = srcsetAttribute.find(isNotHTMLSpace, imageURLEnd + 1);
            if (imageScaleStart == notFound)
                separator = srcsetAttributeLength;
            else if (srcsetAttribute[imageScaleStart] == ',')
                separator = imageScaleStart;
            else {
                // This part differs from the spec as the current implementation only supports pixel density descriptors for now.
                size_t imageScaleEnd = srcsetAttribute.find(isHTMLSpaceOrComma, imageScaleStart + 1);
                imageScaleEnd = (imageScaleEnd == notFound) ? srcsetAttributeLength : imageScaleEnd;
                size_t commaPosition = imageScaleEnd;
                // Make sure there are no other descriptors.
                while ((commaPosition < srcsetAttributeLength - 1) && isHTMLSpace(srcsetAttribute[commaPosition]))
                    ++commaPosition;
                // If the first not html space character after the scale modifier is not a comma,
                // the current candidate is an invalid input.
                if ((commaPosition < srcsetAttributeLength - 1) && srcsetAttribute[commaPosition] != ',') {
                    // Find the nearest comma and skip the input.
                    commaPosition = srcsetAttribute.find(',', commaPosition + 1);
                    if (commaPosition == notFound)
                        break;
                    imageCandidateStart = commaPosition + 1;
                    continue;
                }
                separator = commaPosition;
                if (srcsetAttribute[imageScaleEnd - 1] != 'x') {
                    imageCandidateStart = separator + 1;
                    continue;
                }
                bool validScaleFactor = false;
                size_t scaleFactorLengthWithoutUnit = imageScaleEnd - imageScaleStart - 1;
                imageScaleFactor = charactersToFloat(srcsetAttribute.characters() + imageScaleStart, scaleFactorLengthWithoutUnit, &validScaleFactor);

                if (!validScaleFactor) {
                    imageCandidateStart = separator + 1;
                    continue;
                }
            }
        }
        ImageWithScale image;
        image.imageURLStart = imageURLStart;
        image.imageURLLength = imageURLEnd - imageURLStart;
        image.scaleFactor = imageScaleFactor;

        imageCandidates.append(image);
        // 11. Return to the step labeled splitting loop.
        imageCandidateStart = separator + 1;
    }
}
Example #17
0
NodePath::NodePath(const String &p_path) {

	data = NULL;

	if (p_path.length() == 0)
		return;

	String path = p_path;
	StringName property;
	Vector<StringName> subpath;

	int absolute = (path[0] == '/') ? 1 : 0;
	bool last_is_slash = true;
	int slices = 0;
	int subpath_pos = path.find(":");

	if (subpath_pos != -1) {

		int from = subpath_pos + 1;

		for (int i = from; i <= path.length(); i++) {

			if (path[i] == ':' || path[i] == 0) {

				String str = path.substr(from, i - from);
				if (path[i] == ':') {
					if (str == "") {
						ERR_EXPLAIN("Invalid NodePath: " + p_path);
						ERR_FAIL();
					}
					subpath.push_back(str);
				} else {
					//property can be empty
					property = str;
				}

				from = i + 1;
			}
		}

		path = path.substr(0, subpath_pos);
	}

	for (int i = absolute; i < path.length(); i++) {

		if (path[i] == '/') {

			last_is_slash = true;
		} else {

			if (last_is_slash)
				slices++;

			last_is_slash = false;
		}
	}

	if (slices == 0 && !absolute && !property)
		return;

	data = memnew(Data);
	data->refcount.init();
	data->absolute = absolute ? true : false;
	data->property = property;
	data->subpath = subpath;

	if (slices == 0)
		return;
	data->path.resize(slices);
	last_is_slash = true;
	int from = absolute;
	int slice = 0;

	for (int i = absolute; i < path.length() + 1; i++) {

		if (path[i] == '/' || path[i] == 0) {

			if (!last_is_slash) {

				String name = path.substr(from, i - from);
				ERR_FAIL_INDEX(slice, data->path.size());
				data->path[slice++] = name;
			}
			from = i + 1;
			last_is_slash = true;
		} else {
			last_is_slash = false;
		}
	}
}
Example #18
0
int main(int argc, char *argv[]) {
    Property p;
    p.fromCommand(argc,argv);

    // check where to put description of device
    ConstString dest = "";
    dest = p.check("doc",Value("")).toString();

    ConstString fileName = p.check("file",Value("default.ini")).asString();

    if (p.check("file")) {
        p.fromConfigFile(fileName);
    }

    ConstString deviceName = p.check("device",Value("")).asString();

    // if no device given, we should be operating a completely
    // standard test harness like for libYARP_OS and libYARP_sig
    if (deviceName=="") {
        return harness_main(argc,argv);
    }

    // device name given - use special device testing procedure

#ifdef CHECK_FOR_LEAKS
    mtrace();
#endif

    int result = 0;

    Network::init();
    Network::setLocalMode(true);

    String seek = fileName.c_str();
    ConstString exampleName = "";
    int pos = seek.rfind('/');
    if (pos==-1) {
        pos = seek.rfind('\\');
    }
    if (pos==-1) {
        pos = 0;
    } else {
        pos++;
    }
    int len = seek.find('.',pos);
    if (len==-1) {
        len = seek.length();
    } else {
        len -= pos;
    }
    exampleName = seek.substr(pos,len).c_str();
    ConstString shortFileName = seek.substr(pos,seek.length()).c_str();

    PolyDriver dd;
	YARP_DEBUG(Logger::get(), "harness opening...");
	
    bool ok = dd.open(p);
    YARP_DEBUG(Logger::get(), "harness opened.");
    result = ok?0:1;

    ConstString wrapperName = "";
    ConstString codeName = "";

    DriverCreator *creator = 
        Drivers::factory().find(deviceName.c_str());
    if (creator!=NULL) {
        wrapperName = creator->getWrapper();
        codeName = creator->getCode();
    }


    if (dest!="") {
        String dest2 = dest.c_str();
        if (result!=0) {
            dest2 += ".fail";
        }
        FILE *fout = fopen(dest2.c_str(),"w");
        if (fout==NULL) {
            printf("Problem writing to %s\n", dest2.c_str());
            exit(1);
        }
        fprintf(fout,"/**\n");
        fprintf(fout," * \\ingroup dev_examples\n");
        fprintf(fout," *\n");
        fprintf(fout," * \\defgroup %s Example for %s (%s)\n\n",
                exampleName.c_str(),
                deviceName.c_str(),
                exampleName.c_str());
        fprintf(fout, "Instantiates \\ref cmd_device_%s \"%s\" device implemented by %s.\n",
                deviceName.c_str(), deviceName.c_str(), codeName.c_str());
        fprintf(fout, "\\verbatim\n%s\\endverbatim\n",
                getFile(fileName.c_str()).c_str());
        fprintf(fout, "If this text is saved in a file called %s then the device can be created by doing:\n",
                shortFileName.c_str());
        fprintf(fout, "\\verbatim\nyarpdev --file %s\n\\endverbatim\n",
                shortFileName.c_str());
        fprintf(fout, "Of course, the configuration could be passed just as command line options, or as a yarp::os::Property object in a program:\n");
        fprintf(fout, "\\code\n");
        fprintf(fout, "Property p;\n");
        fprintf(fout, "p.fromConfigFile(\"%s\");\n",
                shortFileName.c_str());
        fprintf(fout, "// of course you could construct the Property object on-the-fly\n");
        fprintf(fout, "PolyDriver dev;\n");
        fprintf(fout, "dev.open(p);\n");
        fprintf(fout, "if (dev.isValid()) { /* use the device via view method */ }\n" );
        fprintf(fout, "\\endcode\n");
        fprintf(fout, "Here is a list of properties checked when starting up a device based on this configuration file.  Note that which properties are checked can depend on whether other properties are present.  In some cases properties can also vary between operating systems.  So this is just an example\n\n");
        toDox(dd,fout);
        fprintf(fout, "\n\\sa %s\n\n",
                codeName.c_str());
        fprintf(fout, " */\n");
        fclose(fout);
        fout = NULL;
    }

    if (ok) {
        YARP_DEBUG(Logger::get(), "harness closing...");
        dd.close();
        YARP_DEBUG(Logger::get(), "harness closed.");
    }

    // just checking for crashes, not device creation
    return result; //result;
}
Example #19
0
int
DaemonApp::run(int argc, char** argv)
{
#if SYSAPI_WIN32
	// win32 instance needed for threading, etc.
	ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
#endif
	
	Arch arch;
	arch.init();

	Log log;
	EventQueue events;
	m_events = &events;

	bool uninstall = false;
	try
	{
#if SYSAPI_WIN32
		// sends debug messages to visual studio console window.
		log.insert(new MSWindowsDebugOutputter());
#endif

		// default log level to system setting.
		string logLevel = arch.setting("LogLevel");
		if (logLevel != "")
			log.setFilter(logLevel.c_str());

		bool foreground = false;

		for (int i = 1; i < argc; ++i) {
			string arg(argv[i]);

			if (arg == "/f" || arg == "-f") {
				foreground = true;
			}
#if SYSAPI_WIN32
			else if (arg == "/install") {
				uninstall = true;
				arch.installDaemon();
				return kExitSuccess;
			}
			else if (arg == "/uninstall") {
				arch.uninstallDaemon();
				return kExitSuccess;
			}
#endif
			else {
				stringstream ss;
				ss << "Unrecognized argument: " << arg;
				foregroundError(ss.str().c_str());
				return kExitArgs;
			}
		}

		if (foreground) {
			// run process in foreground instead of daemonizing.
			// useful for debugging.
			mainLoop(false);
		}
		else {
#if SYSAPI_WIN32
			arch.daemonize("Synergy", winMainLoopStatic);
#elif SYSAPI_UNIX
			arch.daemonize("Synergy", unixMainLoopStatic);
#endif
		}

		return kExitSuccess;
	}
	catch (XArch& e) {
		String message = e.what();
		if (uninstall && (message.find("The service has not been started") != String::npos)) {
			// TODO: if we're keeping this use error code instead (what is it?!).
			// HACK: this message happens intermittently, not sure where from but
			// it's quite misleading for the user. they thing something has gone
			// horribly wrong, but it's just the service manager reporting a false
			// positive (the service has actually shut down in most cases).
		}
		else {
			foregroundError(message.c_str());
		}
		return kExitFailed;
	}
	catch (std::exception& e) {
		foregroundError(e.what());
		return kExitFailed;
	}
	catch (...) {
		foregroundError("Unrecognized error.");
		return kExitFailed;
	}
}
Example #20
0
Error HTTPClient::poll(){

	switch(status) {


		case STATUS_RESOLVING: {
			ERR_FAIL_COND_V(resolving==IP::RESOLVER_INVALID_ID,ERR_BUG);

			IP::ResolverStatus rstatus = IP::get_singleton()->get_resolve_item_status(resolving);
			switch(rstatus) {
				case IP::RESOLVER_STATUS_WAITING: return OK; //still resolving

				case IP::RESOLVER_STATUS_DONE: {

					IP_Address host = IP::get_singleton()->get_resolve_item_address(resolving);
					Error err = tcp_connection->connect(host,conn_port);
					IP::get_singleton()->erase_resolve_item(resolving);
					resolving=IP::RESOLVER_INVALID_ID;
					if (err) {
						status=STATUS_CANT_CONNECT;
						return err;
					}

					status=STATUS_CONNECTING;
				} break;
				case IP::RESOLVER_STATUS_NONE:
				case IP::RESOLVER_STATUS_ERROR: {

					IP::get_singleton()->erase_resolve_item(resolving);
					resolving=IP::RESOLVER_INVALID_ID;
					close();
					status=STATUS_CANT_RESOLVE;
					return ERR_CANT_RESOLVE;
				} break;

			}
		} break;
		case STATUS_CONNECTING: {

			StreamPeerTCP::Status s = tcp_connection->get_status();
			switch(s) {

				case StreamPeerTCP::STATUS_CONNECTING: {
					return OK; //do none
				} break;
				case StreamPeerTCP::STATUS_CONNECTED: {
					if (ssl) {
						Ref<StreamPeerSSL> ssl = StreamPeerSSL::create();
						Error err = ssl->connect(tcp_connection,true,ssl_verify_host?conn_host:String());
						if (err!=OK) {
							close();
							status=STATUS_SSL_HANDSHAKE_ERROR;
							return ERR_CANT_CONNECT;
						}
						//print_line("SSL! TURNED ON!");
						connection=ssl;
					}
					status=STATUS_CONNECTED;
					return OK;
				} break;
				case StreamPeerTCP::STATUS_ERROR:
				case StreamPeerTCP::STATUS_NONE: {

					close();
					status=STATUS_CANT_CONNECT;
					return ERR_CANT_CONNECT;
				} break;
			}
		} break;
		case STATUS_CONNECTED: {
			//request something please
			return OK;
		} break;
		case STATUS_REQUESTING: {


			while(true) {
				uint8_t byte;
				int rec=0;
				Error err = _get_http_data(&byte,1,rec);
				if (err!=OK) {
					close();
					status=STATUS_CONNECTION_ERROR;
					return ERR_CONNECTION_ERROR;
				}

				if (rec==0)
					return OK; //keep trying!

				response_str.push_back(byte);
				int rs = response_str.size();
				if (
					(rs>=2 && response_str[rs-2]=='\n' && response_str[rs-1]=='\n') ||
					(rs>=4 && response_str[rs-4]=='\r' && response_str[rs-3]=='\n' && rs>=4 && response_str[rs-2]=='\r' && response_str[rs-1]=='\n')
				) {


					//end of response, parse.
					response_str.push_back(0);
					String response;
					response.parse_utf8((const char*)response_str.ptr());
					//print_line("END OF RESPONSE? :\n"+response+"\n------");
					Vector<String> responses = response.split("\n");
					body_size=0;
					chunked=false;
					body_left=0;
					chunk_left=0;
					response_headers.clear();
					response_num = RESPONSE_OK;

					for(int i=0;i<responses.size();i++) {

						String header = responses[i].strip_edges();
						String s = header.to_lower();
						if (s.length()==0)
							continue;
						if (s.begins_with("content-length:")) {
							body_size = s.substr(s.find(":")+1,s.length()).strip_edges().to_int();
							body_left=body_size;
						}

						if (s.begins_with("transfer-encoding:")) {
							String encoding = header.substr(header.find(":")+1,header.length()).strip_edges();
							//print_line("TRANSFER ENCODING: "+encoding);
							if (encoding=="chunked") {
								chunked=true;
							}

						}

						if (i==0 && responses[i].begins_with("HTTP")) {

							String num = responses[i].get_slicec(' ',1);
							response_num=num.to_int();
						} else {

							response_headers.push_back(header);
						}

					}

					if (body_size==0 && !chunked) {

						status=STATUS_CONNECTED; //ask for something again?
					} else {
						status=STATUS_BODY;
					}
					return OK;
				}
			}
			//wait for response
			return OK;
		} break;
		case STATUS_DISCONNECTED: {
			return ERR_UNCONFIGURED;
		} break;
		case STATUS_CONNECTION_ERROR: {
			return ERR_CONNECTION_ERROR;
		} break;
		case STATUS_CANT_CONNECT: {
			return ERR_CANT_CONNECT;
		} break;
		case STATUS_CANT_RESOLVE: {
			return ERR_CANT_RESOLVE;
		} break;
	}


	return OK;
}
Example #21
0
RES ResourceFormatLoaderShader::load(const String &p_path,const String& p_original_path) {

    String fragment_code;
    String vertex_code;
    String light_code;

    int mode=-1;

    Error err;
    FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);


    ERR_EXPLAIN("Unable to open shader file: "+p_path);
    ERR_FAIL_COND_V(err,RES());
    String base_path = p_path.get_base_dir();


    Ref<Shader> shader;//( memnew( Shader ) );

    int line=0;

    while(!f->eof_reached()) {

        String l = f->get_line();
        line++;

        if (mode<=0) {
            l = l.strip_edges();
            int comment = l.find(";");
            if (comment!=-1)
                l=l.substr(0,comment);
        }

        if (mode<1)
            vertex_code+="\n";
        if (mode<2)
            fragment_code+="\n";

        if (mode < 1 && l=="")
            continue;

        if (l.begins_with("[")) {
            l=l.strip_edges();
            if (l=="[params]") {
                if (mode>=0) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [params] section.");
                    ERR_FAIL_V(RES());
                }
                mode=0;
            }  else if (l=="[vertex]") {
                if (mode>=1) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [vertex] section.");
                    ERR_FAIL_V(RES());
                }
                mode=1;
            }  else if (l=="[fragment]") {
                if (mode>=2) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [fragment] section.");
                    ERR_FAIL_V(RES());
                }
                mode=1;
            } else {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
                ERR_FAIL_V(RES());
            }
            continue;
        }

        if (mode==0) {

            int eqpos = l.find("=");
            if (eqpos==-1) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
                ERR_FAIL_V(RES());
            }


            String right=l.substr(eqpos+1,l.length()).strip_edges();
            if (right=="") {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
                ERR_FAIL_V(RES());
            }

            Variant value;

            if (right=="true") {
                value = true;
            } else if (right=="false") {
                value = false;
            } else if (right.is_valid_float()) {
                //is number
                value = right.to_double();
            } else if (right.is_valid_html_color()) {
                //is html color
                value = Color::html(right);
            } else {
                //attempt to parse a constructor
                int popenpos = right.find("(");

                if (popenpos==-1) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
                    ERR_FAIL_V(RES());
                }

                int pclosepos = right.find_last(")");

                if (pclosepos==-1) {
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
                    ERR_FAIL_V(RES());

                }

                String type = right.substr(0,popenpos);
                String param = right.substr(popenpos+1,pclosepos-popenpos-1).strip_edges();


                if (type=="tex") {

                    if (param=="") {

                        value=RID();
                    } else {

                        String path;

                        if (param.is_abs_path())
                            path=param;
                        else
                            path=base_path+"/"+param;

                        Ref<Texture> texture = ResourceLoader::load(path);
                        if (!texture.is_valid()) {
                            memdelete(f);
                            ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
                            ERR_FAIL_V(RES());
                        }

                        value=texture;
                    }

                } else if (type=="vec3") {

                    if (param=="") {
                        value=Vector3();
                    } else {
                        Vector<String> params = param.split(",");
                        if (params.size()!=3) {
                            memdelete(f);
                            ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for vec3(): '"+right+"'.");
                            ERR_FAIL_V(RES());

                        }

                        Vector3 v;
                        for(int i=0; i<3; i++)
                            v[i]=params[i].to_double();
                        value=v;
                    }


                } else if (type=="xform") {

                    if (param=="") {
                        value=Transform();
                    } else {

                        Vector<String> params = param.split(",");
                        if (params.size()!=12) {
                            memdelete(f);
                            ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for xform(): '"+right+"'.");
                            ERR_FAIL_V(RES());

                        }

                        Transform t;
                        for(int i=0; i<9; i++)
                            t.basis[i%3][i/3]=params[i].to_double();
                        for(int i=0; i<3; i++)
                            t.origin[i]=params[i-9].to_double();

                        value=t;
                    }

                } else {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
                    ERR_FAIL_V(RES());

                }

            }

            String left= l.substr(0,eqpos);

//			shader->set_param(left,value);
        } else if (mode==1) {

            vertex_code+=l;

        } else if (mode==2) {

            fragment_code+=l;
        }
    }

    shader->set_code(vertex_code,fragment_code,light_code);

    f->close();
    memdelete(f);

    return shader;
}
Example #22
0
//////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::getQueryString - builds the query string from the
//		input parameters for Associator and Reference commands
//
// ///////////////////////////////////////////////////////////////////////////
String WMIBaseProvider::getQueryString(const CIMObjectPath &objectName,
		const String &sQueryCommand,							   
		const String &assocClass, 
		const String &resultClass, 
		const String &role,
		const String &resultRole)
{
	bool hasWHERE = false;
	bool isInst;

	//first we need to get the object name
	String sObjName = getObjectName(objectName);

	// check if is an instance name
	Uint32 pos = sObjName.find(qString(Q_PERIOD));
	isInst = (PEG_NOT_FOUND != pos);

	CMyString sQuery;
	sQuery.Format(CMyString(sQueryCommand), 128, CMyString(sObjName));

	//set up any optional parameters
	if (!((0 == assocClass.size()) && (0 == resultClass.size()) &&
		  (0 == role.size()) && (0 == resultRole.size())))
	{	
		// we have optional parameters, append the appropriate ones
		sQuery += qChar(Q_WHERE);
		hasWHERE = true;

		if (0 != assocClass.size())
		{
			sQuery += qChar(Q_ASSOC_CLS);
			sQuery += assocClass;
		}

		if (0 != resultClass.size())
		{
			sQuery += qChar(Q_RESULT_CLASS);
			sQuery += resultClass;
		}

		if (0 != role.size())
		{
			sQuery += qChar(Q_ROLE);
			sQuery += role;
		}

		if (0 != resultRole.size())
		{
			sQuery += qChar(Q_RESULT_ROLE);
			sQuery += resultRole;
		}
	}

	// check if an instance
	if (!isInst)
	{
		// have a class, add "SchemaOnly"
		if (!hasWHERE)
		{
			sQuery += qChar(Q_WHERE);
		}

		sQuery += qChar(Q_SCHEMA);
	}

	Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3,
		"WMIBaseProvider::getQueryString() - Query is %s", (LPCTSTR)sQuery); 

	String s = (LPCTSTR)sQuery;
	return s;
}
Example #23
0
void RenderPartObject::updateWidget()
{
  String url;
  String serviceType;
  Vector<String> paramNames;
  Vector<String> paramValues;
  Frame* frame = m_view->frame();

  setNeedsLayoutAndMinMaxRecalc();

  if (element()->hasTagName(objectTag)) {

      HTMLObjectElement* o = static_cast<HTMLObjectElement*>(element());

      if (!o->isComplete())
        return;
      // Check for a child EMBED tag.
      HTMLEmbedElement* embed = 0;
      for (Node* child = o->firstChild(); child;) {
          if (child->hasTagName(embedTag)) {
              embed = static_cast<HTMLEmbedElement*>(child);
              break;
          } else if (child->hasTagName(objectTag))
              child = child->nextSibling();         // Don't descend into nested OBJECT tags
          else
              child = child->traverseNextNode(o);   // Otherwise descend (EMBEDs may be inside COMMENT tags)
      }
      
      // Use the attributes from the EMBED tag instead of the OBJECT tag including WIDTH and HEIGHT.
      HTMLElement *embedOrObject;
      if (embed) {
          embedOrObject = (HTMLElement *)embed;
          String attribute = embedOrObject->getAttribute(widthAttr);
          if (!attribute.isEmpty())
              o->setAttribute(widthAttr, attribute);
          attribute = embedOrObject->getAttribute(heightAttr);
          if (!attribute.isEmpty())
              o->setAttribute(heightAttr, attribute);
          url = embed->url;
          serviceType = embed->serviceType;
      } else
          embedOrObject = (HTMLElement *)o;
      
      // If there was no URL or type defined in EMBED, try the OBJECT tag.
      if (url.isEmpty())
          url = o->url;
      if (serviceType.isEmpty())
          serviceType = o->serviceType;
      
      HashSet<StringImpl*, CaseInsensitiveHash> uniqueParamNames;
      
      // Scan the PARAM children.
      // Get the URL and type from the params if we don't already have them.
      // Get the attributes from the params if there is no EMBED tag.
      Node *child = o->firstChild();
      while (child && (url.isEmpty() || serviceType.isEmpty() || !embed)) {
          if (child->hasTagName(paramTag)) {
              HTMLParamElement* p = static_cast<HTMLParamElement*>(child);
              String name = p->name().lower();
              if (url.isEmpty() && (name == "src" || name == "movie" || name == "code" || name == "url"))
                  url = p->value();
              if (serviceType.isEmpty() && name == "type") {
                  serviceType = p->value();
                  int pos = serviceType.find(";");
                  if (pos != -1)
                      serviceType = serviceType.left(pos);
              }
              if (!embed && !name.isEmpty()) {
                  uniqueParamNames.add(p->name().impl());
                  paramNames.append(p->name());
                  paramValues.append(p->value());
              }
          }
          child = child->nextSibling();
      }
      
      // When OBJECT is used for an applet via Sun's Java plugin, the CODEBASE attribute in the tag
      // points to the Java plugin itself (an ActiveX component) while the actual applet CODEBASE is
      // in a PARAM tag. See <http://java.sun.com/products/plugin/1.2/docs/tags.html>. This means
      // we have to explicitly suppress the tag's CODEBASE attribute if there is none in a PARAM,
      // else our Java plugin will misinterpret it. [4004531]
      String codebase;
      if (!embed && serviceType.lower() == "application/x-java-applet") {
          codebase = "codebase";
          uniqueParamNames.add(codebase.impl()); // pretend we found it in a PARAM already
      }
      
      // Turn the attributes of either the EMBED tag or OBJECT tag into arrays, but don't override PARAM values.
      NamedAttrMap* attributes = embedOrObject->attributes();
      if (attributes) {
          for (unsigned i = 0; i < attributes->length(); ++i) {
              Attribute* it = attributes->attributeItem(i);
              const AtomicString& name = it->name().localName();
              if (embed || !uniqueParamNames.contains(name.impl())) {
                  paramNames.append(name.domString());
                  paramValues.append(it->value().domString());
              }
          }
      }
      
      // If we still don't have a type, try to map from a specific CLASSID to a type.
      if (serviceType.isEmpty() && !o->classId.isEmpty())
          mapClassIdToServiceType(o->classId, serviceType);
      
      // If no URL and type, abort.
      if (url.isEmpty() && serviceType.isEmpty())
          return;
      if (!isURLAllowed(document(), url))
          return;

      // Find out if we support fallback content.
      m_hasFallbackContent = false;
      for (Node *child = o->firstChild(); child && !m_hasFallbackContent; child = child->nextSibling()) {
          if ((!child->isTextNode() && !child->hasTagName(embedTag) && !child->hasTagName(paramTag)) || // Discount <embed> and <param>
              (child->isTextNode() && !static_cast<Text*>(child)->containsOnlyWhitespace()))
              m_hasFallbackContent = true;
      }
      bool success = frame->requestObject(this, url, AtomicString(o->name()), serviceType, paramNames, paramValues);
      if (!success && m_hasFallbackContent)
          o->renderFallbackContent();
  } else if (element()->hasTagName(embedTag)) {
      HTMLEmbedElement *o = static_cast<HTMLEmbedElement*>(element());
      url = o->url;
      serviceType = o->serviceType;

      if (url.isEmpty() && serviceType.isEmpty())
          return;
      if (!isURLAllowed(document(), url))
          return;
      
      // add all attributes set on the embed object
      NamedAttrMap* a = o->attributes();
      if (a) {
          for (unsigned i = 0; i < a->length(); ++i) {
              Attribute* it = a->attributeItem(i);
              paramNames.append(it->name().localName().domString());
              paramValues.append(it->value().domString());
          }
      }
      frame->requestObject(this, url, o->getAttribute(nameAttr), serviceType, paramNames, paramValues);
  }
}
Example #24
0
//////////////////////////////////////////////////////////////////////////////
// WMIBaseProvider::getObjectName - extracts the String object name from
//		CIMObjectPath
//		removes namespace
// 
// Possible input Object Path formats: 
// 1. Fully-qualified path 
//     example: \\hostname:port\root\cimv2:ClassName.Key1="Value",Key2="Value" 
// 
// 2. No hostname & port (implies current host) 
//     example: root\cimv2:ClassName.Key1="Value",Key2="Value" 
// 
// 3. No namespace (implies current namespace): 
//     example: ClassName.Key1="Value",Key2="Value" 
// 
// 4. Reference instance 
//     example: ClassName.Key1=R"root\cimv2:RefClass.Key="RefValue"" 
// 
// In all cases, this method needs to return only the class name and keys from 
// the input object path (need to strip any hostname, port, and namespace). 
// For example, the return for cases #1-3, above, should be: 
//    ClassName.Key1="Value",Key2="Value" 
// 
// Also, for "reference" keys, the reference indicator (R) needs to be removed. 
// Therefore, the output from case #4, above, would be: 
//    ClassName.Key1="root\cimv2:RefClass.Key="RefValue"" 
// 
// ///////////////////////////////////////////////////////////////////////////
String WMIBaseProvider::getObjectName( const CIMObjectPath& objectName)
{
	String sObjName;
	String sObjNameLower;	
	bool bHaveReference = false;
	
	PEG_METHOD_ENTER(TRC_WMIPROVIDER,"WMIBaseProvider::getObjectName()");

	sObjName = objectName.toString();			
	sObjNameLower = sObjName;
	sObjNameLower.toLower();
		
	Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3,
		"WMIBaseProvider::getObjectName() - ObjectName: %s", 
        sObjName.getCString()); 		

	Uint32 pos;

	// 1. if Object name initiates with a hostname then remove it
	if ((sObjName.subString(0, 4) != "root") && 
        (sObjNameLower.subString(0, 2) != "//") && 
        (sObjNameLower.subString(0, 2) != "\\\\"))
	{
		pos = sObjNameLower.find("root");

		if (sObjNameLower.find("=") > pos) {
				
		    if (PEG_NOT_FOUND != pos)
		    {
			    sObjName.remove(0, pos);
     			sObjNameLower.remove(0, pos);
		    }
        } 
    }

	//2. Remove the machine name and port if it exists
	if ((sObjNameLower.subString(0, 2) == "//") || 
        (sObjNameLower.subString(0, 2) == "\\\\"))
	{			
		pos = sObjNameLower.find("root");
		
		if (PEG_NOT_FOUND != pos)
		{
			sObjName.remove(0, pos);
			sObjNameLower.remove(0, pos);
		}

		//3. After ensuring that all stuff before root was removed,
		//   get the class/instance name.
		pos = sObjName.find(qString(Q_COLON));
			
		if (PEG_NOT_FOUND != pos)
		{			
			sObjName.remove(0, pos + 1);	
		}
	}
	else
	{		
		//   get the class/instance name.
		if (sObjNameLower.subString(0, 4) == "root")	
		{
			pos = sObjName.find(qString(Q_COLON));
			
			if (PEG_NOT_FOUND != pos)
			{			
				sObjName.remove(0, pos + 1);	
			}
		}
	}

	//4. Check if has =R".." for a reference instance and
	//	if so, remove the R
	//Uint32 pos = sObjName.find(qString(Q_REF_KEY));
	pos = sObjName.find(qString(Q_REF_KEY));
	bHaveReference = (PEG_NOT_FOUND != pos);

	if (bHaveReference)
	{
		while (PEG_NOT_FOUND != pos)
		{
			sObjName.remove(pos + 1, 1);	//removing R"
			pos = sObjName.find(qString(Q_REF_KEY));
		}
	}

	Tracer::trace(TRC_WMIPROVIDER, Tracer::LEVEL3,
		"WMIBaseProvider::getObjectName() - ObjectName: %s", 
        sObjName.getCString()); 		
	
	PEG_METHOD_EXIT();

	return sObjName;
}
Example #25
0
void HHVM_FUNCTION(header, const String& str, bool replace /* = true */,
                   int http_response_code /* = 0 */) {
  if (HHVM_FN(headers_sent)()) {
    raise_warning("Cannot modify header information - headers already sent");
  }

  String header = f_rtrim(str);

  // new line safety check
  // NOTE: PHP actually allows "\n " and "\n\t" to fall through. Is that bad
  // for security?
  if (header.find('\n') >= 0 || header.find('\r') >= 0) {
    raise_warning("Header may not contain more than a single header, "
                  "new line detected");
    return;
  }

  Transport *transport = g_context->getTransport();
  if (transport && header.size()) {
    const char *header_line = header.data();

    // handle single line of status code
    if (header.size() >= 5 && strncasecmp(header_line, "HTTP/", 5) == 0) {
      int code = 200;
      const char *reason = nullptr;
      for (const char *ptr = header_line; *ptr; ptr++) {
        if (*ptr == ' ' && *(ptr + 1) != ' ') {
          code = atoi(ptr + 1);
          for (ptr++; *ptr; ptr++) {
            if (*ptr == ' ' && *(ptr + 1) != ' ') {
              reason = ptr + 1;
              break;
            }
          }
          break;
        }
      }
      if (code) {
        transport->setResponse(code, reason);
      }
      return;
    }

    const char *colon_offset = strchr(header_line, ':');
    String newHeader;
    if (colon_offset) {
      if (!strncasecmp(header_line, "Content-Type",
                       colon_offset - header_line)) {
        const char *ptr = colon_offset+1, *mimetype = NULL;
        while (*ptr == ' ') ptr++;
        mimetype = ptr;
        if (strncmp(mimetype, "text/", 5) == 0 &&
            strstr(mimetype, "charset=") == NULL) {
          newHeader = header + ";charset=utf-8";
        }
      }
    }
    if (replace) {
      transport->replaceHeader(newHeader.empty() ? header : newHeader);
    } else {
      transport->addHeader(newHeader.empty() ? header : newHeader);
    }
    if (http_response_code) {
      transport->setResponse(http_response_code,
                             "explicit_header_response_code");
    }
  }
}
Example #26
0
Variant php_mysql_do_connect_on_link(
    std::shared_ptr<MySQL> mySQL,
    String server,
    String username,
    String password,
    String database,
    int client_flags,
    bool persistent,
    bool async,
    int connect_timeout_ms,
    int query_timeout_ms,
    const Array *conn_attrs,
    std::shared_ptr<SSLOptionsProviderBase> ssl_provider) {
  if (connect_timeout_ms < 0) {
    connect_timeout_ms = mysqlExtension::ConnectTimeout;
  }
  if (query_timeout_ms < 0) {
    query_timeout_ms = MySQL::GetDefaultReadTimeout();
  }
  if (server.empty()) server = MySQL::GetDefaultServer();
  if (username.empty()) username = MySQL::GetDefaultUsername();
  if (password.empty()) password = MySQL::GetDefaultPassword();
  if (database.empty()) database = MySQL::GetDefaultDatabase();

  // server format: hostname[:port][:/path/to/socket]
  // ipv6 hostname:port is of the form [1:2:3:4:5]:port
  String host, socket;
  int port;
  int savePersistent = false;

  auto slash_pos = server.find('/');
  if (slash_pos != std::string::npos) {
    socket = server.substr(slash_pos);
    server = server.substr(0, slash_pos - 1);
  }

  HostURL hosturl(std::string(server), MySQL::GetDefaultPort());
  if (hosturl.isValid()) {
    host = hosturl.getHost();
    port = hosturl.getPort();
  } else {
    host = server;
    port = MySQL::GetDefaultPort();
  }

  if (socket.empty()) {
    socket = MySQL::GetDefaultSocket();
  }

  if (MySQL::IsAllowPersistent() &&
      MySQL::GetCurrentNumPersistent() < MySQL::GetMaxNumPersistent() &&
      persistent) {
    auto p_mySQL = MySQL::GetPersistent(host, port, socket, username,
                                        password, client_flags);

    if (p_mySQL != nullptr) {
      mySQL = p_mySQL;
    } else {
      savePersistent = true;
    }
  }

  if (mySQL == nullptr) {
    mySQL = std::make_shared<MySQL>(
        host.c_str(),
        port,
        username.c_str(),
        password.c_str(),
        database.c_str());
  }

  // Set any connection attributes
  if (conn_attrs != nullptr && conn_attrs->size() > 0) {
    mysql_set_conn_attrs(mySQL, conn_attrs);
  }

  // set SSL Options
  mysql_set_ssl_options(mySQL, ssl_provider);

  if (mySQL->getState() == MySQLState::INITED) {
    if (async) {
#ifdef FACEBOOK
      if (!mySQL->async_connect(host, port, socket, username, password,
                                database)) {
        MySQL::SetDefaultConn(mySQL); // so we can report errno by mysql_errno()
        mySQL->setLastError("mysql_real_connect_nonblocking_init");
        return false;
      }
#else
      throw_not_implemented("mysql_async_connect_start");
#endif
    } else {
      if (!mySQL->connect(host, port, socket, username, password,
                          database, client_flags, connect_timeout_ms)) {
        MySQL::SetDefaultConn(mySQL); // so we can report errno by mysql_errno()
        mySQL->setLastError("mysql_connect");
        return false;
      }
    }
  } else {
    if (!MySQL::IsAllowReconnect()) {
      raise_warning("MySQL: Reconnects are not allowed");
      return false;
    }
    if (!mySQL->reconnect(host, port, socket, username, password,
                          database, client_flags, connect_timeout_ms)) {
      MySQL::SetDefaultConn(mySQL); // so we can report errno by mysql_errno()
      mySQL->setLastError("mysql_connect");
      return false;
    }
  }

  // store SSL Session
  mysql_store_ssl_session(mySQL, ssl_provider);

  if (savePersistent) {
    MySQL::SetPersistent(
        host, port, socket, username, password, client_flags, mySQL);
    MySQL::SetCurrentNumPersistent(MySQL::GetCurrentNumPersistent() + 1);
  }
  MySQL::SetDefaultConn(mySQL);
  return Variant(req::make<MySQLResource>(mySQL));
}
Example #27
0
// FIXME: This function should not deal with url or serviceType!
void HTMLObjectElement::parametersForPlugin(Vector<String>& paramNames, Vector<String>& paramValues, String& url, String& serviceType)
{
    HashSet<StringImpl*, ASCIICaseInsensitiveHash> uniqueParamNames;
    String urlParameter;

    // Scan the PARAM children and store their name/value pairs.
    // Get the URL and type from the params if we don't already have them.
    for (auto& param : childrenOfType<HTMLParamElement>(*this)) {
        String name = param.name();
        if (name.isEmpty())
            continue;

        uniqueParamNames.add(name.impl());
        paramNames.append(param.name());
        paramValues.append(param.value());

        // FIXME: url adjustment does not belong in this function.
        if (url.isEmpty() && urlParameter.isEmpty() && (equalLettersIgnoringASCIICase(name, "src") || equalLettersIgnoringASCIICase(name, "movie") || equalLettersIgnoringASCIICase(name, "code") || equalLettersIgnoringASCIICase(name, "url")))
            urlParameter = stripLeadingAndTrailingHTMLSpaces(param.value());
        // FIXME: serviceType calculation does not belong in this function.
        if (serviceType.isEmpty() && equalLettersIgnoringASCIICase(name, "type")) {
            serviceType = param.value();
            size_t pos = serviceType.find(';');
            if (pos != notFound)
                serviceType = serviceType.left(pos);
        }
    }

    // When OBJECT is used for an applet via Sun's Java plugin, the CODEBASE attribute in the tag
    // points to the Java plugin itself (an ActiveX component) while the actual applet CODEBASE is
    // in a PARAM tag. See <http://java.sun.com/products/plugin/1.2/docs/tags.html>. This means
    // we have to explicitly suppress the tag's CODEBASE attribute if there is none in a PARAM,
    // else our Java plugin will misinterpret it. [4004531]
    String codebase;
    if (MIMETypeRegistry::isJavaAppletMIMEType(serviceType)) {
        codebase = "codebase";
        uniqueParamNames.add(codebase.impl()); // pretend we found it in a PARAM already
    }

    // Turn the attributes of the <object> element into arrays, but don't override <param> values.
    if (hasAttributes()) {
        for (const Attribute& attribute : attributesIterator()) {
            const AtomicString& name = attribute.name().localName();
            if (!uniqueParamNames.contains(name.impl())) {
                paramNames.append(name.string());
                paramValues.append(attribute.value().string());
            }
        }
    }

    mapDataParamToSrc(paramNames, paramValues);

    // HTML5 says that an object resource's URL is specified by the object's data
    // attribute, not by a param element. However, for compatibility, allow the
    // resource's URL to be given by a param named "src", "movie", "code" or "url"
    // if we know that resource points to a plug-in.
#if PLATFORM(IOS)
    if (shouldNotPerformURLAdjustment())
        return;
#endif

    if (url.isEmpty() && !urlParameter.isEmpty()) {
        SubframeLoader& loader = document().frame()->loader().subframeLoader();
        if (loader.resourceWillUsePlugin(urlParameter, serviceType))
            url = urlParameter;
    }
}
static bool isSupported(const String& constraint)
{
    return notFound != constraint.find("_and_supported_");
}
Example #29
0
	//-----------------------------------------------------------------------
	vector< String >::type StringUtil::tokenise( const String& str, const String& singleDelims, const String& doubleDelims, unsigned int maxSplits)
	{
        vector<String>::type ret;
        // Pre-allocate some space for performance
        ret.reserve(maxSplits ? maxSplits+1 : 10);    // 10 is guessed capacity for most case

        unsigned int numSplits = 0;
		String delims = singleDelims + doubleDelims;

		// Use STL methods 
        size_t start, pos;
		char curDoubleDelim = 0;
        start = 0;
        do 
        {
			if (curDoubleDelim != 0)
			{
				pos = str.find(curDoubleDelim, start);
			}
			else
			{
				pos = str.find_first_of(delims, start);
			}

            if (pos == start)
            {
				char curDelim = str.at(pos);
				if (doubleDelims.find_first_of(curDelim) != String::npos)
				{
					curDoubleDelim = curDelim;
				}
                // Do nothing
                start = pos + 1;
            }
            else if (pos == String::npos || (maxSplits && numSplits == maxSplits))
            {
				if (curDoubleDelim != 0)
				{
					//Missing closer. Warn or throw exception?
				}
                // Copy the rest of the string
                ret.push_back( str.substr(start) );
                break;
            }
            else
            {
				if (curDoubleDelim != 0)
				{
					curDoubleDelim = 0;
				}

				// Copy up to delimiter
				ret.push_back( str.substr(start, pos - start) );
				start = pos + 1;
            }
			if (curDoubleDelim == 0)
			{
				// parse up to next real data
				start = str.find_first_not_of(singleDelims, start);
			}
            
            ++numSplits;

        } while (pos != String::npos);

        return ret;
    }
Example #30
0
ProcessStatus::ProcessStatus(pid_t processId)
{
#ifndef __linux
	struct kinfo_proc* proc;
	int mib[4];
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PID;
	mib[3] = processId;
	size_t sz = 0;
	if (::sysctl(mib, 4, NULL, &sz, NULL, 0) == -1)
		FTL_SYSTEM_EXCEPTION;
	proc = (kinfo_proc*)ftl::malloc(sz);
	mem::clr(proc, sz);
	if (::sysctl(mib, 4, proc, &sz, NULL, 0) == -1)
		FTL_SYSTEM_EXCEPTION;
	processId_ = proc->kp_proc.p_pid;
	parentProcessId_ = proc->kp_eproc.e_ppid;
	processGroupId_ = proc->kp_eproc.e_pgid;
	foregroundProcessGroupId_ = proc->kp_eproc.e_tpgid;
	/*const int ttyNameSize = 256;
	char ttyName[ttyNameSize];
	terminalName_ = devname_r(proc->kp_eproc.e_tdev, S_IFCHR, ttyName, ttyNameSize);*/
	loginName_ = User(proc->kp_eproc.e_pcred.p_ruid).loginName();
	commandName_ = proc->kp_proc.p_comm;
	processStatus_ = proc->kp_proc.p_stat;
	if (processStatus_ == SIDL) processStatus_ = 'W';
	else if (processStatus_ == SRUN) processStatus_ = 'R';
	#ifdef SONPROC
	else if (processStatus_ == SONPROC) processStatus_ = 'R';
	#endif
	#ifdef __MACH__
	else if (processStatus_ == SSLEEP) processStatus_ = (proc->kp_proc.sigwait) ? 'S' : 'D';
	#else
	else if (processStatus_ == SSLEEP) processStatus_ = 'S';
	#endif
	else if (processStatus_ == SSTOP) processStatus_ = 'T';
	else if (processStatus_ == SZOMB) processStatus_ = 'Z';
	#ifdef SDEAD
	else if (processStatus_ == SDEAD) processStatus_ = 'Z';
	#endif
	else processStatus_ = '?';
	ftl::free(proc);
#else
	String path = Format("/proc/%%/stat") << processId;
	Ref<File, Owner> file = new File(path);
	file->open(File::Read);
	Ref<LineSource, Owner> source = new LineSource(file);
	String line = source->readLine();
	{
		// extract command name first, because it may contain whitespace
		int i0 = line->find('(') + 1, i1 = line->find(')');
		commandName_ = line->copy(i0, i1);
		for (int i = i0; i < i1; ++i)
			line->set(i, 'x');
	}
	Ref<StringList, Owner> parts = line.split(" ");
	processId_ = parts->at(0).toInt();
	parentProcessId_ = parts->at(3).toInt();
	processGroupId_ = parts->at(4).toInt();
	foregroundProcessGroupId_ = parts->at(7).toInt();
	/*{
		int code = parts->get(6).toInt();
		int major = (code >> 8) & 0xFF;
		int minor = (code & 0xFF) | ((code >> 20) << 8);
		 // interpretation according to lanana.org
		if (major == 4)
			terminalName_ = Format("tty%%") << minor;
		else if ((136 <= major) && (major <= 143))
			terminalName_ = Format("pts/%%") << minor;
		else if (major == 3)
			terminalName_ = Format("ttyp%%") << minor;
	}*/
	loginName_ = User(FileStatus(path).ownerId()).loginName();
	processStatus_ = parts->at(2)->get(0);
	file->close();
#endif
}