跳到正文

个人记录

socket搭建的局域网http服务器(http/1.0)

hdkghc约 58 分钟
原文
文章信息与版本

文章信息

发布
2024年5月2日
收录
2026年3月31日
更新
2026年11月14日
篇幅
约 58 分钟

版本

  1. v2当前
  2. v1

2.0

完整(带文件夹、错误文件):https://hdkghc.lanzouj.com/ivm1Y1xra1zi 若不下载完整版,则在EXE文件同目录创建“html”文件夹,是根目录。每个GET操作(目前只支持 GET)和命令都以此为根目录。 第一次运行请输入命令:

代码
redire ! [路径+你的主页html文件如:/index.html]

C++
// Copyleft (c) 2024~2100 hdkghc, All rights reserved.
#include<winsock2.h>
#include<Windows.h>
#include<bits/stdc++.h>
#define PORT 12345
#define BUFLEN 1048576
#define BUF_SIZE BUFLEN
#define DEFFOLDER "./html"
#define VERSION "HTTP/1.1"
#define CONFIG ((string)DEFFOLDER + "/config.ini").data()
#define check if(conn <= 0) while(1);
#define perr(b, str) if(b) { cout << str << endl; Sleep(10000); exit(GetLastError()); }
using namespace std;
WSADATA wsd;
int conn;
int ipnum;
class INI
{
protected:
	char file[1024];
public:
	void open(const char *File)
	{
		strcpy(file, File);
	}
	string Read(string Sec, string Key)
	{
		string ret = "";
		char *buf = new char[BUFLEN];
		GetPrivateProfileString(Sec.data(), Key.data(), "", buf, BUFLEN, file);
		ret = buf;
		delete[]buf;
		return ret;
	}
	void Write(string Sec, string Key, string Value)
	{
		WritePrivateProfileStringA(Sec.data(), Key.data(), Value.data(), file);
	}
	void *Read(string Sec, string Key, const int size)
	{
		void *buf = malloc(size);
		GetPrivateProfileStruct(Sec.data(), Key.data(), buf, size, file);
		return buf;
	}
	void Write(string Sec, string Key, void *Value, int size)
	{
		WritePrivateProfileStructA(Sec.data(), Key.data(), Value, size, file);
	}
};

