void createAndActivateEVC(char* url, unsigned short ivid, connectionTp AEndTp, connectionTp ZEndTp)
{
    MemoryStruct httpPostBody;
    MemoryStruct httpResponseBody;
    MemoryStruct httpResponseHeaders;
    httpPostBody.data = createRequestBody2(ivid, AEndTp, ZEndTp);
    httpPostBody.size = strlen(httpPostBody.data);
    httpPostBody.bytesCopied = 0;
    httpPostBody.bytesRemaining = httpPostBody.size;
    httpResponseBody.data = malloc(1);
    httpResponseBody.size = 0;
    httpResponseHeaders.data = malloc(1);
    httpResponseHeaders.size = 0;
    //printf("requestBody:\n\n%s\n", requestBody);
    httpPost(NULL, url, &httpPostBody, &httpResponseBody, &httpResponseHeaders);
    free(httpPostBody.data);
    free(httpResponseBody.data);
    free(httpResponseHeaders.data);
    /*
    char* requestBody;
    requestBody = createRequestBody2(ivid, AEndTp, ZEndTp);
    printf("requestBody:\n\n%s\n", requestBody);
    free(requestBody);
    */
}
void PasteBinDotComProtocol::paste(const QString &text,
                                   ContentType ct, int expiryDays,
                                   const QString & /* username */, // Not used unless registered user
                                   const QString &comment,
                                   const QString &description)
{
    Q_UNUSED(comment);
    Q_UNUSED(description);
    QTC_ASSERT(!m_pasteReply, return);

    // Format body
    QByteArray pasteData = API_KEY;
    pasteData += "api_option=paste&";
    pasteData += "api_paste_expire_date=";
    pasteData += expirySpecification(expiryDays);
    pasteData += '&';
    pasteData += format(ct);
    pasteData += "api_paste_name="; // Title or name.
    pasteData += QUrl::toPercentEncoding(description);
    pasteData += "&api_paste_code=";
    pasteData += QUrl::toPercentEncoding(fixNewLines(text));
    // fire request
    m_pasteReply = httpPost(QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_API), pasteData);
    connect(m_pasteReply, &QNetworkReply::finished, this, &PasteBinDotComProtocol::pasteFinished);
    if (debug)
        qDebug() << "paste: sending " << m_pasteReply << pasteData;
}
void PasteBinDotComProtocol::paste(const QString &text,
                                   ContentType ct,
                                   const QString &username,
                                   const QString &comment,
                                   const QString &description)
{
    Q_UNUSED(comment);
    Q_UNUSED(description);
    QTC_ASSERT(!m_pasteReply, return);

    // Format body
    QByteArray pasteData = API_KEY;
    pasteData += "api_option=paste&";
    pasteData += "api_paste_expire_date=1M&";
    pasteData += format(ct);
    pasteData += "api_paste_name=";
    pasteData += QUrl::toPercentEncoding(username);

    pasteData += "&api_paste_code=";
    pasteData += QUrl::toPercentEncoding(fixNewLines(text));

    // fire request
    m_pasteReply = httpPost(QLatin1String(PASTEBIN_BASE) + QLatin1String(PASTEBIN_API), pasteData);
    connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished()));
    if (debug)
        qDebug() << "paste: sending " << m_pasteReply << pasteData;
}
/// <summary>
/// Posts the given url to the db report update script
/// </summary>
/// <returns>Coma separated list of updated caps</returns>
string VulkanDatabase::postReportForUpdate(string xml)
{
    string httpReply;
    stringstream urlss;
    urlss << getBaseUrl() << "services/updatereport.php";
    httpReply = httpPost(urlss.str(), xml);
    return httpReply;
}
Beispiel #5
0
/* Stores the arbitrary buffer of bytes, 'buf' (of length 'len') to
	the master server.  It is written into the user record for the
	user with username 'user', and password 'pass'.
	Returns 0 on success, 1 on failure. */
