您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ strnstr函数代码示例

51自学网 2021-06-03 08:31:48
  C++
这篇教程C++ strnstr函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中strnstr函数的典型用法代码示例。如果您正苦于以下问题:C++ strnstr函数的具体用法?C++ strnstr怎么用?C++ strnstr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了strnstr函数的29个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: readStatusLine

int WebSocketHandshake::readServerHandshake(const char* header, size_t len){    m_mode = Incomplete;    int statusCode;    String statusText;    int lineLength = readStatusLine(header, len, statusCode, statusText);    if (lineLength == -1)        return -1;    if (statusCode == -1) {        m_mode = Failed; // m_failureReason is set inside readStatusLine().        return len;    }    LOG(Network, "WebSocketHandshake %p readServerHandshake() Status code is %d", this, statusCode);    m_serverHandshakeResponse = ResourceResponse();    m_serverHandshakeResponse.setHTTPStatusCode(statusCode);    m_serverHandshakeResponse.setHTTPStatusText(statusText);    if (statusCode != 101) {        m_mode = Failed;        m_failureReason = "Unexpected response code: " + String::number(statusCode);        return len;    }    m_mode = Normal;    if (!strnstr(header, "/r/n/r/n", len)) {        // Just hasn't been received fully yet.        m_mode = Incomplete;        return -1;    }    const char* p = readHTTPHeaders(header + lineLength, header + len);    if (!p) {        LOG(Network, "WebSocketHandshake %p readServerHandshake() readHTTPHeaders() failed", this);        m_mode = Failed; // m_failureReason is set inside readHTTPHeaders().        return len;    }    if (!checkResponseHeaders()) {        LOG(Network, "WebSocketHandshake %p readServerHandshake() checkResponseHeaders() failed", this);        m_mode = Failed;        return p - header;    }    m_mode = Connected;    return p - header;}
开发者ID:3163504123,项目名称:phantomjs,代码行数:44,


示例2: get_mime_len

int get_mime_len(uchar **data) { // Возвращает строку миме-параметра    uchar *str = *data;    int sl,len;    sl = strlen(str);    len=0; // Будем коллектить длину -)))    while(sl>0) {        int ipos = strnstr(str,sl,"/r/n",-1);        if (ipos<0) {            len+= sl;    // Больше строк нет - возвращаем все...            break;        }        ipos+=2;        str+=ipos;        sl-=ipos;        len+=ipos;        if (sl==0 || *str>32) break; // Следующая строка - начало нового параметра...    }    return len;}
开发者ID:vSlipenchuk,项目名称:vos,代码行数:19,


示例3: is_fota_boot

static bool is_fota_boot(void){	char *ptr, buf[11];	unsigned long val;	ptr = strnstr(saved_command_line, WARMBOOT_STR, COMMAND_LINE_SIZE);	if (!ptr)		return 0;	ptr += sizeof(WARMBOOT_STR) - 1;	strlcpy(buf, ptr, sizeof(buf));	if (!kstrtoul(buf, 16, &val)) {		if (val == FOTA_BOOT_REASON)			return 1;	}	return 0;}
开发者ID:auras76,项目名称:aur-kernel-XZxx,代码行数:19,


示例4: print_unique

int print_unique(char *loaded){    char * ptr, *unique, *addr;        addr = unique = (char *)malloc(sizeof(loaded));    if(unique == NULL)        return EXIT_FAILURE;    strcpy(unique, "");        ptr = strtok(loaded, "/n");    do{        if(strnstr(unique, ptr, strlen(ptr)) == NULL){            strcat(unique, ptr);            strcat(unique, "/n");        }        ptr = strtok(NULL, "/n");    }while(ptr != NULL);        printf("Unique strings:/n%s", unique);    free(addr);    return EXIT_SUCCESS;}
开发者ID:Salamander0,项目名称:Progtest,代码行数:21,


示例5: interactive

int interactive(usb_dev_handle* device) {	int len;	char* commandBuffer = NULL;	do {		do {			usleep(100000);			len = get_response(device);			if(len > 0) {				fwrite(response_buffer, 1, len, stdout);				fflush(stdout);			}		} while(len > 0 && strnstr(response_buffer, "] ", len) == NULL);		if(len < 0)			break;ProcessCommand:		if(commandBuffer != NULL)			free(commandBuffer);		commandBuffer = readline(NULL);		if(commandBuffer && *commandBuffer) {			add_history(commandBuffer);		}		if(strncmp(commandBuffer, "sendfile ", sizeof("sendfile ") - 1) == 0) {			char* file = commandBuffer + sizeof("sendfile ") - 1;			send_file(device, file);			goto ProcessCommand;		} else {			send_command(device, commandBuffer);			send_command(device, "/n");		}	} while(1);	return 0;}
开发者ID:cantona,项目名称:iphonelinux,代码行数:40,


示例6: proxy_client_process

static void proxy_client_process(int fd){    char buf[1024];    size_t buflen = 0;    ssize_t val;    /* Read request (and possibly more) */    while (strnstr(buf, "/r/n/r/n", buflen) == NULL)    {        val = recv(fd, buf + buflen, sizeof (buf) - buflen - 1, 0);        if (val <= 0)            assert(!"Incomplete request");        buflen += val;    }    buf[buflen] = '/0';    char host[64];    unsigned port, ver;    int offset;    assert(sscanf(buf, "CONNECT %63[^:]:%u HTTP/1.%1u%n", host, &port, &ver,                  &offset) == 3);    assert(!strcmp(host, "www.example.com"));    assert(port == 443);    assert(ver == 1);    assert(sscanf(buf + offset + 2, "Host: %63[^:]:%u", host, &port) == 2);    assert(!strcmp(host, "www.example.com"));    assert(port == 443);    assert(strstr(buf, "/r/nProxy-Authorization: Basic "                  "QWxhZGRpbjpvcGVuIHNlc2FtZQ==/r/n") != NULL);    const char resp[] = "HTTP/1.1 500 Failure/r/n/r/n";    val = write(fd, resp, strlen(resp));    assert((size_t)val == strlen(resp));    shutdown(fd, SHUT_WR);}
开发者ID:0xheart0,项目名称:vlc,代码行数:40,


示例7: end_outcache

voidend_outcache(){	char *ptr;	int len;	fclose(stdout);	*stdout = oldout;	if (!myoutbuf)		return;	ptr = strstr(myoutbuf, "/n/n");	if (!ptr) {		printf("/n/nfaint! 出毛病了...");		return;	}	if (strnstr(myoutbuf, "Content-type: ", ptr - myoutbuf)) {		len = myoutsize - (ptr - myoutbuf) - 2;		printf("Content-Length: %d/n", len);	}	fputs(myoutbuf, stdout);	free(myoutbuf);	myoutbuf = NULL;}
开发者ID:deepurple,项目名称:bbssrc,代码行数:22,


示例8: parse_ns_str

voidparse_ns_str(const char *ns_str, char *ctrlr_str, int *nsid){	char	*nsloc;	/*	 * Pull the namespace id from the string. +2 skips past the "ns" part	 *  of the string.  Don't search past 10 characters into the string,	 *  otherwise we know it is malformed.	 */	nsloc = strnstr(ns_str, NVME_NS_PREFIX, 10);	if (nsloc != NULL)		*nsid = strtol(nsloc + 2, NULL, 10);	if (nsloc == NULL || (*nsid == 0 && errno != 0))		errx(1, "invalid namespace ID '%s'", ns_str);	/*	 * The controller string will include only the nvmX part of the	 *  nvmeXnsY string.	 */	snprintf(ctrlr_str, nsloc - ns_str + 1, "%s", ns_str);}
开发者ID:2trill2spill,项目名称:freebsd,代码行数:22,


示例9: GetMachinePower

MachinePower GetMachinePower(){	char nameBuf[64];	size_t nameLen = sizeof(nameBuf);	memset(nameBuf, 0, sizeof(nameBuf));	sysctlbyname("hw.model", &nameBuf, &nameLen, NULL, NULL);	if (nameLen == 0)		return MACHINE_POWER_CAPABLE; // assume capable	else	{		// check our list		SDL_RWops* ops = ResourceManager::OpenFile("Config/MacModels.txt");		if (!ops)			return MACHINE_POWER_CAPABLE;		size_t length;		void* ptr = ResourceManager::ReadFull(&length, ops, 1);		if (!ptr)			return MACHINE_POWER_CAPABLE;		bool found = strnstr((const char*)ptr, nameBuf, length);		free(ptr);		return found ? MACHINE_POWER_MIGHTY : MACHINE_POWER_WIMPY;	}}
开发者ID:adam000,项目名称:Apollo,代码行数:23,


示例10: main

int main(int argc, char *argv[]){  if (argc < 2)    {      puts("Usage: ./mygrep <pattern> <name>");    }  else    {      FILE *f = fopen(argv[2], "r");      int str_len;      size_t buf_siz;      char *string;       char *pattern = argv[1];            while ((str_len = getline(&string, &buf_siz, f)) > 0)	{	  if (strnstr(string, pattern, str_len))	    printf("%s", string);	}      fclose(f);    }  return 0; }
开发者ID:roca5461,项目名称:ioopm15,代码行数:24,


示例11: doNetWork

void* doNetWork(struct threadData* td) {    /*Response Variables*/    struct http_request request;    int bytesSent;    int sendResponse;    int controller;    int status;    char * response;    /* Request variables */    int readAmount;    int totalRead;    int flags;     int j,k;    int contentLength;    int contentLengthRecieved;    int contentLengthPosition;    char * tempBuff;    char * raw_message;    char contentLengthBuff[100];    bytesSent = 0;    sendResponse =0;    response = malloc(sizeof(char)*STARTING_RESPONSE_SIZE);    if(response == NULL){        NETWORK_LOG_LEVEL_1("Fatal: Failed to allocate memory for response");        response = "{}";        status = 500;        goto internal_err;    }    memset(response,0,sizeof(char)*STARTING_RESPONSE_SIZE);    raw_message = malloc(1+sizeof(char)*BUFSIZ); /* Just enough space for the first read, to determine content length */    if(raw_message == NULL){        /* Internal Problem! */        NETWORK_LOG_LEVEL_1("Fatal: Failed to allocate memory for first-read temporary buffer");        response[0]='{'; response[1]='}'; response[2]='/0';        status = 500;        goto internal_err;    }    memset(raw_message, 0,1+sizeof(char)*BUFSIZ);    tempBuff = NULL; /* temp buff will be used to realloc */            /* Accept and read incoming request  */    if(td->clientfd == -1)        goto bad_client_id;    readAmount=totalRead=contentLengthRecieved =contentLengthPosition= contentLength = 0;    NETWORK_LOG_LEVEL_2_NUM("Accepted Client Request on File Descriptor ", td->clientfd);    readAmount = 1; /* Sentinal */    flags = fcntl(td->clientfd, F_GETFL, 0);    fcntl(td->clientfd, F_SETFL, flags | O_NONBLOCK);    contentLength = -1; /* Sentinal */    while(readAmount != 0){        readAmount = read(td->clientfd,raw_message+totalRead,BUFSIZ);            if(readAmount == -1){            if(errno == EAGAIN && totalRead == 0)                continue;            else if(contentLengthRecieved != contentLength)                continue;            else                readAmount = 0;        }else{            NETWORK_LOG_LEVEL_2_NUM("Reading Data From Socket", td->clientfd);            /* Since we're here that means we have at least              * the beginning of the request itself but we're             * waiting for more. So determine the content-length             * and then figure out if we have all of it or not            */            contentLengthPosition = strnstr("Content-Length", raw_message, BUFSIZ);                                if(contentLengthPosition == -1){                /* You didn't send us a content length, carry on!                  * so no data, so just url, so good bye.                */                contentLengthRecieved = contentLength = readAmount = 0;            }else{                if(totalRead == 0){                                                /* Convert the content length                     * reuse this connections buffer.                    */                    bzero(contentLengthBuff, sizeof contentLengthBuff); /* Only what we need */                    contentLength = contentLengthPosition;                    contentLength+=strlen("Content-Length: "); /* Skip the text */                                         for(k=0; k < (int)sizeof(contentLengthBuff) && *(raw_message + contentLength) != '/0' && *(raw_message + contentLength) != '/r'; ++k, contentLength++)                        contentLengthBuff[k] = *(raw_message + contentLength);                    contentLengthBuff[k] = '/0';                    contentLength = atoi(contentLengthBuff);                                                                    /* Malloc for the content Length                      * j is the position of the data, all things prior                      * need to be conserved as well                    */                    if( contentLength > 0 ){                        tempBuff = malloc(5+ strlen(raw_message) + contentLength + BUFSIZ);                        if(tempBuff == NULL){                            free(raw_message);                            NETWORK_LOG_LEVEL_1("Could not reallocate memory during request data acquisition");                            goto internal_err;//.........这里部分代码省略.........
开发者ID:EdgeCaseBerg,项目名称:green-serv,代码行数:101,


示例12: sizeof

void LogKlog::sniffTime(log_time &now,                        const char **buf, size_t len,                        bool reverse) {    const char *cp = now.strptime(*buf, "[ %s.%q]");    if (cp && (cp >= &(*buf)[len])) {        cp = NULL;    }    if (cp) {        static const char healthd[] = "healthd";        static const char battery[] = ": battery ";        len -= cp - *buf;        if (len && isspace(*cp)) {            ++cp;            --len;        }        *buf = cp;        if (isMonotonic()) {            return;        }        const char *b;        if (((b = strnstr(cp, len, suspendStr)))                && ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) {            len -= b - cp;            calculateCorrection(now, b, len);        } else if (((b = strnstr(cp, len, resumeStr)))                && ((size_t)((b += sizeof(resumeStr) - 1) - cp) < len)) {            len -= b - cp;            calculateCorrection(now, b, len);        } else if (((b = strnstr(cp, len, healthd)))                && ((size_t)((b += sizeof(healthd) - 1) - cp) < len)                && ((b = strnstr(b, len -= b - cp, battery)))                && ((size_t)((b += sizeof(battery) - 1) - cp) < len)) {            // NB: healthd is roughly 150us late, so we use it instead to            //     trigger a check for ntp-induced or hardware clock drift.            log_time real(CLOCK_REALTIME);            log_time mono(CLOCK_MONOTONIC);            correction = (real < mono) ? log_time::EPOCH : (real - mono);        } else if (((b = strnstr(cp, len, suspendedStr)))                && ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) {            len -= b - cp;            log_time real;            char *endp;            real.tv_sec = strtol(b, &endp, 10);            if ((*endp == '.') && ((size_t)(endp - b) < len)) {                unsigned long multiplier = NS_PER_SEC;                real.tv_nsec = 0;                len -= endp - b;                while (--len && isdigit(*++endp) && (multiplier /= 10)) {                    real.tv_nsec += (*endp - '0') * multiplier;                }                if (reverse) {                    if (real > correction) {                        correction = log_time::EPOCH;                    } else {                        correction -= real;                    }                } else {                    correction += real;                }            }        }        convertMonotonicToReal(now);    } else {        if (isMonotonic()) {            now = log_time(CLOCK_MONOTONIC);        } else {            now = log_time(CLOCK_REALTIME);        }    }}
开发者ID:ArtBears,项目名称:platform_system_core,代码行数:74,


示例13: OpenDemux

int OpenDemux( vlc_object_t* p_this ){    demux_t     *p_demux = (demux_t*)p_this;    demux_sys_t *p_sys;    const uint8_t *p_peek;    ssize_t i_peek = vlc_stream_Peek( p_demux->s, &p_peek, 2048 );    if( unlikely( i_peek <= 32 ) )        return VLC_EGENERIC;    const char *psz_xml = (const char *) p_peek;    size_t i_xml  = i_peek;    /* Try to probe without xml module/loading the full document */    char *psz_alloc = NULL;    switch( GetQWBE(p_peek) )    {        /* See RFC 3023 Part 4 */        case UINT64_C(0xFFFE3C003F007800): /* UTF16 BOM<? */        case UINT64_C(0xFFFE3C003F007400): /* UTF16 BOM<t */        case UINT64_C(0xFEFF003C003F0078): /* UTF16 BOM<? */        case UINT64_C(0xFEFF003C003F0074): /* UTF16 BOM<t */            psz_alloc = FromCharset( "UTF-16", p_peek, i_peek );            break;        case UINT64_C(0x3C003F0078006D00): /* UTF16-LE <?xm */        case UINT64_C(0x3C003F0074007400): /* UTF16-LE <tt */            psz_alloc = FromCharset( "UTF-16LE", p_peek, i_peek );            break;        case UINT64_C(0x003C003F0078006D): /* UTF16-BE <?xm */        case UINT64_C(0x003C003F00740074): /* UTF16-BE <tt */            psz_alloc = FromCharset( "UTF-16BE", p_peek, i_peek );            break;        case UINT64_C(0xEFBBBF3C3F786D6C): /* UTF8 BOM<?xml */        case UINT64_C(0x3C3F786D6C207665): /* UTF8 <?xml ve */        case UINT64_C(0xEFBBBF3C74742078): /* UTF8 BOM<tt x*/            break;        default:            if(GetDWBE(p_peek) != UINT32_C(0x3C747420)) /* tt node without xml document marker */                return VLC_EGENERIC;    }    if( psz_alloc )    {        psz_xml = psz_alloc;        i_xml = strlen( psz_alloc );    }    /* Simplified probing. Valid TTML must have a namespace declaration */    const char *psz_tt = strnstr( psz_xml, "tt ", i_xml );    if( !psz_tt || psz_tt == psz_xml ||        (psz_tt[-1] != ':' && psz_tt[-1] != '<') )    {        free( psz_alloc );        return VLC_EGENERIC;    }    else    {        const char * const rgsz[] =        {            "=/"http://www.w3.org/ns/ttml/"",            "=/"http://www.w3.org/2004/11/ttaf1/"",            "=/"http://www.w3.org/2006/04/ttaf1/"",            "=/"http://www.w3.org/2006/10/ttaf1/"",        };        const char *psz_ns = NULL;        for( size_t i=0; i<ARRAY_SIZE(rgsz) && !psz_ns; i++ )        {            psz_ns = strnstr( psz_xml, rgsz[i],                              i_xml - (psz_tt - psz_xml) );        }        free( psz_alloc );        if( !psz_ns )            return VLC_EGENERIC;    }    p_demux->p_sys = p_sys = calloc( 1, sizeof( *p_sys ) );    if( unlikely( p_sys == NULL ) )        return VLC_ENOMEM;    p_sys->b_first_time = true;    p_sys->temporal_extent.i_type = TT_TIMINGS_PARALLEL;    tt_time_Init( &p_sys->temporal_extent.begin );    tt_time_Init( &p_sys->temporal_extent.end );    tt_time_Init( &p_sys->temporal_extent.dur );    p_sys->temporal_extent.begin.base = 0;    p_sys->p_xml = xml_Create( p_demux );    if( !p_sys->p_xml )        goto error;    p_sys->p_reader = xml_ReaderCreate( p_sys->p_xml, p_demux->s );    if( !p_sys->p_reader )        goto error;#ifndef TTML_DEMUX_DEBUG    p_sys->p_reader->obj.flags |= OBJECT_FLAGS_QUIET;#endif    if( ReadTTML( p_demux ) != VLC_SUCCESS )        goto error;//.........这里部分代码省略.........
开发者ID:chouquette,项目名称:vlc,代码行数:101,


示例14: tps_pack_request

int tps_pack_request(sip_msg_t *msg, tps_data_t *ptsd){	hdr_field_t *hdr;	via_body_t *via;	rr_t *rr;	int i;	int vlen;	if(ptsd->cp==NULL) {		ptsd->cp = ptsd->cbuf;	}	i = 0;	for(hdr=msg->h_via1; hdr; hdr=next_sibling_hdr(hdr)) {		for(via=(struct via_body*)hdr->parsed; via; via=via->next) {			i++;			vlen = tps_skip_rw(via->name.s, via->bsize);			if(ptsd->cp + vlen + 2 >= ptsd->cbuf + TPS_DATA_SIZE) {				LM_ERR("no more spage to pack via headers/n");				return -1;			}			if(i>1) {				*ptsd->cp = ',';				ptsd->cp++;				if(i>2) {					ptsd->x_via2.len++;				}			}			memcpy(ptsd->cp, via->name.s, vlen);			if(i==1) {				ptsd->x_via1.s = ptsd->cp;				ptsd->x_via1.len = vlen;				if(via->branch!=NULL) {					ptsd->x_vbranch1.s = ptsd->x_via1.s + (via->branch->value.s - via->name.s);					ptsd->x_vbranch1.len = via->branch->value.len;				}			} else {				if(i==2) {					ptsd->x_via2.s = ptsd->cp;				}				ptsd->x_via2.len += vlen;			}			ptsd->cp += vlen;		}	}	LM_DBG("compacted headers - x_via1: [%.*s](%d) - x_via2: [%.*s](%d)"			" - x_vbranch1: [%.*s](%d)/n",			ptsd->x_via1.len, ZSW(ptsd->x_via1.s), ptsd->x_via1.len,			ptsd->x_via2.len, ZSW(ptsd->x_via2.s), ptsd->x_via2.len,			ptsd->x_vbranch1.len, ZSW(ptsd->x_vbranch1.s), ptsd->x_vbranch1.len);	i = 0;	ptsd->a_rr.len = 0;	for(hdr=msg->record_route; hdr; hdr=next_sibling_hdr(hdr)) {		if (parse_rr(hdr) < 0) {			LM_ERR("failed to parse RR/n");			return -1;		}		for(rr =(rr_t*)hdr->parsed; rr; rr=rr->next) {			i++;			if(ptsd->cp + rr->nameaddr.uri.len + 4 >= ptsd->cbuf + TPS_DATA_SIZE) {				LM_ERR("no more spage to pack rr headers/n");				return -1;			}			if(i>1) {				*ptsd->cp = ',';				ptsd->cp++;				ptsd->a_rr.len++;			}			*ptsd->cp = '<';			if(i==1) {				ptsd->a_rr.s = ptsd->cp;			}			ptsd->cp++;			ptsd->a_rr.len++;			memcpy(ptsd->cp, rr->nameaddr.uri.s, rr->nameaddr.uri.len);			if(i==1) {				ptsd->bs_contact.s = ptsd->cp;				ptsd->bs_contact.len = rr->nameaddr.uri.len;				if(strnstr(ptsd->bs_contact.s, ";r2=on",							ptsd->bs_contact.len)==NULL) {					LM_DBG("single record routing by proxy/n");					ptsd->as_contact.s = ptsd->cp;					ptsd->as_contact.len = rr->nameaddr.uri.len;				}			} else {				if(i==2 && ptsd->as_contact.len==0) {					LM_DBG("double record routing by proxy/n");					ptsd->as_contact.s = ptsd->cp;					ptsd->as_contact.len = rr->nameaddr.uri.len;				}			}			ptsd->a_rr.len += rr->nameaddr.uri.len;			ptsd->cp += rr->nameaddr.uri.len;			*ptsd->cp = '>';			ptsd->cp++;			ptsd->a_rr.len++;		}//.........这里部分代码省略.........
开发者ID:cloudvox,项目名称:kamailio,代码行数:101,


示例15: reset

//.........这里部分代码省略.........		// if no start was found, must have had a 0 score in there		if ( start == -1 ) {			continue;		}		// if we exhausted the doc, we are done		if ( i >= NW ) {			break;		}		// skip if way too big!		if ( i >= max ) {			continue;		}		// if was too long do not consider a title		if ( i - start > 300 ) {			continue;		}		// . skip if too many bytes		// . this does not include the length of word #i, but #(i-1)		if ( words->getStringSize ( start , i ) > 1000 ) {			continue;		}		// when using pdftohtml, the title tag is the filename when PDF property does not have title tag		if ( tid == TAG_TITLE && contentType == CT_PDF ) {			// skip if title == '/in.[0-9]*'			char* title_start = words->getWord(start);			char* title_end = words->getWord(i);			size_t title_size = title_end - title_start;			const char* result = strnstr( title_start, "/in.", title_size );			if (result != NULL) {				char* endp = NULL;				// do some further verification to avoid screwing up title				if ((strtoll(result + 4, &endp, 10) > 0) && (endp == title_end)) {					continue;				}			}		}		// count it		table[tid]++;		// max it out if we are positive scoring. stop after the		// first positive scoring guy in a section. this might		// hurt the "Hamlet" thing though...		// store a point to the title tag guy. Msg20.cpp needs this		// because the zak's proximity algo uses it in Summary.cpp		// and in Msg20.cpp		// only get the first one! often the 2nd on is in an iframe!! which we now expand into here.		if ( tid == TAG_TITLE && m_titleTagStart == -1 ) {			m_titleTagStart = start;			m_titleTagEnd   = i;			// save the candidate # because we always use this			// as the title if we are a root			if ( tti < 0 ) {				tti = n;			}		}
开发者ID:lemire,项目名称:open-source-search-engine,代码行数:66,


示例16: db_input_wrapper

//.........这里部分代码省略.........    if(gzeof(*db_gzp)){      retval=0;      buf[0]='/0';    }else {      if((retval=gzread(*db_gzp,buf,max_size))<0){	error(0,_("gzread() failed: gzerr=%s!/n"),gzerror(*db_gzp,&err));	retval=0;	buf[0]='/0';      } else {	/* gzread returns 0 even if uncompressed bytes were read*/	error(240,"nread=%d,strlen(buf)=%lu,errno=%s,gzerr=%s/n",              retval,(unsigned long)strnlen((char*)buf, max_size),              strerror(errno),gzerror(*db_gzp,&err));	if(retval==0){	  retval=strnlen((char*)buf, max_size);	}      }    }  }  if((*db_gzp!=NULL)&&!(*domd)){    c=gzgetc(*db_gzp);    retval= (c==EOF) ? 0 : (buf[0] = c,1);  }  if((*db_gzp==NULL)&&!(*domd)){    c=fgetc(*db_filep);    if(c==(unsigned char)'/037'){      c=fgetc(*db_filep);      if(c==(unsigned char)'/213'){	/* We got gzip header. */	error(255,"Got Gzip header. Handling../n");	lseek(fileno(*db_filep),0L,SEEK_SET);	*db_gzp=gzdopen(fileno(*db_filep),"rb");	c=gzgetc(*db_gzp);	error(255,"First character after gzip header is: %c(%#X)/n",c,c);  if(c==-1) {    int xx;	  error(0,"Error reading gzipped file: %s/n",gzerror(*db_gzp,&xx));    exit(EXIT_FAILURE);  }      }else {	/* False alarm */	ungetc(c,*db_filep);      }    }    retval= (c==EOF) ? 0 : (buf[0] = c,1);  }#else /* WITH_ZLIB */#ifdef WITH_MHASH  if(*domd){    retval=fread(buf,1,max_size,*db_filep);  }else {    c=fgetc(*db_filep);    retval= (c==EOF) ? 0 : (buf[0] = c,1);  }#else /* WITH_MHASH */  retval=fread(buf,1,max_size,*db_filep);#endif /* WITH_MHASH */ #endif /* WITH_ZLIB */#ifdef WITH_MHASH      if(*domd){    if(!*md){      if((key=get_db_key())!=NULL){	keylen=get_db_key_len();		if( (*md=	     mhash_hmac_init(conf->dbhmactype,			     key,			     keylen,			     mhash_get_hash_pblock(conf->dbhmactype)))==	    MHASH_FAILED){	  error(0, "mhash_hmac_init() failed for db check. Aborting/n");	  exit(EXIT_FAILURE);	}      } else {	*domd=0;      }    }    /* FIXME This does not handle the case that @@end_config is on        buffer boundary. */    if (*domd!=0) {      if((tmp=strnstr(buf,"@@end_db",retval))!=NULL){	/* We have end of db don't feed the last line to mhash */	mhash(*md,(void*)buf,tmp-buf);	/* We don't want to come here again after the *md has been deinited 	   by db_readline_file() */	*domd=0;      } else {	mhash(*md,(void*)buf,retval);      }    }  }#endif#ifdef WITH_CURL  }#endif /* WITH CURL */  return retval;}
开发者ID:kotasher,项目名称:coverity,代码行数:101,


示例17: stm401_irq_wake_work_func

void stm401_irq_wake_work_func(struct work_struct *work){    int err;    unsigned short irq_status;    u32 irq2_status;    uint8_t irq3_status;    struct stm401_data *ps_stm401 = container_of(work,                                    struct stm401_data, irq_wake_work);    dev_dbg(&ps_stm401->client->dev, "stm401_irq_wake_work_func/n");    mutex_lock(&ps_stm401->lock);    if (ps_stm401->mode == BOOTMODE)        goto EXIT_NO_WAKE;    /* This is to handle the case of receiving an interrupt after       suspend_late, but before interrupts were globally disabled. If this       is the case, interrupts might be disabled now, so we cannot handle       this at this time. suspend_noirq will return BUSY if this happens       so that we can handle these interrupts. */    if (ps_stm401->ignore_wakeable_interrupts) {        dev_info(&ps_stm401->client->dev,                 "Deferring interrupt work/n");        ps_stm401->ignored_interrupts++;        goto EXIT_NO_WAKE;    }    stm401_wake(ps_stm401);    /* read interrupt mask register */    stm401_cmdbuff[0] = WAKESENSOR_STATUS;    err = stm401_i2c_write_read(ps_stm401, stm401_cmdbuff, 1, 2);    if (err < 0) {        dev_err(&ps_stm401->client->dev, "Reading from stm401 failed/n");        goto EXIT;    }    irq_status = (stm401_readbuff[IRQ_WAKE_MED] << 8)                 | stm401_readbuff[IRQ_WAKE_LO];    /* read algorithm interrupt status register */    stm401_cmdbuff[0] = ALGO_INT_STATUS;    err = stm401_i2c_write_read(ps_stm401, stm401_cmdbuff, 1, 3);    if (err < 0) {        dev_err(&ps_stm401->client->dev, "Reading from stm401 failed/n");        goto EXIT;    }    irq2_status = (stm401_readbuff[IRQ_WAKE_HI] << 16) |                  (stm401_readbuff[IRQ_WAKE_MED] << 8) |                  stm401_readbuff[IRQ_WAKE_LO];    /* read generic interrupt register */    stm401_cmdbuff[0] = GENERIC_INT_STATUS;    err = stm401_i2c_write_read(ps_stm401, stm401_cmdbuff, 1, 1);    if (err < 0) {        dev_err(&ps_stm401->client->dev, "Reading from stm failed/n");        goto EXIT;    }    irq3_status = stm401_readbuff[0];    if (ps_stm401->qw_irq_status) {        irq_status |= ps_stm401->qw_irq_status;        ps_stm401->qw_irq_status = 0;    }    /* First, check for error messages */    if (irq_status & M_LOG_MSG) {        stm401_cmdbuff[0] = ERROR_STATUS;        err = stm401_i2c_write_read(ps_stm401, stm401_cmdbuff,                                    1, ESR_SIZE);        if (err >= 0) {            memcpy(stat_string, stm401_readbuff, ESR_SIZE);            stat_string[ESR_SIZE] = 0;            dev_err(&ps_stm401->client->dev,                    "STM401 Error: %s/n", stat_string);        } else            dev_err(&ps_stm401->client->dev,                    "Failed to read error message %d/n", err);    }    /* Second, check for a reset request */    if (irq_status & M_HUB_RESET) {        unsigned char status;        if (strnstr(stat_string, "modality", ESR_SIZE))            status = 0x01;        else if (strnstr(stat_string, "Algo", ESR_SIZE))            status = 0x02;        else if (strnstr(stat_string, "Watchdog", ESR_SIZE))            status = 0x03;        else            status = 0x04;        stm401_as_data_buffer_write(ps_stm401, DT_RESET, &status, 1, 0);        stm401_reset_and_init();        dev_err(&ps_stm401->client->dev, "STM401 requested a reset/n");        goto EXIT;    }    /* Check all other status bits *///.........这里部分代码省略.........
开发者ID:itsmerajit,项目名称:kernel_otus,代码行数:101,


示例18: whois

static voidwhois(const char *query, const char *hostname, int flags){	FILE *sfi, *sfo;	struct addrinfo *hostres, *res;	char *buf, *host, *nhost, *p;	int i, s;	size_t c, len;	hostres = gethostinfo(hostname, 1);	for (res = hostres; res; res = res->ai_next) {		s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);		if (s < 0)			continue;		if (connect(s, res->ai_addr, res->ai_addrlen) == 0)			break;		close(s);	}	freeaddrinfo(hostres);	if (res == NULL)		err(EX_OSERR, "connect()");	sfi = fdopen(s, "r");	sfo = fdopen(s, "w");	if (sfi == NULL || sfo == NULL)		err(EX_OSERR, "fdopen()");	if (strcmp(hostname, GERMNICHOST) == 0) {#ifdef __APPLE__		/* radar:18958875 radar:21503897 */		fprintf(sfo, "-T dn -C UTF-8 %s/r/n", query);#else		fprintf(sfo, "-T dn,ace -C US-ASCII %s/r/n", query);#endif	} else {		fprintf(sfo, "%s/r/n", query);	}	fflush(sfo);	nhost = NULL;	while ((buf = fgetln(sfi, &len)) != NULL) {		while (len > 0 && isspace((unsigned char)buf[len - 1]))			buf[--len] = '/0';		printf("%.*s/n", (int)len, buf);		if ((flags & WHOIS_RECURSE) && nhost == NULL) {			host = strnstr(buf, WHOIS_SERVER_ID, len);			if (host != NULL) {				host += sizeof(WHOIS_SERVER_ID) - 1;				for (p = host; p < buf + len; p++) {					if (!ishost(*p)) {						*p = '/0';						break;					}				}				s_asprintf(&nhost, "%.*s",				     (int)(buf + len - host), host);			} else if ((host =			    strnstr(buf, WHOIS_ORG_SERVER_ID, len)) != NULL) {				host += sizeof(WHOIS_ORG_SERVER_ID) - 1;				for (p = host; p < buf + len; p++) {					if (!ishost(*p)) {						*p = '/0';						break;					}				}				s_asprintf(&nhost, "%.*s",				    (int)(buf + len - host), host);			} else if (strcmp(hostname, ANICHOST) == 0) {				for (c = 0; c <= len; c++)					buf[c] = tolower((int)buf[c]);				for (i = 0; ip_whois[i] != NULL; i++) {					if (strnstr(buf, ip_whois[i], len) !=					    NULL) {						s_asprintf(&nhost, "%s",						    ip_whois[i]);						break;					}				}			}		}	}	if (nhost != NULL) {		whois(query, nhost, 0);		free(nhost);	}}
开发者ID:hnw,项目名称:iOS-WhoisCmd,代码行数:85,


示例19: fetch_ssl_hname_match

/* * Check if the host name h passed matches the pattern passed in m which * is usually part of subjectAltName or CN of a certificate presented to * the client. This includes wildcard matching. The algorithm is based on * RFC6125, sections 6.4.3 and 7.2, which clarifies RFC2818 and RFC3280. */static intfetch_ssl_hname_match(const char *h, size_t hlen, const char *m,    size_t mlen){	int delta, hdotidx, mdot1idx, wcidx;	const char *hdot, *mdot1, *mdot2;	const char *wc; /* wildcard */	if (!(h && *h && m && *m))		return (0);	if ((wc = strnstr(m, "*", mlen)) == NULL)		return (fetch_ssl_hname_equal(h, hlen, m, mlen));	wcidx = wc - m;	/* hostname should not be just dots and numbers */	if (fetch_ssl_hname_is_only_numbers(h, hlen))		return (0);	/* only one wildcard allowed in pattern */	if (strnstr(wc + 1, "*", mlen - wcidx - 1) != NULL)		return (0);	/*	 * there must be at least two more domain labels and	 * wildcard has to be in the leftmost label (RFC6125)	 */	mdot1 = strnstr(m, ".", mlen);	if (mdot1 == NULL || mdot1 < wc || (mlen - (mdot1 - m)) < 4)		return (0);	mdot1idx = mdot1 - m;	mdot2 = strnstr(mdot1 + 1, ".", mlen - mdot1idx - 1);	if (mdot2 == NULL || (mlen - (mdot2 - m)) < 2)		return (0);	/* hostname must contain a dot and not be the 1st char */	hdot = strnstr(h, ".", hlen);	if (hdot == NULL || hdot == h)		return (0);	hdotidx = hdot - h;	/*	 * host part of hostname must be at least as long as	 * pattern it's supposed to match	 */	if (hdotidx < mdot1idx)		return (0);	/*	 * don't allow wildcards in non-traditional domain names	 * (IDN, A-label, U-label...)	 */	if (!fetch_ssl_is_trad_domain_label(h, hdotidx, 0) ||	    !fetch_ssl_is_trad_domain_label(m, mdot1idx, 1))		return (0);	/* match domain part (part after first dot) */	if (!fetch_ssl_hname_equal(hdot, hlen - hdotidx, mdot1,	    mlen - mdot1idx))		return (0);	/* match part left of wildcard */	if (!fetch_ssl_hname_equal(h, wcidx, m, wcidx))		return (0);	/* match part right of wildcard */	delta = mdot1idx - wcidx - 1;	if (!fetch_ssl_hname_equal(hdot - delta, delta,	    mdot1 - delta, delta))		return (0);	/* all tests succeded, it's a match */	return (1);}
开发者ID:ChristosKa,项目名称:freebsd,代码行数:69,


示例20: recv

Network::Err Network::handleConnection(SocketData* conn){	int connSock = conn->fd;	char* buffer = conn->readBuf;	size_t toRead = readBufSize - conn->readLen;	ssize_t receivedBytes = recv(connSock, buffer + conn->readLen, toRead, 0);	if (receivedBytes == -1)	{		Log::err("recv(): %s", strerror(errno));		if (close(connSock) == -1)		{			Log::err("close(): %s", strerror(errno));		}		return Err::Process;	}	else if (receivedBytes == 0)	{		Log::info("Closing disconnected socket");		if (close(connSock) == -1)		{			Log::err("close(): %s", strerror(errno));		}		return Err::Process;	}		conn->readLen += receivedBytes;	receivedBytes = conn->readLen;		if (strnstr(buffer, "/r/n/r/n", receivedBytes) == nullptr		&& strnstr(buffer, "/r/r", receivedBytes) == nullptr		&& strnstr(buffer, "/n/n", receivedBytes) == nullptr)	{		if (receivedBytes == readBufSize)		{			if (close(connSock) == -1)			{				Log::err("close(): %s", strerror(errno));			}			return Err::Process;		}				return Err::ReadMore;	}		char* rPos = (char*)memchr(buffer, '/r', receivedBytes);	char* nPos = (char*)memchr(buffer, '/n', receivedBytes);		char* lineEndPos = nPos;	if (nPos == nullptr || (rPos != nullptr && rPos < nPos))	{		lineEndPos = rPos;	}		RequestResult res;	RequestErr status;	size_t requestLineLen;	if (lineEndPos == nullptr)	{		requestLineLen = receivedBytes;		status = RequestErr::BAD_REQUEST;		res.version = HttpVersion::V1_0;	}	else	{		requestLineLen = lineEndPos - buffer;		status = readRequestLine(buffer, requestLineLen, res);	}		char pathBuff[1024];	const char* path = nullptr;		switch (status)	{	case RequestErr::OK:		{			int unescapedLen = unescape(res.path, pathBuff, res.pathLen);			if (unescapedLen == -1)			{				status = RequestErr::BAD_REQUEST;				path = "/400.html";			}			else			{										pathBuff[unescapedLen] = 0;				path = pathBuff;			}		}		break;			case RequestErr::BAD_REQUEST:		path = "/400.html";		break;			case RequestErr::FORBIDDEN:		path = "/403.html";		break;			case RequestErr::NOT_FOUND:		path = "/404.html";		break;//.........这里部分代码省略.........
开发者ID:Philldomd,项目名称:UNIX-Lab2,代码行数:101,


示例21: sizeof

void LogKlog::sniffTime(log_time &now,                        const char **buf, size_t len,                        bool reverse) {    const char *cp = now.strptime(*buf, "[ %s.%q]");    if (cp && (cp >= &(*buf)[len])) {        cp = NULL;    }    len -= cp - *buf;    if (cp) {        static const char healthd[] = "healthd";        static const char battery[] = ": battery ";        if (len && isspace(*cp)) {            ++cp;            --len;        }        *buf = cp;        const char *b;        if (((b = strnstr(cp, len, suspendStr)))                && ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) {            len -= b - cp;            calculateCorrection(now, b, len);        } else if (((b = strnstr(cp, len, resumeStr)))                && ((size_t)((b += sizeof(resumeStr) - 1) - cp) < len)) {            len -= b - cp;            calculateCorrection(now, b, len);        } else if (((b = strnstr(cp, len, healthd)))                && ((size_t)((b += sizeof(healthd) - 1) - cp) < len)                && ((b = strnstr(b, len -= b - cp, battery)))                && ((size_t)((b += sizeof(battery) - 1) - cp) < len)) {            len -= b - cp;            // NB: healthd is roughly 150us late, worth the price to deal with            //     ntp-induced or hardware clock drift.            // look for " 2???-??-?? ??:??:??.????????? ???"            for (; len && *b && (*b != '/n'); ++b, --len) {                if ((b[0] == ' ') && (b[1] == '2') && (b[5] == '-')) {                    calculateCorrection(now, b + 1, len - 1);                    break;                }            }        } else if (((b = strnstr(cp, len, suspendedStr)))                && ((size_t)((b += sizeof(suspendStr) - 1) - cp) < len)) {            len -= b - cp;            log_time real;            char *endp;            real.tv_sec = strtol(b, &endp, 10);            if ((*endp == '.') && ((size_t)(endp - b) < len)) {                unsigned long multiplier = NS_PER_SEC;                real.tv_nsec = 0;                len -= endp - b;                while (--len && isdigit(*++endp) && (multiplier /= 10)) {                    real.tv_nsec += (*endp - '0') * multiplier;                }                if (reverse) {                    correction -= real;                } else {                    correction += real;                }            }        }        convertMonotonicToReal(now);    } else {        now = log_time(CLOCK_REALTIME);    }}
开发者ID:josh64chen,项目名称:platform_system_core,代码行数:67,


示例22: do_sip_reply_invite

int do_sip_reply_invite(pvp_uthttp put, char **ut_buf, u32 *pack_len){    const static char FLG_INIP4[] = "IN IP4 ";    const static char FLG_VPORT[] = "m=video ";    char cli_ip[16] = {0}; // outer server ip    char   *pstr = NULL;    char   sport[8] = {0};    /*Source port*/    char r_src[64] = {0};    char r_dst[64] = {0};    char lip[16] = {0};    char dip[16] = {0};    char *ptr = NULL;    u16 nlport = 0;    char call_id[128] = {0};    puts("******** 1");    if ((pstr = strstr(*ut_buf, FLG_VPORT)) != NULL)    {    puts("******** 2");    puts(*ut_buf);        pstr += sizeof(FLG_VPORT)-1;        sscanf(pstr, "%[0-9]", sport);        if ((nlport = pplist_getidle_port_x()) == 0)        {            logwar_out("get idle port failed!");            return -1;        }    puts("******** 3");        // replace ip        if ((ptr = strnstr(*ut_buf, FLG_INIP4, *pack_len, true)) != NULL)        {            ptr += sizeof(FLG_INIP4)-1;            sscanf(ptr, "%[0-9.]", dip);            inet_ultoa(__gg.outer_addr, lip);            sprintf(r_src, "%s%s", FLG_INIP4, dip);            //sprintf(r_dst, "%s%s", FLG_INIP4, g_value[L_AUTHIP]);            sprintf(r_dst, "%s%s", FLG_INIP4, lip);            strreplace_pos(NULL, NULL, ut_buf, r_src, r_dst, -1, pack_len);        }    puts("******** 4");        // replace port        sprintf(r_src, "%s%s", FLG_VPORT, sport);        sprintf(r_dst, "%s%d", FLG_VPORT, nlport);        strreplace_pos(NULL,NULL, ut_buf, r_src, r_dst, 1, pack_len);                inet_ultoa(put->src_ip, cli_ip);        // replace invite ip        replace_cmd_ip_port(ut_buf, pack_len, cli_ip, put->src_port);    puts("******** 5");        // start proxy        char camera_id[32] = {0};        int ret = -1;        clivlist *pcvn = NULL;        if (oss_malloc(&pcvn, sizeof(clivlist)) < 0)            return -1;        get_virtual_cameraid(camera_id);        strcpy(pcvn->visit_user, cli_ip);        strcpy(pcvn->camera_id, camera_id);        //if (is_tms())            //pcvn->lip = __gg.inner_addr;        //else            pcvn->lip = __gg.outer_addr;        pcvn->dip = inet_atoul(dip);        pcvn->lvport = nlport;        pcvn->dvport = atoi(sport);        pcvn->platform_id = a_get_pmid();        // pcvn->vstream_tout = put->session_tout;   //        // 信令超时时间需要很长,如果视频流使用相同超时时间,会有大量已经使用完的视频进程逗留在系统中        pcvn->vstream_tout = 60;        pcvn->bind_video_port = nlport;    puts("******** 6");        if (get_call_id(*ut_buf, *pack_len, call_id, sizeof(call_id)) == NULL)            logdbg_out("获取Call id 失败!");        else if ( ! gl_set_data(call_id, (char*)&nlport, sizeof(nlport)))            logdbg_out("记录Call id 失败!");            ret = __start_vs_udp_proxy(pcvn, true, __gg.ferry_port + 1);        oss_free(&pcvn);        //sip_replace_contact(ut_buf, pack_len, g_value[L_AUTHIP], 5060);        //do_sip_reply_replace_by_key(put, SIP_FLAG_CONTACT, ut_buf, pack_len);    }    return 1;}
开发者ID:dulton,项目名称:solotools,代码行数:90,


示例23: parseKernelPrio

//// log a message into the kernel log buffer//// Filter rules to parse <PRI> <TIME> <tag> and <message> in order for// them to appear correct in the logcat output://// LOG_KERN (0):// <PRI>[<TIME>] <tag> ":" <message>// <PRI>[<TIME>] <tag> <tag> ":" <message>// <PRI>[<TIME>] <tag> <tag>_work ":" <message>// <PRI>[<TIME>] <tag> '<tag>.<num>' ":" <message>// <PRI>[<TIME>] <tag> '<tag><num>' ":" <message>// <PRI>[<TIME>] <tag>_host '<tag>.<num>' ":" <message>// (unimplemented) <PRI>[<TIME>] <tag> '<num>.<tag>' ":" <message>// <PRI>[<TIME>] "[INFO]"<tag> : <message>// <PRI>[<TIME>] "------------[ cut here ]------------"   (?)// <PRI>[<TIME>] "---[ end trace 3225a3070ca3e4ac ]---"   (?)// LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, LOG_SYSLOG, LOG_LPR, LOG_NEWS// LOG_UUCP, LOG_CRON, LOG_AUTHPRIV, LOG_FTP:// <PRI+TAG>[<TIME>] (see sys/syslog.h)// Observe://  Minimum tag length = 3   NB: drops things like r5:c00bbadf, but allow PM://  Maximum tag words = 2//  Maximum tag length = 16  NB: we are thinking of how ugly logcat can get.//  Not a Tag if there is no message content.//  leading additional spaces means no tag, inherit last tag.//  Not a Tag if <tag>: is "ERROR:", "WARNING:", "INFO:" or "CPU:"// Drop://  empty messages//  messages with ' audit(' in them if auditd is running//  logd.klogd:// return -1 if message logd.klogd: <signature>//int LogKlog::log(const char *buf, size_t len) {    if (auditd && strnstr(buf, len, " audit(")) {        return 0;    }    const char *p = buf;    int pri = parseKernelPrio(&p, len);    log_time now;    sniffTime(now, &p, len - (p - buf), false);    // sniff for start marker    const char klogd_message[] = "logd.klogd: ";    const char *start = strnstr(p, len - (p - buf), klogd_message);    if (start) {        uint64_t sig = strtoll(start + sizeof(klogd_message) - 1, NULL, 10);        if (sig == signature.nsec()) {            if (initialized) {                enableLogging = true;            } else {                enableLogging = false;            }            return -1;        }        return 0;    }    if (!enableLogging) {        return 0;    }    // Parse pid, tid and uid    const pid_t pid = sniffPid(p, len - (p - buf));    const pid_t tid = pid;    const uid_t uid = pid ? logbuf->pidToUid(pid) : 0;    // Parse (rules at top) to pull out a tag from the incoming kernel message.    // Some may view the following as an ugly heuristic, the desire is to    // beautify the kernel logs into an Android Logging format; the goal is    // admirable but costly.    while ((isspace(*p) || !*p) && (p < &buf[len])) {        ++p;    }    if (p >= &buf[len]) { // timestamp, no content        return 0;    }    start = p;    const char *tag = "";    const char *etag = tag;    size_t taglen = len - (p - buf);    if (!isspace(*p) && *p) {        const char *bt, *et, *cp;        bt = p;        if (!strncmp(p, "[INFO]", 6)) {            // <PRI>[<TIME>] "[INFO]"<tag> ":" message            bt = p + 6;            taglen -= 6;        }        for(et = bt; taglen && *et && (*et != ':') && !isspace(*et); ++et, --taglen) {           // skip ':' within [ ... ]           if (*et == '[') {               while (taglen && *et && *et != ']') {                   ++et;                   --taglen;               }            }//.........这里部分代码省略.........
开发者ID:josh64chen,项目名称:platform_system_core,代码行数:101,


示例24: strlen

/** * mdss_dsi_find_panel_of_node(): find device node of dsi panel * @pdev: platform_device of the dsi ctrl node * @panel_cfg: string containing intf specific config data * * Function finds the panel device node using the interface * specific configuration data. This configuration data is * could be derived from the result of bootloader's GCDB * panel detection mechanism. If such config data doesn't * exist then this panel returns the default panel configured * in the device tree. * * returns pointer to panel node on success, NULL on error. */static struct device_node *mdss_dsi_find_panel_of_node(	struct platform_device *pdev, char *panel_cfg,	struct mdss_dsi_ctrl_pdata *ctrl_pdata){	int len, i;	int ctrl_id = pdev->id - 1;	char panel_name[MDSS_MAX_PANEL_LEN];	char ctrl_id_stream[3] =  "0:";	char *stream = NULL, *pan = NULL;	struct device_node *dsi_pan_node = NULL, *mdss_node = NULL;	len = strlen(panel_cfg);	if (!len) {		dsi_pan_node = mdss_dsi_panel_search_dt_nodes(pdev,								ctrl_pdata);		if (dsi_pan_node)			return dsi_pan_node;		/* no panel cfg chg, parse dt */		pr_debug("%s:%d: no cmd line cfg present/n",			 __func__, __LINE__);		goto end;	} else {		if (ctrl_id == 1)			strlcpy(ctrl_id_stream, "1:", 3);		stream = strnstr(panel_cfg, ctrl_id_stream, len);		if (!stream) {			pr_err("controller config is not present/n");			goto end;		}		stream += 2;		pan = strnchr(stream, strlen(stream), ':');		if (!pan) {			strlcpy(panel_name, stream, MDSS_MAX_PANEL_LEN);		} else {			for (i = 0; (stream + i) < pan; i++)				panel_name[i] = *(stream + i);			panel_name[i] = 0;		}		pr_debug("%s:%d:%s:%s/n", __func__, __LINE__,			 panel_cfg, panel_name);		mdss_node = of_parse_phandle(pdev->dev.of_node,					     "qcom,mdss-mdp", 0);		if (!mdss_node) {			pr_err("%s: %d: mdss_node null/n",			       __func__, __LINE__);			return NULL;		}		dsi_pan_node = of_find_node_by_name(mdss_node,						    panel_name);		if (!dsi_pan_node) {			pr_err("%s: invalid pan node, selecting prim panel/n",			       __func__);			goto end;		}		return dsi_pan_node;	}end:	dsi_pan_node = mdss_dsi_pref_prim_panel(pdev);	return dsi_pan_node;}
开发者ID:FenoROM,项目名称:FenomenalMOD-Kernel,代码行数:81,


示例25: extractResponseCode

int WebSocketHandshake::readServerHandshake(const char* header, size_t len){    m_mode = Incomplete;    if (len < sizeof(webSocketServerHandshakeHeader) - 1) {        // Just hasn't been received fully yet.        return -1;    }    if (!memcmp(header, webSocketServerHandshakeHeader, sizeof(webSocketServerHandshakeHeader) - 1))        m_mode = Normal;    else {        const String& code = extractResponseCode(header, len);        if (code.isNull()) {            m_context->addMessage(ConsoleDestination, JSMessageSource, LogMessageType, ErrorMessageLevel, "Short server handshake: " + String(header, len), 0, clientOrigin());            return -1;        }        if (code.isEmpty()) {            m_mode = Failed;            m_context->addMessage(ConsoleDestination, JSMessageSource, LogMessageType, ErrorMessageLevel, "No response code found: " + String(header, len), 0, clientOrigin());            return len;        }        LOG(Network, "response code: %s", code.utf8().data());        if (code == "401") {            m_mode = Failed;            m_context->addMessage(ConsoleDestination, JSMessageSource, LogMessageType, ErrorMessageLevel, "Authentication required, but not implemented yet.", 0, clientOrigin());            return len;        } else {            m_mode = Failed;            m_context->addMessage(ConsoleDestination, JSMessageSource, LogMessageType, ErrorMessageLevel, "Unexpected response code:" + code, 0, clientOrigin());            return len;        }    }    const char* p = header + sizeof(webSocketServerHandshakeHeader) - 1;    const char* end = header + len + 1;    if (m_mode == Normal) {        size_t headerSize = end - p;        if (headerSize < sizeof(webSocketUpgradeHeader) - 1) {            m_mode = Incomplete;            return 0;        }        if (memcmp(p, webSocketUpgradeHeader, sizeof(webSocketUpgradeHeader) - 1)) {            m_mode = Failed;            m_context->addMessage(ConsoleDestination, JSMessageSource, LogMessageType, ErrorMessageLevel, "Bad Upgrade header: " + String(p, end - p), 0, clientOrigin());            return p - header + sizeof(webSocketUpgradeHeader) - 1;        }        p += sizeof(webSocketUpgradeHeader) - 1;        headerSize = end - p;        if (headerSize < sizeof(webSocketConnectionHeader) - 1) {            m_mode = Incomplete;            return -1;        }        if (memcmp(p, webSocketConnectionHeader, sizeof(webSocketConnectionHeader) - 1)) {            m_mode = Failed;            m_context->addMessage(ConsoleDestination, JSMessageSource, LogMessageType, ErrorMessageLevel, "Bad Connection header: " + String(p, end - p), 0, clientOrigin());            return p - header + sizeof(webSocketConnectionHeader) - 1;        }        p += sizeof(webSocketConnectionHeader) - 1;    }    if (!strnstr(p, "/r/n/r/n", end - p)) {        // Just hasn't been received fully yet.        m_mode = Incomplete;        return -1;    }    HTTPHeaderMap headers;    p = readHTTPHeaders(p, end, &headers);    if (!p) {        LOG(Network, "readHTTPHeaders failed");        m_mode = Failed;        return len;    }    if (!processHeaders(headers)) {        LOG(Network, "header process failed");        m_mode = Failed;        return p - header;    }    switch (m_mode) {    case Normal:        checkResponseHeaders();        break;    default:        m_mode = Failed;        break;    }    return p - header;}
开发者ID:325116067,项目名称:semc-qsd8x50,代码行数:87,


示例26: SNetThreadingSpawn

/***************************************************************************** * Spawn a new task ****************************************************************************/int SNetThreadingSpawn(snet_entity_t *ent)/*  snet_entity_type_t type,  snet_locvec_t *locvec,  int location,  const char *name,  snet_entityfunc_t func,  void *arg  ) */{	int worker;	snet_entity_descr_t type = SNetEntityDescr(ent);	int location = SNetEntityNode(ent);	const char *name = SNetEntityName(ent);	int l1 = strlen(SNET_SOURCE_PREFIX);	int l2 = strlen(SNET_SINK_PREFIX);	if ( type != ENTITY_other) {		if (sosi_placement && (strnstr(name, SNET_SOURCE_PREFIX, l1) || strnstr(name, SNET_SINK_PREFIX, l2))) {			worker = LPEL_MAP_SOSI;		// sosi placemnet and entity is source/sink		} else if (dloc_placement) {			assert(location != -1);			worker = location % num_workers;		} else			worker = SNetAssignTask( (type==ENTITY_box), name );	} else		worker = SNetEntityNode(ent);	//wrapper	lpel_task_t *t = LpelTaskCreate(			worker,			//(lpel_taskfunc_t) func,			EntityTask,			ent,			GetStacksize(type)	);#ifdef USE_LOGGING	if ((mon_flags & SNET_MON_TASK) || (mon_flags & SNET_MON_WAIT_PROP)){		mon_task_t *mt = SNetThreadingMonTaskCreate(				LpelTaskGetId(t),				name		);		LpelTaskMonitor(t, mt);		/* if we monitor the task, we make an entry in the map file */	}	if ((mon_flags & SNET_MON_MAP) && mapfile) {		int tid = LpelTaskGetId(t);		(void) fprintf(mapfile, "%d%s %d%c", tid, SNetEntityStr(ent), worker, END_LOG_ENTRY);	}#endif	if (type != ENTITY_box && type != ENTITY_fbbuf) {		LpelTaskSetPriority(t, 1);	}	//FIXME only for debugging purposes	//fflush(mapfile);	LpelTaskStart(t);	return 0;}
开发者ID:nguyenvuthiennga,项目名称:snet-rts,代码行数:70,


示例27: dbuf_alloc

/* * Receive a reply message */DBUF *ebxml_receive (NETCON *conn){  long n;  int e;  char c, *ch;  DBUF *b;  b = dbuf_alloc ();  n = 0;  /*   * read to end of message request header - empty line   */  while ((e = net_read (conn, &c, 1)) == 1)  {    dbuf_putc (b, c);    if (c == '/n')    {      if (n++ == 1)        break;    }    else if (c != '/r')      n = 0;  }  if (e != 1)  {    if (e == 0)      error ("Acknowledgment header read failed or connection closed/n");    else      error ("Timed out reading acknowledgment header/n");    dbuf_free (b);    return (NULL);  }  ch = strnstr (dbuf_getbuf (b), "Content-Length: ", dbuf_size (b));  if (ch == NULL)  {    error ("Acknowledgment header missing Content-Length/n");    dbuf_free (b);    return (NULL);  }  n = atol (ch + 16);  debug ("expecting %d bytes/n", n);readbytes:  while (n--)  {    if ((e = net_read (conn, &c, 1)) != 1)    {      if (e == 0)        error ("Acknowledgment content read failed or connection closed");      else        error ("Timed out reading acknowledgment content/n");      // note we'll take what we get and hope it's enough...      break;    }    dbuf_putc (b, c);  }  if (n = net_available (conn))  {    warn ("Found %d unread bytes.../n", n);    goto readbytes;  }  debug ("returning %d bytes/n", dbuf_size (b));  return (b);}
开发者ID:tdunnick,项目名称:phineas,代码行数:68,


示例28: parseKernelPrio

//// log a message into the kernel log buffer//// Filter rules to parse <PRI> <TIME> <tag> and <message> in order for// them to appear correct in the logcat output://// LOG_KERN (0):// <PRI>[<TIME>] <tag> ":" <message>// <PRI>[<TIME>] <tag> <tag> ":" <message>// <PRI>[<TIME>] <tag> <tag>_work ":" <message>// <PRI>[<TIME>] <tag> '<tag>.<num>' ":" <message>// <PRI>[<TIME>] <tag> '<tag><num>' ":" <message>// <PRI>[<TIME>] <tag>_host '<tag>.<num>' ":" <message>// (unimplemented) <PRI>[<TIME>] <tag> '<num>.<tag>' ":" <message>// <PRI>[<TIME>] "[INFO]"<tag> : <message>// <PRI>[<TIME>] "------------[ cut here ]------------"   (?)// <PRI>[<TIME>] "---[ end trace 3225a3070ca3e4ac ]---"   (?)// LOG_USER, LOG_MAIL, LOG_DAEMON, LOG_AUTH, LOG_SYSLOG, LOG_LPR, LOG_NEWS// LOG_UUCP, LOG_CRON, LOG_AUTHPRIV, LOG_FTP:// <PRI+TAG>[<TIME>] (see sys/syslog.h)// Observe://  Minimum tag length = 3   NB: drops things like r5:c00bbadf, but allow PM://  Maximum tag words = 2//  Maximum tag length = 16  NB: we are thinking of how ugly logcat can get.//  Not a Tag if there is no message content.//  leading additional spaces means no tag, inherit last tag.//  Not a Tag if <tag>: is "ERROR:", "WARNING:", "INFO:" or "CPU:"// Drop://  empty messages//  messages with ' audit(' in them if auditd is running//  logd.klogd:// return -1 if message logd.klogd: <signature>//int LogKlog::log(const char *buf, size_t len) {    if (auditd && strnstr(buf, len, " audit(")) {        return 0;    }    const char *p = buf;    int pri = parseKernelPrio(&p, len);    log_time now;    sniffTime(now, &p, len - (p - buf), false);    // sniff for start marker    const char klogd_message[] = "logd.klogd: ";    const char *start = strnstr(p, len - (p - buf), klogd_message);    if (start) {        uint64_t sig = strtoll(start + sizeof(klogd_message) - 1, NULL, 10);        if (sig == signature.nsec()) {            if (initialized) {                enableLogging = true;            } else {                enableLogging = false;            }            return -1;        }        return 0;    }    if (!enableLogging) {        return 0;    }    // Parse pid, tid and uid    const pid_t pid = sniffPid(p, len - (p - buf));    const pid_t tid = pid;    const uid_t uid = pid ? logbuf->pidToUid(pid) : 0;    // Parse (rules at top) to pull out a tag from the incoming kernel message.    // Some may view the following as an ugly heuristic, the desire is to    // beautify the kernel logs into an Android Logging format; the goal is    // admirable but costly.    while ((p < &buf[len]) && (isspace(*p) || !*p)) {        ++p;    }    if (p >= &buf[len]) { // timestamp, no content        return 0;    }    start = p;    const char *tag = "";    const char *etag = tag;    size_t taglen = len - (p - buf);    if (!isspace(*p) && *p) {        const char *bt, *et, *cp;        bt = p;        if ((taglen >= 6) && !fast<strncmp>(p, "[INFO]", 6)) {            // <PRI>[<TIME>] "[INFO]"<tag> ":" message            bt = p + 6;            taglen -= 6;        }        for(et = bt; taglen && *et && (*et != ':') && !isspace(*et); ++et, --taglen) {           // skip ':' within [ ... ]           if (*et == '[') {               while (taglen && *et && *et != ']') {                   ++et;                   --taglen;               }            }//.........这里部分代码省略.........
开发者ID:ArtBears,项目名称:platform_system_core,代码行数:101,


示例29: parseRequest

int parseRequest(struct http_request * requestToFill, char * requestStr){    char buff[FIRSTLINEBUFFSIZE]; /* This is the most we'll read */    int i;    int methodLoc;    int urlEnd;    int contentLength;    bzero(buff,FIRSTLINEBUFFSIZE);    bzero(requestToFill->url,MAX_URL_LENGTH);    requestToFill->url[0] = '/'; /* Default assumption */    /* Attempt to determine the request method */    for(i=0; i <  FIRSTLINEBUFFSIZE && requestStr[i] != '/0'; ++i){        if(requestStr[i] == '/r')            if(requestStr[i+1] == '/n')                break;        /* Copy copy copy... */        buff[i] = requestStr[i];    }    methodLoc = strnstr("GET", buff, FIRSTLINEBUFFSIZE  );    if(methodLoc == -1){        methodLoc = strnstr("POST", buff, FIRSTLINEBUFFSIZE );        if(methodLoc == -1){            methodLoc = strnstr("PUT", buff, FIRSTLINEBUFFSIZE  );            if(methodLoc == -1){                methodLoc = strnstr("DELETE", buff, FIRSTLINEBUFFSIZE   );                if(methodLoc == -1){                    /* Fuck it. What'd you try to give me? */                    NETWORK_LOG_LEVEL_1("Could not determine HTTP method. Method Not Recognized:");                    NETWORK_LOG_LEVEL_2(buff);                    requestToFill->method = UNKNOWN_METHOD;                }else{                    requestToFill->method = DELETE;                    methodLoc+= 7; /* Advance past the method and space */                }            }else{                requestToFill->method = PUT;                methodLoc+= 4;            }        }else{            requestToFill->method = POST;            methodLoc+=5;        }    }else{        requestToFill->method = GET;        methodLoc+=4;    }    urlEnd = strnstr("HTTP", buff, FIRSTLINEBUFFSIZE );    /* Find the url (Which will be between the method to the http version)*/    i=methodLoc;    for(methodLoc=0; methodLoc < MAX_URL_LENGTH && i < FIRSTLINEBUFFSIZE && requestStr[i] != '/0' && i < urlEnd; ++i){        if(requestStr[i] != ' '){            requestToFill->url[methodLoc] = requestStr[i];            methodLoc++; /* Just re-using a variable instead of using a new one */        }    }    /* Find out if there's any content: */    contentLength = strnstr("Content-Length",requestStr,strlen(requestStr));    if(contentLength != -1){        /*Determine actual content length */        contentLength+=strlen("Content-Length: "); /* Skip the text */        methodLoc=0; /* ReUsing again */        for(i=contentLength; methodLoc < FIRSTLINEBUFFSIZE && requestStr[i] != '/0' && requestStr[i] != '/r'; ++i)            buff[methodLoc++] = requestStr[i];        buff[i] = '/0';        /* Attempt to parse: */        contentLength = atoi(buff);        if(contentLength > 0){            /* If there's data than place it into the structure */            if(requestToFill->method == POST || requestToFill->method == PUT){                requestToFill->data = malloc(contentLength*sizeof(char)+1);                if(requestToFill->data != NULL){                    /* Find the content: */                    i = strnstr("/r/n/r/n", requestStr, strlen(requestStr));                    if(i != -1){                        i+=4; /* skip newlines */                        for(methodLoc = 0; i < (int)strlen(requestStr) && requestStr[i] != '/0'; ++i, ++methodLoc)                            requestToFill->data[methodLoc] = requestStr[i];                        requestToFill->data[methodLoc] = '/0';                    }else{                        /* Could not find content...*/                        free(requestToFill->data);                    }                }else{                    NETWORK_LOG_LEVEL_1("Could not allocate enough memory for content in request");                }            }else{                /* Don't preallocate memory for the struct or this will cause                 * memory not being able to be reached                */                requestToFill->data = NULL;            }        }    }    /* Calling parties must use contentLength to tell if they will need to free the memory */    requestToFill->contentLength = contentLength;    return contentLength;    }
开发者ID:EdgeCaseBerg,项目名称:green-serv,代码行数:100,



注:本文中的strnstr函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ strobe函数代码示例
C++ strnlen函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。