struct _BWLIST
{
	vector<string> conf;
	vector<string> acce;
	void read()
	{
		int nconf = GetPrivateProfileIntA("bwlist", "confnum", 0, CONFIG);
		char *buf = new char[BUFLEN];
		for (int i = 0; i < nconf; i++)
		{
			GetPrivateProfileStringA("bwlist", ("conf" + to_string(i)).data(), "*.*.*.*", buf, BUFLEN, CONFIG);
			conf.push_back((string)buf);
		}
		int nacce = GetPrivateProfileIntA("bwlist", "accenum", 0, CONFIG);
		for (int i = 0; i < nacce; i++)
		{
			GetPrivateProfileStringA("bwlist", ("acce" + to_string(i)).data(), "*.*.*.*", buf, BUFLEN, CONFIG);
			acce.push_back((string)buf);
		}
		delete[]buf;
	}
	void write()
	{
		WritePrivateProfileStringA("bwlist", NULL, NULL, CONFIG);
		WritePrivateProfileStringA("bwlist", "confnum", to_string(conf.size()).data(), CONFIG);
		for (int i = 0; i < conf.size(); i++)
		{
			WritePrivateProfileStringA("bwlist", ("conf" + to_string(i)).data(), conf[i].data(), CONFIG);
		}
		WritePrivateProfileStringA("bwlist", "accenum", to_string(acce.size()).data(), CONFIG);
		for (int i = 0; i < acce.size(); i++)
		{
			WritePrivateProfileStringA("bwlist", ("acce" + to_string(i)).data(), acce[i].data(), CONFIG);
		}
	}
} BWlist;
int nfile;
map<int, string> filemp;
map<string, bool> fileatt; // 0:public
/*
这些状态码被分为五大类:
100-199 用于指定客户端应相应的某些动作。
200-299 用于表示请求成功。
300-399 用于已经移动的文件并且常被包含在定位头信息中指定新的地址信息。
400-499 用于指出客户端的错误。 (自己电脑这边的问题) 自己电脑这边的问题)
500-599 用于支持服务器错误。 (对方的问题) 对方的问题)

一些常见的状态码为:
200 - 服务器成功返回网页
404 - 请求的网页不存在
503 - 服务不可用

详细分解:
1xx(临时响应)
表示临时响应并需要请求者继续执行操作的状态代码。

代码 说明
100 (继续) 请求者应当继续提出请求。 服务器返回此代码表示已收到请求的第一部分,正在等待其余部分。
101 (切换协议) 请求者已要求服务器切换协议,服务器已确认并准备切换。

2xx (成功)
表示成功处理了请求的状态代码。

代码 说明
200 (成功) 服务器已成功处理了请求。 通常,这表示服务器提供了请求的网页。
201 (已创建) 请求成功并且服务器创建了新的资源。
202 (已接受) 服务器已接受请求,但尚未处理。
203 (非授权信息) 服务器已成功处理了请求,但返回的信息可能来自另一来源。
204 (无内容) 服务器成功处理了请求,但没有返回任何内容。
205 (重置内容) 服务器成功处理了请求,但没有返回任何内容。
206 (部分内容) 服务器成功处理了部分 GET 请求。

3xx (重定向)
表示要完成请求,需要进一步操作。 通常,这些状态代码用来重定向。

代码 说明
300 (多种选择) 针对请求,服务器可执行多种操作。 服务器可根据请求者 (user agent) 选择一项操作,或提供操作列表供请求者选择。
301 (永久移动) 请求的网页已永久移动到新位置。 服务器返回此响应(对 GET 或 HEAD 请求的响应)时,会自动将请求者转到新位置。
302 (临时移动) 服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来进行以后的请求。
303 (查看其他位置) 请求者应当对不同的位置使用单独的 GET 请求来检索响应时,服务器返回此代码。
304 (未修改) 自从上次请求后,请求的网页未修改过。 服务器返回此响应时,不会返回网页内容。
305 (使用代理) 请求者只能使用代理访问请求的网页。 如果服务器返回此响应,还表示请求者应使用代理。
307 (临时重定向) 服务器目前从不同位置的网页响应请求,但请求者应继续使用原有位置来进行以后的请求。

4xx(请求错误)
这些状态代码表示请求可能出错,妨碍了服务器的处理。

代码 说明
400 (错误请求) 服务器不理解请求的语法。
401 (未授权) 请求要求身份验证。 对于需要登录的网页,服务器可能返回此响应。
403 (禁止) 服务器拒绝请求。
404 (未找到) 服务器找不到请求的网页。
405 (方法禁用) 禁用请求中指定的方法。
406 (不接受) 无法使用请求的内容特性响应请求的网页。
407 (需要代理授权) 此状态代码与 401(未授权)类似,但指定请求者应当授权使用代理。
408 (请求超时) 服务器等候请求时发生超时。
409 (冲突) 服务器在完成请求时发生冲突。 服务器必须在响应中包含有关冲突的信息。
410 (已删除) 如果请求的资源已永久删除,服务器就会返回此响应。
411 (需要有效长度) 服务器不接受不含有效内容长度标头字段的请求。
412 (未满足前提条件) 服务器未满足请求者在请求中设置的其中一个前提条件。
413 (请求实体过大) 服务器无法处理请求,因为请求实体过大,超出服务器的处理能力。
414 (请求的 URI 过长) 请求的 URI(通常为网址)过长,服务器无法处理。
415 (不支持的媒体类型) 请求的格式不受请求页面的支持。
416 (请求范围不符合要求) 如果页面无法提供请求的范围,则服务器会返回此状态代码。
417 (未满足期望值) 服务器未满足”期望”请求标头字段的要求。

5xx(服务器错误)
这些状态代码表示服务器在尝试处理请求时发生内部错误。 这些错误可能是服务器本身的错误,而不是请求出错。

代码 说明
500 (服务器内部错误) 服务器遇到错误,无法完成请求。
501 (尚未实施) 服务器不具备完成请求的功能。 例如,服务器无法识别请求方法时可能会返回此代码。
502 (错误网关) 服务器作为网关或代理,从上游服务器收到无效响应。
503 (服务不可用) 服务器目前无法使用(由于超载或停机维护)。 通常,这只是暂时状态。
504 (网关超时) 服务器作为网关或代理,但是没有及时从上游服务器收到请求。
505 (HTTP 版本不受支持) 服务器不支持请求中所用的 HTTP 协议版本。
*/
map<int, string> errcd;
int errcode[] = {100, 101, 200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307,
	400, 401, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417,
	500, 501, 502, 503, 504, 505, 0
};

map<string, string> redirect;
void readatt()
{
	int n = GetPrivateProfileIntA("fileatt", "num", 0, CONFIG);
	char *buf = new char[BUFLEN];
	nfile = n;
	for (int i = 0; i < n; i++)
	{
		GetPrivateProfileStringA("fileatt", to_string(i).data(), "", buf, BUFLEN, CONFIG);
		string tmp = buf;
		if (tmp == "")
		{
			continue;
		}
		bool t = tmp[0] == '1';
		tmp = tmp.substr(1);
		filemp[i] = tmp;
		fileatt[tmp] = t;
	}
	for (int i = 0; errcode[i] != 0; i++)
	{
		GetPrivateProfileStringA("errc", to_string(errcode[i]).data(), "", buf, BUFLEN, CONFIG);
		errcd[errcode[i]] = buf;
		errcd[errcode[i]] = errcd[errcode[i]] == "" ? (DEFFOLDER"/err/" + to_string(errcode[i]) + ".htm") : errcd[errcode[i]];
	}
	delete[]buf;
}
void writeatt()
{
	WritePrivateProfileStringA("fileatt", NULL, NULL, CONFIG);
	WritePrivateProfileStringA("errc", NULL, NULL, CONFIG);
	WritePrivateProfileStringA("fileatt", "num", to_string(nfile).data(), CONFIG);
	for(int i = 0; i < nfile; i++)
	{
		WritePrivateProfileStringA("fileatt", to_string(i).data(), ((fileatt[filemp[i]] ? '1' : '0') + filemp[i]).data(),
			CONFIG);
	}
	for(int i = 0; errcode[i] != 0; i++)
	{
		WritePrivateProfileStringA("errc", to_string(errcode[i]).data(), errcd[errcode[i]].data(), CONFIG);
	}
}

