Example #1
0
int http_show_dir(int client, char *filepath)
{
    DIR *dp;
    struct dirent *dirp; struct stat st;
    struct passwd *filepasswd;
    int num = 1;
    char files[MAXLINE], buf[MAXLINE], name[LINE], img[LINE], mtime[LINE], dir[LINE];
    char *p;

    p = strrchr(filepath, '/');
    ++p;
    strcpy(dir, p);
    strcat(dir, "/");

    if ((dp =opendir(filepath))== NULL){
        http_error(client);
        return -1;
    }

    sprintf (files, "<HTML><TITLE>Dir Browser</TITLE>");
    sprintf (files, "%s<style type = ""text/css""> a:link{text-decoration:none;} </style>", files);
    sprintf (files, "%s<body bgcolor=""ffffff"" font-family=Arial color=#fff font-size=14px}\r\n", files);

    while ((dirp=readdir(dp))!=NULL){
        if (strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..")==0)
            continue;

        sprintf (name, "%s/%s", filepath, dirp->d_name);
        stat(name, &st);
        filepasswd = getpwuid(st.st_uid);

        if (S_ISDIR(st.st_mode))
            sprintf (img, "<img src=""dir.png"" width=""24px"" height=""24px"">");
        else if(S_ISFIFO(st.st_mode))
            sprintf (img, "<img src=""fifo.png"" width=""24px"" height=""24px"">");
        else if (S_ISLNK(st.st_mode))
            sprintf (img, "<img src=""link.png"" width=""24px"" height=""24px"">");
        else if (S_ISSOCK(st.st_mode))
            sprintf (img, "<img src=""sock.png"" width=""24px"" height=""24px"">");
        else 
            sprintf (img, "<img src=""file.png"" width=""24px"" height=""24px"">");
    

        sprintf (files, "%s<p><pre>%-2d %s ""<a href=%s%s"">%-15s</a>%-10s%10d %24s</pre></p>\r\n", files, num++, img, dir, dirp->d_name, dirp->d_name, filepasswd->pw_name, (int)st.st_size, tmmodify(st.st_mode, mtime));
    }
    closedir(dp);
    sprintf (files, "%s</BODY></HTML>", files);
       
    sprintf (buf, "HTTP/1.0 200 OK \r\n");
    sprintf (buf, "%sServer: "SERVER"\r\n", buf);
    sprintf (buf, "%sContent-length: %ld\r\n", buf, strlen(files));
    sprintf (buf, "%sContent-type: text/html\r\n", buf);
    sprintf (buf, "%s\r\n", buf);

    http_send(client, buf);
    http_send(client, files);

    return 0; 

}
Example #2
0
int play_cgi(struct httpctl * ctl)
{
	strcpy(rtsp_host, http_query_lookup(ctl, "host"));
	strcpy(rtsp_media, http_query_lookup(ctl, "mrl"));
	rtsp_port = atoi(http_query_lookup(ctl, "port"));
	audio_level = atoi(http_query_lookup(ctl, "vol"));
	if (audio_level > 800)
		audio_level = 800;

	if (rtsp_connect(&rtsp, rtsp_host, rtsp_port, rtsp_media) < 0) {
		int code;

		WARN("RTSP connection failed!");
		send_play_form(ctl);
		send_error(ctl, "RTSP playback failed");
		if ((code = rtsp_response_code(&rtsp)) > 200) {
			http_send(ctl, rtsp_iframe_html, sizeof(rtsp_iframe_html) - 1);
		}
	} else {
		audio_gain_set(audio_level * Q15(1.0) / 100);
		send_stop_form(ctl);
	}

	return http_send(ctl, footer_html, sizeof(footer_html) - 1);
}
Example #3
0
void http_mk_header(int client, int status, char *phrase)
{
    char buf[MAXLINE];
    sprintf(buf, "HTTP/1.1 %d %s\r\n", status, phrase);
    http_send(client, buf);
    http_send(client, "Content-type: text/html\r\n");
    http_send(client, "\r\n");
}
Example #4
0
int http_send_file(int client, char *filepath)
{
    char buf[MAXLINE];
    char file[MAXLINE];
    char filetype[20];
    FILE *f = fopen(filepath, "r");
    struct stat st;
    stat(filepath, &st);
   
    /*
    fgets(buf, MAXLINE, f);
    sprintf (file, "%s", buf);
    while(!feof(f)){
        fgets(buf, MAXLINE, f);
        sprintf(file, "%s%s", file, buf);
    }
    */
    
    
    http_getfiletype(filepath, filetype);
    sprintf(buf, "HTTP/1.0 200 OK\r\n");
    sprintf (buf, "%sContent-type: %s\r\n",buf, filetype);
    sprintf (buf, "%sContent-length: %ld\r\n\r\n",buf, st.st_size);
    http_send(client, buf);

    char *src=(char*)mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fileno(f), 0);
    fclose(f);
    send(client, src, st.st_size,0);
    munmap(src, st.st_size);
    return 0;
}
Example #5
0
uint http_send_error(uchar nr, int nStatus, char *szTitle, char *szText)
{
	char	*pbuf;
	char	html_buf[MAX_ETHER_PKT_LEN];
	uint	page_len = 0;
	uint 	hdr_len;
	uint 	body_len;
	
	page_len += sprintf(&html_buf[page_len], 
			"<html><head><title>%s</title></head>", _HTTP_TITLE);
	page_len += sprintf(&html_buf[page_len],
			"<body>%s</body></html>", szText);
			
	pbuf = http_buf + 54;
	hdr_len = http_header(pbuf, nStatus, szTitle, page_len);
	memcpy(&pbuf[hdr_len],html_buf,page_len);
	
	body_len = hdr_len + page_len;
	
	pbuf[54 + body_len] = 0;	/* Append NULL */

	/* Segment length = body_len + 20(TCP header) */
	http_send((uchar *)http_buf, body_len + 20, nr);
	conxn[nr].my_sequence += body_len;
	
	return 0;
}
Example #6
0
static void addr_handler(int err, const struct dnshdr *hdr, struct list *ansl,
			 struct list *authl, struct list *addl, void *arg)
{
	struct request *req = arg;
	int ok;
	(void)hdr;
	(void)authl;
	(void)addl;

