Beispiel #1
0
    std::map<std::string, std::string> Message::getFormatInfo() const throw (std::runtime_error)
    {
        std::map<std::string, std::string> formatInfo;
        std::string formatHeader = (*this)["X-MMS-IM-Format"];
        if (formatHeader.empty())
            return formatInfo;
        
        std::vector<std::string> parameters = splitString(formatHeader, ";");
        std::vector<std::string>::iterator i = parameters.begin();
        for (; i != parameters.end(); i++)
        {
	    if (i->at(0) == ' ')
	        i->erase(0, 1);

            std::vector<std::string> pair = splitString(*i, "=");
            if (pair.size() == 2)
                formatInfo[decodeURL(pair[0])] = decodeURL(pair[1]);
            else if (pair.size() == 1)
                formatInfo[decodeURL(pair[0])] = "";
            else
                throw std::runtime_error("Incorrectly specified message format!");
        }
        
        return formatInfo;
    }
Beispiel #2
0
    static strstr_map_t parseUrlParameters(std::string parameters) {
      std::string::size_type pos = 0;
      strstr_map_t parameter_map;
      while (pos != std::string::npos) {
        // find next parameter start
        std::string::size_type nextpos = parameters.find("&", pos);
        std::string::size_type delim = parameters.find("=", pos);
        if (delim > nextpos) {
          delim = nextpos;
        }
        std::string key;
        std::string value;
        if (delim == std::string::npos) {
          key = parameters.substr(pos);
        } else {
          key = parameters.substr(pos, delim-pos);
          if (nextpos == std::string::npos) {
            value = parameters.substr(delim+1);
          } else {
            value = parameters.substr(delim+1, nextpos-delim-1);
          }
        }
        if (key.empty()) {
          // no parameters at all
          break;
        }
        key = decodeURL(key);
        value = decodeURL(value);
        parameter_map[key] = value;
        if (nextpos == std::string::npos) {
          // no more parameters left
          break;
        }

        pos = nextpos+1;
      }
      return parameter_map;
    }; //<! parses URL parameters into string map 
