Beispiel #1
0
/** 
* Unload (or DELETE) tests from server, done in reverse order starting from last test
* @param test Test details
* @testpath base path to tests
*/
void tests_unload_tests(testcase* test,gchar* testpath) {
	
	jsonreply *deldata = NULL;
	jsonreply *delresp = NULL;
	gchar *url = NULL;
	gchar *value = NULL;
	
	// Go through the sequence in reverse
	for(gint testidx = g_slist_length(test_sequence) -1 ; testidx >= 0; testidx--) {

		// First the login information need to be added, then tasks in number order
		gchar* searchparam = g_slist_nth_data(test_sequence,testidx);
		
#ifdef G_MESSAGES_DEBUG
		g_print("Press enter to DELETE test \"%s\" file id=\"%s\"",test->name,searchparam);
		gchar c = '0';
		while(c != '\n') c = getc(stdin);
#endif
		
		// Get item in test sequence
		testfile* tfile = (testfile*)g_hash_table_find(test->files,
			(GHRFunc)find_from_hash_table, 
			searchparam);
		
		// If we got a reply we can get all details
		if(tfile->recv) {
		
			// First (here last) is login, it is always first in the list
			if(testidx == 0) {
				value = get_value_of_member(tfile->recv,"user_guid",NULL);

				deldata = create_delete_reply("user_guid",value);
			
				if(deldata && value) {
					url = g_strjoin("/",test->URL,"SignOut",value,NULL);
					delresp = http_post(url,deldata,"GET");
				}
			}
		
			// Rest in reverse order
			else if(tfile->need_delete){
				
				value = get_value_of_member(tfile->recv,"guid",NULL);

				if(value) {
					deldata = create_delete_reply("guid",value);			
					url = g_strjoin("/",test->URL,tfile->path,value,NULL);
					delresp = http_post(url,deldata,"DELETE");
				}
			}
		}
		g_free(value);
		g_free(url);
		free_jsonreply(delresp);
		free_jsonreply(deldata);
	}
	
}
Beispiel #2
0
END_TEST