	dns_rrlist_apply2(ansl, NULL, DNS_TYPE_A, DNS_TYPE_AAAA, DNS_CLASS_IN,
			  false, rr_append_handler, &req->addrl);


	ok = request_next(req, &req->dest);
	mem_deref(req->dnsq);

	DEBUG_INFO("dns ok %d dst %j\n", ok, &req->dest);
	if(ok)
	    goto fail;

	req->state = RESOLVED;
	http_send(req);
	return;
fail:
        DEBUG_WARNING("cant resolve %s\n", req->host);
        req->err_h(-ENOTCONN, req->arg);
        mem_deref(req);
}
Example #7
0
int send_error(struct httpctl * ctl, char * msg)
{
	char s[S_MAX];
	int n;
	n = snprintf(s, S_MAX, "<p><b>Error:</b> %s!</p>\r\n", msg);
	return http_send(ctl, s, n);
}
Example #8
0
int
http_send_status_line(http_t *ctx, unsigned int code, const char *msg)
{
  char buf[256], *p = buf;
  size_t size = sizeof buf;

  RUNTIME_ASSERT(code >= 100 && code <= 999);
  ACCLOG_SET(ctx->acclog, code, code);

  p = append_string(p, &size, "HTTP/1.1 ");
  p = append_uint(p, &size, code);
  p = append_char(p, &size, ' ');
  p = append_string(p, &size, msg);

#if 0
  DBUG("Sending HTTP response \"%s\"", buf);
#endif

  p = APPEND_CRLF(p, &size);
  
  p = APPEND_STATIC_CHARS(p, &size, "Date: ");
  p = append_date(p, &size, compat_mono_time(NULL));
  p = APPEND_CRLF(p, &size);

  if (
    0 != http_send(ctx, buf, sizeof buf - size) ||
    0 != http_send_str(ctx, http_server_header)
  )
    return -1;

  return 0;
}
Example #9
0
uint http_send_ok(uchar nr, char *html_page, int nStatus, char *szTitle)
{
	char	*pbuf;
	char	html_buf[MAX_ETHER_PKT_LEN];
	uint	page_len = 0;
	uint 	hdr_len;
	uint 	body_len;

	/* fill html title to html buffer */
	page_len += sprintf(&html_buf[page_len], 
			"<html><head><title>%s</title></head>", _HTTP_TITLE);
	/* copy html body to html buffer */
	memcpy(&html_buf[page_len], html_page, strlen(html_page));
	page_len += strlen(html_page);
	
	/* fill html header to packet buffer */
	pbuf = http_buf + 54;
	hdr_len = http_header(pbuf, nStatus, szTitle, page_len);
	
	/* copy html buffer to packet buffer */
	memcpy(&pbuf[hdr_len],html_buf,page_len);
	
	body_len = hdr_len + page_len;
	
	pbuf[54 + body_len] = 0;	/* Append NULL */

	/* Segment length = body_len + 20(TCP header) */
	http_send((uchar *)http_buf, body_len + 20, nr);
	conxn[nr].my_sequence += body_len;
	
	return 0;	
}
Example #10
0
int stop_cgi(struct httpctl * ctl)
{
	if (rtsp_teardown(&rtsp) < 0) {
		WARN("RTSP teardown failed!");
	}
	send_play_form(ctl);
	return http_send(ctl, footer_html, sizeof(footer_html) - 1);
}
Example #11
0
static int
http_send_str(http_t *ctx, const char *s)
{
  RUNTIME_ASSERT(ctx);
  RUNTIME_ASSERT(s);

  return http_send(ctx, s, strlen(s));
}
Example #12
0
int send_play_form(struct httpctl * ctl)
{
	char s[S_MAX];
	int n;

	httpd_200(ctl->tp, TEXT_HTML);
	http_send(ctl, index_hdr_html, sizeof(index_hdr_html) - 1);
	http_send(ctl, play_hdr_html, sizeof(play_hdr_html) - 1);

	n = snprintf(s, S_MAX, "<tr><td align=\"right\">RTSP server:</td><td>"
			"<input type=\"text\" name=\"host\"  size=\"32\" maxlength=\"128\" value=\"%s\"></td></tr>\r\n",
			rtsp_host);
	http_send(ctl, s, n);

	n = snprintf(s, S_MAX, "<tr><td align=\"right\">TCP Port:</td><td>"
			"<input type=\"text\" name=\"port\" size=\"5\" maxlength=\"5\" value=\"%d\"></td></tr>\r\n",
			rtsp_port);
	http_send(ctl, s, n);

	n = snprintf(s, S_MAX, "<tr><td align=\"right\">Media (MRL):</td><td>"
			"<input type=\"text\" name=\"mrl\" size=\"32\" maxlength=\"128\" value=\"%s\"></td></tr>\r\n",
			rtsp_media);
	http_send(ctl, s, n);

	n = snprintf(s, S_MAX, "<tr><td align=\"right\">Volume (0..200):</td><td>"
			"<input type=\"text\" name=\"vol\" size=\"4\" maxlength=\"3\" value=\"%d\"></td></tr>\r\n",
			audio_level);
	http_send(ctl, s, n);

	return http_send(ctl, play_foot_html, sizeof(play_foot_html) - 1);
}
Example #13
0
/**
 * Marks the end of the message headers.
 */
