static Vector<OwnArrayPtr<char>> createArgsArray(const String& prefix, const String& executablePath, const String& socket, const String& pluginPath)
{
    ASSERT(!executablePath.isEmpty());
    ASSERT(!socket.isEmpty());

    Vector<String> splitArgs;
    prefix.split(' ', splitArgs);

    splitArgs.append(executablePath);
    splitArgs.append(socket);
    if (!pluginPath.isEmpty())
        splitArgs.append(pluginPath);

    Vector<OwnArrayPtr<char>> args;
    args.resize(splitArgs.size() + 1); // Extra room for null.

    size_t numArgs = splitArgs.size();
    for (size_t i = 0; i < numArgs; ++i) {
        CString param = splitArgs[i].utf8();
        args[i] = adoptArrayPtr(new char[param.length() + 1]); // Room for the terminating null coming from the CString.
        strncpy(args[i].get(), param.data(), param.length() + 1); // +1 here so that strncpy copies the ending null.
    }
    // execvp() needs the pointers' array to be null-terminated.
    args[numArgs] = nullptr;

    return args;
}
Example #2
0
void Bridge::send(const CString& message)
{
    ASSERT(m_peer);
    OwnPtr<Vector<char>> data = adoptPtr(new Vector<char>(message.length()));
    if (message.length())
        memcpy(data->data(), static_cast<const char*>(message.data()), message.length());

    m_loaderProxy->postTaskToLoader(createCrossThreadTask(&Peer::sendTextAsCharVector, m_peer.get(), data.release()));
}
Example #3
0
void TAccount::setFlag(const CString& pFlagName, const CString& pFlagValue)
{
	if (server->getSettings()->getBool("cropflags", true))
	{
		int totalLength = pFlagName.length() + 1 + pFlagValue.length();
		int fixedLength = 223 - 1 - pFlagName.length();
		flagList[pFlagName] = pFlagValue.subString(0, fixedLength);
	}
	else flagList[pFlagName] = pFlagValue;
}
Example #4
0
void handleDataURL(ResourceHandle* handle)
{
    ASSERT(handle->firstRequest().url().protocolIs("data"));
    String url = handle->firstRequest().url().string();

    int index = url.find(',');
    if (index == -1) {
        handle->client()->cannotShowURL(handle);
        return;
    }

    String mediaType = url.substring(5, index - 5);
    String data = url.substring(index + 1);

    bool base64 = mediaType.endsWith(";base64", false);
    if (base64)
        mediaType = mediaType.left(mediaType.length() - 7);

    if (mediaType.isEmpty())
        mediaType = "text/plain";

    String mimeType = extractMIMETypeFromMediaType(mediaType);
    String charset = extractCharsetFromMediaType(mediaType);

    if (charset.isEmpty())
        charset = "US-ASCII";

    ResourceResponse response;
    response.setMimeType(mimeType);
    response.setTextEncodingName(charset);
    response.setURL(handle->firstRequest().url());

    if (base64) {
        data = decodeURLEscapeSequences(data);
        handle->client()->didReceiveResponse(handle, response);

        Vector<char> out;
        if (base64Decode(data, out, IgnoreWhitespace) && out.size() > 0) {
            response.setExpectedContentLength(out.size());
            handle->client()->didReceiveData(handle, out.data(), out.size(), 0);
        }
    } else {
        TextEncoding encoding(charset);
        data = decodeURLEscapeSequences(data, encoding);
        handle->client()->didReceiveResponse(handle, response);

        CString encodedData = encoding.encode(data.characters(), data.length(), URLEncodedEntitiesForUnencodables);
        response.setExpectedContentLength(encodedData.length());
        if (encodedData.length())
            handle->client()->didReceiveData(handle, encodedData.data(), encodedData.length(), 0);
    }

    handle->client()->didFinishLoading(handle, 0);
}
Example #5
0
void PasteboardHelper::fillSelectionData(GtkSelectionData* selectionData, guint info, DataObjectGtk* dataObject)
{
    if (info == TargetTypeText)
        gtk_selection_data_set_text(selectionData, dataObject->text().utf8().data(), -1);

    else if (info == TargetTypeMarkup) {
        // Some Linux applications refuse to accept pasted markup unless it is
        // prefixed by a content-type meta tag.
        CString markup = String(gMarkupPrefix + dataObject->markup()).utf8();
        gtk_selection_data_set(selectionData, markupAtom, 8,
                               reinterpret_cast<const guchar*>(markup.data()), markup.length());

    } else if (info == TargetTypeURIList) {
        CString uriList = dataObject->uriList().utf8();
        gtk_selection_data_set(selectionData, uriListAtom, 8,
                               reinterpret_cast<const guchar*>(uriList.data()), uriList.length());

    } else if (info == TargetTypeNetscapeURL && dataObject->hasURL()) {
        String url(dataObject->url());
        String result(url);
        result.append("\n");

        if (dataObject->hasText())
            result.append(dataObject->text());
        else
            result.append(url);

        GUniquePtr<gchar> resultData(g_strdup(result.utf8().data()));
        gtk_selection_data_set(selectionData, netscapeURLAtom, 8,
                               reinterpret_cast<const guchar*>(resultData.get()), strlen(resultData.get()));

    } else if (info == TargetTypeImage)
        gtk_selection_data_set_pixbuf(selectionData, dataObject->image());

    else if (info == TargetTypeSmartPaste)
        gtk_selection_data_set_text(selectionData, "", -1);

    else if (info == TargetTypeUnknown) {
        GVariantBuilder builder;
        g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);

        auto types = dataObject->unknownTypes();
        auto end = types.end();
        for (auto it = types.begin(); it != end; ++it) {
            GUniquePtr<gchar> dictItem(g_strdup_printf("{'%s', '%s'}", it->key.utf8().data(), it->value.utf8().data()));
            g_variant_builder_add_parsed(&builder, dictItem.get());
        }

        GRefPtr<GVariant> variant = g_variant_builder_end(&builder);
        GUniquePtr<gchar> serializedVariant(g_variant_print(variant.get(), TRUE));
        gtk_selection_data_set(selectionData, unknownAtom, 1, reinterpret_cast<const guchar*>(serializedVariant.get()), strlen(serializedVariant.get()));
    }
}
Example #6
0
void CIRCSock::SendAltNick(const CString& sBadNick) {
    const CString& sLastNick = m_Nick.GetNick();

    // We don't know the maximum allowed nick length yet, but we know which
    // nick we sent last. If sBadNick is shorter than that, we assume the
    // server truncated our nick.
    if (sBadNick.length() < sLastNick.length())
        m_uMaxNickLen = (unsigned int)sBadNick.length();

    unsigned int uMax = m_uMaxNickLen;

    const CString& sConfNick = m_pNetwork->GetNick();
    const CString& sAltNick  = m_pNetwork->GetAltNick();
    CString sNewNick = sConfNick.Left(uMax - 1);

    if (sLastNick.Equals(sConfNick)) {
        if ((!sAltNick.empty()) && (!sConfNick.Equals(sAltNick))) {
            sNewNick = sAltNick;
        } else {
            sNewNick += "-";
        }
    } else if (sLastNick.Equals(sAltNick) && !sAltNick.Equals(sNewNick + "-")) {
        sNewNick += "-";
    } else if (sLastNick.Equals(sNewNick + "-") && !sAltNick.Equals(sNewNick + "|")) {
        sNewNick += "|";
    } else if (sLastNick.Equals(sNewNick + "|") && !sAltNick.Equals(sNewNick + "^")) {
        sNewNick += "^";
    } else if (sLastNick.Equals(sNewNick + "^") && !sAltNick.Equals(sNewNick + "a")) {
        sNewNick += "a";
    } else {
        char cLetter = 0;
        if (sBadNick.empty()) {
            m_pNetwork->PutUser("No free nick available");
            Quit();
            return;
        }

        cLetter = sBadNick.back();

        if (cLetter == 'z') {
            m_pNetwork->PutUser("No free nick found");
            Quit();
            return;
        }

        sNewNick = sConfNick.Left(uMax -1) + ++cLetter;
        if (sNewNick.Equals(sAltNick))
            sNewNick = sConfNick.Left(uMax -1) + ++cLetter;
    }
    PutIRC("NICK " + sNewNick);
    m_Nick.SetNick(sNewNick);
}
Example #7
0
static void expectMD5(CString input, CString expected)
{
    MD5 md5;
    md5.addBytes(reinterpret_cast<const uint8_t*>(input.data()), input.length());
    MD5::Digest digest;
    md5.checksum(digest);
    char* buf = 0;
    CString actual = CString::newUninitialized(32, buf);
    for (size_t i = 0; i < MD5::hashSize; i++, buf += 2)
        snprintf(buf, 3, "%02x", digest[i]);

    ASSERT_EQ(expected.length(), actual.length());
    ASSERT_STREQ(expected.data(), actual.data());
}
Example #8
0
// 16 variables may be a bit of over kill, but hey, it's only code.
unsigned CIniFile::GetValueV( const CString& keyname, const CString& valuename, char *format,
            void *v1, void *v2, void *v3, void *v4,
              void *v5, void *v6, void *v7, void *v8,
              void *v9, void *v10, void *v11, void *v12,
              void *v13, void *v14, void *v15, void *v16)
{
  CString   value;
  // va_list  args;
  unsigned nVals;


  value = GetValue( keyname, valuename);
  if ( !value.length())
    return false;
  // Why is there not vsscanf() function. Linux man pages say that there is
  // but no compiler I've seen has it defined. Bummer!
  //
  // va_start( args, format);
  // nVals = vsscanf( value.c_str(), format, args);
  // va_end( args);

  nVals = sscanf( value.c_str(), format,
      v1, v2, v3, v4, v5, v6, v7, v8,
      v9, v10, v11, v12, v13, v14, v15, v16);

  return nVals;
}
PassRefPtr<FormData> WMLGoElement::createFormData(const CString& boundary)
{
    CString key;
    CString value;

    Vector<char> encodedData;
    TextEncoding encoding = FormDataBuilder::encodingFromAcceptCharset(m_formAttributes.acceptCharset(), document()).encodingForFormSubmission();

    Vector<WMLPostfieldElement*>::iterator it = m_postfieldElements.begin();
    Vector<WMLPostfieldElement*>::iterator end = m_postfieldElements.end();

    RefPtr<FormData> result = FormData::create();
    for (; it != end; ++it) {
        (*it)->encodeData(encoding, key, value);

        if (m_formAttributes.isMultiPartForm()) {
            Vector<char> header;
            FormDataBuilder::beginMultiPartHeader(header, boundary, key);
            FormDataBuilder::finishMultiPartHeader(header);
            result->appendData(header.data(), header.size());

            if (size_t dataSize = value.length())
                result->appendData(value.data(), dataSize);

            result->appendData("\r\n", 2);
        } else
            FormDataBuilder::addKeyValuePairAsFormData(encodedData, key, value);
    }

    if (m_formAttributes.isMultiPartForm())
        FormDataBuilder::addBoundaryToMultiPartHeader(encodedData, boundary, true);

    result->appendData(encodedData.data(), encodedData.size());
    return result;
}
Example #10
0
bool makeAllDirectories(const String& path)
{
    CString fullPath = fileSystemRepresentation(path);
    if (!access(fullPath.data(), F_OK))
        return true;

    char* p = fullPath.mutableData() + 1;
    int length = fullPath.length();

    if(p[length - 1] == '/')
        p[length - 1] = '\0';
    for (; *p; ++p)
        if (*p == '/') {
            *p = '\0';
            if (access(fullPath.data(), F_OK))
                if (mkdir(fullPath.data(), S_IRWXU))
                    return false;
            *p = '/';
        }
    if (access(fullPath.data(), F_OK))
        if (mkdir(fullPath.data(), S_IRWXU))
            return false;

    return true;
}
void WebInspectorServer::buildPageList(Vector<char>& data, String& contentType)
{
    StringBuilder builder;
    builder.appendLiteral("[ ");
    ClientMap::iterator end = m_clientMap.end();
    for (ClientMap::iterator it = m_clientMap.begin(); it != end; ++it) {
        WebPageProxy* webPage = it->value->page();
        if (it != m_clientMap.begin())
            builder.appendLiteral(", ");
        builder.appendLiteral("{ \"id\": ");
        builder.appendNumber(it->key);
        builder.appendLiteral(", \"title\": \"");
        builder.append(webPage->pageTitle());
        builder.appendLiteral("\", \"url\": \"");
        builder.append(webPage->activeURL());
        builder.appendLiteral("\", \"inspectorUrl\": \"");
        builder.appendLiteral("/inspector.html?page=");
        builder.appendNumber(it->key);
        builder.appendLiteral("\" }");
    }
    builder.appendLiteral(" ]");
    CString cstr = builder.toString().utf8();
    data.append(cstr.data(), cstr.length());
    contentType = "application/json; charset=utf-8";
}
Example #12
0
Vector<String> listDirectory(const String& path, const String& filter)
{
    Vector<String> entries;
    CString cpath = path.utf8();
    CString cfilter = filter.utf8();
    char filePath[PATH_MAX];
    char* fileName;
    size_t fileNameSpace;
    DIR* dir;

    if (cpath.length() + NAME_MAX >= sizeof(filePath))
        return entries;
    // loop invariant: directory part + '/'
    memcpy(filePath, cpath.data(), cpath.length());
    fileName = filePath + cpath.length();
    if (cpath.length() > 0 && filePath[cpath.length() - 1] != '/') {
        fileName[0] = '/';
        fileName++;
    }
    fileNameSpace = sizeof(filePath) - (fileName - filePath) - 1;

    dir = opendir(cpath.data());
    if (!dir)
        return entries;

    struct dirent* de;
    while (de = readdir(dir)) {
        size_t nameLen;
        if (de->d_name[0] == '.') {
            if (de->d_name[1] == '\0')
                continue;
            if (de->d_name[1] == '.' && de->d_name[2] == '\0')
                continue;
        }
        if (fnmatch(cfilter.data(), de->d_name, 0))
            continue;

        nameLen = strlen(de->d_name);
        if (nameLen >= fileNameSpace)
            continue; // maybe assert? it should never happen anyway...

        memcpy(fileName, de->d_name, nameLen + 1);
        entries.append(filePath);
    }
    closedir(dir);
    return entries;
}
Example #13
0
File: User.cpp Project: johnfb/znc
bool CUser::SetStatusPrefix(const CString& s) {
	if ((!s.empty()) && (s.length() < 6) && (s.find(' ') == CString::npos)) {
		m_sStatusPrefix = (s.empty()) ? "*" : s;
		return true;
	}

	return false;
}
Example #14
0
void PluginStream::sendJavaScriptStream(const KURL& requestURL, const CString& resultString)
{
    didReceiveResponse(0, ResourceResponse(requestURL, "text/plain", resultString.length(), "", ""));

    if (m_streamState == StreamStopped)
        return;

    if (!resultString.isNull()) {
        didReceiveData(0, resultString.data(), resultString.length());
        if (m_streamState == StreamStopped)
            return;
    }

    m_loader = 0;

    destroyStream(resultString.isNull() ? NPRES_NETWORK_ERR : NPRES_DONE);
}
Example #15
0
void DateTimeChooserImpl::writeDocument(WebCore::DocumentWriter& writer)
{
    WebCore::DateComponents date;
    date.setMillisecondsSinceEpochForDate(m_parameters.minimum);
    String minString = date.toString();
    date.setMillisecondsSinceEpochForDate(m_parameters.maximum);
    String maxString = date.toString();
    String stepString = String::number(m_parameters.step);

    addString("<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", writer);
    writer.addData(WebCore::pickerCommonCss, sizeof(WebCore::pickerCommonCss));
    writer.addData(WebCore::calendarPickerCss, sizeof(WebCore::calendarPickerCss));
    CString extraStyle = WebCore::RenderTheme::defaultTheme()->extraCalendarPickerStyleSheet();
    if (extraStyle.length())
        writer.addData(extraStyle.data(), extraStyle.length());
    addString("</style></head><body><div id=main>Loading...</div><script>\n"
               "window.dialogArguments = {\n", writer);
    addProperty("min", minString, writer);
    addProperty("max", maxString, writer);
    addProperty("step", stepString, writer);
    addProperty("required", m_parameters.required, writer);
    addProperty("currentValue", m_parameters.currentValue, writer);
    addProperty("locale", WebCore::defaultLanguage(), writer);
    addProperty("todayLabel", Platform::current()->queryLocalizedString(WebLocalizedString::CalendarToday), writer);
    addProperty("clearLabel", Platform::current()->queryLocalizedString(WebLocalizedString::CalendarClear), writer);
    addProperty("weekStartDay", WebCore::firstDayOfWeek(), writer);
    addProperty("monthLabels", WebCore::monthLabels(), writer);
    addProperty("dayLabels", WebCore::weekDayShortLabels(), writer);
    Direction dir = direction(WebCore::monthLabels()[0][0]);
    addProperty("isRTL", dir == RightToLeft || dir == RightToLeftArabic, writer);
    if (m_parameters.suggestionValues.size()) {
        addProperty("inputWidth", static_cast<unsigned>(m_parameters.anchorRectInRootView.width()), writer);
        addProperty("suggestionValues", m_parameters.suggestionValues, writer);
        addProperty("localizedSuggestionValues", m_parameters.localizedSuggestionValues, writer);
        addProperty("suggestionLabels", m_parameters.suggestionLabels, writer);
        addProperty("showOtherDateEntry", m_parameters.type == WebCore::InputTypeNames::date(), writer);
        addProperty("otherDateLabel", Platform::current()->queryLocalizedString(WebLocalizedString::OtherDateLabel), writer);
    }
    addString("}\n", writer);

    writer.addData(WebCore::pickerCommonJs, sizeof(WebCore::pickerCommonJs));
    writer.addData(WebCore::calendarPickerJs, sizeof(WebCore::calendarPickerJs));
    addString("</script></body>\n", writer);
}
Example #16
0
void CIRCSock::ParseISupport(const CMessage& Message) {
    const VCString vsParams = Message.GetParams();

    for (size_t i = 1; i < vsParams.size() - 1; ++i) {
        const CString& sParam = vsParams[i];
        CString sName = sParam.Token(0, false, "=");
        CString sValue = sParam.Token(1, true, "=");

        if (0 < sName.length() && ':' == sName[0]) {
            break;
        }

        m_mISupport[sName] = sValue;

        if (sName.Equals("PREFIX")) {
            CString sPrefixes = sValue.Token(1, false, ")");
            CString sPermModes = sValue.Token(0, false, ")");
            sPermModes.TrimLeft("(");

            if (!sPrefixes.empty() && sPermModes.size() == sPrefixes.size()) {
                m_sPerms = sPrefixes;
                m_sPermModes = sPermModes;
            }
        } else if (sName.Equals("CHANTYPES")) {
            m_pNetwork->SetChanPrefixes(sValue);
        } else if (sName.Equals("NICKLEN")) {
            unsigned int uMax = sValue.ToUInt();

            if (uMax) {
                m_uMaxNickLen = uMax;
            }
        } else if (sName.Equals("CHANMODES")) {
            if (!sValue.empty()) {
                m_mueChanModes.clear();

                for (unsigned int a = 0; a < 4; a++) {
                    CString sModes = sValue.Token(a, false, ",");

                    for (unsigned int b = 0; b < sModes.size(); b++) {
                        m_mueChanModes[sModes[b]] = (EChanModeArgs) a;
                    }
                }
            }
        } else if (sName.Equals("NAMESX")) {
            if (m_bNamesx)
                continue;
            m_bNamesx = true;
            PutIRC("PROTOCTL NAMESX");
        } else if (sName.Equals("UHNAMES")) {
            if (m_bUHNames)
                continue;
            m_bUHNames = true;
            PutIRC("PROTOCTL UHNAMES");
        }
    }
}
Example #17
0
	virtual EModRet OnUserRaw(CString& sLine)
	{
		CString sCmd = sLine.Token(0).AsUpper();

		if (!m_pNetwork->GetIRCSock())
			return CONTINUE;

		if (sCmd.Equals("MODE")) {
			// Check if this is a mode request that needs to be handled

			// If there are arguments to a mode change,
			// we must not route it.
			if (!sLine.Token(3, true).empty())
				return CONTINUE;

			// Grab the mode change parameter
			CString sMode = sLine.Token(2);

			// If this is a channel mode request, znc core replies to it
			if (sMode.empty())
				return CONTINUE;

			// Check if this is a mode change or a specific
			// mode request (the later needs to be routed).
			sMode.TrimPrefix("+");
			if (sMode.length() != 1)
				return CONTINUE;

			// Now just check if it's one of the supported modes
			switch (sMode[0]) {
			case 'I':
			case 'b':
			case 'e':
				break;
			default:
				return CONTINUE;
			}

			// Ok, this looks like we should route it.
			// Fall through to the next loop
		}

		for (size_t i = 0; vRouteReplies[i].szRequest != NULL; i++) {
			if (vRouteReplies[i].szRequest == sCmd) {
				struct queued_req req = {
					sLine, vRouteReplies[i].vReplies
				};
				m_vsPending[m_pClient].push_back(req);
				SendRequest();

				return HALTCORE;
			}
		}

		return CONTINUE;
	}