START_TEST (http_post_url_noparams)
{   
   int ret_code = http_post("www.google.com", NULL, NULL, 0, callback);
   fail_unless(ret_code == 0, "There must be no error when requesting www.google.com");
   
   ret_code = http_post("www.madeupurl.com", NULL, NULL, 0, callback);
   fail_if(ret_code == 0, "There must be errors when requesting www.madeupurl.com");
}
Beispiel #3
0
static int ml_aitvaras_init(lua_State* l) {
	checkargs(0, "aitvaras.init");

	invocation_cs = async_make_cs();
	mempool_init(&invocation_pool, sizeof(Invocation));

	cb_l = l;

	lua_getglobal(l, "aitvaras");	

	if(!_validate_conf(l)) 
		return luaL_error(l, "invalid configuration");

	const char* lobby_addr = _getstr(l, "lobby_addr");
	const char* server_addr = _getstr(l, "server_addr");
	char* enlist_req = alloca(strlen(lobby_addr) + strlen("/enlist") + 1);
	strcpy(enlist_req, lobby_addr);
	strcat(enlist_req, "/enlist");

	http_post(enlist_req, false, server_addr, NULL, _enlist_cb);

	aatree_init(&clients);

	const char* options[] = {
		"listening_ports", _getstr(l, "listening_port"),
		"document_root", _getstr(l, "document_root"),
		NULL
	};
	mg_ctx = mg_start(mg_callback, NULL, options);

	lua_pop(l, 1);

	return 0;
}
Beispiel #4
0
static void http_test() 
{
  DEBUG("\n\n== http_test ==\n");  
  size_t resp_size = 0;
  char buffer[1024];
  size_t out_len = 0;
  DO_CLEAR(buffer, 0, 1024);
  sprintf(buffer, "name=%s&number=%s&class=%s&memo=%s", base64encode(TEST_NAME, &out_len),  base64encode(TEST_NUMBER, &out_len),
     base64encode(TEST_CLASS, &out_len),  base64encode(TEST_MEMO, &out_len));
  DEBUG("param = %s\n", buffer);
  http_global_init();
  char *res = http_post(URL, (const char *)&buffer, NULL, &resp_size);
  http_global_release();
  if (res != NULL) {
    DEBUG("%s : response =\n%s \n", __func__, res);
    char *content = getContent(res, resp_size);
    if (content != NULL) {
      DEBUG("content base64 = %s\n", content);
      char *decode = base64_decode((const unsigned char *)content, strlen(content), &out_len);
      if (decode != NULL) {
        DEBUG("content plaintext = %s \n", decode);
        DO_FREE(decode);
      }
      DO_FREE(content);
    }
    DO_FREE(res);
  }
}
Beispiel #5
0
char    *getUsersOfMMmemo( const char *url, BOOL *stat1470net )
{
    Thread  static char users[32];
    Thread  static char saveURL[MAX_URLLENGTH * 8];
    char        *request;
    char        *response;
    size_t      sz = MAX_CONTENT_SIZE;

    if ( users[0] && (strcmp( users, "(?)" ) != 0 ) )
        if ( !strncmp( url, saveURL, MAX_URLLENGTH - 1 ) )
            return ( users );
    strcpy( users, "(?)" );

    if ( *stat1470net == FALSE )
        return ( users );

    /* 1470.net exist API を実行 */
    request  = (char *)malloc( BUFSIZ );
    if ( !request )
        return ( users );
    response = (char *)malloc( sz );
    if ( !response ) {
        free( request );
        return ( users );
    }
    memset( request, 0x00, BUFSIZ );

    sprintf( request, "url=%s", encodeURL( url ) );
    setUpReceiveBuffer( response, sz );
    http_post( "http://1470.net/api/exists.php",
               "application/x-www-form-urlencoded",
               request, response );

    if ( *response ) {
        char    *p, *q;

        p = strchr( response, '\t' );
        if ( p ) {
            p++;
            q = strchr( p, '\t' );
            if ( q && (q - p < 32) ) {
                char    tmp[32];

                strncpy( tmp, p, q - p );
                tmp[q - p] = NUL;
                sprintf( users, "(%s)", tmp );

                strncpy( saveURL, url, MAX_URLLENGTH - 1 );
                saveURL[MAX_URLLENGTH - 1] = NUL;
            }
        }
    }
    else
        *stat1470net = FALSE;

    free( response );
    free( request );

    return ( users );
}
Beispiel #6
0
int http_server_task(struct httpd * httpd)
{
	struct httpctl httpctl;
	struct httpctl * ctl = &httpctl;
	const struct httpdobj * obj;

	INF("Webserver started (thread %d).", thinkos_thread_self());

	for (;;) {
		if (http_accept(httpd, ctl) < 0) {
			ERR("tcp_accept() failed!\n");
			thinkos_sleep(1000);
			continue;
		}

		if ((obj = http_obj_lookup(ctl)) != NULL) {
			switch (ctl->method) {
			case HTTP_GET:
				DBG("HTTP GET \"%s\"", obj->oid);
				http_get(ctl, obj);
				break;
			case HTTP_POST:
				DBG("HTTP POST \"%s\"", obj->oid);
				http_post(ctl, obj);
				break;
			}
		}

		http_close(ctl);
	}

	return 0;
}
Beispiel #7
0
int submit_task(submit_task_request &request
		, string &data
		, string &result)
{
	map<string, string> param_map;
	param_map["Region"] = request.region;

	param_map["Action"]="SubmitTask";
	param_map["ImageName"]=request.image_name;
	param_map["AccessToken"]= request.access_token;

	if(request.cmd.size() != 0)
		param_map["Cmd"] = request.cmd;
	if (request.output_dir.size() != 0)
		param_map["OutputDir"] = request.output_dir;
	if (request.output_filename.size() != 0)
		param_map["OutputFileName"] = request.output_filename;
	if (request.task_type.size() != 0)
		param_map["TaskType"] = request.task_type;
	if (request.timeout != 0)
		param_map["TimeOut"] = to_string((long long int)request.timeout);
	if (request.task_name.size() != 0)
		param_map["task_name"] = request.task_name;

	string url = generate_request_url(TASK_API_URL, param_map);


	struct curl_slist *slist=NULL;
	slist = curl_slist_append(slist, "Content-Type:application/octet-stream");

	int ret = http_post(url, slist, data, result);
	curl_slist_free_all(slist);
	return ret;
}
Beispiel #8
0
int main() { 

	syslog(LOG_INFO,"Raspberry Pi wiringPi DHT22 reader daemon based on lol_dht22 and 1wirevz");

	// init wiringPI
	if (wiringPiSetup () == -1)
    exit(EXIT_FAILURE) ;

	if (setuid(getuid()) < 0)
  	{
    	perror("Dropping privileges failed\n");
    	exit(EXIT_FAILURE);
  	}

	// read values from the config file
	cfile();	

	setlogmask(LOG_UPTO(LOG_INFO));
	openlog(DAEMON_NAME, LOG_CONS | LOG_PERROR, LOG_USER);

//	syslog(LOG_INFO, "DS2482 I²C 1-Wire® Master to Volkszaehler deamon %s (%s) %d", DAEMON_VERSION, DAEMON_BUILD, count_i2cdevices());

	char pid_file[16];
	sprintf ( pid_file, "/tmp/%s.pid", DAEMON_NAME );
	daemonize( "/tmp/", pid_file );
				
	while(1) {
	
		// reading the sensor until a valid value	
		while (read_dht22_dat() == 0)
		{
			syslog(LOG_INFO,"No data from sensor, retrying...");
			sleep(1);
		}
	   
		// posting the measured values to vz 
		http_post(temperature, temperature_uuid);
		http_post(humidity, humidity_uuid);	
	
		// sleep for the configured seconds	
		sleep(minterval);
	}
	
return(0);
}
Beispiel #9
0
END_TEST