Beispiel #3
0
String XSSAuditor::CachingURLCanonicalizer::canonicalizeURL(const String& url, const TextEncoding& encoding, bool decodeEntities, 
                                                            bool decodeURLEscapeSequencesTwice)
{
    if (decodeEntities == m_decodeEntities && decodeURLEscapeSequencesTwice == m_decodeURLEscapeSequencesTwice 
        && encoding == m_encoding && url == m_inputURL)
        return m_cachedCanonicalizedURL;

    m_cachedCanonicalizedURL = canonicalize(decodeURL(url, encoding, decodeEntities, decodeURLEscapeSequencesTwice));
    m_inputURL = url;
    m_encoding = encoding;
    m_decodeEntities = decodeEntities;
    m_decodeURLEscapeSequencesTwice = decodeURLEscapeSequencesTwice;
    ++m_generation;
    return m_cachedCanonicalizedURL;
}
Beispiel #4
0
void DecodeURLComponentImpl::vector(const ColumnString::Chars_t & data, const ColumnString::Offsets_t & offsets,
	ColumnString::Chars_t & res_data, ColumnString::Offsets_t & res_offsets)
{
	res_data.resize(data.size());
	size_t size = offsets.size();
	res_offsets.resize(size);

	size_t prev_offset = 0;
	size_t res_offset = 0;

	for (size_t i = 0; i < size; ++i)
	{
		const char * src_data = reinterpret_cast<const char *>(&data[prev_offset]);
		size_t src_size = offsets[i] - prev_offset;
		size_t dst_size = decodeURL(src_data, src_size, reinterpret_cast<char *>(res_data.data() + res_offset));

		res_offset += dst_size;
		res_offsets[i] = res_offset;
		prev_offset = offsets[i];
	}

	res_data.resize(res_offset);
}
Beispiel #5
0
MyClip  *
getIB( const char *ibID, int *numOfClips )
{
    char    *response;
    char    url[MAX_URLLENGTH];
    char    tmp[BUFSIZ * 2];
    char    *p, *q, *r;
    int     maxNum = MAX_NUMBER_OF_IB;
    int     yyyy, mm, dd, HH, MM, num;
    MyClip  *mp = NULL;
    size_t  sz  = MAX_CONTENT_SIZE * 20;

    *numOfClips = num = 0;
    response = (char *)malloc( sz );
    if ( !response )
        return ( mp );

    sprintf( url, "http://www.blogpeople.net/display/usr/ib/%s.html", ibID );
    setTargetURL( url );
    setUpReceiveBuffer( response, sz );
    p = http_get( url, response );
    if ( !p || !(*p) || !(*response) ) {
        free( response );
        return ( mp );
    }

    mp = (MyClip *)malloc( sizeof ( MyClip ) * maxNum );
    if ( mp ) {
        char    tag[80];
        char    *t = sjis2utf( "title=\"更新日:" );
        int     tlen = strlen( t );

        memset( mp, 0x00, sizeof ( MyClip ) * maxNum );
        p = response;
        tag[0] = NUL;
        while ( *p ) {
            if ( !strncmp( p, "<span class=\"blogpeople-linklist\">", 34 ) ) {
                q = p + 34;
                r = strstr( q, "</span>" );
                if ( r ) {
                    strncpy( tag, q, r - q );
                    tag[r - q] = NUL;
                    p = r + 7;
                }
                else
                    p = q;

                continue;
            }

            if ( !strncmp( p,
                           "<a href=\"http://www.blogpeople.net/cgi-bin/ib_click.cgi?u=http",
                           62 ) ) {
                q = p + 58;
                r = strstr( q, "\" " );
                if ( r ) {
                    strncpy( tmp, q, r - q );
                    tmp[r - q] = NUL;
                    strcpy( mp[num].url, decodeURL( tmp ) );
                    p = r + 2;
                }
                else
                    p = q;

                continue;
            }

            if ( !strncmp( p, t, tlen ) ) {
                q = p + tlen;
                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                yyyy = 2000 + (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                mm   = (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                dd   = (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                HH   = (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                while ( *q && ((*q < '0') || (*q > '9')) )
                    q++;
                MM   = (*q - '0') * 10 + (*(q + 1) - '0');
                q += 2;

                mp[num].yyyy = yyyy;
                mp[num].mm   = mm;
                mp[num].dd   = dd;
                mp[num].HH   = HH;
                mp[num].MM   = MM;
                mp[num].SS   = 0;

                p = q + 20;

                r = strchr( q, '>' );
                if ( r ) {
                    r++;
#ifdef  _DEBUG
                    if ( tag[0] ) {
                        if ( !strstr( tag, "BPIB" ) )
                            strcat( tag, " BPIB" );
                    }
                    else
                        strcpy( tag, "BPIB" );
#endif  /* _DEBUG */
                    strcpy( mp[num].tags, tag );

                    q = strstr( r, "</a>" );
                    if ( q ) {
                        strncpy( mp[num].title, r, q - r );
                        mp[num].title[q - r] = NUL;
                        p = q + 4;
                    }

                    num++;
                    if ( num >= maxNum )
                        break;
                }

                continue;
            }

            p++;
        }
    }

    free( response );
    *numOfClips = num;

    return ( mp );
}
Boolean parseRTSPRequestString(char const* reqStr,
			       unsigned reqStrSize,
			       char* resultCmdName,
			       unsigned resultCmdNameMaxSize,
			       char* resultURLPreSuffix,
			       unsigned resultURLPreSuffixMaxSize,
			       char* resultURLSuffix,
			       unsigned resultURLSuffixMaxSize,
			       char* resultCSeq,
			       unsigned resultCSeqMaxSize,
                               char* resultSessionIdStr,
                               unsigned resultSessionIdStrMaxSize,
			       unsigned& contentLength,
	               unsigned& resultPinId,
	               unsigned& resultDisplayId) {
  // This parser is currently rather dumb; it should be made smarter #####

  // Read everything up to the first space as the command name:
  Boolean parseSucceeded = False;
  unsigned i;
  for (i = 0; i < resultCmdNameMaxSize-1 && i < reqStrSize; ++i) {
    char c = reqStr[i];
    if (c == ' ' || c == '\t') {
      parseSucceeded = True;
      break;
    }

    resultCmdName[i] = c;
  }
  resultCmdName[i] = '\0';
  if (!parseSucceeded) return False;

  // Skip over the prefix of any "rtsp://" or "rtsp:/" URL that follows:
  unsigned j = i+1;
  while (j < reqStrSize && (reqStr[j] == ' ' || reqStr[j] == '\t')) ++j; // skip over any additional white space
  for (; (int)j < (int)(reqStrSize-8); ++j) {
    if ((reqStr[j] == 'r' || reqStr[j] == 'R')
	&& (reqStr[j+1] == 't' || reqStr[j+1] == 'T')
	&& (reqStr[j+2] == 's' || reqStr[j+2] == 'S')
	&& (reqStr[j+3] == 'p' || reqStr[j+3] == 'P')
	&& reqStr[j+4] == ':' && reqStr[j+5] == '/') {
      j += 6;
      if (reqStr[j] == '/') {
	// This is a "rtsp://" URL; skip over the host:port part that follows:
	++j;
	while (j < reqStrSize && reqStr[j] != '/' && reqStr[j] != ' ') ++j;
      } else {
	// This is a "rtsp:/" URL; back up to the "/":
	--j;
      }
      i = j;
      break;
    }
  }

  // Look for the URL suffix (before the following "RTSP/"):
  parseSucceeded = False;
  for (unsigned k = i+1; (int)k < (int)(reqStrSize-5); ++k) {
    if (reqStr[k] == 'R' && reqStr[k+1] == 'T' &&
	reqStr[k+2] == 'S' && reqStr[k+3] == 'P' && reqStr[k+4] == '/') {
      while (--k >= i && reqStr[k] == ' ') {} // go back over all spaces before "RTSP/"
      unsigned k1 = k;
      while (k1 > i && reqStr[k1] != '/') --k1;

      // ASSERT: At this point
      //   i: first space or slash after "host" or "host:port"
      //   k: last non-space before "RTSP/"
      //   k1: last slash in the range [i,k]

      // The URL suffix comes from [k1+1,k]
      // Copy "resultURLSuffix":
      unsigned n = 0, k2 = k1+1;
      if (i <= k) { // There's a slash after "host" or "host:port"
        if (k - k1 + 1 > resultURLSuffixMaxSize) return False; // there's no room
        while (k2 <= k) resultURLSuffix[n++] = reqStr[k2++];
      }
      resultURLSuffix[n] = '\0';

      // The URL 'pre-suffix' comes from [i+1,k1-1]
      // Copy "resultURLPreSuffix":
      n = 0; k2 = i + 1;
      if (i <= k) { // There's a slash after "host" or "host:port"
        if (k1 - i > resultURLPreSuffixMaxSize) return False; // there's no room
        while (k2 <= k1 - 1) resultURLPreSuffix[n++] = reqStr[k2++];
      }
      resultURLPreSuffix[n] = '\0';
      decodeURL(resultURLPreSuffix);

      i = k + 7; // to go past " RTSP/"
      parseSucceeded = True;
      break;
    }
  }
  if (!parseSucceeded) return False;

  // Look for "CSeq:" (mandatory, case insensitive), skip whitespace,
  // then read everything up to the next \r or \n as 'CSeq':
  parseSucceeded = False;
  for (j = i; (int)j < (int)(reqStrSize-5); ++j) {
    if (_strncasecmp("CSeq:", &reqStr[j], 5) == 0) {
      j += 5;
      while (j < reqStrSize && (reqStr[j] ==  ' ' || reqStr[j] == '\t')) ++j;
      unsigned n;
      for (n = 0; n < resultCSeqMaxSize-1 && j < reqStrSize; ++n,++j) {
	char c = reqStr[j];
	if (c == '\r' || c == '\n') {
	  parseSucceeded = True;
	  break;
	}

	resultCSeq[n] = c;
      }
      resultCSeq[n] = '\0';
      break;
    }
  }
  if (!parseSucceeded) return False;

  // Look for "Session:" (optional, case insensitive), skip whitespace,
  // then read everything up to the next \r or \n as 'Session':
  resultSessionIdStr[0] = '\0'; // default value (empty string)
  for (j = i; (int)j < (int)(reqStrSize-8); ++j) {
    if (_strncasecmp("Session:", &reqStr[j], 8) == 0) {
      j += 8;
      while (j < reqStrSize && (reqStr[j] ==  ' ' || reqStr[j] == '\t')) ++j;
      unsigned n;
      for (n = 0; n < resultSessionIdStrMaxSize-1 && j < reqStrSize; ++n,++j) {
	char c = reqStr[j];
	if (c == '\r' || c == '\n') {
	  break;
	}

	resultSessionIdStr[n] = c;
      }
      resultSessionIdStr[n] = '\0';
      break;
    }
  }


  // Also: Look for "Content-Length:" (optional, case insensitive)
  contentLength = 0; // default value
  for (j = i; (int)j < (int)(reqStrSize-15); ++j) {
    if (_strncasecmp("Content-Length:", &(reqStr[j]), 15) == 0) {
      j += 15;
      while (j < reqStrSize && (reqStr[j] ==  ' ' || reqStr[j] == '\t')) ++j;
      unsigned num;
      if (sscanf(&reqStr[j], "%u", &num) == 1) {
	contentLength = num;
      }
    }
  }

  // ESD: Look for "DisplayId:" (optional, case insensitive)
  resultDisplayId = 1; // default value
  for (j = i; (int)j < (int)(reqStrSize-10); ++j) {
    if (_strncasecmp("DisplayId:", &(reqStr[j]), 10) == 0) {
      j += 10;
      while (j < reqStrSize && (reqStr[j] ==  ' ' || reqStr[j] == '\t')) ++j;
      unsigned num;
      if (sscanf(&reqStr[j], "%u", &num) == 1) {
        resultDisplayId = num;
      }
    }
  }

  // ESD: Look for "Pin:" (optional, case insensitive)
  resultPinId = 0; // default value
  for (j = i; (int)j < (int)(reqStrSize-4); ++j) {
    if (_strncasecmp("Pin:", &(reqStr[j]), 4) == 0) {
      j += 4;
      while (j < reqStrSize && (reqStr[j] ==  ' ' || reqStr[j] == '\t')) ++j;
      unsigned num;
      if (sscanf(&reqStr[j], "%u", &num) == 1) {
        resultPinId = num;
      }
    }
  }

  return true;
}
/*Respond Client Request Function
  Variable Definition:
  -- request: client request line
  -- header: client header lines
  -- client_socket: socket connected to the client
  Return Value: NULL
*/
void respondClientRequest(char *request, RTSP_HEADER *header, int client_socket) {
    char 		method[STRING_SIZE];			//method field: SETUP, PLAY, PAUSE, or TEARDOWN
    char 		url[STRING_SIZE];				//url field: for example, rtsp://localhost:5678/movie.Mjpeg
    char 		version[STRING_SIZE];			//rtsp version field: RTSP/1.0
    char		field_value[HALFBUF_SIZE];		//field value string
    u_int32		cseq_number = 0;				//cseq number

    //Initialize method, url, version, and field_value buffer
    memset(method, 0, STRING_SIZE);
    memset(url, 0, STRING_SIZE);
    memset(version, 0, STRING_SIZE);
    memset(field_value, 0, HALFBUF_SIZE);

    //Test the client RTSP Request Line
    if (!syntaxChecking(request, REQUEST_LINE)) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest("Request Line is syntactically incorrect!", client_socket);
        return;
    }

    //Get the method, url, and rtsp version
    sscanf(request, "%s%s%s", method, url, version);
    //Decode the URL(if it has %HEX code)
    decodeURL(url);

    //Test the method
    if (methodNotAllow(method)) {
        //405 Method Not Allowed: the method field is neither "SETUP", "PLAY", "PAUSE" nor "TEARDOWN"
        sendMethodNotAllowed(method, client_socket);
        return;
    }
    //Test the Requested URL
    else if (!syntaxChecking(url, URL_FORMAT)) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest("Requested URL is syntactically incorrect!", client_socket);
        return;
    }
    //Test the RTSP version
    else if (!syntaxChecking(version, RTSP_VERSION)) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest("RTSP Version is syntactically incorrect!", client_socket);
        return;
    }
    //Test the RTSP version 1.0
    else if (!syntaxChecking(version, RTSP_VERSION_1)) {
        //505 RTSP Version Not Supported: the requested RTSP protocol version is not supported by server
        sendRTSPVersionNotSupported(version, client_socket);
        return;
    }

#ifdef	DEBUG
    RTSP_HEADER		*debug_header_node;

    DEBUG_START;
    fputs("RTSP request header lines:\n", stdout);
    //Output the RTSP request header lines
    for (debug_header_node = header->next; debug_header_node != NULL; debug_header_node = debug_header_node->next) {
        fputs(debug_header_node->field_name, stdout);
        fputs(": ", stdout);
        fputs(debug_header_node->field_value, stdout);
        fputc('\n', stdout);
    }
    DEBUG_END;
#endif

    //Test the Header Line
    if (headerLinesIncorrect(header, field_value)) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest(field_value, client_socket);
        return;
    }
    //Test the "CSeq" field
    else if (fieldNotExist(header, "cseq", field_value)) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest("CSeq field does not exist!", client_socket);
        return;
    }
    //Test the "Session" field
    else if ((!methodIsSetup(method)) && fieldNotExist(header, "session", field_value)) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest("Session field does not exist!", client_socket);
        return;
    }
    //Test the "Transport" field
    else if (methodIsSetup(method) && fieldNotExist(header, "transport", field_value)) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest("Transport field does not exist!", client_socket);
        return;
    }
    //Test the "Range" field
    else if ((!(fieldNotExist(header, "range", field_value)))
             && (!syntaxChecking(field_value, RANGE_FORMAT))) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest("Range field value(npt=number[-number]) is syntactically incorrect!", client_socket);
        return;
    }
    //Test the "If-Modified-Since" field
    else if ((!(fieldNotExist(header, "if-modified-since", field_value)))
             && (!syntaxChecking(field_value, TIME_FORMAT))) {
        //400 Bad Request: the request could not be understood by the server
        sendBadRequest("If-Modified-Since field value(time format) is syntactically incorrect!", client_socket);
        return;
    }

    //Now we are sure that the request message is SYNTACTICALLY CORRECT
    //Get the Requested File or Directory's name
    pathBelowCurrentDirectory(url);
    printf("Requested File or Directory is %s\n", url);

    //Test the requested file on the server
    if (urlNotExist(url)) {
        //404 Not Found: the requested document does not exist on this server
        sendNotFound(url, client_socket);
        return;
    }
    //Test the requested url is a directory
    else if (urlIsADirectory(url)) {
        //404 Not Found: the requested document does not exist on this server
        sendNotFound(url, client_socket);
        return;
    }
    //Test the method is valid in special state
    else if (methodIsNotValidInState(method)) {
        //455 Method is not valid in this state: the method is not valid in this state
        sendMethodNotValidInThisState(method, client_socket);
        return;
    }

    //Get the RTSP Request Message information
    cseq_number = getRTSPInfo(header);

    //Test the "Session" field's value
    if (cseq_number == 0) {
        //454 Session Not Found: the session id is not equal to the server's
        sendSessionNotFound(client_socket);
        return;
    }
    //Test the protocol type
    else if (strcmp(protocol_type, PROTOCOL_TYPE) != 0) {
        //461 Unsupported Transport: the transport protocol is not supported by the server
        sendUnsupportedTransport(protocol_type, client_socket);
        return;
    }
    //Test the "If-Modified-Since" field
    else if (fieldNotExist(header, "if-modified-since", field_value)) {
        //200 OK: the request is good
        sendOK(url, method, cseq_number, client_socket);
        return;
    }
    //Test the "If-Modified-Since" field value
    else if (compareModifiedTime(url, field_value)) {
        //304 Not Modified: the request does not Modified since If-Modified-Since field
        sendNotModified(url, cseq_number, client_socket);
        return;
    }
    else {
        //200 OK: the request is good
        sendOK(url, method, cseq_number, client_socket);
        return;
    }
}
Beispiel #8
0
 void SwitchboardServerConnection::callback_AnsweredCall(std::vector<std::string> & args, int trid, void * data)
 {
     this->assertConnectionStateIs(SB_WAITING_FOR_USERS);        
     if (args.size() >= 3 && args[0] == "ANS" && args[2] == "OK")
         return;
     
     if (isdigit(args[0][0]))
     {
         this->removeCallback(trid);
         this->showError(decimalFromString(args[0]));
         this->disconnect();
         return;
     }
     
     if (args.size() >= 6 && args[0] == "IRO")
     {
         if (args[4] == this->auth.username)
             return;
         
         this->users.push_back(args[4]);
         this->myNotificationServer()->externalCallbacks.buddyJoinedConversation(this, args[4], decodeURL(args[5]), 1);
         if (args[2] == args[3])
         {
             this->removeCallback(trid);
             this->setConnectionState(SB_READY);
         }
     }
 }
