-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJDaemon.cpp
More file actions
411 lines (354 loc) · 10.9 KB
/
JDaemon.cpp
File metadata and controls
411 lines (354 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h>
#include <algorithm>
#include <string>
#include <mutex>
#include <future>
#include <vector>
#include <thread>
#define _MACROSTR(x) #x
#define MACROSTR(x) _MACROSTR(x)
#define BUILDTIME MACROSTR(XUE_COMPILE_TIME)
using namespace std;
// 获取时间
long GetCurSec();
// 执行shell 命令 返回结果
string GetCMDRet(string cmd);
// 解码url
string UrlDecode(string str);
// 发送文件
void send_file(struct evhttp_request *req, const char *file_path);
//接收文件
void upload_handler(struct evhttp_request* req, void* arg);
// 处理回调
void on_request(struct evhttp_request *req, void *arg);
// 格式化json
string GetLevelStr(int level);
string FormatJsonToDisplay(string json);
// 重启进程任务
std::future<void> kill_future;
std::future<string> shell_future;
// 上一次重启时间
long lastStartAIITime = GetCurSec();
static string env_lib = "export PATH=/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/bin:/sbin && export LD_LIBRARY_PATH=/usr/local/lib:/usr/lib:/lib && ";
int main()
{
// 初始化libevent库
event_base *base = event_base_new();
if (!base)
{
std::cerr << "Failed to initialize event base." << std::endl;
return 1;
}
// 创建HTTP服务器
evhttp *http_server = evhttp_new(base);
if (!http_server)
{
std::cerr << "Failed to create HTTP server." << std::endl;
return 1;
}
// 设置请求处理回调函数
evhttp_set_gencb(http_server, on_request, nullptr);
// 绑定监听地址和端口
if (evhttp_bind_socket(http_server, "0.0.0.0", 1000) != 0)
{
std::cerr << "Failed to bind to port 10000." << std::endl;
return 1;
}
std::cout << "Server started on port 10000." << std::endl;
// 进入事件循环
event_base_dispatch(base);
// 清理资源
evhttp_free(http_server);
event_base_free(base);
return 0;
}
void on_request(struct evhttp_request *req, void *arg)
{
// 解析URL
const char *url = evhttp_request_get_uri(req);
string curl(url);
std::cout << "Received request for URL: " << curl << "\n";
curl = UrlDecode(curl);
std::cout << "Decode URL: " << curl << "\n";
string ret = curl + " ok ";
if (curl.find("getfile") != string::npos)
{
const evhttp_uri *uri = evhttp_request_get_evhttp_uri(req);
char url[1024];
evhttp_uri_join(const_cast<evhttp_uri *>(uri), url, sizeof(url));
struct evkeyvalq params;
evhttp_parse_query(url, ¶ms);
const char *file_param = evhttp_find_header(¶ms, "getfile");
if (!file_param)
{
evhttp_send_error(req, HTTP_BADREQUEST, "Bad request");
evhttp_clear_headers(¶ms);
return;
}
printf("getfile ok \n");
send_file(req, file_param);
evhttp_clear_headers(¶ms);
return;
}
if (curl.find("upload") != string::npos)
{
upload_handler(req, arg);
return;
}
if (curl.find("exec_shell") != string::npos)
{
string cmdstr = "";
if (curl.find("=") != string::npos && curl.find("=") + 1 < curl.size())
{
cmdstr = curl.substr(curl.find("=") + 1);
}
printf("exec_shell cmd %s\n", cmdstr.c_str());
string querystr = cmdstr;
ret = GetCMDRet(querystr);
}
if (curl.find("query_buildtime") != string::npos)
{
string str = "AIIDaemon buildtime :";
string cmdstr(BUILDTIME);
ret = str + cmdstr;
}
if (curl.find("query_disk") != string::npos)
{
string querystr = R"(df -h)";
ret = GetCMDRet(querystr);
}
if (curl.find("query_ipcs") != string::npos)
{
string querystr = R"(ipcs -m)";
ret = GetCMDRet(querystr);
}
// 处理请求
// 这里可以根据你的需求进行具体的处理逻辑
ret += "\n";
// 发送响应
struct evbuffer *response_buffer = evbuffer_new();
if (response_buffer)
{
evbuffer_add_printf(response_buffer, ret.c_str());
evhttp_send_reply(req, HTTP_OK, "OK", response_buffer);
evbuffer_free(response_buffer);
}
else
{
std::cerr << "Failed to create response buffer." << std::endl;
}
}
void send_file(struct evhttp_request *req, const char *file_path)
{
struct stat st;
if (stat(file_path, &st) < 0)
{
evhttp_send_error(req, HTTP_NOTFOUND, "File not found");
return;
}
int fd = open(file_path, O_RDONLY);
if (fd < 0)
{
evhttp_send_error(req, HTTP_NOTFOUND, "File not found");
return;
}
struct evbuffer *evb = evbuffer_new();
evbuffer_add_file(evb, fd, 0, st.st_size);
evhttp_send_reply(req, HTTP_OK, "OK", evb);
evbuffer_free(evb);
}
void upload_handler(struct evhttp_request* req, void* arg) {
// Check if it's a POST request
if (evhttp_request_get_command(req) != EVHTTP_REQ_POST) {
evhttp_send_error(req, HTTP_BADMETHOD, "Method Not Allowed");
return;
}
// Get the content type of the request
const char* content_type = evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type");
if (!content_type || strncmp(content_type, "application/octet-stream", 24) != 0) {
evhttp_send_error(req, HTTP_BADREQUEST, "Invalid Content-Type");
return;
}
// Create a buffer to store the uploaded file
struct evbuffer* evbuf = evhttp_request_get_input_buffer(req);
if (!evbuf) {
evhttp_send_error(req, HTTP_BADREQUEST, "No Input Buffer");
return;
}
// Get the filename from the Content-Disposition header
const char* content_disposition = evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Disposition");
if (!content_disposition) {
evhttp_send_error(req, HTTP_BADREQUEST, "No Content-Disposition Header");
return;
}
std::string filename;
const std::string prefix = "filename=\"";
const std::string suffix = "\"";
std::string contentDisposition(content_disposition);
std::size_t start = contentDisposition.find(prefix);
std::size_t end = contentDisposition.find(suffix, start + prefix.length());
if (start != std::string::npos && end != std::string::npos && end > start + prefix.length()) {
filename = contentDisposition.substr(start + prefix.length(), end - start - prefix.length());
}
if (filename.empty()) {
evhttp_send_error(req, HTTP_BADREQUEST, "Invalid Filename");
return;
}
cout<<filename<<endl;
// Save the uploaded file to disk
std::ofstream file(filename, std::ios::binary);
if (!file) {
evhttp_send_error(req, HTTP_INTERNAL, "Failed to Save File");
return;
}
char buf[1024];
size_t n;
while ((n = evbuffer_remove(evbuf, buf, sizeof(buf))) > 0) {
file.write(buf, n);
}
file.close();
// Send a response to the client
struct evbuffer* response = evbuffer_new();
evbuffer_add_printf(response, "File '%s' uploaded successfully\n", filename.c_str());
evhttp_send_reply(req, HTTP_OK, "OK", response);
evbuffer_free(response);
}
long GetCurSec()
{
time_t seconds;
seconds = time(NULL);
return seconds;
}
string GetCMDRet(string cmd)
{
auto this_future = std::async(std::launch::async, [cmd]
{
string s = "";
char buf[5000];
FILE *p_file = NULL;
string com = env_lib + cmd;
p_file = popen(com.c_str(), "r");
if (!p_file)
{
fprintf(stderr, "Erro to popen");
}
while (fgets(buf, 500, p_file) != NULL)
{
s += buf;
}
pclose(p_file);
return s;
});
string ret = "";
std::future_status status = this_future.wait_for(std::chrono::milliseconds(700));
if (status == std::future_status::deferred)
{
ret = "shell cmd not exec";
}
else if (status == std::future_status::timeout)
{
ret = "shell cmd exec timeout";
}
else if (status == std::future_status::ready)
{
ret = this_future.get();
}
shell_future = std::move(this_future);
return ret;
}
string UrlDecode(string str)
{
string ret;
char ch;
int i, ii, len = str.length();
for (i = 0; i < len; i++)
{
if (str[i] != '%')
{
if (str[i] == '+')
ret += ' ';
else
ret += str[i];
}
else
{
sscanf(str.substr(i + 1, 2).c_str(), "%x", &ii);
ch = static_cast<char>(ii);
ret += ch;
i = i + 2;
}
}
return ret;
}
string getString(char x)
{
// string class has a constructor
// that allows us to specify size of
// string as first parameter and character
// to be filled in given size as second
// parameter.
string s(1, x);
return s;
}
string GetLevelStr(int level)
{
string levelStr = "";
for (int i = 0; i < level; i++)
{
levelStr += " ";
}
return levelStr;
}
string FormatJsonToDisplay(string json)
{
string result = "";
int level = 0;
for (string::size_type index = 0; index < json.size(); index++)
{
char c = json[index];
if (level > 0 && '\n' == json[json.size() - 1])
{
result += GetLevelStr(level);
}
switch (c)
{
case '{':
case '[':
result = result + getString(c) + "\n";
level++;
result += GetLevelStr(level);
break;
case ',':
result = result + getString(c) + "\n";
result += GetLevelStr(level);
break;
case '}':
case ']':
result += "\n";
level--;
result += GetLevelStr(level);
result += getString(c);
break;
default:
result += getString(c);
break;
}
}
return result;
}