int
http_terminate_headers(http_t *ctx)
{
  const char crlf[] = "\r\n";
  int ret;
  
  ret = http_send(ctx, crlf, STATIC_STRLEN(crlf));
  ACCLOG_COMMIT(ctx->acclog);
  return 0 != ret ? -1 : 0;
}
Example #14
0
/** Close the HTTP connection after sending content **/
static void http_close(HTTP *http)
{
	if (http->len>0)
		http_send(http);
#ifdef WIN32
	closesocket(http->s);
#else
	close(http->s);
#endif
}
Example #15
0
static response *resolve_stream(const char *url)
{
    request *request = http_get(url);
    response *response = http_send(request);

    if (http_read_body(response) < 0 && response->status != 302) {
        fprintf(stderr, "request failed %s", url); 
        return NULL;
    }

    sds stream_url = sdsnew(http_header(response, "Location"));

    free_response(response);

    request = http_get(stream_url);
    response = http_send(request);
    
    sdsfree(stream_url);

    return response;
}
Example #16
0
static JSBool
req_send(JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval)
{
    JSBool ret = JS_FALSE;
    if(argc == 1) {
        ret = http_send(cx, obj, argv[0]);
    } else {
        JS_ReportError(cx, "Invalid call to CouchHTTP.send");
    }

    *rval = JSVAL_VOID;
    return ret;
}
Example #17
0
int rtsp_msg_cgi(struct httpctl * ctl)
{
	char s[S_MAX];
	int n;

	httpd_200(ctl->tp, TEXT_HTML);

	while ((n = rtsp_recv(&rtsp, s, S_MAX)) > 0) {
		http_send(ctl, s, n);
	}

	return 0;
}
Example #18
0
int send_stop_form(struct httpctl * ctl)
{
	char * host;
	char * mrl;
	char * track;
	int port;
	char s[S_MAX];
	int n;

	host = rtsp_host_name(&rtsp);
	mrl = rtsp_media_name(&rtsp);
	track = rtsp_track_name(&rtsp);
	port = rtsp_port_get(&rtsp);

	httpd_200(ctl->tp, TEXT_HTML);
	http_send(ctl, index_hdr_html, sizeof(index_hdr_html) - 1);
	http_send(ctl, stop_hdr_html, sizeof(stop_hdr_html) - 1);

	n = snprintf(s, S_MAX, "<p><b>Playing</b> RTSP://%s:%d/%s/%s</p>\r\n",
			host, port, mrl, track);
	http_send(ctl, s, n);

	return http_send(ctl, stop_foot_html, sizeof(stop_foot_html) - 1);
}
Example #19
0
/** Process an incoming action request
	@returns non-zero on success, 0 on failure (errno set)
 **/
