-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnewserver.cpp
More file actions
1645 lines (1391 loc) · 49.1 KB
/
newserver.cpp
File metadata and controls
1645 lines (1391 loc) · 49.1 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
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 <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <mutex>
#include <thread>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iomanip>
#include <arpa/inet.h>
#include <ctime>
#include <math.h>
#include <unordered_map>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <netinet/tcp.h>
#include <regex>
#include <openssl/sha.h>
#define BROADCAST_PORT 9000
#define TCP_PORT 8050
using namespace std;
mutex mtx;
const string USER_FILE = "users.txt";
const string DRIVER_FILE = "drivers.txt";
const string TRIPS_FILE = "trips.txt";
const string BOOKING_FILE = "bookings.txt";
const string BUS_FILE = "buses.txt";
// --- UTILITY ---
// Read from a file
vector<vector<string>> readFile(const string &filename)
{
vector<vector<string>> data;
ifstream file(filename);
string line;
while (getline(file, line))
{
stringstream ss(line);
vector<string> row;
string cell;
while (getline(ss, cell, ','))
row.push_back(cell);
data.push_back(row);
}
return data;
}
void hash_password(const char *password, char *output)
{
unsigned char hash[SHA256_DIGEST_LENGTH];
SHA256((const unsigned char *)password, strlen(password), hash);
for (int i = 0; i < SHA256_DIGEST_LENGTH; i++)
sprintf(output + (i * 2), "%02x", hash[i]);
output[SHA256_DIGEST_LENGTH * 2] = '\0';
}
string extractTime(const string &dateTime) {
// Example: "Thu May 15 06:45:00 2025" --> "06:45"
size_t timeStart = dateTime.find(':') - 2;
return dateTime.substr(timeStart, 5); // extracts "06:45"
}
string extractDateDDMMYYYY(const string &dateTime) {
// input: "Thu May 15 06:45:00 2025"
// output: "15/05/2025"
istringstream iss(dateTime);
string dayOfWeek, monthStr, dayStr, timeStr, yearStr;
iss >> dayOfWeek >> monthStr >> dayStr >> timeStr >> yearStr;
// Convert month name to number
map<string, string> monthMap = {
{"Jan", "01"}, {"Feb", "02"}, {"Mar", "03"}, {"Apr", "04"},
{"May", "05"}, {"Jun", "06"}, {"Jul", "07"}, {"Aug", "08"},
{"Sep", "09"}, {"Oct", "10"}, {"Nov", "11"}, {"Dec", "12"}
};
string month = monthMap[monthStr];
if (dayStr.length() == 1) dayStr = "0" + dayStr;
return dayStr + "/" + month + "/" + yearStr;
}
// Escape special characters in CSV
string escapeCSV(const string &field)
{
string escaped = field;
bool needsQuotes = escaped.find(',') != string::npos ||
escaped.find('"') != string::npos ||
escaped.find('\n') != string::npos;
if (needsQuotes)
{
size_t pos = 0;
while ((pos = escaped.find('"', pos)) != string::npos)
{
escaped.insert(pos, "\""); // Escape quotes by doubling them
pos += 2;
}
escaped = "\"" + escaped + "\"";
}
return escaped;
}
// FOR FINDING UPCOMING TRIPS ++ DYNAMIC PRICING
int timeToMinutes(const string &timeStr)
{
stringstream ss(timeStr);
int hours, minutes;
char colon;
ss >> hours >> colon >> minutes;
return hours * 60 + minutes;
}
bool isTimeDifferenceSafe(const string &existingTime, const string &newTime)
{
int existingMinutes = timeToMinutes(existingTime);
int newMinutes = timeToMinutes(newTime);
return abs(existingMinutes - newMinutes) >= 60;
}
// Updating a file
void updateFile(const string &filename, const vector<vector<string>> &data)
{
ofstream outFile(filename);
if (!outFile)
{
cerr << "❌ Could not open file: " << filename << endl;
return;
}
for (const auto &row : data)
{
for (size_t i = 0; i < row.size(); ++i)
{
outFile << escapeCSV(row[i]);
if (i < row.size() - 1)
outFile << ",";
}
outFile << "\n";
}
outFile.close();
}
void writeFile(const string &filename, const vector<string> &row) {
// Check if row is completely empty (i.e., all fields are empty)
bool isBlank = true;
for (const auto &field : row) {
if (!field.empty()) {
isBlank = false;
break;
}
}
if (row.empty() || isBlank) {
// Don't write empty or all-blank lines
return;
}
// First write using ofstream (for convenient formatting)
{
ofstream file(filename, ios::app);
if (!file) {
cerr << "❌ Could not open file: " << filename << endl;
return;
}
for (size_t i = 0; i < row.size(); ++i) {
file << escapeCSV(row[i]);
if (i < row.size() - 1)
file << ",";
}
file << "\n";
// Flush C++ buffers
file.flush();
} // ofstream closes here
// Then sync using file descriptor (POSIX)
int fd = open(filename.c_str(), O_WRONLY | O_APPEND);
if (fd != -1) {
fsync(fd); // Force sync to disk
close(fd);
}
}
// ---------- Communication Functions ----------
void sendPrompt(int sock, const string &msg)
{
// 1. Clear any pending data in the socket buffer
char temp_buf[256];
while (recv(sock, temp_buf, sizeof(temp_buf), MSG_DONTWAIT) > 0) {}
// 2. Send the message
send(sock, msg.c_str(), msg.length(), 0);
// 3. Force TCP buffer flush
int flag = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
// 4. Debug trace
cout << "[SEND] " << msg << endl;
// 5. Brief delay to stabilize client receive
usleep(10000); // 10ms
}
void sendMessage(int sock, const string &message)
{
send(sock, message.c_str(), message.size(), 0);
cout << "[SEND] " << message << endl;
}
string receiveInput(int sock)
{
int flag = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(flag));
char buffer[8192];
string input;
int blankInputCount = 0;
while (true) {
memset(buffer, 0, sizeof(buffer));
// Clear any unread junk in socket buffer
fd_set set;
struct timeval timeout = {0, 1000}; // 1ms
FD_ZERO(&set);
FD_SET(sock, &set);
while (select(sock + 1, &set, NULL, NULL, &timeout) > 0) {
recv(sock, buffer, sizeof(buffer) - 1, MSG_DONTWAIT);
}
int bytesReceived = recv(sock, buffer, sizeof(buffer) - 1, 0);
if (bytesReceived == 0) {
cout << "[RECV] Client closed the connection.\n";
close(sock);
pthread_exit(NULL);
}
else if (bytesReceived < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
usleep(10000);
continue;
}
perror("[RECV] Error receiving data");
continue;
}
buffer[bytesReceived] = '\0';
input = string(buffer);
// Trim whitespace
size_t start = input.find_first_not_of(" \t\r\n");
/*
if (start == string::npos) {
blankInputCount++;
if (blankInputCount >= 2) {
// Allow 2nd blank input to break sync (consume junk)
cout << "[RECV] ⚠️ Second blank input detected. Consuming it to resync...\n";
blankInputCount = 0;
continue; // skip this input
} else {
sendPrompt(sock, "⚠️ Empty input. Please enter again:\nPROMPT@> ");
continue;
}
}
*/
// If input was only spaces/newlines
if (start == string::npos) {
continue; // silently skip if you don't want to handle it anymore
}
size_t end = input.find_last_not_of(" \t\r\n");
input = input.substr(start, end - start + 1);
if (input == "A client got disconnected") {
cout << "⚠️ Client disconnected using Ctrl+C.\n";
close(sock);
pthread_exit(NULL);
}
cout << "[RECV] " << input << endl;
return input;
}
}
// Ignoring Case
bool equalsIgnoreCase(const string a, const string b) {
string lowerA = a;
string lowerB = b;
transform(lowerA.begin(), lowerA.end(), lowerA.begin(), ::tolower);
transform(lowerB.begin(), lowerB.end(), lowerB.begin(), ::tolower);
return lowerA == lowerB;
}
// UPDATING SEAT FILE BY LOCKING
mutex seatLockMutex;
bool bookSeat(int sock, const string &tripId, const string &seatChoice, const string &aadhar, const string &name)
{
string seatKey = tripId + "_" + seatChoice;
unique_lock<mutex> seatLock(seatLockMutex);
string seatFile = "seat" + tripId + ".txt";
auto seatData = readFile(seatFile);
bool seatFoundAndBooked = false;
for (auto &seat : seatData)
{
if (seat.size() >= 3 && seat[0] == seatChoice && seat[1] == "0")
{
seat[1] = "1";
seatFoundAndBooked = true;
break;
}
}
if (!seatFoundAndBooked)
{
sendPrompt(sock, "❌ Seat " + seatChoice + " is either already booked or invalid.\n");
return false;
}
// Update the seat data after booking
updateFile(seatFile, seatData);
return true;
}
// Aadhar validation
bool isValidAadhar(const string &aadhar)
{
return aadhar.length() == 12 && all_of(aadhar.begin(), aadhar.end(), ::isdigit);
}
bool isAadharExist(const string &aadhar)
{
auto users = readFile(USER_FILE);
for (const auto &row : users)
if (row.size() > 0 && row[0] == aadhar)
return true;
return false;
} // d
// License validation
bool isValidLicense(const string &license)
{
return (license.length() == 16);
}
bool isLicenseExist(const string &license)
{
auto users = readFile(DRIVER_FILE);
for (const auto &row : users)
if (row.size() > 0 && row[1] == license)
return true;
return false;
} // d
// CURRENT TIME CHECKING
// bool isTimeAfterNow(const string &timeStr)
// {
// int tripHour, tripMin;
// char colon;
// stringstream ss(timeStr);
// if (!(ss >> tripHour >> colon >> tripMin) || colon != ':')
// {
// return false; // Invalid time
// }
// time_t now = time(0);
// tm *ltm = localtime(&now);
// int currMinutes = ltm->tm_hour * 60 + ltm->tm_min;
// int tripMinutes = tripHour * 60 + tripMin;
// return tripMinutes > currMinutes;
// } // d
bool isDateTimeAfterNow(const string &dateTimeStr)
{
tm trip_tm = {};
if (strptime(dateTimeStr.c_str(), "%a %b %d %H:%M:%S %Y", &trip_tm) == nullptr)
{
return false; // Invalid datetime format
}
time_t trip_time = mktime(&trip_tm);
time_t now_time = time(nullptr);
return difftime(trip_time, now_time) > 0;
}
// int getMinutesFromDateTime(const string &dateTimeStr)
time_t getTimeFromDateTime(const string &dateTimeStr)
{
tm trip_tm = {};
if (strptime(dateTimeStr.c_str(), "%a %b %d %H:%M:%S %Y", &trip_tm) == nullptr)
{
return -1; // Error
}
// return trip_tm.tm_hour * 60 + trip_tm.tm_min;
return mktime(&trip_tm); // full datetime in seconds since epoch
}
//Printing the SEAT MATRIX
void seatMatrix(const string &tripId, int rows, int cols, int sock) {
string seatFile = "seat" + tripId + ".txt";
auto seatData = readFile(seatFile); // Load seat data
stringstream response;
response << "SEAT CHART FOR THE TRIP " << tripId << "\n";
// GATE and driver header
stringstream ss;
ss << "\n|===============================|";
ss << "\n| G Driver Seat |";
ss << "\n| A |";
ss << "\n| T |";
ss << "\n| E |";
ss << "\n|-------------------------------|";
response << ss.str() << "\n\n";
int leftCols = cols / 2;
int rightCols = cols - leftCols;
int totalSeats = rows * cols;
int seatIndex = 0;
for (int row = 0; row < rows; ++row) {
stringstream iconLine;
stringstream numberLine;
iconLine << "|";
numberLine << "|";
// Left side
for (int i = 0; i < leftCols; ++i) {
if (seatIndex < seatData.size() && seatData[seatIndex].size() >= 2) {
string status = seatData[seatIndex][1];
string seatIcon = (status == "0") ? "💺" : "❌";
iconLine << setw(2) << seatIcon << " ";
numberLine << setw(2) << setfill('0') << seatData[seatIndex][0] << " ";
} else {
iconLine << setw(3) << " ";
numberLine << setw(3) << " ";
}
++seatIndex;
}
// Middle aisle spacing
int aisleSpacing = 31 - (leftCols + rightCols) * 3 - 2; // 2 for '|'
iconLine << string(aisleSpacing, ' ');
numberLine << string(aisleSpacing, ' ');
// Right side
for (int i = 0; i < rightCols; ++i) {
if (seatIndex < seatData.size() && seatData[seatIndex].size() >= 2) {
string status = seatData[seatIndex][1];
string seatIcon = (status == "0") ? "💺" : "❌";
iconLine << setw(2) << seatIcon << " ";
numberLine << setw(2) << setfill('0') << seatData[seatIndex][0] << " ";
} else {
iconLine << setw(3) << " ";
numberLine << setw(3) << " ";
}
++seatIndex;
}
iconLine << " |";
numberLine << " |";
response << iconLine.str() << "\n";
response << numberLine.str() << "\n";
}
response << "\n|===============================|";
response << "\n 💺 = Available, ❌ = Booked\n";
// Collect price details
string windowPrice = "N/A";
string middlePrice = "N/A";
string backWindowPrice = "N/A";
string backMiddlePrice = "N/A";
if (!seatData.empty()) {
// Window seat (first seat)
if (seatData[0].size() >= 3) {
windowPrice = seatData[0][2];
}
// Middle seat (if cols > 2)
if (cols > 2) {
if (seatData.size() > 1 && seatData[1].size() >= 3) {
middlePrice = seatData[1][2];
} else {
middlePrice = "N/A";
}
}
// Back window seat
int backRowIndex = (rows - 1) * cols;
if (backRowIndex < seatData.size() && seatData[backRowIndex].size() >= 3) {
backWindowPrice = seatData[backRowIndex][2];
}
// Back middle seat (if cols > 2)
if (cols > 2) {
int backMiddleIndex = backRowIndex + 1;
if (backMiddleIndex < seatData.size() && seatData[backMiddleIndex].size() >= 3) {
backMiddlePrice = seatData[backMiddleIndex][2];
} else {
backMiddlePrice = "N/A";
}
}
}
// Build the price details response
response << "\n IMPORTANT PRICE DETAILS\n";
if (cols > 2) {
response << "1. LOWER PRICE FOR MIDDLE SEATS: " << middlePrice << "\n";
} else {
response << "1. LOWER PRICE FOR MIDDLE SEATS: Not applicable (no middle seats in 2-column layout)\n";
}
response << "2. MORE LOWER PRICES FOR BACK SEATS -> BACK WINDOW: " << backWindowPrice;
if (cols > 2) {
response << ", BACK MIDDLE: " << backMiddlePrice;
}
response << "\n";
response << "3. PRICE HIKE FOR WINDOW SEATS: " << windowPrice << "\n";
sendMessage(sock, response.str());
}
// --- CLASS DECLARATIONS ---
class User
{
public:
void registerUser(int sock);
string login(int sock);
};
// reservation handler
class ReservationHandler
{
private:
string uid;
public:
ReservationHandler(string userID) : uid(userID) {}
void viewTickets(int sock);
vector<vector<string>> viewTrips(int sock);
void reserve(int sock);
};
// driver class
class Driver
{
public:
void registerDriver(int sock);
string loginDriver(int sock);
};
//------BUS_TRIP_HANDLER-------------
class bus_trip_handler
{
string aadhar;
public:
bus_trip_handler(string a) : aadhar(a) {}; // constructor
void registerBus(int sock);
void insertTrip(int sock);
void createSeatFile(const string &tripId, int row, int col,float dist);
private:
string generateTripID()
{
auto trips = readFile(TRIPS_FILE);
int maxID = 0;
std::regex idPattern(R"(T(\d+))");
for (const auto& trip : trips) {
if (trip.empty()) continue;
std::smatch match;
if (std::regex_match(trip[0], match, idPattern)) {
int idNum = std::stoi(match[1]);
if (idNum > maxID) {
maxID = idNum;
}
}
}
stringstream ss;
ss << "T" << setfill('0') << setw(3) << (maxID + 1);
return ss.str();
}
}; // d
// --------- Create Seat File Function----------
void bus_trip_handler::createSeatFile(const string &tripId, int rows, int cols, float dist)
{
int k = 1;
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; ++c)
{
string seatNum = to_string(k);
string status = "0";
int baseprice;
// Check for back row seats first
if ((r == rows - 1) && (c == 0 || c == cols - 1))
{
baseprice = 105; // Back window seats
}
else if (r == rows - 1)
{
baseprice = 100; // Back middle seats
}
else if (c == 0 || c == cols - 1)
{
baseprice = 150; // Window seats (not back row)
}
else
{
baseprice = 120; // Middle seats (not back row)
}
// Calculate price based on distance
int multiplier = ceil(dist / 80.0);
int price = baseprice * multiplier;
vector<string> row = {seatNum, status, to_string(price)};
writeFile("seat" + tripId + ".txt", row);
k++;
}
}
}
// --- USER METHODS ---
//------------USER REGISTER--------------------------
void User::registerUser(int sock)
{
sendPrompt(sock, "Enter your Name:PROMPT@");
string name = receiveInput(sock);
int age = 0;
while (true)
{
sendPrompt(sock, "Enter your Age:PROMPT@");
string ageinput = receiveInput(sock);
try
{
age = stoi(ageinput);
if (age < 1)
sendMessage(sock, "Children below 1 year of age are not eligible for safety concerns.\n");
else if (age > 150)
sendMessage(sock, "❌ Enter realistic age data.\n");
else
break;
}
catch (invalid_argument &e)
{
sendMessage(sock, "❌ Invalid input. Please enter a number for age.\n");
}
}
string aadhar;
while (true)
{
sendPrompt(sock, "Enter your Unique Aadhar number:PROMPT@");
aadhar = receiveInput(sock);
if (!isValidAadhar(aadhar))
{
sendMessage(sock, "❌ Invalid Aadhar number. It must be 12 digits.\n");
continue;
}
if (isAadharExist(aadhar))
{
sendPrompt(sock, "This Aadhar number is already registered.\nIs it a Typo error? (y/n): PROMPT@");
string ans = receiveInput(sock);
if (ans == "y" || ans == "Y")
{
sendMessage(sock, "No worries, Re-enter again.\n");
continue;
}
else
{
sendMessage(sock, "You're already registered. Please login instead.\n");
return;
}
}
else
{
break;
}
}
sendPrompt(sock, "Enter a Strong Password:PROMPT@");
string password = receiveInput(sock);
// Hash the password
char hash[SHA256_DIGEST_LENGTH * 2 + 1];
hash_password(password.c_str(), hash);
mtx.lock();
// writeFile(USER_FILE, {aadhar, name, to_string(age), password});
writeFile(USER_FILE, {aadhar, name, to_string(age), string(hash)});
mtx.unlock();
sendMessage(sock, "✅ Registration Successful!\n");
} // d
//----------USER LOGIN----------------
string User::login(int sock)
{
sendPrompt(sock, "Enter Your Aadhar Number:PROMPT@");
string aadhar = receiveInput(sock);
sendPrompt(sock, "Enter Your Password:PROMPT@");
string password = receiveInput(sock);
// Hash the entered password
char hashedPassword[SHA256_DIGEST_LENGTH * 2 + 1];
hash_password(password.c_str(), hashedPassword);
auto users = readFile(USER_FILE);
for (auto &row : users)
{
if (row.size() < 4)
continue;
// if (row[0] == aadhar && row[3] == password)
if (row[0] == aadhar && row[3] == hashedPassword)
{
sendMessage(sock, "✅ Login Successful!\n");
return aadhar;
}
}
sendMessage(sock, "❌ Invalid Aadhar number or Password.\n");
return "";
} // d
//------DRIVER CLASS-----------------
void Driver::registerDriver(int sock)
{
// Asking for name
sendPrompt(sock, "Enter your Name:PROMPT@");
string name = receiveInput(sock);
// asking for age
int age = 0;
while (true)
{
sendPrompt(sock, "Enter your Age:PROMPT@");
string ageinput = receiveInput(sock);
try
{
age = stoi(ageinput);
if (age < 25 || age > 60)
sendMessage(sock, "Not Eligible to register here as a driver.\n");
else
break;
}
catch (invalid_argument &e)
{
sendMessage(sock, "❌ Invalid input. Please enter a number for age.\n");
}
}
// Asking for Aadhar no
string aadhar;
while (true)
{
sendPrompt(sock, "Enter your Unique Aadhar number:PROMPT@");
aadhar = receiveInput(sock);
if (!isValidAadhar(aadhar))
{
sendMessage(sock, "❌ Invalid Aadhar number. It must be 12 digits.\n");
continue;
}
if (isAadharExist(aadhar))
{
sendPrompt(sock, "This Aadhar number is already registered.\nIs it a Typo error? (y/n): PROMPT@");
string ans = receiveInput(sock);
if (ans == "y" || ans == "Y")
{
sendMessage(sock, "No worries, Re-enter again.\n");
continue;
}
else
{
sendMessage(sock, "You're already registered. Please login instead.\n");
return;
}
}
else
{
break;
}
}
// Asking for license
string license;
while (true)
{
sendPrompt(sock, "Enter your Unique License number:PROMPT@");
license = receiveInput(sock);
if (!isValidLicense(license))
{
sendMessage(sock, "❌ Invalid License number.\n");
continue;
}
if (isLicenseExist(license))
{
sendPrompt(sock, "This License number is already registered.\nIs it a Typo error? (y/n): PROMPT@");
string ans = receiveInput(sock);
if (ans == "y" || ans == "Y")
{
sendMessage(sock, "No worries, Re-enter again.\n");
continue;
}
else
{
sendMessage(sock, "You're already registered. Please login instead.\n");
return;
}
}
else
{
break;
}
}
sendPrompt(sock, "Enter a Strong Password:PROMPT@");
string password = receiveInput(sock);
// Hash the password
char hash[SHA256_DIGEST_LENGTH * 2 + 1];
hash_password(password.c_str(), hash);
mtx.lock();
writeFile(DRIVER_FILE, {aadhar, license, name, to_string(age), string(hash)});
// writeFile(DRIVER_FILE, {aadhar, license, name, to_string(age), password});
mtx.unlock();
sendMessage(sock, "✅ Registration Successful!\n");
} // d
//--------------LOGIN DRIVER-----------------
string trim(const string &s)
{
size_t start = s.find_first_not_of(" \t\n\r");
size_t end = s.find_last_not_of(" \t\n\r");
if (start == string::npos || end == string::npos)
return "";
return s.substr(start, end - start + 1);
}
string Driver::loginDriver(int sock)
{
sendPrompt(sock, "Enter Your Aadhar Number:PROMPT@");
string aadhar = trim(receiveInput(sock));
sendPrompt(sock, "Enter Your Password:PROMPT@");
string password = trim(receiveInput(sock));
// Hash the entered password
char hashedPassword[SHA256_DIGEST_LENGTH * 2 + 1];
hash_password(password.c_str(), hashedPassword);
auto users = readFile(DRIVER_FILE);
for (auto &row : users)
{
if (row.size() < 5)
continue;
string storedAadhar = trim(row[0]);
string storedPassword = trim(row[4]);
if (storedAadhar == aadhar && storedPassword == hashedPassword)
// if (storedAadhar == aadhar && storedPassword == password)
{
sendMessage(sock, "✅ Login Successful!\n");
return storedAadhar;
}
}
sendMessage(sock, "❌ Invalid Aadhar number or Password.\n");
return "";
}
//-------------Insert a Trip(bus_trip_handler)------------------
// Function to split string by delimiter
vector<string> split(const string &s, char delimiter)
{
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
// Function to validate date and compare
bool validateAndCompareDate(const string &departDate, time_t ×tamp, const string &startTime)
{
vector<string> parts = split(departDate, '/');
vector<string> timeParts = split(startTime, ':');
// Check for proper format
if (parts.size() != 3)
return false;
int day, month, year, hh, mm;
try
{
day = stoi(parts[0]);
month = stoi(parts[1]);
year = stoi(parts[2]);
hh = stoi(timeParts[0]);
mm = stoi(timeParts[1]);
}
catch (...)
{
return false; // Non-numeric input
}
// Basic range checks
if (month < 1 || month > 12 || day < 1 || day > 31 || year < 1900)
return false;
// Set up struct tm
struct tm datetime = {};
datetime.tm_year = year - 1900;
datetime.tm_mon = month - 1;
datetime.tm_mday = day;
datetime.tm_hour = hh;
datetime.tm_min = mm;
datetime.tm_sec = 0;
datetime.tm_isdst = -1;
// Convert to time_t
timestamp = mktime(&datetime);
cout << ctime(×tamp);
if (timestamp == -1)
return false; // Invalid timestamp
// Compare with current time
time_t now = time(NULL);
if (difftime(timestamp, now) < 0)
{
// Date is in the past
return false;
}
// Valid and in future
return true;
}
//-----------INSERT TRIPS----------------
void bus_trip_handler::insertTrip(int sock)
{
sendPrompt(sock, "Enter Bus Number: PROMPT@");
string busNo = receiveInput(sock);
sendPrompt(sock, "Enter Source: PROMPT@");
string source = receiveInput(sock);