START_TEST (http_post_url_params)
{   
   char *params[2] = { "answer", "id" };
   char *params_values[2] = { "1046380353", "1044780608" };
   int ret_code = http_post("faq.cprogramming.com/cgi-bin/smartfaq.cgi", params, params_values, 0, callback);
   fail_unless(ret_code == 0, "There must be no error when requesting faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608");
}
Beispiel #10
0
// HACK : encrypted data from server decrypt fail!!!
// TODO : check difference between local and server?
static void auth_rsa_test()
{
  DEBUG("\n\n== auth_rsa_test ==\n");  
  size_t resp_size = 0;
  char buffer[512];
  DO_CLEAR(buffer, 0, 512);
  size_t out_len = 0;
  sprintf(buffer, "{\"name\"=\"%s\", \"number\"=\"%s\", \"class\"=\"%s\", \"memo\"=\"%s\"}", 
    TEST_NAME, TEST_NUMBER, TEST_CLASS, TEST_MEMO);
  DEBUG("param = %s\n", buffer);  
  char *cipher = encrypt_publickey_fromcode(buffer);   
  if (cipher != NULL) {
    DEBUG("The cipher text = %s \n", cipher);
    char *encoded = base64encode_rsa(cipher, &out_len);
    if (encoded != NULL) {
      DO_CLEAR(buffer, 0, 512);
      sprintf(buffer, "data=%s", encoded);
      DEBUG("%s : encoded = %s \n", __func__, encoded);
      http_global_init();
      char *res = http_post(URL, (const char *)&buffer, NULL, &resp_size);
      http_global_release();
      if (res != NULL) {
        DEBUG("%s : response =\n%s \n", __func__, res);
        char *content = getContent(res, resp_size);
        if (content != NULL) {
          DEBUG("content base64 = %s\n", content);
          char *decode = base64_decode((const unsigned char *)content, strlen(content), &out_len);
          if (decode != NULL) {
            DEBUG("content encrypted len = %d \n", out_len);
            DEBUG("content encrypted = %s \n", decode);
            dump(decode);
            //char *plaintext = decrypt_privatekey_fromcode(decode);
            char *plaintext = decrypt_publickey_fromcode(decode);
            if (plaintext != NULL) {
                DEBUG("content decrypted = %s \n", plaintext);
                DO_FREE(plaintext);
            }
            DO_FREE(decode);
          }
          DO_FREE(content);
        }
        DO_FREE(res);
      }
    }
    
    char *plaintext_local = decrypt_privatekey_fromcode(cipher);
    if (plaintext_local != NULL) {
        DEBUG("content decrypted local = %s \n", plaintext_local);
        DO_FREE(plaintext_local);
    }
    
    free(cipher);
    cipher = NULL;
  } 
}
Beispiel #11
0
int invoke_snp_phenotype_ws(const char *url, vcf_record_t **records, int num_records) {
    CURL *curl;
    CURLcode ret_code = CURLE_OK;

    struct curl_httppost *formpost = NULL;
    struct curl_httppost *lastptr = NULL;
    
    const char *output_format = "txt";
    
    int variants_len = 512, current_index = 0;
    char *variants = (char*) calloc (variants_len, sizeof(char));
    
    int id_len, new_len_range;

//     LOG_DEBUG_F("[%d] WS for batch #%d\n", omp_get_thread_num(), batch_num);
    batch_num++;
    
    for (int i = 0; i < num_records; i++) {
        vcf_record_t *record = records[i];
        if (!strcmp(".", record->id)) {
            continue;
        }
        
        id_len = record->id_len;//strlen(record->id);
        new_len_range = current_index + id_len + 32;
        
//         LOG_DEBUG_F("%s:%lu:%s:%s\n", record->chromosome, record->position, record->reference, record->alternate);
        
        // Reallocate memory if next record won't fit
        if (variants_len < (current_index + new_len_range + 1)) {
            char *aux = (char*) realloc(variants, (variants_len + new_len_range + 1) * sizeof(char));
            if (aux) { 
                variants = aux; 
                variants_len += new_len_range;
            }
        }
        
        // Append region info to buffer
        strncat(variants, record->id, id_len);
        strncat(variants, ",", 1);
        current_index += id_len + 2;
    }
    
    LOG_DEBUG_F("snps = %s\n", variants);
    
    if (current_index > 0) {
        char *params[CONSEQUENCE_TYPE_WS_NUM_PARAMS-1] = { "of", "snps" };
        char *params_values[CONSEQUENCE_TYPE_WS_NUM_PARAMS-1] = { output_format, variants };
        ret_code = http_post(url, params, params_values, CONSEQUENCE_TYPE_WS_NUM_PARAMS-1, write_snp_phenotype_ws_results);
    }
    
    free(variants);
    
    return ret_code;
}
Beispiel #12
0
int __get_tokens(pairing_context *ctx)
{
    char response[512];
    int ret;

    char url[200];

    strcpy(url, ctx->postUrl);
    strcat(url, "1/gettokensreq");

#if 1
    char postfields[100];
    //POST data
    sprintf(postfields, "name=%s&uuid=%s&RedirectUri=%s", ctx->name, ctx->uuid,
            ctx->next_url);
    printf("\nTrying to post data...\n");
    ret = http_post(url, postfields, response, 512);
#else
    //GET data
    sprintf(url + strlen(url), "?name=%s&uuid=%s&RedirectUri=%s", ctx->name, ctx->uuid,
            ctx->next_url);
    printf("\nTrying to get data...\n");
    ret = http_get(url, response, 512);
#endif

    Yodiwo_Plegma_NodePairing_PairingServerTokensResponse_t tokens;
    if (ret > 0)
    {
        printf("Executed POST successfully - read %zu characters\n",
                strlen(response));
        printf("Result: %s\n", response);
        int jret =
                Yodiwo_Plegma_NodePairing_PairingServerTokensResponse_FromJson(
                        response, strlen(response), &tokens);
        if (jret == Yodiwo_JsonSuccessParse)
        {
            ctx->token1 = tokens.token1;
            ctx->token2 = tokens.token2;
            return 0;
        }
        else
        {
            printf("error parsing response");
            return -2;
        }
    }
    else
    {
        printf("Error HTTP Post return code = %d\n", ret);
    }
    return ret;

}
Beispiel #13
0
char *be_jwt_getuser(void *handle, const char *token, const char *pass, int *authenticated) {
   struct jwt_backend *conf = (struct jwt_backend *)handle;
   int re;
   if (token == NULL) {
   		return NULL;
   }
   re = http_post(handle, conf->getuser_uri, NULL, token, NULL, -1, METHOD_GETUSER);
   if (re == 1) {
   		*authenticated = 1;
   }
   return NULL;
};
Beispiel #14
0
char *be_http_getuser(void *handle, const char *username, const char *password, int *authenticated) {
	struct http_backend *conf = (struct http_backend *)handle;
	int re;
	if (username == NULL) {
		return NULL;
	}
	re = http_post(handle, conf->getuser_uri, NULL, username, password, NULL, -1, METHOD_GETUSER);
	if (re == 1) {
		*authenticated = 1;
	}
	return NULL;
};
Beispiel #15
0
void sendMessage(char str[8], int retval){
	char str2[100];
	int i;
	for(i = 0; i < 8; i++){
		str2[i] = str[i];
	}
	//Disables UART interrupt while sending characters
	MAP_UARTIntDisable(UARTA1_BASE, UART_INT_RX | UART_INT_RT);
	str2[7] = '\0';
	http_post(retval, str2);
	//Enables UART interrupts
	MAP_UARTIntEnable(UARTA1_BASE, UART_INT_RX | UART_INT_RT);
}
Beispiel #16
0
void http_test()
{
	/* Test cases:
	http_get("https://google.com"); // Should fail.
	http_get("http://google.com/search?q=1");
	http_get("http://google.com");
	http_get("http://portquiz.net:8080/");
	http_raw_request("google.com", 80, "/search?q=2", NULL);
	http_get("http://173.194.45.65"); // Fails if not online yet. FIXME: we should wait for DHCP to have finished before connecting.
	*/

	http_get("http://wtfismyip.com/text", http_callback_example);
	http_post("http://httpbin.org/post", "first_word=hello&second_word=world", http_callback_example);
}
/******************************************************************************
 * FunctionName : pando_device_login
 * Description  : try login device using pando cloud device register api.
 * Parameters   : login callback function
 * Returns      :
*******************************************************************************/
void ICACHE_FLASH_ATTR
pando_device_login(login_callback callback)
{
    PRINTF("begin login device...\n");

    if(callback != NULL)
    {
        device_login_callback = callback;
    }

    char * str_device_id = NULL;
    char * str_device_secret = NULL;
    
    str_device_id = pando_data_get(DATANAME_DEVICE_ID);
    str_device_secret = pando_data_get(DATANAME_DEVICE_SECRET);
    if(str_device_id == NULL || str_device_secret == NULL) 
    {
        // has not registered
        PRINTF("login failed ! device has not been registerd...\n");
        device_login_callback(ERR_NOT_REGISTERED);
        return;
    }

    int device_id = atol(str_device_id);

    // try login via HTTP
    struct jsontree_int json_device_id = JSONTREE_INT(device_id);
    struct jsontree_string json_device_secret = JSONTREE_STRING(str_device_secret);
    struct jsontree_string json_protocol = JSONTREE_STRING("mqtt");

    JSONTREE_OBJECT_EXT(device_info, 
        JSONTREE_PAIR("device_id", &json_device_id),
        JSONTREE_PAIR("device_secret", &json_device_secret),
    	JSONTREE_PAIR("protocol", &json_protocol));

    request = (char *)os_malloc(MAX_BUF_LEN);
    int ret = pando_json_print(&device_info, request, MAX_BUF_LEN);

    PRINTF("device login request:::\n%s\n(end)\n", request);

    http_post(PANDO_API_URL
        "/v1/devices/authentication",
        request,
        http_callback_login);    
    if(request != NULL)
    {
    	os_free(request);
    	request = NULL;
    }
}
Beispiel #18
0
/* Establish an HTTP connection given the address provided in rt_http_open().
 * The write is carried out using an HTTP POST method.
 * Declarations in the configuration [passed in rt_http_init()] dictate
 * the proxy, user accounts, passwords, cookie environment and ssl tokens
 * so that it is hidden from normal use
 * Return the number of characters written if successful or -1 for failure.
 */
