Exemplo n.º 1
0
int main( void ) {
    FILE *fp;
    
    long length;

    http_t *http = malloc( sizeof( http_t ) );
    http->data = NULL;

    dispatch( getenv( "QUERY_STRING" ), http );

    if( strcmp( http->data, "" ) != 0 ) {
        sendresponse( http );
    }

    return EXIT_SUCCESS;
}
Exemplo n.º 2
0
/**
 *
 * Goes over the table of records and cleans up those that have not received a
 * message in the last TIMEOUT seconds. For each of those records, it calls
 * sendresponse() to transmit a response to the corresponding client.
 *
 * Returns,
 *  0, on success
 * -1, on failure
 *
 */
int removeoldrecords(struct clientrec *clientp, int sockfd) {
  int i;
  struct clientrec client;
  struct timeval curtime;

  assert(clientp);

  if (gettimeofday(&curtime, NULL) < 0) {
    return -1;
  }

  for (i = 0; i < CLIARRAYSIZE; i++) {
    client = clientp[i];
    if (client.full && curtime.tv_sec - client.lastrecvd.tv_sec > TIMEOUT) {
      sendresponse(sockfd, clientp + i, PKT_RESPONSE);
      cleanrecord(clientp + i);
    }
  }
  return 0;
}  // removeoldrecords()
Exemplo n.º 3
0
int process_request(char *read_request,char *site,int newsockfd)
{

     FILE *fpread;
     
     struct timeval start_request_process;
     struct timeval finish_request_process;
     
    // request_count++;

     gettimeofday(&start_request_process,NULL);
    // printf(ctime(&start_request_process));

	 int majversion,minversion;
     http_method_t http_method;
     http_request_t http_request;
     http_response_t http_response;
     http_status_t http_status;

	char *verb;
    verb=malloc(MEMORYSIZE);

    char path[MEMORYSIZE];
    memset(path,0,sizeof(path));

    char *version;
    version=malloc(MEMORYSIZE);

	char *header_name,*header_value;
	header_name=malloc(MEMORYSIZE);
	header_value=malloc(MEMORYSIZE);
	
	sscanf(read_request,"%s %s %s",verb,path,version);
	sscanf(version,"HTTP/%d.%d",&http_request.major_version,&http_request.minor_version);	
    
  /*  if(strcmp(path,"/favicon.ico")==0)
        return 0;
    */
	http_method=parseverb(verb);

    process_path(path,site,&http_request);


	int headercount=0,parseheaderval=0,headerline_length=0;
	char *read_header;
	read_header=malloc(MEMORYSIZE);

	read_request=read_request+(strlen(verb)+strlen(path)+strlen(version)+4);
	/* Saving request headers */
	while(headercount!=MAX_HEADERS)
	{
		if(*(read_request+0)==13 && *(read_request+1)==10)
			break;

		sscanf(read_request,"%[^\n]",read_header);
        headerline_length=strlen(read_header);
		parseheaderval= preparerequestheader(read_header,headercount,&http_request);
		headercount++;
		memset(read_header,'0',strlen(read_header));
		read_request=read_request+headerline_length+1;
	}

	http_request.method=http_method;
    http_request.header_count=headercount;

	if(http_request.method!=HTTP_METHOD_GET)
	{
		http_status.code=HTTP_STATUS_LOOKUP[POSITION_NOTIMPLEMENTED].code;
        http_status.reason=HTTP_STATUS_LOOKUP[POSITION_NOTIMPLEMENTED].reason;
	}
	else if(http_request.method==HTTP_METHOD_GET)
    {
              
        int filecheck=check_file(http_request.uri);
		if(filecheck==0)
        {
            http_status.code=HTTP_STATUS_LOOKUP[POSITION_NOTFOUND].code;
            http_status.reason=HTTP_STATUS_LOOKUP[POSITION_NOTFOUND].reason;
	       
        }
        else
        {
		    http_status.code=HTTP_STATUS_LOOKUP[POSITION_OK].code;
            http_status.reason=HTTP_STATUS_LOOKUP[POSITION_OK].reason;
		   
        }
		
	}
    
    buildresponse(&http_request,&http_status,&http_response);
	sendresponse(newsockfd,http_response,http_request.uri);
    
    gettimeofday(&finish_request_process,NULL);
   // printf(ctime(&finish_request_process));

    pthread_mutex_lock(&mtx_processtime);
    process_times[ind]=finish_request_process.tv_usec - start_request_process.tv_usec;
    ind++;
    pthread_mutex_unlock(&mtx_processtime);
    

    reset_reponse_headers(&http_response);
    free(read_header);
	free(header_name);
	free(header_value);
	free(version);
	
	free(verb);
    return 0;
}
Exemplo n.º 4
0
int processpacket(int sockfd, struct clientrec *clientp, char *msgp,
                  struct sockaddr_in cliaddr) {
  unsigned char index;
  struct clientrec *cp;
  struct timeval tim;
  struct packet *clipacketp;
  char buf[STRBUFSIZE];
  int ptype, i, burstsize;

  assert(msgp);
  assert(clientp);

  index = ntohl(cliaddr.sin_addr.s_addr) & 0x000000FF;
  clipacketp = (struct packet *) msgp;
  ptype = ntohl(clipacketp->ptype);

  if (ptype != PKT_DATA && ptype != PKT_REQUEST) {
    cp = (struct clientrec *) malloc(sizeof(struct clientrec));
    assert(cp);
    cp->addr = ntohl(cliaddr.sin_addr.s_addr);
    cp->port = ntohs(cliaddr.sin_port);
    cp->burstsize = 0;
    cp->pktrecvd = 0;
    cp->seq = 0;
    cp->pktsize = sizeof(struct packet);
    sendresponse(sockfd, cp, PKT_ERROR);
    logmsg("Malformed packet", NULL);
    free(cp);
    return -1;
  }

  if (ptype == PKT_REQUEST) {
    cp = (struct clientrec *) malloc(sizeof(struct clientrec));
    assert(cp);
    burstsize = ntohl(clipacketp->burstsize);

    cp->addr = ntohl(cliaddr.sin_addr.s_addr);
    cp->port = ntohs(cliaddr.sin_port);
    cp->pktsize = ntohl(clipacketp->pktsize);
    cp->burstsize = burstsize;
    cp->seq = 0;

    if (cp->pktsize < sizeof(struct packet)) {
      return -1;
    }

    for (i = 0; i < burstsize; i++) {
      cp->pktrecvd = i;
      sendresponse(sockfd, cp, PKT_DATA);
    }
    free(cp);
    return 0;
  }

  snprintf(buf, sizeof(buf), "s:%d b:%d p:%d", ntohl(clipacketp->seq),
           ntohl(clipacketp->burstsize), ntohl(clipacketp->pktnum));
  logmsg("Data packet", buf);

  cp = clientp + index;

  if (cp->full) {
    // record already exists
    if (cp->addr == ntohl(cliaddr.sin_addr.s_addr) &&
        cp->port == ntohs(cliaddr.sin_port) &&
        cp->seq == ntohl(clipacketp->seq)) {
      cp->pktrecvd++;
    } else {
      // record is used by a different client or
      // client sent a different sequence number
      sendresponse(sockfd, cp, PKT_ERROR);
      return -1;
    }
  } else {
    // empty record
    cp->full = 1;
    cp->addr = ntohl(cliaddr.sin_addr.s_addr);
    cp->port = ntohs(cliaddr.sin_port);
    cp->burstsize = ntohl(clipacketp->burstsize);
    cp->pktsize = ntohl(clipacketp->pktsize);
    cp->pktrecvd = 1;
    cp->seq = ntohl(clipacketp->seq);
  }

  if (gettimeofday(&tim, NULL) < 0)  {
    return -1;
  }
  cp->lastrecvd.tv_sec = tim.tv_sec;
  cp->lastrecvd.tv_usec = tim.tv_usec;

  if (cp->pktrecvd == cp->burstsize) {
    // send a response and clean the record
    sendresponse(sockfd, cp, PKT_RESPONSE);
    cleanrecord(cp);
  }

  return 0;
}  // processpacket()
Exemplo n.º 5
0
/** send out response according to different http request. 
a typical workflow of auto case would be
/check_server_status						(by com-module)
/init_test									(by com-module)
/set_testcase								(by com-module)
/check_server 								(by widget)
/init_session_id?session_id=2033			(by widget)
/auto_test_task?session_id=2033				(by widget)
/check_execution_progress?session_id=2033	(by widget)
/ask_next_step?session_id=2033				(by widget)
/commit_result 								(by widget)
/auto_test_task?session_id=2033				(by widget)
/manual_cases 								(by widget)
/generate_xml 								(by widget)
/check_server_status 						(by com-module)
/get_test_result 							(by com-module)

a typical workflow of manual case would be
/check_server_status						(by com-module)
/init_test									(by com-module)
/set_testcase								(by com-module)
/check_server 								(by widget)
/init_session_id?session_id=2033			(by widget)
/auto_test_task?session_id=2033				(by widget)
/manual_cases 								(by widget)
/check_server_status 						(by com-module)
/commit_manual_result 						(by widget)
...
/check_server_status 						(by com-module)
/commit_manual_result 						(by widget)
/generate_xml 								(by widget)
/get_test_result 							(by com-module)

**/
void HttpServer::processpost(int s, struct HttpRequest *prequest)
{
	prequest->prefix = "application/json";
	string json_str = "{\"OK\":1}";

#if defined(__WIN32__) || defined(__WIN64__)
	cout << "prequest->path is:" << prequest->path << endl;
	cout << "prequest->content is:" << prequest->content << endl;
#else
	if (g_show_log) {
		DBG_ONLY("prequest->path is:" << prequest->path);
		DBG_ONLY("prequest->content is:" << prequest->content);
	}
#endif

	if (prequest->path.find("/init_test") != string::npos) {	// invoke by com-module to init some para for test
		set_cl_timeout(0);
		Json::Reader reader;
		Json::Value value;
		if (g_show_log)
			DBG_ONLY("[ init the test suite ]");

		bool parsed = reader.parse(prequest->content, value);
		if (parsed) {
			g_launcher = value["launcher"].asString();
            g_platform = value["platform"].asString();

			m_suite_name = value["suite_name"].asString();
			if (g_launcher == "wrt-launcher") {
				g_run_wiget = true;
				m_suite_id = value["suite_id"].asString();

				g_launch_cmd = g_launcher + " -s " + m_suite_id;
				g_kill_cmd = g_launcher + " -k " + m_suite_id;
				killAllWidget();
			} else if (g_platform == "androidmobile") {	// xwalk on android
				g_run_wiget = false;
				//am start -n org.xwalk.tct-2dtransforms-css3-tests/.tct-2dtransforms-css3-testsActivity
				//g_launch_cmd = "am start -n org.xwalk." + m_suite_name + "/." + m_suite_name + "Activity";
				//g_kill_cmd = "am force-stop org.xwalk." + m_suite_name;
				g_launch_cmd = "";
				g_kill_cmd = "";
			} else if (g_platform == "windowshttp"){ // xwalk on windows
				g_run_wiget = true;
				m_suite_id = value["suite_id"].asString();
				//g_launch_cmd = "C:\\\"Program Files\"\\"+m_suite_id + "\\" + g_launcher;
				g_launch_cmd = "notepad C:\\\"Program Files\"\\" + m_suite_id + "\\" + m_suite_id + "\\manifest.json";
				g_kill_cmd = "";
				sleep(1);
		    }else {
#if defined(__WIN32__) || defined(__WIN64__)
				g_launch_cmd = "start /b " + g_launcher;
				g_kill_cmd = "";
#else
				g_launch_cmd = g_launcher + " &";
				if (g_launcher.find("XWalkLauncher") != string::npos)	//kill xwalk
					g_kill_cmd = "pkill XWalkLauncher";
				//g_kill_cmd = "ps ax | grep xwalk | grep -v testkit-lite | grep -v grep | awk '{print $1F}' | xargs kill -9;";
				else
					g_kill_cmd = "";	// not kill browser
#endif
				m_suite_id = value["suite_id"].asString();
				g_run_wiget = true;
				//wait for the index window.close, otherwise will occur bind aleady error
				sleep(1);
			}
		} else {
			if (g_show_log) {
				DBG_ONLY
				    ("error while parse para from com-module, can't start test");
				DBG_ONLY(prequest->content);
			}
			json_str = "{\"Error\":\"parse error\"}";
		}
	} else if (prequest->path.find("/execute_cmd") != string::npos){  //Only work on Windows! invoke by com-module for executing command on windows platform
		if (g_show_log){
			DBG_ONLY("[ execute command: ]" << endl);
			DBG_ONLY(prequest->content);
		}
		Json::Reader reader;
		Json::Value value;

		bool parsed = reader.parse(prequest->content, value);
		string json_cmd = "";
		if (parsed){
			json_cmd = value["cmd"].asString();
		}

		std::vector < string > outputs;
		string cmd = json_cmd;
		cout << "[ command: ]" << cmd << endl;
		run_cmd(cmd, "", &outputs);
		for (unsigned int i = 0; i < outputs.size(); i++){
			cout << "[ output: ]" << outputs[i] << endl;
		}
#if defined(__WIN32__) || defined(__WIN64__)
	} else if (prequest->path.find("/powershell_install") != string::npos){
		//Only work with Windows PowerShell. JSON {suite: suitename, host: hostip, file:suitefile_file_path}
		Json::Reader reader;
		Json::Value value;

		bool parsed = reader.parse(prequest->content, value);
		string json_suite = "";
		string json_file = "";
		string json_host = "";
		if (parsed) {
			json_suite = value["suite"].asString();
			json_file = value["file"].asString();
			json_host = value["host"].asString();
		}

		string ps_cmd = "powershell -file c:\\stub\\powershell\\download.ps1 ";
		ps_cmd = ps_cmd + json_suite + " " + json_file + " " + json_host;
		cout << "[ command: ]" << ps_cmd << endl;
		int ret = run_cmd_return_code(ps_cmd);
		if(ret != 1){
			if (ret == -1)
				json_str = "{\"Error\":\"Fail to install "+ json_suite +"\"}";
			else if (ret == -2)
				json_str = "{\"Error\":\"Fail to download "+ json_file +"\"}";
			else if (ret == -5)
				json_str = "{\"Error\":\"Fail to execute "+ json_file +". Popen return null\"}";
			else
				json_str = "{\"Error\":\"Unknown script errors.\"}";
		}
	} else if (prequest->path.find("/powershell_uninstall") != string::npos){
		//Only work with Windows PowerShell. JSON {suite: suitename}
		Json::Reader reader;
		Json::Value value;

		bool parsed = reader.parse(prequest->content, value);
		string json_suite = "";
		if (parsed) {
			json_suite = value["suite"].asString();
		}

		string ps_cmd = "powershell -file c:\\stub\\powershell\\uninstall.ps1 ";
		ps_cmd = ps_cmd + json_suite;
		cout << "[ command: ]" << ps_cmd << endl;
		int ret = run_cmd_return_code(ps_cmd);
		if(ret != 1){
			json_str = "{\"Error\":\"Fail to uninstall.\"}";
		}
	} else if (prequest->path.find("/powershell_exitcode") != string::npos){
		string ps_cmd = "powershell -file c:\\stub\\powershell\\exitcode.ps1 0";
		cout << "[ command: ]" << ps_cmd << endl;
		int ret = run_cmd_return_code(ps_cmd);
		cout << "[ return: ]" << ret << endl;
#endif
	} else if (prequest->path.find("/execute_async_cmd") != string::npos) {
		Json::Reader reader;
		Json::Value value;

		bool parsed = reader.parse(prequest->content, value);
		string json_cmd = "";
		if (parsed) {
			json_cmd = value["cmd"].asString();
		}
		string cmd = json_cmd;
		run_cmd_async(cmd);
    }else if (prequest->path.find("/set_testcase") != string::npos) {	// invoke by com-module to send testcase data
		m_block_finished = false;
		m_set_finished = false;
		m_timeout_count = 0;
		m_server_checked = false;
		if (g_show_log)
			DBG_ONLY("[ set test cases ]");
		parse_json_str(prequest->content);

		set_timer(20);	// set timer here incase widget hang.
		m_check_times = 0;

		m_block_case_index = 0;
		if (m_current_block_index == 1)
			m_total_case_index = 0;
	} else if (prequest->path == "/check_server") {	// invoke by index.html to find server running or not
		set_cl_timeout(0);
		m_server_checked = true;
		m_check_times = 0;
		cancel_time_check();
		if (g_show_log)
			DBG_ONLY
			    ("[ checking server, and found the server is running ]");
	} else if (prequest->path == "/check_server_status") {	// invoke by com-module to get server status
		Json::Value status;
		status["block_finished"] = m_block_finished ? 1 : 0;
		status["finished"] = m_set_finished ? 1 : 0;
		if (m_exeType == "auto" && check_cl_timeout()) {
			status["error_code"] = 2;
			status["finished"] = 1;	//finish current set if widget is timeout
		} else if (m_failto_launch > m_max_fail_launch) {
			status["error_code"] = 2;
			status["finished"] = 1;	// finish current set if can't launch widget
		} else if (g_error_code > 0) {
			status["error_code"] = g_error_code;
			g_error_code = 0;
		}

		pthread_mutex_lock(&result_mutex);
		char count[8];
		memset(count, 0, 8);
		sprintf(count, "%d", m_result.size());
		status["count"] = count;
		status["cases"] = m_result;
		m_result.clear();
		pthread_mutex_unlock(&result_mutex);

		json_str = status.toStyledString();

		if (!m_server_checked) {
			if (g_show_log)
				DBG_ONLY
				    ("wait for widget check_server, please check on device."
				     << endl);
		}
		if (m_totalBlocks > 0) {
			if (g_show_log)
				DBG_ONLY("group: " << m_current_block_index <<
					 "/" << m_totalBlocks <<
					 ", total case: " << m_total_case_index
					 << "/" << m_totalcaseCount <<
					 ", group case: " << m_block_case_index
					 << "/" << m_block_case_count <<
					 ", m_timeout_count:" <<
					 m_timeout_count);
			if (m_exeType != "auto") {
				if (g_show_log)
					DBG_ONLY
					    ("manual cases. please check on device."
					     << endl);
			}
		}
	} else if (prequest->path == "/shut_down_server") {
		if (g_run_wiget == true)
			killAllWidget();	// kill all widget when shutdown server
		gIsRun = 0;
	} else if (prequest->path.find("/init_session_id") != string::npos) {	// invoke by index.html to record a session id
		set_cl_timeout(0);
		int index = prequest->path.find('=');
		if (index != -1) {
			m_running_session = prequest->path.substr(index + 1);
			if (g_show_log)
				DBG_ONLY("[ sessionID: " << m_running_session <<
					 " is gotten from the client ]");
		} else {
			if (g_show_log)
				DBG_ONLY("[ invalid session id ]");
		}
	} else if (prequest->path.find("/ask_next_step") != string::npos) {	// invoke by index.html to check whether there are more cases
		set_cl_timeout(0);
		if (m_block_finished || m_set_finished)
			json_str = "{\"step\":\"stop\"}";
		else
			json_str = "{\"step\":\"continue\"}";

		m_timeout_count = 0;	// reset the timeout count
	} else if (prequest->path.find("/auto_test_task") != string::npos) {	// invoke by index.html to get current auto case
		set_cl_timeout(0);
		if (m_test_cases == NULL) {
			json_str = "{\"Error\":\"no case\"}";
		} else if (m_exeType != "auto") {
			json_str = "{\"none\":0}";
		} else {
			string error_type = "";
			bool find_tc =
			    get_auto_case(prequest->content, &error_type);
			if (find_tc == false) {
				json_str = "{\"" + error_type + "\":0}";
			} else {
				json_str =
				    m_test_cases[m_block_case_index].to_json().
				    toStyledString();
			}
		}
	} else if (prequest->path.find("/manual_cases") != string::npos) {	// invoke by index.html to get all manual cases
		cancel_time_check();	// should not timeout in manual mode
		if (!m_test_cases) {
			json_str = "{\"Error\":\"no case\"}";
		} else if (m_exeType == "auto") {
			json_str = "{\"none\":0}";
		} else {
			Json::Value arrayObj;
			for (int i = 0; i < m_block_case_count; i++)
				arrayObj.append(m_test_cases[i].to_json());

			json_str = arrayObj.toStyledString();
			set_timer(60);	// check every 60 seconds to make sure widget alive when run manual cases.
		}
	} else if (prequest->path.find("/commit_manual_result") != string::npos) {	// invoke by index.html to provide result of a manual case.
		set_cl_timeout(0);
		if ((prequest->content.length() == 0) || (!m_test_cases)) {
			json_str = "{\"Error\":\"no manual result\"}";
		} else {
			find_id(splitContent(prequest->content), false);	// will set index in find_id
		}
	} else if (prequest->path.find("/check_execution_progress") != string::npos) {	//invoke by index.html to get test result of last auto case
		set_cl_timeout(0);
		char *total_count = new char[16];
		sprintf(total_count, "%d", m_totalcaseCount);
		char *current_index = new char[16];
		sprintf(current_index, "%d", m_total_case_index + 1);

		string count_str(total_count);
		string index_str(current_index);
		json_str =
		    "{\"total\":" + count_str + ",\"current\":" + index_str +
		    ",\"last_test_result\":\"" + m_last_auto_result + "\"}";

		delete[]total_count;
		delete[]current_index;
	}
	//generate_xml:from index_html, a maually block finished when click done in widget, or no manual cases anymore(when run auto block)
	else if (prequest->path == "/generate_xml") {
		set_cl_timeout(0);
		if (m_exeType != "auto") {
			cancel_time_check();
			m_block_finished = true;
			if (m_current_block_index == m_totalBlocks)
				m_set_finished = true;
		}
	}
	//from com module,when m_set_finished is true
	else if (prequest->path == "/get_test_result") {
		cancel_time_check();
		if (!m_test_cases) {
			json_str = "{\"Error\":\"no case\"}";
		} else {
			Json::Value root;
			root["count"] = "0";
			root["cases"] = m_result;	// m_result will always be empty here
			json_str = root.toStyledString();
		}
	}
	// index.html invoke this with id and result of an auto case, auto case commit result. 
	// we need find correct test case by id, and record test result to it.
	else if (prequest->path == "/commit_result") {
		set_cl_timeout(0);
		if ((prequest->content.length() == 0) || (!m_test_cases)) {
			json_str = "{\"Error\":\"no result\"}";
			m_last_auto_result = "BLOCK";
		} else {
			Json::Value paras = splitContent(prequest->content);
			if (m_running_session == paras["session_id"].asString()) {
				find_id(paras, true);
			}
		}
	} else if (prequest->path == "/set_capability") {	// by com-module to send capability data
		Json::Reader reader;

		reader.parse(prequest->content, m_capability);
	} else if (prequest->path.find("/capability") != string::npos) {	// by test suite. only one query parameter each time
		json_str = "{\"support\":0}";

		Json::Value paras = splitContent(prequest->content);
		string value = paras["value"].asString();
		string name = paras["name"].asString();
		for (unsigned int i = 0; i < name.size(); i++)
			name[i] = tolower(name[i]);

		if (m_capability[name].isBool()) {	// for bool value, omit the value part
			json_str = "{\"support\":1}";
		} else if (m_capability[name].isInt()) {
			if (m_capability[name].asInt() == atoi(value.c_str()))
				json_str = "{\"support\":1}";
		} else if (m_capability[name].isString()) {
			if (m_capability[name].asString() == value)
				json_str = "{\"support\":1}";
		}
	} else {
		json_str = "{\"Error\":\"unknown request\"}";
	}

	if (json_str != "")
		sendresponse(s, 200, prequest, json_str);

#if defined(__WIN32__) || defined(__WIN64__)
	cout << "server response is:" << json_str << endl;
#else
	if (g_show_log)
		DBG_ONLY("server response is:" << json_str);
#endif
}