bool isredirect(string path)
{
	if(redirect[path] != path && redirect[path] != "")
	{
		WritePrivateProfileStringA("redirect", path.data(), redirect[path].data(), CONFIG);
		return 1;
	}
	if(redirect[path] == path)
	{
		WritePrivateProfileStringA("redirect", path.data(), path.data(), CONFIG);
		return 0;
	}
	char *buf = new char[BUFLEN];
	string tmp;
	GetPrivateProfileStringA("redirect", path.data(), "", buf, BUFLEN, CONFIG);
	tmp = buf;
	delete[]buf;
	if(tmp == "" || tmp == path)
	{
		redirect[path] = path;
		WritePrivateProfileStringA("redirect", path.data(), path.data(), CONFIG);
		return 0;
	}
	else
	{
		redirect[path] = tmp;
		return 1;
	}

}

string Redirect(string url)
{
	int pos = url.find(DEFFOLDER);
	if(pos == 0)
	{
		url = url.substr(strlen(DEFFOLDER));
	}
	return "302 Found\nLocation: " + url + "\n\n";
}


string help =
"指令:\n\
CONFUS [ip]			拒绝某ip连接请求\n\
				不写全拒绝\n\
ACCEPT [ip]			允许某ip连接请求\n\
				不写全同意\n\
ATTRIB [--private | --public] htmlfile	更改某html是否可见\n\
ERRPAG errorcode errorpage		更改错误码对应错误页面\n\
BWLIST				获取黑白名单情况\n\
REDIRE html [htmlfile]		重定向\n\
				将html重定向至htmlfile\n\
				htmlfile不写:清除重定向\n\
				html填 '!':主页重定向\n\
注意:文件以"DEFFOLDER"为根目录。\n\
示例:\"/wiki/index.html\"指\""DEFFOLDER"/wiki/index.html\"\n\
";
enum CMDTYPE
{
	HELP,
	CONFUS,
	ACCEPT,
	ATTRIB,
	ERRPAG,
	BWLIST,
	REDIRE
};
#define ATT_PRI 0
#define ATT_PUB 1
struct COMMAND
{
	CMDTYPE cmdtype;
	string IpFile;
	string str2;
	int ErrcodeAttrib;
	struct
	{
		bool error;
		string what;
	}syntax;
	COMMAND()
	{
		syntax.error = 0;
	}
	void err(string what = "Syntax error.")
	{
		syntax.error = 1;
		syntax.what = what + "\n";
	}
};

unsigned long long cmdcnt;
queue<pair<unsigned long long, COMMAND>> command;
queue<string> cmdresponse;

