static object_query_t *set_object_raw(object_query_t *req) { int resp_code; object_query_t *resp = NULL; ne_buffer *req_body = NULL; ne_buffer *resp_body = NULL; assert(NULL != req); /* Sanity check */ assert(SET_OBJECT_REQUEST == req->type); assert(RAW_POST == req->mode); /* Serialise request POST data */ req_body = set_object_serialise_raw(req); /* Send request */ resp_body = ne_buffer_create(); assert(NULL != resp_body); resp_code = send_http_request(session, "POST", "/set_obj.htm", NULL, req_body, resp_body); /* * Repeat in case of 401 - Unauthorised * * Note that this is a WA of NMC sending Connection: close * header in the 401 response, in which case neon closes * connection (quite rightfully). */ if (401 == resp_code) resp_code = send_http_request(session, "POST", "/set_obj.htm", NULL, req_body, resp_body); /* Deserialise response */ if (200 == resp_code) resp = set_object_deserialise_raw(resp_body); /* Cleanup */ if (NULL != req_body) ne_buffer_destroy(req_body); if (NULL != resp_body) ne_buffer_destroy(resp_body); return resp; }
void http_net::open_url(const string& url, receive_functor receive_cb_, const size_t timeout, const bool continue_on_error_status_) { // set the new server_url (note that any amount of urls can be requested consecutively on the same connection) server_url = url; request_timeout = timeout; continue_on_error_status = continue_on_error_status_; receive_cb = receive_cb_; send_http_request(url, server_name); }
static object_query_t *set_object_form(object_query_t *req) { int resp_code; ne_buffer *req_body = NULL; const char *ct = "multipart/form-data; boundary=" FORM_POST_BOUNDARY; /* TODO: Single request doesn't seem to work if (1 == object_query_size(req)) ct = "application/x-form-urlencoded"; */ assert(NULL != req); /* Sanity check */ assert(SET_OBJECT_REQUEST == req->type); assert(FORM_POST == req->mode); /* Serialise request POST data */ req_body = set_object_serialise_form(req); /* Send request (response is ignored by the proto. spec v3) */ resp_code = send_http_request(session, "POST", "/Forms/set_obj_2", ct, req_body, NULL); /* * Repeat in case of 401 - Unauthorised * * Note that this is a WA of NMC sending Connection: close * header in the 401 response, in which case neon closes * connection (quite rightfully). */ if (401 == resp_code) { resp_code = send_http_request(session, "POST", "/Forms/set_obj_2", ct, req_body, NULL); } /* Cleanup */ if (NULL != req_body) ne_buffer_destroy(req_body); return NULL; }
http_net::http_net(const string& server_url_, receive_functor receive_cb_, const size_t timeout, const bool continue_on_error_status_) : http_net(server_url_, timeout, continue_on_error_status_) { // note: server_url has already been extracted in the delegated http_net constructor receive_cb = receive_cb_; if(failure) { if(receive_cb) { receive_cb(this, HTTP_STATUS::NONE, server_name, "failure"); } return; } send_http_request(server_url, server_name); }
/** * Post status's tweet * @param status Stastus text * @return true if successful, false otherwise */ bool AdafruitTwitter::tweet(char const* status) { // Data contents: ASSUME key are already in urlencoded char const* httpdata[][2] = { { "status" , status } }; uint8_t data_count = sizeof(httpdata) / sizeof(httpdata[0]); // Send HTTP request AdafruitHTTP http; send_http_request(http, HTTP_METHOD_POST, TWITTER_JSON_UPDATE, httpdata, data_count); http.stop(); return true; }
static gboolean cockpit_http_stream_control (CockpitChannel *channel, const gchar *command, JsonObject *options) { CockpitHttpStream *self = COCKPIT_HTTP_STREAM (channel); if (g_str_equal (command, "done")) { g_return_val_if_fail (self->state == BUFFER_REQUEST, FALSE); self->state = RELAY_REQUEST; send_http_request (self); return TRUE; } return FALSE; }
bool CGetter::start() { do { if (!get_ip_list()) break; if (!send_http_request()) break; if (!wait_response()) break; return true; } while(false); return false; }
/** * Sends a new direct message to the specified user from the authenticating user. * Requires both the user and text parameters and must be a POST. * @param user Recipient username * @param text Direct message's content * @return true if successful, false otherwise */ bool AdafruitTwitter::sendDirectMessage(char const* username, char const* text) { // Data contents: ASSUME key are already in urlencoded char const* httpdata[][2] = { { "screen_name" , username }, { "text" , text }, }; uint8_t data_count = arrcount(httpdata); #ifdef DEBUG_TWITTER_DM_SCREENNAME httpdata[0][1] = DEBUG_TWITTER_DM_SCREENNAME; #endif // Send HTTP request AdafruitHTTP http; send_http_request(http, HTTP_METHOD_POST, TWITTER_JSON_DIRECTMESSAGE_NEW, httpdata, data_count); http.stop(); return true; }
static void HttpProtocol_on_error(Protocol *prot, DWORD error) { HttpProtocol *This = impl_from_Protocol(prot); HRESULT hres; TRACE("(%p) %d\n", prot, error); if(prot->flags & FLAG_FIRST_CONTINUE_COMPLETE) { FIXME("Not handling error %d\n", error); return; } while((hres = handle_http_error(This, error)) == RPC_E_RETRY) { error = send_http_request(This); if(error == ERROR_IO_PENDING || error == ERROR_SUCCESS) return; } protocol_abort(prot, hres); protocol_close_connection(prot); return; }
int ParseJSON(cJSON *node, const char *box_id) { FILE *stream = NULL; char buf[512] = {0}; char *result_url; cJSON *cmdArray = cJSON_GetObjectItem(node, "remote_control"); ghttp_request *req_remotectl_feedback; char *id = NULL, *content = NULL; char *command = NULL, *ptr = NULL, *p = NULL; if(!cmdArray) { bail("parse result : json has no node named remote_control"); return 0; } char *errorMsg = NULL; cJSON *cmdList = cmdArray->child; while(cmdList != NULL) { if(cJSON_GetObjectItem(cmdList, "id")->valuestring != NULL) { id = cJSON_GetObjectItem(cmdList, "id")->valuestring; printf("id : %s\n", id); } if(cJSON_GetObjectItem(cmdList, "content")->valuestring != NULL) { content = cJSON_GetObjectItem(cmdList, "content")->valuestring; printf("content : %s\n", content); } stream = NULL; if(strcmp(content, "reboot") == 0) { printf("command : reboot\n"); printf("send http feedback...\n"); result_url = (char *)malloc(150); req_remotectl_feedback = ghttp_request_new(); sprintf(result_url, "http://www.ailvgobox.com/box_manage/remote_feedback.php?box_id=%s&id=%s&result=reboot_ok", box_id, id); printf("result_url : %s\n", result_url); result_url[149] = '\0'; send_http_request(req_remotectl_feedback, result_url); ghttp_request_destroy(req_remotectl_feedback); free(result_url); printf("command : reboot, run!\n"); stream = popen(content, "r"); pclose(stream); } ptr = strstr(content, "@"); if(!ptr) { printf("content : one command!\n"); printf("command : %s, run!\n", content); stream = popen(content, "r"); memset(buf, 0, 512); fread(buf, sizeof(char), sizeof(buf), stream); buf[511] = '\0'; printf("buf : %s\n", buf); pclose(stream); str_rep(buf, '\n', ','); str_rep(buf, ' ', '-'); if(strlen(buf) == 0) strcpy(buf, "no_result"); printf("send http feedback...\n"); result_url = (char *)malloc(strlen(buf)+150); memset(result_url, 0, strlen(buf)+150); req_remotectl_feedback = ghttp_request_new(); sprintf(result_url, "http://www.ailvgobox.com/box_manage/remote_feedback.php?box_id=%s&id=%s&result=%s", box_id, id, buf); printf("result_url : %s\n", result_url); result_url[strlen(buf)+150-1] = '\0'; send_http_request(req_remotectl_feedback, result_url); ghttp_request_destroy(req_remotectl_feedback); free(result_url); } else { printf("content : multiple command!\n"); command = strtok_r(content, "@", &p); while(command) { printf("command : %s\n", command); if(strcmp(command, "reboot") == 0) { printf("command : reboot\n"); printf("send http feedback...\n"); result_url = (char *)malloc(150); req_remotectl_feedback = ghttp_request_new(); sprintf(result_url, "http://www.ailvgobox.com/box_manage/remote_feedback.php?box_id=%s&id=%s&result=reboot_ok", box_id, id); printf("result_url : %s\n", result_url); result_url[149] = '\0'; send_http_request(req_remotectl_feedback, result_url); ghttp_request_destroy(req_remotectl_feedback); free(result_url); printf("command : reboot, run!\n"); stream = popen(command, "r"); pclose(stream); } else { printf("command : %s, run!\n", command); stream = popen(command, "r"); memset(buf, 0, 512); fread(buf, sizeof(char), sizeof(buf), stream); buf[511] = '\0'; printf("buf : %s\n", buf); pclose(stream); str_rep(buf, '\n', ','); str_rep(buf, ' ', '-'); if(strlen(buf) == 0) strcpy(buf, "no_result"); printf("send http feedback...\n"); result_url = (char *)malloc(strlen(buf)+150); memset(result_url, 0, strlen(buf)+150); req_remotectl_feedback = ghttp_request_new(); sprintf(result_url, "http://www.ailvgobox.com/box_manage/remote_feedback.php?box_id=%s&id=%s&result=%s", box_id, id, buf); printf("result_url : %s\n", result_url); result_url[strlen(buf)+150-1] = '\0'; send_http_request(req_remotectl_feedback, result_url); ghttp_request_destroy(req_remotectl_feedback); free(result_url); } command = strtok_r(NULL, "@", &p); } } cmdList = cmdList->next; } }
int remote_control() { ghttp_request *req; char *http_body = NULL; req = ghttp_request_new(); sqlite3 *db = NULL; int rc = 0; sqlite3_stmt *ppstmt = NULL; char sql_cmd[100] ={0}; const char *box_id; char box_id_tmp[10] = {0}; const char *wan_state; char *errorMsg = NULL; char request_url[200] = {0}; printf("****************************************\n"); printf("remote_control : start\n"); printf("****************************************\n"); rc = sqlite3_open(box_db, &db); if(rc == SQLITE_ERROR) { printf("cannot open box.db!\n"); return 0; } strcpy(sql_cmd, "select box_id from box_info"); sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); rc = sqlite3_step(ppstmt); if(rc == SQLITE_ROW) { box_id = sqlite3_column_text(ppstmt, 0); strcpy(box_id_tmp, box_id); printf("box_id : %s\n", box_id_tmp); } sqlite3_finalize(ppstmt); sqlite3_close(db); printf("send http request...\n"); sprintf(request_url, "http://www.ailvgobox.com/box_manage/remote_control.php?box_id=%s", box_id_tmp); printf("request_url : %s\n", request_url); http_body = send_http_request(req, request_url); fprintf(stderr, "http_body : %s\n", http_body); cJSON *node; if(http_body) { printf("HTTP success!\n"); if(strcmp(http_body, "null") == 0) printf("http_body : null, no remote_control!\n"); else { node = cJSON_Parse(http_body); ParseJSON(node, box_id_tmp); } } else { printf("HTTP failure!\n"); } if(http_body) free(http_body); ghttp_request_destroy(req); free(request_url); printf("remote_control : complete!\n"); return 1; }
main() { ghttp_request *req; char http_body[1024] = {0}, *errmsg = NULL; sqlite3 *db = NULL; int rc = 0, result = 0; sqlite3_stmt *ppstmt = NULL; char sql_cmd[100] ={0}; const char *box_id, *wifi_detect; char box_id_tmp[10] = {0}, wifi_detect_tmp[5] = {0}; const char *trafficnum = NULL; char trafficnum_tmp[10] = {0}; char request_url[5000] = {0}, traffic_list[1500] = {0}, time_list[3000] = {0}; int t = 0, select_cnt, ailvgobox_break; printf("****************************************\n"); printf("heart_beat : start\n"); printf("****************************************\n"); printf("box.db : check box_id, wifi_detect\n"); select_cnt = 0; while(select_cnt < 20) { if(sqlite3_open(box_db, &db)) printf("cannot open box.db!\n"); strcpy(sql_cmd, "select box_id, wifi_detect from box_info"); sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); rc = sqlite3_step(ppstmt); if(rc == SQLITE_ROW) { box_id = sqlite3_column_text(ppstmt, 0); strcpy(box_id_tmp, box_id); printf("box_id : %s\n", box_id_tmp); wifi_detect = sqlite3_column_text(ppstmt, 1); strcpy(wifi_detect_tmp, wifi_detect); printf("wifi_detect : %s\n", wifi_detect_tmp); sqlite3_finalize(ppstmt); sqlite3_close(db); break; } else { printf("select box_id,wifi_detect failure!\n"); sqlite3_finalize(ppstmt); sqlite3_close(db); sleep(1); select_cnt++; } } if(strcmp(wifi_detect_tmp, "off") == 0) { printf("wifi detect : off, traffic = null!\n"); strcpy(trafficnum_tmp, "null"); } else { printf("wifi detect : on, collect traffic!\n"); t = time(NULL)+8*3600; printf("traffic.db : check new traffic\n"); select_cnt = 0; while(select_cnt < 20) { rc = sqlite3_open(traffic_db, &db); if(rc == SQLITE_ERROR) printf("cannot open traffic.db!\n"); ppstmt = NULL; sprintf(sql_cmd, "select count(*) from traffic_info where time>=%d-650 and time<=%d", t, t); sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); rc = sqlite3_step(ppstmt); if(rc == SQLITE_ROW) { trafficnum = sqlite3_column_text(ppstmt, 0); strcpy(trafficnum_tmp, trafficnum); printf("new traffic in last 10 minutes : %s\n", trafficnum); sqlite3_finalize(ppstmt); sqlite3_close(db); break; } else { printf("select count(*) from traffic.db failure!\n"); sqlite3_finalize(ppstmt); sqlite3_close(db); sleep(10); select_cnt++; } } printf("traffic_total.db : check total traffic\n"); select_cnt = 0; while(select_cnt < 20) { rc = sqlite3_open(traffic_total_db, &db); if(rc == SQLITE_ERROR) printf("cannot open traffic_total.db!\n"); ppstmt = NULL; sprintf(sql_cmd, "select count(*) from traffic_total where time>=%d-650 and time<=%d", t, t); sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); rc = sqlite3_step(ppstmt); if(rc == SQLITE_ROW) { trafficnum = sqlite3_column_text(ppstmt, 0); if(atoi(trafficnum) < atoi(trafficnum_tmp)) { printf("total traffic in last 10 minutes : %s\n", trafficnum); printf("collect in traffic_total.db in progress, retry\n"); sqlite3_finalize(ppstmt); sqlite3_close(db); sleep(10); select_cnt++; } else { strcat(trafficnum_tmp, "*"); strcat(trafficnum_tmp, trafficnum); printf("total traffic in last 10 minutes : %s\n", trafficnum); printf("trafficnum_tmp : %s\n", trafficnum_tmp); sqlite3_finalize(ppstmt); sqlite3_close(db); break; } } else { printf("select count(*) from traffic_total.db failure!\n"); sqlite3_finalize(ppstmt); sqlite3_close(db); sleep(10); select_cnt++; } } } printf("------------ailvgobox monitor---------------\n"); ailvgobox_break = ailvgobox_monitor(); if(ailvgobox_break == 0) { printf("ailvgobox server : online!\n"); printf("------------send heart_beat request---------------\n"); sprintf(request_url, "http://www.ailvgobox.com/box_manage_2/heart_beat_1.php?box_id=%s&traffic=%s", box_id_tmp, trafficnum_tmp); printf("request_url : %s\n", request_url); req = ghttp_request_new(); strcpy(http_body, send_http_request(req, request_url)); ghttp_request_destroy(req); printf("http_body : %s\n", http_body); printf("length of http_body : %d\n", strlen(http_body)); if(strlen(http_body) == 0) { printf("HTTP failure!\n"); if(strcmp(trafficnum_tmp, "null") == 0) printf("Wifi detect : off, skip save traffic\n"); else { printf("Wifi detect : on, save traffic...\n"); select_cnt = 0; while(select_cnt < 20) { rc = sqlite3_open(traffic_saved_db, &db); if(rc == SQLITE_ERROR) printf("cannot open traffic_saved.db!\n"); memset(sql_cmd, 0, sizeof(sql_cmd)); sprintf(sql_cmd, "insert into traffic_saved values('%s', %d)", trafficnum_tmp, t); printf("sql_cmd : %s\n", sql_cmd); result = sqlite3_exec(db, sql_cmd, NULL, NULL, &errmsg); if(result == SQLITE_OK) { printf("insert traffic_saved.db successfully!\n"); sqlite3_free(errmsg); sqlite3_close(db); break; } else { printf("insert traffic_saved.db error : %s", errmsg); sqlite3_free(errmsg); sqlite3_close(db); sleep(1); select_cnt++; } } } } else { printf("HTTP success!\n"); if(strcmp(trafficnum_tmp, "null") == 0) printf("Wifi detect : off, skip send saved_traffic\n"); else { printf("Wifi detect : on, send saved_traffic...\n"); printf("traffic_saved.db : check record\n"); rc = sqlite3_open(traffic_saved_db, &db); if(rc == SQLITE_ERROR) printf("cannot open traffic_saved.db!\n"); ppstmt = NULL; int saved_cnt_tmp = 0; sprintf(sql_cmd, "select count(*) from traffic_saved"); sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); rc = sqlite3_step(ppstmt); if(rc == SQLITE_ROW) { saved_cnt_tmp = sqlite3_column_int(ppstmt, 0); printf("saved_cnt_tmp : %d\n", saved_cnt_tmp); } if(saved_cnt_tmp == 0) printf("No saved traffic, skip traffic resend!\n"); if(saved_cnt_tmp > 0) { ppstmt = NULL; printf("records in traffic_saved.db : %d\n", saved_cnt_tmp); if(saved_cnt_tmp <= 200) sprintf(sql_cmd, "select traffic, time from traffic_saved"); else if(saved_cnt_tmp > 200) sprintf(sql_cmd, "select traffic, time from traffic_saved limit %d, %d", saved_cnt_tmp-200, 200); sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); rc = sqlite3_step(ppstmt); while(rc == SQLITE_ROW) { trafficnum = sqlite3_column_text(ppstmt, 0); strcpy(trafficnum_tmp, trafficnum); printf("traffic : %s\n", trafficnum); t = sqlite3_column_int(ppstmt, 1); printf("time : %d\n", t); strcat(traffic_list, trafficnum_tmp); strcat(traffic_list, "-"); sprintf(time_list, "%s%d-", time_list, t); rc = sqlite3_step(ppstmt); } traffic_list[strlen(traffic_list)-1] = '\0'; time_list[strlen(time_list)-1] = '\0'; printf("-----------send saved_traffic request-----------\n"); ghttp_request *req_traffic_saved; req_traffic_saved = ghttp_request_new(); sprintf(request_url, "http://www.ailvgobox.com/box_manage_2/traffic_resend_1.php?box_id=%s&traffic=%s&time=%s", box_id_tmp, traffic_list, time_list); printf("request_url : %s\n", request_url); strcpy(http_body, send_http_request(req_traffic_saved, request_url)); ghttp_request_destroy(req_traffic_saved); printf("http_body : %s\n", http_body); if(strlen(http_body) > 0) { printf("traffic resend success, delete all records in traffic_saved.db\n"); result = sqlite3_exec(db, "delete from traffic_saved", NULL, NULL, &errmsg); if(result != SQLITE_OK) printf("delete database error : %s", errmsg); } } sqlite3_free(errmsg); sqlite3_finalize(ppstmt); sqlite3_close(db); } } } else { printf("ailvgobox server : offline!\n"); if(strcmp(trafficnum_tmp, "null") == 0) printf("Wifi detect : off, skip save traffic\n"); else { printf("Wifi detect : on, save traffic...\n"); select_cnt = 0; while(select_cnt < 20) { rc = sqlite3_open(traffic_saved_db, &db); if(rc == SQLITE_ERROR) printf("cannot open traffic_saved.db!\n"); memset(sql_cmd, 0, sizeof(sql_cmd)); sprintf(sql_cmd, "insert into traffic_saved values('%s', %d)", trafficnum_tmp, t); printf("sql_cmd : %s\n", sql_cmd); result = sqlite3_exec(db, sql_cmd, NULL, NULL, &errmsg); if(result == SQLITE_OK) { printf("insert traffic_saved.db successfully!\n"); sqlite3_free(errmsg); sqlite3_close(db); break; } else { printf("insert traffic_saved.db error : %s\n", errmsg); sqlite3_free(errmsg); sqlite3_close(db); sleep(1); select_cnt++; } } } } printf("heart_beat : complete!\n"); }
//Main function int main(int argc, char* argv[]) { //LIRC Variables struct lirc_config *config; //HTTP Variables char *host = "10.0.0.2"; char *http_request_format = "POST /php/remote_control_api.php HTTP/1.1\n" "Host: 10.0.0.2\n" "Content-Type: application/x-www-form-urlencoded\n" "Content-Length: 10\n\n" "function=%s\n"; char http_request[MAX_HTTP_REQUEST_LEN]; char http_response[MAX_HTTP_RESPONSE_LEN]; //Socket Variables int sockfd, error; struct addrinfo hints, *addrinfo_list, *addrinfo; //Misc Variables int valid_key = 0; struct timeval tv; gettimeofday(&tv, NULL); time_t start_time = tv.tv_sec, end_time, time_delay; //Outputs usage and exits if given more than one file path in arguments if (argc>2) { fprintf(stderr, "Usage: %s <config file>\n", argv[0]); return -1; } //Initializes LIRC and exits if unsuccessful, called at start of execution if (lirc_init("lirc",1)==-1) { fprintf(stderr, "lirc_init: failed to initialize lirc\n"); return -1; } //Clears hints structure and set appropriately for call to getaddrinfo() memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; //Gets the linked list of possible addrinfo structures if (error = getaddrinfo(host, PORT, &hints, &addrinfo_list) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error)); return -1; } //Iterate through linked list of possible addrinfo structures and attempts to create socket to connect to for (addrinfo = addrinfo_list; addrinfo != NULL; addrinfo = addrinfo->ai_next) { //Creates a socket if ((sockfd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol)) == -1) { continue; } //Connect to socket if (connect(sockfd, addrinfo->ai_addr, addrinfo->ai_addrlen) == -1) { close(sockfd); continue; } //Break out of loop if calls to socket() and connect() are both successful break; } //If none of the addrinfo structures in the linked list works, then exit program if (addrinfo == NULL) { fprintf(stderr, "failed to connect to %s\n", host); return -1; } fprintf(stdout, "connection to %s was successful\n\n", host); close(sockfd); //Read in configuration file from either argument or default path if (lirc_readconfig(argc==2 ? argv[1]:NULL, &config, NULL) == 0) { char *code; //Used to store the key code of the remote //Blocks the program until an IR signal is recieved from key press while (lirc_nextcode(&code)==0) { //Handle logic key press, if any if (code==NULL) continue; { gettimeofday(&tv, NULL); end_time = tv.tv_sec; printf("Starttime=%ld\tEndtime=%ld\n\n", start_time, end_time); if (end_time - start_time > DELAY) { //Clears request and response buffer memset(&http_request, 0, sizeof http_request); memset(&http_response, 0, sizeof http_response); if (strstr(code,"KEY_POWER")) { if ((valid_key = handle_key_power(http_request, http_request_format)) == -1) { return -1; } } else if (strstr(code,"KEY_STOP")) { if ((valid_key = handle_key_stop(http_request, http_request_format)) == -1) { return -1; } } else if (strstr(code,"KEY_PAUSE")) { if ((valid_key = handle_key_pause(http_request, http_request_format)) == -1) { return -1; } } else if (strstr(code,"KEY_PLAY")) { if ((valid_key = handle_key_play(http_request, http_request_format)) == -1) { return -1; } } else if (strstr(code,"KEY_REWIND")) { if ((valid_key = handle_key_rewind(http_request, http_request_format)) == -1) { return -1; } } else if (strstr(code,"KEY_FORWARD")) { if ((valid_key = handle_key_forward(http_request, http_request_format)) == -1) { return -1; } } if (valid_key) { //Creates socket if ((sockfd = socket(addrinfo->ai_family, addrinfo->ai_socktype, addrinfo->ai_protocol)) == -1) { return -1; } //Connect to socket if (connect(sockfd, addrinfo->ai_addr, addrinfo->ai_addrlen) == -1) { close(sockfd); return -1; } if (send_http_request(sockfd, http_request) == -1) { fprintf(stderr, "An error has occur while sending the HTTP request\n"); } else { fprintf(stdout, "HTTP request has been sent successfully.\n" "--------------------------------------------------\n" "%s\n\n", http_request); } if (receive_http_response(sockfd, http_response) == -1) { fprintf(stderr, "An error has occur while receiving the HTTP response\n"); } else { fprintf(stdout, "HTTP response has been received successfully.\n" "--------------------------------------------------\n" "%s\n\n", http_response); } close(sockfd); } gettimeofday(&tv, NULL); start_time = tv.tv_sec; } } free(code); //Free allocated memory for code after key press is handled } lirc_freeconfig(config); //Free allocated memory for configuration structure } //Deallocate memory from linked list of addrinfo structures freeaddrinfo(addrinfo_list); lirc_deinit(); //Deinitializes LIRC, called at end of program execution return 0; //EXIT_SUCCESS } //end of main()
upload_file(const char *filename, const char *type, sqlite3 *db) { FILE *stream = NULL; char sh_cmd[512] = {0}; char filename_all[100] = {0}; char filename_query[100] = {0}; char sql_cmd[100] = {0}, del_cmd[100] = {0}, request_url[200] = {0}; char buf[100] = {0}, uploadfile_folder[50] = {0}; char *errorMsg = NULL, *md5_value = NULL, *md5 = NULL; int rc = 0; ghttp_request *req_upload; char http_body[200] = {0}; memset(sh_cmd, 0, sizeof(sh_cmd)); memset(filename_all, 0, sizeof(filename_all)); memset(sql_cmd, 0, sizeof(sql_cmd)); if(strcmp(type, "1") == 0) { sprintf(sh_cmd, "curl -u user:user -T /ailvgo/www/userfile/pic/%s.jpg ftp://www.ailvgobox.com/userfile_manage/pic/%s.jpg", filename, filename); sprintf(filename_all, "/ailvgo/www/userfile/pic/%s.jpg", filename); strcpy(uploadfile_folder, "/userfile_manage/pic/"); sprintf(filename_query, "%s.jpg", filename); } if(strcmp(type, "2") == 0) { sprintf(sh_cmd, "curl -u user:user -T /ailvgo/www/userfile/audio/%s.mp3 ftp://www.ailvgobox.com/userfile_manage/audio/%s.mp3 ", filename, filename); sprintf(filename_all, "/ailvgo/www/userfile/audio/%s.mp3", filename); strcpy(uploadfile_folder, "/userfile_manage/audio/"); sprintf(filename_query, "%s.mp3", filename); } if(strcmp(type, "3") == 0) { sprintf(sh_cmd, "curl -u user:user -T /ailvgo/www/userfile/video/%s.mp4 ftp://www.ailvgobox.com/userfile_manage/video/%s.mp4 ", filename, filename); sprintf(filename_all, "/ailvgo/www/userfile/video/%s.mp4", filename); strcpy(uploadfile_folder, "/userfile_manage/video/"); sprintf(filename_query, "%s.mp4", filename); } printf("sh_md : %s\n", sh_cmd); sprintf(sql_cmd, "update userfile_info set upload=\"1\" where filename=\"%s\"", filename); printf("sql_cmd : %s\n", sql_cmd); if(access(filename_all, W_OK) == -1) { memset(del_cmd, 0, sizeof(del_cmd)); sprintf(del_cmd, "delete from userfile_info where filename=\"%s\"", filename); printf("del_cmd : %s\n", del_cmd); printf("result : upload file not exist\n"); sqlite3_exec(db, del_cmd, NULL, NULL, &errorMsg); if (errorMsg) printf("errorMsg : %s\n", errorMsg); return 0; } else { md5_value = md5_file(filename_all); sprintf(request_url, "http://www.ailvgobox.com/box_manage_2/file_query_1.php?file_name=%s&folder=%s", filename_query, uploadfile_folder); printf("request_url : %s\n", request_url); req_upload = ghttp_request_new(); strcpy(http_body, send_http_request(req_upload, request_url)); ghttp_request_destroy(req_upload); printf("http_body : %s\n", http_body); cJSON *node; if(strlen(http_body) == 0) { printf("HTTP failure!\n"); } else { if(strcmp(http_body, "null") == 0) printf("server has no file!\n"); else { node = cJSON_Parse(http_body); cJSON *file_query = cJSON_GetObjectItem(node, "file_query"); if(file_query) { char *md5 = cJSON_GetObjectItem(file_query, "md5")->valuestring; printf("md5_value - md5 : %s - %s", md5_value, md5); if(strcmp(md5_value, md5) == 0) { printf("update databse...\n"); sqlite3_exec(db, sql_cmd, NULL, NULL, &errorMsg); if(errorMsg) printf("errorMsg : %s\n", errorMsg); return 1; } } } } } printf("upload cmd : %s\n", sh_cmd); sleep(2); printf("upload start...\n"); system(sh_cmd); sleep(2); return 1; }
static HRESULT HttpProtocol_open_request(Protocol *prot, IUri *uri, DWORD request_flags, HINTERNET internet_session, IInternetBindInfo *bind_info) { HttpProtocol *This = impl_from_Protocol(prot); WCHAR *addl_header = NULL, *post_cookie = NULL, *rootdoc_url = NULL; IServiceProvider *service_provider = NULL; IHttpNegotiate2 *http_negotiate2 = NULL; BSTR url, host, user, pass, path; LPOLESTR accept_mimes[257]; const WCHAR **accept_types; BYTE security_id[512]; DWORD len, port, flags; ULONG num, error; BOOL res, b; HRESULT hres; static const WCHAR wszBindVerb[BINDVERB_CUSTOM][5] = {{'G','E','T',0}, {'P','O','S','T',0}, {'P','U','T',0}}; hres = IUri_GetPort(uri, &port); if(FAILED(hres)) return hres; hres = IUri_GetHost(uri, &host); if(FAILED(hres)) return hres; hres = IUri_GetUserName(uri, &user); if(SUCCEEDED(hres)) { hres = IUri_GetPassword(uri, &pass); if(SUCCEEDED(hres)) { This->base.connection = InternetConnectW(internet_session, host, port, user, pass, INTERNET_SERVICE_HTTP, This->https ? INTERNET_FLAG_SECURE : 0, (DWORD_PTR)&This->base); SysFreeString(pass); } SysFreeString(user); } SysFreeString(host); if(FAILED(hres)) return hres; if(!This->base.connection) { WARN("InternetConnect failed: %d\n", GetLastError()); return INET_E_CANNOT_CONNECT; } num = 0; hres = IInternetBindInfo_GetBindString(bind_info, BINDSTRING_ROOTDOC_URL, &rootdoc_url, 1, &num); if(hres == S_OK && num) { FIXME("Use root doc URL %s\n", debugstr_w(rootdoc_url)); CoTaskMemFree(rootdoc_url); } num = sizeof(accept_mimes)/sizeof(accept_mimes[0])-1; hres = IInternetBindInfo_GetBindString(bind_info, BINDSTRING_ACCEPT_MIMES, accept_mimes, num, &num); if(hres == INET_E_USE_DEFAULT_SETTING) { static const WCHAR default_accept_mimeW[] = {'*','/','*',0}; static const WCHAR *default_accept_mimes[] = {default_accept_mimeW, NULL}; accept_types = default_accept_mimes; num = 0; }else if(hres == S_OK) { accept_types = (const WCHAR**)accept_mimes; }else { WARN("GetBindString BINDSTRING_ACCEPT_MIMES failed: %08x\n", hres); return INET_E_NO_VALID_MEDIA; } accept_mimes[num] = 0; if(This->https) request_flags |= INTERNET_FLAG_SECURE; hres = IUri_GetPathAndQuery(uri, &path); if(SUCCEEDED(hres)) { This->base.request = HttpOpenRequestW(This->base.connection, This->base.bind_info.dwBindVerb < BINDVERB_CUSTOM ? wszBindVerb[This->base.bind_info.dwBindVerb] : This->base.bind_info.szCustomVerb, path, NULL, NULL, accept_types, request_flags, (DWORD_PTR)&This->base); SysFreeString(path); } while(num--) CoTaskMemFree(accept_mimes[num]); if(FAILED(hres)) return hres; if (!This->base.request) { WARN("HttpOpenRequest failed: %d\n", GetLastError()); return INET_E_RESOURCE_NOT_FOUND; } hres = IInternetProtocolSink_QueryInterface(This->base.protocol_sink, &IID_IServiceProvider, (void **)&service_provider); if (hres != S_OK) { WARN("IInternetProtocolSink_QueryInterface IID_IServiceProvider failed: %08x\n", hres); return hres; } hres = IServiceProvider_QueryService(service_provider, &IID_IHttpNegotiate, &IID_IHttpNegotiate, (void **)&This->http_negotiate); if (hres != S_OK) { WARN("IServiceProvider_QueryService IID_IHttpNegotiate failed: %08x\n", hres); IServiceProvider_Release(service_provider); return hres; } hres = IUri_GetAbsoluteUri(uri, &url); if(FAILED(hres)) { IServiceProvider_Release(service_provider); return hres; } hres = IHttpNegotiate_BeginningTransaction(This->http_negotiate, url, default_headersW, 0, &addl_header); SysFreeString(url); if(hres != S_OK) { WARN("IHttpNegotiate_BeginningTransaction failed: %08x\n", hres); IServiceProvider_Release(service_provider); return hres; } len = addl_header ? strlenW(addl_header) : 0; This->full_header = heap_alloc(len*sizeof(WCHAR)+sizeof(default_headersW)); if(!This->full_header) { IServiceProvider_Release(service_provider); return E_OUTOFMEMORY; } if(len) memcpy(This->full_header, addl_header, len*sizeof(WCHAR)); CoTaskMemFree(addl_header); memcpy(This->full_header+len, default_headersW, sizeof(default_headersW)); hres = IServiceProvider_QueryService(service_provider, &IID_IHttpNegotiate2, &IID_IHttpNegotiate2, (void **)&http_negotiate2); IServiceProvider_Release(service_provider); if(hres != S_OK) { WARN("IServiceProvider_QueryService IID_IHttpNegotiate2 failed: %08x\n", hres); /* No goto done as per native */ }else { len = sizeof(security_id)/sizeof(security_id[0]); hres = IHttpNegotiate2_GetRootSecurityId(http_negotiate2, security_id, &len, 0); IHttpNegotiate2_Release(http_negotiate2); if (hres != S_OK) WARN("IHttpNegotiate2_GetRootSecurityId failed: %08x\n", hres); } /* FIXME: Handle security_id. Native calls undocumented function IsHostInProxyBypassList. */ if(This->base.bind_info.dwBindVerb == BINDVERB_POST) { num = 0; hres = IInternetBindInfo_GetBindString(bind_info, BINDSTRING_POST_COOKIE, &post_cookie, 1, &num); if(hres == S_OK && num) { if(!InternetSetOptionW(This->base.request, INTERNET_OPTION_SECONDARY_CACHE_KEY, post_cookie, lstrlenW(post_cookie))) WARN("InternetSetOption INTERNET_OPTION_SECONDARY_CACHE_KEY failed: %d\n", GetLastError()); CoTaskMemFree(post_cookie); } } flags = INTERNET_ERROR_MASK_COMBINED_SEC_CERT; res = InternetSetOptionW(This->base.request, INTERNET_OPTION_ERROR_MASK, &flags, sizeof(flags)); if(!res) WARN("InternetSetOption(INTERNET_OPTION_ERROR_MASK) failed: %u\n", GetLastError()); b = TRUE; res = InternetSetOptionW(This->base.request, INTERNET_OPTION_HTTP_DECODING, &b, sizeof(b)); if(!res) WARN("InternetSetOption(INTERNET_OPTION_HTTP_DECODING) failed: %u\n", GetLastError()); do { error = send_http_request(This); switch(error) { case ERROR_IO_PENDING: return S_OK; case ERROR_SUCCESS: /* * If sending response ended synchronously, it means that we have the whole data * available locally (most likely in cache). */ return protocol_syncbinding(&This->base); default: hres = handle_http_error(This, error); } } while(hres == RPC_E_RETRY); WARN("HttpSendRequest failed: %d\n", error); return hres; }
int main() { printf("\n********************************\n"); printf("box_conf_change : start\n"); printf("********************************\n"); char url[1024] = {0}; ghttp_request *req; char http_body[1024] = {0}; sqlite3 *db = NULL; sqlite3_stmt *ppstmt = NULL; int rc = 0; char sql_cmd[100] = {0}; char *errorMsg = NULL; const char *box_id = NULL; char box_id_tmp[10] = {0}; int db_cnt = 0; while(db_cnt < 20) { rc = sqlite3_open(box_db, &db); if(rc == SQLITE_ERROR) printf("open box.db failed"); ppstmt = NULL; memset(sql_cmd, 0, sizeof(sql_cmd)); strcpy(sql_cmd, "select box_id from box_info"); sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); rc = sqlite3_step(ppstmt); if(rc == SQLITE_ROW) { box_id = sqlite3_column_text(ppstmt, 0); strcpy(box_id_tmp, box_id); printf("box_id : %s\n", box_id_tmp); sqlite3_finalize(ppstmt); sqlite3_close(db); break; } else { printf("select box_id failure!\n"); sqlite3_finalize(ppstmt); sqlite3_close(db); sleep(1); db_cnt++; } } printf("----------------send http request-------------\n"); sprintf(url, "http://www.ailvgobox.com/box_manage_2/box_conf_change_1.php?box_id=%s", box_id_tmp); printf("request_url : %s\n",url); req = ghttp_request_new(); strcpy(http_body, send_http_request(req, url)); ghttp_request_destroy(req); printf("http_body : %s\n", http_body); printf("length of http_body : %d\n", strlen(http_body)); cJSON *node; if(strlen(http_body) <= 2) printf("HTTP failure!\n"); else { printf("HTTP success!\n"); if(strcmp(http_body, "null") == 0) printf("http_body : null, no box_conf_change!\n"); else { node = cJSON_Parse(http_body); ParseJSON(node); } } printf("box_conf_chanage : complete!\n"); if(change_flag == 1) { printf("reboot due to conf change!\n"); sleep(5); system("reboot"); } }
bool AdafruitTwitter::checkDirectMessage(uint64_t since_id, uint64_t max_id) { // False if setDirectMessageRecvCallback() is not called VERIFY(_dm_rx_callback); #if TWITTER_DEBUG // test code since_id = 240136858829479935ULL; #endif // char const count_str[] = { '0' + count , 0}; char sinceid_str[64]; sprintf(sinceid_str, "%llu", since_id); char maxid_str[64]; sprintf(maxid_str, "%llu", max_id); // Data contents: ASSUME key are already in urlencoded char const* httpdata[][2] = { { "count" , "1" }, { "since_id" , sinceid_str }, { "max_id " , maxid_str }, }; uint8_t data_count = arrcount(httpdata); if ( max_id == 0 ) data_count--; // Send HTTP request AdafruitHTTP http; send_http_request(http, HTTP_METHOD_GET, TWITTER_JSON_DIRECTMESSAGE, httpdata, data_count); // Process HTTP response TwitterDM dm; http.respParseHeader(); // Content Length is too short for a new message --> skip // Only process response if message is arrived if ( http.respContentLength() > 100 ) { char buffer[256]; while ( http.readUntil(',', buffer, sizeof(buffer)) ) { char* key = buffer; char* value = strchr(buffer, ':'); if ( value == NULL ) continue; *value++ = 0; // separate key & value with null-terminator // Both interested (key and value) are quoted, discard them key++; key[strlen(key)-1] = 0; value++; value[strlen(value)-1] = 0; // Serial.print(key); Serial.print('='); Serial.println(value); if ( (dm.id == 0) && !strcmp("id_str", key) ) { dm.id = strtoull(value, NULL, 10); } if ( (dm.text == NULL) && !strcmp("text", key) ) { dm.text = (char*) malloc_named("Twitter DM", strlen(value) + 1); VERIFY(dm.text != NULL); strcpy(dm.text, value); } if ( (dm.sender == NULL) && !strcmp("screen_name", key) ) { dm.sender = (char*) malloc_named("Twitter DM", strlen(value) + 1); VERIFY( dm.sender != NULL ); strcpy(dm.sender, value); } if ( !strcmp("created_at", key) ) { // message time is likely the last time field if ( dm.created_at == NULL ) { dm.created_at = (char*) malloc_named("Twitter DM", strlen(value) + 10); VERIFY( dm.created_at != NULL ); } strcpy(dm.created_at, value); } } } http.stop(); // There is new message if (dm.id) { // update last sinceid _dm_last_sinceid = dm.id; // Fire callback _dm_rx_callback(dm); // clean up DM resource if (dm.sender ) free_named("Twitter DM", dm.sender); if (dm.text ) free_named("Twitter DM", dm.text); if (dm.created_at ) free_named("Twitter DM", dm.created_at); } return true; }