Beispiel #1
0
INT_PTR NetlibHttpRecvHeaders(WPARAM wParam, LPARAM lParam)
{
	NetlibConnection *nlc = (struct NetlibConnection*)wParam;
	if (!NetlibEnterNestedCS(nlc, NLNCS_RECV))
		return 0;

	char *peol, *pbuffer;
	int headersCount = 0, bufferSize = 8192;

	DWORD dwRequestTimeoutTime = GetTickCount() + HTTPRECVDATATIMEOUT;
	NETLIBHTTPREQUEST *nlhr = (NETLIBHTTPREQUEST*)mir_calloc(sizeof(NETLIBHTTPREQUEST));
	nlhr->cbSize = sizeof(NETLIBHTTPREQUEST);
	nlhr->nlc = nlc;  // Needed to id connection in the protocol HTTP gateway wrapper functions
	nlhr->requestType = REQUEST_RESPONSE;

	int firstLineLength = 0;
	if (!HttpPeekFirstResponseLine(nlc, dwRequestTimeoutTime, lParam | MSG_PEEK, &nlhr->resultCode, &nlhr->szResultDescr, &firstLineLength)) {
		NetlibLeaveNestedCS(&nlc->ncsRecv);
		NetlibHttpFreeRequestStruct(0, (LPARAM)nlhr);
		return 0;
	}

	char *buffer = (char*)mir_alloc(bufferSize + 1);
	int bytesPeeked = NLRecv(nlc, buffer, min(firstLineLength, bufferSize), lParam | MSG_DUMPASTEXT);
	if (bytesPeeked != firstLineLength) {
		NetlibLeaveNestedCS(&nlc->ncsRecv);
		NetlibHttpFreeRequestStruct(0, (LPARAM)nlhr);
		if (bytesPeeked != SOCKET_ERROR) SetLastError(ERROR_HANDLE_EOF);
		mir_free(buffer);
		return 0;
	}

	// Make sure all headers arrived
	bytesPeeked = 0;
	for (bool headersCompleted = false; !headersCompleted;) {
		if (bytesPeeked >= bufferSize) {
			bufferSize += 8192;
			mir_free(buffer);
			if (bufferSize > 32 * 1024) {
				bytesPeeked = 0;
				break;
			}
			buffer = (char*)mir_alloc(bufferSize + 1);
		}

		bytesPeeked = RecvWithTimeoutTime(nlc, dwRequestTimeoutTime, buffer, bufferSize, MSG_PEEK | MSG_NODUMP | lParam);
		if (bytesPeeked == 0)
			break;

		if (bytesPeeked == SOCKET_ERROR) {
			bytesPeeked = 0;
			break;
		}
		buffer[bytesPeeked] = 0;

		for (pbuffer = buffer, headersCount = 0;; pbuffer = peol + 1, ++headersCount) {
			peol = strchr(pbuffer, '\n');
			if (peol == NULL) break;
			if (peol == pbuffer || (peol == (pbuffer + 1) && *pbuffer == '\r')) {
				bytesPeeked = peol - buffer + 1;
				headersCompleted = true;
				break;
			}
		}
	}

	// Receive headers
	if (bytesPeeked > 0)
		bytesPeeked = NLRecv(nlc, buffer, bytesPeeked, lParam | MSG_DUMPASTEXT);
	if (bytesPeeked <= 0) {
		NetlibLeaveNestedCS(&nlc->ncsRecv);
		NetlibHttpFreeRequestStruct(0, (LPARAM)nlhr);
		mir_free(buffer);
		return 0;
	}
	buffer[bytesPeeked] = 0;

	nlhr->headersCount = headersCount;
	nlhr->headers = (NETLIBHTTPHEADER*)mir_calloc(sizeof(NETLIBHTTPHEADER) * headersCount);

	for (pbuffer = buffer, headersCount = 0;; pbuffer = peol + 1, ++headersCount) {
		peol = strchr(pbuffer, '\n');
		if (peol == NULL || peol == pbuffer || (peol == (pbuffer + 1) && *pbuffer == '\r')) break;
		*peol = 0;

		char *pColon = strchr(pbuffer, ':');
		if (pColon == NULL) {
			NetlibHttpFreeRequestStruct(0, (LPARAM)nlhr); nlhr = NULL;
			SetLastError(ERROR_INVALID_DATA);
			break;
		}

		*(pColon++) = 0;
		nlhr->headers[headersCount].szName = mir_strdup(rtrim(pbuffer));
		nlhr->headers[headersCount].szValue = mir_strdup(lrtrimp(pColon));
	}

	NetlibLeaveNestedCS(&nlc->ncsRecv);
	mir_free(buffer);
	return (INT_PTR)nlhr;
}
	std::string trim(const std::string& a_Input, char l_ToTrim){
		return ltrim(rtrim(a_Input, l_ToTrim), l_ToTrim);
	}