int master_gamesave(const char *user, const char *pass, const unsigned char *buf, int len)
{
	if(strlen(user) >= 25)
		return 1;
	if(strlen(pass) >= 25)
		return 1;

	if(len > ((sizeof(hex) - 1) / 2))
		return 0;

	hexify(buf, len);

	strcpy(path, master_path);
	strcat(path, "?action=gamesave2&");
	if(URLEncode::addParam(path, sizeof(path), user, "username") == false)
		return 1;
	if(URLEncode::addParam(path, sizeof(path), pass, "password") == false)
		return 1;

	/* XXX If the windows HTTPGetRequest() thing can be made to work with
	long, 4K char paths (which it's supposed to, but for some reason
	refused to work for me) then the following, commented out code can
	be used instead of the httpGet() call below it (which requires you to
	roll your own Socket() class. */
#if 0
	HTTPGetRequest *hgr = new HTTPGetRequest(master_host, 80, path, false, true, false);
	if(!hgr)
		return 1;
	int r = 0;
	char *b = master_http_buf;
	int bs = sizeof(master_http_buf);
	while(true)
	{
		int n = hgr->read(b, bs);
		if(n == 0)
			break;		// normal EOF
		if(hgr->failed)
			break;
		bs -= n;
		b += n;
		r += n;
	}
	bool f = hgr->failed;
	delete hgr;
	if(f)
		return 1;	// error
#else
	char *b = master_http_buf;
	int bs = sizeof(master_http_buf);
	if(httpPost(master_host, 80, path, b, bs, hex, len*2, "userfile", "gamedata", "text/hexed") == -1)
		return 1;
#endif


	return bustup_response();
}
Beispiel #6
0
/* ======================================================================
Function: jeedomPost
Purpose : Do a http post to jeedom server
Input   : 
Output  : true if post returned 200 OK
Comments: -
====================================================================== */
boolean jeedomPost(void)
{
  boolean ret = false;

  // Some basic checking
  if (*config.jeedom.host) {
    ValueList * me = tinfo.getList();
    // Got at least one ?
    if (me && me->next) {
      String url ; 
      boolean skip_item;

      url = *config.jeedom.url ? config.jeedom.url : "/";
      url += "?";

      // Config identifiant forcée ?
      if (*config.jeedom.adco) {
        url+= F("ADCO=");
        url+= config.jeedom.adco;
        url+= "&";
      } 

      url += F("api=") ;
      url += config.jeedom.apikey;
      url += F("&") ;

      // Loop thru the node
      while (me->next) {
        // go to next node
        me = me->next;
        skip_item = false;

        // Si ADCO déjà renseigné, on le remet pas
        if (!strcmp(me->name, "ADCO")) {
          if (*config.jeedom.adco)
            skip_item = true;
        }

        // Si Item virtuel, on le met pas
        if (*me->name =='_')
          skip_item = true;

        // On doit ajouter l'item ?
        if (!skip_item) {
          url +=  me->name ;
          url += "=" ;
          url +=  me->value;
          url += "&" ;
        }
      } // While me

      ret = httpPost( config.jeedom.host, config.jeedom.port, (char *) url.c_str()) ;
    } // if me
  } // if host
  return ret;
}
Beispiel #7
0
static void 
_post_send (GtkCupsRequest *request)
{
  gchar length[255];
  struct stat data_info;

  GTK_NOTE (PRINTING,
            g_print ("CUPS Backend: %s\n", G_STRFUNC));

  request->poll_state = GTK_CUPS_HTTP_WRITE;

  if (request->data_io != NULL)
    {
      fstat (g_io_channel_unix_get_fd (request->data_io), &data_info);
      sprintf (length, "%lu", (unsigned long) (ippLength (request->ipp_request) + data_info.st_size));
    }
  else
    sprintf (length, "%lu", (unsigned long) ippLength (request->ipp_request));
	
  httpClearFields (request->http);
  httpSetField (request->http, HTTP_FIELD_CONTENT_LENGTH, length);
  httpSetField (request->http, HTTP_FIELD_CONTENT_TYPE, "application/ipp");
#ifdef HAVE_HTTPGETAUTHSTRING
  httpSetField (request->http, HTTP_FIELD_AUTHORIZATION, httpGetAuthString (request->http));
#else
#ifdef HAVE_HTTP_AUTHSTRING
  httpSetField (request->http, HTTP_FIELD_AUTHORIZATION, request->http->authstring);
#endif
#endif

  if (httpPost (request->http, request->resource))
    {
      if (httpReconnect (request->http))
        {
          request->state = GTK_CUPS_POST_DONE;
          request->poll_state = GTK_CUPS_HTTP_IDLE;

          /* TODO: should add a status or error code for failed post */
          gtk_cups_result_set_error (request->result,
                                     GTK_CUPS_ERROR_GENERAL,
                                     0,
                                     0,
                                     "Failed Post");
        }

      request->attempts++;
      return;    
    }
        
    request->attempts = 0;

    request->state = GTK_CUPS_POST_WRITE_REQUEST;
    ippSetState (request->ipp_request, IPP_IDLE);
}
Beispiel #8
0
HISINFOPOST_API BOOL PASCAL confirmPres(const char *url, const char *pres_no, int post_type)
{
	url_schema *urls = url_parse(url);
	if (!urls) 
		return FALSE;
	char data[100] = { 0 };
	sprintf(data, "pres_no=%s&post_type=%d", pres_no, post_type);
	static TCHAR hdrs[] = _T("Content-Type: text/html");
	BOOL result = TRUE;

	if (ERROR_SUCCESS != httpPost(urls, hdrs, data))
		result = FALSE;
	url_free(urls);

	return result;
}
void LepheProtocol::paste(const QString &text, Protocol::ContentType ct, int expiryDays, const QString &username, const QString &comment, const QString &description)
{
    Q_UNUSED(ct);
    Q_UNUSED(comment);
    Q_UNUSED(expiryDays);

    // Format body
    QByteArray pasteData;
    pasteData += "name="; // Title or name.
    pasteData += QUrl::toPercentEncoding(description);
    pasteData += "&snippet=";
    pasteData += QUrl::toPercentEncoding(fixNewLines(text));
    // fire request
    _pasteReply = httpPost(QLatin1String(LEPHE_BASE) + QLatin1String(LEPHE_POST), pasteData);
    connect(_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished()));
}
void RequestParser::read(QByteArray data)
{
	m_buffer = m_buffer + data;
	int eoh = m_buffer.indexOf("\r\n\r\n");
	if (eoh > 0 && m_headersDone == false)
	{
		if (m_headersDone == false)
		{
			QHttpRequestHeader header(QString(m_buffer.left(eoh+4)));
			m_header = header;
			m_headersDone = true;

		}
	}

	if (m_headersDone)
	{
		QString method = m_header.method();
		QString path = m_header.path();
		if (method == "GET")
		{
			qDebug() << "Http: GET" << path;
			emit httpGet(m_header);
			m_buffer = "";
			m_headersDone = false;
		} else if (method == "POST" || method == "PUT") {

			if ((uint) m_buffer.length() == m_header.contentLength() - (uint)(eoh+4))
			{
				qDebug() << "Http: POST" << path;
				if (method == "POST")
					emit httpPost(m_header, m_buffer.mid(eoh+4, m_header.contentLength()));
				else
					emit httpPut(m_header, m_buffer.mid(eoh+4, m_header.contentLength()));
				m_buffer = "";
				m_headersDone = false;

			} // if we have all post data
		} else if (method == "DELETE") {
			emit httpDelete(m_header);
			m_buffer = "";
			m_headersDone = false;
		}

	} // headers done == true

}
Beispiel #11
0
////////////
/// \brief QQPalmiFilePoster::postFileUpload3TerOrg
/// \param file
///
QNetworkReply * QQPalmiFilePoster::postFileUpload3TerOrg(QFile *file)
{
	QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

	QHttpPart filePart;
#if(QT_VERSION >= QT_VERSION_CHECK(5, 0, 0))
	QMimeDatabase mimeDatabase;
	QMimeType mimeType = mimeDatabase.mimeTypeForFile(file->fileName(), QMimeDatabase::MatchDefault);
	filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(mimeType.name()));
