resp协议定义, xml定义配置文件
This commit is contained in:
15
NtyCo/sample/CMakeLists.txt
Normal file
15
NtyCo/sample/CMakeLists.txt
Normal file
@@ -0,0 +1,15 @@
|
||||
|
||||
aux_source_directory(. SRC)
|
||||
|
||||
# 编译不过的,先放这里
|
||||
set(NOT_COMPILE )
|
||||
|
||||
foreach(FILE_PATH ${SRC})
|
||||
string(REGEX REPLACE ".+/(.+)\\..*" "\\1" FILE_NAME ${FILE_PATH})
|
||||
list(FIND NOT_COMPILE ${FILE_NAME} RESULT)
|
||||
if(${RESULT} EQUAL -1)
|
||||
message(${FILE_NAME})
|
||||
add_executable(${FILE_NAME} ${FILE_PATH})
|
||||
target_link_libraries(${FILE_NAME} nty_core ${LIBS})
|
||||
endif()
|
||||
endforeach()
|
||||
16
NtyCo/sample/Makefile
Normal file
16
NtyCo/sample/Makefile
Normal file
@@ -0,0 +1,16 @@
|
||||
|
||||
|
||||
CUR_SOURCE = ${wildcard *.c}
|
||||
|
||||
CUR_OBJS = ${patsubst %.c, %.o, $(CUR_SOURCE)}
|
||||
|
||||
all : $(SUB_DIR) $(CUR_OBJS)
|
||||
|
||||
$(SUB_DIR) : ECHO
|
||||
make -C $@
|
||||
|
||||
$(CUR_OBJS) : %.o : %.c
|
||||
$(CC) -c $^ -o $(OBJS_DIR)/$@ $(FLAG)
|
||||
|
||||
ECHO :
|
||||
@echo $(SUB_DIR)
|
||||
84
NtyCo/sample/hook_tcpserver.c
Executable file
84
NtyCo/sample/hook_tcpserver.c
Executable file
@@ -0,0 +1,84 @@
|
||||
|
||||
|
||||
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
|
||||
|
||||
|
||||
void server_reader(void *arg) {
|
||||
int fd = *(int *)arg;
|
||||
int ret = 0;
|
||||
|
||||
|
||||
while (1) {
|
||||
|
||||
char buf[1024] = {0};
|
||||
ret = recv(fd, buf, 1024, 0);
|
||||
if (ret > 0) {
|
||||
printf("read from server: %.*s\n", ret, buf);
|
||||
|
||||
ret = send(fd, buf, strlen(buf), 0);
|
||||
if (ret == -1) {
|
||||
close(fd);
|
||||
break;
|
||||
}
|
||||
} else if (ret == 0) {
|
||||
close(fd);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
void server(void *arg) {
|
||||
|
||||
unsigned short port = *(unsigned short *)arg;
|
||||
|
||||
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) return ;
|
||||
|
||||
struct sockaddr_in local, remote;
|
||||
local.sin_family = AF_INET;
|
||||
local.sin_port = htons(port);
|
||||
local.sin_addr.s_addr = INADDR_ANY;
|
||||
bind(fd, (struct sockaddr*)&local, sizeof(struct sockaddr_in));
|
||||
|
||||
listen(fd, 20);
|
||||
printf("listen port : %d\n", port);
|
||||
|
||||
|
||||
while (1) {
|
||||
socklen_t len = sizeof(struct sockaddr_in);
|
||||
int cli_fd = accept(fd, (struct sockaddr*)&remote, &len);
|
||||
|
||||
|
||||
nty_coroutine *read_co;
|
||||
nty_coroutine_create(&read_co, server_reader, &cli_fd);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
int port = atoi(argv[1]);
|
||||
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
nty_coroutine_create(&co, server, &port);
|
||||
|
||||
nty_schedule_run();
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
727
NtyCo/sample/nty_bench.c
Normal file
727
NtyCo/sample/nty_bench.c
Normal file
@@ -0,0 +1,727 @@
|
||||
/*
|
||||
* Author : WangBoJing , email : 1989wangbojing@gmail.com
|
||||
*
|
||||
* Copyright Statement:
|
||||
* --------------------
|
||||
* This software is protected by Copyright and the information contained
|
||||
* herein is confidential. The software may not be copied and the information
|
||||
* contained herein may not be used or disclosed except with the written
|
||||
* permission of Author. (C) 2017
|
||||
*
|
||||
*
|
||||
|
||||
**** ***** *****
|
||||
*** * ** ***
|
||||
*** * * * **
|
||||
* ** * * ** **
|
||||
* ** * * ** *
|
||||
* ** * ** ** *
|
||||
* ** * *** **
|
||||
* ** * *********** ***** ***** ** ****
|
||||
* ** * ** ** ** ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * ** **
|
||||
* *** ** * * ** * ** **
|
||||
* *** ** * ** * * ** **
|
||||
* ** ** * ** ** * ** **
|
||||
* ** ** * * ** * ** **
|
||||
***** * **** * ***** ****
|
||||
*
|
||||
*
|
||||
*****
|
||||
****
|
||||
|
||||
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
/*
|
||||
* (C) Radim Kolar 1997-2004
|
||||
* This is free software, see GNU Public License version 2 for
|
||||
* details.
|
||||
*
|
||||
* Simple forking WWW Server benchmark:
|
||||
*
|
||||
* Usage:
|
||||
* webbench --help
|
||||
*
|
||||
* Return codes:
|
||||
* 0 - sucess
|
||||
* 1 - benchmark failed (server is not on-line)
|
||||
* 2 - bad param
|
||||
* 3 - internal error, fork failed
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <fcntl.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/time.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
#define ENABLE_NTYCO 1
|
||||
#define MAX_BUFFER_LENGTH 1024
|
||||
|
||||
|
||||
#define write(a, b, c) nty_send(a, b, c, 0)
|
||||
#define send(a, b, c, d) nty_send(a, b, c, d)
|
||||
#define read(a, b, c) nty_recv(a, b, c, 0)
|
||||
#define recv(a, b, c, d) nty_recv(a, b, c, d)
|
||||
#define connect(a, b, c) nty_connect(a, b, c)
|
||||
#define socket(a, b, c) nty_socket(a, b, c)
|
||||
#define close(a) nty_close(a)
|
||||
#define accept(a, b, c) nty_accept(a, b, c)
|
||||
|
||||
|
||||
|
||||
int Socket(const char *host, int clientPort)
|
||||
{
|
||||
int sock;
|
||||
unsigned long inaddr;
|
||||
struct sockaddr_in ad;
|
||||
struct hostent *hp;
|
||||
|
||||
memset(&ad, 0, sizeof(ad));
|
||||
ad.sin_family = AF_INET;
|
||||
|
||||
inaddr = inet_addr(host);
|
||||
if (inaddr != INADDR_NONE)
|
||||
memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
|
||||
else
|
||||
{
|
||||
hp = gethostbyname(host);
|
||||
if (hp == NULL)
|
||||
return -1;
|
||||
memcpy(&ad.sin_addr, hp->h_addr, hp->h_length);
|
||||
}
|
||||
ad.sin_port = htons(clientPort);
|
||||
|
||||
sock = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sock < 0)
|
||||
return sock;
|
||||
if (connect(sock, (struct sockaddr *)&ad, sizeof(ad)) < 0)
|
||||
return -1;
|
||||
return sock;
|
||||
}
|
||||
|
||||
|
||||
#include <unistd.h>
|
||||
#include <sys/param.h>
|
||||
#include <rpc/types.h>
|
||||
#include <getopt.h>
|
||||
#include <strings.h>
|
||||
#include <time.h>
|
||||
#include <signal.h>
|
||||
|
||||
/* values */
|
||||
volatile int timerexpired=0;
|
||||
int speed=0;
|
||||
int failed=0;
|
||||
int bytes=0;
|
||||
/* globals */
|
||||
int http10=1; /* 0 - http/0.9, 1 - http/1.0, 2 - http/1.1 */
|
||||
/* Allow: GET, HEAD, OPTIONS, TRACE */
|
||||
#define METHOD_GET 0
|
||||
#define METHOD_HEAD 1
|
||||
#define METHOD_OPTIONS 2
|
||||
#define METHOD_TRACE 3
|
||||
#define PROGRAM_VERSION "1.5"
|
||||
int method=METHOD_GET;
|
||||
int clients=1;
|
||||
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
// clients --> fork num
|
||||
// nreqs --> http request
|
||||
// socket --> io num
|
||||
// socket per fork --> sockets / client
|
||||
// request per socket --> request / sockets
|
||||
|
||||
int nreqs = 0;
|
||||
int sockets = 0;
|
||||
#endif
|
||||
int force=0;
|
||||
int force_reload=0;
|
||||
int proxyport=80;
|
||||
char *proxyhost=NULL;
|
||||
int benchtime=30;
|
||||
/* internal */
|
||||
int mypipe[2];
|
||||
char host[MAXHOSTNAMELEN];
|
||||
#define REQUEST_SIZE 2048
|
||||
char request[REQUEST_SIZE] = {0};
|
||||
|
||||
static const struct option long_options[]=
|
||||
{
|
||||
{"force",no_argument,&force,1},
|
||||
{"reload",no_argument,&force_reload,1},
|
||||
{"time",required_argument,NULL,'t'},
|
||||
{"help",no_argument,NULL,'?'},
|
||||
{"http09",no_argument,NULL,'9'},
|
||||
{"http10",no_argument,NULL,'1'},
|
||||
{"http11",no_argument,NULL,'2'},
|
||||
{"get",no_argument,&method,METHOD_GET},
|
||||
{"head",no_argument,&method,METHOD_HEAD},
|
||||
{"options",no_argument,&method,METHOD_OPTIONS},
|
||||
{"trace",no_argument,&method,METHOD_TRACE},
|
||||
{"version",no_argument,NULL,'V'},
|
||||
{"proxy",required_argument,NULL,'p'},
|
||||
{"clients",required_argument,NULL,'c'},
|
||||
{NULL,0,NULL,0}
|
||||
};
|
||||
|
||||
/* prototypes */
|
||||
static void benchcore(const char* host,const int port, const char *request);
|
||||
static int bench(void);
|
||||
static void build_request(const char *url);
|
||||
|
||||
static void alarm_handler(int signal)
|
||||
{
|
||||
timerexpired=1;
|
||||
}
|
||||
|
||||
static void usage(void)
|
||||
{
|
||||
fprintf(stderr,
|
||||
"webbench [option]... URL\n"
|
||||
" -f|--force Don't wait for reply from server.\n"
|
||||
" -r|--reload Send reload request - Pragma: no-cache.\n"
|
||||
" -t|--time <sec> Run benchmark for <sec> seconds. Default 30.\n"
|
||||
" -n|--request <num> Sum of requestion\n"
|
||||
" -s|--socket <num> Sum of socket\n"
|
||||
" -p|--proxy <server:port> Use proxy server for request.\n"
|
||||
" -c|--clients <n> Run <n> HTTP clients at once. Default one.\n"
|
||||
" -9|--http09 Use HTTP/0.9 style requests.\n"
|
||||
" -1|--http10 Use HTTP/1.0 protocol.\n"
|
||||
" -2|--http11 Use HTTP/1.1 protocol.\n"
|
||||
" --get Use GET request method.\n"
|
||||
" --head Use HEAD request method.\n"
|
||||
" --options Use OPTIONS request method.\n"
|
||||
" --trace Use TRACE request method.\n"
|
||||
" -?|-h|--help This information.\n"
|
||||
" -V|--version Display program version.\n"
|
||||
);
|
||||
};
|
||||
int main(int argc, char *argv[])
|
||||
{
|
||||
int opt=0;
|
||||
int options_index=0;
|
||||
char *tmp=NULL;
|
||||
|
||||
if(argc==1)
|
||||
{
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
|
||||
while((opt=getopt_long(argc,argv,"912Vfrt:p:n:s:c:?h",long_options,&options_index))!=EOF )
|
||||
{
|
||||
switch(opt)
|
||||
{
|
||||
case 0 : break;
|
||||
case 'f': force=1;break;
|
||||
case 'r': force_reload=1;break;
|
||||
case '9': http10=0;break;
|
||||
case '1': http10=1;break;
|
||||
case '2': http10=2;break;
|
||||
case 'V': printf(PROGRAM_VERSION"\n");exit(0);
|
||||
case 't': benchtime=atoi(optarg);break;
|
||||
case 'p':
|
||||
/* proxy server parsing server:port */
|
||||
tmp=strrchr(optarg,':');
|
||||
proxyhost=optarg;
|
||||
if(tmp==NULL)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if(tmp==optarg)
|
||||
{
|
||||
fprintf(stderr,"Error in option --proxy %s: Missing hostname.\n",optarg);
|
||||
return 2;
|
||||
}
|
||||
if(tmp==optarg+strlen(optarg)-1)
|
||||
{
|
||||
fprintf(stderr,"Error in option --proxy %s Port number is missing.\n",optarg);
|
||||
return 2;
|
||||
}
|
||||
*tmp='\0';
|
||||
proxyport=atoi(tmp+1);break;
|
||||
case ':':
|
||||
case 'h':
|
||||
case '?': usage();return 2;break;
|
||||
case 'c': clients=atoi(optarg);break;
|
||||
#if ENABLE_NTYCO
|
||||
case 'n': nreqs=atoi(optarg);break;
|
||||
case 's': sockets=atoi(optarg);break;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
if(optind==argc) {
|
||||
fprintf(stderr,"webbench: Missing URL!\n");
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
|
||||
if(clients==0) clients=1;
|
||||
if(benchtime==0) benchtime=60;
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
if (clients > 10) clients = 10;
|
||||
if (nreqs < 1000) nreqs = 1000;
|
||||
//if (sockets < clients) sockets = clients;
|
||||
if (sockets % clients != 0) sockets = sockets / clients * clients;
|
||||
#endif
|
||||
|
||||
/* Copyright */
|
||||
fprintf(stderr,"Webbench - Simple Web Benchmark "PROGRAM_VERSION"\n"
|
||||
"Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.\n"
|
||||
);
|
||||
build_request(argv[optind]);
|
||||
/* print bench info */
|
||||
printf("\nBenchmarking: ");
|
||||
switch(method)
|
||||
{
|
||||
case METHOD_GET:
|
||||
default:
|
||||
printf("GET");break;
|
||||
case METHOD_OPTIONS:
|
||||
printf("OPTIONS");break;
|
||||
case METHOD_HEAD:
|
||||
printf("HEAD");break;
|
||||
case METHOD_TRACE:
|
||||
printf("TRACE");break;
|
||||
}
|
||||
printf(" %s",argv[optind]);
|
||||
switch(http10)
|
||||
{
|
||||
case 0: printf(" (using HTTP/0.9)");break;
|
||||
case 2: printf(" (using HTTP/1.1)");break;
|
||||
}
|
||||
printf("\n");
|
||||
if(clients==1) printf("1 client");
|
||||
else
|
||||
printf("%d clients",clients);
|
||||
|
||||
printf(", running %d sec", benchtime);
|
||||
if(force) printf(", early socket close");
|
||||
if(proxyhost!=NULL) printf(", via proxy server %s:%d",proxyhost,proxyport);
|
||||
if(force_reload) printf(", forcing reload");
|
||||
printf(".\n");
|
||||
return bench();
|
||||
}
|
||||
|
||||
void build_request(const char *url)
|
||||
{
|
||||
char tmp[10];
|
||||
int i;
|
||||
|
||||
bzero(host,MAXHOSTNAMELEN);
|
||||
bzero(request,REQUEST_SIZE);
|
||||
|
||||
if(force_reload && proxyhost!=NULL && http10<1) http10=1;
|
||||
if(method==METHOD_HEAD && http10<1) http10=1;
|
||||
if(method==METHOD_OPTIONS && http10<2) http10=2;
|
||||
if(method==METHOD_TRACE && http10<2) http10=2;
|
||||
|
||||
switch(method)
|
||||
{
|
||||
default:
|
||||
case METHOD_GET: strcpy(request,"GET");break;
|
||||
case METHOD_HEAD: strcpy(request,"HEAD");break;
|
||||
case METHOD_OPTIONS: strcpy(request,"OPTIONS");break;
|
||||
case METHOD_TRACE: strcpy(request,"TRACE");break;
|
||||
}
|
||||
|
||||
strcat(request," ");
|
||||
|
||||
if(NULL==strstr(url,"://"))
|
||||
{
|
||||
fprintf(stderr, "\n%s: is not a valid URL.\n",url);
|
||||
exit(2);
|
||||
}
|
||||
if(strlen(url)>1500)
|
||||
{
|
||||
fprintf(stderr,"URL is too long.\n");
|
||||
exit(2);
|
||||
}
|
||||
if(proxyhost==NULL)
|
||||
if (0!=strncasecmp("http://",url,7))
|
||||
{ fprintf(stderr,"\nOnly HTTP protocol is directly supported, set --proxy for others.\n");
|
||||
exit(2);
|
||||
}
|
||||
/* protocol/host delimiter */
|
||||
i=strstr(url,"://")-url+3;
|
||||
/* printf("%d\n",i); */
|
||||
|
||||
if(strchr(url+i,'/')==NULL) {
|
||||
fprintf(stderr,"\nInvalid URL syntax - hostname don't ends with '/'.\n");
|
||||
exit(2);
|
||||
}
|
||||
if(proxyhost==NULL)
|
||||
{
|
||||
/* get port from hostname */
|
||||
if(index(url+i,':')!=NULL &&
|
||||
index(url+i,':')<index(url+i,'/'))
|
||||
{
|
||||
strncpy(host,url+i,strchr(url+i,':')-url-i);
|
||||
bzero(tmp,10);
|
||||
strncpy(tmp,index(url+i,':')+1,strchr(url+i,'/')-index(url+i,':')-1);
|
||||
/* printf("tmp=%s\n",tmp); */
|
||||
proxyport=atoi(tmp);
|
||||
if(proxyport==0) proxyport=80;
|
||||
} else
|
||||
{
|
||||
strncpy(host,url+i,strcspn(url+i,"/"));
|
||||
}
|
||||
// printf("Host=%s\n",host);
|
||||
strcat(request+strlen(request),url+i+strcspn(url+i,"/"));
|
||||
} else
|
||||
{
|
||||
// printf("ProxyHost=%s\nProxyPort=%d\n",proxyhost,proxyport);
|
||||
strcat(request,url);
|
||||
}
|
||||
if(http10==1)
|
||||
strcat(request," HTTP/1.0");
|
||||
else if (http10==2)
|
||||
strcat(request," HTTP/1.1");
|
||||
strcat(request,"\r\n");
|
||||
if(http10>0)
|
||||
strcat(request,"User-Agent: WebBench "PROGRAM_VERSION"\r\n");
|
||||
if(proxyhost==NULL && http10>0)
|
||||
{
|
||||
strcat(request,"Host: ");
|
||||
strcat(request,host);
|
||||
strcat(request,"\r\n");
|
||||
}
|
||||
if(force_reload && proxyhost!=NULL)
|
||||
{
|
||||
strcat(request,"Pragma: no-cache\r\n");
|
||||
}
|
||||
if(http10>1)
|
||||
strcat(request,"Connection: close\r\n");
|
||||
/* add empty line at end */
|
||||
if(http10>0) strcat(request,"\r\n");
|
||||
// printf("Req=%s\n",request);
|
||||
}
|
||||
|
||||
/* vraci system rc error kod */
|
||||
static int bench(void)
|
||||
{
|
||||
int i,j,k;
|
||||
pid_t pid=0;
|
||||
FILE *f;
|
||||
#if ENABLE_NTYCO == 0
|
||||
/* check avaibility of target server */
|
||||
i=Socket(proxyhost==NULL?host:proxyhost,proxyport);
|
||||
if(i<0) {
|
||||
fprintf(stderr,"\nConnect to server failed. Aborting benchmark.\n");
|
||||
return 1;
|
||||
}
|
||||
close(i);
|
||||
#endif
|
||||
/* create pipe */
|
||||
if(pipe(mypipe))
|
||||
{
|
||||
perror("pipe failed.");
|
||||
return 3;
|
||||
}
|
||||
|
||||
/* not needed, since we have alarm() in childrens */
|
||||
/* wait 4 next system clock tick */
|
||||
/*
|
||||
cas=time(NULL);
|
||||
while(time(NULL)==cas)
|
||||
sched_yield();
|
||||
*/
|
||||
printf("bench enter\n");
|
||||
|
||||
/* fork childs */
|
||||
for(i=0;i<clients;i++)
|
||||
{
|
||||
pid=fork();
|
||||
if(pid <= (pid_t) 0)
|
||||
{
|
||||
/* child process or error*/
|
||||
sleep(1); /* make childs faster */
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if( pid< (pid_t) 0)
|
||||
{
|
||||
fprintf(stderr,"problems forking worker no. %d\n",i);
|
||||
perror("fork failed.");
|
||||
return 3;
|
||||
}
|
||||
|
||||
if(pid== (pid_t) 0)
|
||||
{
|
||||
/* I am a child */
|
||||
if(proxyhost==NULL)
|
||||
benchcore(host,proxyport,request);
|
||||
else
|
||||
benchcore(proxyhost,proxyport,request);
|
||||
|
||||
/* write results to pipe */
|
||||
f=fdopen(mypipe[1],"w");
|
||||
if(f==NULL)
|
||||
{
|
||||
perror("open pipe for writing failed.");
|
||||
return 3;
|
||||
}
|
||||
/* fprintf(stderr,"Child - %d %d\n",speed,failed); */
|
||||
fprintf(f,"%d %d %d\n",speed,failed,bytes);
|
||||
fclose(f);
|
||||
return 0;
|
||||
} else
|
||||
{
|
||||
f=fdopen(mypipe[0],"r");
|
||||
if(f==NULL)
|
||||
{
|
||||
perror("open pipe for reading failed.");
|
||||
return 3;
|
||||
}
|
||||
setvbuf(f,NULL,_IONBF,0);
|
||||
speed=0;
|
||||
failed=0;
|
||||
bytes=0;
|
||||
|
||||
while(1)
|
||||
{
|
||||
pid=fscanf(f,"%d %d %d",&i,&j,&k);
|
||||
if(pid<2)
|
||||
{
|
||||
fprintf(stderr,"Some of our childrens died.\n");
|
||||
break;
|
||||
}
|
||||
speed+=i;
|
||||
failed+=j;
|
||||
bytes+=k;
|
||||
/* fprintf(stderr,"*Knock* %d %d read=%d\n",speed,failed,pid); */
|
||||
if(--clients==0) break;
|
||||
}
|
||||
fclose(f);
|
||||
|
||||
printf("\nSpeed=%d pages/min, %d bytes/sec.\nRequests: %d susceed, %d failed.\n",
|
||||
(int)((speed+failed)/(benchtime/60.0f)),
|
||||
(int)(bytes/(float)benchtime),
|
||||
speed,
|
||||
failed);
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
struct serv_host {
|
||||
const char *host;
|
||||
const int port;
|
||||
const char *req;
|
||||
};
|
||||
|
||||
int testok(char *response) {
|
||||
if (response == NULL) return -1;
|
||||
|
||||
char* p;
|
||||
char* q;
|
||||
|
||||
p = strchr(response, '\n');
|
||||
*p = '\0';
|
||||
if(NULL != (q = strstr(response, "200 OK")))
|
||||
return 1;
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
int send_buffer(int sockfd, char *buffer, int length) {
|
||||
|
||||
int idx = 0;
|
||||
while (idx < length) {
|
||||
|
||||
int count = 0;
|
||||
if ((idx+MAX_BUFFER_LENGTH) < length) {
|
||||
count = send(sockfd, buffer+idx, MAX_BUFFER_LENGTH, 0);
|
||||
} else {
|
||||
count = send(sockfd, buffer+idx, length-idx, 0);
|
||||
}
|
||||
if (count < 0) break;
|
||||
|
||||
idx += count;
|
||||
}
|
||||
|
||||
return idx;
|
||||
|
||||
}
|
||||
|
||||
int recv_buffer(int sockfd, char *buffer, int length, int *ret) {
|
||||
|
||||
int idx = 0;
|
||||
|
||||
while (1) {
|
||||
|
||||
int count = recv(sockfd, buffer+idx, MAX_BUFFER_LENGTH, 0);
|
||||
//printf("sockfd : %d, recv_buffer --> %d\n", sockfd, count);
|
||||
if (count < 0) {
|
||||
*ret = -1;
|
||||
break;
|
||||
} else if (count == 0) {
|
||||
*ret = 0;
|
||||
close(sockfd);
|
||||
break;
|
||||
} else {
|
||||
//printf("sockfd : %d, recv_buffer --> %d\n", sockfd, count);
|
||||
idx += count;
|
||||
}
|
||||
}
|
||||
if (idx > 0) *ret = 1;
|
||||
|
||||
return idx;
|
||||
}
|
||||
|
||||
|
||||
void httprequest_commit(void *arg) {
|
||||
char buf[1500] = {0};
|
||||
struct serv_host *shost = (struct serv_host *)arg;
|
||||
|
||||
int slen = strlen(shost->req);
|
||||
|
||||
int idx = 0;
|
||||
for (idx = 0;idx < (nreqs / sockets);idx ++) {
|
||||
|
||||
int s = Socket(shost->host, shost->port);
|
||||
if (s < 0) {
|
||||
failed ++;
|
||||
continue ;
|
||||
}
|
||||
|
||||
if (slen != send(s, shost->req, slen, 0)) {
|
||||
failed ++;
|
||||
close(s);
|
||||
continue;
|
||||
}
|
||||
|
||||
memset(buf, 0, 1500);
|
||||
#if ENABLE_NTYCO
|
||||
int ret = 0;
|
||||
int rlen = recv_buffer(s, buf, 1500, &ret);
|
||||
#else
|
||||
int rlen = recv(s, buf, 1500, 0);
|
||||
#endif
|
||||
if (ret < 0) {
|
||||
failed ++;
|
||||
} else {
|
||||
|
||||
if (testok(buf)) {
|
||||
speed ++;
|
||||
|
||||
} else {
|
||||
failed ++;
|
||||
|
||||
}
|
||||
bytes += rlen;
|
||||
}
|
||||
}
|
||||
|
||||
return ;
|
||||
}
|
||||
|
||||
|
||||
void benchcore(const char *host,const int port,const char *req)
|
||||
{
|
||||
int rlen;
|
||||
char buf[1500];
|
||||
int s,i;
|
||||
struct sigaction sa;
|
||||
|
||||
/* setup alarm signal handler */
|
||||
sa.sa_handler=alarm_handler;
|
||||
sa.sa_flags=0;
|
||||
if(sigaction(SIGALRM,&sa,NULL))
|
||||
exit(3);
|
||||
alarm(benchtime);
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
|
||||
//int i = 0;
|
||||
nty_coroutine *co = NULL;
|
||||
struct serv_host shost = {host, port, req};
|
||||
|
||||
for (i = 0;i < sockets / clients;i ++) {
|
||||
|
||||
nty_coroutine_create(&co, httprequest_commit, &shost);
|
||||
}
|
||||
nty_schedule_run();
|
||||
|
||||
#else
|
||||
|
||||
rlen=strlen(req);
|
||||
nexttry:while(1)
|
||||
{
|
||||
if(timerexpired)
|
||||
{
|
||||
if(failed>0)
|
||||
{
|
||||
/* fprintf(stderr,"Correcting failed by signal\n"); */
|
||||
failed--;
|
||||
}
|
||||
return;
|
||||
}
|
||||
s=Socket(host,port);
|
||||
if(s<0) { failed++;continue;}
|
||||
if(rlen!=write(s, req, rlen)) {failed++;close(s);continue;}
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
if(http10==0)
|
||||
close(s);
|
||||
#else
|
||||
if(http10==0)
|
||||
if(shutdown(s,1)) { failed++;close(s);continue;}
|
||||
|
||||
#endif
|
||||
if(force==0)
|
||||
{
|
||||
/* read all available data from socket */
|
||||
while(1)
|
||||
{
|
||||
if(timerexpired) break;
|
||||
i=read(s,buf,1500);
|
||||
/* fprintf(stderr,"%d\n",i); */
|
||||
if(i<0)
|
||||
{
|
||||
failed++;
|
||||
close(s);
|
||||
goto nexttry;
|
||||
}
|
||||
else
|
||||
if(i==0) break;
|
||||
else
|
||||
bytes+=i;
|
||||
}
|
||||
}
|
||||
if(close(s)) {failed++;continue;}
|
||||
speed++;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
111
NtyCo/sample/nty_client.c
Normal file
111
NtyCo/sample/nty_client.c
Normal file
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Author : WangBoJing , email : 1989wangbojing@gmail.com
|
||||
*
|
||||
* Copyright Statement:
|
||||
* --------------------
|
||||
* This software is protected by Copyright and the information contained
|
||||
* herein is confidential. The software may not be copied and the information
|
||||
* contained herein may not be used or disclosed except with the written
|
||||
* permission of Author. (C) 2017
|
||||
*
|
||||
*
|
||||
|
||||
**** ***** *****
|
||||
*** * ** ***
|
||||
*** * * * **
|
||||
* ** * * ** **
|
||||
* ** * * ** *
|
||||
* ** * ** ** *
|
||||
* ** * *** **
|
||||
* ** * *********** ***** ***** ** ****
|
||||
* ** * ** ** ** ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * ** **
|
||||
* *** ** * * ** * ** **
|
||||
* *** ** * ** * * ** **
|
||||
* ** ** * ** ** * ** **
|
||||
* ** ** * * ** * ** **
|
||||
***** * **** * ***** ****
|
||||
*
|
||||
*
|
||||
*****
|
||||
****
|
||||
|
||||
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
|
||||
|
||||
|
||||
#define NTY_SERVER_IPADDR "127.0.0.1"
|
||||
#define NTY_SERVER_PORT 9096
|
||||
|
||||
int init_client(void) {
|
||||
|
||||
int clientfd = nty_socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (clientfd <= 0) {
|
||||
printf("socket failed\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct sockaddr_in serveraddr = {0};
|
||||
serveraddr.sin_family = AF_INET;
|
||||
serveraddr.sin_port = htons(NTY_SERVER_PORT);
|
||||
serveraddr.sin_addr.s_addr = inet_addr(NTY_SERVER_IPADDR);
|
||||
|
||||
int result = nty_connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));
|
||||
if (result != 0) {
|
||||
printf("connect failed\n");
|
||||
return -2;
|
||||
}
|
||||
|
||||
return clientfd;
|
||||
|
||||
}
|
||||
|
||||
void client(void *arg) {
|
||||
|
||||
int clientfd = init_client();
|
||||
char *buffer = "ntyco_client\r\n";
|
||||
|
||||
while (1) {
|
||||
|
||||
int length = nty_send(clientfd, buffer, strlen(buffer), 0);
|
||||
printf("echo length : %d\n", length);
|
||||
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
nty_coroutine *co = NULL;
|
||||
|
||||
nty_coroutine_create(&co, client, NULL);
|
||||
|
||||
nty_schedule_run(); //run
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
745
NtyCo/sample/nty_http_epoll.c
Normal file
745
NtyCo/sample/nty_http_epoll.c
Normal file
@@ -0,0 +1,745 @@
|
||||
/*
|
||||
* Author : WangBoJing , email : 1989wangbojing@gmail.com
|
||||
*
|
||||
* Copyright Statement:
|
||||
* --------------------
|
||||
* This software is protected by Copyright and the information contained
|
||||
* herein is confidential. The software may not be copied and the information
|
||||
* contained herein may not be used or disclosed except with the written
|
||||
* permission of Author. (C) 2017
|
||||
*
|
||||
*
|
||||
|
||||
**** ***** *****
|
||||
*** * ** ***
|
||||
*** * * * **
|
||||
* ** * * ** **
|
||||
* ** * * ** *
|
||||
* ** * ** ** *
|
||||
* ** * *** **
|
||||
* ** * *********** ***** ***** ** ****
|
||||
* ** * ** ** ** ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * ** **
|
||||
* *** ** * * ** * ** **
|
||||
* *** ** * ** * * ** **
|
||||
* ** ** * ** ** * ** **
|
||||
* ** ** * * ** * ** **
|
||||
***** * **** * ***** ****
|
||||
*
|
||||
*
|
||||
*****
|
||||
****
|
||||
|
||||
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/sysinfo.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/shm.h>
|
||||
#include <sys/sem.h>
|
||||
|
||||
#include <errno.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <sys/poll.h>
|
||||
|
||||
#define __USE_GNU
|
||||
|
||||
#include <sched.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#define MAX_CLIENT_NUM 1000000
|
||||
#define TOTALFDS 16
|
||||
|
||||
typedef struct _shm_area {
|
||||
int totalfds[TOTALFDS];
|
||||
char cpu_lb[TOTALFDS];
|
||||
//mtx : default 0
|
||||
// 1 : lock -- del epoll
|
||||
// 2 : lock -- del complete
|
||||
// 3 : unlock -- add
|
||||
// 0 : unlock -- add complete
|
||||
int accept_mtx;
|
||||
} shm_area;
|
||||
|
||||
static shm_area *global_shmaddr = NULL;
|
||||
static int global_shmid = -1;
|
||||
|
||||
int cpu_size = 0;
|
||||
int accept_disable = 1000;
|
||||
int enable_accept = 1;
|
||||
pid_t self_id = 0;
|
||||
|
||||
|
||||
|
||||
unsigned long cmpxchg(void *addr, unsigned long _old, unsigned long _new, int size) {
|
||||
unsigned long prev;
|
||||
volatile unsigned int *_ptr = (volatile unsigned int *)(addr);
|
||||
|
||||
switch (size) {
|
||||
case 1: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchgb %b1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchgw %w1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchg %1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return prev;
|
||||
}
|
||||
|
||||
int atomic_add(volatile int *value, int add)
|
||||
{
|
||||
__asm__ volatile (
|
||||
|
||||
"lock;"
|
||||
" addl %0, %1; "
|
||||
|
||||
: "+r" (add) : "m" (*value) : "cc", "memory");
|
||||
|
||||
return add;
|
||||
}
|
||||
|
||||
int atomic_sub(volatile int *value, int sub)
|
||||
{
|
||||
__asm__ volatile (
|
||||
|
||||
"lock;"
|
||||
" subl %0, %1; "
|
||||
|
||||
: "+r" (sub) : "m" (*value) : "cc", "memory");
|
||||
|
||||
return sub;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#define ISspace(x) isspace((int)(x))
|
||||
|
||||
#define SERVER_STRING "Server: ntyco_httpd/0.1.0\r\n"
|
||||
#define STDIN 0
|
||||
#define STDOUT 1
|
||||
#define STDERR 2
|
||||
|
||||
#define ENABLE_NTYCO 0
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
|
||||
#define socket nty_socket
|
||||
#define accept nty_accept
|
||||
#define recv(a, b, c, d) nty_recv(a, b, c, d)
|
||||
#define send(a, b, c, d) nty_send(a, b, c, d)
|
||||
|
||||
#define MAX_BUFFER_LENGTH 1024
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
#define INC_COUNTFD do { \
|
||||
atomic_add(&global_shmaddr->totalfds[self_id % cpu_size], 1); \
|
||||
} while (0)
|
||||
|
||||
|
||||
#define DEC_COUNTFD do { \
|
||||
atomic_sub(&global_shmaddr->totalfds[self_id % cpu_size], 1); \
|
||||
} while (0)
|
||||
|
||||
int get_countfd(void) {
|
||||
return global_shmaddr->totalfds[self_id % cpu_size];
|
||||
}
|
||||
|
||||
int max_countfd(void) {
|
||||
|
||||
int count = -1;
|
||||
int i = 0;
|
||||
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
if (count < global_shmaddr->totalfds[i]) {
|
||||
count = global_shmaddr->totalfds[i];
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
int min_countfd(void) {
|
||||
|
||||
int count = 0xffffffff;
|
||||
int i = 0;
|
||||
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
if (count > global_shmaddr->totalfds[i]) {
|
||||
count = global_shmaddr->totalfds[i];
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
int compare_out_countfd(void) {
|
||||
|
||||
int current = get_countfd();
|
||||
int min = min_countfd();
|
||||
|
||||
if ((current * 7 / 8) > min) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int compare_in_countfd(void) {
|
||||
|
||||
int current = get_countfd();
|
||||
int max = max_countfd();
|
||||
|
||||
if ((current * 8 / 7) < max) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void print_countfds(void) {
|
||||
|
||||
int i = 0;
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
printf("%5d : %5d ", i, global_shmaddr->totalfds[i]);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
void lock_accept(void) {
|
||||
|
||||
global_shmaddr->cpu_lb[self_id % cpu_size] = 1;
|
||||
|
||||
int count = 0xffffffff;
|
||||
int i = 0;
|
||||
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
if (count > global_shmaddr->totalfds[i]) {
|
||||
count = global_shmaddr->totalfds[i];
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
if (count == global_shmaddr->totalfds[i]) {
|
||||
global_shmaddr->cpu_lb[i] = 3;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
char read_accept(void) {
|
||||
return global_shmaddr->cpu_lb[self_id % cpu_size];
|
||||
}
|
||||
|
||||
void write_accept(char state) { //0, 1, 2, 3
|
||||
global_shmaddr->cpu_lb[self_id % cpu_size] = state;
|
||||
}
|
||||
|
||||
int lock(void) {
|
||||
|
||||
return cmpxchg(&global_shmaddr->accept_mtx, 0, 1, 4); //zero:success, non-zero:failed
|
||||
|
||||
}
|
||||
|
||||
void unlock(void) {
|
||||
|
||||
global_shmaddr->accept_mtx = 0;
|
||||
|
||||
}
|
||||
|
||||
|
||||
void accept_request(int fd, int epfd);
|
||||
void bad_request(int);
|
||||
void cat(int);
|
||||
void cannot_execute(int);
|
||||
void error_die(const char *);
|
||||
void execute_cgi(int, const char *, const char *, const char *);
|
||||
int get_line(int, char *, int);
|
||||
void headers(int);
|
||||
void not_found(int);
|
||||
void serve_file(int);
|
||||
int startup(u_short *);
|
||||
void unimplemented(int);
|
||||
|
||||
|
||||
ssize_t nsend(int fd, const void *buf, size_t len, int flags) {
|
||||
|
||||
int sent = 0;
|
||||
|
||||
int ret = send(fd, ((char*)buf)+sent, len-sent, flags);
|
||||
if (ret == 0) return ret;
|
||||
if (ret > 0) sent += ret;
|
||||
|
||||
while (sent < len) {
|
||||
#if 0
|
||||
struct pollfd fds;
|
||||
fds.fd = fd;
|
||||
fds.events = POLLIN | POLLERR | POLLHUP;
|
||||
poll(&fds, 1, -1);
|
||||
#endif
|
||||
ret = send(fd, ((char*)buf)+sent, len-sent, flags);
|
||||
//printf("send --> len : %d\n", ret);
|
||||
if (ret <= 0) {
|
||||
if (errno == EAGAIN) continue;
|
||||
|
||||
break;
|
||||
}
|
||||
sent += ret;
|
||||
}
|
||||
|
||||
if (ret <= 0 && sent == 0) return ret;
|
||||
|
||||
return sent;
|
||||
}
|
||||
|
||||
static int ntySetNonblock(int fd) {
|
||||
int flags;
|
||||
|
||||
flags = fcntl(fd, F_GETFL, 0);
|
||||
if (flags < 0) return flags;
|
||||
flags |= O_NONBLOCK;
|
||||
if (fcntl(fd, F_SETFL, flags) < 0) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ntySetReUseAddr(int fd) {
|
||||
int reuse = 1;
|
||||
return setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));
|
||||
}
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
/* A request has caused a call to accept() on the server port to
|
||||
* return. Process the request appropriately.
|
||||
* Parameters: the socket connected to the client */
|
||||
/**********************************************************************/
|
||||
void accept_request(int fd, int epfd)
|
||||
{
|
||||
int client = fd;
|
||||
|
||||
char buf[1024];
|
||||
size_t numchars;
|
||||
char method[16];
|
||||
char url[32];
|
||||
char path[64];
|
||||
size_t i, j;
|
||||
struct stat st;
|
||||
int cgi = 0; /* becomes true if server decides this is a CGI
|
||||
* program */
|
||||
char *query_string = NULL;
|
||||
|
||||
numchars = recv(client, buf, sizeof(buf), 0);
|
||||
if (numchars == -1) {
|
||||
//printf("recv errno : %d\n", errno);
|
||||
if (errno == ECONNRESET) {
|
||||
close(client);
|
||||
|
||||
struct epoll_event ev;
|
||||
ev.events = EPOLLIN | EPOLLET;
|
||||
ev.data.fd = client;
|
||||
epoll_ctl(epfd, EPOLL_CTL_DEL, client, &ev);
|
||||
|
||||
DEC_COUNTFD;
|
||||
}
|
||||
} else if (numchars == 0) {
|
||||
close(client);
|
||||
|
||||
struct epoll_event ev;
|
||||
ev.events = EPOLLIN | EPOLLET;
|
||||
ev.data.fd = client;
|
||||
epoll_ctl(epfd, EPOLL_CTL_DEL, client, &ev);
|
||||
|
||||
DEC_COUNTFD;
|
||||
} else {
|
||||
//printf("recv numchars : %ld\n", numchars);
|
||||
}
|
||||
//serve_file(client, path);
|
||||
|
||||
}
|
||||
|
||||
#if 0
|
||||
#define HTML_PAGE "<HTML> \
|
||||
<TITLE>Index</TITLE> \
|
||||
<BODY> \
|
||||
<P>Welcome to J. David's webserver.\
|
||||
<H1>CGI demo \
|
||||
<FORM ACTION=\"color.cgi\" METHOD=\"POST\">\
|
||||
Enter a color: <INPUT TYPE=\"text\" NAME=\"color\">\
|
||||
<INPUT TYPE=\"submit\">\
|
||||
</FORM>\
|
||||
</BODY>\
|
||||
</HTML>"
|
||||
|
||||
#else
|
||||
#define HTML_PAGE "<!DOCTYPE html> \
|
||||
<html> \
|
||||
<head> \
|
||||
<title>Welcome to nginx!</title> \
|
||||
<style> \
|
||||
body { \
|
||||
width: 35em;\
|
||||
margin: 0 auto;\
|
||||
font-family: Tahoma, Verdana, Arial, sans-serif;\
|
||||
}\
|
||||
</style>\
|
||||
</head>\
|
||||
<body>\
|
||||
<h1>Welcome to nginx!</h1>\
|
||||
<p>If you see this page, the nginx web server is successfully installed and\
|
||||
working. Further configuration is required.</p>\
|
||||
\
|
||||
<p>For online documentation and support please refer to\
|
||||
<a href=\"http://nginx.org/\">nginx.org</a>.<br/>\
|
||||
Commercial support is available at\
|
||||
<a href=\"http://nginx.com/\">nginx.com</a>.</p>\
|
||||
\
|
||||
<p><em>Thank you for using nginx.</em></p>\
|
||||
</body>\
|
||||
</html>"
|
||||
#endif
|
||||
|
||||
void cat(int client)
|
||||
{
|
||||
|
||||
//char buf[1024] = HTML_PAGE;
|
||||
|
||||
int ret = send(client, HTML_PAGE, strlen(HTML_PAGE), 0);
|
||||
if (ret == -1) {
|
||||
printf("send : errno : %d\n", errno);
|
||||
} else {
|
||||
printf("cat send ret : %d\n", ret);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void error_die(const char *sc)
|
||||
{
|
||||
printf("%s\n", sc);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
void headers(int client)
|
||||
{
|
||||
char buf[1024] = {0};
|
||||
char content[128] = {0};
|
||||
|
||||
sprintf(buf, "HTTP/1.0 200 OK\r\n");
|
||||
strcat(buf, SERVER_STRING);
|
||||
strcat(buf, "Content-Type: text/html\r\n");
|
||||
#if 0
|
||||
strcat(buf, "Transfer-Encoding: chunked\r\n");
|
||||
#else
|
||||
sprintf(content, "Content-Length: %ld\r\n", strlen(HTML_PAGE));
|
||||
strcat(buf, content);
|
||||
#endif
|
||||
strcat(buf, "\r\n");
|
||||
|
||||
strcat(buf, HTML_PAGE);
|
||||
|
||||
int ret = send(client, buf, strlen(buf), 0);
|
||||
if (ret == -1) {
|
||||
printf("send : errno : %d\n", errno);
|
||||
} else {
|
||||
//printf("headers send ret : %d\n", ret);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Send a regular file to the client. Use headers, and report
|
||||
* errors to client if they occur.
|
||||
* Parameters: a pointer to a file structure produced from the socket
|
||||
* file descriptor
|
||||
* the name of the file to serve */
|
||||
/**********************************************************************/
|
||||
void serve_file(int client)
|
||||
{
|
||||
headers(client);
|
||||
//cat(client);
|
||||
|
||||
}
|
||||
|
||||
#define MAX_EPOLLSIZE 10240
|
||||
|
||||
void server(void *arg) {
|
||||
|
||||
int fd = *(int *)arg;
|
||||
|
||||
int epfd = epoll_create(1);
|
||||
struct epoll_event events[MAX_EPOLLSIZE];
|
||||
|
||||
struct epoll_event ev;
|
||||
ev.events = EPOLLIN;
|
||||
ev.data.fd = fd;
|
||||
epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
|
||||
int acc = 1; //
|
||||
|
||||
while (1) {
|
||||
#if 0
|
||||
char lock = read_accept();
|
||||
if (lock == 1) { //lock
|
||||
ev.events = EPOLLIN;
|
||||
ev.data.fd = fd;
|
||||
epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &ev);
|
||||
|
||||
write_accept(2); //add complete
|
||||
|
||||
} else if (acc == 0 && lock == 3) {
|
||||
ev.events = EPOLLIN;
|
||||
ev.data.fd = fd;
|
||||
epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
|
||||
|
||||
write_accept(0);
|
||||
}
|
||||
#endif
|
||||
int nready = epoll_wait(epfd, events, MAX_EPOLLSIZE, 1);
|
||||
if (nready == -1) {
|
||||
if (errno == EINTR) {
|
||||
printf("errno : EINTR\n");
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
for (i = 0;i < nready;i ++) {
|
||||
int sockfd = events[i].data.fd;
|
||||
if (sockfd == fd) {
|
||||
|
||||
struct sockaddr_in client_addr;
|
||||
memset(&client_addr, 0, sizeof(struct sockaddr_in));
|
||||
socklen_t client_len = sizeof(client_addr);
|
||||
#if 0
|
||||
if (get_countfd() % accept_disable == 999) {
|
||||
lock_accept();
|
||||
acc = 0;
|
||||
}
|
||||
char lock = read_accept();
|
||||
if (lock != 0 && lock != 3) continue;
|
||||
#endif
|
||||
if (lock()) {
|
||||
continue;
|
||||
}
|
||||
int clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &client_len);
|
||||
unlock();
|
||||
|
||||
if (clientfd < 0) {
|
||||
if (errno == EAGAIN) {
|
||||
//printf("accept : EAGAIN\n");
|
||||
continue;
|
||||
} else if (errno == ECONNABORTED) {
|
||||
printf("accept : ECONNABORTED\n");
|
||||
|
||||
} else if (errno == EMFILE || errno == ENFILE) {
|
||||
printf("accept : EMFILE || ENFILE\n");
|
||||
}
|
||||
return ;
|
||||
}
|
||||
|
||||
INC_COUNTFD;
|
||||
|
||||
ntySetNonblock(clientfd);
|
||||
ntySetReUseAddr(clientfd);
|
||||
|
||||
struct epoll_event ev;
|
||||
ev.events = EPOLLIN | EPOLLET | EPOLLONESHOT;
|
||||
ev.data.fd = clientfd;
|
||||
epoll_ctl(epfd, EPOLL_CTL_ADD, clientfd, &ev);
|
||||
|
||||
}
|
||||
else if (events[i].events & EPOLLIN) {
|
||||
|
||||
accept_request(sockfd, epfd);
|
||||
#if 1
|
||||
//struct epoll_event ev;
|
||||
ev.events = EPOLLOUT | EPOLLET | EPOLLONESHOT;
|
||||
ev.data.fd = sockfd;
|
||||
epoll_ctl(epfd, EPOLL_CTL_MOD, sockfd, &ev);
|
||||
|
||||
//close(sockfd);
|
||||
#endif
|
||||
}
|
||||
else if (events[i].events & EPOLLOUT) {
|
||||
|
||||
serve_file(sockfd);
|
||||
|
||||
//close(sockfd);
|
||||
|
||||
//struct epoll_event ev;
|
||||
ev.events = EPOLLIN | EPOLLHUP | EPOLLRDHUP | EPOLLERR;
|
||||
ev.data.fd = sockfd;
|
||||
epoll_ctl(epfd, EPOLL_CTL_MOD, sockfd, &ev);
|
||||
|
||||
DEC_COUNTFD;
|
||||
|
||||
}
|
||||
else if (events[i].events & (EPOLLHUP|EPOLLRDHUP|EPOLLERR)) {
|
||||
|
||||
close(sockfd);
|
||||
|
||||
printf(" EPOLLHUP | EPOLLRDHUP\n");
|
||||
//struct epoll_event ev;
|
||||
ev.events = EPOLLIN | EPOLLET | EPOLLONESHOT;
|
||||
ev.data.fd = sockfd;
|
||||
epoll_ctl(epfd, EPOLL_CTL_DEL, sockfd, &ev);
|
||||
|
||||
DEC_COUNTFD;
|
||||
}
|
||||
}
|
||||
|
||||
// print_countfds();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int mulcore_entry(int begin_port) {
|
||||
|
||||
int i = 0;
|
||||
unsigned short base_port = begin_port;
|
||||
|
||||
unsigned short *port = calloc(1, sizeof(unsigned short));
|
||||
*port = base_port;
|
||||
server(port);
|
||||
|
||||
}
|
||||
|
||||
int process_bind(int fd) {
|
||||
|
||||
int num = sysconf(_SC_NPROCESSORS_CONF);
|
||||
|
||||
self_id = syscall(__NR_gettid);
|
||||
//printf("selfid --> %d\n", self_id);
|
||||
|
||||
cpu_set_t mask;
|
||||
|
||||
CPU_ZERO(&mask);
|
||||
CPU_SET(self_id % num, &mask);
|
||||
|
||||
sched_setaffinity(0, sizeof(mask), &mask);
|
||||
server(&fd);
|
||||
//mulcore_entry(9000);
|
||||
|
||||
}
|
||||
|
||||
int init_shmvalue(int num) {
|
||||
|
||||
global_shmid = shmget(IPC_PRIVATE, sizeof(shm_area), IPC_CREAT|0600);
|
||||
if (global_shmid < 0) {
|
||||
perror("shmget failed\n");
|
||||
return -1;
|
||||
}
|
||||
global_shmaddr = (shm_area*)shmat(global_shmid, NULL, 0);
|
||||
if (global_shmaddr == (shm_area*)-1) {
|
||||
perror("shmat addr error");
|
||||
return -1;
|
||||
}
|
||||
memset(global_shmaddr->totalfds, 0, TOTALFDS * sizeof(int));
|
||||
memset(global_shmaddr->cpu_lb, 0, TOTALFDS * sizeof(char));
|
||||
global_shmaddr->accept_mtx = 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
short port = 9000;
|
||||
struct sockaddr_in client_name;
|
||||
socklen_t client_name_len = sizeof(client_name);
|
||||
|
||||
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) return -1;
|
||||
|
||||
ntySetNonblock(fd);
|
||||
ntySetReUseAddr(fd);
|
||||
|
||||
|
||||
struct sockaddr_in local, remote;
|
||||
local.sin_family = AF_INET;
|
||||
local.sin_port = htons(port);
|
||||
local.sin_addr.s_addr = INADDR_ANY;
|
||||
bind(fd, (struct sockaddr*)&local, sizeof(struct sockaddr_in));
|
||||
|
||||
listen(fd, 20);
|
||||
|
||||
int num = sysconf(_SC_NPROCESSORS_CONF);
|
||||
cpu_size = num;
|
||||
init_shmvalue(num);
|
||||
|
||||
int i = 0;
|
||||
pid_t pid=0;
|
||||
for(i = 0;i < num;i ++) {
|
||||
pid=fork();
|
||||
if(pid <= (pid_t) 0)
|
||||
{
|
||||
usleep(1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
#if 1
|
||||
if (pid > 0) {
|
||||
printf("ntyco_httpd server running ...\n");
|
||||
getchar();
|
||||
} else if (pid == 0) {
|
||||
process_bind(fd);
|
||||
}
|
||||
#else
|
||||
|
||||
|
||||
INC_COUNTFD;
|
||||
|
||||
INC_COUNTFD;
|
||||
print_countfds();
|
||||
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
634
NtyCo/sample/nty_http_server.c
Normal file
634
NtyCo/sample/nty_http_server.c
Normal file
@@ -0,0 +1,634 @@
|
||||
/*
|
||||
* Author : WangBoJing , email : 1989wangbojing@gmail.com
|
||||
*
|
||||
* Copyright Statement:
|
||||
* --------------------
|
||||
* This software is protected by Copyright and the information contained
|
||||
* herein is confidential. The software may not be copied and the information
|
||||
* contained herein may not be used or disclosed except with the written
|
||||
* permission of Author. (C) 2017
|
||||
*
|
||||
*
|
||||
|
||||
**** ***** *****
|
||||
*** * ** ***
|
||||
*** * * * **
|
||||
* ** * * ** **
|
||||
* ** * * ** *
|
||||
* ** * ** ** *
|
||||
* ** * *** **
|
||||
* ** * *********** ***** ***** ** ****
|
||||
* ** * ** ** ** ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * ** **
|
||||
* *** ** * * ** * ** **
|
||||
* *** ** * ** * * ** **
|
||||
* ** ** * ** ** * ** **
|
||||
* ** ** * * ** * ** **
|
||||
***** * **** * ***** ****
|
||||
*
|
||||
*
|
||||
*****
|
||||
****
|
||||
|
||||
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
/* J. David's webserver */
|
||||
/* This is a simple webserver.
|
||||
* Created November 1999 by J. David Blackstone.
|
||||
* CSE 4344 (Network concepts), Prof. Zeigler
|
||||
* University of Texas at Arlington
|
||||
*/
|
||||
/* This program compiles for Sparc Solaris 2.6.
|
||||
* To compile for Linux:
|
||||
* 1) Comment out the #include <pthread.h> line.
|
||||
* 2) Comment out the line that defines the variable newthread.
|
||||
* 3) Comment out the two lines that run pthread_create().
|
||||
* 4) Uncomment the line that runs accept_request().
|
||||
* 5) Remove -lsocket from the Makefile.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <unistd.h>
|
||||
#include <ctype.h>
|
||||
#include <strings.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <pthread.h>
|
||||
#include <sys/wait.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#define ISspace(x) isspace((int)(x))
|
||||
|
||||
#define SERVER_STRING "Server: ntyco_httpd/0.1.0\r\n"
|
||||
#define STDIN 0
|
||||
#define STDOUT 1
|
||||
#define STDERR 2
|
||||
|
||||
#define ENABLE_NTYCO 1
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
#define socket nty_socket
|
||||
#define accept nty_accept
|
||||
#define recv(a, b, c, d) nty_recv(a, b, c, d)
|
||||
#define send(a, b, c, d) nty_send(a, b, c, d)
|
||||
|
||||
#define MAX_BUFFER_LENGTH 1024
|
||||
|
||||
#endif
|
||||
|
||||
void accept_request(void *);
|
||||
void bad_request(int);
|
||||
void cat(int, FILE *);
|
||||
void cannot_execute(int);
|
||||
void error_die(const char *);
|
||||
void execute_cgi(int, const char *, const char *, const char *);
|
||||
int get_line(int, char *, int);
|
||||
void headers(int, const char *);
|
||||
void not_found(int);
|
||||
void serve_file(int, const char *);
|
||||
int startup(u_short *);
|
||||
void unimplemented(int);
|
||||
|
||||
int readline(char* allbuf,int level,char* linebuf){
|
||||
int len = strlen(allbuf);
|
||||
|
||||
for (;level < len; ++level) {
|
||||
if(allbuf[level]=='\r' && allbuf[level+1]=='\n')
|
||||
return level+2;
|
||||
else
|
||||
*(linebuf++) = allbuf[level];
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
/* A request has caused a call to accept() on the server port to
|
||||
* return. Process the request appropriately.
|
||||
* Parameters: the socket connected to the client */
|
||||
/**********************************************************************/
|
||||
void accept_request(void *arg)
|
||||
{
|
||||
int *pclient = (int*)arg;
|
||||
int client = *pclient;
|
||||
|
||||
char buf[1024];
|
||||
size_t numchars;
|
||||
char method[255];
|
||||
char url[255];
|
||||
char path[512];
|
||||
size_t i, j;
|
||||
struct stat st;
|
||||
int cgi = 0; /* becomes true if server decides this is a CGI
|
||||
* program */
|
||||
char *query_string = NULL;
|
||||
|
||||
numchars = nty_recv(client, buf, sizeof(buf), 0);
|
||||
|
||||
i = 0; j = 0;
|
||||
while (!ISspace(buf[i]) && (i < sizeof(method) - 1))
|
||||
{
|
||||
method[i] = buf[i];
|
||||
i++;
|
||||
}
|
||||
j=i;
|
||||
method[i] = '\0';
|
||||
|
||||
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
|
||||
{
|
||||
unimplemented(client);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcasecmp(method, "POST") == 0)
|
||||
cgi = 1;
|
||||
|
||||
i = 0;
|
||||
while (ISspace(buf[j]) && (j < numchars))
|
||||
j++;
|
||||
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < numchars))
|
||||
{
|
||||
url[i] = buf[j];
|
||||
i++; j++;
|
||||
}
|
||||
url[i] = '\0';
|
||||
|
||||
if (strcasecmp(method, "GET") == 0)
|
||||
{
|
||||
query_string = url;
|
||||
while ((*query_string != '?') && (*query_string != '\0'))
|
||||
query_string++;
|
||||
if (*query_string == '?')
|
||||
{
|
||||
cgi = 1;
|
||||
*query_string = '\0';
|
||||
query_string++;
|
||||
}
|
||||
}
|
||||
|
||||
sprintf(path, "htdocs%s", url);
|
||||
if (path[strlen(path) - 1] == '/')
|
||||
strcat(path, "index.html");
|
||||
if (stat(path, &st) == -1) {
|
||||
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
not_found(client);
|
||||
}
|
||||
else
|
||||
{
|
||||
if ((st.st_mode & S_IFMT) == S_IFDIR)
|
||||
strcat(path, "/index.html");
|
||||
if ((st.st_mode & S_IXUSR) ||
|
||||
(st.st_mode & S_IXGRP) ||
|
||||
(st.st_mode & S_IXOTH) )
|
||||
cgi = 1;
|
||||
|
||||
cgi = 0;
|
||||
|
||||
if (!cgi)
|
||||
serve_file(client, path);
|
||||
else
|
||||
execute_cgi(client, path, method, query_string);
|
||||
}
|
||||
|
||||
nty_close(client);
|
||||
free(pclient);
|
||||
}
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
/* Inform the client that a request it has made has a problem.
|
||||
* Parameters: client socket */
|
||||
/**********************************************************************/
|
||||
void bad_request(int client)
|
||||
{
|
||||
char buf[1024];
|
||||
|
||||
sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
sprintf(buf, "Content-type: text/html\r\n");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
sprintf(buf, "\r\n");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
sprintf(buf, "<P>Your browser sent a bad request, ");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
sprintf(buf, "such as a POST without a Content-Length.\r\n");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Put the entire contents of a file out on a socket. This function
|
||||
* is named after the UNIX "cat" command, because it might have been
|
||||
* easier just to do something like pipe, fork, and exec("cat").
|
||||
* Parameters: the client socket descriptor
|
||||
* FILE pointer for the file to cat */
|
||||
/**********************************************************************/
|
||||
void cat(int client, FILE *resource)
|
||||
{
|
||||
char buf[1024];
|
||||
|
||||
char *ch = fgets(buf, sizeof(buf), resource);
|
||||
while (!feof(resource))
|
||||
{
|
||||
send(client, buf, strlen(buf), 0);
|
||||
ch = fgets(buf, sizeof(buf), resource);
|
||||
}
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Inform the client that a CGI script could not be executed.
|
||||
* Parameter: the client socket descriptor. */
|
||||
/**********************************************************************/
|
||||
void cannot_execute(int client)
|
||||
{
|
||||
char buf[1024];
|
||||
|
||||
sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "Content-type: text/html\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<P>Error prohibited CGI execution.\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Print out an error message with perror() (for system errors; based
|
||||
* on value of errno, which indicates system call errors) and exit the
|
||||
* program indicating an error. */
|
||||
/**********************************************************************/
|
||||
void error_die(const char *sc)
|
||||
{
|
||||
perror(sc);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Execute a CGI script. Will need to set environment variables as
|
||||
* appropriate.
|
||||
* Parameters: client socket descriptor
|
||||
* path to the CGI script */
|
||||
/**********************************************************************/
|
||||
void execute_cgi(int client, const char *path,
|
||||
const char *method, const char *query_string)
|
||||
{
|
||||
char buf[1024];
|
||||
int cgi_output[2];
|
||||
int cgi_input[2];
|
||||
pid_t pid;
|
||||
int status;
|
||||
int i;
|
||||
char c;
|
||||
int numchars = 1;
|
||||
int content_length = -1;
|
||||
|
||||
buf[0] = 'A'; buf[1] = '\0';
|
||||
if (strcasecmp(method, "GET") == 0)
|
||||
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
else if (strcasecmp(method, "POST") == 0) /*POST*/
|
||||
{
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
while ((numchars > 0) && strcmp("\n", buf))
|
||||
{
|
||||
buf[15] = '\0';
|
||||
if (strcasecmp(buf, "Content-Length:") == 0)
|
||||
content_length = atoi(&(buf[16]));
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
}
|
||||
if (content_length == -1) {
|
||||
bad_request(client);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else/*HEAD or other*/
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
if (pipe(cgi_output) < 0) {
|
||||
cannot_execute(client);
|
||||
return;
|
||||
}
|
||||
if (pipe(cgi_input) < 0) {
|
||||
cannot_execute(client);
|
||||
return;
|
||||
}
|
||||
|
||||
if ( (pid = fork()) < 0 ) {
|
||||
cannot_execute(client);
|
||||
return;
|
||||
}
|
||||
sprintf(buf, "HTTP/1.0 200 OK\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
if (pid == 0) /* child: CGI script */
|
||||
{
|
||||
char meth_env[255];
|
||||
char query_env[255];
|
||||
char length_env[255];
|
||||
|
||||
dup2(cgi_output[1], STDOUT);
|
||||
dup2(cgi_input[0], STDIN);
|
||||
close(cgi_output[0]);
|
||||
close(cgi_input[1]);
|
||||
sprintf(meth_env, "REQUEST_METHOD=%s", method);
|
||||
putenv(meth_env);
|
||||
if (strcasecmp(method, "GET") == 0) {
|
||||
sprintf(query_env, "QUERY_STRING=%s", query_string);
|
||||
putenv(query_env);
|
||||
}
|
||||
else { /* POST */
|
||||
sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
|
||||
putenv(length_env);
|
||||
}
|
||||
execl(path, "", NULL);
|
||||
exit(0);
|
||||
} else { /* parent */
|
||||
close(cgi_output[1]);
|
||||
close(cgi_input[0]);
|
||||
if (strcasecmp(method, "POST") == 0)
|
||||
for (i = 0; i < content_length; i++) {
|
||||
recv(client, &c, 1, 0);
|
||||
int len = write(cgi_input[1], &c, 1);
|
||||
}
|
||||
while (read(cgi_output[0], &c, 1) > 0)
|
||||
send(client, &c, 1, 0);
|
||||
|
||||
close(cgi_output[0]);
|
||||
close(cgi_input[1]);
|
||||
waitpid(pid, &status, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Get a line from a socket, whether the line ends in a newline,
|
||||
* carriage return, or a CRLF combination. Terminates the string read
|
||||
* with a null character. If no newline indicator is found before the
|
||||
* end of the buffer, the string is terminated with a null. If any of
|
||||
* the above three line terminators is read, the last character of the
|
||||
* string will be a linefeed and the string will be terminated with a
|
||||
* null character.
|
||||
* Parameters: the socket descriptor
|
||||
* the buffer to save the data in
|
||||
* the size of the buffer
|
||||
* Returns: the number of bytes stored (excluding null) */
|
||||
/**********************************************************************/
|
||||
int get_line(int sock, char *buf, int size)
|
||||
{
|
||||
int i = 0;
|
||||
char c = '\0';
|
||||
int n;
|
||||
|
||||
while ((i < size - 1) && (c != '\n'))
|
||||
{
|
||||
|
||||
n = recv(sock, &c, 1, 0);
|
||||
|
||||
if (n > 0)
|
||||
{
|
||||
if (c == '\r')
|
||||
{
|
||||
n = recv(sock, &c, 1, MSG_PEEK);
|
||||
|
||||
if ((n > 0) && (c == '\n'))
|
||||
recv(sock, &c, 1, 0);
|
||||
else
|
||||
c = '\n';
|
||||
}
|
||||
buf[i] = c;
|
||||
i++;
|
||||
}
|
||||
else
|
||||
c = '\n';
|
||||
}
|
||||
buf[i] = '\0';
|
||||
|
||||
return(i);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Return the informational HTTP headers about a file. */
|
||||
/* Parameters: the socket to print the headers on
|
||||
* the name of the file */
|
||||
/**********************************************************************/
|
||||
void headers(int client, const char *filename)
|
||||
{
|
||||
char buf[1024];
|
||||
(void)filename; /* could use filename to determine file type */
|
||||
|
||||
strcpy(buf, "HTTP/1.0 200 OK\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
strcpy(buf, SERVER_STRING);
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "Content-Type: text/html\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
strcpy(buf, "\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Give a client a 404 not found status message. */
|
||||
/**********************************************************************/
|
||||
void not_found(int client)
|
||||
{
|
||||
char buf[1024];
|
||||
|
||||
sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, SERVER_STRING);
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "Content-Type: text/html\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<BODY><P>The server could not fulfill\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "your request because the resource specified\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "is unavailable or nonexistent.\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "</BODY></HTML>\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Send a regular file to the client. Use headers, and report
|
||||
* errors to client if they occur.
|
||||
* Parameters: a pointer to a file structure produced from the socket
|
||||
* file descriptor
|
||||
* the name of the file to serve */
|
||||
/**********************************************************************/
|
||||
void serve_file(int client, const char *filename)
|
||||
{
|
||||
FILE *resource = NULL;
|
||||
int numchars = 1;
|
||||
char buf[1024];
|
||||
|
||||
#if (ENABLE_NTYCO == 0)
|
||||
buf[0] = 'A'; buf[1] = '\0';
|
||||
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
#endif
|
||||
|
||||
resource = fopen(filename, "r");
|
||||
if (resource == NULL)
|
||||
not_found(client);
|
||||
else
|
||||
{
|
||||
headers(client, filename);
|
||||
cat(client, resource);
|
||||
}
|
||||
fclose(resource);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* This function starts the process of listening for web connections
|
||||
* on a specified port. If the port is 0, then dynamically allocate a
|
||||
* port and modify the original port variable to reflect the actual
|
||||
* port.
|
||||
* Parameters: pointer to variable containing the port to connect on
|
||||
* Returns: the socket */
|
||||
/**********************************************************************/
|
||||
int startup(u_short *port)
|
||||
{
|
||||
int httpd = 0;
|
||||
int on = 1;
|
||||
struct sockaddr_in name;
|
||||
|
||||
httpd = socket(PF_INET, SOCK_STREAM, 0);
|
||||
if (httpd == -1)
|
||||
error_die("socket");
|
||||
memset(&name, 0, sizeof(name));
|
||||
name.sin_family = AF_INET;
|
||||
name.sin_port = htons(*port);
|
||||
name.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
if ((setsockopt(httpd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) < 0)
|
||||
{
|
||||
error_die("setsockopt failed");
|
||||
}
|
||||
if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
|
||||
error_die("bind");
|
||||
if (*port == 0) /* if dynamically allocating a port */
|
||||
{
|
||||
socklen_t namelen = sizeof(name);
|
||||
if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
|
||||
error_die("getsockname");
|
||||
*port = ntohs(name.sin_port);
|
||||
}
|
||||
if (listen(httpd, 5) < 0)
|
||||
error_die("listen");
|
||||
|
||||
|
||||
return(httpd);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Inform the client that the requested web method has not been
|
||||
* implemented.
|
||||
* Parameter: the client socket */
|
||||
/**********************************************************************/
|
||||
void unimplemented(int client)
|
||||
{
|
||||
char buf[1024];
|
||||
|
||||
sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, SERVER_STRING);
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "Content-Type: text/html\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "</TITLE></HEAD>\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "</BODY></HTML>\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
|
||||
|
||||
void server(void *arg)
|
||||
{
|
||||
int server_sock = -1;
|
||||
u_short port = 4000;
|
||||
struct sockaddr_in client_name;
|
||||
socklen_t client_name_len = sizeof(client_name);
|
||||
|
||||
server_sock = startup(&port);
|
||||
printf("httpd running on port %d\n", port);
|
||||
|
||||
while (1)
|
||||
{
|
||||
int *client_sock = (int *)malloc(sizeof(int));
|
||||
*client_sock = accept(server_sock,
|
||||
(struct sockaddr *)&client_name,
|
||||
&client_name_len);
|
||||
if (*client_sock == -1)
|
||||
error_die("accept");
|
||||
/* accept_request(&client_sock); */
|
||||
#if 1 //ENABLE_NTYCO
|
||||
|
||||
printf(" %d.%d.%d.%d:%d clientfd:%d --> New Client Connected \n",
|
||||
*(unsigned char*)(&client_name.sin_addr.s_addr), *((unsigned char*)(&client_name.sin_addr.s_addr)+1),
|
||||
*((unsigned char*)(&client_name.sin_addr.s_addr)+2), *((unsigned char*)(&client_name.sin_addr.s_addr)+3),
|
||||
client_name.sin_port, *client_sock);
|
||||
|
||||
nty_coroutine *read_co;
|
||||
nty_coroutine_create(&read_co, accept_request, client_sock);
|
||||
|
||||
#else
|
||||
pthread_t newthread;
|
||||
if (pthread_create(&newthread , NULL, (void *)accept_request, (void *)(intptr_t)client_sock) != 0)
|
||||
perror("pthread_create");
|
||||
#endif
|
||||
}
|
||||
|
||||
nty_close(server_sock);
|
||||
|
||||
return ;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
nty_coroutine_create(&co, server, 0); ////////no run
|
||||
|
||||
|
||||
nty_schedule_run(); //run
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
891
NtyCo/sample/nty_http_server_mulcore.c
Normal file
891
NtyCo/sample/nty_http_server_mulcore.c
Normal file
@@ -0,0 +1,891 @@
|
||||
/*
|
||||
* Author : WangBoJing , email : 1989wangbojing@gmail.com
|
||||
*
|
||||
* Copyright Statement:
|
||||
* --------------------
|
||||
* This software is protected by Copyright and the information contained
|
||||
* herein is confidential. The software may not be copied and the information
|
||||
* contained herein may not be used or disclosed except with the written
|
||||
* permission of Author. (C) 2017
|
||||
*
|
||||
*
|
||||
|
||||
**** ***** *****
|
||||
*** * ** ***
|
||||
*** * * * **
|
||||
* ** * * ** **
|
||||
* ** * * ** *
|
||||
* ** * ** ** *
|
||||
* ** * *** **
|
||||
* ** * *********** ***** ***** ** ****
|
||||
* ** * ** ** ** ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * ** **
|
||||
* *** ** * * ** * ** **
|
||||
* *** ** * ** * * ** **
|
||||
* ** ** * ** ** * ** **
|
||||
* ** ** * * ** * ** **
|
||||
***** * **** * ***** ****
|
||||
*
|
||||
*
|
||||
*****
|
||||
****
|
||||
|
||||
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <sys/sysinfo.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
#include <sys/stat.h>
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/shm.h>
|
||||
#include <sys/sem.h>
|
||||
|
||||
|
||||
#define __USE_GNU
|
||||
|
||||
#include <sched.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
static int global_shmid = -1;
|
||||
static int global_semid = -1;
|
||||
|
||||
#define TIME_SUB_MS(tv1, tv2) ((tv1.tv_sec - tv2.tv_sec) * 1000 + (tv1.tv_usec - tv2.tv_usec) / 1000)
|
||||
|
||||
|
||||
typedef struct _shm_area {
|
||||
int total;
|
||||
int accept_lock;
|
||||
struct timeval tv_begin;
|
||||
} shm_area;
|
||||
|
||||
static shm_area *global_shmaddr = NULL;
|
||||
|
||||
|
||||
#define MAX_CLIENT_NUM 1000000
|
||||
|
||||
|
||||
struct timeval* get_shm_timevalue(void);
|
||||
void set_shm_timevalue(struct timeval *tv);
|
||||
|
||||
|
||||
int add_shmvalue(void);
|
||||
int sub_shmvalue(void);
|
||||
|
||||
int init_shmvalue(void);
|
||||
|
||||
int lock_accept_mutex(void);
|
||||
int unlock_accept_mutex(void);
|
||||
|
||||
|
||||
|
||||
|
||||
unsigned long cmpxchg(void *addr, unsigned long _old, unsigned long _new, int size) {
|
||||
unsigned long prev;
|
||||
volatile unsigned int *_ptr = (volatile unsigned int *)(addr);
|
||||
|
||||
switch (size) {
|
||||
case 1: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchgb %b1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchgw %w1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchg %1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return prev;
|
||||
}
|
||||
|
||||
|
||||
#define ISspace(x) isspace((int)(x))
|
||||
|
||||
#define SERVER_STRING "Server: ntyco_httpd/0.1.0\r\n"
|
||||
#define STDIN 0
|
||||
#define STDOUT 1
|
||||
#define STDERR 2
|
||||
|
||||
#define ENABLE_NTYCO 1
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
|
||||
#define socket nty_socket
|
||||
#define accept nty_accept
|
||||
#define recv(a, b, c, d) nty_recv(a, b, c, d)
|
||||
#define send(a, b, c, d) nty_send(a, b, c, d)
|
||||
#define close(a) nty_close(a)
|
||||
|
||||
#define MAX_BUFFER_LENGTH 1024
|
||||
|
||||
#endif
|
||||
|
||||
void accept_request(void *);
|
||||
void bad_request(int);
|
||||
void cat(int, FILE *);
|
||||
void cannot_execute(int);
|
||||
void error_die(const char *);
|
||||
void execute_cgi(int, const char *, const char *, const char *);
|
||||
int get_line(int, char *, int);
|
||||
void headers(int, const char *);
|
||||
void not_found(int);
|
||||
void serve_file(int, const char *);
|
||||
int startup(u_short *);
|
||||
void unimplemented(int);
|
||||
|
||||
int readline(char* allbuf, int level, char* linebuf) {
|
||||
int len = strlen(allbuf);
|
||||
|
||||
for (;level < len; ++level) {
|
||||
if(allbuf[level]=='\r' && allbuf[level+1]=='\n')
|
||||
return level+2;
|
||||
else
|
||||
*(linebuf++) = allbuf[level];
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
/* A request has caused a call to accept() on the server port to
|
||||
* return. Process the request appropriately.
|
||||
* Parameters: the socket connected to the client */
|
||||
/**********************************************************************/
|
||||
void accept_request(void *arg)
|
||||
{
|
||||
int *pclient = (int*)arg;
|
||||
int client = *pclient;
|
||||
|
||||
char buf[1024];
|
||||
size_t numchars;
|
||||
char method[16];
|
||||
char url[32];
|
||||
char path[64];
|
||||
size_t i, j;
|
||||
struct stat st;
|
||||
int cgi = 0; /* becomes true if server decides this is a CGI
|
||||
* program */
|
||||
char *query_string = NULL;
|
||||
|
||||
numchars = recv(client, buf, sizeof(buf), 0);
|
||||
|
||||
i = 0; j = 0;
|
||||
while (!ISspace(buf[i]) && (i < sizeof(method) - 1))
|
||||
{
|
||||
method[i] = buf[i];
|
||||
i++;
|
||||
}
|
||||
j=i;
|
||||
method[i] = '\0';
|
||||
|
||||
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
|
||||
{
|
||||
unimplemented(client);
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcasecmp(method, "POST") == 0)
|
||||
cgi = 1;
|
||||
|
||||
i = 0;
|
||||
while (ISspace(buf[j]) && (j < numchars))
|
||||
j++;
|
||||
while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < numchars))
|
||||
{
|
||||
url[i] = buf[j];
|
||||
i++; j++;
|
||||
}
|
||||
url[i] = '\0';
|
||||
|
||||
if (strcasecmp(method, "GET") == 0)
|
||||
{
|
||||
query_string = url;
|
||||
while ((*query_string != '?') && (*query_string != '\0'))
|
||||
query_string++;
|
||||
if (*query_string == '?')
|
||||
{
|
||||
cgi = 1;
|
||||
*query_string = '\0';
|
||||
query_string++;
|
||||
}
|
||||
}
|
||||
|
||||
sprintf(path, "htdocs%s", url);
|
||||
if (path[strlen(path) - 1] == '/')
|
||||
strcat(path, "index.html");
|
||||
if (stat(path, &st) == -1) {
|
||||
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
not_found(client);
|
||||
}
|
||||
else
|
||||
{
|
||||
if ((st.st_mode & S_IFMT) == S_IFDIR)
|
||||
strcat(path, "/index.html");
|
||||
if ((st.st_mode & S_IXUSR) ||
|
||||
(st.st_mode & S_IXGRP) ||
|
||||
(st.st_mode & S_IXOTH) )
|
||||
cgi = 1;
|
||||
|
||||
cgi = 0;
|
||||
|
||||
if (!cgi)
|
||||
serve_file(client, path);
|
||||
else
|
||||
execute_cgi(client, path, method, query_string);
|
||||
}
|
||||
|
||||
close(client);
|
||||
free(pclient);
|
||||
}
|
||||
|
||||
|
||||
/**********************************************************************/
|
||||
/* Inform the client that a request it has made has a problem.
|
||||
* Parameters: client socket */
|
||||
/**********************************************************************/
|
||||
void bad_request(int client)
|
||||
{
|
||||
char buf[1024];
|
||||
|
||||
sprintf(buf, "HTTP/1.0 400 BAD REQUEST\r\n");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
sprintf(buf, "Content-type: text/html\r\n");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
sprintf(buf, "\r\n");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
sprintf(buf, "<P>Your browser sent a bad request, ");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
sprintf(buf, "such as a POST without a Content-Length.\r\n");
|
||||
send(client, buf, sizeof(buf), 0);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Put the entire contents of a file out on a socket. This function
|
||||
* is named after the UNIX "cat" command, because it might have been
|
||||
* easier just to do something like pipe, fork, and exec("cat").
|
||||
* Parameters: the client socket descriptor
|
||||
* FILE pointer for the file to cat */
|
||||
/**********************************************************************/
|
||||
|
||||
#define HTML_PAGE "<HTML> \
|
||||
<TITLE>Index</TITLE> \
|
||||
<BODY> \
|
||||
<P>Welcome to J. David's webserver.\
|
||||
<H1>CGI demo \
|
||||
<FORM ACTION=\"color.cgi\" METHOD=\"POST\">\
|
||||
Enter a color: <INPUT TYPE=\"text\" NAME=\"color\">\
|
||||
<INPUT TYPE=\"submit\">\
|
||||
</FORM>\
|
||||
</BODY>\
|
||||
</HTML>"
|
||||
|
||||
void cat(int client, FILE *resource)
|
||||
{
|
||||
#if ENABLE_NTYCO
|
||||
char buf[1024] = HTML_PAGE;
|
||||
|
||||
send(client, buf, strlen(buf), 0);
|
||||
|
||||
#else
|
||||
char buf[1024] = {0};
|
||||
fgets(buf, sizeof(buf), resource);
|
||||
while (!feof(resource))
|
||||
{
|
||||
send(client, buf, strlen(buf), 0);
|
||||
fgets(buf, sizeof(buf), resource);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Inform the client that a CGI script could not be executed.
|
||||
* Parameter: the client socket descriptor. */
|
||||
/**********************************************************************/
|
||||
void cannot_execute(int client)
|
||||
{
|
||||
char buf[1024];
|
||||
|
||||
sprintf(buf, "HTTP/1.0 500 Internal Server Error\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "Content-type: text/html\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<P>Error prohibited CGI execution.\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Print out an error message with perror() (for system errors; based
|
||||
* on value of errno, which indicates system call errors) and exit the
|
||||
* program indicating an error. */
|
||||
/**********************************************************************/
|
||||
void error_die(const char *sc)
|
||||
{
|
||||
perror(sc);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Execute a CGI script. Will need to set environment variables as
|
||||
* appropriate.
|
||||
* Parameters: client socket descriptor
|
||||
* path to the CGI script */
|
||||
/**********************************************************************/
|
||||
void execute_cgi(int client, const char *path,
|
||||
const char *method, const char *query_string)
|
||||
{
|
||||
char buf[1024];
|
||||
int cgi_output[2];
|
||||
int cgi_input[2];
|
||||
pid_t pid;
|
||||
int status;
|
||||
int i;
|
||||
char c;
|
||||
int numchars = 1;
|
||||
int content_length = -1;
|
||||
|
||||
buf[0] = 'A'; buf[1] = '\0';
|
||||
if (strcasecmp(method, "GET") == 0)
|
||||
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
else if (strcasecmp(method, "POST") == 0) /*POST*/
|
||||
{
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
while ((numchars > 0) && strcmp("\n", buf))
|
||||
{
|
||||
buf[15] = '\0';
|
||||
if (strcasecmp(buf, "Content-Length:") == 0)
|
||||
content_length = atoi(&(buf[16]));
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
}
|
||||
if (content_length == -1) {
|
||||
bad_request(client);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else/*HEAD or other*/
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
if (pipe(cgi_output) < 0) {
|
||||
cannot_execute(client);
|
||||
return;
|
||||
}
|
||||
if (pipe(cgi_input) < 0) {
|
||||
cannot_execute(client);
|
||||
return;
|
||||
}
|
||||
|
||||
if ( (pid = fork()) < 0 ) {
|
||||
cannot_execute(client);
|
||||
return;
|
||||
}
|
||||
sprintf(buf, "HTTP/1.0 200 OK\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
if (pid == 0) /* child: CGI script */
|
||||
{
|
||||
char meth_env[255];
|
||||
char query_env[255];
|
||||
char length_env[255];
|
||||
|
||||
dup2(cgi_output[1], STDOUT);
|
||||
dup2(cgi_input[0], STDIN);
|
||||
close(cgi_output[0]);
|
||||
close(cgi_input[1]);
|
||||
sprintf(meth_env, "REQUEST_METHOD=%s", method);
|
||||
putenv(meth_env);
|
||||
if (strcasecmp(method, "GET") == 0) {
|
||||
sprintf(query_env, "QUERY_STRING=%s", query_string);
|
||||
putenv(query_env);
|
||||
}
|
||||
else { /* POST */
|
||||
sprintf(length_env, "CONTENT_LENGTH=%d", content_length);
|
||||
putenv(length_env);
|
||||
}
|
||||
execl(path, "", NULL);
|
||||
exit(0);
|
||||
} else { /* parent */
|
||||
close(cgi_output[1]);
|
||||
close(cgi_input[0]);
|
||||
if (strcasecmp(method, "POST") == 0)
|
||||
for (i = 0; i < content_length; i++) {
|
||||
|
||||
recv(client, &c, 1, 0);
|
||||
|
||||
int len = write(cgi_input[1], &c, 1);
|
||||
}
|
||||
while (read(cgi_output[0], &c, 1) > 0)
|
||||
|
||||
send(client, &c, 1, 0);
|
||||
|
||||
|
||||
close(cgi_output[0]);
|
||||
close(cgi_input[1]);
|
||||
waitpid(pid, &status, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Get a line from a socket, whether the line ends in a newline,
|
||||
* carriage return, or a CRLF combination. Terminates the string read
|
||||
* with a null character. If no newline indicator is found before the
|
||||
* end of the buffer, the string is terminated with a null. If any of
|
||||
* the above three line terminators is read, the last character of the
|
||||
* string will be a linefeed and the string will be terminated with a
|
||||
* null character.
|
||||
* Parameters: the socket descriptor
|
||||
* the buffer to save the data in
|
||||
* the size of the buffer
|
||||
* Returns: the number of bytes stored (excluding null) */
|
||||
/**********************************************************************/
|
||||
int get_line(int sock, char *buf, int size)
|
||||
{
|
||||
int i = 0;
|
||||
char c = '\0';
|
||||
int n;
|
||||
|
||||
while ((i < size - 1) && (c != '\n'))
|
||||
{
|
||||
|
||||
n = recv(sock, &c, 1, 0);
|
||||
|
||||
if (n > 0)
|
||||
{
|
||||
if (c == '\r')
|
||||
{
|
||||
|
||||
n = recv(sock, &c, 1, MSG_PEEK);
|
||||
|
||||
if ((n > 0) && (c == '\n'))
|
||||
|
||||
recv(sock, &c, 1, 0);
|
||||
|
||||
else
|
||||
c = '\n';
|
||||
}
|
||||
buf[i] = c;
|
||||
i++;
|
||||
}
|
||||
else
|
||||
c = '\n';
|
||||
}
|
||||
buf[i] = '\0';
|
||||
|
||||
return(i);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Return the informational HTTP headers about a file. */
|
||||
/* Parameters: the socket to print the headers on
|
||||
* the name of the file */
|
||||
/**********************************************************************/
|
||||
void headers(int client, const char *filename)
|
||||
{
|
||||
char buf[1024] = {0};
|
||||
(void)filename; /* could use filename to determine file type */
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
|
||||
|
||||
sprintf(buf, "HTTP/1.0 200 OK\r\n");
|
||||
strcat(buf, SERVER_STRING);
|
||||
strcat(buf, "Content-Type: text/html\r\n");
|
||||
strcat(buf, "\r\n");
|
||||
|
||||
send(client, buf, strlen(buf), 0);
|
||||
|
||||
#else
|
||||
strcpy(buf, "HTTP/1.0 200 OK\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
strcpy(buf, SERVER_STRING);
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "Content-Type: text/html\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
strcpy(buf, "\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Give a client a 404 not found status message. */
|
||||
/**********************************************************************/
|
||||
void not_found(int client)
|
||||
{
|
||||
char buf[1024];
|
||||
#if ENABLE_NTYCO
|
||||
|
||||
sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
|
||||
strcat(buf, SERVER_STRING);
|
||||
strcat(buf, "Content-Type: text/html\r\n");
|
||||
strcat(buf, "\r\n");
|
||||
strcat(buf, "<HTML><TITLE>Not Found</TITLE>\r\n");
|
||||
strcat(buf, "<BODY><P>The server could not fulfill\r\n");
|
||||
strcat(buf, "your request because the resource specified\r\n");
|
||||
strcat(buf, "is unavailable or nonexistent.\r\n");
|
||||
strcat(buf, "</BODY></HTML>\r\n");
|
||||
|
||||
send(client, buf, strlen(buf), 0);
|
||||
|
||||
#else
|
||||
sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, SERVER_STRING);
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "Content-Type: text/html\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<HTML><TITLE>Not Found</TITLE>\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<BODY><P>The server could not fulfill\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "your request because the resource specified\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "is unavailable or nonexistent.\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "</BODY></HTML>\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Send a regular file to the client. Use headers, and report
|
||||
* errors to client if they occur.
|
||||
* Parameters: a pointer to a file structure produced from the socket
|
||||
* file descriptor
|
||||
* the name of the file to serve */
|
||||
/**********************************************************************/
|
||||
void serve_file(int client, const char *filename)
|
||||
{
|
||||
FILE *resource = NULL;
|
||||
int numchars = 1;
|
||||
char buf[1024];
|
||||
|
||||
#if (ENABLE_NTYCO == 0)
|
||||
buf[0] = 'A'; buf[1] = '\0';
|
||||
while ((numchars > 0) && strcmp("\n", buf)) /* read & discard headers */
|
||||
numchars = get_line(client, buf, sizeof(buf));
|
||||
resource = fopen(filename, "r");
|
||||
if (resource == NULL)
|
||||
not_found(client);
|
||||
else
|
||||
{
|
||||
headers(client, filename);
|
||||
cat(client, resource);
|
||||
}
|
||||
fclose(resource);
|
||||
#else
|
||||
headers(client, filename);
|
||||
cat(client, resource);
|
||||
#endif
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* This function starts the process of listening for web connections
|
||||
* on a specified port. If the port is 0, then dynamically allocate a
|
||||
* port and modify the original port variable to reflect the actual
|
||||
* port.
|
||||
* Parameters: pointer to variable containing the port to connect on
|
||||
* Returns: the socket */
|
||||
/**********************************************************************/
|
||||
int startup(u_short *port)
|
||||
{
|
||||
int httpd = 0;
|
||||
int on = 1;
|
||||
struct sockaddr_in name;
|
||||
|
||||
httpd = socket(PF_INET, SOCK_STREAM, 0);
|
||||
if (httpd == -1)
|
||||
error_die("socket");
|
||||
memset(&name, 0, sizeof(name));
|
||||
name.sin_family = AF_INET;
|
||||
name.sin_port = htons(*port);
|
||||
name.sin_addr.s_addr = htonl(INADDR_ANY);
|
||||
if ((setsockopt(httpd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) < 0)
|
||||
{
|
||||
error_die("setsockopt failed");
|
||||
}
|
||||
if (bind(httpd, (struct sockaddr *)&name, sizeof(name)) < 0)
|
||||
error_die("bind");
|
||||
if (*port == 0) /* if dynamically allocating a port */
|
||||
{
|
||||
socklen_t namelen = sizeof(name);
|
||||
if (getsockname(httpd, (struct sockaddr *)&name, &namelen) == -1)
|
||||
error_die("getsockname");
|
||||
*port = ntohs(name.sin_port);
|
||||
}
|
||||
if (listen(httpd, 5) < 0)
|
||||
error_die("listen");
|
||||
|
||||
|
||||
return(httpd);
|
||||
}
|
||||
|
||||
/**********************************************************************/
|
||||
/* Inform the client that the requested web method has not been
|
||||
* implemented.
|
||||
* Parameter: the client socket */
|
||||
/**********************************************************************/
|
||||
void unimplemented(int client)
|
||||
{
|
||||
char buf[1024];
|
||||
#if ENABLE_NTYCO
|
||||
sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
|
||||
strcat(buf, SERVER_STRING);
|
||||
strcat(buf, "Content-Type: text/html\r\n");
|
||||
strcat(buf, "\r\n");
|
||||
strcat(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
|
||||
strcat(buf, "</TITLE></HEAD>\r\n");
|
||||
strcat(buf, "<BODY><P>HTTP request method not supported.\r\n");
|
||||
strcat(buf, "</BODY></HTML>\r\n");
|
||||
|
||||
send(client, buf, strlen(buf), 0);
|
||||
#else
|
||||
sprintf(buf, "HTTP/1.0 501 Method Not Implemented\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, SERVER_STRING);
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "Content-Type: text/html\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<HTML><HEAD><TITLE>Method Not Implemented\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "</TITLE></HEAD>\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "<BODY><P>HTTP request method not supported.\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
sprintf(buf, "</BODY></HTML>\r\n");
|
||||
send(client, buf, strlen(buf), 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
void server(void *arg) {
|
||||
|
||||
unsigned short port = *(unsigned short *)arg;
|
||||
struct sockaddr_in client_name;
|
||||
socklen_t client_name_len = sizeof(client_name);
|
||||
free(arg);
|
||||
|
||||
int fd = nty_socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) return ;
|
||||
|
||||
struct sockaddr_in local, remote;
|
||||
local.sin_family = AF_INET;
|
||||
local.sin_port = htons(port);
|
||||
local.sin_addr.s_addr = INADDR_ANY;
|
||||
bind(fd, (struct sockaddr*)&local, sizeof(struct sockaddr_in));
|
||||
|
||||
listen(fd, 20);
|
||||
|
||||
while (1) {
|
||||
int *client_sock = (int *)malloc(sizeof(int));
|
||||
*client_sock = accept(fd,
|
||||
(struct sockaddr *)&client_name,
|
||||
&client_name_len);
|
||||
if (*client_sock == -1)
|
||||
error_die("accept");
|
||||
/* accept_request(&client_sock); */
|
||||
#if 0
|
||||
printf(" %d.%d.%d.%d:%d clientfd:%d --> New Client Connected \n",
|
||||
*(unsigned char*)(&client_name.sin_addr.s_addr), *((unsigned char*)(&client_name.sin_addr.s_addr)+1),
|
||||
*((unsigned char*)(&client_name.sin_addr.s_addr)+2), *((unsigned char*)(&client_name.sin_addr.s_addr)+3),
|
||||
client_name.sin_port, *client_sock);
|
||||
#endif
|
||||
nty_coroutine *read_co;
|
||||
nty_coroutine_create(&read_co, accept_request, client_sock);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int mulcore_entry(int begin_port) {
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
|
||||
int i = 0;
|
||||
unsigned short base_port = begin_port;
|
||||
|
||||
unsigned short *port = calloc(1, sizeof(unsigned short));
|
||||
*port = base_port + i;
|
||||
nty_coroutine_create(&co, server, port); ////////no run
|
||||
|
||||
|
||||
nty_schedule_run(); //run
|
||||
|
||||
}
|
||||
|
||||
int process_bind(void) {
|
||||
|
||||
int num = sysconf(_SC_NPROCESSORS_CONF);
|
||||
|
||||
pid_t self_id = syscall(__NR_gettid);
|
||||
//printf("selfid --> %d\n", self_id);
|
||||
|
||||
cpu_set_t mask;
|
||||
|
||||
CPU_ZERO(&mask);
|
||||
CPU_SET(self_id % num, &mask);
|
||||
|
||||
sched_setaffinity(0, sizeof(mask), &mask);
|
||||
|
||||
mulcore_entry(9096);
|
||||
|
||||
}
|
||||
|
||||
|
||||
struct timeval* get_shm_timevalue(void) {
|
||||
|
||||
return global_shmaddr ? &global_shmaddr->tv_begin : NULL;
|
||||
|
||||
}
|
||||
|
||||
void set_shm_timevalue(struct timeval *tv) {
|
||||
if (global_shmaddr == NULL || tv == NULL) {
|
||||
return ;
|
||||
}
|
||||
|
||||
memcpy(&global_shmaddr->tv_begin, tv, sizeof(struct timeval));
|
||||
|
||||
}
|
||||
|
||||
int add_shmvalue(void) {
|
||||
int value = 0;
|
||||
int ret = -1;
|
||||
|
||||
do {
|
||||
|
||||
value = global_shmaddr->total;
|
||||
ret = cmpxchg(&global_shmaddr->total, (unsigned long)value, (unsigned long)(value+1), 4);
|
||||
|
||||
|
||||
} while (ret != value);
|
||||
|
||||
return global_shmaddr->total;
|
||||
}
|
||||
|
||||
int sub_shmvalue(void) {
|
||||
int value = 0;
|
||||
int ret = -1;
|
||||
|
||||
do {
|
||||
|
||||
value = global_shmaddr->total;
|
||||
ret = cmpxchg(&global_shmaddr->total, (unsigned long)value, (unsigned long)(value-1), 4);
|
||||
|
||||
|
||||
} while (ret != value);
|
||||
|
||||
return global_shmaddr->total;
|
||||
}
|
||||
|
||||
int lock_accept_mutex(void) {
|
||||
|
||||
int ret = cmpxchg(&global_shmaddr->accept_lock, (unsigned long)0, (unsigned long)1, 4);
|
||||
|
||||
return ret; //success 0, failed 1.
|
||||
}
|
||||
|
||||
int unlock_accept_mutex(void) {
|
||||
|
||||
int ret = cmpxchg(&global_shmaddr->accept_lock, (unsigned long)1, (unsigned long)0, 4);
|
||||
|
||||
return ret; //unlock 1, lock 0
|
||||
}
|
||||
|
||||
|
||||
int init_shmvalue(void) {
|
||||
|
||||
global_shmid = shmget(IPC_PRIVATE, sizeof(shm_area), IPC_CREAT|0600);
|
||||
if (global_shmid < 0) {
|
||||
perror("shmget failed\n");
|
||||
return -1;
|
||||
}
|
||||
global_shmaddr = (shm_area*)shmat(global_shmid, NULL, 0);
|
||||
if (global_shmaddr == (shm_area*)-1) {
|
||||
perror("shmat addr error");
|
||||
return -1;
|
||||
}
|
||||
global_shmaddr->total = 0;
|
||||
gettimeofday(&global_shmaddr->tv_begin, NULL);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
int ret = init_shmvalue();
|
||||
if (ret == -1) {
|
||||
printf("init share memory failed\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
int num = sysconf(_SC_NPROCESSORS_CONF);
|
||||
int i = 0;
|
||||
pid_t pid=0;
|
||||
for(i = 0;i < num;i ++) {
|
||||
pid=fork();
|
||||
if(pid <= (pid_t) 0)
|
||||
{
|
||||
usleep(1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (pid > 0) {
|
||||
printf("ntyco_httpd server running ...\n");
|
||||
getchar();
|
||||
} else if (pid == 0) {
|
||||
process_bind();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
49
NtyCo/sample/nty_mysql_client.c
Normal file
49
NtyCo/sample/nty_mysql_client.c
Normal file
@@ -0,0 +1,49 @@
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <mysql.h>
|
||||
|
||||
|
||||
void func (void *arg) {
|
||||
|
||||
|
||||
MYSQL* m_mysql = mysql_init(NULL);
|
||||
if (!m_mysql) {
|
||||
printf("mysql_init failed\n");
|
||||
return ;
|
||||
}
|
||||
|
||||
if (!mysql_real_connect(m_mysql,
|
||||
"192.168.233.133", "king", "123456",
|
||||
"KING_DB", 3306,
|
||||
NULL, CLIENT_FOUND_ROWS)) {
|
||||
printf("mysql_real_connect failed: %s\n", mysql_error(m_mysql));
|
||||
return ;
|
||||
} else{
|
||||
printf("mysql_real_connect success\n");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
#if 1
|
||||
init_hook();
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
nty_coroutine_create(&co, func, NULL);
|
||||
nty_schedule_run(); //run
|
||||
#else
|
||||
|
||||
func(NULL);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
315
NtyCo/sample/nty_mysql_oper.c
Normal file
315
NtyCo/sample/nty_mysql_oper.c
Normal file
@@ -0,0 +1,315 @@
|
||||
|
||||
|
||||
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
|
||||
#include <mysql.h>
|
||||
|
||||
|
||||
#define KING_DB_SERVER_IP "192.168.233.133"
|
||||
#define KING_DB_SERVER_PORT 3306
|
||||
|
||||
#define KING_DB_USERNAME "king"
|
||||
#define KING_DB_PASSWORD "123456"
|
||||
|
||||
#define KING_DB_DEFAULTDB "KING_DB"
|
||||
|
||||
|
||||
#define SQL_INSERT_TBL_USER "INSERT TBL_USER(U_NAME, U_GENDER) VALUES('King', 'man');"
|
||||
#define SQL_SELECT_TBL_USER "SELECT * FROM TBL_USER;"
|
||||
|
||||
#define SQL_DELETE_TBL_USER "CALL PROC_DELETE_USER('King')"
|
||||
#define SQL_INSERT_IMG_USER "INSERT TBL_USER(U_NAME, U_GENDER, U_IMG) VALUES('King', 'man', ?);"
|
||||
|
||||
#define SQL_SELECT_IMG_USER "SELECT U_IMG FROM TBL_USER WHERE U_NAME='King';"
|
||||
|
||||
|
||||
#define FILE_IMAGE_LENGTH (64*1024)
|
||||
// C U R D -->
|
||||
//
|
||||
|
||||
int king_mysql_select(MYSQL *handle) { //
|
||||
|
||||
// mysql_real_query --> sql
|
||||
if (mysql_real_query(handle, SQL_SELECT_TBL_USER, strlen(SQL_SELECT_TBL_USER))) {
|
||||
printf("mysql_real_query : %s\n", mysql_error(handle));
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
// store -->
|
||||
MYSQL_RES *res = mysql_store_result(handle);
|
||||
if (res == NULL) {
|
||||
printf("mysql_store_result : %s\n", mysql_error(handle));
|
||||
return -2;
|
||||
}
|
||||
|
||||
// rows / fields
|
||||
int rows = mysql_num_rows(res);
|
||||
printf("rows: %d\n", rows);
|
||||
|
||||
int fields = mysql_num_fields(res);
|
||||
printf("fields: %d\n", fields);
|
||||
|
||||
// fetch
|
||||
MYSQL_ROW row;
|
||||
while ((row = mysql_fetch_row(res))) {
|
||||
|
||||
int i = 0;
|
||||
for (i = 0;i < fields;i ++) {
|
||||
printf("%s\t", row[i]);
|
||||
}
|
||||
printf("\n");
|
||||
|
||||
}
|
||||
|
||||
mysql_free_result(res);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
// filename : path + file name
|
||||
// buffer : store image data
|
||||
|
||||
int read_image(char *filename, char *buffer) {
|
||||
|
||||
if (filename == NULL || buffer == NULL) return -1;
|
||||
|
||||
FILE *fp = fopen(filename, "rb"); //
|
||||
if (fp == NULL) {
|
||||
printf("fopen failed\n");
|
||||
return -2;
|
||||
}
|
||||
|
||||
// file size
|
||||
fseek(fp, 0, SEEK_END);
|
||||
int length = ftell(fp); // file size
|
||||
fseek(fp, 0, SEEK_SET);
|
||||
|
||||
int size = fread(buffer, 1, length, fp);
|
||||
if (size != length) {
|
||||
printf("fread failed: %d\n", size);
|
||||
return -3;
|
||||
}
|
||||
|
||||
fclose(fp);
|
||||
|
||||
return size;
|
||||
|
||||
}
|
||||
|
||||
// filename :
|
||||
// buffer :
|
||||
// length :
|
||||
|
||||
int write_image(char *filename, char *buffer, int length) {
|
||||
|
||||
if (filename == NULL || buffer == NULL || length <= 0) return -1;
|
||||
|
||||
FILE *fp = fopen(filename, "wb+"); //
|
||||
if (fp == NULL) {
|
||||
printf("fopen failed\n");
|
||||
return -2;
|
||||
}
|
||||
|
||||
int size = fwrite(buffer, 1, length, fp);
|
||||
if (size != length) {
|
||||
printf("fwrite failed: %d\n", size);
|
||||
return -3;
|
||||
}
|
||||
|
||||
fclose(fp);
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
int mysql_write(MYSQL *handle, char *buffer, int length) {
|
||||
|
||||
if (handle == NULL || buffer == NULL || length <= 0) return -1;
|
||||
|
||||
MYSQL_STMT *stmt = mysql_stmt_init(handle);
|
||||
int ret = mysql_stmt_prepare(stmt, SQL_INSERT_IMG_USER, strlen(SQL_INSERT_IMG_USER));
|
||||
if (ret) {
|
||||
printf("mysql_stmt_prepare : %s\n", mysql_error(handle));
|
||||
return -2;
|
||||
}
|
||||
|
||||
MYSQL_BIND param = {0};
|
||||
param.buffer_type = MYSQL_TYPE_LONG_BLOB;
|
||||
param.buffer = NULL;
|
||||
param.is_null = 0;
|
||||
param.length = NULL;
|
||||
|
||||
ret = mysql_stmt_bind_param(stmt, ¶m);
|
||||
if (ret) {
|
||||
printf("mysql_stmt_bind_param : %s\n", mysql_error(handle));
|
||||
return -3;
|
||||
}
|
||||
|
||||
ret = mysql_stmt_send_long_data(stmt, 0, buffer, length);
|
||||
if (ret) {
|
||||
printf("mysql_stmt_send_long_data : %s\n", mysql_error(handle));
|
||||
return -4;
|
||||
}
|
||||
|
||||
ret = mysql_stmt_execute(stmt);
|
||||
if (ret) {
|
||||
printf("mysql_stmt_execute : %s\n", mysql_error(handle));
|
||||
return -5;
|
||||
}
|
||||
|
||||
ret = mysql_stmt_close(stmt);
|
||||
if (ret) {
|
||||
printf("mysql_stmt_close : %s\n", mysql_error(handle));
|
||||
return -6;
|
||||
}
|
||||
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
int mysql_read(MYSQL *handle, char *buffer, int length) {
|
||||
|
||||
if (handle == NULL || buffer == NULL || length <= 0) return -1;
|
||||
|
||||
MYSQL_STMT *stmt = mysql_stmt_init(handle);
|
||||
int ret = mysql_stmt_prepare(stmt, SQL_SELECT_IMG_USER, strlen(SQL_SELECT_IMG_USER));
|
||||
if (ret) {
|
||||
printf("mysql_stmt_prepare : %s\n", mysql_error(handle));
|
||||
return -2;
|
||||
}
|
||||
|
||||
|
||||
MYSQL_BIND result = {0};
|
||||
|
||||
result.buffer_type = MYSQL_TYPE_LONG_BLOB;
|
||||
unsigned long total_length = 0;
|
||||
result.length = &total_length;
|
||||
|
||||
ret = mysql_stmt_bind_result(stmt, &result);
|
||||
if (ret) {
|
||||
printf("mysql_stmt_bind_result : %s\n", mysql_error(handle));
|
||||
return -3;
|
||||
}
|
||||
|
||||
ret = mysql_stmt_execute(stmt);
|
||||
if (ret) {
|
||||
printf("mysql_stmt_execute : %s\n", mysql_error(handle));
|
||||
return -4;
|
||||
}
|
||||
|
||||
ret = mysql_stmt_store_result(stmt);
|
||||
if (ret) {
|
||||
printf("mysql_stmt_store_result : %s\n", mysql_error(handle));
|
||||
return -5;
|
||||
}
|
||||
|
||||
|
||||
while (1) {
|
||||
|
||||
ret = mysql_stmt_fetch(stmt);
|
||||
if (ret != 0 && ret != MYSQL_DATA_TRUNCATED) break; //
|
||||
|
||||
int start = 0;
|
||||
while (start < (int)total_length) {
|
||||
result.buffer = buffer + start;
|
||||
result.buffer_length = 1;
|
||||
mysql_stmt_fetch_column(stmt, &result, 0, start);
|
||||
start += result.buffer_length;
|
||||
}
|
||||
}
|
||||
|
||||
mysql_stmt_close(stmt);
|
||||
|
||||
return total_length;
|
||||
|
||||
}
|
||||
|
||||
void coroutine_func(void *arg) {
|
||||
|
||||
MYSQL mysql;
|
||||
|
||||
printf("coroutine_func\n");
|
||||
if (NULL == mysql_init(&mysql)) {
|
||||
printf("mysql_init : %s\n", mysql_error(&mysql));
|
||||
return ;
|
||||
}
|
||||
|
||||
if (!mysql_real_connect(&mysql, KING_DB_SERVER_IP, KING_DB_USERNAME, KING_DB_PASSWORD,
|
||||
KING_DB_DEFAULTDB, KING_DB_SERVER_PORT, NULL, 0)) {
|
||||
|
||||
printf("mysql_real_connect : %s\n", mysql_error(&mysql));
|
||||
goto Exit;
|
||||
}
|
||||
|
||||
// mysql --> insert
|
||||
printf("case 1 : mysql --> insert \n");
|
||||
#if 1
|
||||
if (mysql_real_query(&mysql, SQL_INSERT_TBL_USER, strlen(SQL_INSERT_TBL_USER))) {
|
||||
printf("mysql_real_query : %s\n", mysql_error(&mysql));
|
||||
goto Exit;
|
||||
}
|
||||
#endif
|
||||
|
||||
king_mysql_select(&mysql);
|
||||
|
||||
// mysql --> delete
|
||||
|
||||
printf("case 2 : mysql --> delete \n");
|
||||
#if 1
|
||||
if (mysql_real_query(&mysql, SQL_DELETE_TBL_USER, strlen(SQL_DELETE_TBL_USER))) {
|
||||
printf("mysql_real_query : %s\n", mysql_error(&mysql));
|
||||
goto Exit;
|
||||
}
|
||||
#endif
|
||||
|
||||
king_mysql_select(&mysql);
|
||||
|
||||
|
||||
|
||||
printf("case 3 : mysql --> read image and write mysql\n");
|
||||
|
||||
char buffer[FILE_IMAGE_LENGTH] = {0};
|
||||
int length = read_image("0voice.jpg", buffer);
|
||||
if (length < 0) goto Exit;
|
||||
|
||||
mysql_write(&mysql, buffer, length); ///
|
||||
|
||||
|
||||
printf("case 4 : mysql --> read mysql and write image\n");
|
||||
|
||||
memset(buffer, 0, FILE_IMAGE_LENGTH);
|
||||
length = mysql_read(&mysql, buffer, FILE_IMAGE_LENGTH);
|
||||
|
||||
write_image("a.jpg", buffer, length);
|
||||
|
||||
Exit:
|
||||
mysql_close(&mysql);
|
||||
|
||||
return ;
|
||||
|
||||
}
|
||||
|
||||
|
||||
int main() {
|
||||
#if 1
|
||||
//init_hook();
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
nty_coroutine_create(&co, coroutine_func, NULL);
|
||||
nty_schedule_run(); //run
|
||||
#else
|
||||
|
||||
coroutine_func(NULL);
|
||||
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
108
NtyCo/sample/nty_rediscli.c
Normal file
108
NtyCo/sample/nty_rediscli.c
Normal file
@@ -0,0 +1,108 @@
|
||||
|
||||
|
||||
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <hiredis.h>
|
||||
|
||||
|
||||
void coroutine_func(void *arg) {
|
||||
unsigned int j, isunix = 0;
|
||||
redisContext *c;
|
||||
redisReply *reply;
|
||||
const char *hostname = "192.168.233.133";
|
||||
int port = 6379;
|
||||
|
||||
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
|
||||
if (isunix) {
|
||||
c = redisConnectUnixWithTimeout(hostname, timeout);
|
||||
} else {
|
||||
c = redisConnectWithTimeout(hostname, port, timeout);
|
||||
}
|
||||
if (c == NULL || c->err) {
|
||||
if (c) {
|
||||
printf("Connection error: %s\n", c->errstr);
|
||||
redisFree(c);
|
||||
} else {
|
||||
printf("Connection error: can't allocate redis context\n");
|
||||
}
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/* PING server */
|
||||
reply = redisCommand(c,"PING");
|
||||
printf("PING: %s\n", reply->str);
|
||||
freeReplyObject(reply);
|
||||
|
||||
/* Set a key */
|
||||
reply = redisCommand(c,"SET %s %s", "foo", "hello world");
|
||||
printf("SET: %s\n", reply->str);
|
||||
freeReplyObject(reply);
|
||||
|
||||
/* Set a key using binary safe API */
|
||||
reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
|
||||
printf("SET (binary API): %s\n", reply->str);
|
||||
freeReplyObject(reply);
|
||||
|
||||
/* Try a GET and two INCR */
|
||||
reply = redisCommand(c,"GET foo");
|
||||
printf("GET foo: %s\n", reply->str);
|
||||
freeReplyObject(reply);
|
||||
|
||||
reply = redisCommand(c,"INCR counter");
|
||||
printf("INCR counter: %lld\n", reply->integer);
|
||||
freeReplyObject(reply);
|
||||
/* again ... */
|
||||
reply = redisCommand(c,"INCR counter");
|
||||
printf("INCR counter: %lld\n", reply->integer);
|
||||
freeReplyObject(reply);
|
||||
|
||||
/* Create a list of numbers, from 0 to 9 */
|
||||
reply = redisCommand(c,"DEL mylist");
|
||||
freeReplyObject(reply);
|
||||
for (j = 0; j < 10; j++) {
|
||||
char buf[64];
|
||||
|
||||
snprintf(buf,64,"%u",j);
|
||||
reply = redisCommand(c,"LPUSH mylist element-%s", buf);
|
||||
freeReplyObject(reply);
|
||||
}
|
||||
|
||||
/* Let's check what we have inside the list */
|
||||
reply = redisCommand(c,"LRANGE mylist 0 -1");
|
||||
if (reply->type == REDIS_REPLY_ARRAY) {
|
||||
for (j = 0; j < reply->elements; j++) {
|
||||
printf("%u) %s\n", j, reply->element[j]->str);
|
||||
}
|
||||
}
|
||||
freeReplyObject(reply);
|
||||
|
||||
/* Disconnects and frees the context */
|
||||
redisFree(c);
|
||||
|
||||
return ;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
|
||||
//init_hook();
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
nty_coroutine_create(&co, coroutine_func, NULL);
|
||||
nty_schedule_run(); //run
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
150
NtyCo/sample/nty_server.c
Normal file
150
NtyCo/sample/nty_server.c
Normal file
@@ -0,0 +1,150 @@
|
||||
/*
|
||||
* Author : WangBoJing , email : 1989wangbojing@gmail.com
|
||||
*
|
||||
* Copyright Statement:
|
||||
* --------------------
|
||||
* This software is protected by Copyright and the information contained
|
||||
* herein is confidential. The software may not be copied and the information
|
||||
* contained herein may not be used or disclosed except with the written
|
||||
* permission of Author. (C) 2017
|
||||
*
|
||||
*
|
||||
|
||||
**** ***** *****
|
||||
*** * ** ***
|
||||
*** * * * **
|
||||
* ** * * ** **
|
||||
* ** * * ** *
|
||||
* ** * ** ** *
|
||||
* ** * *** **
|
||||
* ** * *********** ***** ***** ** ****
|
||||
* ** * ** ** ** ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * ** **
|
||||
* *** ** * * ** * ** **
|
||||
* *** ** * ** * * ** **
|
||||
* ** ** * ** ** * ** **
|
||||
* ** ** * * ** * ** **
|
||||
***** * **** * ***** ****
|
||||
*
|
||||
*
|
||||
*****
|
||||
****
|
||||
|
||||
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#define MAX_CLIENT_NUM 1000000
|
||||
#define TIME_SUB_MS(tv1, tv2) ((tv1.tv_sec - tv2.tv_sec) * 1000 + (tv1.tv_usec - tv2.tv_usec) / 1000)
|
||||
|
||||
|
||||
void server_reader(void *arg) {
|
||||
int fd = *(int *)arg;
|
||||
free(arg);
|
||||
int ret = 0;
|
||||
|
||||
|
||||
struct pollfd fds;
|
||||
fds.fd = fd;
|
||||
fds.events = POLLIN;
|
||||
|
||||
while (1) {
|
||||
|
||||
char buf[1024] = {0};
|
||||
ret = nty_recv(fd, buf, 1024, 0);
|
||||
if (ret > 0) {
|
||||
if(fd > MAX_CLIENT_NUM)
|
||||
printf("read from server: %.*s\n", ret, buf);
|
||||
|
||||
ret = nty_send(fd, buf, strlen(buf), 0);
|
||||
if (ret == -1) {
|
||||
nty_close(fd);
|
||||
break;
|
||||
}
|
||||
} else if (ret == 0) {
|
||||
nty_close(fd);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void server(void *arg) {
|
||||
|
||||
unsigned short port = *(unsigned short *)arg;
|
||||
free(arg);
|
||||
|
||||
int fd = nty_socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) return ;
|
||||
|
||||
struct sockaddr_in local, remote;
|
||||
local.sin_family = AF_INET;
|
||||
local.sin_port = htons(port);
|
||||
local.sin_addr.s_addr = INADDR_ANY;
|
||||
bind(fd, (struct sockaddr*)&local, sizeof(struct sockaddr_in));
|
||||
|
||||
listen(fd, 20);
|
||||
printf("listen port : %d\n", port);
|
||||
|
||||
|
||||
struct timeval tv_begin;
|
||||
gettimeofday(&tv_begin, NULL);
|
||||
|
||||
while (1) {
|
||||
socklen_t len = sizeof(struct sockaddr_in);
|
||||
int cli_fd = nty_accept(fd, (struct sockaddr*)&remote, &len);
|
||||
if (cli_fd % 1000 == 999) {
|
||||
|
||||
struct timeval tv_cur;
|
||||
memcpy(&tv_cur, &tv_begin, sizeof(struct timeval));
|
||||
|
||||
gettimeofday(&tv_begin, NULL);
|
||||
int time_used = TIME_SUB_MS(tv_begin, tv_cur);
|
||||
|
||||
printf("client fd : %d, time_used: %d\n", cli_fd, time_used);
|
||||
}
|
||||
printf("new client comming\n");
|
||||
|
||||
nty_coroutine *read_co;
|
||||
int *arg = malloc(sizeof(int));
|
||||
*arg = cli_fd;
|
||||
nty_coroutine_create(&read_co, server_reader, arg);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
nty_coroutine *co = NULL;
|
||||
|
||||
int i = 0;
|
||||
unsigned short base_port = 9096;
|
||||
for (i = 0;i < 100;i ++) {
|
||||
unsigned short *port = calloc(1, sizeof(unsigned short));
|
||||
*port = base_port + i;
|
||||
nty_coroutine_create(&co, server, port); ////////no run
|
||||
}
|
||||
|
||||
nty_schedule_run(); //run
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
351
NtyCo/sample/nty_server_mulcore.c
Normal file
351
NtyCo/sample/nty_server_mulcore.c
Normal file
@@ -0,0 +1,351 @@
|
||||
/*
|
||||
* Author : WangBoJing , email : 1989wangbojing@gmail.com
|
||||
*
|
||||
* Copyright Statement:
|
||||
* --------------------
|
||||
* This software is protected by Copyright and the information contained
|
||||
* herein is confidential. The software may not be copied and the information
|
||||
* contained herein may not be used or disclosed except with the written
|
||||
* permission of Author. (C) 2017
|
||||
*
|
||||
*
|
||||
|
||||
**** ***** *****
|
||||
*** * ** ***
|
||||
*** * * * **
|
||||
* ** * * ** **
|
||||
* ** * * ** *
|
||||
* ** * ** ** *
|
||||
* ** * *** **
|
||||
* ** * *********** ***** ***** ** ****
|
||||
* ** * ** ** ** ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * ** **
|
||||
* *** ** * * ** * ** **
|
||||
* *** ** * ** * * ** **
|
||||
* ** ** * ** ** * ** **
|
||||
* ** ** * * ** * ** **
|
||||
***** * **** * ***** ****
|
||||
*
|
||||
*
|
||||
*****
|
||||
****
|
||||
|
||||
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/sysinfo.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/shm.h>
|
||||
#include <sys/sem.h>
|
||||
|
||||
|
||||
#define __USE_GNU
|
||||
|
||||
#include <sched.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
static int global_shmid = -1;
|
||||
static int global_semid = -1;
|
||||
|
||||
#define TIME_SUB_MS(tv1, tv2) ((tv1.tv_sec - tv2.tv_sec) * 1000 + (tv1.tv_usec - tv2.tv_usec) / 1000)
|
||||
|
||||
|
||||
typedef struct _shm_area {
|
||||
int total;
|
||||
int lock;
|
||||
struct timeval tv_begin;
|
||||
} shm_area;
|
||||
|
||||
static shm_area *global_shmaddr = NULL;
|
||||
|
||||
|
||||
#define MAX_CLIENT_NUM 1000000
|
||||
|
||||
|
||||
struct timeval* get_shm_timevalue(void);
|
||||
void set_shm_timevalue(struct timeval *tv);
|
||||
|
||||
|
||||
int add_shmvalue(void);
|
||||
int sub_shmvalue(void);
|
||||
|
||||
int init_shmvalue(void);
|
||||
|
||||
|
||||
unsigned long cmpxchg(void *addr, unsigned long _old, unsigned long _new, int size) {
|
||||
unsigned long prev;
|
||||
volatile unsigned int *_ptr = (volatile unsigned int *)(addr);
|
||||
|
||||
switch (size) {
|
||||
case 1: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchgb %b1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchgw %w1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchg %1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return prev;
|
||||
}
|
||||
|
||||
#define SERVER_STRING "Server: ntyco\r\n"
|
||||
|
||||
|
||||
int headers(char *buffer)
|
||||
{
|
||||
strcat(buffer, "HTTP/1.0 200 OK\r\n");
|
||||
strcat(buffer, SERVER_STRING);
|
||||
strcat(buffer, "Content-Type: text/html\r\n");
|
||||
strcat(buffer, "\r\n");
|
||||
|
||||
return strlen(buffer);
|
||||
}
|
||||
|
||||
int body(char *buffer) {
|
||||
strcat(buffer, "<html><h1> coroutine --> ntyco<h1></html>");
|
||||
|
||||
return strlen(buffer);
|
||||
}
|
||||
|
||||
void server_reader(void *arg) {
|
||||
int fd = *(int *)arg;
|
||||
int ret = 0;
|
||||
|
||||
|
||||
struct pollfd fds;
|
||||
fds.fd = fd;
|
||||
fds.events = POLLIN;
|
||||
|
||||
while (1) {
|
||||
|
||||
char buf[1024] = {0};
|
||||
ret = nty_recv(fd, buf, 1024, 0);
|
||||
if (ret > 0) {
|
||||
if(fd > MAX_CLIENT_NUM)
|
||||
printf("read from server: %.*s\n", ret, buf);
|
||||
|
||||
memset(buf, 0, 1024);
|
||||
int hlen = headers(buf);
|
||||
int blen = body(buf+hlen);
|
||||
|
||||
ret = nty_send(fd, buf, strlen(buf), 0);
|
||||
if (ret == -1) {
|
||||
nty_close(fd);
|
||||
sub_shmvalue();
|
||||
|
||||
break;
|
||||
}
|
||||
} else if (ret == 0) {
|
||||
nty_close(fd);
|
||||
|
||||
sub_shmvalue();
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void server(void *arg) {
|
||||
|
||||
unsigned short port = *(unsigned short *)arg;
|
||||
free(arg);
|
||||
|
||||
int fd = nty_socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) return ;
|
||||
|
||||
struct sockaddr_in local, remote;
|
||||
local.sin_family = AF_INET;
|
||||
local.sin_port = htons(port);
|
||||
local.sin_addr.s_addr = INADDR_ANY;
|
||||
bind(fd, (struct sockaddr*)&local, sizeof(struct sockaddr_in));
|
||||
|
||||
listen(fd, 20);
|
||||
printf("listen port : %d\n", port);
|
||||
|
||||
while (1) {
|
||||
socklen_t len = sizeof(struct sockaddr_in);
|
||||
int cli_fd = nty_accept(fd, (struct sockaddr*)&remote, &len);
|
||||
|
||||
printf("new client comming\n");
|
||||
|
||||
nty_coroutine *read_co;
|
||||
nty_coroutine_create(&read_co, server_reader, &cli_fd);
|
||||
|
||||
int value = add_shmvalue();
|
||||
if (value % 1000 == 999) {
|
||||
struct timeval *tv_begin = get_shm_timevalue();
|
||||
|
||||
struct timeval tv_cur;
|
||||
memcpy(&tv_cur, tv_begin, sizeof(struct timeval));
|
||||
gettimeofday(tv_begin, NULL);
|
||||
|
||||
int time_used = TIME_SUB_MS((*tv_begin), tv_cur);
|
||||
|
||||
printf("client sum: %d, time_used: %d\n", value, time_used);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int mulcore_entry(int begin_port) {
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
|
||||
int i = 0;
|
||||
unsigned short base_port = begin_port;
|
||||
//for (i = 0;i < 10;i ++) {
|
||||
unsigned short *port = calloc(1, sizeof(unsigned short));
|
||||
*port = base_port + i;
|
||||
nty_coroutine_create(&co, server, port); ////////no run
|
||||
//}
|
||||
|
||||
nty_schedule_run(); //run
|
||||
|
||||
}
|
||||
|
||||
int process_bind(void) {
|
||||
|
||||
int num = sysconf(_SC_NPROCESSORS_CONF);
|
||||
|
||||
pid_t self_id = syscall(__NR_gettid);
|
||||
//printf("selfid --> %d\n", self_id);
|
||||
|
||||
cpu_set_t mask;
|
||||
|
||||
CPU_ZERO(&mask);
|
||||
CPU_SET(self_id % num, &mask);
|
||||
|
||||
sched_setaffinity(0, sizeof(mask), &mask);
|
||||
|
||||
mulcore_entry(9096);
|
||||
|
||||
}
|
||||
|
||||
|
||||
struct timeval* get_shm_timevalue(void) {
|
||||
|
||||
return global_shmaddr ? &global_shmaddr->tv_begin : NULL;
|
||||
|
||||
}
|
||||
|
||||
void set_shm_timevalue(struct timeval *tv) {
|
||||
if (global_shmaddr == NULL || tv == NULL) {
|
||||
return ;
|
||||
}
|
||||
|
||||
memcpy(&global_shmaddr->tv_begin, tv, sizeof(struct timeval));
|
||||
|
||||
}
|
||||
|
||||
int add_shmvalue(void) {
|
||||
int value = 0;
|
||||
int ret = -1;
|
||||
|
||||
do {
|
||||
|
||||
value = global_shmaddr->total;
|
||||
ret = cmpxchg(&global_shmaddr->total, (unsigned long)value, (unsigned long)(value+1), 4);
|
||||
|
||||
|
||||
} while (ret != value);
|
||||
|
||||
return global_shmaddr->total;
|
||||
}
|
||||
|
||||
int sub_shmvalue(void) {
|
||||
int value = 0;
|
||||
int ret = -1;
|
||||
|
||||
do {
|
||||
|
||||
value = global_shmaddr->total;
|
||||
ret = cmpxchg(&global_shmaddr->total, (unsigned long)value, (unsigned long)(value-1), 4);
|
||||
|
||||
|
||||
} while (ret != value);
|
||||
|
||||
return global_shmaddr->total;
|
||||
}
|
||||
|
||||
|
||||
int init_shmvalue(void) {
|
||||
|
||||
global_shmid = shmget(IPC_PRIVATE, sizeof(shm_area), IPC_CREAT|0600);
|
||||
if (global_shmid < 0) {
|
||||
perror("shmget failed\n");
|
||||
return -1;
|
||||
}
|
||||
global_shmaddr = (shm_area*)shmat(global_shmid, NULL, 0);
|
||||
if (global_shmaddr == (shm_area*)-1) {
|
||||
perror("shmat addr error");
|
||||
return -1;
|
||||
}
|
||||
global_shmaddr->total = 0;
|
||||
gettimeofday(&global_shmaddr->tv_begin, NULL);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
int ret = init_shmvalue();
|
||||
if (ret == -1) {
|
||||
printf("init share memory failed\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
fork();
|
||||
fork();
|
||||
//fork();
|
||||
//fork();
|
||||
//fork();
|
||||
|
||||
process_bind();
|
||||
|
||||
377
NtyCo/sample/nty_websocket_server.c
Normal file
377
NtyCo/sample/nty_websocket_server.c
Normal file
@@ -0,0 +1,377 @@
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include <openssl/sha.h>
|
||||
#include <openssl/pem.h>
|
||||
#include <openssl/bio.h>
|
||||
#include <openssl/evp.h>
|
||||
|
||||
|
||||
#define MAX_CLIENT_NUM 1000000
|
||||
#define TIME_SUB_MS(tv1, tv2) ((tv1.tv_sec - tv2.tv_sec) * 1000 + (tv1.tv_usec - tv2.tv_usec) / 1000)
|
||||
|
||||
#define NTY_WEBSOCKET_SERVER_PORT 9096
|
||||
#define GUID "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
#define MAX_BUFFER_LENGTH 1024
|
||||
|
||||
struct _nty_ophdr {
|
||||
|
||||
unsigned char opcode:4,
|
||||
rsv3:1,
|
||||
rsv2:1,
|
||||
rsv1:1,
|
||||
fin:1;
|
||||
unsigned char payload_length:7,
|
||||
mask:1;
|
||||
|
||||
} __attribute__ ((packed));
|
||||
|
||||
struct _nty_websocket_head_126 {
|
||||
unsigned short payload_length;
|
||||
char mask_key[4];
|
||||
unsigned char data[8];
|
||||
} __attribute__ ((packed));
|
||||
|
||||
struct _nty_websocket_head_127 {
|
||||
|
||||
unsigned long long payload_length;
|
||||
char mask_key[4];
|
||||
|
||||
unsigned char data[8];
|
||||
|
||||
} __attribute__ ((packed));
|
||||
|
||||
#define UNION_HEADER(type1, type2) \
|
||||
struct { \
|
||||
struct type1 hdr; \
|
||||
struct type2 len; \
|
||||
}
|
||||
|
||||
|
||||
typedef struct _nty_websocket_head_127 nty_websocket_head_127;
|
||||
typedef struct _nty_websocket_head_126 nty_websocket_head_126;
|
||||
typedef struct _nty_ophdr nty_ophdr;
|
||||
|
||||
|
||||
static int ntySetNonblock(int fd) {
|
||||
int flags;
|
||||
|
||||
flags = fcntl(fd, F_GETFL, 0);
|
||||
if (flags < 0) return flags;
|
||||
flags |= O_NONBLOCK;
|
||||
if (fcntl(fd, F_SETFL, flags) < 0) return -1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int ntySetBlock(int fd)
|
||||
{
|
||||
int flags = fcntl(fd, F_GETFL, 0);
|
||||
if (flags < 0) return flags;
|
||||
flags &=~O_NONBLOCK;
|
||||
if (fcntl(fd, F_SETFL, flags) < 0) return -1;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
int base64_encode(char *in_str, int in_len, char *out_str) {
|
||||
BIO *b64, *bio;
|
||||
BUF_MEM *bptr = NULL;
|
||||
size_t size = 0;
|
||||
|
||||
if (in_str == NULL || out_str == NULL)
|
||||
return -1;
|
||||
|
||||
b64 = BIO_new(BIO_f_base64());
|
||||
bio = BIO_new(BIO_s_mem());
|
||||
bio = BIO_push(b64, bio);
|
||||
|
||||
BIO_write(bio, in_str, in_len);
|
||||
BIO_flush(bio);
|
||||
|
||||
BIO_get_mem_ptr(bio, &bptr);
|
||||
memcpy(out_str, bptr->data, bptr->length);
|
||||
out_str[bptr->length-1] = '\0';
|
||||
size = bptr->length;
|
||||
|
||||
BIO_free_all(bio);
|
||||
return size;
|
||||
}
|
||||
|
||||
|
||||
int readline(char* allbuf,int level,char* linebuf){
|
||||
int len = strlen(allbuf);
|
||||
|
||||
for (;level < len; ++level) {
|
||||
if(allbuf[level]=='\r' && allbuf[level+1]=='\n')
|
||||
return level+2;
|
||||
else
|
||||
*(linebuf++) = allbuf[level];
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
void umask(char *data,int len,char *mask){
|
||||
int i;
|
||||
for (i = 0;i < len;i ++)
|
||||
*(data+i) ^= *(mask+(i%4));
|
||||
}
|
||||
|
||||
|
||||
char* decode_packet(unsigned char *stream, char *mask, int length, int *ret) {
|
||||
|
||||
nty_ophdr *hdr = (nty_ophdr*)stream;
|
||||
unsigned char *data = stream + sizeof(nty_ophdr);
|
||||
int size = 0;
|
||||
int start = 0;
|
||||
//char mask[4] = {0};
|
||||
int i = 0;
|
||||
|
||||
if ((hdr->mask & 0x7F) == 126) {
|
||||
|
||||
nty_websocket_head_126 *hdr126 = (nty_websocket_head_126*)data;
|
||||
size = hdr126->payload_length;
|
||||
|
||||
for (i = 0;i < 4;i ++) {
|
||||
mask[i] = hdr126->mask_key[i];
|
||||
}
|
||||
|
||||
start = 8;
|
||||
|
||||
} else if ((hdr->mask & 0x7F) == 127) {
|
||||
|
||||
nty_websocket_head_127 *hdr127 = (nty_websocket_head_127*)data;
|
||||
size = hdr127->payload_length;
|
||||
|
||||
for (i = 0;i < 4;i ++) {
|
||||
mask[i] = hdr127->mask_key[i];
|
||||
}
|
||||
|
||||
start = 14;
|
||||
|
||||
} else {
|
||||
size = hdr->payload_length;
|
||||
|
||||
memcpy(mask, data, 4);
|
||||
start = 6;
|
||||
}
|
||||
|
||||
*ret = size;
|
||||
umask(stream+start, size, mask);
|
||||
|
||||
return stream + start;
|
||||
|
||||
}
|
||||
|
||||
int encode_packet(char *buffer,char *mask, char *stream, int length) {
|
||||
|
||||
nty_ophdr head = {0};
|
||||
head.fin = 1;
|
||||
head.opcode = 1;
|
||||
int size = 0;
|
||||
|
||||
if (length < 126) {
|
||||
head.payload_length = length;
|
||||
memcpy(buffer, &head, sizeof(nty_ophdr));
|
||||
size = 2;
|
||||
} else if (length < 0xffff) {
|
||||
nty_websocket_head_126 hdr = {0};
|
||||
hdr.payload_length = length;
|
||||
memcpy(hdr.mask_key, mask, 4);
|
||||
|
||||
memcpy(buffer, &head, sizeof(nty_ophdr));
|
||||
memcpy(buffer+sizeof(nty_ophdr), &hdr, sizeof(nty_websocket_head_126));
|
||||
size = sizeof(nty_websocket_head_126);
|
||||
|
||||
} else {
|
||||
|
||||
nty_websocket_head_127 hdr = {0};
|
||||
hdr.payload_length = length;
|
||||
memcpy(hdr.mask_key, mask, 4);
|
||||
|
||||
memcpy(buffer, &head, sizeof(nty_ophdr));
|
||||
memcpy(buffer+sizeof(nty_ophdr), &hdr, sizeof(nty_websocket_head_127));
|
||||
|
||||
size = sizeof(nty_websocket_head_127);
|
||||
|
||||
}
|
||||
|
||||
memcpy(buffer+2, stream, length);
|
||||
|
||||
return length + 2;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void server_reader(void *arg) {
|
||||
int fd = *(int *)arg;
|
||||
int length = 0;
|
||||
int ret = 0;
|
||||
|
||||
struct pollfd fds;
|
||||
fds.fd = fd;
|
||||
fds.events = POLLIN;
|
||||
|
||||
while (1) {
|
||||
|
||||
char stream[MAX_BUFFER_LENGTH] = {0};
|
||||
length = nty_recv(fd, stream, MAX_BUFFER_LENGTH, 0);
|
||||
if (length > 0) {
|
||||
if(fd > MAX_CLIENT_NUM)
|
||||
printf("read from server: %.*s\n", length, stream);
|
||||
|
||||
char mask[4] = {0};
|
||||
char *data = decode_packet(stream, mask, length, &ret);
|
||||
|
||||
printf(" data : %s , length : %d\n", data, ret);
|
||||
|
||||
#if 1
|
||||
char buffer[MAX_BUFFER_LENGTH+14] = {0};
|
||||
ret = encode_packet(buffer, mask, data, ret);
|
||||
ret = nty_send(fd, buffer, ret, 0);
|
||||
#endif
|
||||
} else if (length == 0) {
|
||||
nty_close(fd);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int handshake(int cli_fd) {
|
||||
int level = 0;
|
||||
char buffer[MAX_BUFFER_LENGTH];
|
||||
char linebuf[128]; //Sec-WebSocket-Accept
|
||||
char sec_accept[32] = {0}; //sha1 data
|
||||
unsigned char sha1_data[SHA_DIGEST_LENGTH+1] = {0}; //reponse head buffer
|
||||
//char head[MAX_BUFFER_LENGTH] = {0};
|
||||
|
||||
#if 1
|
||||
if (read(cli_fd, buffer, sizeof(buffer))<=0)
|
||||
perror("read");
|
||||
#else
|
||||
|
||||
int ret = 0;
|
||||
int length = recv_buffer(cli_fd, buffer, MAX_BUFFER_LENGTH, &ret);
|
||||
if (ret < 0) perror("read");
|
||||
|
||||
#endif
|
||||
printf("request\n");
|
||||
printf("%s\n",buffer);
|
||||
|
||||
do {
|
||||
memset(linebuf, 0, sizeof(linebuf));
|
||||
level = readline(buffer,level,linebuf);
|
||||
|
||||
if (strstr(linebuf,"Sec-WebSocket-Key") != NULL) {
|
||||
|
||||
strcat(linebuf, GUID);
|
||||
|
||||
SHA1((unsigned char*)&linebuf+19,strlen(linebuf+19),(unsigned char*)&sha1_data);
|
||||
|
||||
memset(buffer, 0, MAX_BUFFER_LENGTH);
|
||||
base64_encode(sha1_data,strlen(sha1_data),sec_accept);
|
||||
sprintf(buffer, "HTTP/1.1 101 Switching Protocols\r\n" \
|
||||
"Upgrade: websocket\r\n" \
|
||||
"Connection: Upgrade\r\n" \
|
||||
"Sec-WebSocket-Accept: %s\r\n" \
|
||||
"\r\n", sec_accept);
|
||||
|
||||
|
||||
printf("response\n");
|
||||
printf("%s",buffer);
|
||||
#if 1
|
||||
if (write(cli_fd, buffer, strlen(buffer)) < 0)
|
||||
perror("write");
|
||||
#else
|
||||
|
||||
length = send_buffer(cli_fd, head, strlen(head));
|
||||
assert(length == strlen(head));
|
||||
|
||||
#endif
|
||||
printf("accept : %s\n", sec_accept);
|
||||
break;
|
||||
}
|
||||
|
||||
}while((buffer[level]!='\r' || buffer[level+1]!='\n') && level!=-1);
|
||||
|
||||
return 0;
|
||||
|
||||
}
|
||||
|
||||
|
||||
int init_server(void) {
|
||||
|
||||
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd < 0) {
|
||||
printf("socket failed\n");
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct sockaddr_in addr;
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(NTY_WEBSOCKET_SERVER_PORT);
|
||||
addr.sin_addr.s_addr = INADDR_ANY;
|
||||
|
||||
if (bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) < 0) {
|
||||
printf("bind failed\n");
|
||||
return -2;
|
||||
}
|
||||
|
||||
if (listen(sockfd, 5) < 0) {
|
||||
printf("listen failed\n");
|
||||
return -3;
|
||||
}
|
||||
|
||||
return sockfd;
|
||||
|
||||
}
|
||||
|
||||
void server(void *arg) {
|
||||
|
||||
int sockfd = init_server();
|
||||
|
||||
struct timeval tv_begin;
|
||||
gettimeofday(&tv_begin, NULL);
|
||||
|
||||
while (1) {
|
||||
socklen_t len = sizeof(struct sockaddr_in);
|
||||
struct sockaddr_in remote;
|
||||
|
||||
int cli_fd = nty_accept(sockfd, (struct sockaddr*)&remote, &len);
|
||||
if (cli_fd % 1000 == 999) {
|
||||
|
||||
struct timeval tv_cur;
|
||||
memcpy(&tv_cur, &tv_begin, sizeof(struct timeval));
|
||||
|
||||
gettimeofday(&tv_begin, NULL);
|
||||
int time_used = TIME_SUB_MS(tv_begin, tv_cur);
|
||||
|
||||
printf("client fd : %d, time_used: %d\n", cli_fd, time_used);
|
||||
}
|
||||
printf("new client comming\n");
|
||||
ntySetBlock(cli_fd);
|
||||
handshake(cli_fd);
|
||||
ntySetNonblock(cli_fd);
|
||||
|
||||
nty_coroutine *read_co = NULL;
|
||||
nty_coroutine_create(&read_co, server_reader, &cli_fd);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
nty_coroutine_create(&co, server, NULL);
|
||||
|
||||
nty_schedule_run();
|
||||
}
|
||||
|
||||
|
||||
|
||||
536
NtyCo/sample/ntyco_httpd.c
Normal file
536
NtyCo/sample/ntyco_httpd.c
Normal file
@@ -0,0 +1,536 @@
|
||||
/*
|
||||
* Author : WangBoJing , email : 1989wangbojing@gmail.com
|
||||
*
|
||||
* Copyright Statement:
|
||||
* --------------------
|
||||
* This software is protected by Copyright and the information contained
|
||||
* herein is confidential. The software may not be copied and the information
|
||||
* contained herein may not be used or disclosed except with the written
|
||||
* permission of Author. (C) 2017
|
||||
*
|
||||
*
|
||||
|
||||
**** ***** *****
|
||||
*** * ** ***
|
||||
*** * * * **
|
||||
* ** * * ** **
|
||||
* ** * * ** *
|
||||
* ** * ** ** *
|
||||
* ** * *** **
|
||||
* ** * *********** ***** ***** ** ****
|
||||
* ** * ** ** ** ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** ** * ** ** **
|
||||
* ** * ** * * ** ** **
|
||||
* ** * ** ** * ** * ** **
|
||||
* *** ** * * ** * ** **
|
||||
* *** ** * ** * * ** **
|
||||
* ** ** * ** ** * ** **
|
||||
* ** ** * * ** * ** **
|
||||
***** * **** * ***** ****
|
||||
*
|
||||
*
|
||||
*****
|
||||
****
|
||||
|
||||
|
||||
|
||||
*
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
#include <arpa/inet.h>
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <sys/sysinfo.h>
|
||||
#include <sys/syscall.h>
|
||||
|
||||
#include <sys/ipc.h>
|
||||
#include <sys/shm.h>
|
||||
#include <sys/sem.h>
|
||||
|
||||
#include <errno.h>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <sys/poll.h>
|
||||
|
||||
#define __USE_GNU
|
||||
|
||||
#include <sched.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
|
||||
#include <ctype.h>
|
||||
|
||||
#include "nty_coroutine.h"
|
||||
|
||||
|
||||
#define MAX_CLIENT_NUM 1000000
|
||||
#define TOTALFDS 16
|
||||
|
||||
|
||||
typedef struct _shm_area {
|
||||
int totalfds[TOTALFDS];
|
||||
char cpu_lb[TOTALFDS];
|
||||
//mtx : default 0
|
||||
// 1 : lock -- del epoll
|
||||
// 2 : lock -- del complete
|
||||
// 3 : unlock -- add
|
||||
// 0 : unlock -- add complete
|
||||
int accept_mtx;
|
||||
} shm_area;
|
||||
|
||||
static shm_area *global_shmaddr = NULL;
|
||||
static int global_shmid = -1;
|
||||
|
||||
int cpu_size = 0;
|
||||
int accept_disable = 1000;
|
||||
int enable_accept = 1;
|
||||
pid_t self_id = 0;
|
||||
|
||||
|
||||
|
||||
unsigned long cmpxchg(void *addr, unsigned long _old, unsigned long _new, int size) {
|
||||
unsigned long prev;
|
||||
volatile unsigned int *_ptr = (volatile unsigned int *)(addr);
|
||||
|
||||
switch (size) {
|
||||
case 1: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchgb %b1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
case 2: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchgw %w1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
case 4: {
|
||||
__asm__ volatile (
|
||||
"lock; cmpxchg %1, %2"
|
||||
: "=a" (prev)
|
||||
: "r" (_new), "m" (*_ptr), "0" (_old)
|
||||
: "memory");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return prev;
|
||||
}
|
||||
|
||||
|
||||
int atomic_add(volatile int *value, int add)
|
||||
{
|
||||
__asm__ volatile (
|
||||
|
||||
"lock;"
|
||||
" addl %0, %1; "
|
||||
|
||||
: "+r" (add) : "m" (*value) : "cc", "memory");
|
||||
|
||||
return add;
|
||||
}
|
||||
|
||||
int atomic_sub(volatile int *value, int sub)
|
||||
{
|
||||
__asm__ volatile (
|
||||
|
||||
"lock;"
|
||||
" subl %0, %1; "
|
||||
|
||||
: "+r" (sub) : "m" (*value) : "cc", "memory");
|
||||
|
||||
return sub;
|
||||
}
|
||||
|
||||
|
||||
#define ISspace(x) isspace((int)(x))
|
||||
|
||||
#define SERVER_STRING "Server: ntyco_httpd/0.1.0\r\n"
|
||||
#define STDIN 0
|
||||
#define STDOUT 1
|
||||
#define STDERR 2
|
||||
|
||||
#define ENABLE_NTYCO 0
|
||||
|
||||
#if ENABLE_NTYCO
|
||||
|
||||
#define socket nty_socket
|
||||
#define accept nty_accept
|
||||
#define recv(a, b, c, d) nty_recv(a, b, c, d)
|
||||
#define send(a, b, c, d) nty_send(a, b, c, d)
|
||||
|
||||
#define MAX_BUFFER_LENGTH 1024
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
#define INC_COUNTFD do { \
|
||||
atomic_add(&global_shmaddr->totalfds[self_id % cpu_size], 1); \
|
||||
} while (0)
|
||||
|
||||
|
||||
#define DEC_COUNTFD do { \
|
||||
atomic_sub(&global_shmaddr->totalfds[self_id % cpu_size], 1); \
|
||||
} while (0)
|
||||
|
||||
int get_countfd(void) {
|
||||
return global_shmaddr->totalfds[self_id % cpu_size];
|
||||
}
|
||||
|
||||
int max_countfd(void) {
|
||||
|
||||
int count = -1;
|
||||
int i = 0;
|
||||
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
if (count < global_shmaddr->totalfds[i]) {
|
||||
count = global_shmaddr->totalfds[i];
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
int min_countfd(void) {
|
||||
|
||||
int count = 0xffffffff;
|
||||
int i = 0;
|
||||
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
if (count > global_shmaddr->totalfds[i]) {
|
||||
count = global_shmaddr->totalfds[i];
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
int compare_out_countfd(void) {
|
||||
|
||||
int current = get_countfd();
|
||||
int min = min_countfd();
|
||||
|
||||
if ((current * 7 / 8) > min) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int compare_in_countfd(void) {
|
||||
|
||||
int current = get_countfd();
|
||||
int max = max_countfd();
|
||||
|
||||
if ((current * 8 / 7) < max) {
|
||||
return 1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
void print_countfds(void) {
|
||||
|
||||
int i = 0;
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
printf("%5d : %5d ", i, global_shmaddr->totalfds[i]);
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
void lock_accept(void) {
|
||||
|
||||
global_shmaddr->cpu_lb[self_id % cpu_size] = 1;
|
||||
|
||||
int count = 0xffffffff;
|
||||
int i = 0;
|
||||
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
if (count > global_shmaddr->totalfds[i]) {
|
||||
count = global_shmaddr->totalfds[i];
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0;i < cpu_size;i ++) {
|
||||
if (count == global_shmaddr->totalfds[i]) {
|
||||
global_shmaddr->cpu_lb[i] = 3;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
char read_accept(void) {
|
||||
return global_shmaddr->cpu_lb[self_id % cpu_size];
|
||||
}
|
||||
|
||||
void write_accept(char state) { //0, 1, 2, 3
|
||||
global_shmaddr->cpu_lb[self_id % cpu_size] = state;
|
||||
}
|
||||
|
||||
int lock(void) {
|
||||
|
||||
return cmpxchg(&global_shmaddr->accept_mtx, 0, 1, 4); //zero:success, non-zero:failed
|
||||
|
||||
}
|
||||
|
||||
void unlock(void) {
|
||||
|
||||
global_shmaddr->accept_mtx = 0;
|
||||
|
||||
}
|
||||
|
||||
|
||||
void accept_request(void *arg);
|
||||
void bad_request(int);
|
||||
void cat(int);
|
||||
void cannot_execute(int);
|
||||
void error_die(const char *);
|
||||
void execute_cgi(int, const char *, const char *, const char *);
|
||||
int get_line(int, char *, int);
|
||||
void headers(int);
|
||||
void not_found(int);
|
||||
void serve_file(int);
|
||||
int startup(u_short *);
|
||||
void unimplemented(int);
|
||||
|
||||
|
||||
void accept_request(void* arg)
|
||||
{
|
||||
int client = *(int*)arg;
|
||||
|
||||
char buf[1024];
|
||||
size_t numchars;
|
||||
char method[16];
|
||||
char url[32];
|
||||
char path[64];
|
||||
size_t i, j;
|
||||
struct stat st;
|
||||
int cgi = 0; /* becomes true if server decides this is a CGI
|
||||
* program */
|
||||
char *query_string = NULL;
|
||||
|
||||
while (1) {
|
||||
|
||||
numchars = nty_recv(client, buf, sizeof(buf), 0);
|
||||
if (numchars > 0) {
|
||||
serve_file(client);
|
||||
} else if (numchars == 0) {
|
||||
nty_close(client);
|
||||
DEC_COUNTFD;
|
||||
break;
|
||||
} else if (numchars == -1) {
|
||||
if (errno == EAGAIN) {
|
||||
continue;
|
||||
}
|
||||
nty_close(client);
|
||||
DEC_COUNTFD;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
#define HTML_PAGE "<!DOCTYPE html> \
|
||||
<html> \
|
||||
<head> \
|
||||
<title>Welcome to nginx!</title> \
|
||||
<style> \
|
||||
body { \
|
||||
width: 35em;\
|
||||
margin: 0 auto;\
|
||||
font-family: Tahoma, Verdana, Arial, sans-serif;\
|
||||
}\
|
||||
</style>\
|
||||
</head>\
|
||||
<body>\
|
||||
<h1>Welcome to nginx!</h1>\
|
||||
<p>If you see this page, the nginx web server is successfully installed and\
|
||||
working. Further configuration is required.</p>\
|
||||
\
|
||||
<p>For online documentation and support please refer to\
|
||||
<a href=\"http://nginx.org/\">nginx.org</a>.<br/>\
|
||||
Commercial support is available at\
|
||||
<a href=\"http://nginx.com/\">nginx.com</a>.</p>\
|
||||
\
|
||||
<p><em>Thank you for using nginx.</em></p>\
|
||||
</body>\
|
||||
</html>"
|
||||
|
||||
|
||||
void error_die(const char *sc)
|
||||
{
|
||||
printf("%s\n", sc);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
void headers(int client)
|
||||
{
|
||||
char buf[1024] = {0};
|
||||
char content[128] = {0};
|
||||
|
||||
sprintf(buf, "HTTP/1.0 200 OK\r\n");
|
||||
strcat(buf, SERVER_STRING);
|
||||
strcat(buf, "Content-Type: text/html\r\n");
|
||||
#if 0
|
||||
strcat(buf, "Transfer-Encoding: chunked\r\n");
|
||||
#else
|
||||
sprintf(content, "Content-Length: %ld\r\n", strlen(HTML_PAGE));
|
||||
strcat(buf, content);
|
||||
#endif
|
||||
strcat(buf, "\r\n");
|
||||
|
||||
strcat(buf, HTML_PAGE);
|
||||
|
||||
int ret = nty_send(client, buf, strlen(buf), 0);
|
||||
if (ret == -1) {
|
||||
printf("send : errno : %d\n", errno);
|
||||
} else {
|
||||
//printf("headers send ret : %d\n", ret);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
void serve_file(int client)
|
||||
{
|
||||
headers(client);
|
||||
}
|
||||
|
||||
#define MAX_EPOLLSIZE 10240
|
||||
|
||||
void server(void *arg) {
|
||||
|
||||
int fd = *(int *)arg;
|
||||
|
||||
while (1) {
|
||||
|
||||
struct sockaddr_in client_addr;
|
||||
memset(&client_addr, 0, sizeof(struct sockaddr_in));
|
||||
socklen_t client_len = sizeof(client_addr);
|
||||
|
||||
if (lock()) {
|
||||
nty_coroutine_sleep(0);
|
||||
continue;
|
||||
}
|
||||
|
||||
int clientfd = nty_accept(fd, (struct sockaddr*)&client_addr, &client_len);
|
||||
unlock();
|
||||
|
||||
if (clientfd < 0) {
|
||||
return ;
|
||||
}
|
||||
|
||||
INC_COUNTFD;
|
||||
|
||||
nty_coroutine *read_co;
|
||||
int *client_sock = (int *)malloc(sizeof(int));
|
||||
*client_sock = clientfd;
|
||||
nty_coroutine_create(&read_co, accept_request, client_sock);
|
||||
|
||||
print_countfds();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int process_bind(int fd) {
|
||||
|
||||
int num = sysconf(_SC_NPROCESSORS_CONF);
|
||||
|
||||
self_id = syscall(__NR_gettid);
|
||||
//printf("selfid --> %d\n", self_id);
|
||||
|
||||
cpu_set_t mask;
|
||||
|
||||
CPU_ZERO(&mask);
|
||||
CPU_SET(self_id % num, &mask);
|
||||
|
||||
sched_setaffinity(0, sizeof(mask), &mask);
|
||||
|
||||
nty_coroutine *co = NULL;
|
||||
nty_coroutine_create(&co, server, &fd);
|
||||
|
||||
nty_schedule_run();
|
||||
}
|
||||
|
||||
int init_shmvalue(int num) {
|
||||
|
||||
global_shmid = shmget(IPC_PRIVATE, sizeof(shm_area), IPC_CREAT|0600);
|
||||
if (global_shmid < 0) {
|
||||
perror("shmget failed\n");
|
||||
return -1;
|
||||
}
|
||||
global_shmaddr = (shm_area*)shmat(global_shmid, NULL, 0);
|
||||
if (global_shmaddr == (shm_area*)-1) {
|
||||
perror("shmat addr error");
|
||||
return -1;
|
||||
}
|
||||
memset(global_shmaddr->totalfds, 0, TOTALFDS * sizeof(int));
|
||||
memset(global_shmaddr->cpu_lb, 0, TOTALFDS * sizeof(char));
|
||||
global_shmaddr->accept_mtx = 0;
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
|
||||
short port = 9001;
|
||||
struct sockaddr_in client_name;
|
||||
socklen_t client_name_len = sizeof(client_name);
|
||||
|
||||
int fd = nty_socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (fd < 0) return -1;
|
||||
|
||||
struct sockaddr_in local, remote;
|
||||
local.sin_family = AF_INET;
|
||||
local.sin_port = htons(port);
|
||||
local.sin_addr.s_addr = INADDR_ANY;
|
||||
bind(fd, (struct sockaddr*)&local, sizeof(struct sockaddr_in));
|
||||
|
||||
listen(fd, 5);
|
||||
|
||||
int num = sysconf(_SC_NPROCESSORS_CONF);
|
||||
cpu_size = num;
|
||||
init_shmvalue(num);
|
||||
|
||||
int i = 0;
|
||||
pid_t pid = 0;
|
||||
for(i = 0;i < num;i ++) {
|
||||
pid = fork();
|
||||
if(pid <= (pid_t) 0)
|
||||
{
|
||||
usleep(1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (pid > 0) {
|
||||
printf("ntyco_httpd server running ...\n");
|
||||
getchar();
|
||||
} else if (pid == 0) {
|
||||
process_bind(fd);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user