std::string 
ProgrammableOpAttributes::trim(const std::string &s) 
{
        return ltrim(rtrim(s));
}
Beispiel #4
0
static GtkWidget *script_info_add(const char *path, const char *fname)
{
    char *fullname;
    ScriptInfo *si;
    FILE *script;
    int i;
    char line[1024];
    const char *str;
    char *dot;
    char *underscore;
    GtkWidget *menuitem = NULL;

    fullname = g_malloc(strlen(path)+strlen(fname)+2);
    sprintf(fullname,"%s/%s",path,fname);

    script = fopen(fullname,"r");
    if (script)
    {
        si = (ScriptInfo *)g_malloc0(sizeof(ScriptInfo));
        si->script_file = strdup(fname);

        //rtrim(line); uninitialized yet

        for (i=0; i<30; i++)
        {
            if (fgets(line,1024,script)==NULL) break;

            rtrim(line);

            if ((str=locate_after_prefix("@name",line))!=NULL)
            {
                si->script_name = g_strdup(str);
            }
            else if ((str=locate_after_prefix("@description",line))!=NULL)
            {
                si->script_description = g_strdup(str);
            }
            else if ((str=locate_after_prefix("@targets",line))!=NULL)
            {
                si->script_targeted_version = g_strdup(str);
            }
        }

        fclose(script);

        if (si->script_name==NULL)
        {
            si->script_name = g_strdup(fname);

            dot = rindex(si->script_name,'.');
            if (dot) *dot=0;

            for (underscore=si->script_name; *underscore!=0; underscore++)
            {
                if (*underscore=='_') *underscore=' ';
            }
        }

        si->prev = SCRIPTS;
        SCRIPTS = si;

        menuitem = gtk_menu_item_new_with_label(si->script_name);
        if (si->script_description) gtk_widget_set_tooltip_text(menuitem,si->script_description);
        g_signal_connect(GTK_WIDGET(menuitem),"activate",G_CALLBACK(menu_run_script_cb),si);
        gtk_widget_show(menuitem);
    }
    else
    {
        log_printf(LOG_ERROR,"Failed to open %s for reading",fullname);
    }
    g_free(fullname);
    return menuitem;
}
Beispiel #5
0
char *trim(char *s)
{
    return rtrim(ltrim(s)); 
}
Beispiel #6
0
std::string GumboInterface::serialize(GumboNode* node, enum UpdateTypes doupdates) {
    // special case the document node
    if (node->type == GUMBO_NODE_DOCUMENT) {
        std::string results = build_doctype(node);
        results.append(serialize_contents(node, doupdates));
        return results;
    }

    std::string close = "";
    std::string closeTag = "";
    std::string atts = "";
    std::string tagname            = get_tag_name(node);
    bool need_special_handling     = in_set(special_handling, tagname);
    bool is_void_tag               = in_set(void_tags, tagname);
    bool no_entity_substitution    = in_set(no_entity_sub, tagname);
    bool is_href_src_tag           = in_set(href_src_tags, tagname);
    bool in_xml_ns                 = node->v.element.tag_namespace != GUMBO_NAMESPACE_HTML;
    // bool is_inline                 = in_set(nonbreaking_inline, tagname);

    // build attr string  
    const GumboVector * attribs = &node->v.element.attributes;
    for (unsigned int i=0; i< attribs->length; ++i) {
        GumboAttribute* at = static_cast<GumboAttribute*>(attribs->data[i]);
        atts.append(build_attributes(at, no_entity_substitution, ((doupdates & SourceUpdates) && is_href_src_tag), (doupdates & StyleUpdates)));
    }

    // Make sure that the xmlns attribute exists as an html tag attribute
    if (tagname == "html") {
      if (atts.find("xmlns=") == std::string::npos) {
        atts.append(" xmlns=\"http://www.w3.org/1999/xhtml\"");
      }
    }

    // determine contents
    std::string contents;

    if ((tagname == "body") && (doupdates & BodyUpdates)) {
        contents = m_newbody;
    } else {
        // serialize your contents
        contents = serialize_contents(node, doupdates);
    }

    // determine closing tag type
    std::string testcontents = contents;
    ltrim(testcontents);
    if (is_void_tag || (in_xml_ns && testcontents.empty())) {
        close = "/";
    } else {
        closeTag = "</" + tagname + ">";
    }

    if ((doupdates & StyleUpdates) && (tagname == "style") && 
        (node->parent->type == GUMBO_NODE_ELEMENT) && 
        (node->parent->v.element.tag == GUMBO_TAG_HEAD)) {
        contents = update_style_urls(contents);
    }

    if (need_special_handling) {
        ltrimnewlines(contents);
        rtrim(contents);
        contents.append("\n");
    }

    // build results
    std::string results;

    if ((doupdates & LinkUpdates) && (tagname == "link") && 
        (node->parent->type == GUMBO_NODE_ELEMENT) && 
        (node->parent->v.element.tag == GUMBO_TAG_HEAD)) {
      return "";
    }

    results.append("<"+tagname+atts+close+">");
    if (need_special_handling) results.append("\n");
    results.append(contents);

    if ((doupdates & LinkUpdates) && (tagname == "head")) {
        results.append(m_newcsslinks);
    }

    results.append(closeTag);
    if (need_special_handling) results.append("\n");
    return results;
}
Beispiel #7
0
// trim from both ends 
static inline std::string &trim(std::string &s) { 
        return ltrim(rtrim(s)); 
} 
Beispiel #8
0
bool CLemWord::ProcessPlmLineForTheFirstHomonym(const char* sPlmLine, MorphLanguageEnum langua, int& OborotNo)
{
    char buffer[CriticalGraphemLineLength*2];
    assert (strlen(sPlmLine) < CriticalGraphemLineLength*2);
    strcpy(buffer, sPlmLine);
    char* strPlmLine = buffer;


    // откусываю признаки конца строки, если они по¤вились
    size_t iPlmLineLen = strlen(strPlmLine);
    rtrim(strPlmLine,&iPlmLineLen);

    size_t iFirstFieldLen = strcspn(strPlmLine," ");
    char WordBuffer[CriticalTokenLength+1];
    strncpy(WordBuffer, strPlmLine, iFirstFieldLen);
    WordBuffer[iFirstFieldLen] = '\0';
    SetWordStr(WordBuffer, langua);


    size_t iSomeUnusefulDigitsLen = strspn(strPlmLine + iFirstFieldLen," -1234567890");

    //  reading file position of an item from graline
    if (sscanf(strPlmLine + iFirstFieldLen, "%i %i", &m_GraphematicalUnitOffset, &m_TokenLengthInFile) != 2)
        return false;

    strPlmLine += iFirstFieldLen + iSomeUnusefulDigitsLen;

    int MorphSectionOffset = ProcessGraphematicalDescriptors(strPlmLine);

    if( m_bSpace )
        return true;

    CHomonym*  pHomonym  = AddNewHomonym();

    if (HasDes(OEXPR1))
        OborotNo = ParseOborotNo(m_UnparsedGraphemDescriptorsStr);

    if (OborotNo != -1)
    {
        pHomonym->m_OborotNo =  OborotNo;
        pHomonym->m_bInOb =  true;
        pHomonym->m_bOborot1 = HasDes(OEXPR1);
        pHomonym->m_bOborot2 = HasDes(OEXPR2);
    }
    if (HasDes(OEXPR2))
        OborotNo = -1;

    if( MorphSectionOffset == strlen(strPlmLine) )
        pHomonym->SetLemma(m_strWord);
    else
        if (!pHomonym->ProcessLemmaAndGrammems(strPlmLine+MorphSectionOffset))
            return false;

    InitLevelSpecific(pHomonym);

    if	(		(m_strWord == "\"")
        ||	(m_strWord == "'")
        )
        DelDes(OPun);




    if (pHomonym->m_LemSign != '+')
        m_bPredicted = true;

    return true;
}
Beispiel #9
0
char *trim(char *str) {
	return ltrim(rtrim(str));
}
Beispiel #10
0
std::string GumboInterface::prettyprint(GumboNode* node, int lvl, const std::string indent_chars)
{

    // special case the document node
    if (node->type == GUMBO_NODE_DOCUMENT) {
      std::string results = build_doctype(node);
      results.append(prettyprint_contents(node,lvl+1,indent_chars));
      return results;
    }

    std::string close              = "";
    std::string closeTag           = "";
    std::string atts               = "";
    std::string tagname            = get_tag_name(node);
    std::string parentname         = get_tag_name(node->parent);
    bool in_head                   = (parentname == "head");
    // bool need_special_handling     = in_set(special_handling, tagname);
    bool is_empty_tag              = in_set(empty_tags, tagname);
    bool no_entity_substitution    = in_set(no_entity_sub, tagname);
    bool keep_whitespace           = in_set(preserve_whitespace, tagname);
    bool is_inline                 = in_set(nonbreaking_inline, tagname) && (parentname != "body");
    bool is_structural             = in_set(structural_tags, tagname);
    bool pp_okay                   = !is_inline && !keep_whitespace;
    char c                         = indent_chars.at(0);
    int  n                         = indent_chars.length(); 

    // build attr string
    const GumboVector * attribs = &node->v.element.attributes;
    for (unsigned int i=0; i< attribs->length; ++i) {
        GumboAttribute* at = static_cast<GumboAttribute*>(attribs->data[i]);
        atts.append(build_attributes(at, no_entity_substitution));
    }

    // determine closing tag type
    if (is_empty_tag) {
        close = "/";
    } else {
        closeTag = "</" + tagname + ">";
    }

    std::string indent_space = std::string((lvl-1)*n,c);
    std::string contents;

    // prettyprint your contents
    if (is_structural && tagname != "html") {
        contents = prettyprint_contents(node, lvl+1, indent_chars);
    } else {
        contents = prettyprint_contents(node, lvl, indent_chars);
    }

    if (is_structural) {
        rtrim(contents);
        if (!contents.empty()) contents.append("\n");
    }

    // remove any leading or trailing whitespace form within paragraphs
    if (tagname == "p") {
        ltrim(contents);
        rtrim(contents);
    }

    char last_char = ' ';
    if (!contents.empty()) {
        last_char = contents.at(contents.length()-1);
    } 

    // build results
    std::string results;

    if (!is_inline && !in_set(nonbreaking_inline, parentname)) {
      results.append(indent_space);
    }

    results.append("<"+tagname+atts+close+">");

    if (pp_okay && is_structural && !contents.empty()) {
        results.append("\n");
    }

    results.append(contents);

    if (pp_okay && (last_char != '\n') && !contents.empty() && is_structural) {
        results.append("\n");
    }

    // handle any indent before structural close tags
    if (!is_inline && is_structural && !closeTag.empty() && !contents.empty()) {
        results.append(indent_space);
    }

    results.append(closeTag);

    if ((pp_okay || tagname =="br") && !in_set(nonbreaking_inline, parentname)) {
        if (!in_head  && tagname != "html") {
            results.append("\n\n");
        } else {
            results.append("\n");
        }
    }

    return results;
}
Beispiel #11
0
std::string GumboInterface::serialize(GumboNode* node, enum UpdateTypes doupdates) {
    // special case the document node
    if (node->type == GUMBO_NODE_DOCUMENT) {
        std::string results = build_doctype(node);
        results.append(serialize_contents(node, doupdates));
        return results;
    }

    std::string close = "";
    std::string closeTag = "";
    std::string atts = "";
    std::string tagname            = get_tag_name(node);
    bool need_special_handling     = in_set(special_handling, tagname);
    bool is_empty_tag              = in_set(empty_tags, tagname);
    bool no_entity_substitution    = in_set(no_entity_sub, tagname);
    // bool is_inline                 = in_set(nonbreaking_inline, tagname);
    bool is_href_src_tag           = in_set(href_src_tags, tagname);

    // build attr string  
    const GumboVector * attribs = &node->v.element.attributes;
    for (unsigned int i=0; i< attribs->length; ++i) {
        GumboAttribute* at = static_cast<GumboAttribute*>(attribs->data[i]);
        atts.append(build_attributes(at, no_entity_substitution, ((doupdates & SourceUpdates) && is_href_src_tag) ));
    }

    // determine closing tag type
    if (is_empty_tag) {
        close = "/";
    } else {
        closeTag = "</" + tagname + ">";
    }

    std::string contents;

    if ((tagname == "body") && (doupdates & BodyUpdates)) {
        contents = m_newbody;
    } else {
        // serialize your contents
        contents = serialize_contents(node, doupdates);
    }

    if (need_special_handling) {
        ltrimnewlines(contents);
        rtrim(contents);
        contents.append("\n");
    }

    // build results
    std::string results;

    if ((doupdates & LinkUpdates) && (tagname == "link") && 
        (node->parent->type == GUMBO_NODE_ELEMENT) && 
        (node->parent->v.element.tag == GUMBO_TAG_HEAD)) {
      return "";
    }

    results.append("<"+tagname+atts+close+">");
    if (need_special_handling) results.append("\n");
    results.append(contents);

    if ((doupdates & LinkUpdates) && (tagname == "head")) {
        results.append(m_newcsslinks);
    }

    results.append(closeTag);
    if (need_special_handling) results.append("\n");
    return results;
}
Beispiel #12
0
 inline std::string &trim(std::string &s, char x)
 {
     return ltrim(rtrim(s, x), x);
 }