COMMAND TranslateCommand(string cmd)
{
	for(int i = 0; i < cmd.size(); i++)
	{
		cmd[i] = isupper(cmd[i]) ? tolower(cmd[i]) : cmd[i];
	}
	stringstream ss;
	ss << cmd;
	string cmdtp;
	ss >> cmdtp;
	COMMAND com;
	try
	{
		if(0);
		else if(cmdtp == "confus")
		{
			com.cmdtype = CMDTYPE::CONFUS;
			ss >> cmdtp;
			if(cmdtp != "confus")
			{
				com.IpFile = cmdtp;
			}
			else
			{
				com.IpFile = "*.*.*.*";
			}
			return com;
		}
		else if(cmdtp == "accept")
		{
			com.cmdtype = CMDTYPE::ACCEPT;
			ss >> cmdtp;
			if(cmdtp != "accept")
			{
				com.IpFile = cmdtp;
			}
			else
			{
				com.IpFile = "*.*.*.*";
			}
			return com;
		}
		else if(cmdtp == "attrib")
		{
			com.cmdtype = CMDTYPE::ATTRIB;
			ss >> cmdtp;
			if(cmdtp != "attrib")
			{
				if(cmdtp == "--public")
				{
					com.ErrcodeAttrib = ATT_PUB;
				}
				else if(cmdtp == "--private")
				{
					com.ErrcodeAttrib = ATT_PRI;
				}
				else
				{
					com.err("Unidentified attrib mode.");
					return com;
				}
				ss >> cmdtp;
				if(cmdtp == "--public" || cmdtp == "--private")
				{
					com.err("Htmlpage?");
				}
				else if(cmdtp.front() == '"')
				{
					string tmp, last = "";
					ss >> tmp;
					while(tmp.back() != '"' && tmp != last)
					{
						cmdtp += tmp;
						last = tmp;
						ss >> tmp;
					}
					if(last == tmp)
					{
						com.err("'\"'?");
					}
					else
					{
						cmdtp += tmp;
						com.IpFile = cmdtp;
					}
				}
				else com.IpFile = cmdtp;
				com.IpFile = DEFFOLDER + com.IpFile;
			}
			else
			{
				com.err("What attrib?");
			}
			return com;
		}
		else if(cmdtp == "errpag")
		{
			com.cmdtype = CMDTYPE::ERRPAG;
			ss >> cmdtp;
			if(cmdtp != "errpag")
			{
				com.ErrcodeAttrib = stoi(cmdtp);
				ss >> cmdtp;
				if(cmdtp == to_string(com.ErrcodeAttrib))
				{
					com.err("Errpage?");
				}
				else if(cmdtp.front() == '"')
				{
					string tmp, last = "";
					ss >> tmp;
					while(tmp.back() != '"' && tmp != last)
					{
						cmdtp += tmp;
						last = tmp;
						ss >> tmp;
					}
					if(last == tmp)
					{
						com.err("'\"'?");
					}
					else
					{
						cmdtp += tmp;
						com.IpFile = cmdtp;
					}
				}
				else com.IpFile = cmdtp;
				com.IpFile = DEFFOLDER + com.IpFile;
			}
			else
			{
				com.err("Errcode?");
			}
			return com;
		}
		else if(cmdtp == "help")
		{
			com.cmdtype = CMDTYPE::HELP;
			return com;
		}
		else if(cmdtp == "bwlist")
		{
			com.cmdtype = CMDTYPE::BWLIST;
			return com;
		}
		else if(cmdtp == "redire")
		{
			com.cmdtype = CMDTYPE::REDIRE;
			ss >> cmdtp;
			if(cmdtp == "redire")
			{
				com.err("Page?");
				return com;
			}
			else if(cmdtp.front() == '"')
			{
				string tmp, last = "";
				ss >> tmp;
				while(tmp.back() != '"' && tmp != last)
				{
					cmdtp += tmp;
					last = tmp;
					ss >> tmp;
				}
				if(last == tmp)
				{
					com.err("'\"'?");
					return com;
				}
				else
				{
					cmdtp += tmp;
				}
			}
			if(cmdtp != "!") com.IpFile = DEFFOLDER + cmdtp;
			else com.IpFile = DEFFOLDER"/";

			ss >> cmdtp;
			if(cmdtp == com.IpFile)
			{
				com.err("Htmlpage?");
				return com;
			}
			else if(cmdtp.front() == '"')
			{
				string tmp, last = "";
				ss >> tmp;
				while(tmp.back() != '"' && tmp != last)
				{
					cmdtp += tmp;
					last = tmp;
					ss >> tmp;
				}
				if(last == tmp)
				{
					com.err("'\"'?");
					return com;
				}
				else
				{
					cmdtp += tmp;
				}
			}
			if(cmdtp != "!") com.str2 = DEFFOLDER + cmdtp;
			else com.str2 = DEFFOLDER"/";
		}
		else
		{
			com.err();
			return com;
		}
		return com;
	}
	catch(...)
	{
		com.err("Unexpected error.");
	}
}

void PushCmdResp(unsigned long long cnt, string resp)
{
	cmdresponse.push("Response No." + to_string(cnt) + ": \n\n" + resp);
}

/////////////////// pipe

string pname = "\\\\.\\PIPE\\HTTPSERVERV1";
bool send(HANDLE hWPipe, string s)
{
	DWORD dwReturn;
	return WriteFile(hWPipe, s.data(), s.length(), &dwReturn, NULL);
}
string rece(HANDLE hRPipe)
{
	string s;
	char szBuffer[BUF_SIZE] = { 0 };
	DWORD dwReturn;
	if (ReadFile(hRPipe, szBuffer, BUF_SIZE, &dwReturn, NULL))
	{
		szBuffer[dwReturn] = '\0';
		return (s = szBuffer);
	}
	return "";
}
HANDLE hWPipe, hRPipe;

int ipcolor[] =
{
	0x04, 0x06, 0x02, 0x03, 0x01, 0x05,
	0x40, 0x46, 0x42, 0x43, 0x41, 0x45,
	0x64, 0x60, 0x62, 0x63, 0x61, 0x65,
	0x24, 0x26, 0x20, 0x23, 0x21, 0x25,
	0x34, 0x36, 0x32, 0x30, 0x31, 0x35,
	0x14, 0x16, 0x12, 0x13, 0x10, 0x15,
	0x54, 0x56, 0x52, 0x53, 0x51, 0x50
};

void col(int n = -1)
{
	SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), n == -1 ? 0x07 : ipcolor[n]);
}

string substr(string s, int l, int r)
{
	return s.substr(l, r - l + 1);
}