Beispiel #9
0
 void SwitchboardServerConnection::handle_JOI(std::vector<std::string> & args)
 {
     this->assertConnectionStateIsAtLeast(SB_CONNECTED);        
     if (args[1] == this->auth.username)
         return;
     
     if (this->auth.sessionID.empty() && this->connectionState() == SB_WAITING_FOR_USERS)
         this->setConnectionState(SB_READY);
     
     this->users.push_back(args[1]);
     this->myNotificationServer()->externalCallbacks.buddyJoinedConversation(this, args[1], decodeURL(args[2]), 0);
 }
Beispiel #10
0
 void SwitchboardServerConnection::message_typing_user(std::vector<std::string> & args, std::string mime, std::string body)
 {
     this->myNotificationServer()->externalCallbacks.buddyTyping(this, args[1], decodeURL(args[2]));        
 }   
Beispiel #11
0
 void SwitchboardServerConnection::message_plain(std::vector<std::string> & args, std::string mime, std::string body)
 {
     Message msg = Message(body, mime);
     
     this->myNotificationServer()->externalCallbacks.gotInstantMessage(this,args[1], decodeURL(args[2]), &msg);
 }
Beispiel #12
0
MyClip  *
inputLivedoorFeed( int *numOfClips, FILE *fp )
{
    MyClip  *mp = NULL;
    MyClip  *newClip_p;
    long    numOfPosts = 0;
    long    total      = 0;
    char    *buf, *temp;
    char    *p, *q, *pp, *qq;
    int     num = 1000; /* 暫定 */
    int     block = 1;
    int     len;

    buf = (char *)malloc( MAX_CONTENT_SIZE * 16 );
    if ( !buf )
        return ( mp );
    temp = (char *)malloc( MAX_CONTENT_SIZE * 16 );
    if ( !temp ) {
        free( buf );
        return ( mp );
    }

    while ( ( p = fgets( buf, MAX_CONTENT_SIZE - 1, fp ) ) != NULL ) {
        if ( total == 0 ) {
            // total
            q = strstr( p, "<opensearch:totalResults>" );
            if ( q ) {
                q += 25;
                total = atol( q );
                p = q + 1;
            }

            continue;
        }

        while ( isWhiteSpace(*p) )
            p++;

        // item
        if ( !strncmp( p, "<item>", 6 ) ) {
            newClip_p = allocateMyClipIfNecessary( &mp, num, &block,
                                                   numOfPosts );
            if ( !newClip_p )
                break;
            mp = newClip_p;

            continue;
        }

        //  -- title                  題名
        if ( !strncmp( p, "<title>", 7 ) ) {
            p += 7;
            q = strstr( p, "</title>" );
            while ( !q ) {
                len = strlen( buf );
                qq = buf + len;
                pp = fgets( qq,
                        min(MAX_CONTENT_SIZE - 1, MAX_CONTENT_SIZE * 1 - len),
                            fp );
                if ( !pp || !(*pp) )
                    break;
                if ( len + strlen( pp ) >= MAX_CONTENT_SIZE * 16 )
                    break;
                q = strstr( p, "</title>" );
            }
            if ( q ) {
                while ( isWhiteSpace(*p) )
                    p++;
                strncpy( temp, p, q - p );
                temp[q - p] = NUL;
                p = q + 8;
                q = any2utf( decodeURL( temp ) );
                strcpy( mp[numOfPosts].title, q ? q : temp );

                while (((q = strchr(mp[numOfPosts].title, '\r')) != NULL) ||
                       ((q = strchr(mp[numOfPosts].title, '\n')) != NULL)   )
                    strcpy( q, q + 1 ); /* 改行を取り除く */
            }

            continue;
        }

        //  -- link                   URL
        if ( !strncmp( p, "<link>", 6 ) ) {
            p += 6;
            q = strstr( p, "</link>" );
            if ( q ) {
                strncpy( mp[numOfPosts].url, p, q - p );
                mp[numOfPosts].url[q - p] = NUL;
                p = q + 7;
            }

            continue;
        }

        //  -- description            コメント
        if ( !strncmp( p, "<description>", 13 ) ) {
            p += 13;
            q = strstr( p, "</description>" );
            while ( !q ) {
                len = strlen( buf );
                qq = buf + len;
                pp = fgets( qq,
                        min(MAX_CONTENT_SIZE - 1, MAX_CONTENT_SIZE * 1 - len),
                            fp );
                if ( !pp || !(*pp) )
                    break;
                if ( len + strlen( pp ) >= MAX_CONTENT_SIZE * 16 )
                    break;
                q = strstr( p, "</description>" );
            }
            if ( q ) {
                strncpy( temp, p, q - p );
                temp[q - p] = NUL;
                p = q + 14;
                q = any2utf(temp);
                if ( q )
                    strcpy( mp[numOfPosts].comment, q );

                while (((q = strchr(mp[numOfPosts].comment, '\r')) != NULL)||
                       ((q = strchr(mp[numOfPosts].comment, '\n')) != NULL)  )
                    strcpy( q, q + 1 ); /* 改行を取り除く */
            }

            continue;
        }

        //  -- pubDate (RFC 822形式)  登録日時
        if ( !strncmp( p, "<pubDate>", 9 ) ) {
            p += 9;
            getDateTimeFromDateString( p,
                                       &(mp[numOfPosts].yyyy),
                                       &(mp[numOfPosts].mm),
                                       &(mp[numOfPosts].dd),
                                       &(mp[numOfPosts].HH),
                                       &(mp[numOfPosts].MM),
                                       &(mp[numOfPosts].SS) );
            q = strstr( p, "</pubDate>" );
            if ( q )
                p = q + 10;

            continue;
        }

        //  -- author                 登録者
        if ( !strncmp( p, "<author>", 8 ) ) {
            p += 13;
            q = strstr( p, "</author>" );
            if ( q )
                p = q + 9;

            continue;
        }

        //  -- dc:subject             タグ (複数)
        if ( !strncmp( p, "<dc:subject>", 12 ) ) {
            p += 12;
            q = strstr( p, "</dc:subject>" );
            if ( q ) {
                if ( !strncmp( p, "system:private", 14 ) ) {
                    mp[numOfPosts].publication = PUB_PRIVATE;
                }
                else {
                    int len = mp[numOfPosts].tags[0]
                                    ? strlen(mp[numOfPosts].tags)
                                    : 0;
                    if ( len >= 1 ) {
                        strcat( mp[numOfPosts].tags, " " );
                        len++;
                    }
                    strncat( mp[numOfPosts].tags, p, q - p );
                    mp[numOfPosts].tags[len + (q - p)] = NUL;
                }
                p = q + 13;
            }

            continue;
        }

        //  -- rvw:rating             評価
        if ( !strncmp( p, "<rvw:rating>", 12 ) ) {
            p += 12;
            q = strstr( p, "</rvw:rating>" );
            if ( q ) {
                long    rating = atol( p );
                if ( rating > 0 ) {
                    // 100段階評価 → 5段階評価
                    mp[numOfPosts].evaluation = rating / 20;
                }

                p = q + 13;
            }

            continue;
        }

        if ( !strncmp( p, "</item>", 7 ) ) {
            numOfPosts++;
            if ( numOfPosts >= total )
                break;

            p += 7;
        }
    }

    *numOfClips = numOfPosts;

    free( temp );
    free( buf );

    return ( mp );
}
Beispiel #13
0
long
getAllPostsFromDeliciousXML(
        const char      *buf,           /* (I) 取得する情報元  */
        long            *numOfPosts,    /* (I) 取得する情報数  */
                                        /* (O) 取得した情報数  */
        DELICIOUS_POSTS *posts          /* (O) 取得した情報    */
    )
{
    long    num = 0;

    if ( buf && *buf ) {
        char    *p = strstr( buf, "<posts " );

        if ( p ) {
            char    tmp[MAX_DESCRIPTION_LEN];
            char    *q, *r, *s, *t, *terminate;
            long    l;

            p += 5;
            while ( ( q = strstr( p, "<post " ) ) != NULL ) {
                q += 6;
                terminate = strstr( q, " />" );
                if ( !terminate )
                    terminate = strstr( q, "/>" );
                if ( !terminate )
                    break;

                posts[num].href[0]        = NUL;
                posts[num].description[0] = NUL;
                posts[num].extended[0]    = NUL;
                posts[num].hash[0]        = NUL;
                posts[num].others         = 0;
                posts[num].tag[0]         = NUL;
                posts[num].dateTime[0]    = NUL;
                posts[num].shared         = TRUE;

                /* href */
                r = strstr( q, "href=\"" );
                if ( !r )
                    break;
                r += 6;
                s = strchr( r, '"' );
                if ( !s )
                    break;
                strncpy( posts[num].href, r, s - r );
                posts[num].href[s - r] = NUL;
                if ( strstr( posts[num].href, "&amp;amp;" ) ) {
                    while ( ( r = strstr(posts[num].href, "&amp;amp;") ) != NULL )
                        strcpy( r + 1, r + 5 );
                }
                else {
                    while ( ( r = strstr(posts[num].href, "&amp;") ) != NULL )
                        strcpy( r + 1, r + 5 );
                }

                /* description */
                r = strstr( q, "description=\"" );
                if ( r && (r < terminate) ) {
                    r += 13;
                    s = strchr( r, '"' );
                    if ( s ) {
                        char    *pp, *qq;

                        strncpy( tmp, r, s - r );
                        tmp[s - r] = NUL;
                        t = utf2sjisEx(tmp);
                        s = decodeURL( t ? t : tmp );
                        strcpy( posts[num].description, s ? s : tmp );

                        pp = posts[num].description;
                        while ( ( ( qq = strchr( pp, '\r' ) ) != NULL ) ||
                                ( ( qq = strchr( pp, '\n' ) ) != NULL )    ) {
                            if ( *(qq + 1) == '\n' )
                                strcpy( qq, qq + 2 );
                            else
                                strcpy( qq, qq + 1 );
                            pp = qq;
                        }
                    }
                }

                /* extended */
                r = strstr( q, "extended=\"" );
                if ( r && (r < terminate) ) {
                    r += 10;
                    s = strchr( r, '"' );
                    if ( s ) {
                        char    *pp, *qq;

                        strncpy( tmp, r, s - r );
                        tmp[s - r] = NUL;
                        t = utf2sjisEx(tmp);
                        if ( t )
                            s = strchr( t, '%' ) ? t : decodeURL( t );
                        else
                            s = strchr( tmp, '%' ) ? tmp : decodeURL( tmp );
                        strcpy( posts[num].extended, s ? s : tmp );

                        pp = posts[num].extended;
                        while ( ( ( qq = strchr( pp, '\r' ) ) != NULL ) ||
                                ( ( qq = strchr( pp, '\n' ) ) != NULL )    ) {
                            if ( *(qq + 1) == '\n' )
                                strcpy( qq, qq + 2 );
                            else
                                strcpy( qq, qq + 1 );
                            pp = qq;
                        }
                    }
                }

                /* hash */
                r = strstr( q, "hash=\"" );
                if ( r && (r < terminate) ) {
                    r += 6;
                    s = strchr( r, '"' );
                    if ( s ) {
                        strncpy( posts[num].hash, r, s - r );
                        posts[num].hash[s - r] = NUL;
                    }
                }

                /* others */
                r = strstr( q, "others=\"" );
                if ( r && (r < terminate) ) {
                    r += 8;
                    l = atol(r);
                    posts[num].others = l;
                }

                /* tag */
                r = strstr( q, "tag=\"" );
                if ( r && (r < terminate) ) {
                    r += 5;
                    s = strchr( r, '"' );
                    if ( s ) {
                        strncpy( tmp, r, s - r );
                        tmp[s - r] = NUL;
                        t = utf2sjisEx(tmp);
                        s = decodeURL( t ? t : tmp );
                        strcpy( posts[num].tag, s ? s : tmp );
                    }
                }

                /* time */
                r = strstr( q, "time=\"" );
                if ( r && (r < terminate) ) {
                    r += 6;
                    s = strchr( r, '"' );
                    if ( s ) {
                        strncpy( posts[num].dateTime, r, s - r );
                        posts[num].dateTime[s - r] = NUL;
                    }
                }

                /* shared */
                r = strstr( q, "shared=\"" );
                if ( r && (r < terminate) ) {
                    r += 8;
                    if ( !strncmpi( r, "no", 2 ) )
                        posts[num].shared = FALSE;
                }

                num++;
                if ( num >= *numOfPosts )
                    break;
                p = strchr( q, '>' );
                if ( !p )
                    break;
            }

            *numOfPosts = num;
        }
    }

    return ( num );
}
/*Respond Client Request Function
  Variable Definition:
  -- request: client request line
  -- header: client header lines
  -- client_socket: socket connected to the client
  Return Value: NULL
*/
void respondClientRequest(char *request, struct http_header *header, int client_socket){
	char 	method[STRING_SIZE];		//method field: GET or HEAD
	char 	url[STRING_SIZE];			//url field: /TestServer
	char 	version[STRING_SIZE];		//http version field: HTTP/1.1
	char	field_value[HALFBUF_SIZE];	//field value string
	bool	modified_signal;			//whether if-modified-since field exist
	
	//Initialize method, url and version buffer
	memset(method, 0, STRING_SIZE);
	memset(url, 0, STRING_SIZE);
	memset(version, 0, STRING_SIZE);
	memset(field_value, 0, HALFBUF_SIZE);
	
	//Test the client HTTP Request Line
	if (!syntaxChecking(request, 'R')){
		//400 Bad Request: the request could not be understood by the server
		sendBadRequest("Request Line is syntactically incorrect!", client_socket);
		return;
	}
	
	//Get the method, url, and http version
	// NC: i don't think this works: need   sscanf(request, "%s %s %s", method, url, version);
	sscanf(request, "%s%s%s", method, url, version);
	//Decode the URL(if it has %HEX code)
	decodeURL(url);
	//Test the method
	if ((strcmp(method, "GET") != 0) && (strcmp(method, "HEAD") != 0)){
		//405 Method Not Allowed: the method field is neither "GET" nor "HEAD"
		sendMethodNotAllowed(method, client_socket);
		return;
	}
	//Test the Requested URL
	else if (!syntaxChecking(url, 'U')){
		// NC: but, "the only legal Request-URI is the abs_path “/TestServer”. Generate a 404 Response to all other Request-URIs."
		// #17: -1
		//400 Bad Request: the request could not be understood by the server
		sendBadRequest("Requested URL is syntactically incorrect!", client_socket);
		return;
	}
	//Test the HTTP version
	else if (!syntaxChecking(version, 'V')){
		//400 Bad Request: the request could not be understood by the server
		sendBadRequest("HTTP Version is syntactically incorrect!", client_socket);
		return;
	}
	else if (!syntaxChecking(version, 'O')){
		//505 HTTP Version Not Supported: the requested HTTP protocol version is not supported by server
		sendHTTPVersionNotSupported(version, client_socket);
		return;
	}
	
	//Test the Header Line
	if (headerLinesIncorrect(header, field_value)){
		//400 Bad Request: the request could not be understood by the server
		sendBadRequest(field_value, client_socket);
		return;
	}
	//Test the "Host" field
	else if (fieldNotExist(header, "host", field_value)){
		//400 Bad Request: the request could not be understood by the server
		sendBadRequest("Host field does not exist!", client_socket);
		return;
	}
	else if (!syntaxChecking(field_value, 'I')){
		//400 Bad Request: the request could not be understood by the server
		sendBadRequest("Host field value(domain name, IP address, or port format) is syntactically incorrect!", client_socket);
		return;
	}
	//Test the "If-Modified-Since" field
	else if ((!(modified_signal = fieldNotExist(header, "if-modified-since", field_value))) && (!syntaxChecking(field_value, 'T'))){
		//400 Bad Request: the request could not be understood by the server
		sendBadRequest("If-Modified-Since field value(time format) is syntactically incorrect!", client_socket);
		return;
	}
	
	//Now we are sure that the request message is SYNTACTICALLY CORRECT
	//Get the Requested File or Directory's name
	pathBelowCurrentDirectory(url);
	printf("Requested File or Directory is %s\n", url);
// NC: but OUR server doesn't do this
	
	//Test the requested file on the server
	if (urlNotExist(url)){
		//404 Not Found: the requested document does not exist on this server
		sendNotFound(url, client_socket);
	}
	else if (urlIsADirectory(url)){
		//List the File Name of Directory
		sendFileNameInDirectory(url, method, client_socket);
	}
	else if (modified_signal){
		//200 OK: the request is good
		sendOK(url, method, client_socket);
	}
	else if (compareModifiedTime(url, field_value)){
		//304 Not Modified: the request does not Modified since If-Modified-Since field
		sendNotModified(url, client_socket);
	}
	else{
		//200 OK: the request is good
		sendOK(url, method, client_socket);
	}

	return;
}