Example #18
0
File: Modules.cpp Project: md-5/znc
ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath, bool &bVersionMismatch,
		CModInfo& Info, CString& sRetMsg) {
	// Some sane defaults in case anything errors out below
	bVersionMismatch = false;
	sRetMsg.clear();

	for (unsigned int a = 0; a < sModule.length(); a++) {
		if (((sModule[a] < '0') || (sModule[a] > '9')) && ((sModule[a] < 'a') || (sModule[a] > 'z')) && ((sModule[a] < 'A') || (sModule[a] > 'Z')) && (sModule[a] != '_')) {
			sRetMsg = "Module names can only contain letters, numbers and underscores, [" + sModule + "] is invalid.";
			return NULL;
		}
	}

	// The second argument to dlopen() has a long history. It seems clear
	// that (despite what the man page says) we must include either of
	// RTLD_NOW and RTLD_LAZY and either of RTLD_GLOBAL and RTLD_LOCAL.
	//
	// RTLD_NOW vs. RTLD_LAZY: We use RTLD_NOW to avoid ZNC dying due to
	// failed symbol lookups later on. Doesn't really seem to have much of a
	// performance impact.
	//
	// RTLD_GLOBAL vs. RTLD_LOCAL: If perl is loaded with RTLD_LOCAL and later on
	// loads own modules (which it apparently does with RTLD_LAZY), we will die in a
	// name lookup since one of perl's symbols isn't found. That's worse
	// than any theoretical issue with RTLD_GLOBAL.
	ModHandle p = dlopen((sModPath).c_str(), RTLD_NOW | RTLD_GLOBAL);

	if (!p) {
		// dlerror() returns pointer to static buffer, which may be overwritten very soon with another dl call
		// also it may just return null.
		const char* cDlError = dlerror();
		CString sDlError = cDlError ? cDlError : "Unknown error";
		sRetMsg = "Unable to open module [" + sModule + "] [" + sDlError + "]";
		return NULL;
	}

	typedef bool (*InfoFP)(double, CModInfo&);
	InfoFP ZNCModInfo = (InfoFP) dlsym(p, "ZNCModInfo");

	if (!ZNCModInfo) {
		dlclose(p);
		sRetMsg = "Could not find ZNCModInfo() in module [" + sModule + "]";
		return NULL;
	}

	if (ZNCModInfo(CModule::GetCoreVersion(), Info)) {
		sRetMsg = "";
		bVersionMismatch = false;
	} else {
		bVersionMismatch = true;
		sRetMsg = "Version mismatch, recompile this module.";
	}

	return p;
}
Example #19
0
void ClipboardWin::writeURL(const KURL& kurl, const String& titleStr, Frame*)
{
    if (!m_writableDataObject)
         return;
    WebCore::writeURL(m_writableDataObject.get(), kurl, titleStr, true, true);

    String url = kurl.string();
    ASSERT(url.containsOnlyASCII()); // KURL::string() is URL encoded.

    String fsPath = filesystemPathFromUrlOrTitle(url, titleStr, L".URL", true);
    String contentString("[InternetShortcut]\r\nURL=" + url + "\r\n");
    CString content = contentString.latin1();

    if (fsPath.length() <= 0)
        return;

    HGLOBAL urlFileDescriptor = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR));
    if (!urlFileDescriptor)
        return;

    HGLOBAL urlFileContent = GlobalAlloc(GPTR, content.length());
    if (!urlFileContent) {
        GlobalFree(urlFileDescriptor);
        return;
    }

    FILEGROUPDESCRIPTOR* fgd = static_cast<FILEGROUPDESCRIPTOR*>(GlobalLock(urlFileDescriptor));
    ZeroMemory(fgd, sizeof(FILEGROUPDESCRIPTOR));
    fgd->cItems = 1;
    fgd->fgd[0].dwFlags = FD_FILESIZE;
    fgd->fgd[0].nFileSizeLow = content.length();

    unsigned maxSize = min(fsPath.length(), WTF_ARRAY_LENGTH(fgd->fgd[0].cFileName));
    CopyMemory(fgd->fgd[0].cFileName, fsPath.characters(), maxSize * sizeof(UChar));
    GlobalUnlock(urlFileDescriptor);

    char* fileContents = static_cast<char*>(GlobalLock(urlFileContent));
    CopyMemory(fileContents, content.data(), content.length());
    GlobalUnlock(urlFileContent);

    writeFileToDataObject(m_writableDataObject.get(), urlFileDescriptor, urlFileContent, 0);
}
static void loadDataIntoFrame(Frame* frame, KURL baseUrl, const String& url,
        const String& data) {
    if (baseUrl.isEmpty()) {
        baseUrl = blankURL();
    }
    ResourceRequest request(baseUrl);
    CString cstr = data.utf8();
    RefPtr<WebCore::SharedBuffer> buf = WebCore::SharedBuffer::create(cstr.data(), cstr.length());
    SubstituteData subData(buf, String("text/html"), String("utf-8"),
            KURL(KURL(), url));
    frame->loader()->load(request, subData, false);
}
String WebSocketHandshake::getExpectedWebSocketAccept(const String& secWebSocketKey)
{
    static const char* const webSocketKeyGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    static const size_t sha1HashSize = 20; // FIXME: This should be defined in SHA1.h.
    SHA1 sha1;
    CString keyData = secWebSocketKey.ascii();
    sha1.addBytes(reinterpret_cast<const uint8_t*>(keyData.data()), keyData.length());
    sha1.addBytes(reinterpret_cast<const uint8_t*>(webSocketKeyGUID), strlen(webSocketKeyGUID));
    Vector<uint8_t, sha1HashSize> hash;
    sha1.computeHash(hash);
    return base64Encode(reinterpret_cast<const char*>(hash.data()), sha1HashSize);
}
Example #22
0
CString CHTTPSock::GetParam(const CString& sName,
                            const map<CString, VCString>& msvsParams,
                            const CString& sFilter) {
    CString sRet = GetRawParam(sName, msvsParams);
    sRet.Trim();

    for (size_t i = 0; i < sFilter.length(); i++) {
        sRet.Replace(CString(sFilter.at(i)), "");
    }

    return sRet;
}
Example #23
0
void WebSocketChannel::didOpenSocketStream(SocketStreamHandle* handle)
{
    LOG(Network, "WebSocketChannel %p didOpenSocketStream()", this);
    ASSERT(handle == m_handle);
    if (!m_document)
        return;
    if (m_identifier)
        InspectorInstrumentation::willSendWebSocketHandshakeRequest(m_document, m_identifier, *m_handshake->clientHandshakeRequest());
    CString handshakeMessage = m_handshake->clientHandshakeMessage();
    if (!handle->send(handshakeMessage.data(), handshakeMessage.length()))
        fail("Failed to send WebSocket handshake.");
}
Example #24
0
void CurlCacheEntry::generateBaseFilename(const CString& url)
{
    MD5 md5;
    md5.addBytes(reinterpret_cast<const uint8_t*>(url.data()), url.length());

    MD5::Digest sum;
    md5.checksum(sum);
    uint8_t* rawdata = sum.data();

    for (size_t i = 0; i < MD5::hashSize; i++)
        appendByteAsHex(rawdata[i], m_basename, Lowercase);
}
Example #25
0
void CalendarPickerElement::writeDocument(DocumentWriter& writer)
{
    HTMLInputElement* input = hostInput();
    DateComponents date;
    date.setMillisecondsSinceEpochForDate(input->minimum());
    String minString = date.toString();
    date.setMillisecondsSinceEpochForDate(input->maximum());
    String maxString = date.toString();
    Decimal step;
    String stepString = input->fastGetAttribute(stepAttr);
    if (stepString.isEmpty() || !input->getAllowedValueStep(&step))
        stepString = "1";

    addString("<!DOCTYPE html><head><meta charset='UTF-8'><style>\n", writer);
    writer.addData(calendarPickerCss, sizeof(calendarPickerCss));
    if (document()->page()) {
        CString extraStyle = document()->page()->theme()->extraCalendarPickerStyleSheet();
        if (extraStyle.length())
            writer.addData(extraStyle.data(), extraStyle.length());
    }
    addString("</style></head><body><div id=main>Loading...</div><script>\n"
               "window.dialogArguments = {\n", writer);
    addProperty("min", minString, writer);
    addProperty("max", maxString, writer);
    addProperty("step", stepString, writer);
    addProperty("required", input->required(), writer);
    addProperty("currentValue", input->value(), writer);
    addProperty("locale", defaultLanguage(), writer);
    addProperty("todayLabel", calendarTodayText(), writer);
    addProperty("clearLabel", calendarClearText(), writer);
    addProperty("weekStartDay", firstDayOfWeek(), writer);
    addProperty("monthLabels", monthLabels(), writer);
    addProperty("dayLabels", weekDayShortLabels(), writer);
    Direction dir = direction(monthLabels()[0][0]);
    addProperty("isRTL", dir == RightToLeft || dir == RightToLeftArabic, writer);
    addString("}\n", writer);

    writer.addData(calendarPickerJs, sizeof(calendarPickerJs));
    addString("</script></body>\n", writer);
}
Example #26
0
CString CDir::CheckPathPrefix(const CString& sPath, const CString& sAdd, const CString& sHomeDir) {
#ifdef _WIN32
	const CString sPrefix = ChangeDir(sPath, "./", sHomeDir);
	const CString sAbsolutePath = ChangeDir(sPath, sAdd, sHomeDir);
#else
	CString sPrefix = sPath.Replace_n("//", "/").TrimRight_n("/") + "/";
	CString sAbsolutePath = ChangeDir(sPrefix, sAdd, sHomeDir);
#endif

	if (sAbsolutePath.Left(sPrefix.length()) != sPrefix)
		return "";
	return sAbsolutePath;
}
Example #27
0
	CString CDataStream::GetLine()
	{
		// keep looping while not hitting delimiter
		int nReadCount;
		char szTmpBuf[MAX_PATH];
		CString szRet;
		while ( (nReadCount = Read(szTmpBuf, MAX_PATH - 1)) != 0)
		{
			// Terminate string
			szTmpBuf[nReadCount] = '\0';

			char *p = strchr(szTmpBuf, '\n');
			if (p != 0)
			{
				// reposition backwards
				Skip((long)(p + 1 - szTmpBuf - nReadCount));
				*p = '\0';
			}

			szRet = szTmpBuf;

			if (p != 0)
			{
				// trim off trailing cr if this was a cr/lf entry
				if (szRet.length() && szRet[szRet.length() - 1] == '\r')
				{
					szRet.erase(szRet.length() - 1, 1);
				}

				// found terminator, break out
				break;
			}
		}

		CStringUtil::Trim(szRet);

		return szRet;
	}