class ip_int
{
public:
	int a, b, c, d;
	ip_int() : a(-1), b(-1), c(-1), d(-1) {}
	ip_int(string s)
	{
		try
		{
			string ta = substr(s, 0, s.find_first_of('.') - 1), tb = substr(s, s.find_first_of('.') + 1, s.substr(s.find_first_of('.' + 1)).find_first_of('.') - 1);
			string tc = substr(s, s.substr(s.find_first_of('.' + 1)).find_first_of('.') + 1, s.substr(s.substr(s.find_first_of('.' + 1)).find_first_of('.') + 1).find_first_of('.') - 1);
			string td = s.substr(s.substr(s.substr(s.find_first_of('.' + 1)).find_first_of('.') + 1).find_first_of('.') + 1);
			int sa = ta == "*" ? -1 : stoi(ta);
			int sb = tb == "*" ? -1 : stoi(tb);
			int sc = tc == "*" ? -1 : stoi(tc);
			int sd = td == "*" ? -1 : stoi(td);
			a = sa;
			b = sb;
			c = sc;
			d = sd;
		}
		catch(...)
		{
			a = b = c = d = -1;
		}
	}
	ip_int operator=(string s)
	{
		try
		{
			string ta = substr(s, 0, s.find_first_of('.') - 1), tb = substr(s, s.find_first_of('.') + 1, s.substr(s.find_first_of('.' + 1)).find_first_of('.') - 1);
			string tc = substr(s, s.substr(s.find_first_of('.' + 1)).find_first_of('.') + 1, s.substr(s.substr(s.find_first_of('.' + 1)).find_first_of('.') + 1).find_first_of('.') - 1);
			string td = s.substr(s.substr(s.substr(s.find_first_of('.' + 1)).find_first_of('.') + 1).find_first_of('.') + 1);
			int sa = ta == "*" ? -1 : stoi(ta);
			int sb = tb == "*" ? -1 : stoi(tb);
			int sc = tc == "*" ? -1 : stoi(tc);
			int sd = td == "*" ? -1 : stoi(td);
			a = sa;
			b = sb;
			c = sc;
			d = sd;
		}
		catch(...)
		{
			a = b = c = d = -1;
		}
	}
	bool in(ip_int ip)
	{
		if(ip.a != -1 && a != ip.a) return false;
		if(ip.b != -1 && b != ip.b) return false;
		if(ip.c != -1 && c != ip.c) return false;
		if(ip.d != -1 && d != ip.d) return false;
		return true;
	}
	bool ni(ip_int ip)
	{
		return ip.in(*this);
	}
	bool operator==(ip_int ip)
	{
		return in(ip) && ni(ip);
	}
	bool operator!=(ip_int ip)
	{
		return !in(ip) || !ni(ip);
	}
	bool operator<=(ip_int ip)
	{
		return in(ip);
	}
	bool operator>=(ip_int ip)
	{
		return ni(ip);
	}
	bool operator<(ip_int ip)
	{
		return in(ip) && !ni(ip);
	}
	bool operator>(ip_int ip)
	{
		return ni(ip) && !in(ip);
	}
	ip_int Union(ip_int ip)
	{
		ip_int ret;
		if(a == -1 || ip.a == -1 || ip.a != a) ret.a = -1; else ret.a = a;
		if(b == -1 || ip.b == -1 || ip.b != b) ret.b = -1; else ret.b = b;
		if(c == -1 || ip.c == -1 || ip.c != c) ret.c = -1; else ret.c = c;
		if(d == -1 || ip.d == -1 || ip.d != d) ret.d = -1; else ret.d = d;
		return ret;
	}
};

int findip(vector<string> v, string s)
{
	ip_int f = s;
	for(int i = 0; i < v.size(); i++)
	{
		string u = v[i];
		ip_int w = u;
		if(f <= w)
		{
			return i;
		}
	}
	return -1;
}

bool IsConfused(string ip)
{
	int conf = findip(BWlist.conf, ip);
	int acce = findip(BWlist.acce, ip);
	return conf != -1 && acce == -1;
}

queue<pair<int, int>> writq;

string GetFormatTime()
{
	SYSTEMTIME st;
	GetSystemTime(&st);
	string ret = "";
	ret += to_string(st.wYear) + "/" + to_string(st.wMonth) + "/" + to_string(st.wDay) + " ";
	ret += to_string(st.wHour) + ":" + to_string(st.wMinute) + ":" + to_string(st.wSecond) + "." + to_string(st.wMilliseconds);
	return ret;
}

void cprintf(int n, int tn, const char *format, ...)
{
	writq.push(make_pair(n, tn));
	va_list va;
	char buf[BUFLEN];
	va_start(va, format);
	vsprintf(buf, format, va);
	va_end(va);
	string tmp = buf;
	tmp = to_string(n) + "." + to_string(tn) + "@" + GetFormatTime() + " [LOG] " + tmp;
	while (writq.front().first != n || writq.front().second != tn) ;
	//	col(n);
	//	col(n);
	//	col(n);
	//	cout << tmp << flush;
	////	printf(tmp.data());
	//	col();
	for (auto u : tmp)
	{
		col(n);
		cout << u << flush;
		//		printf("%c", u);
		//		putchar(u);
		col();
	}
	fflush(stdout);
	Sleep(10);
	writq.pop();
}

