-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.cpp
3404 lines (2987 loc) · 113 KB
/
server.cpp
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>
#include <sstream>
#include <fstream>
#include <signal.h>
#include <errno.h>
#include <unordered_map>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <map>
#include <jsoncpp/json/json.h>
#include <algorithm>
#include <functional>
#include <regex>
#include <random>
#include "nlohmann/json.hpp"
#include <filesystem>
#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <chrono>
#include <ctime>
#include <syslog.h>
#include <mutex>
#include <mysql/mysql.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/prepared_statement.h>
#include <poll.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <event2/keyvalq_struct.h>
#include <event2/bufferevent_ssl.h>
#include <event2/http_struct.h>
#include <curl/curl.h>
#include "header/router.h"
#include "header/database.h"
#include "header/crypto_utils.h"
// HTTP status codes
#define HTTP_OK 200
#define HTTP_BAD_REQUEST 400
#define HTTP_UNAUTHORIZED 401
#define HTTP_FORBIDDEN 403
#define HTTP_NOT_FOUND 404
#define HTTP_METHOD_NOT_ALLOWED 405
#define HTTP_INTERNAL 500
#define HTTP_CREATED 201
#define HTTP_NO_CONTENT 204
#define HTTP_BAD_REQUEST 400
#define HTTP_UNAUTHORIZED 401
#define HTTP_FORBIDDEN 403
#define HTTP_NOT_FOUND 404
#define HTTP_METHOD_NOT_ALLOWED 405
#define HTTP_CONFLICT 409
#define HTTP_INTERNAL 500
#define HTTP_SERVICE_UNAVAILABLE 503
namespace fs = std::filesystem;
using json = nlohmann::json;
const int HTTP_PORT = 8081;
const int HTTPS_PORT = 8444;
const int BUFFER_SIZE = 2048;
struct event_base *base;
struct evhttp *http;
struct evhttp *https;
struct bufferevent *bevcb(struct event_base *base, void *arg)
{
SSL *ssl = (SSL *)arg;
struct bufferevent *bev = bufferevent_openssl_socket_new(base, -1, ssl, BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE);
return bev;
}
struct bufferevent *https_bevcb(struct event_base *base, void *arg)
{
SSL_CTX *ctx = (SSL_CTX *)arg;
SSL *ssl = SSL_new(ctx);
return bufferevent_openssl_socket_new(base, -1, ssl, BUFFEREVENT_SSL_ACCEPTING, BEV_OPT_CLOSE_ON_FREE);
}
const std::string UPLOAD_DIR = "uploads/";
const std::string UPLOAD_IMAGE_DIR = "images/";
const std::string UPLOAD_OBJ_DIR = "uploads/objs/"; // .obj 파일을 저장할 디렉토리 경로
const std::string UPLOAD_ROOT_DIR = "./";
SSL *ssl;
class Logger
{
public:
enum class Level
{
DEBUG,
INFO,
WARNING,
ERROR
};
// Logger(const std::string &filename, Level level = Level::INFO)
// : file(filename, std::ios::app), level(level) {}
Logger() : level(Level::INFO) {}
void initialize(const std::string &filename, Level log_level = Level::INFO)
{
file.open(filename, std::ios::out | std::ios::trunc);
if (!file.is_open())
{
throw std::runtime_error("Failed to open log file: " + filename);
}
level = log_level;
log(Level::INFO, "Log initialized");
}
void log(Level msg_level, const std::string &message)
{
if (msg_level >= level)
{
std::time_t now = std::time(nullptr);
file << std::put_time(std::localtime(&now), "%Y-%m-%d %H:%M:%S")
<< " [" << levelToString(msg_level) << "] "
<< message << std::endl;
}
}
void setLevel(Level new_level)
{
level = new_level;
}
private:
std::ofstream file;
Level level;
std::string levelToString(Level l)
{
switch (l)
{
case Level::DEBUG:
return "DEBUG";
case Level::INFO:
return "INFO";
case Level::WARNING:
return "WARNING";
case Level::ERROR:
return "ERROR";
default:
return "UNKNOWN";
}
}
};
// 전역 로거 인스턴스
Logger g_logger;
class ServerError : public std::runtime_error
{
public:
ServerError(const std::string &message, int code)
: std::runtime_error(message), error_code(code) {}
int getErrorCode() const { return error_code; }
private:
int error_code;
};
void complex_operation()
{
sql::Connection *con = get_connection();
if (!con)
return;
try
{
con->setAutoCommit(false);
sql::Statement *stmt = con->createStatement();
stmt->execute("INSERT INTO ...");
stmt->execute("UPDATE ...");
con->commit();
delete stmt;
delete con;
}
catch (sql::SQLException &e)
{
g_logger.log(Logger::Level::ERROR, "SQL Exception: " + std::string(e.what()));
con->rollback();
delete con;
}
}
const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
const std::string SECRET_KEY = "your_secret_key";
std::string base64_encode(unsigned char const *bytes_to_encode, unsigned int in_len)
{
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--)
{
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3)
{
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (i = 0; (i < 4); i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for (j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while ((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_url_encode(unsigned char const *bytes_to_encode, unsigned int in_len)
{
std::string base64 = base64_encode(bytes_to_encode, in_len);
// Replace '+' with '-', '/' with '_'
for (char &c : base64)
{
if (c == '+')
{
c = '-';
}
else if (c == '/')
{
c = '_';
}
}
// Remove padding characters
base64.erase(std::remove(base64.begin(), base64.end(), '='), base64.end());
return base64;
}
std::string base64_decode(const char *encoded_string, unsigned int in_len)
{
BIO *b64, *bmem;
char *buffer = (char *)malloc(in_len);
memset(buffer, 0, in_len);
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf((void *)encoded_string, in_len);
bmem = BIO_push(b64, bmem);
BIO_set_flags(bmem, BIO_FLAGS_BASE64_NO_NL);
int decoded_len = BIO_read(bmem, buffer, in_len);
BIO_free_all(bmem);
std::string result(buffer, decoded_len);
free(buffer);
return result;
}
// Base64 디코딩 함수
std::vector<unsigned char> base64_decode_uchar(const std::string &encoded_string)
{
BIO *b64, *bmem;
size_t in_len = encoded_string.size();
std::vector<unsigned char> buffer(in_len);
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(encoded_string.c_str(), in_len);
bmem = BIO_push(b64, bmem);
BIO_set_flags(bmem, BIO_FLAGS_BASE64_NO_NL);
int decoded_len = BIO_read(bmem, buffer.data(), in_len);
buffer.resize(decoded_len);
BIO_free_all(bmem);
return buffer;
}
std::string base64_url_decode(const std::string &input)
{
std::string base64 = input;
// Replace '-' with '+', '_' with '/'
for (char &c : base64)
{
if (c == '-')
{
c = '+';
}
else if (c == '_')
{
c = '/';
}
}
// Add padding characters
while (base64.size() % 4)
{
base64 += '=';
}
return base64_decode(base64.c_str(), base64.size());
}
std::string urlDecode(const std::string &encoded)
{
std::string decoded;
char ch;
int i, ii;
for (i = 0; i < encoded.length(); i++)
{
if (int(encoded[i]) == 37)
{
sscanf(encoded.substr(i + 1, 2).c_str(), "%x", &ii);
ch = static_cast<char>(ii);
decoded += ch;
i = i + 2;
}
else
{
decoded += encoded[i];
}
}
return decoded;
}
std::string url_decode(const std::string &encoded)
{
std::string result;
for (size_t i = 0; i < encoded.length(); ++i)
{
if (encoded[i] == '%' && i + 2 < encoded.length())
{
int value;
std::istringstream is(encoded.substr(i + 1, 2));
if (is >> std::hex >> value)
{
result += static_cast<char>(value);
i += 2;
}
else
{
result += encoded[i];
}
}
else if (encoded[i] == '+')
{
result += ' ';
}
else
{
result += encoded[i];
}
}
return result;
}
std::string sha1(const std::string &str)
{
unsigned char hash[SHA_DIGEST_LENGTH];
SHA1(reinterpret_cast<const unsigned char *>(str.c_str()), str.size(), hash);
return std::string(reinterpret_cast<char *>(hash), SHA_DIGEST_LENGTH);
}
std::string generate_websocket_accept_key(const std::string &client_key)
{
std::string magic_key = client_key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
std::string hash = sha1(magic_key);
return base64_url_encode(reinterpret_cast<const unsigned char *>(hash.c_str()), hash.size());
}
std::string read_file(const std::string &file_path)
{
std::ifstream file(file_path);
if (!file.is_open())
{
return "";
}
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
void send_response(SSL *ssl, int client_socket, const std::string &response)
{
if (ssl)
{
SSL_write(ssl, response.c_str(), response.length());
}
else if (client_socket != -1)
{
send(client_socket, response.c_str(), response.length(), 0);
}
}
void send_html(SSL *ssl, int client_socket, const std::string &file_path)
{
std::string html_content = read_file(file_path);
if (html_content.empty())
{
std::cerr << "Failed to read " << file_path << std::endl;
return;
}
std::string response = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n"
"Content-Length: " +
std::to_string(html_content.size()) + "\r\n"
"Connection: close\r\n\r\n" +
html_content;
// SSL_write(ssl, response.c_str(), response.size());
send_response(ssl, client_socket, response);
}
void handle_websocket_connection(SSL *ssl, int client_socket, const std::string &client_key)
{
std::string accept_key = generate_websocket_accept_key(client_key);
std::string response = "HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: " +
accept_key + "\r\n\r\n";
send_response(ssl, client_socket, response);
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::string message = "Server message";
std::vector<char> ws_frame;
// Create WebSocket frame
ws_frame.push_back(0x81); // FIN and text frame
ws_frame.push_back(message.size()); // No mask, payload length
ws_frame.insert(ws_frame.end(), message.begin(), message.end());
int sent_bytes = SSL_write(ssl, ws_frame.data(), ws_frame.size());
if (sent_bytes < 0)
{
perror("send failed");
break; // Exit the loop if sending fails
}
}
}
// URL 인코딩된 데이터 파싱 함수
std::unordered_map<std::string, std::string> parse_urlencoded(const std::string &body)
{
std::unordered_map<std::string, std::string> params;
std::istringstream stream(body);
std::string key_value;
while (std::getline(stream, key_value, '&'))
{
size_t pos = key_value.find('=');
if (pos != std::string::npos)
{
std::string key = key_value.substr(0, pos);
std::string value = key_value.substr(pos + 1);
params[key] = value;
}
}
return params;
}
void handle_signup(SSLInfo *ssl_info, struct evhttp_request *req, const std::string &body)
{
struct evbuffer *buf = evbuffer_new();
json response;
auto params = parse_urlencoded(body);
if (params.find("username") != params.end() && params.find("password") != params.end())
{
std::string username = params["username"];
std::string password = params["password"];
std::string salt = generate_salt();
std::string hashed_password = hash_password(password, salt);
try
{
bool signup_success = withConnection([&](sql::Connection &con)
{
std::unique_ptr<sql::PreparedStatement> pstmt(con.prepareStatement(
"INSERT INTO USERS (USERNAME, PASSWORD, SALT) VALUES (?, ?, ?)"));
pstmt->setString(1, username);
pstmt->setString(2, hashed_password);
pstmt->setString(3, salt);
int affected_rows = pstmt->executeUpdate();
return affected_rows > 0; });
if (signup_success)
{
g_logger.log(Logger::Level::INFO, "Signup successful for user: " + username);
response["success"] = true;
response["message"] = "Signup successful";
}
else
{
g_logger.log(Logger::Level::WARNING, "Signup failed for user: " + username);
response["success"] = false;
response["message"] = "Signup failed (DB error)";
}
}
catch (const sql::SQLException &e)
{
response["success"] = false;
response["message"] = "Signup failed (DB error: " + std::string(e.what()) + ")";
}
}
else
{
response["success"] = false;
response["message"] = "Bad Request";
}
std::string json_response = response.dump();
evbuffer_add(buf, json_response.c_str(), json_response.length());
evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "application/json");
evhttp_send_reply(req, HTTP_OK, "OK", buf);
evbuffer_free(buf);
}
bool verify_user(const std::string &username, const std::string &password)
{
sql::Connection *con = get_connection();
if (!con)
return false;
try
{
sql::PreparedStatement *pstmt = con->prepareStatement(
"SELECT PASSWORD, SALT FROM USERS WHERE USERNAME = ?");
pstmt->setString(1, username);
sql::ResultSet *res = pstmt->executeQuery();
if (res->next())
{
std::string stored_password = res->getString("PASSWORD");
std::string salt = res->getString("SALT");
delete res;
delete pstmt;
delete con;
std::string hashed_input = hash_password(password, salt);
return stored_password == hashed_input;
}
delete res;
delete pstmt;
delete con;
return false;
}
catch (sql::SQLException &e)
{
std::cerr << "SQL Exception: " << e.what() << std::endl;
delete con;
return false;
}
}
std::string hmac_sha256(const std::string &key, const std::string &data)
{
unsigned char *digest;
unsigned int len = SHA256_DIGEST_LENGTH;
digest = HMAC(EVP_sha256(), key.c_str(), key.size(), (unsigned char *)data.c_str(), data.size(), NULL, NULL);
return std::string(reinterpret_cast<char *>(digest), len);
}
std::string create_jwt(const std::string &username, const std::string &secret_key)
{
// Header
Json::Value header;
header["alg"] = "HS256";
header["typ"] = "JWT";
// Payload
Json::Value payload;
payload["username"] = username;
std::time_t now = std::time(nullptr);
payload["exp"] = static_cast<Json::UInt64>(now + 3600); // 1 hour expiration
// JSON 객체를 문자열로 변환
Json::StreamWriterBuilder writer;
std::string header_str = Json::writeString(writer, header);
std::string payload_str = Json::writeString(writer, payload);
// Base64 URL 인코딩
std::string header_base64 = base64_url_encode(reinterpret_cast<const unsigned char *>(header_str.c_str()), header_str.length());
std::string payload_base64 = base64_url_encode(reinterpret_cast<const unsigned char *>(payload_str.c_str()), payload_str.length());
// Signature
std::string signature = hmac_sha256(secret_key, header_base64 + "." + payload_base64);
std::string signature_base64 = base64_url_encode(reinterpret_cast<const unsigned char *>(signature.c_str()), signature.length());
// JWT
return header_base64 + "." + payload_base64 + "." + signature_base64;
}
// 로그인 요청을 처리하는 함수
void handle_login(SSLInfo *ssl_info, struct evhttp_request *req, const std::string &body)
{
struct evbuffer *buf = evbuffer_new();
json response;
try
{
json request_data = json::parse(body);
if (!request_data.contains("username") || !request_data.contains("password"))
{
throw std::runtime_error("Missing username or password");
}
std::string username = request_data["username"];
std::string password = request_data["password"];
withConnection([&](sql::Connection &conn)
{
std::unique_ptr<sql::PreparedStatement> pstmt(conn.prepareStatement(
"SELECT PASSWORD, SALT FROM USERS WHERE USERNAME = ?"));
pstmt->setString(1, username);
std::unique_ptr<sql::ResultSet> res(pstmt->executeQuery());
if (res->next()) {
std::string stored_password = res->getString("PASSWORD");
std::string salt = res->getString("SALT");
std::string hashed_input = hash_password(password, salt);
if (stored_password == hashed_input) {
g_logger.log(Logger::Level::INFO, "Login successful for user: " + username);
std::string token = create_jwt(username, SECRET_KEY);
response["success"] = true;
response["token"] = token;
response["username"] = username;
} else {
g_logger.log(Logger::Level::WARNING, "Login failed for user: " + username);
response["success"] = false;
response["message"] = "Invalid credentials";
}
} else {
g_logger.log(Logger::Level::WARNING, "Login failed for user: " + username);
response["success"] = false;
response["message"] = "Invalid credentials";
} });
}
catch (const sql::SQLException &e)
{
g_logger.log(Logger::Level::ERROR, "Database error during login: " + std::string(e.what()));
response["success"] = false;
response["message"] = "Database error: " + std::string(e.what());
}
catch (const std::exception &e)
{
g_logger.log(Logger::Level::ERROR, "Unexpected error during login: " + std::string(e.what()));
response["success"] = false;
response["message"] = e.what();
}
std::string json_response = response.dump();
evbuffer_add(buf, json_response.c_str(), json_response.length());
evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "application/json");
evhttp_add_header(evhttp_request_get_output_headers(req), "X-Content-Type-Options", "nosniff");
evhttp_add_header(evhttp_request_get_output_headers(req), "X-Frame-Options", "DENY");
evhttp_add_header(evhttp_request_get_output_headers(req), "X-XSS-Protection", "1; mode=block");
evhttp_send_reply(req, HTTP_OK, "OK", buf);
evbuffer_free(buf);
}
bool is_username_taken(const std::string &username)
{
return withConnection([&username](sql::Connection &conn)
{
bool is_taken = false;
try
{
std::unique_ptr<sql::PreparedStatement> pstmt(conn.prepareStatement(
"SELECT COUNT(*) FROM USERS WHERE USERNAME = ?"));
pstmt->setString(1, username);
std::unique_ptr<sql::ResultSet> res(pstmt->executeQuery());
if (res->next())
{
int count = res->getInt(1);
is_taken = (count > 0);
}
}
catch (const sql::SQLException &e)
{
std::cerr << "SQL Exception in is_username_taken: " << e.what() << std::endl;
// 에러 발생 시 예외를 던져서 상위에서 처리하도록 합니다.
throw;
}
return is_taken; });
}
// 아이디 중복 확인 요청을 처리하는 함수
void handle_check_username(SSLInfo *ssl_info, struct evhttp_request *req, const std::string &body)
{
struct evbuffer *buf = evbuffer_new();
json response;
try
{
auto params = parse_urlencoded(body);
if (params.find("username") != params.end())
{
std::string username = params["username"];
bool is_taken = is_username_taken(username);
response["success"] = true;
response["is_taken"] = is_taken;
response["message"] = is_taken ? "Username is taken" : "Username is available";
}
else
{
response["success"] = false;
response["message"] = "Bad Request";
}
}
catch (const std::exception &e)
{
response["success"] = false;
response["message"] = "Error checking username: " + std::string(e.what());
}
std::string json_response = response.dump();
evbuffer_add(buf, json_response.c_str(), json_response.length());
evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "application/json");
evhttp_send_reply(req, HTTP_OK, "OK", buf);
evbuffer_free(buf);
}
void send_json_response(SSL *ssl, int client_socket, int status_code, const std::string &status_message, const json &response_json)
{
std::string json_str = response_json.dump();
std::ostringstream header_stream;
header_stream << "HTTP/1.1 " << status_code << " " << status_message << "\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << json_str.length() << "\r\n"
<< "Connection: close\r\n\r\n";
std::string header = header_stream.str();
std::string full_response = header + json_str;
size_t total_sent = 0;
const size_t chunk_size = 4096; // 4KB chunks
while (total_sent < full_response.length())
{
size_t remaining = full_response.length() - total_sent;
size_t to_send = std::min(remaining, chunk_size);
ssize_t sent;
if (ssl)
{
sent = SSL_write(ssl, full_response.c_str() + total_sent, to_send);
}
else
{
sent = send(client_socket, full_response.c_str() + total_sent, to_send, 0);
}
if (sent <= 0)
{
if (ssl)
{
int ssl_error = SSL_get_error(ssl, sent);
if (ssl_error == SSL_ERROR_WANT_WRITE || ssl_error == SSL_ERROR_WANT_READ)
{
// 재시도 필요
continue;
}
ERR_print_errors_fp(stderr);
}
else
{
perror("send failed");
}
break;
}
total_sent += sent;
}
if (total_sent != full_response.length())
{
std::cerr << "Warning: Not all data was sent. Sent "
<< total_sent << " out of " << full_response.length() << " bytes." << std::endl;
}
}
// void send_json_response(SSL *ssl, int client_socket, int status_code, const std::string &status_message, const json &response_json)
// {
// std::string json_str = response_json.dump();
// std::ostringstream response_stream;
// response_stream << "HTTP/1.1 " << status_code << " " << status_message << "\r\n";
// response_stream << "Content-Type: application/json\r\n";
// response_stream << "Content-Length: " << json_str.length() << "\r\n";
// response_stream << "\r\n";
// response_stream << json_str;
// std::string response = response_stream.str();
// // SSL_write(ssl, response.c_str(), response.length());
// send_response(ssl, client_socket, response);
// }
// void send_json_response(SSL *ssl, int client_socket, int status_code, const std::string &status_message, const std::string &json_content)
// {
// std::ostringstream response;
// response << "HTTP/1.1 " << status_code << " " << status_message << "\r\n";
// response << "Content-Type: application/json\r\n";
// response << "Cache-Control: no-cache\r\n";
// response << "Content-Length: " << json_content.length() << "\r\n";
// response << "\r\n";
// response << json_content;
// std::string response_str = response.str();
// size_t total_sent = 0;
// size_t remaining = response_str.length();
// while (total_sent < response_str.length()) {
// ssize_t bytes_sent;
// if (ssl) {
// bytes_sent = SSL_write(ssl, response_str.c_str() + total_sent, remaining);
// } else {
// bytes_sent = send(client_socket, response_str.c_str() + total_sent, remaining, 0);
// }
// if (bytes_sent <= 0) {
// // 에러 처리
// if (ssl) {
// std::cerr << "SSL_write failed. Error: " << SSL_get_error(ssl, bytes_sent) << std::endl;
// } else {
// std::cerr << "send failed. Error: " << strerror(errno) << std::endl;
// }
// break;
// }
// total_sent += bytes_sent;
// remaining -= bytes_sent;
// }
// if (total_sent != response_str.length()) {
// std::cerr << "Failed to send full response. Sent " << total_sent << " out of " << response_str.length() << " bytes." << std::endl;
// }
// }
// void send_json_response(SSL *ssl, int client_socket, int status_code, const std::string &status_message, const std::string &json_content)
// {
// std::ostringstream response;
// response << "HTTP/1.1 " << status_code << " " << status_message << "\r\n";
// response << "Content-Type: application/json\r\n";
// response << "Cache-Control: no-cache\r\n";
// response << "Content-Length: " << json_content.length() << "\r\n";
// response << "\r\n";
// response << json_content;
// std::string response_str = response.str();
// ssize_t bytes_sent = SSL_write(ssl, response_str.c_str(), response_str.length());
// if (bytes_sent != static_cast<ssize_t>(response_str.length()))
// {
// std::cerr << "Failed to send full response. Sent " << bytes_sent << " out of " << response_str.length() << " bytes." << std::endl;
// }
// }
void handle_user_count_request(SSLInfo *ssl_info, struct evhttp_request *req)
{
struct evbuffer *buf = evbuffer_new();
json response_json;
int status_code = HTTP_OK;
std::string status_message = "OK";
try
{
int user_count = withConnection([](sql::Connection &conn)
{
std::unique_ptr<sql::Statement> stmt(conn.createStatement());
std::unique_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT COUNT(*) FROM USERS"));
res->next();
return res->getInt(1); });
response_json["success"] = true;
response_json["user_count"] = user_count;
}
catch (const std::exception &e)
{
status_code = HTTP_INTERNAL;
status_message = "Internal Server Error";
response_json["success"] = false;
response_json["error"] = e.what();
}
std::string response_str = response_json.dump();
evbuffer_add(buf, response_str.c_str(), response_str.length());
struct evkeyvalq *headers = evhttp_request_get_output_headers(req);
evhttp_add_header(headers, "Content-Type", "application/json");
evhttp_send_reply(req, status_code, status_message.c_str(), buf);
evbuffer_free(buf);
}
// 파일 업로드 요청을 처리하는 함수
void handle_file_upload(SSL *ssl, int client_socket, const std::string &boundary, int bytes_received)
{
std::ofstream outfile;
char buffer[BUFFER_SIZE];
// int bytes_received;
bool file_started = false;
std::string filename;
while (bytes_received > 0)
{
std::string data(buffer, bytes_received);
if (!file_started)
{
size_t filename_pos = data.find("filename=\"");
if (filename_pos != std::string::npos)
{
filename_pos += 10;
size_t filename_end = data.find("\"", filename_pos);
filename = data.substr(filename_pos, filename_end - filename_pos);
outfile.open(UPLOAD_DIR + filename, std::ios::binary);
file_started = true;
}
}
else
{
size_t boundary_pos = data.find(boundary);
if (boundary_pos != std::string::npos)
{
outfile.write(data.c_str(), boundary_pos);
break;
}
else
{
outfile.write(data.c_str(), bytes_received);
}
}
}
outfile.close();
g_logger.log(Logger::Level::INFO, "File uploaded: " + filename);
std::string response = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 7\r\n"
"Connection: close\r\n\r\n"
"Success";
send_response(ssl, client_socket, response);
}
// 파일 다운로드 요청을 처리하는 함수
void handle_file_download(SSL *ssl, int client_socket, const std::string &filename)
{
std::ifstream infile(UPLOAD_DIR + filename, std::ios::binary);
if (!infile)
{
g_logger.log(Logger::Level::WARNING, "File not found: " + filename);
std::string response = "HTTP/1.1 404 Not Found\r\n"
"Content-Type: text/plain\r\n"
"Content-Length: 9\r\n"
"Connection: close\r\n\r\n"
"Not Found";
send_response(ssl, client_socket, response);
}
else
{
g_logger.log(Logger::Level::INFO, "File download started: " + filename);
infile.seekg(0, std::ios::end);
size_t file_size = infile.tellg();
infile.seekg(0, std::ios::beg);
g_logger.log(Logger::Level::INFO, "File download completed: " + filename);
std::string response = "HTTP/1.1 200 OK\r\n"