Example #28
0
/*
	TAccount: Attribute-Managing
*/
bool TAccount::hasChest(const TLevelChest *pChest, const CString& pLevel)
{
	// Definitions
	CString chestStr = pChest->getChestStr((pLevel.length() > 1 ? pLevel : levelName));

	// Iterate Chest List
	for (std::vector<CString>::iterator i = chestList.begin(); i != chestList.end(); ++i)
	{
		if (*i == chestStr)
			return true;
	}

	return false;
}
Example #29
0
bool CFile::ReadLine(CString& sData, const CString & sDelimiter) {
	char buff[4096];
	ssize_t iBytes;

	if (m_iFD == -1) {
		errno = EBADF;
		return false;
	}

	do {
		CString::size_type iFind = m_sBuffer.find(sDelimiter);
		if (iFind != CString::npos) {
			// We found a line, return it
			sData = m_sBuffer.substr(0, iFind + sDelimiter.length());
			m_sBuffer.erase(0, iFind + sDelimiter.length());
			return true;
		}

		iBytes = read(m_iFD, buff, sizeof(buff));

		if (iBytes > 0) {
			m_sBuffer.append(buff, iBytes);
		}
	} while (iBytes > 0);

	// We are at the end of the file or an error happened

	if (!m_sBuffer.empty()) {
		// ..but there is still some partial line in the buffer
		sData = m_sBuffer;
		m_sBuffer.clear();
		return true;
	}

	// Nothing left for reading :(
	return false;
}
void MainThreadWebSocketChannel::didOpenSocketStream(SocketStreamHandle* handle)
{
    WTF_LOG(Network, "MainThreadWebSocketChannel %p didOpenSocketStream()", this);
    ASSERT(handle == m_handle);
    if (!m_document)
        return;
    if (m_identifier) {
        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"), "WebSocketSendHandshakeRequest", "data", InspectorWebSocketEvent::data(m_document, m_identifier));
        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline.stack"), "CallStack", "stack", InspectorCallStackEvent::currentCallStack());
        // FIXME(361045): remove InspectorInstrumentation calls once DevTools Timeline migrates to tracing.
        InspectorInstrumentation::willSendWebSocketHandshakeRequest(m_document, m_identifier, m_handshake->clientHandshakeRequest().get());
    }
    CString handshakeMessage = m_handshake->clientHandshakeMessage();
    if (!handle->send(handshakeMessage.data(), handshakeMessage.length()))
        failAsError("Failed to send WebSocket handshake.");
}