int http_action_request(HTTP *http,char *action)
{
	if (gui_post_action(action)==-1)
	{
		http_status(http,HTTP_ACCEPTED);
		http_type(http,"text/plain");
		http_format(http,"Goodbye");
		http_send(http);
		http_close(http);
		shutdown_now();
		return 1;
	}
	else
		return 0;
}
Example #20
0
int http_error(int client)
{
    //http_send(client, "HTTP/1.1 Bad Request\r\n");
    //http_send(client, "Content-type: text/html\r\n");
    //http_send(client, "\r\n");
    //http_send(client, "<HTML><TITLE>Bad Request</TITLE>");
    //http_send(client, "<BODY>The resource can't be retrived</BODY></HTML>");
    
    http_send(client, "HTTP/1.1 400 Bad Request\r\n"
                      "Content-Type: text/html\r\n"
                      "\r\n"
                      "<HTML><TITLE>Bad Request</TITLE>"
                      "<BODY>The resource can't be retrived</BODY></HTML>");

    return 0;
}
Example #21
0
static JSBool
req_send(JSContext* cx, uintN argc, jsval* vp)
{
    JSObject* obj = JS_THIS_OBJECT(cx, vp);
    jsval* argv = JS_ARGV(cx, vp);
    JSBool ret = JS_FALSE;

    if(argc == 1) {
        ret = http_send(cx, obj, argv[0]);
    } else {
        JS_ReportError(cx, "Invalid call to CouchHTTP.send");
    }

    JS_SET_RVAL(cx, vp, JSVAL_VOID);
    return ret;
}
Example #22
0
int http_not_support(int client)
{
   // http_send(client, "HTTP/1.1 400 NoFoundation\r\n");
    //http_send(client, "Content-Type: text/html\r\n");
    //http_send(client, "\r\n");
    //http_send(client, "<HTML><TITLE>NOT SUPPORT</TITLE>");
    //http_send(client, "<BODY>Walker server do not support the mothod you request.</BODY></HTML>");

    http_send(client, "HTTP/1.1 400 NoFoundation\r\n"
                      "Content-type: text/html\r\n"
                      "\r\n"
                      "<HTML><TITLE>Not Support</TITLE>"
                      "<BODY>Walker server do not support the method you request.</BODY></HTML>");
    
    return 0;

}
Example #23
0
int http_not_found(int client)
{
    //http_send(client, "HTTP/1.1 404 NotFoundation\r\n");
    //http_send(client, "Content-Type: text/html\r\n");
    //http_send(client, "\r\n");
    //http_send(client, "<HTML><TITLE>Not Foundation</TITLE>");
    //http_send(client, "<BODY><p>The server could not fullfill your request.");
    //http_send(client, "Because the resource specified is unavailable or not exit");
    //http_send(client, "</p></BODY></HTML>");
    
    http_send(client, "HTTP/1.1 404 Not Found\r\n"
                      "Content-type: text/html\r\n"
                      "\r\n"
                      "<HTML><TITLE>Not Found</TITLE>"
                      "<BODY>File requested isn't found on the server</BODY></HTML>");
    
    return 0;
}
Example #24
0
void http_send_file(int sock, char *file)
{
    FILE *fp;
    fp = fopen(file, "rb");
    if( fp != NULL )
    {
        OPS("### @ HTTP : Send File : %s", file);
        // header
        char *http;
        NEW(http, 256);
        //memset(http, 0, 128);
        strcat(http, "HTTP/1.1 200 OK\r\n");
        strcat(http, "Content-Type: image/png\r\n");
        strcat(http, "\r\n");
        // send
        send(sock, http, strlen(http), 0);
        // body
        char *buffer;
        NEW(buffer, 512);
        while( !feof(fp) )
        {
            fread(buffer, 512, 1, fp);
            send(sock, buffer, 512, 0);
        }
        fclose(fp);
        // Close
        shutdown(sock, SD_BOTH);
        closesocket(sock);
        // Clear
        DEL(http);
        DEL(buffer);
        //DEL(sock);
        //DEL(fp);
     }
     else
     {
         OPS("### @ HTTP : File Not Found : %s", file);
         //DEL(sock);
         DEL(fp);
         http_send(sock, "FILE NOT FOUND");
     }
}
Example #25
0
void tcp_buffer( TCP_NODE *n, char *buffer, ssize_t bytes ) {
	/* Append buffer */
	node_appendBuffer( n, buffer, bytes );

	if( n->pipeline != NODE_READY ) {
		fail( "FIXME tcp_buffer..." );
	}

	/* Overflow? */
	if( n->recv_size >= BUF_OFF1 ) {
		info( &n->c_addr, "Max head buffer exceeded..." );
		node_status( n, NODE_SHUTDOWN );
		return;
	}

	/* Parse request */
	http_buf( n );

	/* Start sending data */
	http_send( n );
}
Example #26
0
/** Process an incoming request
	@returns nothing
 **/