Beispiel #13
0
static int do_command(char type, const char *command, const char *parameters, char *response)
{
	char	buffer[SMALLBUF];
	int	count, ret;

	ser_flush_io(upsfd);

	if (response) {
		*response = '\0';
	}

	snprintf(buffer, sizeof(buffer), "~00%c%03d%s%s", type, (int)(strlen(command) + strlen(parameters)), command, parameters);

	ret = ser_send_pace(upsfd, 10000, "%s", buffer);
	if (ret <= 0) {
		upsdebug_with_errno(3, "do_command: send [%s]", buffer);
		return -1;
	}

	upsdebugx(3, "do_command: %d bytes sent [%s] -> OK", ret, buffer);

	ret = ser_get_buf_len(upsfd, (unsigned char *)buffer, 4, 3, 0);
	if (ret < 0) {
		upsdebug_with_errno(3, "do_command: read");
		return -1;
	}
	if (ret == 0) {
		upsdebugx(3, "do_command: read -> TIMEOUT");
		return -1;
	}

	buffer[ret] = '\0';
	upsdebugx(3, "do_command: %d byted read [%s]", ret, buffer);

	if (!strcmp(buffer, "~00D")) {

		ret = ser_get_buf_len(upsfd, (unsigned char *)buffer, 3, 3, 0);
		if (ret < 0) {
			upsdebug_with_errno(3, "do_command: read");
			return -1;
		}
		if (ret == 0) {
			upsdebugx(3, "do_command: read -> TIMEOUT");
			return -1;
		}

		buffer[ret] = '\0';
		upsdebugx(3, "do_command: %d bytes read [%s]", ret, buffer);

		count = atoi(buffer);
		if (count >= MAX_RESPONSE_LENGTH) {
			upsdebugx(3, "do_command: response exceeds expected size!");
			return -1;
		}

		if (count && !response) {
			upsdebugx(3, "do_command: response not expected!");
			return -1;
		}

		if (count == 0) {
			return 0;
		}

		ret = ser_get_buf_len(upsfd, (unsigned char *)response, count, 3, 0);
		if (ret < 0) {
			upsdebug_with_errno(3, "do_command: read");
			return -1;
		}
		if (ret == 0) {
			upsdebugx(3, "do_command: read -> TIMEOUT");
			return -1;
		}

		response[ret] = '\0';
		upsdebugx(3, "do_command: %d bytes read [%s]", ret, response);

		/* Tripp Lite pads their string responses with spaces.
		   I don't like that, so I remove them.  This is safe to
		   do with all responses for this protocol, so I just
		   do that here. */
		rtrim(response, ' ');

		return ret;
	}

	if (!strcmp(buffer, "~00A")) {
		return 0;
	}

	return -1;
}
Beispiel #14
0
 std::string & trim(std::string & str)
 {
     return ltrim(rtrim(str));
 }
