-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi3router.cpp
More file actions
3987 lines (3432 loc) · 107 KB
/
Copy pathi3router.cpp
File metadata and controls
3987 lines (3432 loc) · 107 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
/*
* Intermud-3 Router Copyright (c)2003 by Roger Libiez (Samson)
*
* Version 2.0
*
* See License/License.txt for legal info.
*/
/*
* Uncomment this to enable Noplex's packet verification.
* If not enabled, channel-admin packets will not be properly processed.
* However, with this enabled, packets can often get mangled beyond use.
* So only enable this if you're trying to help debug why channel-admin
* isn't working properly.
*/
#define PACKET_CHECK
#include <fcntl.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <poll.h>
#include <signal.h>
#include <chrono>
#include <cstring>
#include <filesystem>
#include <format>
#include <fstream>
#include <iostream>
#include <list>
#include <random>
#include <thread>
#include "i3router.h"
/*
* This will seed the random number generator once during startup. I guess it's magic code :P
* Uses the Mersenne Twister algorithm. - Samson 7/2/2026.
*/
std::mt19937 global_rng( std::random_device{}() );
std::list<descriptor_data *> descriptor_list;
std::list<ban_data *> ban_list;
std::list<i3_mud *> mud_list;
std::list<event_info *> eventlist;
std::list<i3_channel *> channel_list;
std::string I3_THISMUD;
std::string I3_THISIP;
int I3_socket = -1;
bool router_down = false;
long bytes_received = 0;
long bytes_sent = 0;
bool packetdebug = false; /* Packet debugging toggle, can be turned on to check outgoing packets */
std::chrono::system_clock::time_point current_time;
i3_mud *this_mud;
const char *alarm_section = "(unknown)";
int newdesc = -1;
int mud_count = 0;
int chan_count = 0;
long events_served = 0;
void close_socket( descriptor_data *dclose );
void i3_sendtoall( i3_mud *mud, std::string_view type, std::string_view msg );
descriptor_data::descriptor_data( )
{
}
descriptor_data::~descriptor_data( )
{
close( this->descriptor );
descriptor_list.remove( this );
}
event_info::event_info( )
{
}
event_info::~event_info( )
{
}
i3header::i3header( )
{
}
i3header::~i3header( )
{
}
ban_data::ban_data( )
{
}
ban_data::~ban_data( )
{
ban_list.remove( this );
}
i3_mud::i3_mud( )
{
}
i3_mud::~i3_mud( )
{
mud_list.remove( this );
}
i3_listener::i3_listener( )
{
}
i3_listener::~i3_listener( )
{
}
mlist::mlist( )
{
}
mlist::~mlist( )
{
}
i3_channel::i3_channel( )
{
}
i3_channel::~i3_channel( )
{
for( auto it = this->listeners.begin( ); it != this->listeners.end( ); )
{
i3_listener *listener = *it;
++it;
this->listeners.remove( listener );
deleteptr( listener );
}
for( auto it = this->m_listeners.begin( ); it != this->m_listeners.end( ); )
{
mlist *m_list = *it;
++it;
this->m_listeners.remove( m_list );
deleteptr( m_list );
}
this->listeners.clear();
this->m_listeners.clear();
channel_list.remove( this );
}
// This only exists to correct a legit mistake on the part of the C++ committee. Boolean values are not WORDS, they are NUMBERS. Treat them as such.
template <>
struct std::formatter<bool> : std::formatter<int>
{
auto format(bool b, format_context& ctx) const { return std::formatter<int>::format( b ? 1 : 0, ctx ); }
};
const std::string c_time( std::chrono::system_clock::time_point curtime )
{
const std::chrono::time_zone* zone = std::chrono::current_zone();
std::chrono::zoned_time zt{zone, std::chrono::floor<std::chrono::seconds>(curtime)};
// Format: Sun Jan 01, 2026 12:00:00 PM UTC
// %I is 12-hour clock, %p is AM/PM, %Z is zone name.
return std::format( "{:%a %b %d, %Y %I:%M:%S %p %Z}", zt );
}
// Historical compatibility: Returns FALSE when they match, TRUE when they don't.
bool str_cmp( std::string_view astr, std::string_view bstr )
{
// If neither one exists, then they're equal.
if( astr.empty() && bstr.empty() )
return false;
auto case_insensitive_equals = []( std::string_view a, std::string_view b ) {
return std::ranges::equal(a, b, [](char c1, char c2) {
return std::tolower( static_cast<unsigned char>(c1) ) == std::tolower( static_cast<unsigned char>(c2) );
});
};
if( case_insensitive_equals( astr, bstr ) )
return false; // They match.
return true; // They do not match.
}
// Strips off any leading and trailing spaces, plus any stray tabs, carriage returns, or newlines.
void strip_whitespace( std::string & str )
{
// This should be every conceivable whitespace character to run into.
const std::string_view whitespace = " \t\r\n\v\f";
// Find first non-whitespace character.
const auto start = str.find_first_not_of( whitespace );
if( start == std::string::npos )
{
str.clear(); // The string is entirely whitespace.
return;
}
// Find last non-whitespace character.
const auto end = str.find_last_not_of( whitespace );
// Update the string.
str = str.substr( start, end - start + 1 );
}
template <typename... Args>
void i3log( std::format_string<Args...> fmt, Args&&... args )
{
std::cerr << std::format( "{} :: ", c_time( current_time ) );
std::cerr << std::format( fmt, std::forward<Args>( args )... );
std::cerr << '\n';
}
template <typename... Args>
void i3bug( std::format_string<Args...> fmt, Args&&... args )
{
std::cerr << std::format( "{} :: *** BUG: ", c_time( current_time ) );
std::cerr << std::format( fmt, std::forward<Args>( args )... );
std::cerr << '\n';
}
void write_shutdown_file( )
{
std::ofstream stream( std::filesystem::path{"shutdown.txt"} );
if( !stream.is_open() )
{
i3bug( "{}: Cannot open shutdown.txt for writing: {}", __func__, std::strerror(errno) );
return;
}
stream << "Router shutdown was called.\n";
stream.close();
if( stream.fail() )
i3bug( "{}: Error occurred after closing shutdown.txt: {}", __func__, std::strerror(errno) );
}
void free_event( event_info * e )
{
eventlist.remove( e );
deleteptr( e );
}
void free_all_events( void )
{
for( auto it = eventlist.begin( ); it != eventlist.end( ); )
{
event_info *ev = *it;
++it;
free_event( ev );
}
}
void add_event( time_t when, void ( *callback ) ( void * ), void *data )
{
event_info *e = new event_info;
e->when = current_time + std::chrono::seconds( when );
e->callback = callback;
e->data = data;
for( auto it = eventlist.begin(); it != eventlist.end(); ++it )
{
event_info *cur = *it;
if( cur->when > e->when )
{
eventlist.insert( it, e );
return;
}
}
eventlist.push_back( e );
}
void run_events( std::chrono::system_clock::time_point newtime )
{
while( !eventlist.empty( ) )
{
event_info *e = eventlist.front();
if( e->when > newtime )
break;
auto callback = e->callback;
void *data = e->data;
// Temporarily changed in case the callback function needs to know if the event matches current real world time.
current_time = e->when;
eventlist.pop_front();
++events_served;
if( callback )
callback ( data );
else
i3bug( "{}: nullptr callback", __func__ );
deleteptr (e );
}
current_time = newtime;
}
void cancel_event( void ( *callback ) ( void * ), void *data )
{
for( auto it = eventlist.begin( ); it != eventlist.end( ); )
{
event_info *ev = *it;
++it;
if( ( !callback ) && ev->data == data )
free_event( ev );
else if( ( callback ) && ev->data == data && data != nullptr )
free_event( ev );
else if( ev->callback == callback && data == nullptr )
free_event( ev );
}
}
event_info *find_event( void ( *callback ) ( void * ), void *data )
{
for( auto* ev : eventlist )
{
if( ev->callback == callback && ev->data == data )
return ev;
}
return nullptr;
}
// Read one full line from a file, stopping at the first instance of the delimiter.
std::string i3fread_line( std::ifstream & stream, char delimiter )
{
std::string line;
if( std::getline( stream, line, delimiter ) )
strip_whitespace( line ); // Once you have the line, it's best to strip it of any potential whitespace characters to eliminate the possibility of a bloat loop later on when the value is written back to disk.
return line;
}
// Read one word from a file. Can be encased in single or double quotes.
std::string i3fread_word( std::ifstream & stream )
{
char c;
// Skip leading whitespace.
while( stream.get(c) && std::isspace( static_cast<unsigned char>(c) ) );
if( stream.eof() )
{
i3bug( "{}: EOF encountered on read.", __func__ );
return {};
}
std::string word;
word.reserve(64);
if( c == '\'' || c == '"' )
{
const char delimiter = c;
while( stream.get(c) && c != delimiter )
{
word.push_back(c);
}
if( stream.eof() )
{
i3bug( "{}: EOF encountered inside quoted string.", __func__ );
}
return word;
}
word.push_back(c);
while( stream.get(c) )
{
if( std::isspace( static_cast<unsigned char>(c) ) )
{
stream.unget();
break;
}
word.push_back(c);
}
return word;
}
// Read a letter from a file.
char i3fread_letter( std::ifstream & stream )
{
char c;
while( stream.get(c) )
{
if( !std::isspace( static_cast<unsigned char>( c ) ) )
{
return static_cast<char>( c );
}
}
i3bug( "{}: EOF encountered on read.", __func__ );
return '\0';
}
// Read to end of line (for comments).
void i3fread_to_eol( std::ifstream & stream )
{
stream.ignore( static_cast<std::streamsize>(MSL), '\n' );
}
// Searches through the channel list to see if one exists with the I3 channel name supplied to it.
i3_channel *find_channel( std::string_view name )
{
for( auto *channel :channel_list )
{
if( !str_cmp( channel->name, name ) )
return channel;
}
return nullptr;
}
i3_mud *find_mud( std::string_view name )
{
for( auto* mud: mud_list )
{
if( !str_cmp( name, mud->name ) )
return mud;
}
return nullptr;
}
// Add backslashes in front of the " and \'s
std::string I3_escape( std::string_view input )
{
std::string escaped;
escaped.reserve( input.size() * 2 );
for( char c : input )
{
if( c == '"' || c == '\\' )
{
escaped.push_back( '\\' );
}
escaped.push_back(c);
}
return escaped;
}
/*
* Gets the next I3 field, that is when the amount of {[("'s and
* ")]}'s match each other when a , is read. It's not foolproof, it
* should honestly be some kind of statemachine, which does error-
* checking. Right now I trust the I3-router to send proper packets
* only. How naive :-) [Indeed Edwin, but I suppose we have little choice :P - Samson]
*
* ps will point to the beginning of the next field.
*
*/
char *I3_get_field( char *packet, char **ps )
{
int count[256];
char has_apostrophe = 0, has_backslash = 0;
char foundit = 0;
bzero( count, sizeof(count) );
*ps = packet;
while( 1 )
{
switch( *ps[0] )
{
case '{': if( !has_apostrophe ) count[(int)'{']++; break;
case '}': if( !has_apostrophe ) count[(int)'}']++; break;
case '[': if( !has_apostrophe ) count[(int)'[']++; break;
case ']': if( !has_apostrophe ) count[(int)']']++; break;
case '(': if( !has_apostrophe ) count[(int)'(']++; break;
case ')': if( !has_apostrophe ) count[(int)')']++; break;
case '\\':
if( has_backslash )
has_backslash = 0;
else
has_backslash = 1;
break;
case '"':
if( has_backslash )
{
has_backslash = 0;
}
else
{
if( has_apostrophe )
has_apostrophe = 0;
else
has_apostrophe = 1;
}
break;
case ',':
case ':':
if( has_apostrophe )
break;
if( has_backslash )
break;
if( count[(int)'{'] != count[(int)'}'] )
break;
if( count[(int)'['] != count[(int)']'] )
break;
if( count[(int)'('] != count[(int)')'] )
break;
foundit = 1;
break;
default:
break;
}
if( foundit )
break;
(*ps)++;
}
*ps[0] = '\0';
(*ps)++;
return *ps;
}
/*
* Remove "'s at begin/end of string
* If a character is prefixed by \'s it also will be unescaped
*/
void I3_remove_quotes( char **ps )
{
char *ps1, *ps2;
if( *ps[0] == '"' )
(*ps)++;
if( (*ps)[strlen(*ps)-1] == '"' )
(*ps)[strlen(*ps)-1] = '\0';
ps1 = ps2 = *ps;
while( ps2[0] )
{
if( ps2[0] == '\\' )
{
ps2++;
}
ps1[0] = ps2[0];
ps1++;
ps2++;
}
ps1[0] = '\0';
}
/*
* Read the header of an I3 packet. pps will point to the next field
* of the packet.
*/
i3header *I3_get_header( char **pps )
{
char *ps = *pps, *next_ps;
i3header *header = new i3header;
I3_get_field( ps, &next_ps );
ps = next_ps;
I3_get_field( ps, &next_ps );
I3_remove_quotes( &ps );
strlcpy( header->originator_mudname, ps, 256 );
ps = next_ps;
I3_get_field( ps, &next_ps );
I3_remove_quotes( &ps );
strlcpy( header->originator_username, ps, 256 );
ps = next_ps;
I3_get_field( ps, &next_ps );
I3_remove_quotes( &ps );
strlcpy( header->target_mudname, ps, 256 );
ps = next_ps;
I3_get_field( ps, &next_ps );
I3_remove_quotes( &ps );
strlcpy( header->target_username, ps, 256 );
*pps = next_ps;
return header;
}
// Writes the string into the socket, prefixed by the size.
bool I3_write_packet( descriptor_data *d, std::string_view msg )
{
if( msg.empty() )
return true;
uint32_t len = htonl( static_cast<uint32_t>( msg.size() ) );
int sbytes = 0;
size_t offset = 0;
std::string packet;
packet.reserve( 4 + msg.size() );
packet.append( reinterpret_cast<const char*>(&len), 4 );
packet.append( msg );
while( offset < packet.size() )
{
size_t nBlock = std::min( packet.size() - offset, size_t{4096} );
int nWrite = send( d->descriptor, packet.data() + offset, static_cast<int>(nBlock), 0 );
if( nWrite == -1 )
{
if( errno == EWOULDBLOCK || errno == EAGAIN )
{
d->output_buffer.insert( 0, packet.substr(offset) );
return true; // Partially sent, not a fatal error
}
return false;
}
sbytes += nWrite;
offset += nWrite;
}
bytes_sent += sbytes;
if( packetdebug )
{
i3log( "Bytes Sent: {}", sbytes );
i3log( "Packet Sent: {}", msg );
}
d->output_buffer.erase();
return true;
}
void I3_send_packet( descriptor_data *d )
{
if( d == nullptr )
return;
if( !I3_write_packet( d, d->output_buffer ) )
i3log( "Unable to write to descriptor." );
}
// Write a string into the send-buffer. Does not yet send it.
void I3_write_buffer( i3_mud *mud, std::string_view msg )
{
if( !mud->desc )
return;
mud->desc->output_buffer.append( msg );
}
// Put a I3-header in the send-buffer. If a field is empty it will be replaced by a 0 (zero).
void I3_write_header( i3_mud *mud, std::string_view identifier, std::string_view originator_mudname, std::string_view originator_username, std::string_view target_mudname, std::string_view target_username )
{
I3_write_buffer( mud, "({\"" );
I3_write_buffer( mud, identifier );
I3_write_buffer( mud, "\",5," );
if( !originator_mudname.empty() && str_cmp( originator_mudname, "0" ) )
{
I3_write_buffer( mud, "\"" );
I3_write_buffer( mud, originator_mudname );
I3_write_buffer( mud, "\"," );
}
else I3_write_buffer( mud, "0," );
if( !originator_username.empty() && str_cmp( originator_username, "0" ) )
{
I3_write_buffer( mud, "\"" );
I3_write_buffer( mud, originator_username );
I3_write_buffer( mud, "\"," );
}
else I3_write_buffer( mud, "0," );
if( !target_mudname.empty() && str_cmp( target_mudname, "0" ) )
{
I3_write_buffer( mud, "\"" );
I3_write_buffer( mud, target_mudname );
I3_write_buffer( mud, "\"," );
}
else I3_write_buffer( mud, "0," );
if( !target_username.empty() && str_cmp( target_username, "0" ) )
{
I3_write_buffer( mud, "\"" );
I3_write_buffer( mud, target_username );
I3_write_buffer( mud, "\"," );
}
else I3_write_buffer( mud, "0," );
}
void I3_send_error( i3_mud *mud, std::string_view user, std::string_view code, std::string_view message, std::string_view packet )
{
I3_write_header( mud, "error", I3_THISMUD, "", mud->name, user );
I3_write_buffer( mud, "\"" );
I3_write_buffer( mud, code );
I3_write_buffer( mud, "\",\"" );
I3_write_buffer( mud, I3_escape( message ) );
I3_write_buffer( mud, "\"," );
if( packet.empty() || !str_cmp( packet, "0" ) )
I3_write_buffer( mud, "0," );
else
{
I3_write_buffer( mud, packet );
I3_write_buffer( mud, "," );
}
I3_write_buffer( mud, "})\r" );
}
int random_number( int from, int to )
{
if( from > to )
std::swap( from, to );
if( from == to )
return from;
static std::uniform_int_distribution<int> dist;
using param_t = std::uniform_int_distribution<int>::param_type;
return dist( global_rng, param_t( from, to ) );
}
void I3_fread_config_file( std::ifstream & stream )
{
std::string key;
while( stream >> key )
{
if( key[0] == '*' )
{
i3fread_to_eol( stream );
continue;
}
else if( key == "Router" )
this_mud->routerIP = i3fread_line( stream, '\n' );
else if( key == "Port" )
stream >> this_mud->player_port;
else if( key == "Routername" )
this_mud->routerName = i3fread_line( stream, '\n' );
else if( key == "End" )
return;
else
{
i3bug( "{}: Bad section '{}' in config file - skipping.", __func__, key );
i3fread_to_eol( stream );
}
}
}
bool I3_read_config( void )
{
i3log( "Loading Intermud-3 network data..." );
std::ifstream stream( std::filesystem::path{CONFIG_FILE} );
if( !stream.is_open() )
{
i3bug( "{}: Cannot open {} for reading: {}", __func__, CONFIG_FILE, std::strerror(errno) );
return false;
}
if( !this_mud )
this_mud = new i3_mud;
this_mud->player_port = 0;
std::string key;
while( stream >> key )
{
if( key == "#I3CONFIG" )
I3_fread_config_file( stream );
else if( key == "#END" )
break;
else
{
i3bug( "{}: Bad section '{}' in {} - skipping.", __func__, key, CONFIG_FILE );
i3fread_to_eol( stream );
}
}
stream.close();
if( this_mud->routerIP.empty() )
{
i3log( "Router IP not loaded in configuration file." );
i3log( "Network configuration aborted." );
return false;
}
if( !this_mud->player_port )
{
i3log( "Router port not loaded in configuration file." );
i3log( "Network configuration aborted." );
return false;
}
if( this_mud->routerName.empty() )
{
i3log( "No router name loaded in config file." );
i3log( "Network configuration aborted." );
return false;
}
I3_THISMUD = this_mud->routerName;
I3_THISIP = this_mud->routerIP;
i3log( "IP Address: {}", I3_THISIP );
i3log( "Network data loaded." );
return true;
}
void I3_readchannel( i3_channel *channel, std::ifstream & stream )
{
std::string key;
while( stream >> key )
{
if( key == "ChanName" )
channel->name = i3fread_line( stream, '\n' );
else if( key == "ChanMud" )
channel->host_mud = i3fread_line( stream, '\n' );
else if( key == "ChanStatus" )
stream >> channel->status;
else if( key =="Purgetime" )
{
time_t loaded_time;
stream >> loaded_time;
channel->purge_time = std::chrono::system_clock::from_time_t( loaded_time );
}
else if( key == "Mlist" )
{
mlist *m_list = new mlist;
m_list->name = i3fread_line( stream, '\n' );
channel->m_listeners.push_back( m_list );
}
else if( key == "End" )
return;
else
{
i3bug( "{}: Bad section '{}' - skipping.", __func__, key );
i3fread_to_eol( stream );
}
}
}
void I3_loadchannels( void )
{
i3log( "Loading channels..." );
std::ifstream stream( std::filesystem::path{CHANNEL_FILE} );
if( !stream.is_open() )
{
i3bug( "{}: Cannot open {} for reading: {}", __func__, CHANNEL_FILE, std::strerror(errno) );
return;
}
chan_count = 0;
std::string key;
while( stream >> key )
{
if( key == "#I3CHAN" )
{
i3_channel *channel = new i3_channel;
channel->purge_time = current_time + std::chrono::days( 30 );
I3_readchannel( channel, stream );
if( channel->purge_time <= std::chrono::system_clock::time_point{} )
channel->purge_time = current_time + std::chrono::days( 30 );
channel_list.push_back( channel );
if( !channel->host_mud.empty() && ( channel->status == 1 || channel->status == 2 ) )
{
bool found = false;
for( auto* m_list : channel->m_listeners )
{
if( !str_cmp( m_list->name, channel->host_mud ) )
{
found = true;
break;
}
}
if( !found )
{
mlist *m_list = new mlist;
m_list->name = channel->host_mud;
channel->m_listeners.push_back( m_list );
}
}
chan_count++;
continue;
}
else if( key == "#END" )
break;
else
{
i3bug( "{}: Bad section '{}' in {} - skipping.", __func__, key, CHANNEL_FILE );
i3fread_to_eol( stream );
}
}
stream.close();
i3log( "{} Channels loaded.", chan_count );
}
void save_channels( void )
{
std::ofstream stream( std::filesystem::path{CHANNEL_FILE} );
if( !stream.is_open() )
{
i3bug( "{}: Cannot open {} for writing: {}", __func__, CHANNEL_FILE, std::strerror(errno) );
return;
}
for( auto* channel : channel_list )
{
auto purge_time = std::chrono::system_clock::to_time_t( channel->purge_time );
stream << "#I3CHAN\n";
stream << std::format( "ChanName {}\n", channel->name );
stream << std::format( "ChanMud {}\n", channel->host_mud );
stream << std::format( "ChanStatus {}\n", channel->status );
stream << std::format( "Purgetime {}\n", purge_time );
for( auto* m_list : channel->m_listeners )
stream << std::format( "Mlist {}\n", m_list->name );
stream << "End\n\n";
}
stream << "#END\n";
stream.close();
if( stream.fail() )
i3bug( "{}: Error occurred after closing {}: ", __func__, CHANNEL_FILE, std::strerror(errno) );
}
void ev_savechanlist( void *data )
{
save_channels();
add_event( 300, ev_savechanlist, nullptr );
}
void send_chanlist( i3_mud *mud )
{
/*
* Muds crash if there are no channels. Empty chanlist packets are evil anyway.
* chanlist-reply also isn't required by the protocol to complete connection with.
*/
if( channel_list.empty() )
return;
mud->chanlist_id++;
I3_write_header( mud, "chanlist-reply", I3_THISMUD, "", mud->name, "" );
std::string s = std::format( "{},([", mud->chanlist_id );
I3_write_buffer( mud, s );
for( auto* chan : channel_list )
{
s = std::format( "\"{}\":({{\"{}\",{},}}),", chan->name, chan->host_mud, chan->status );
I3_write_buffer( mud, s );
}
I3_write_buffer( mud, "]),})\r" );
}
void send_locate_req( i3_mud *mud, i3header *header, std::string_view tname )
{
I3_write_header( mud, "locate-req", header->originator_mudname, header->originator_username, "", "" );
I3_write_buffer( mud, "\"" );
I3_write_buffer( mud, tname );
I3_write_buffer( mud, "\",})\r" );
}
void process_locate_req( i3_mud *mud, i3header *header, char *s )
{
char *ps = s, *next_ps;
char tname[MIL];
I3_get_field( ps, &next_ps );
I3_remove_quotes( &ps );
strlcpy( tname, ps, MIL );
for( auto* tmud : mud_list )
{
if( tmud->locate )
send_locate_req( tmud, header, tname );
}
}
void send_ucache_update( i3_mud *mud, i3header *header, std::string_view username, std::string_view visname, int gender )
{
std::string s;
I3_write_header( mud, "ucache-update", header->originator_mudname, "", "", "" );
I3_write_buffer( mud, "\"" );
I3_write_buffer( mud, username );
I3_write_buffer( mud, "\",\"" );
I3_write_buffer( mud, visname );
I3_write_buffer( mud, "\"," );
s = std::format( "{}", gender );
I3_write_buffer( mud, s );
I3_write_buffer( mud, ",})\r" );
}
void process_ucache_update( i3_mud *mud, i3header *header, char *s )
{