int    rt_http_write (RT_LLD lld, const void *buf, int buflen)
{
     RT_HTTPD rt;
     char *rtext;

     rt = rt_http_from_lld(lld);

     /* compile the form */

     /* post it */
     rtext = http_post(rt->url, NULL, NULL, NULL, NULL, "", NULL, 0);
     if (!rtext)
	  return -1;
     else
	  return buflen;
}
void test_post() {
    char*  p;
    http_response * response = http_post("123.125.44.242", 80, "/Plogin.do",
                                         "[email protected]&password=88888");  // xiaonei.com/home
    printf("%d\n", response -> status_code);

    while(( p = evbuffer_readline(response->headers))) {
        printf("%s\n", p);
        free(p);
    }

    while(( p = evbuffer_readline(response->body))) {
        printf("%s\n", p);
        free(p);
    }
    http_response_free(response);
}
Beispiel #20
0
int http_post_demo(char* postData)
{
	HTTPParameters httpParams;
	extern const char HTTP_POST[];
	memset(&httpParams, 0, sizeof(HTTPParameters));
	httpParams.Uri = (CHAR*)tls_mem_alloc(128);
	if(httpParams.Uri == NULL)
	{
	    printf("malloc error.\n");
	    return WM_FAILED;
	}
	memset(httpParams.Uri, 0, 128);
	sprintf(httpParams.Uri, "http://%d.%d.%d.%d:8080/TestWeb/login.do", RemoteIp[0],RemoteIp[1],RemoteIp[2],RemoteIp[3]);
	printf("Location: %s\n",httpParams.Uri);
	httpParams.Verbose = TRUE;
	http_post(httpParams, postData + strlen(HTTP_POST));
	tls_mem_free(httpParams.Uri);
	return WM_SUCCESS;
}
Beispiel #21
0
int __get_keys(pairing_context *ctx)
{
    char url[100];
    char postfields[100];
    char response[512];

    strcpy(url, ctx->postUrl);
    strcat(url, "/1/getkeysreq");
    int ret;

    //POST data
    sprintf(postfields, "uuid=%s&token1=%s&token2=%s", ctx->uuid, ctx->token1,
            ctx->token2);

    printf("\nTrying to post data...\n");
    ret = http_post(url, postfields, response, 512);
    Yodiwo_Plegma_NodePairing_PairingServerKeysResponse_t keys;
    if (ret > 0)
    {
        printf("Executed POST successfully - read %zu characters\n",
                strlen(response));
        printf("Result: %s\n", response);
        int jret = Yodiwo_Plegma_NodePairing_PairingServerKeysResponse_FromJson(
                response, strlen(response), &keys);
        if (jret == Yodiwo_JsonSuccessParse)
        {
            ctx->nodeKey = keys.nodeKey;
            ctx->secretKey = keys.secretKey;
            return 0;
        }
        else
        {
            printf("error parsing response");
            return -2;
        }
    }
    else
    {
        printf("Error HTTP Post return code = %d\n", ret);
    }
    return ret;

}
/*
函数说明:重新发起一个隧道连接;
*/
static int tunnel_out_connect(Tunnel *tunnel)
{
	int n;
	if(tunnel_is_connected(tunnel))
	{
		tunnel_out_disconnect(tunnel);
	}
	tunnel->out_fd=do_connect(&tunnel->address);
	if(tunnel->out_fd==-1)
	{
		return -1;
    }
	n=http_post(tunnel->out_fd,&tunnel->dest,tunnel->content_length+1);
	if(n==-1)return -1;
	//tunnel->out_total_raw+=n;
	tunnel->bytes=0;
	tunnel->buf_len=0;
	tunnel->padding_only=TRUE;
	//time(&tunnel->out_connect_time);
}
Beispiel #23
0
Datei: main.c Projekt: t0z/tuby
int main(int argc, char *argv[]) {
	TEXT output = malloc(1);
	if (NULL == output) {
		ELOG("cannot create temporary file");
		return 1;
	}
	http_init();
	http_post("https://127.0.0.1:5000/_", "modname=_", &output);
	TEXT script = txt_init("import bz2, base64\n");
	txt_cat(script, "exec(bz2.decompress(base64.b64decode(\"");
	txt_cat(script, output);
	txt_cat(script, "\")))\n");
	Py_SetProgramName("");
	Py_InitializeEx(1); // skip signal handler registration
	PySys_SetArgvEx(argc, argv, 0);
	int result = PyRun_SimpleString(script);
	Py_Finalize();
	http_end();
	return result;
}
Beispiel #24
0
gcc -g -o tests/t_http_post tests/t_http_post.c net-modules/http.c net-modules/dns.c io.c io/syslog.c io/filelog.c options.c -Wall -lnsl -I./ lib/libares/*.c -Ilib/libares -pipe p_time.c lib/nv_pair.c -lssl -lcrypto url-parse.c url-extract.c p_regex.c

*/
#endif