#else
	filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
#endif
	filePart.setHeader(QNetworkRequest::ContentDispositionHeader,
					   QString("form-data; name=\"file\"; filename=\"%1\"").arg(file->fileName()));
	filePart.setBodyDevice(file);
	file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart

	multiPart->append(filePart);

	QHttpPart timePart;
	timePart.setHeader(QNetworkRequest::ContentDispositionHeader,
					   QString("form-data; name=\"time\""));
	timePart.setBody(QString::fromLatin1("week").toLatin1());
	multiPart->append(timePart);

	QUrl url(QString("http://%1/script.php").arg(FILE_SHARING_SERVICE_JIRAFEAU_3TER_ORG));
	QNetworkRequest request(url);
	//request.setRawHeader("User-Agent", "Mozilla/5.0 (quteqoin)"); // Le service n'accepte pas l'ua par défaut ...
	//request.setRawHeader("Accept", "application/json, text/javascript, */*; q=0.01");
	//request.setRawHeader("Accept-Language", "en-US,en;q=0.5");
	//request.setRawHeader("Accept-Encoding", "gzip, deflate"); // Qt 4 ne supporte pas gunzip nativement ....
	//request.setRawHeader("X-Requested-With", "XMLHttpRequest");
	request.setRawHeader("Referer", QString("http://%1/").arg(FILE_SHARING_SERVICE_JIRAFEAU_3TER_ORG).toLatin1());

	QNetworkReply *reply = httpPost(request, multiPart);
	multiPart->setParent(reply); // delete the multiPart with the reply

	return reply;
}
Beispiel #12
0
HISINFOPOST_API int PASCAL postPres(const char *url, const char *xml, int post_type, const char *encoding)
{
	int rc = 0;
	url_schema *urls = url_parse(url);
	if (!urls) 
		return ERROR_URL_INVALID;
	HWND hParent = ::GetForegroundWindow();
	rc = DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), hParent, DlgProc);
	if (rc == ACTION_COMMIT) {
		int length = strlen(xml) + 100;
		std::vector<char> data;
		data.reserve(length);
		char *p = &data[0];
		length = sprintf(p, "post_type=%d&encoding=%s&data=%s", post_type, encoding, xml);
		p[length] = '\0';
		static TCHAR hdrs[] = _T("Content-Type: application/xml");
		if (ERROR_SUCCESS != httpPost(urls, hdrs, p))
			rc = ERROR_POST_FAILED;
	}

	url_free(urls);
	return rc;
}
int main(int argc, char **argv)
{
    CURL *curlHandle;
    CURLcode res;
    struct curl_slist *headerList = NULL;
    char *urlString = "http://192.168.201.20:8080/wm/core/controller/switches/json";

    //curl_global_init(CURL_GLOBAL_ALL);
    //curlHandle = curl_easy_init();                                                 //init the curl session

    struct MemoryStruct httpPostBody;
    httpPostBody.data = readFileToBuffer(argv[1]);
    httpPostBody.size = strlen(httpPostBody.data);      //nie potrzeba nulla na koncu dawac
    httpPostBody.bytesCopied = 0;
    httpPostBody.bytesRemaining = httpPostBody.size;

    struct MemoryStruct httpResponseBody;
    struct MemoryStruct httpResponseHeaders;
    httpResponseBody.data = malloc(1);
    httpResponseBody.size = 0;
    httpResponseHeaders.data = malloc(1);
    httpResponseHeaders.size = 0;

    httpPost(NULL, urlString, &httpPostBody, &httpResponseBody, &httpResponseHeaders);

    printf("Wczytane body: \n%s\n", httpResponseBody.data);
    printf("Wczytane hedery: \n%s\n", httpResponseHeaders.data);

    free(httpPostBody.data);

    if (httpResponseBody.data) free(httpResponseBody.data);
    if (httpResponseHeaders.data) free(httpResponseHeaders.data);

    //curl_global_cleanup();
    return 0;

}
                                  const QString & /* comment */,
                                  const QString &description)
{
    QTC_ASSERT(!m_pasteReply, return);
    QByteArray data = "api=+xKvWG+1UFXkr2Kn3Td4AnpYtCIjA4qt&";
    data += "content=";
    data += QUrl::toPercentEncoding(fixNewLines(text));
    data += "&type=";
    data += toTypeId(ct);
    data += "&description=";
    data += QUrl::toPercentEncoding(description);
    data += "expiry=1%20day&name=";
    data += QUrl::toPercentEncoding(username);
    // fire request
    const QString link = QLatin1String(urlC) + QLatin1String("quiet-paste.php");
    m_pasteReply = httpPost(link, data);
    connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished()));
}