void http_response(SOCKET fd)
{
	HTTP *http = http_create(fd);
	size_t len;
	int content_length = 0;
	char *user_agent = NULL;
	char *host = NULL;
	int keep_alive = 0;
	char *connection = NULL;
	char *accept = NULL;
	struct s_map {
		char *name;
		enum {INTEGER,STRING} type;
		void *value;
		size_t sz;
	} map[] = {
		{"Content-Length", INTEGER, (void*)&content_length, 0},
		{"Host", STRING, (void*)&host, 0},
		{"Keep-Alive", INTEGER, (void*)&keep_alive, 0},
		{"Connection", STRING, (void*)&connection, 0},
		{"Accept", STRING, (void*)&accept, 0},
	};

	while ( (int)(len=recv_data(fd,http->query,sizeof(http->query)))>0 )
	{
		/* first term is always the request */
		char *request = http->query;
		char method[32];
		char uri[1024];
		char version[32];
		char *p = strchr(http->query,'\r');
		int v;
		
		/* initialize the response */
		http_reset(http);

		/* read the request string */
		if (sscanf(request,"%s %s %s",method,uri,version)!=3)
		{
			http_status(http,HTTP_BADREQUEST);
			http_format(http,HTTP_BADREQUEST);
			http_type(http,"text/html");
			http_send(http);
			break;
		}

		/* read the rest of the header */
		while (p!=NULL && (p=strchr(p,'\r'))!=NULL) 
		{
 			*p = '\0';
			p+=2;
			for ( v=0 ; v<sizeof(map)/sizeof(map[0]) ; v++ )
			{
				if (map[v].sz==0) map[v].sz = strlen(map[v].name);
				if (strnicmp(map[v].name,p,map[v].sz)==0 && strncmp(p+map[v].sz,": ",2)==0)
				{
					if (map[v].type==INTEGER) { *(int*)(map[v].value) = atoi(p+map[v].sz+2); break; }
					else if (map[v].type==STRING) { *(char**)map[v].value = p+map[v].sz+2; break; }
				}
			}
		}
		output_verbose("%s (host='%s', len=%d)",http->query,host?host:"???",content_length);

		/* reject anything but a GET */
		if (stricmp(method,"GET")!=0)
		{
			http_status(http,HTTP_METHODNOTALLOWED);
			http_format(http,HTTP_METHODNOTALLOWED);
			http_type(http,"text/html");
			/* technically, we should add an Allow entry to the response header */
			http_send(http);
			break;
		}

		/* handle request */
		if ( strcmp(uri,"/favicon.ico")==0 )
		{
			if ( http_favicon(http) )
				http_status(http,HTTP_OK);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else {
			static struct s_map {
				char *path;
				int (*request)(HTTP*,char*);
				char *success;
				char *failure;
			} map[] = {
				/* this is the map of recognize request types */
				{"/xml/",		http_xml_request,		HTTP_OK, HTTP_NOTFOUND},
				{"/gui/",		http_gui_request,		HTTP_OK, HTTP_NOTFOUND},
				{"/output/",	http_output_request,	HTTP_OK, HTTP_NOTFOUND},
				{"/action/",	http_action_request,	HTTP_ACCEPTED,HTTP_NOTFOUND},
				{"/rt/",		http_get_rt,			HTTP_OK, HTTP_NOTFOUND},
				{"/perl/",		http_run_perl,			HTTP_OK, HTTP_NOTFOUND},
				{"/gnuplot/",	http_run_gnuplot,		HTTP_OK, HTTP_NOTFOUND},
				{"/java/",		http_run_java,			HTTP_OK, HTTP_NOTFOUND},
				{"/python/",	http_run_python,		HTTP_OK, HTTP_NOTFOUND},
				{"/r/",			http_run_r,				HTTP_OK, HTTP_NOTFOUND},
				{"/scilab/",	http_run_scilab,		HTTP_OK, HTTP_NOTFOUND},
				{"/octave/",	http_run_octave,		HTTP_OK, HTTP_NOTFOUND},
			};
			int n;
			for ( n=0 ; n<sizeof(map)/sizeof(map[0]) ; n++ )
			{
				size_t len = strlen(map[n].path);
				if (strncmp(uri,map[n].path,len)==0)
				{
					if ( map[n].request(http,uri+len) )
						http_status(http,map[n].success);
					else
						http_status(http,map[n].failure);
					http_send(http);
					goto Next;
				}
			}
		}
		/* deprecated XML usage */
		if (strncmp(uri,"/",1)==0 )
		{
			if ( http_xml_request(http,uri+1) )
			{	
				output_warning("deprecate XML usage in request '%s'", uri);
				http_status(http,HTTP_OK);
			}
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else 
		{
			http_status(http,HTTP_NOTFOUND);
			http_format(http,HTTP_NOTFOUND);
			http_type(http,"text/html");
			http_send(http);
		}

		/* keep-alive not desired*/
Next:
		if (connection && stricmp(connection,"close")==0)
			break;
	}
	http_close(http);
	output_verbose("socket %d closed",http->s);
}
Example #27
0
void APISelect(void *data)
{
    OPS("### @ API : Accept Success - Thread[%d]", pthread_self());
    // struct data
    qqclient* qq = ((void**)data)[0];
    qq->api_select_count ++ ;
    apiclient* apis = ((void**)data)[1];
    int client = apis->sock;
    pthread_mutex_unlock(&apis->mxsock);
    // Request
    char *buffer;
    NEW(buffer, REQUEST_BUFFER);
    // Select 模型读取请求
    fd_set fdRead;
    struct timeval fdRTV = {1, 0};

    FD_ZERO(&fdRead);
    FD_SET(client, &fdRead);
    switch ( select(client, &fdRead, NULL, NULL, &fdRTV) )
    {
        default:
        if ( FD_ISSET(client, &fdRead) )
        {
            recv(client, buffer, REQUEST_BUFFER, 0);
        }
    }

    if ( strlen(buffer) < 9 )
    {
        OPS("### @ API : Request Unavailable.");
        DEL(buffer);
        return;
    }

    // Request Test
    DBG("##### Request Begin #####\n%s\n##### Request End #####\n", buffer);

    char *http;
    NEW(http, 16);
    mid_value(buffer, "GET ", " HTTP/1.1", http, 16);
    if ( strstr(http, "/v?") >0 )
    {
        // 验证码读取
        char *uid, *file;
        NEW(uid, 18);
        NEW(file, 32);
        if ( strstr(http, "&") > 0 )
        {
            mid_value(http, "/v?", "&", uid, 18);
        }
        else
        {
            mid_value(http, "/v?", NULL, uid, 18);
        }
        sprintf(file, "./verify/%s.png", uid);
        http_send_file(client, file);
        DEL(uid);
        DEL(file);
        DEL(http);
        DEL(buffer);
        return;
    }
    else if ( strstr(http, "/send?") > 0 )
    {
        // 发送自定义信息
        char *msg;
        NEW(msg, REQUEST_BUFFER);
        mid_value(buffer, "GET /send?", " HTTP/1.1", msg, REQUEST_BUFFER);
        api_callback_build("http.send", msg);
        DEL(msg);
        http_send(client, "Message Sends OK.");
        DEL(http);
        DEL(buffer);
        return;
    }
    else if ( strlen(http) > 0 )
    {
        http_send(client, "QQRobot API Server.");
        DEL(http);
        DEL(buffer);
        return;
    }
    DEL(http);

    char *api;
    NEW(api, API_BUFFER);
    mid_value(buffer, "API ", " MOYO/1.1", api, API_BUFFER);
    if (strlen(api) == 0)
    {
        http_send(client, "API IS EMPTY");
        DEL(api);
        DEL(buffer);
        return;
    }

    // API Commands
    char *response;
    NEW(response, RESPONSE_BUFFER);
    // Check SecKey
    char *seckey;
    NEW(seckey, 255);
    mid_value(buffer, "<seckey>", "</seckey>", seckey, 255);
    if ( strcmp(apis->APISeckey, seckey)!=0 )
    {
        strcat(response, "ACCESS DENIED");
        OPS("### @ API : Denied of : %s", api);
        DEL(seckey);
        goto API_RESPONSE;
    }
    DEL(seckey);
    // API Runs
    OPS("### @ API : Command of : %s ...Runs ...", api);
    // ##### API of login #####
    if ( stricmp(api, "login.create")==0 )
    {
        char *uid, *password;
        NEW(uid, 10);
        NEW(password, 32);
        mid_value(buffer, "<uid>", "</uid>", uid, 10);
        mid_value(buffer, "<password>", "</password>", password, 32);
        strcat(response, myqq_login(atoi(uid), password));
        //printf("Done of %s.\n", api);
        DEL(uid);
        DEL(password);
    }
    else if ( stricmp(api, "login.destroy")==0 )
    {
        strcat(response, myqq_logout());
        //printf("Done of %s.\n", api);
    }
    else if ( stricmp(api, "login.verify")==0 )
    {
        char *vcode;
        NEW(vcode, 4);
        mid_value(buffer, "<verify>", "</verify>", vcode, 4);
        if ( qq->process == P_VERIFYING )
        {
            qqclient_verify(qq, vcode);
            OPS("### @ API : [Input] Verify Code : %s", vcode);
            strcat(response, myqq_resume_login());
        }
        else
        {
            strcat(response, "DONT NEED");
        }
        //printf("Done of %s.\n", api);
        DEL(vcode);
    }
    else if ( stricmp(api, "login.check")==0 )
    {
        strcat(response, myqq_check_login(qq));
        //printf("Done of %s.\n", api);
    }
    // ##### API of buddy #####
    else if ( stricmp(api, "buddy.name")==0 )
    {
        char *uid;
        NEW(uid, 10);
        mid_value(buffer, "<uid>", "</uid>", uid, 10);
        strcat(response, myqq_get_buddy_name(qq, atoi(uid)));
        //printf("Done of %s.\n", api);
        DEL(uid);
    }
    else if ( stricmp(api, "buddy.send")==0 )
    {
        char *uid, *message;
        NEW(uid, 10);
        NEW(message, SEND_MESSAGE_SIZE);
        mid_value(buffer, "<uid>", "</uid>", uid, 10);
        mid_value(buffer, "<message>", "</message>", message, SEND_MESSAGE_SIZE);
        if ( myqq_send_im_to_buddy(qq, atoi(uid), message, 0) )
        {
            strcat(response, "SEND FAILED");
        }
        else
        {
            strcat(response, "SEND SUCCESS");
        }
        //printf("Done of %s.\n", api);
        DEL(uid);
        DEL(message);
    }
    else if ( stricmp(api, "buddy.info")==0 )
    {
        char *uid;
        NEW(uid, 10);
        mid_value(buffer, "<uid>", "</uid>", uid, 10);
        char *info;
        NEW(info, KB(4));
        myqq_get_buddy_info(qq, atoi(uid), info, KB(4));
        strcat(response, info);
        //printf("Done of %s.\n", api);
        DEL(uid);
        DEL(info);
    }
    else if ( stricmp(api, "buddy.list")==0 )
    {
        char *online;
        NEW(online, 3);
        mid_value(buffer, "<online>", "</online>", online, 3);
        char *info;
        NEW(info, BUDDY_BUF_SIZE);
        if ( stricmp(online, "yes")==0 )
        {
            myqq_get_buddy_list(qq, info, BUDDY_BUF_SIZE, 1);
        }
        else
        {
            myqq_get_buddy_list(qq, info, BUDDY_BUF_SIZE, 0);
        }
        strcat(response, info);
        //printf("Done of %s.\n", api);
        DEL(online);
        DEL(info);
    }
    // ##### API of qun #####
    else if ( stricmp(api, "qun.name")==0 )
    {
        char *gid;
        NEW(gid, 10);
        mid_value(buffer, "<gid>", "</gid>", gid, 10);
        strcat(response, myqq_get_qun_name(qq, atoi(gid)));
        //printf("Done of %s.\n", api);
        DEL(gid);
    }
    else if ( stricmp(api, "qun.send")==0 )
    {
        char *gid, *message;
        NEW(gid, 10);
        NEW(message, SEND_MESSAGE_SIZE);
        mid_value(buffer, "<gid>", "</gid>", gid, 10);
        mid_value(buffer, "<message>", "</message>", message, SEND_MESSAGE_SIZE);
        if ( myqq_send_im_to_qun(qq, atoi(gid), message, 0) )
        {
            strcat(response, "SEND FAILED");
        }
        else
        {
            strcat(response, "SEND SUCCESS");
        }
        //printf("Done of %s.\n", api);
        DEL(gid);
        DEL(message);
    }
    else if ( stricmp(api, "qun.buddy.name")==0 )
    {
        char *gid, *uid;
        NEW(gid, 10);
        NEW(uid, 10);
        mid_value(buffer, "<gid>", "</gid>", gid, 10);
        mid_value(buffer, "<uid>", "</uid>", uid, 10);
        strcat(response, myqq_get_qun_member_name(qq, atoi(gid), atoi(uid)));
        //printf("Done of %s.\n", api);
        DEL(gid);
        DEL(uid);
    }
    else if ( stricmp(api, "qun.info")==0 )
    {
        char *gid;
        NEW(gid, 10);
        mid_value(buffer, "<gid>", "</gid>", gid, 10);
        char *info;
        NEW(info, KB(4));
        myqq_get_qun_info(qq, atoi(gid), info, KB(4));
        strcat(response, info);
        //printf("Done of %s.\n", api);
        DEL(gid);
        DEL(info);
    }
    else if ( stricmp(api, "qun.list")==0 )
    {
        char *info;
        NEW(info, QUN_BUF_SIZE);
        myqq_get_qun_list(qq, info, QUN_BUF_SIZE);
        strcat(response, info);
        //printf("Done of %s.\n", api);
        DEL(info);
    }
    else if ( stricmp(api, "qun.buddy.list")==0 )
    {
        char *gid, *online;
        NEW(gid, 10);
        NEW(online, 3);
        mid_value(buffer, "<gid>", "</gid>", gid, 10);
        mid_value(buffer, "<online>", "</online>", online, 3);
        char *info;
        NEW(info, BUDDY_BUF_SIZE);
        if ( stricmp(online, "yes")==0 )
        {
            myqq_get_qun_member_list(qq, atoi(gid), info, BUDDY_BUF_SIZE, 1);
        }
        else
        {
            myqq_get_qun_member_list(qq, atoi(gid), info, BUDDY_BUF_SIZE, 0);
        }
        strcat(response, info);
        //printf("Done of %s.\n", api);
        DEL(gid);
        DEL(online);
        DEL(info);
    }
    // ##### API of me #####
    else if ( stricmp(api, "me.sleep")==0 )
    {
        char *power;
        NEW(power, 3);
        mid_value(buffer, "<power>", "</power>", power, 3);
        if ( strcmp(power, "on")==0 )
        {
            apis->APISleep = 1;
        }
        else
        {
            apis->APISleep = 0;
        }
        strcat(response, "SWITCH SUCCESS");
        //printf("Done of %s.\n", api);
        DEL(power);
    }
    else if ( stricmp(api, "me.list.update")==0 )
    {
        qun_update_all(qq);
        buddy_update_list(qq);
        group_update_list(qq);
        if ( qqclient_wait(qq, 10)<0 )
        {
            strcat(response, "UPDATE FAILED");
        }
        else
        {
            strcat(response, "UPDATE SUCCESS");
        }
        //printf("Done of %s.\n", api);
    }
    else if ( stricmp(api, "me.autoreply")==0 )
    {
        char *power;
        NEW(power, 3);
        mid_value(buffer, "<power>", "</power>", power, 3);
        if ( strcmp(power, "on")==0 )
        {
            myqq_auto_reply(1);
        }
        else
        {
            myqq_auto_reply(0);
        }
        strcat(response, "SWITCH SUCCESS");
        //printf("Done of %s.\n", api);
        DEL(power);
    }
    else if ( stricmp(api, "me.status.update")==0 )
    {
        char *status;
        NEW(status, 6);
        mid_value(buffer, "<status>", "</status>", status, 6);
        if( strcmp( status, "away") == 0 )
            qqclient_change_status( qq, QQ_AWAY );
        else if( strcmp( status, "online") == 0 )
            qqclient_change_status( qq, QQ_ONLINE );
        else if( strcmp( status, "hidden") == 0 )
            qqclient_change_status( qq, QQ_HIDDEN );
        else if( strcmp( status, "killme") == 0 )
            qqclient_change_status( qq, QQ_KILLME );
        else if( strcmp( status, "busy") == 0 )
            qqclient_change_status( qq, QQ_BUSY );
        strcat(response, "UPDATE SUCCESS");
        //printf("Done of %s.\n", api);
        DEL(status);
    }
    else if ( stricmp(api, "me.buddy.add")==0 )
    {
        char *uid, *message;
        NEW(uid, 10);
        NEW(message, 50);
        mid_value(buffer, "<uid>", "</uid>", uid, 10);
        mid_value(buffer, "<message>", "</message>", message, 50);
        qqclient_add(qq, atoi(uid), message);
        strcat(response, "ADD SUCCESS");
        //printf("Done of %s.\n", api);
        DEL(uid);
        DEL(message);
    }
    else if ( stricmp(api, "me.buddy.del")==0 )
    {
        char *uid;
        NEW(uid, 10);
        mid_value(buffer, "<uid>", "</uid>", uid, 10);
        qqclient_del(qq, atoi(uid));
        strcat(response, "DELETE SUCCESS");
        //printf("Done of %s.\n", api);
        DEL(uid);
    }
    else
    {
        strcat(response, "UNKNOWN API COMMAND");
        OPS("### @ API : Command Unknown : %s", api);
    }
API_RESPONSE:
    // Send
    send(client, response, strlen(response), 0);

    // print
    OPS("### @ API : Command of : %s ...Done.", api);

    // Response Test
    DBG("##### Response Begin #####\n%s\n##### Response End #####\n", response);
    // Close
    shutdown(client, SD_BOTH);
    closesocket(client);
    // Clear
    DEL(response);
    //DEL(client);
    pthread_detach(pthread_self());
}
Example #28
0
int
http_send_data(http_t *ctx, const char *data, size_t size)
{
  return http_send(ctx, data, size);
}
Example #29
0
int index_cgi(struct httpctl * ctl)
{
	send_play_form(ctl);
	return http_send(ctl, footer_html, sizeof(footer_html) - 1);
}
Example #30
0
void start_server(void)
{
    int pid, c_dsc;
    struct sockaddr_in s_sin, c_sin;
    socklen_t s_len, c_len;
    http_in_t* req;

    s_len = sizeof(s_sin);
    c_len = sizeof(c_sin);

    s_sin.sin_family      = AF_INET;
    s_sin.sin_port        = htons(conf.port);
    s_sin.sin_addr.s_addr = htonl(INADDR_ANY);

    /* Creates socket */
    if((s_dsc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
        log_critical("Failed to create socket: %s", strerror(errno));
        remove_pid();
        return;
    }

    /* Binds socket */
    if(bind(s_dsc, (struct sockaddr*)&s_sin, s_len) < 0)
    {
        log_critical("Failed to bind: %s", strerror(errno));
        remove_pid();
        return;
    }

    /* Listens */
    if(listen(s_dsc, SOMAXCONN) < 0)
    {
        log_critical("Failed to listen: %s", strerror(errno));
        remove_pid();
        return;
    }

    /* Infinite loop */
    while(1)
    {
        if((c_dsc = accept(s_dsc, (struct sockaddr*)&c_sin, &c_len)) < 0)
        {
            log_error("Failed to accept: %s", strerror(errno));
            continue;
        }

        pid = fork();

        switch(pid)
        {
             case -1: /* Error */
                log_error("Failed to fork: %s", strerror(errno));
                break;

             case 0: /* Child process */
                close(s_dsc);
                log_debug("Connection by %s:%d", inet_ntoa(c_sin.sin_addr), htons(c_sin.sin_port));

                /* Receives HTTP request */
                req = http_recv(c_dsc);

                /* Sends HTTP response */
                http_send(c_dsc, req);

                close(c_dsc);
                exit(EXIT_SUCCESS);

            default: /* Father process */
                close(c_dsc);
        }
    }
}