void CloseSocket(SOCKET &s) { closesocket(s); conn++; }
bool IsFileExist(string path) { FILE *f = fopen(path.data(), "r"); bool ret = f == NULL; if (!ret) fclose(f); return !ret; }
string GetFile(string path)
{
	if (!IsFileExist(path))
	{
		cprintf(33, 0, "request file %s not exist\n", path.data());
		return "";
	}
	cprintf(33, 0, "request file %s succ\n", path.data());
	ifstream ifs(path, ios::in | ios::binary);
	stringstream ss;
	ss << ifs.rdbuf();
	ifs.close();
	return ss.str();
}
DWORD WINAPI OntToOneTalkingThread(LPVOID lpPara)
{
	pair<SOCKET, pair<int, int>> psi = *(pair<SOCKET, pair<int, int>> *)lpPara;
	SOCKET clientfd = psi.first;
	int num = psi.second.first;
	int tnum = psi.second.second;
	char *buf = new char[BUFLEN];
	string request, msg;
	sockaddr_in addrClient;
	int addrlen = sizeof(sockaddr);
	getpeername(clientfd, (sockaddr *) &addrClient, &addrlen);
	do
	{
		recv(clientfd, buf, BUFLEN, 0);
		cprintf(num, tnum, "%s message:\n%s\n------\n", inet_ntoa(addrClient.sin_addr), buf);
		request = buf;
		msg = "EXIT";
		{
			stringstream ss;
			ss << request;
			string method, path, version;
			ss >> method >> path >> version;
			path = DEFFOLDER + path; ///////////////////////////////////////////////////////////// cng
			string question = path.find('?') == string::npos ? "" : path.substr(path.find('?') + 1);
			path = path.substr(0, path.find('?'));
//			if (path.size() <= 5 || path.substr(path.find_last_of('/') + 1).find('.') == string::npos)
//			{
//				path += ".html";
//			}
			if (method != "UNLINE")
			{
				if (method == "GET")
				{
					msg = VERSION" ";
					if(isredirect(path)) // 重定向优先
					{
						cprintf(num, tnum, "%s redirect to %s\n", path.data(), redirect[path].data());
						msg += Redirect(redirect[path]);
						goto end;
					}
					else if (!IsFileExist(path)) // 文件不存在,404
					{
						//						msg += "200 OK\n\n" + GetFile(errcd[404]); // 直接发送404页面内容
						msg += Redirect(errcd[404]);
						goto end;
					}
					else if(fileatt[path])
					{
						msg += Redirect(errcd[403]);
						goto end;
					}
					else // 文件存在
					{
						msg += "200 OK\n\n" + GetFile(path);
						goto end;
					}
				}
			}
			end:
				;
		}
		if (msg == "EXIT") break;
		cprintf(num, tnum, "Send message to %s:\n%s\n------\n", inet_ntoa(addrClient.sin_addr), msg.data());
		send(clientfd, msg.data(), msg.size(), 0);
	}
	while (0);
	CloseSocket(clientfd);
	return EXIT_SUCCESS;
}
vector<string> ret;
DWORD WINAPI IPServerThread(LPVOID lpPara)
{
	check;
	string ip = *(string *)lpPara;
	int num = stoi(ip.substr(ip.find('@') + 1));
	ip = ip.substr(0, ip.find('@'));
	sockaddr_in addrMe, addrClient;
	conn--;
	SOCKET sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	ZeroMemory(&addrMe, sizeof(sockaddr_in));
	addrMe.sin_family = AF_INET;
	addrMe.sin_port = htons(PORT);
	addrMe.sin_addr.s_addr = inet_addr(ip.data());
	cprintf(num, 0, "bind\n");
	if (bind(sockfd, (sockaddr *)&addrMe, sizeof(addrMe)) == -1)
	{
		CloseSocket(sockfd);
		while (1);
	}
	cprintf(num, 0, "listen\n");
	if (listen(sockfd, conn / (ipnum) - 1) == -1)
	{
		CloseSocket(sockfd);
		while (1);
	}
	cprintf(num, 0, "YEAH!\n");
	SOCKET clientfd;
	int addrlen = sizeof(sockaddr);
	int tnum = 0;
	while ((clientfd = accept(sockfd, (sockaddr *)&addrClient, &addrlen)) != INVALID_SOCKET)
	{
		if(IsConfused(inet_ntoa(addrClient.sin_addr)))
		{
			cprintf(num, 0, "blacklist %s:%d request, confused.\n", inet_ntoa(addrClient.sin_addr), ntohs(addrClient.sin_port));
			CloseSocket(clientfd);
		}
		else
		{
			cprintf(num, 0, "welcome %s:%d\n", inet_ntoa(addrClient.sin_addr), ntohs(addrClient.sin_port));
			pair<SOCKET, pair<int, int>> psi = make_pair(clientfd, make_pair(num, ++tnum));
			CreateThread(NULL, 0, OntToOneTalkingThread, (LPVOID)&psi, 0, NULL);
		}
	}
	cprintf(num, 0, "?\n");
	//	return EXIT_SUCCESS;
}
void httpmain()
{
	WSAStartup(MAKEWORD(2, 2), &wsd);
	cout << "Max Connections: " << wsd.iMaxSockets << endl;
	conn = 20;
	string strIP("127.0.0.1");
	cprintf(0, 0, (strIP + "\n").data());
	ret.clear();
	ret.push_back(strIP + "@0");
	char strName[1024];
	gethostname(strName, 1024);
	struct hostent *pHostEnt = gethostbyname(strName);
	int n = 1;
	while (pHostEnt->h_addr_list[n] != NULL)
	{
		stringstream ss;
		ss << (pHostEnt->h_addr_list[n][0] & 0x00FF) << "."
		<< (pHostEnt->h_addr_list[n][1] & 0x00FF) << "."
		<< (pHostEnt->h_addr_list[n][2] & 0x00FF) << "."
		<< (pHostEnt->h_addr_list[n][3] & 0x00FF) << flush;
		string strTemp(ss.str());
		cprintf(n, 0, (strTemp + "\n").data());
		if (string::npos == strTemp.find("127.0.0."))
		{
			ret.push_back(strTemp + "@" + to_string(n));
		}
		n++;
	}
	cout << "next" << endl;
	ipnum = ret.size();
	cout << "next" << endl;
	for (int i = 0; i < ret.size(); i++)
	{
		CreateThread(NULL, 0, IPServerThread, (LPVOID)&ret[i], 0, NULL);
	}
	while (1);
	WSACleanup();
}
int has(vector<string> v, string s)
{
	int i = 0;
	for(auto u : v)
	{
		if(u == s) return i;
		i++;
	}
	return -1;
}
void ProcessCommand(COMMAND cmd)
{
	if(cmd.syntax.error) // have syntax error
	{
		PushCmdResp(cmdcnt, cmd.syntax.what);
	}
	else if(cmd.cmdtype == CMDTYPE::HELP) // help
	{
		PushCmdResp(cmdcnt, help);
	}
	else if(cmd.cmdtype == CMDTYPE::ACCEPT)
	{
		int pos;
		if((pos = has(BWlist.conf, cmd.IpFile)) == -1) BWlist.acce.push_back(cmd.IpFile);
		else BWlist.conf.erase(BWlist.conf.begin() + pos);
		BWlist.write();
		PushCmdResp(cmdcnt, "Done");
	}
	else if(cmd.cmdtype == CMDTYPE::CONFUS)
	{
		//		int pos;
		//		if((pos = has(BWlist.acce, cmd.IpFile)) == -1) BWlist.conf.push_back(cmd.IpFile);
		//		else BWlist.acce.erase(BWlist.acce.begin() + pos);

		int pos;
		if((pos = has(BWlist.acce, cmd.IpFile)) != -1) BWlist.acce.erase(BWlist.acce.begin() + pos);
		BWlist.conf.push_back(cmd.IpFile);

		BWlist.write();
		PushCmdResp(cmdcnt, "Done");
	}
	else if(cmd.cmdtype == CMDTYPE::BWLIST)
	{
		string resp = "Confuse:";
		for(auto u : BWlist.conf)
		{
			resp += "\n *\t" + u;
		}
		resp += "\nAccept:";
		for(auto u : BWlist.acce)
		{
			resp += "\n *\t" + u;
		}
		PushCmdResp(cmdcnt, resp);
	}
	else if(cmd.cmdtype == CMDTYPE::ATTRIB)
	{
		bool bHave = false;
		for(int i = 0; i < nfile; i++)
		{
			if(filemp[i] == cmd.IpFile)
			{
				bHave = true;
				break;
			}
		}
		if(!bHave)
		{
			if(IsFileExist(cmd.IpFile)) filemp[nfile++] = cmd.IpFile;
			else
			{
				PushCmdResp(cmdcnt, "File " + cmd.IpFile + " not exist.");
				return;
			}
		}
		if(cmd.ErrcodeAttrib == ATT_PUB)
		{
			fileatt[cmd.IpFile] = 0;
		}
		else
		{
			fileatt[cmd.IpFile] = 1;
		}
		writeatt();
		PushCmdResp(cmdcnt, "Done file " + cmd.IpFile + to_string(cmd.ErrcodeAttrib));
	}
	else if(cmd.cmdtype == CMDTYPE::ERRPAG)
	{
		bool bHave = false;
		for(int i = 0; errcode[i] != 0; i++)
		{
			if(errcode[i] == cmd.ErrcodeAttrib)
			{
				bHave = true;
				break;
			}
		}
		if(!bHave)
		{
			PushCmdResp(cmdcnt, "Unidentified errorcode " + to_string(cmd.ErrcodeAttrib) + ".");
		}
		else if(!IsFileExist(cmd.IpFile))
		{
			PushCmdResp(cmdcnt, "File " + cmd.IpFile + " not exist");
		}
		else
		{
			errcd[cmd.ErrcodeAttrib] = cmd.IpFile;
			writeatt();
			PushCmdResp(cmdcnt, "Done file " + cmd.IpFile + " errcode " + to_string(cmd.ErrcodeAttrib));
		}
	}
	else if(cmd.cmdtype == CMDTYPE::REDIRE)
	{
		if(!IsFileExist(cmd.str2))
		{
			PushCmdResp(cmdcnt, "File " + cmd.str2 + " not exist");
		}
		else
		{
			redirect[cmd.IpFile] = cmd.str2;
			WritePrivateProfileStringA("redirect", cmd.IpFile.data(), cmd.str2.data(), CONFIG);
			PushCmdResp(cmdcnt, "Done \""+ cmd.IpFile + "\" redirect to \"" + cmd.str2 + "\".");
		}
	}
	else command.push(make_pair(cmdcnt, cmd));
}
DWORD WINAPI ProcessCommandR(LPVOID lpIgnore)
{
	// data loop
	while(1)
	{
		try
		{
			string s = rece(hRPipe);
			++cmdcnt;
			COMMAND cmd = TranslateCommand(s);
			ProcessCommand(cmd);

			cprintf(35, 0, "Recv num %lld cmd:\n%s\n------\n", cmdcnt, s.data());
		}
		catch(...)
		{
			cprintf(35, 0, "Unexpected error\n");
		}
	}
}
DWORD WINAPI ProcessCommandW(LPVOID lpIgnore)
{
	// data loop
	while(1)
	{
		cout << "";
		if(cmdresponse.size())
		{
			cprintf(34, 0, "Send response\n");
			send(hWPipe, cmdresponse.front());
			cmdresponse.pop();
		}
	}
}
queue<string> stq;
DWORD WINAPI Pop(LPVOID lpIgnore)
{
	string s = stq.front();
	stq.pop();
	//	cout << s << endl;
	MessageBoxA(NULL, s.data(), "Command Response", MB_ICONINFORMATION);
	return 0;
}
DWORD WINAPI CmdProcessResp(LPVOID lpIgnore)
{
	// data loop
	while(1)
	{
		string s = rece(hRPipe);
		if(s != "")
		{
			stq.push(s);
			CreateThread(NULL, 0, Pop, NULL, 0, NULL);
		}
	}
}
int main(int argc, char **argv)
{
	/*{
		int size = 30;
		static int firstrun  = 1, sz = 0;
	    HANDLE hcsb = GetStdHandle(STD_OUTPUT_HANDLE);	//handle to the current console
	    CONSOLE_FONT_INFOEX cfi = {sizeof(cfi)}; 	//current font info
	    GetCurrentConsoleFontEx(hcsb, FALSE, &cfi);
	    cfi.nFont = 0;
	    sz = cfi.dwFontSize.X * 2;
	    size = (size == -1 ? sz : size);
	    cfi.dwFontSize.X = size / 2;
	    cfi.dwFontSize.Y = cfi.dwFontSize.X * 2 * 9 / 8;
	    SetCurrentConsoleFontEx(hcsb, FALSE, &cfi);	//set the screen buffer's new font
	}*/
	if(argc == 1)
	{
		while(writq.size()) writq.pop();
		cout << "PIPE NAME:" << pname << "(R/W)" << endl;
		cout << "create r: ";
		hRPipe = CreateNamedPipe((pname + "R").data(), PIPE_ACCESS_INBOUND, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUF_SIZE, BUF_SIZE, 0, NULL);
		perr(hRPipe == INVALID_HANDLE_VALUE, "Create Read Pipe Error");
		cout << hRPipe << endl;

		cout << "create w: ";
		hWPipe = CreateNamedPipe((pname + "W").data(), PIPE_ACCESS_OUTBOUND, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUF_SIZE, BUF_SIZE, 0, NULL);
		perr(hWPipe == INVALID_HANDLE_VALUE, "Create Write Pipe Error");
		cout << hWPipe << endl;

		ShellExecuteA(NULL, "open", "httpserver.exe", pname.data(), NULL, SW_SHOWDEFAULT);

		perr(!ConnectNamedPipe(hRPipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED, "Connect R");
		perr(!ConnectNamedPipe(hWPipe, NULL) && GetLastError() != ERROR_PIPE_CONNECTED, "Connect W");

		CreateThread(NULL, 0, ProcessCommandR, NULL, 0, NULL);
		CreateThread(NULL, 0, ProcessCommandW, NULL, 0, NULL);
		SetConsoleTitle("HTTP server main");
		if(!IsFileExist(CONFIG))
		{
			FILE *f = fopen(CONFIG, "w");
			fclose(f);
			BWlist.conf.clear();
			BWlist.acce.clear();
			BWlist.write();
			filemp.clear();
			fileatt.clear();
			writeatt();
			readatt();
			writeatt();
		}
		else
		{
			BWlist.read();
			readatt();
		}
		httpmain();
	}
	else
	{
		Sleep(1000);
		pname = argv[1];

		perr(!WaitNamedPipe((pname + "R").data(), NMPWAIT_USE_DEFAULT_WAIT), "No Write(main R) Pipe");
		perr(!WaitNamedPipe((pname + "W").data(), NMPWAIT_USE_DEFAULT_WAIT), "No Read(main W) Pipe");

		cout << "open w(mr) ";
		hWPipe = CreateFile((pname + "R").data(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
		perr(hWPipe == INVALID_HANDLE_VALUE, "Open Write (mR) Pipe Error");
		cout << hWPipe << endl;

		cout << "open r(mw) ";
		hRPipe = CreateFile((pname + "W").data(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
		perr(hRPipe == INVALID_HANDLE_VALUE, "Open Read (mW) Pipe Error");
		cout << hWPipe << endl;

		cout << "Input command here:" << endl;
		unsigned long long i = 0;
		CreateThread(NULL, 0, CmdProcessResp, NULL, 0, NULL);
		while(1)
		{
			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x07);
			cout << "@" << ++i << endl;
			cout << ">>> $" << flush;
			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x02);
			string input, tmp;
			getline(cin, tmp);
			input = tmp;
			while(input.back() == '\\' && (input.size() < 2 || input[input.size() - 2] != '!'))
			{
				input.pop_back();
				input += '\n';
				SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x07);
				cout << "... $" << flush;
				SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x02);
				getline(cin, tmp);
				input += tmp;
			}
			if(input.back() == '\\' && input[input.size() - 2] == '!')
			{
				input.pop_back();
				input.pop_back();
				input += '\\';
			}
			cout << "stat: " << send(hWPipe, input) << endl;
			//			input = rece(hRPipe);
			//			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x04);
			//			cout << input << endl;
			//			SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 0x07);
		}
	}
}
原文
存档评论1 条抓取于