static void update_topol(const char *topinout, int p_num, int n_num,
                         const char *p_name, const char *n_name, char *grpname)
{
#define TEMP_FILENM "temp.top"
    FILE    *fpin, *fpout;
    char     buf[STRLEN], buf2[STRLEN], *temp, **mol_line = NULL;
    int      line, i, nsol, nmol_line, sol_line, nsol_last;
    gmx_bool bMolecules;

    printf("\nProcessing topology\n");
    fpin  = gmx_ffopen(topinout, "r");
    fpout = gmx_ffopen(TEMP_FILENM, "w");

    line       = 0;
    bMolecules = FALSE;
    nmol_line  = 0;
    sol_line   = -1;
    nsol_last  = -1;
    while (fgets(buf, STRLEN, fpin))
    {
        line++;
        strcpy(buf2, buf);
        if ((temp = strchr(buf2, '\n')) != NULL)
        {
            temp[0] = '\0';
        }
        ltrim(buf2);
        if (buf2[0] == '[')
        {
            buf2[0] = ' ';
            if ((temp = strchr(buf2, '\n')) != NULL)
            {
                temp[0] = '\0';
            }
            rtrim(buf2);
            if (buf2[strlen(buf2)-1] == ']')
            {
                buf2[strlen(buf2)-1] = '\0';
                ltrim(buf2);
                rtrim(buf2);
                bMolecules = (gmx_strcasecmp(buf2, "molecules") == 0);
            }
            fprintf(fpout, "%s", buf);
        }
        else if (!bMolecules)
        {
            fprintf(fpout, "%s", buf);
        }
        else
        {
            /* Check if this is a line with solvent molecules */
            sscanf(buf, "%s", buf2);
            if (gmx_strcasecmp(buf2, grpname) == 0)
            {
                sol_line = nmol_line;
                sscanf(buf, "%*s %d", &nsol_last);
            }
            /* Store this molecules section line */
            srenew(mol_line, nmol_line+1);
            mol_line[nmol_line] = strdup(buf);
            nmol_line++;
        }
    }
    gmx_ffclose(fpin);

    if (sol_line == -1)
    {
        gmx_ffclose(fpout);
        gmx_fatal(FARGS, "No line with moleculetype '%s' found the [ molecules ] section of file '%s'", grpname, topinout);
    }
    if (nsol_last < p_num+n_num)
    {
        gmx_ffclose(fpout);
        gmx_fatal(FARGS, "The last entry for moleculetype '%s' in the [ molecules ] section of file '%s' has less solvent molecules (%d) than were replaced (%d)", grpname, topinout, nsol_last, p_num+n_num);
    }

    /* Print all the molecule entries */
    for (i = 0; i < nmol_line; i++)
    {
        if (i != sol_line)
        {
            fprintf(fpout, "%s", mol_line[i]);
        }
        else
        {
            printf("Replacing %d solute molecules in topology file (%s) "
                   " by %d %s and %d %s ions.\n",
                   p_num+n_num, topinout, p_num, p_name, n_num, n_name);
            nsol_last -= p_num + n_num;
            if (nsol_last > 0)
            {
                fprintf(fpout, "%-10s  %d\n", grpname, nsol_last);
            }
            if (p_num > 0)
            {
                fprintf(fpout, "%-15s  %d\n", p_name, p_num);
            }
            if (n_num > 0)
            {
                fprintf(fpout, "%-15s  %d\n", n_name, n_num);
            }
        }
    }
    gmx_ffclose(fpout);
    /* use gmx_ffopen to generate backup of topinout */
    fpout = gmx_ffopen(topinout, "w");
    gmx_ffclose(fpout);
    rename(TEMP_FILENM, topinout);
#undef TEMP_FILENM
}
Beispiel #16
0
std::string
ossfs::util::trim(const std::string &s)
{
    return ltrim(rtrim(s));
}
Beispiel #17
0
int main(void) {
    plan(60);

    /* lowercase */
    char test[100];
    ok(lc(NULL) == NULL, "lc(NULL)");
    strcpy(test, "Yes"); like(lc(test), "yes", "lc(yes)");
    strcpy(test, "YES"); like(lc(test), "yes", "lc(YES)");
    strcpy(test, "yeS"); like(lc(test), "yes", "lc(yeS)");


    /* trim */
    strcpy(test, "    text  "); like(ltrim(test), "text  ",   "ltrim()");
    strcpy(test, "    text  "); like(rtrim(test), "    text", "rtrim()");
    strcpy(test, "    text  "); like(trim(test),  "text",     "trim()");
    char *test2;
    test2 = strdup("   text   ");  like(trim(test2),  "text", "trim()");
    free(test2);

    /* parse_yes_or_no */
    ok(parse_yes_or_no(NULL,    GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 1");
    ok(parse_yes_or_no(NULL,    GM_DISABLED) == GM_DISABLED, "parse_yes_or_no 2");
    strcpy(test, "");      ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 3");
    strcpy(test, "");      ok(parse_yes_or_no(test, GM_DISABLED) == GM_DISABLED, "parse_yes_or_no 4");
    strcpy(test, "yes");   ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 5");
    strcpy(test, "true");  ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 6");
    strcpy(test, "Yes");   ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 7");
    strcpy(test, "1");     ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 8");
    strcpy(test, "On");    ok(parse_yes_or_no(test, GM_ENABLED)  == GM_ENABLED, "parse_yes_or_no 9");
    strcpy(test, "Off");   ok(parse_yes_or_no(test, GM_ENABLED)  == GM_DISABLED, "parse_yes_or_no 10");
    strcpy(test, "false"); ok(parse_yes_or_no(test, GM_ENABLED)  == GM_DISABLED, "parse_yes_or_no 11");
    strcpy(test, "no");    ok(parse_yes_or_no(test, GM_ENABLED)  == GM_DISABLED, "parse_yes_or_no 12");
    strcpy(test, "0");     ok(parse_yes_or_no(test, GM_ENABLED)  == GM_DISABLED, "parse_yes_or_no 13");


    /* trim */
    ok(trim(NULL) == NULL, "trim(NULL)");
    strcpy(test, " test "); like(trim(test), "^test$", "trim(' test ')");
    strcpy(test, "\ntest\n"); like(trim(test), "^test$", "trim('\\ntest\\n')");

    /* reading keys */
    mod_gm_opt_t *mod_gm_opt;
    mod_gm_opt = malloc(sizeof(mod_gm_opt_t));
    int rc = set_default_options(mod_gm_opt);

    ok(rc == 0, "setting default options");
    mod_gm_opt->keyfile = strdup("t/data/test1.key");
    read_keyfile(mod_gm_opt);
    //printf_hex(mod_gm_opt->crypt_key, 32);
    test[0]='\x0';
    int i = 0;
    char hex[4];
    for(i=0; i<32; i++) {
        hex[0] = '\x0';
        snprintf(hex, 4, "%02x", mod_gm_opt->crypt_key[i]);
        strncat(test, hex, 4);
    }
    like(test, "3131313131313131313131313131313131313131313131313131313131310000", "read keyfile t/data/test1.key");

    free(mod_gm_opt->keyfile);
    mod_gm_opt->keyfile = strdup("t/data/test2.key");
    read_keyfile(mod_gm_opt);

    like(mod_gm_opt->crypt_key, "abcdef", "reading keyfile t/data/test2.key");

    free(mod_gm_opt->keyfile);
    mod_gm_opt->keyfile = strdup("t/data/test3.key");
    read_keyfile(mod_gm_opt);
    //printf_hex(mod_gm_opt->crypt_key, 32);
    like(mod_gm_opt->crypt_key, "11111111111111111111111111111111", "reading keyfile t/data/test3.key");
    ok(strlen(mod_gm_opt->crypt_key) == 32, "key size for t/data/test3.key");


    /* encrypt */
    char * key       = "test1234";
    char * encrypted = malloc(GM_BUFFERSIZE);
    char * text      = "test message";
    char * base      = "a7HqhQEE8TQBde9uknpPYQ==";
    mod_gm_crypt_init(key);
    int len;
    len = mod_gm_encrypt(&encrypted, text, GM_ENCODE_AND_ENCRYPT);
    ok(len == 24, "length of encrypted only");
    like(encrypted, base, "encrypted string");

    /* decrypt */
    char * decrypted = malloc(GM_BUFFERSIZE);
    mod_gm_decrypt(&decrypted, encrypted, GM_ENCODE_AND_ENCRYPT);
    like(decrypted, text, "decrypted text");
    free(decrypted);
    free(encrypted);

    /* base 64 */
    char * base64 = malloc(GM_BUFFERSIZE);
    len = mod_gm_encrypt(&base64, text, GM_ENCODE_ONLY);
    ok(len == 16, "length of encode only");
    like(base64, "dGVzdCBtZXNzYWdl", "base64 only string");

    /* debase 64 */
    char * debase64 = malloc(GM_BUFFERSIZE);
    mod_gm_decrypt(&debase64, base64, GM_ENCODE_ONLY);
    like(debase64, text, "debase64 text");
    free(debase64);
    free(base64);


    /* file_exists */
    ok(file_exists("01_utils") == 1, "file_exists('01_utils')");
    ok(file_exists("non-exist") == 0, "file_exists('non-exist')");

    /* nr2signal */
    char * signame1 = nr2signal(9);
    like(signame1, "SIGKILL", "get SIGKILL for 9");
    free(signame1);

    char * signame2 = nr2signal(15);
    like(signame2, "SIGTERM", "get SIGTERM for 15");
    free(signame2);


    /* string2timeval */
    struct timeval t;
    string2timeval("100.50", &t);
    ok(t.tv_sec  == 100, "string2timeval 1");
    ok(t.tv_usec == 50, "string2timeval 2");

    string2timeval("100", &t);
    ok(t.tv_sec  == 100, "string2timeval 3");
    ok(t.tv_usec == 0, "string2timeval 4");

    string2timeval("", &t);
    ok(t.tv_sec  == 0, "string2timeval 5");
    ok(t.tv_usec == 0, "string2timeval 6");

    string2timeval(NULL, &t);
    ok(t.tv_sec  == 0, "string2timeval 7");
    ok(t.tv_usec == 0, "string2timeval 8");

    /* command line parsing */
    mod_gm_free_opt(mod_gm_opt);
    mod_gm_opt = renew_opts();
    strcpy(test, "server=host:4730");
    parse_args_line(mod_gm_opt, test, 0);
    like(mod_gm_opt->server_list[0], "host:4730", "server=host:4730");
    ok(mod_gm_opt->server_num == 1, "server_number = %d", mod_gm_opt->server_num);

    mod_gm_free_opt(mod_gm_opt);
    mod_gm_opt = renew_opts();
    strcpy(test, "server=:4730");
    parse_args_line(mod_gm_opt, test, 0);
    like(mod_gm_opt->server_list[0], "localhost:4730", "server=:4730");
    ok(mod_gm_opt->server_num == 1, "server_number = %d", mod_gm_opt->server_num);

    mod_gm_free_opt(mod_gm_opt);
    mod_gm_opt = renew_opts();
    strcpy(test, "server=localhost:4730");
    parse_args_line(mod_gm_opt, test, 0);
    strcpy(test, "server=localhost:4730");
    parse_args_line(mod_gm_opt, test, 0);
    like(mod_gm_opt->server_list[0], "localhost:4730", "duplicate server");
    ok(mod_gm_opt->server_num == 1, "server_number = %d", mod_gm_opt->server_num);

    mod_gm_free_opt(mod_gm_opt);
    mod_gm_opt = renew_opts();
    strcpy(test, "server=localhost:4730,localhost:4730,:4730,host:4730,");
    parse_args_line(mod_gm_opt, test, 0);
    like(mod_gm_opt->server_list[0], "localhost:4730", "duplicate server");
    like(mod_gm_opt->server_list[1], "host:4730", "duplicate server");
    ok(mod_gm_opt->server_num == 2, "server_number = %d", mod_gm_opt->server_num);

    /* escape newlines */
    char * escaped = gm_escape_newlines(" test\n", GM_DISABLED);
    is(escaped, " test\\n", "untrimmed escape string");
    free(escaped);
    escaped = gm_escape_newlines(" test\n", GM_ENABLED);
    is(escaped, "test", "trimmed escape string");
    free(escaped);

    /* md5 sum */
    char * sum = NULL;
    strcpy(test, "");
    sum = md5sum(test);
    like(sum, "d41d8cd98f00b204e9800998ecf8427e", "md5sum()");
    free(sum);

    strcpy(test, "The quick brown fox jumps over the lazy dog.");
    sum = md5sum(test);
    like(sum, "e4d909c290d0fb1ca068ffaddf22cbd0", "md5sum()");
    free(sum);

    mod_gm_free_opt(mod_gm_opt);

    return exit_status();
}
void StringUtil::atrim(std::wstring& str) {
	ltrim(str);
	rtrim(str);
}
Beispiel #19
0
std::string GumboInterface::prettyprint(GumboNode* node, int lvl, const std::string indent_chars)
{

    // special case the document node
    if (node->type == GUMBO_NODE_DOCUMENT) {
      std::string results = build_doctype(node);
      results.append(prettyprint_contents(node,lvl+1,indent_chars));
      return results;
    }

    std::string tagname = get_tag_name(node);
    std::string parentname = get_tag_name(node->parent);
    bool in_head = (parentname == "head");

    bool is_structural = in_set(structural_tags, tagname);
    bool is_inline = in_set(nonbreaking_inline, tagname);
    bool in_xml_ns = node->v.element.tag_namespace != GUMBO_NAMESPACE_HTML;

    // build attr string
    std::string atts = "";
    bool no_entity_substitution = in_set(no_entity_sub, tagname);
    const GumboVector * attribs = &node->v.element.attributes;
    for (unsigned int i=0; i< attribs->length; ++i) {
        GumboAttribute* at = static_cast<GumboAttribute*>(attribs->data[i]);
        atts.append(build_attributes(at, no_entity_substitution));
    }

    bool is_void_tag = in_set(void_tags, tagname);

    // get tag contents
    std::string contents = "";
    if (!is_void_tag) {
        if (is_structural && tagname != "html") {
            contents = prettyprint_contents(node, lvl+1, indent_chars);
        } else {
            contents = prettyprint_contents(node, lvl, indent_chars);
        }
    }

    bool keep_whitespace = in_set(preserve_whitespace, tagname);
    if (!keep_whitespace && !is_inline) {
        rtrim(contents);
    }

    std::string testcontents = contents;
    ltrim(testcontents);

    bool single = is_void_tag || (in_xml_ns && testcontents.empty());

    char c = indent_chars.at(0);
    int  n = indent_chars.length(); 
    std::string indent_space = std::string((lvl-1)*n,c);

    // handle self-closed tags with no contents first
    if (single) {
        std::string selfclosetag = "<" + tagname + atts + "/>";
        if (is_inline) {
            // always add newline after br tags when they are children of structural tags
            if ((tagname == "br") && in_set(structural_tags, parentname)) {
              selfclosetag.append("\n");
              if (!in_head && (tagname != "html")) selfclosetag.append("\n");
            }
            return selfclosetag;
        }
        if (!in_head && (tagname != "html")) selfclosetag.append("\n");
        return indent_space + selfclosetag + "\n";
    } 

    // Handle the general case
    std::string results;
    std::string starttag = "<" + tagname +  atts + ">";
    std::string closetag = "</" + tagname + ">";

    if (is_structural) {
        results = indent_space + starttag;
        if (!contents.empty()) {
            results.append("\n" + contents + "\n" + indent_space);
        }  
        results.append(closetag + "\n");
        if (!in_head && (tagname != "html")) results.append("\n");
    } else if (is_inline) {
        results = starttag;
        results.append(contents);
        results.append(closetag);
    } else /** all others */ {
        results = indent_space + starttag;
        if (!keep_whitespace) {
            ltrim(contents);
        }
        results.append(contents);
        results.append(closetag + "\n");
        if (!in_head && (tagname != "html")) results.append("\n");
    }
    return results;
}
Beispiel #20
0
// trim from left & right
inline std::string& trim(std::string& s, const char* t = " \t\n\r\f\v")
{
    return ltrim(rtrim(s, t), t);
}
Beispiel #21
0
// trim from both ends
string& trim(string &s) {
  return ltrim(rtrim(s));
}
Beispiel #22
0
inline std::string rtrim_copy(std::string s, const char* t = " \t\n\r\f\v")
{
    return rtrim(s, t);
}
Beispiel #23
0
 static std::string& trim(std::string &s)
 { return rtrim(ltrim(s)); }
Beispiel #24
0
 const std::string
 trim (const std::string& s)
 {
   return ltrim (rtrim (s));
 }
Beispiel #25
0
static INT_PTR CALLBACK AccFormDlgProc(HWND hwndDlg,UINT message, WPARAM wParam, LPARAM lParam)
{
	switch( message ) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		{
			PROTOCOLDESCRIPTOR** proto;
			int protoCount, i, cnt = 0;
			Proto_EnumProtocols(( WPARAM )&protoCount, ( LPARAM )&proto );
			for ( i=0; i < protoCount; i++ ) {
				PROTOCOLDESCRIPTOR* pd = proto[i];
				if ( pd->type == PROTOTYPE_PROTOCOL && pd->cbSize == sizeof( *pd )) {
					SendDlgItemMessageA( hwndDlg, IDC_PROTOTYPECOMBO, CB_ADDSTRING, 0, (LPARAM)proto[i]->szName );
					++cnt;
				}
			}
			SendDlgItemMessage( hwndDlg, IDC_PROTOTYPECOMBO, CB_SETCURSEL, 0, 0 );
			EnableWindow( GetDlgItem( hwndDlg, IDOK ), cnt != 0 );

			SetWindowLongPtr( hwndDlg, GWLP_USERDATA, lParam );
			AccFormDlgParam* param = ( AccFormDlgParam* )lParam;

			if ( param->action == PRAC_ADDED ) // new account
				SetWindowText( hwndDlg, TranslateT( "Create new account" ));
			else {
				TCHAR str[200];
				if ( param->action == PRAC_CHANGED ) { // update
					EnableWindow( GetDlgItem( hwndDlg, IDC_PROTOTYPECOMBO ), FALSE );
					mir_sntprintf( str, SIZEOF(str), _T("%s: %s"), TranslateT( "Editing account" ), param->pa->tszAccountName );
				}
				else mir_sntprintf( str, SIZEOF(str), _T("%s: %s"), TranslateT( "Upgrading account" ), param->pa->tszAccountName );

				SetWindowText( hwndDlg, str );
				SetDlgItemText( hwndDlg, IDC_ACCNAME, param->pa->tszAccountName );
				SetDlgItemTextA( hwndDlg, IDC_ACCINTERNALNAME, param->pa->szModuleName );
				SendDlgItemMessageA( hwndDlg, IDC_PROTOTYPECOMBO, CB_SELECTSTRING, -1, (LPARAM)param->pa->szProtoName );

				EnableWindow( GetDlgItem( hwndDlg, IDC_ACCINTERNALNAME ), FALSE );
			}
			SendDlgItemMessage( hwndDlg, IDC_ACCINTERNALNAME, EM_LIMITTEXT, 40, 0 );
		}
		return TRUE;

	case WM_COMMAND:
		switch( LOWORD(wParam)) {
		case IDOK:
			{
				AccFormDlgParam* param = ( AccFormDlgParam* )GetWindowLongPtr( hwndDlg, GWLP_USERDATA );
				PROTOACCOUNT* pa = param->pa;

				if ( param->action == PRAC_ADDED ) {
					char buf[200];
					GetDlgItemTextA( hwndDlg, IDC_ACCINTERNALNAME, buf, SIZEOF( buf ));
					rtrim( buf );
					if ( buf[0] ) {
						for (int i = 0; i < accounts.getCount(); ++i)
							if (_stricmp(buf, accounts[i]->szModuleName) == 0)
								return FALSE;
				}	}

				switch( param->action ) {
				case PRAC_UPGRADED:
					{
						int idx;
						BOOL oldProto = pa->bOldProto;
						TCHAR szPlugin[MAX_PATH];
						mir_sntprintf(szPlugin, SIZEOF(szPlugin), _T("%s.dll"), StrConvT(pa->szProtoName));
						idx = accounts.getIndex(pa);
						UnloadAccount(pa, false, false);
						accounts.remove(idx);
						if (oldProto && UnloadPlugin(szPlugin, SIZEOF(szPlugin))) 
						{
							TCHAR szNewName[MAX_PATH];
							mir_sntprintf(szNewName, SIZEOF(szNewName), _T("%s~"), szPlugin);
							MoveFile(szPlugin, szNewName);
						}
					}
					// fall through

				case PRAC_ADDED:
					pa = (PROTOACCOUNT*)mir_calloc( sizeof( PROTOACCOUNT ));
					pa->cbSize = sizeof( PROTOACCOUNT );
					pa->bIsEnabled = TRUE;
                    pa->bIsVisible = TRUE;
                    
					pa->iOrder = accounts.getCount();
					pa->type = PROTOTYPE_PROTOCOL;
					break;
				}
				{
					TCHAR buf[256];
					GetDlgItemText( hwndDlg, IDC_ACCNAME, buf, SIZEOF( buf ));
					mir_free(pa->tszAccountName);
					pa->tszAccountName = mir_tstrdup( buf );
				}
				if ( param->action == PRAC_ADDED || param->action == PRAC_UPGRADED ) 
                {
					char buf[200];
					GetDlgItemTextA( hwndDlg, IDC_PROTOTYPECOMBO, buf, SIZEOF( buf ));
					pa->szProtoName = mir_strdup( buf );
					GetDlgItemTextA( hwndDlg, IDC_ACCINTERNALNAME, buf, SIZEOF( buf ));
					rtrim( buf );
					if ( buf[0] == 0 ) {
						int count = 1;
						for( ;; ) {
							DBVARIANT dbv;
							mir_snprintf( buf, SIZEOF(buf), "%s_%d", pa->szProtoName, count++ );
							if ( DBGetContactSettingString( NULL, buf, "AM_BaseProto", &dbv ))
								break;
							DBFreeVariant( &dbv );
					}	}
					pa->szModuleName = mir_strdup( buf );

					if ( !pa->tszAccountName[0] ) {
						mir_free(pa->tszAccountName);
						pa->tszAccountName = mir_a2t(buf);
					}

					DBWriteContactSettingString( NULL, pa->szModuleName, "AM_BaseProto", pa->szProtoName );
					accounts.insert( pa );

					if ( ActivateAccount( pa )) {
						pa->ppro->OnEvent( EV_PROTO_ONLOAD, 0, 0 );
						if (!DBGetContactSettingByte(NULL, "CList", "MoveProtoMenus", FALSE))
							pa->ppro->OnEvent( EV_PROTO_ONMENU, 0, 0 );
					}
					else pa->type = PROTOTYPE_DISPROTO;
				}

				WriteDbAccounts();
				NotifyEventHooks( hAccListChanged, param->action, ( LPARAM )pa );

				SendMessage( GetParent(hwndDlg), WM_MY_REFRESH, 0, 0 );
			}

			EndDialog( hwndDlg, TRUE );
			break;

		case IDCANCEL:
			EndDialog( hwndDlg, FALSE );
			break;
		}
	}

	return FALSE;
}
Beispiel #26
0
std::wstring trim ( const std::wstring & sourceStr ,const wstring &whitespace)
{
	std::wstring str = sourceStr;
	return ltrim ( rtrim ( str , whitespace ) , whitespace );
}
/**
 * In-place left and right trim a string. Strip all the characters specified.
 * @param s String to trim
 * @param charList List of character to trim
 * @return Reference to the (modified) input string
 */
static inline std::string &trim(std::string &s, const char* charList) {
        return ltrim(rtrim(s, charList), charList);
}
Beispiel #28
0
int CMsnProto::MSN_GCEventHook(WPARAM, LPARAM lParam) 
{
	GCHOOK *gch = (GCHOOK*) lParam;
	if (!gch)
		return 1;

	if (_stricmp(gch->pDest->pszModule, m_szModuleName)) return 0;

	switch (gch->pDest->iType) 
	{
		case GC_SESSION_TERMINATE: 
		{
 			ThreadData* thread = MSN_GetThreadByChatId(gch->pDest->ptszID);
			if (thread != NULL) 
				thread->sendTerminate();
			break;
		}

		case GC_USER_MESSAGE:
			if (gch->ptszText && gch->ptszText[0]) 
			{
				ThreadData* thread = MSN_GetThreadByChatId(gch->pDest->ptszID);
				if (thread)
				{
					rtrim(gch->ptszText); // remove the ending linebreak
					TCHAR* pszMsg = UnEscapeChatTags(NEWTSTR_ALLOCA(gch->ptszText));
					thread->sendMessage('N', NULL, NETID_MSN, UTF8(pszMsg), 0);

					DBVARIANT dbv;
					int bError = getTString("Nick", &dbv);

					GCDEST gcd = { m_szModuleName, { NULL }, GC_EVENT_MESSAGE };
					gcd.ptszID = gch->pDest->ptszID;

					GCEVENT gce = {0};
					gce.cbSize = sizeof(GCEVENT);
					gce.dwFlags = GC_TCHAR | GCEF_ADDTOLOG;
					gce.pDest = &gcd;
					gce.ptszNick = bError ? _T("") : dbv.ptszVal;
					gce.ptszUID = mir_a2t(MyOptions.szEmail);
					gce.time = time(NULL);
					gce.ptszText = gch->ptszText;
					gce.bIsMe = TRUE;
					CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);

					mir_free((void*)gce.ptszUID);
					if (!bError)
						MSN_FreeVariant(&dbv);
				}
			}
			break;

		case GC_USER_CHANMGR: 
			DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_CHATROOM_INVITE), NULL, DlgInviteToChat, 
				LPARAM(new InviteChatParam(gch->pDest->ptszID, NULL, this)));
			break;

		case GC_USER_PRIVMESS: 
		{
			char *email = mir_t2a(gch->ptszUID);
			HANDLE hContact = MSN_HContactFromEmail(email);
			MSN_CallService(MS_MSG_SENDMESSAGE, (WPARAM)hContact, 0);
			mir_free(email);
			break;
		}

		case GC_USER_LOGMENU:
			switch(gch->dwData) 
			{
			case 10: 
				DialogBoxParam(hInst, MAKEINTRESOURCE(IDD_CHATROOM_INVITE), NULL, DlgInviteToChat, 
					LPARAM(new InviteChatParam(gch->pDest->ptszID, NULL, this)));
				break;

			case 20:
				MSN_KillChatSession(gch->pDest->ptszID);
				break;
			}
			break;

		case GC_USER_NICKLISTMENU: 
		{
			char *email = mir_t2a(gch->ptszUID);
			HANDLE hContact = MSN_HContactFromEmail(email);
			mir_free(email);

			switch(gch->dwData) 
			{
			case 10:
				MSN_CallService(MS_USERINFO_SHOWDIALOG, (WPARAM)hContact, 0);
				break;

			case 20:
				MSN_CallService(MS_HISTORY_SHOWCONTACTHISTORY, (WPARAM)hContact, 0);
				break;

			case 110:
				MSN_KillChatSession(gch->pDest->ptszID);
				break;
			}
			break;
		}
/*	haven't implemented in chat.dll
		case GC_USER_TYPNOTIFY: 
		{
			int chatID = atoi(p);
			ThreadData* thread = MSN_GetThreadByContact((HANDLE)-chatID);
			for (int j=0; j < thread->mJoinedCount; j++) 
			{
				if ((long)thread->mJoinedContacts[j] > 0)
					CallService(MS_PROTO_SELFISTYPING, (WPARAM) thread->mJoinedContacts[j], (LPARAM) PROTOTYPE_SELFTYPING_ON);
			}
			break;
		}
*/
	}

	return 0;
}
Beispiel #29
0
/*删除str两端的空白字符*/
void trim(char *str)
{
	ltrim(str);
	rtrim(str);
}
Beispiel #30
0
int main(){
	ltrim();
	rtrim();
	return 0;
}