void PasteBinDotCaProtocol::pasteFinished()
{
    if (m_pasteReply->error()) {
        qWarning("Pastebin.ca protocol error: %s", qPrintable(m_pasteReply->errorString()));
    } else {
        /// returns ""SUCCESS:[id]""
        const QByteArray data = m_pasteReply->readAll();
        const QString link = QString::fromLatin1(urlC) + QString::fromLatin1(data).remove(QLatin1String("SUCCESS:"));
        emit pasteDone(link);
    }
    m_pasteReply->deleteLater();
    m_pasteReply = 0;
/**
   [ client interface ]
   call to send a request to another transport
   @param address the RPC address to send the request to
   @param request the data to send
   @param response the response to the request. On input null, on
   output the response of the message
   @return the synchronous result of the call
*/
bool
RpcHttpTransport::sendRequest(
    const String& address,
    const String& request,
    String& response )
{
    RefCountedPtr<HttpClientPost> httpPost( new HttpClientPost );

    // check to see if we are using proxy settings
    httpPost->setServerURL( address );
    if(_proxy.size() > 0 && _proxyPort > 0)
    {
        httpPost->setProxyServer( _proxy, _proxyPort );
    }

    // Set the request in HttpContent Format
    HttpContent httpRequest;
    httpRequest.setHttpMsgType( HttpContent::HTTP_MSG_TYPE_REQUEST );
    httpRequest.setHttpVersion( HttpUtils::HTTP_VERSION );

    // RPC specific attributes
    // we add to the address attribute an address where the server we are contacting
    // would be able to get back to us.
    httpRequest.setHeaderProperty( Rpc::ADDRESS_ATTR, _transportAddress.toString() );
    httpRequest.setRequestBody( request );

    String protocol;
    String host;
    unsigned short port;
    String path;

    HttpUtils::parseURL( address, protocol, host, port, path );
    if( !path.empty() )
    {
        httpRequest.setServerPath( path );
    }
    else
    {
        httpRequest.setServerPath( HttpUtils::HTTP_DEFAULT_SVRPATH );
    }

    host += COLON;
    host += StringUtils::toString( (int)port );
    httpRequest.setHeaderProperty( HttpUtils::HTTP_HOST, host );

    // setup the retry mechanism
    int currentRetry = 0;
    bool sendResult = false;

    // we call add post to allow this post to be cancelled
    // asynchronously by another thread
    HttpContent httpReply;
    addClientPost( httpPost );

    while ( !sendResult && ( currentRetry < _retries ) )
    {
        /**
           one quick check before we send
           send the request and check for errors
        */
//        if( status() != keRpcStarted )
//        {
//            CBLOGERR(_logger, NTEXT("RpcHttpClientTransport::sendRequest - Unable to Send data because the server is down") );
//            break;
//        }

        sendResult = httpPost->send( httpRequest, httpReply );
        currentRetry++;

        if ( !sendResult && ( currentRetry < _retries ) )
        {
            CBLOGERR(_logger, NTEXT("RpcHttpClientTransport::sendRequest - preparing to resend data...") );
            ThdManager::Sleep( _sleepInterval );
        }
    }

    removeClientPost( httpPost );

    if( !sendResult )
    {
        CBLOGERR(_logger, NTEXT("RpcHttpClientTransport::sendRequest - Unable to Send data") );
        return false;
    }

    /**
       Check for return code
    */
    if( httpReply.getErrorCode() > HttpUtils::keCodeNoContent )
    {
        CBLOGERR(_logger,
                 (NTEXT("RpcHttpClientTransport::request - The following error was returned: '") +
                  httpReply.getErrorCode()) +
                 (NTEXT("' for the following request '") +
                  request) +
                 NTEXT("'") );
        return false;
    }

    if( httpReply.getErrorCode() != HttpUtils::keCodeNoContent )
    {
        response = httpReply.getResponseBody();
    }

    return true;
}
Beispiel #16
0
http_status_t				/* O - Initial HTTP status */
cupsSendRequest(http_t     *http,	/* I - Connection to server or @code CUPS_HTTP_DEFAULT@ */
                ipp_t      *request,	/* I - IPP request */
                const char *resource,	/* I - Resource path */
		size_t     length)	/* I - Length of data to follow or @code CUPS_LENGTH_VARIABLE@ */
{
  http_status_t		status;		/* Status of HTTP request */
  int			got_status;	/* Did we get the status? */
  ipp_state_t		state;		/* State of IPP processing */
  http_status_t		expect;		/* Expect: header to use */


  DEBUG_printf(("cupsSendRequest(http=%p, request=%p(%s), resource=\"%s\", "
                "length=" CUPS_LLFMT ")", http, request,
		request ? ippOpString(request->request.op.operation_id) : "?",
		resource, CUPS_LLCAST length));

 /*
  * Range check input...
  */

  if (!request || !resource)
  {
    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);

    return (HTTP_STATUS_ERROR);
  }

 /*
  * Get the default connection as needed...
  */

  if (!http)
    if ((http = _cupsConnect()) == NULL)
      return (HTTP_STATUS_SERVICE_UNAVAILABLE);

 /*
  * If the prior request was not flushed out, do so now...
  */

  if (http->state == HTTP_STATE_GET_SEND ||
      http->state == HTTP_STATE_POST_SEND)
  {
    DEBUG_puts("2cupsSendRequest: Flush prior response.");
    httpFlush(http);
  }
  else if (http->state != HTTP_STATE_WAITING)
  {
    DEBUG_printf(("1cupsSendRequest: Unknown HTTP state (%d), "
                  "reconnecting.", http->state));
    if (httpReconnect2(http, 30000, NULL))
      return (HTTP_STATUS_ERROR);
  }

#ifdef HAVE_SSL
 /*
  * See if we have an auth-info attribute and are communicating over
  * a non-local link.  If so, encrypt the link so that we can pass
  * the authentication information securely...
  */

  if (ippFindAttribute(request, "auth-info", IPP_TAG_TEXT) &&
      !httpAddrLocalhost(http->hostaddr) && !http->tls &&
      httpEncryption(http, HTTP_ENCRYPTION_REQUIRED))
  {
    DEBUG_puts("1cupsSendRequest: Unable to encrypt connection.");
    return (HTTP_STATUS_SERVICE_UNAVAILABLE);
  }
#endif /* HAVE_SSL */

 /*
  * Reconnect if the last response had a "Connection: close"...
  */

  if (!_cups_strcasecmp(http->fields[HTTP_FIELD_CONNECTION], "close"))
  {
    DEBUG_puts("2cupsSendRequest: Connection: close");
    httpClearFields(http);
    if (httpReconnect2(http, 30000, NULL))
    {
      DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
      return (HTTP_STATUS_SERVICE_UNAVAILABLE);
    }
  }

 /*
  * Loop until we can send the request without authorization problems.
  */

  expect = HTTP_STATUS_CONTINUE;

  for (;;)
  {
    DEBUG_puts("2cupsSendRequest: Setup...");

   /*
    * Setup the HTTP variables needed...
    */

    httpClearFields(http);
    httpSetExpect(http, expect);
    httpSetField(http, HTTP_FIELD_CONTENT_TYPE, "application/ipp");
    httpSetLength(http, length);

#ifdef HAVE_GSSAPI
    if (http->authstring && !strncmp(http->authstring, "Negotiate", 9))
    {
     /*
      * Do not use cached Kerberos credentials since they will look like a
      * "replay" attack...
      */

      _cupsSetNegotiateAuthString(http, "POST", resource);
    }
#endif /* HAVE_GSSAPI */

    httpSetField(http, HTTP_FIELD_AUTHORIZATION, http->authstring);

    DEBUG_printf(("2cupsSendRequest: authstring=\"%s\"", http->authstring));

   /*
    * Try the request...
    */

    DEBUG_puts("2cupsSendRequest: Sending HTTP POST...");

    if (httpPost(http, resource))
    {
      DEBUG_puts("2cupsSendRequest: POST failed, reconnecting.");
      if (httpReconnect2(http, 30000, NULL))
      {
        DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
        return (HTTP_STATUS_SERVICE_UNAVAILABLE);
      }
      else
        continue;
    }

   /*
    * Send the IPP data...
    */

    DEBUG_puts("2cupsSendRequest: Writing IPP request...");

    request->state = IPP_STATE_IDLE;
    status         = HTTP_STATUS_CONTINUE;
    got_status     = 0;

    while ((state = ippWrite(http, request)) != IPP_STATE_DATA)
      if (state == IPP_STATE_ERROR)
	break;
      else if (httpCheck(http))
      {
        got_status = 1;

        _httpUpdate(http, &status);
	if (status >= HTTP_STATUS_MULTIPLE_CHOICES)
	  break;
      }

    if (state == IPP_STATE_ERROR)
    {
      DEBUG_puts("1cupsSendRequest: Unable to send IPP request.");

      http->status = HTTP_STATUS_ERROR;
      http->state  = HTTP_STATE_WAITING;

      return (HTTP_STATUS_ERROR);
    }

   /*
    * Wait up to 1 second to get the 100-continue response as needed...
    */

    if (!got_status)
    {
      if (expect == HTTP_STATUS_CONTINUE)
      {
	DEBUG_puts("2cupsSendRequest: Waiting for 100-continue...");

	if (httpWait(http, 1000))
	  _httpUpdate(http, &status);
      }
      else if (httpCheck(http))
	_httpUpdate(http, &status);
    }

    DEBUG_printf(("2cupsSendRequest: status=%d", status));

   /*
    * Process the current HTTP status...
    */

    if (status >= HTTP_STATUS_MULTIPLE_CHOICES)
    {
      int temp_status;			/* Temporary status */

      _cupsSetHTTPError(status);

      do
      {
	temp_status = httpUpdate(http);
      }
      while (temp_status != HTTP_STATUS_ERROR &&
             http->state == HTTP_STATE_POST_RECV);

      httpFlush(http);
    }

    switch (status)
    {
      case HTTP_STATUS_CONTINUE :
      case HTTP_STATUS_OK :
      case HTTP_STATUS_ERROR :
          DEBUG_printf(("1cupsSendRequest: Returning %d.", status));
          return (status);

      case HTTP_STATUS_UNAUTHORIZED :
          if (cupsDoAuthentication(http, "POST", resource))
	  {
            DEBUG_puts("1cupsSendRequest: Returning HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED.");
	    return (HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED);
	  }

          DEBUG_puts("2cupsSendRequest: Reconnecting after HTTP_STATUS_UNAUTHORIZED.");

	  if (httpReconnect2(http, 30000, NULL))
	  {
	    DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
	    return (HTTP_STATUS_SERVICE_UNAVAILABLE);
	  }
	  break;

#ifdef HAVE_SSL
      case HTTP_STATUS_UPGRADE_REQUIRED :
	 /*
	  * Flush any error message, reconnect, and then upgrade with
	  * encryption...
	  */

          DEBUG_puts("2cupsSendRequest: Reconnecting after "
	             "HTTP_STATUS_UPGRADE_REQUIRED.");

	  if (httpReconnect2(http, 30000, NULL))
	  {
	    DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
	    return (HTTP_STATUS_SERVICE_UNAVAILABLE);
	  }

	  DEBUG_puts("2cupsSendRequest: Upgrading to TLS.");
	  if (httpEncryption(http, HTTP_ENCRYPTION_REQUIRED))
	  {
	    DEBUG_puts("1cupsSendRequest: Unable to encrypt connection.");
	    return (HTTP_STATUS_SERVICE_UNAVAILABLE);
	  }
	  break;
#endif /* HAVE_SSL */

      case HTTP_STATUS_EXPECTATION_FAILED :
	 /*
	  * Don't try using the Expect: header the next time around...
	  */

	  expect = (http_status_t)0;

          DEBUG_puts("2cupsSendRequest: Reconnecting after "
	             "HTTP_EXPECTATION_FAILED.");

	  if (httpReconnect2(http, 30000, NULL))
	  {
	    DEBUG_puts("1cupsSendRequest: Unable to reconnect.");
	    return (HTTP_STATUS_SERVICE_UNAVAILABLE);
	  }
	  break;

      default :
         /*
	  * Some other error...
	  */

	  return (status);
    }
  }
}
int					/* O - 1 on success, 0 on error */
translate_messages(cups_array_t *cat,	/* I - Message catalog */
                   const char *lang)	/* I - Output language... */
{
 /*
  * Google provides a simple translation/language tool for translating
  * from one language to another.  It is far from perfect, however it
  * can be used to get a basic translation done or update an existing
  * translation when no other resources are available.
  *
  * Translation requests are sent as HTTP POSTs to
  * "http://translate.google.com/translate_t" with the following form
  * variables:
  *
  *   Name      Description                         Value
  *   --------  ----------------------------------  ----------------
  *   hl        Help language?                      "en"
  *   ie        Input encoding                      "UTF8"
  *   langpair  Language pair                       "en|" + language
  *   oe        Output encoding                     "UTF8"
  *   text      Text to translate                   translation string
  */

  int		ret;			/* Return value */
  _cups_message_t *m;			/* Current message */
  int		tries;			/* Number of tries... */
  http_t	*http;			/* HTTP connection */
  http_status_t	status;			/* Status of POST request */
  char		*idptr,			/* Pointer into msgid */
		buffer[65536],		/* Input/output buffer */
		*bufptr,		/* Pointer into buffer */
		*bufend,		/* Pointer to end of buffer */
		length[16];		/* Content length */
  int		bytes;			/* Number of bytes read */


 /*
  * Connect to translate.google.com...
  */

  puts("Connecting to translate.google.com...");

  if ((http = httpConnect("translate.google.com", 80)) == NULL)
  {
    perror("Unable to connect to translate.google.com");
    return (0);
  }

 /*
  * Scan the current messages, requesting a translation of any untranslated
  * messages...
  */

  for (m = (_cups_message_t *)cupsArrayFirst(cat), ret = 1;
       m;
       m = (_cups_message_t *)cupsArrayNext(cat))
  {
   /*
    * Skip messages that are already translated...
    */

    if (m->str && m->str[0])
      continue;

   /*
    * Encode the form data into the buffer...
    */

    snprintf(buffer, sizeof(buffer),
             "hl=en&ie=UTF8&langpair=en|%s&oe=UTF8&text=", lang);
    bufptr = buffer + strlen(buffer);
    bufend = buffer + sizeof(buffer) - 5;

    for (idptr = m->id; *idptr && bufptr < bufend; idptr ++)
      if (*idptr == ' ')
        *bufptr++ = '+';
      else if (*idptr < ' ' || *idptr == '%')
      {
        sprintf(bufptr, "%%%02X", *idptr & 255);
	bufptr += 3;
      }
      else if (*idptr != '&')
        *bufptr++ = *idptr;

    *bufptr++ = '&';
    *bufptr = '\0';

    sprintf(length, "%d", (int)(bufptr - buffer));

   /*
    * Send the request...
    */

    printf("\"%s\" = ", m->id);
    fflush(stdout);

    tries = 0;

    do
    {
      httpClearFields(http);
      httpSetField(http, HTTP_FIELD_CONTENT_TYPE,
                   "application/x-www-form-urlencoded");
      httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, length);

      if (httpPost(http, "/translate_t"))
      {
	httpReconnect(http);
	httpPost(http, "/translate_t");
      }

      httpWrite2(http, buffer, bufptr - buffer);

      while ((status = httpUpdate(http)) == HTTP_CONTINUE);

      if (status != HTTP_OK && status != HTTP_ERROR)
        httpFlush(http);

      tries ++;
    }
    while (status == HTTP_ERROR && tries < 10);

    if (status == HTTP_OK)
    {
     /*
      * OK, read the translation back...
      */

      bufptr = buffer;
      bufend = buffer + sizeof(buffer) - 1;

      while ((bytes = httpRead2(http, bufptr, bufend - bufptr)) > 0)
        bufptr += bytes;

      if (bytes < 0)
      {
       /*
        * Read error, abort!
	*/

        puts("READ ERROR!");
	ret = 0;
	break;
      }

      *bufptr = '\0';

     /*
      * Find the div containing translation
      */

      if ((bufptr = strstr(buffer, "<div id=result_box")) == NULL)
      {
       /*
        * No textarea, abort!
	*/

        puts("NO div id=result_box!");
	ret = 0;
	break;
      }

      if ((bufptr = strchr(bufptr, '>')) == NULL)
      {
       /*
        * textarea doesn't end, abort!
	*/

        puts("DIV SHORT DATA!");
	ret = 0;
	break;
      }

      bufptr ++;

      if ((bufend = strstr(bufptr, "</div>")) == NULL)
      {
       /*
        * textarea doesn't close, abort!
	*/

        puts("/DIV SHORT DATA!");
	ret = 0;
	break;
      }

      *bufend = '\0';

     /*
      * Copy the translation...
      */

      m->str = strdup(bufptr);

     /*
      * Convert character entities to regular chars...
      */

      for (bufptr = strchr(m->str, '&');
           bufptr;
	   bufptr = strchr(bufptr + 1, '&'))
      {
        if (!strncmp(bufptr, "&lt;", 4))
	{
	  *bufptr = '<';
	  _cups_strcpy(bufptr + 1, bufptr + 4);
	}
        else if (!strncmp(bufptr, "&gt;", 4))
	{
	  *bufptr = '>';
	  _cups_strcpy(bufptr + 1, bufptr + 4);
	}
        else if (!strncmp(bufptr, "&amp;", 5))
	  _cups_strcpy(bufptr + 1, bufptr + 5);
      }

      printf("\"%s\"\n", m->str);
    }
    else if (status == HTTP_ERROR)
    {
      printf("NETWORK ERROR (%s)!\n", strerror(httpError(http)));
      ret = 0;
      break;
    }
    else
    {
      printf("HTTP ERROR %d!\n", status);
      ret = 0;
      break;
    }
  }

  httpClose(http);

  return (ret);
}
Beispiel #18
0
void
translate_messages(const char *language)/* I - Output language... */
{
 /*
  * Google provides a simple translation/language tool for translating
  * from one language to another.  It is far from perfect, however it
  * can be used to get a basic translation done or update an existing
  * translation when no other resources are available.
  *
  * Translation requests are sent as HTTP POSTs to
  * "http://translate.google.com/translate_t" with the following form
  * variables:
  *
  *   Name      Description                         Value
  *   --------  ----------------------------------  ----------------
  *   hl        Help language?                      "en"
  *   ie        Input encoding                      "UTF8"
  *   langpair  Language pair                       "en|" + language
  *   oe        Output encoding                     "UTF8"
  *   text      Text to translate                   translation string
  */

  int		i;			/* Looping var */
  message_t     *m;			/* Current message */
  int		tries;			/* Number of tries... */
  http_t	*http;			/* HTTP connection */
  http_status_t	status;			/* Status of POST request */
  char		*idptr,			/* Pointer into msgid */
		*strptr,		/* Pointer into msgstr */
		buffer[65536],		/* Input/output buffer */
		*bufptr,		/* Pointer into buffer */
		*bufend,		/* Pointer to end of buffer */
		length[16];		/* Content length */
  unsigned char	*utf8;			/* UTF-8 string */
  int		ch;			/* Current decoded character */
  int		bytes;			/* Number of bytes read */


 /*
  * Connect to translate.google.com...
  */

  puts("Connecting to translate.google.com...");

  if ((http = httpConnect("translate.google.com", 80)) == NULL)
  {
    perror("Unable to connect to translate.google.com");
    return;
  }

 /*
  * Scan the current messages, requesting a translation of any untranslated
  * messages...
  */

  for (i = num_messages, m = messages; i > 0; i --, m ++)
  {
   /*
    * Skip messages that are already translated...
    */

    if (m->str && m->str[0])
      continue;

   /*
    * Encode the form data into the buffer...
    */

    snprintf(buffer, sizeof(buffer),
             "hl=en&ie=UTF8&langpair=en|%s&oe=UTF8&text=", language);
    bufptr = buffer + strlen(buffer);
    bufend = buffer + sizeof(buffer) - 5;

    for (idptr = m->id; *idptr && bufptr < bufend; idptr ++)
      if (*idptr == ' ')
        *bufptr++ = '+';
      else if (*idptr < ' ' || *idptr == '%')
      {
        sprintf(bufptr, "%%%02X", *idptr & 255);
	bufptr += 3;
      }
      else if (*idptr != '&')
        *bufptr++ = *idptr;

    *bufptr++ = '&';
    *bufptr = '\0';

    sprintf(length, "%d", bufptr - buffer);

   /*
    * Send the request...
    */

    printf("\"%s\" = ", m->id);
    fflush(stdout);

    tries = 0;

    do
    {
      httpClearFields(http);
      httpSetField(http, HTTP_FIELD_CONTENT_TYPE,
                   "application/x-www-form-urlencoded");
      httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, length);

      if (httpPost(http, "/translate_t"))
      {
	httpReconnect(http);
	httpPost(http, "/translate_t");
      }

      httpWrite(http, buffer, bufptr - buffer);

      while ((status = httpUpdate(http)) == HTTP_CONTINUE);

      if (status != HTTP_OK && status != HTTP_ERROR)
        httpFlush(http);

      tries ++;
    }
    while (status == HTTP_ERROR && tries < 10);

    if (status == HTTP_OK)
    {
     /*
      * OK, read the translation back...
      */

      bufptr = buffer;
      bufend = buffer + sizeof(buffer) - 1;

      while ((bytes = httpRead(http, bufptr, bufend - bufptr)) > 0)
        bufptr += bytes;

      if (bytes < 0)
      {
       /*
        * Read error, abort!
	*/

        puts("READ ERROR!");
	break;
      }

      *bufptr = '\0';

     /*
      * Find the first textarea element - that will have the translation data...
      */

      if ((bufptr = strstr(buffer, "<textarea")) == NULL)
      {
       /*
        * No textarea, abort!
	*/

        puts("NO TEXTAREA!");
	break;
      }

      if ((bufptr = strchr(bufptr, '>')) == NULL)
      {
       /*
        * textarea doesn't end, abort!
	*/

        puts("TEXTAREA SHORT DATA!");
	break;
      }

      utf8 = (unsigned char *)bufptr + 1;

      if ((bufend = strstr(bufptr, "</textarea>")) == NULL)
      {
       /*
        * textarea doesn't close, abort!
	*/

        puts("/TEXTAREA SHORT DATA!");
	break;
      }

      *bufend = '\0';

     /*
      * Copy the UTF-8 translation to ISO-8859-1 (for now)...
      */

      m->str = malloc(bufend - bufptr);

      for (strptr = m->str; *utf8;)
        if (*utf8 < 0x80)
	  *strptr++ = *utf8++;
	else
	{
	  if ((*utf8 & 0xe0) == 0xc0)
	  {
	   /*
	    * Two-byte encoding...
	    */

            ch   = ((utf8[0] & 0x1f) << 6) | (utf8[1] & 0x3f);
	    utf8 += 2;
	  }
	  else if ((ch & 0xf0) == 0xe0)
	  {
	   /*
	    * Three-byte encoding...
	    */

            ch   = ((((utf8[0] & 0x0f) << 6) | (utf8[1] & 0x3f)) << 6) |
	           (utf8[2] & 0x3f);
	    utf8 += 3;
	  }

          if (ch < 256)			/* ISO-8859-1 */
	    *strptr++ = ch;
	  else if (ch == 0x20ac)	/* Euro */
	    *strptr++ = 0xA4;		/* ISO-8859-15 mapping */
	}

      *strptr = '\0';

      printf("\"%s\"\n", m->str);
    }
    else if (status == HTTP_ERROR)
    {
      printf("NETWORK ERROR (%s)!\n", strerror(httpError(http)));
      break;
    }
    else
    {
      printf("HTTP ERROR %d!\n", status);
      break;
    }
  }

  httpClose(http);
}
bool	HttpClient::execute(HttpRequest* request,HttpResponse* respone)
{
	//参数检查
	PTR_BOOL(request);
	PTR_BOOL(respone);
	_request	=	request;
	_response	=	respone;
	setErrorCode(HTTPERROR_SUCCESS);

	//连接服务器
	const std::string&	host	=	_request->getHost();
	int	port_number				=	_request->getPortNumber();
	_proxy_socket->setHost(host,port_number);

	//尝试连接
	{
		const Util::ScopedLock scoped_lock(*_is_valid_lock);
		if (_is_valid)	//判断HttpClient是否还有效
		{
			if (!(_keep_connection && _proxy_socket->isConnected()))
			{
				if (!_proxy_socket->connect())
				{
					setErrorCode(HTTPERROR_CONNECT);
					return false;
				}
			}
		}
		else
		{
			setErrorCode(HTTPERROR_INVALID);
			return false;
		}
	}

	//进行数据传输
	bool	execute				=	false;
	const	std::string& method	=	_request->getMethod();

	//Get方法
	if (_strcmpi(method.c_str(),kget) == 0)
	{
		execute	=	httpGet();
	}
	//Post方法
	else if (_strcmpi(method.c_str(),kpost) == 0)
	{
		execute	=	httpPost();
	}
	//其他,抛出错误
	else
	{
		assert(false);
	}
	
	//如果不是长连接 就关闭网络
	if (!_keep_connection)
	{
		_proxy_socket->close();
	}

	return execute;
}
Beispiel #20
0
/* ======================================================================
Function: emoncmsPost
Purpose : Do a http post to emoncms
Input   : 
Output  : true if post returned 200 OK
Comments: -
====================================================================== */
boolean emoncmsPost(void)
{
  boolean ret = false;

  // Some basic checking
  if (*config.emoncms.host) {
    ValueList * me = tinfo.getList();
    // Got at least one ?
    if (me && me->next) {
      String url ; 
      boolean first_item;

      url = *config.emoncms.url ? config.emoncms.url : "/";
      url += "?";
      if (config.emoncms.node>0) {
        url+= F("node=");
        url+= String(config.emoncms.node);
        url+= "&";
      } 

      url += F("apikey=") ;
      url += config.emoncms.apikey;
      url += F("&json={") ;

      first_item = true;

      // Loop thru the node
      while (me->next) {
        // go to next node
        me = me->next;
        // First item do not add , separator
        if (first_item)
          first_item = false;
        else
          url += ",";

        url +=  me->name ;
        url += ":" ;

        // EMONCMS ne sais traiter que des valeurs numériques, donc ici il faut faire une 
        // table de mappage, tout à fait arbitraire, mais c"est celle-ci dont je me sers 
        // depuis mes débuts avec la téléinfo
        if (!strcmp(me->name, "OPTARIF")) {
          // L'option tarifaire choisie (Groupe "OPTARIF") est codée sur 4 caractères alphanumériques 
          /* J'ai pris un nombre arbitraire codé dans l'ordre ci-dessous
          je mets le 4eme char à 0, trop de possibilités
          BASE => Option Base. 
          HC.. => Option Heures Creuses. 
          EJP. => Option EJP. 
          BBRx => Option Tempo
          */
          char * p = me->value;
            
               if (*p=='B'&&*(p+1)=='A'&&*(p+2)=='S') url += "1";
          else if (*p=='H'&&*(p+1)=='C'&&*(p+2)=='.') url += "2";
          else if (*p=='E'&&*(p+1)=='J'&&*(p+2)=='P') url += "3";
          else if (*p=='B'&&*(p+1)=='B'&&*(p+2)=='R') url += "4";
          else url +="0";
        } else if (!strcmp(me->name, "HHPHC")) {
          // L'horaire heures pleines/heures creuses (Groupe "HHPHC") est codé par un caractère A à Y 
          // J'ai choisi de prendre son code ASCII
          int code = *me->value;
          url += String(code);
        } else if (!strcmp(me->name, "PTEC")) {
          // La période tarifaire en cours (Groupe "PTEC"), est codée sur 4 caractères 
          /* J'ai pris un nombre arbitraire codé dans l'ordre ci-dessous
          TH.. => Toutes les Heures. 
          HC.. => Heures Creuses. 
          HP.. => Heures Pleines. 
          HN.. => Heures Normales. 
          PM.. => Heures de Pointe Mobile. 
          HCJB => Heures Creuses Jours Bleus. 
          HCJW => Heures Creuses Jours Blancs (White). 
          HCJR => Heures Creuses Jours Rouges. 
          HPJB => Heures Pleines Jours Bleus. 
          HPJW => Heures Pleines Jours Blancs (White). 
          HPJR => Heures Pleines Jours Rouges. 
          */
               if (!strcmp(me->value, "TH..")) url += "1";
          else if (!strcmp(me->value, "HC..")) url += "2";
          else if (!strcmp(me->value, "HP..")) url += "3";
          else if (!strcmp(me->value, "HN..")) url += "4";
          else if (!strcmp(me->value, "PM..")) url += "5";
          else if (!strcmp(me->value, "HCJB")) url += "6";
          else if (!strcmp(me->value, "HCJW")) url += "7";
          else if (!strcmp(me->value, "HCJR")) url += "8";
          else if (!strcmp(me->value, "HPJB")) url += "9";
          else if (!strcmp(me->value, "HPJW")) url += "10";
          else if (!strcmp(me->value, "HPJR")) url += "11";
          else url +="0";
        } else {
          url += me->value;
        }
      } // While me

      // Json end
      url += "}";

      ret = httpPost( config.emoncms.host, config.emoncms.port, (char *) url.c_str()) ;
    } // if me
  } // if host
  return ret;
}