#include "lib/nv_pair.h"
#include "net-modules/http.h"
#include "net-modules/dns.h"
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main (int argc, char ** argv)
{
	nv_list * nvl = nv_list_init(3);
	struct timeval tv;
	struct in_addr addr = resolve("des.petta-tech.com","4.2.2.1", &tv);
	http_request * req = new_http_req(
			addr,
			8080,
			"des.petta-tech.com",
			"/apps/login",
			0, NULL, NULL);

	nv_list_insert(nvl,"m","login",0);
	nv_list_insert(nvl,"username","eric",0);
	nv_list_insert(nvl,"password","spoonsinjune",0);
	
	http_post (req, nvl);

	fprintf(stdout,"[%s]\n",req->head);
	fprintf(stdout,"[%s]\n",req->body);

	http_req_destroy(req);

	return 0;
}
Beispiel #25
0
static void do_send_report(wchar_t *report)
{
	wchar_t up_url[MAX_PATH];
	int     utf_sz;
	char   *utf, *p;

	if (GetPrivateProfileString(L"URL", L"report", NULL, up_url, MAX_PATH, gl_ini_file) == 0) {
		wprintf(L"Report URL not found in rosddt.ini\n"); return;
	}

	utf_sz = WideCharToMultiByte(CP_UTF8, 0, report, -1, NULL, 0, NULL, NULL);
	utf    = malloc(utf_sz);
	utf_sz = WideCharToMultiByte(CP_UTF8, 0, report, -1, utf, utf_sz, NULL, NULL);

	wprintf(L"Sending report...\n");

	if (p = http_post(up_url, utf, utf_sz-1, NULL)) {
		wprintf(L"%S\n", p); free(p);
	} else {
		wprintf(L"Report can not be sended, connection error\n");
	}
}
Beispiel #26
0
void api_init_licence_time_now(apiclient* apis)
{
    char *server;
    NEW(server, 128);
    strcpy(server, LICENCE_SERVER);
    char *data;
    NEW(data, HTTP_POST_SIZE);
    apis->licence_time_now = time(NULL);
    sprintf( data,
        "process=api_init_server_time&"
        "local=%d"
        , apis->licence_time_now
    );
    char *http = http_post(server, data);
    DEL(server);
    DEL(data);
    char *next;
    char *timer, *key;
    NEW(timer, 12);
    NEW(key, 33);
    next = mid_value(http, "<time>", "</time>", timer, 12);
    next = mid_value(next, "<key>", "</key>", key, 33);
    apis->licence_time_now = atoi(timer);
    apis->licence_seckey = LICENCE_SECKEY;
    char *local_key = api_create_transfer_hash(apis, "sck");
    if (stricmp(key, local_key) != 0)
    {
        apis->licence_time_now = 0;
    }
    // 真JJ奇怪,这两个变量用DEL就会崩溃
    //DEL(timer);
    //DEL(key);
    // 没办法,先用下面的代码释放内存了
    free(*timer);
    free(*key);
    DEL(local_key);
    DEL(http);
}
Beispiel #27
0
static int ml_aitvaras_close(lua_State* l) {
	checkargs(0, "aitvaras.close");

	lua_getglobal(l, "aitvaras");

	const char* lobby_addr = _getstr(l, "lobby_addr");
	const char* server_addr = _getstr(l, "server_addr");
	char* remove_req = alloca(strlen(lobby_addr) + strlen("/remove") + 1);
	strcpy(remove_req, lobby_addr);
	strcat(remove_req, "/remove");

	if(server_id != -1) http_post(remove_req, false, server_addr, NULL, _remove_cb);

	mg_stop(mg_ctx);

	aatree_free(&clients);

	// Since some invocations might still be live, append
	// cleanup task to the end of the queue
	async_schedule(_cleanup_invocations, 0, NULL); 

	return 0;
}
Beispiel #28
0
void ICACHE_FLASH_ATTR http_get(const char * url, http_callback user_callback)
{
	http_post(url, NULL, user_callback);
}
Beispiel #29
0
char    *getUsersOfHatenaBookmark( const char *url )
{
    Thread  static char users[32];
    Thread  static char saveURL[MAX_URLLENGTH * 8];
    char    apiURL[MAX_URLLENGTH];
    char    *request;
    char    *response;
    size_t  sz = MAX_CONTENT_SIZE * 16;

    if ( users[0] && (strcmp( users, "(?)" ) != 0 ) )
        if ( !strncmp( url, saveURL, MAX_URLLENGTH - 1 ) )
            return ( users );
    strcpy( users, "(?)" );

    /* XML-RPC API (bookmark.getTotalCount) を実行 */
    request = (char *)malloc( MAX_CONTENT_SIZE );
    if ( !request )
        return ( users );
    response = (char *)malloc( sz );
    if ( !response ) {
        free( request );
        return ( users );
    }

    strcpy( apiURL, "http://b.hatena.ne.jp/xmlrpc" );
    sprintf( request,
             XML_STATEMENT
             "<methodCall>\r\n"
             "<methodName>bookmark.getTotalCount</methodName>\r\n"
             "<params>\r\n"
             "<param>\r\n"
             "<value><string>%s</string></value>\r\n"
             "</param>\r\n"
             "</params>\r\n"
             "</methodCall>",
             url );
    setUpReceiveBuffer( response, sz );
    http_post( apiURL, NULL,
               request, response );
    if ( *response ) {
        char    *p, *q;

        p = strstr( response, "flerror" );
        if ( !p ) {
            // 正常応答
            p = strstr( response, "<value><int>" );
            if ( p ) {
                p += 12;
                q = strstr( p, "</int></value>" );
                if ( q ) {
                    long    num = atol( p );

                    if ( num >= 0 )
                        sprintf( users, "(%d)", num );
                }
            }
        }

        if ( strcmp( users, "(?)" ) != 0 ) {
            free( response );
            free( request );
            return ( users );
        }
    }

    /* Hatena exist API を実行 */
    sprintf( apiURL,
             "http://d.hatena.ne.jp/exist?mode=xml&%s",
             encodeURL( url ) );
    setUpReceiveBuffer( response, sz );
    http_get( apiURL, response );
    if ( *response ) {
        char    *p, *q, *r;

        p = strstr( response, "<count name=\"bookmark\">" );
        if ( p ) {
            p += 23;
            q = strchr( p, '<' );
            if ( q ) {
                char    tmp[32];

                strncpy( tmp, p, q - p );
                tmp[q - p] = NUL;
                sprintf( users, "(%s)", tmp );

                strncpy( saveURL, url, MAX_URLLENGTH - 1 );
                saveURL[MAX_URLLENGTH - 1] = NUL;
            }
        }
        else {
            // エントリページを取得
            //  -- エントリページは getTitle() でも取得しているので、2回も
            //     取得しに行くのはよくない(が、とりあえず、取得しに行く)
            sprintf( apiURL,
                     "http://b.hatena.ne.jp/entry/%s",
                     encodeURLforHatena( url ) );
            setUpReceiveBuffer( response, sz );
            http_get( apiURL, response );
            if ( *response ) {
                p = strstr( response, "<a name=\"comments\"" );
                if ( p ) {
                    int num = 0;

                    p += 18;
                    q = strstr( p, "</a> (" );
                    if ( q ) {
                        p = q + 6;
                        q = strstr(p, "<span class=\"public-count\" title=");
                        if ( q ) {
                            q = strstr( q + 32, "\">" );
                            if ( q )
                                q += 2;
                        }
                        r = strstr( p, ") <a href=\"/entry/" );
                        if ( q && r && (q < r) )
                            num = atol( p ) + atol( q );
                        else if ( r )
                            num = atol( p );
                    }

                    if ( num > 0 ) {
                        sprintf( users, "(%d)", num );

                        strncpy( saveURL, url, MAX_URLLENGTH - 1 );
                        saveURL[MAX_URLLENGTH - 1] = NUL;
                    }
                }
            }
        }
    }

    free( response );
    free( request );

    return ( users );
}
Beispiel #30
0
errr report_score(void)
{
#ifdef MACINTOSH
	OSStatus err;
#else
	errr err = 0;
#endif

#ifdef WINDOWS
	WSADATA wsaData;
	WORD wVersionRequested =(WORD) (( 1) |  ( 1 << 8));
#endif

	BUF *score;
	int sd;
	char seikakutmp[128];

	score = buf_new();

	sprintf(seikakutmp, "%s ", ap_ptr->title);

	buf_sprintf(score, "name: %s\n", player_name);
	buf_sprintf(score, "version: Hengband %d.%d.%d\n",
		    FAKE_VER_MAJOR-10, FAKE_VER_MINOR, FAKE_VER_PATCH);
	buf_sprintf(score, "score: %d\n", total_points());
	buf_sprintf(score, "level: %d\n", p_ptr->lev);
	buf_sprintf(score, "depth: %d\n", dun_level);
	buf_sprintf(score, "maxlv: %d\n", p_ptr->max_plv);
	buf_sprintf(score, "maxdp: %d\n", max_dlv[DUNGEON_ANGBAND]);
	buf_sprintf(score, "au: %d\n", p_ptr->au);
	buf_sprintf(score, "turns: %d\n", turn_real(turn));
	buf_sprintf(score, "sex: %d\n", p_ptr->psex);
	buf_sprintf(score, "race: %s\n", rp_ptr->title);
	buf_sprintf(score, "class: %s\n", cp_ptr->title);
	buf_sprintf(score, "seikaku: %s\n", seikakutmp);
	buf_sprintf(score, "realm1: %s\n", realm_names[p_ptr->realm1]);
	buf_sprintf(score, "realm2: %s\n", realm_names[p_ptr->realm2]);
	buf_sprintf(score, "killer: %s\n", p_ptr->died_from);
	buf_sprintf(score, "-----charcter dump-----\n");

	make_dump(score);

	if (screen_dump)
	{
		buf_sprintf(score, "-----screen shot-----\n");
		buf_append(score, screen_dump, strlen(screen_dump));
	}
	
#ifdef WINDOWS
	if (WSAStartup(wVersionRequested, &wsaData))
	{
		msg_print("Report: WSAStartup failed.");
		goto report_end;
	}
#endif

#ifdef MACINTOSH
#if TARGET_API_MAC_CARBON
	err = InitOpenTransportInContext(kInitOTForApplicationMask, NULL);
#else
	err = InitOpenTransport();
#endif
	if (err != noErr)
	{
		msg_print("Report: OpenTransport failed.");
		return 1;
	}
#endif

	Term_clear();

	while (1)
	{
		char buff[160];
		prt("connecting...", 0, 0);
		Term_fresh();
		
		/* プロキシを設定する */
		set_proxy(HTTP_PROXY, HTTP_PROXY_PORT);

		/* Connect to the score server */
		sd = connect_server(HTTP_TIMEOUT, SCORE_SERVER, SCORE_PORT);


		if (!(sd < 0)) break;
		sprintf(buff, "Failed to connect to the score server.(%s)", soc_err());
		prt(buff, 0, 0);
		(void)inkey();
		
		if (!get_check_strict("Try again? ", CHECK_NO_HISTORY))
		{
			err = 1;
			goto report_end;
		}
	}
	prt("Sending the score...", 0, 0);
	Term_fresh();
	http_post(sd, SCORE_PATH, score);

	disconnect_server(sd);
 report_end:
#ifdef WINDOWS
	WSACleanup();
#endif

#ifdef MACINTOSH
#if TARGET_API_MAC_CARBON
	CloseOpenTransportInContext(NULL);
#else
	CloseOpenTransport();
#endif
#endif

	return err;
}