-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbarev.pas
More file actions
1329 lines (1118 loc) · 36.1 KB
/
barev.pas
File metadata and controls
1329 lines (1118 loc) · 36.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
{
Barev Protocol - Main Client
High-level API for Barev messaging
}
unit Barev;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Sockets, DateUtils,
BarevTypes, BarevConfig, BarevAvatar, BarevChatStates, BarevXML, BarevNet, BarevFT;
type
TypingNotificationProc = procedure(Buddy: TBarevBuddy; IsTyping: Boolean) of object;
{ Main Barev client }
TBarevClient = class
private
FNick: string;
FMyJID: string;
FMyIPv6: string;
FPort: Word;
FFileTransfer: TBarevFTManager;
FSocketManager: TBarevSocketManager;
FBuddies: TList; // List of TBarevBuddy
FRunning: Boolean;
FContactsFile: string;
FAvatarManager: TBarevAvatarManager;
FConfig: TBarevConfig;
FTypingNotificationsEnabled: Boolean;
FOnTypingNotification: procedure(Buddy: TBarevBuddy; IsTyping: Boolean) of object;
{ Event handlers }
FOnBuddyStatus: TBuddyStatusEvent;
FOnMessageReceived: TMessageReceivedEvent;
FOnConnectionState: TConnectionStateEvent;
FOnLog: TLogEvent;
procedure Log(const Level, Message: string);
function StripLeadingXMLDecl(const S: string): string;
function StripXMLDeclForStanza(const S: string): string;
function GetMyJID_Internal: string;
function GetMyIPv6_Internal: string;
procedure SendRawToBuddy(Buddy: TBarevBuddy; const Data: string);
function SendToBuddy(Buddy: TBarevBuddy; const Stanza: string): Boolean;
procedure HandleIncomingConnection;
procedure HandleBuddyConnection(Buddy: TBarevBuddy);
procedure ProcessReceivedData(Buddy: TBarevBuddy; const Data: string);
procedure HandleStreamStart(Buddy: TBarevBuddy; const XML: string);
procedure HandlePresence(Buddy: TBarevBuddy; const XML: string);
procedure HandleMessage(Buddy: TBarevBuddy; const XML: string);
procedure HandlePing(Buddy: TBarevBuddy; const XML: string);
procedure HandlePong(Buddy: TBarevBuddy; const XML: string);
procedure HandleIQ(Buddy: TBarevBuddy; const XML: string);
procedure TriggerBuddyStatus(Buddy: TBarevBuddy; OldStatus, NewStatus: TBuddyStatus);
procedure TriggerMessageReceived(Buddy: TBarevBuddy; const MessageText: string);
procedure TriggerConnectionState(Buddy: TBarevBuddy; State: TConnectionState);
public
constructor Create(const ANick, AMyIPv6: string; APort: Word = BAREV_DEFAULT_PORT);
destructor Destroy; override;
{ Client control }
function Start: Boolean;
procedure Stop;
procedure Process; // Call this regularly in your main loop
{ Buddy management }
function AddBuddy(const BuddyNick, BuddyIPv6: string; BuddyPort: Word = BAREV_DEFAULT_PORT): TBarevBuddy;
function RemoveBuddy(const BuddyJID: string): Boolean;
function GetBuddy(const BuddyJID: string): TBarevBuddy;
function GetBuddyCount: Integer;
function GetBuddyByIndex(Index: Integer): TBarevBuddy;
function FindBuddyByJID(const JID: string): TBarevBuddy;
function FindBuddyByIP(const IP: string): TBarevBuddy;
// This one apparently is not needed because source port is chosen by OS randomly
function FindBuddyByIPAndPort(const IP: string; Port: Word): TBarevBuddy;
{ Config file }
function LoadContactsFromFile(const FileName: string): Boolean;
function SaveContactsToFile(const FileName: string): Boolean;
function LoadConfig(const ConfigFile: string): Boolean;
function SaveConfig: Boolean;
{ Avatar }
function LoadMyAvatar(const FilePath: string): Boolean;
procedure ClearMyAvatar;
function GetMyAvatarHash: string;
function RequestBuddyAvatar(const BuddyJid: string): Boolean;
{ Typing notifications }
function SendTyping(const BuddyJID: string): Boolean;
function SendPaused(const BuddyJID: string): Boolean;
{ Communication }
function ConnectToBuddy(const BuddyJID: string): Boolean;
function SendMessage(const BuddyJID, MessageText: string): Boolean;
function SendPresence(Status: TBuddyStatus = bsAvailable; const StatusMessage: string = ''): Boolean;
function SendPresenceToBuddy(const BuddyJID: string; Status: TBuddyStatus = bsAvailable; const StatusMessage: string = ''): Boolean;
{ Properties }
property Nick: string read FNick;
property MyJID: string read FMyJID;
property MyIPv6: string read FMyIPv6;
property Port: Word read FPort;
property Running: Boolean read FRunning;
property ContactsFile: string read FContactsFile write FContactsFile;
property AvatarManager: TBarevAvatarManager read FAvatarManager;
property TypingNotificationsEnabled: Boolean read FTypingNotificationsEnabled write FTypingNotificationsEnabled;
{ Event handlers }
property OnBuddyStatus: TBuddyStatusEvent read FOnBuddyStatus write FOnBuddyStatus;
property OnMessageReceived: TMessageReceivedEvent read FOnMessageReceived write FOnMessageReceived;
property OnConnectionState: TConnectionStateEvent read FOnConnectionState write FOnConnectionState;
property OnLog: TLogEvent read FOnLog write FOnLog;
property FileTransfer: TBarevFTManager read FFileTransfer;
property OnTypingNotification: TypingNotificationProc read FOnTypingNotification write FOnTypingNotification;
end;
implementation
uses
StrUtils;
{ Helper function to normalize JID for comparison }
{ Uses NormalizeIPv6 from BarevTypes unit }
function NormalizeJID(const JID: string): string;
var
AtPos: Integer;
Nick, IPv6: string;
begin
AtPos := Pos('@', JID);
if AtPos = 0 then
begin
Result := LowerCase(JID);
Exit;
end;
Nick := Copy(JID, 1, AtPos - 1);
IPv6 := Copy(JID, AtPos + 1, Length(JID) - AtPos);
// Normalize the IPv6 part using barevtypes.NormalizeIPv6
IPv6 := NormalizeIPv6(IPv6);
Result := LowerCase(Nick) + '@' + IPv6;
end;
{ TBarevClient }
constructor TBarevClient.Create(const ANick, AMyIPv6: string; APort: Word);
begin
inherited Create;
FAvatarManager := TBarevAvatarManager.Create;
FConfig := nil; // Will be created when LoadConfig is called
FOnTypingNotification := nil;
FTypingNotificationsEnabled := True;
FNick := ANick;
FMyIPv6 := AMyIPv6;
FPort := APort;
FMyJID := FNick + '@' + FMyIPv6;
FSocketManager := TBarevSocketManager.Create(APort);
FSocketManager.OnLog := @Log;
FFileTransfer := TBarevFTManager.Create(
@SendRawToBuddy,
@Log,
@GetMyJID_Internal,
@GetMyIPv6_Internal
);
FBuddies := TList.Create;
FRunning := False;
FContactsFile := '';
Randomize;
end;
destructor TBarevClient.Destroy;
var
i: Integer;
begin
Stop;
// Free all buddies
for i := 0 to FBuddies.Count - 1 do
TBarevBuddy(FBuddies[i]).Free;
FBuddies.Free;
FreeAndNil(FFileTransfer);
FSocketManager.Free;
FreeAndNil(FAvatarManager);
FreeAndNil(FConfig);
inherited;
end;
// config
function TBarevClient.LoadConfig(const ConfigFile: string): Boolean;
var
i: Integer;
Contact: TConfigContact;
Buddy: TBarevBuddy;
begin
Result := False;
if not Assigned(FConfig) then
FConfig := TBarevConfig.Create(ConfigFile);
if not FConfig.Load then
Exit;
// Load user settings only if they exist in config.
// This allows using a contacts-only config file without wiping
// the identity that was already provided by the caller.
if FConfig.HasUserInfo then
begin
FNick := FConfig.UserNick;
FMyIPv6 := FConfig.UserIPv6;
FPort := FConfig.UserPort;
FMyJID := FNick + '@' + FMyIPv6;
end;
// Load avatar if configured
if (FConfig.UserAvatarPath <> '') and FileExists(FConfig.UserAvatarPath) then
FAvatarManager.LoadMyAvatar(FConfig.UserAvatarPath);
// Load contacts as buddies
for i := 0 to FConfig.GetContactCount - 1 do
begin
Contact := FConfig.GetContact(i);
Buddy := AddBuddy(Contact.Nick, Contact.IPv6, Contact.Port);
// If we have a cached avatar path, we could load it here
// (not implemented yet - would need to parse the avatar file)
end;
Result := True;
end;
function TBarevClient.SaveConfig: Boolean;
var
i: Integer;
Buddy: TBarevBuddy;
DefaultConfigPath: string;
begin
Result := False;
// If config not loaded, create one with default path
if not Assigned(FConfig) then
begin
DefaultConfigPath := GetUserDir + '.barev' + PathDelim + 'barev.ini';
if not DirectoryExists(GetUserDir + '.barev') then
ForceDirectories(GetUserDir + '.barev');
FConfig := TBarevConfig.Create(DefaultConfigPath);
Log('INFO', 'Created new config file: ' + DefaultConfigPath);
end;
// Save user settings
FConfig.UserNick := FNick;
FConfig.UserIPv6 := FMyIPv6;
FConfig.UserPort := FPort;
FConfig.UserAvatarPath := FAvatarManager.MyAvatarPath;
// Save contacts
FConfig.ClearContactList;
for i := 0 to FBuddies.Count - 1 do
begin
Buddy := TBarevBuddy(FBuddies[i]);
FConfig.AddContact(Buddy.Nick, Buddy.IPv6Address, Buddy.Port, Buddy.AvatarPath);
end;
Result := FConfig.Save;
end;
// avatar
function TBarevClient.LoadMyAvatar(const FilePath: string): Boolean;
begin
Result := FAvatarManager.LoadMyAvatar(FilePath);
if Result then
begin
Log('INFO', 'Avatar loaded: ' + FilePath);
Log('INFO', 'Avatar hash: ' + FAvatarManager.MyAvatarHash);
// Update config if we have one
if Assigned(FConfig) then
begin
FConfig.UserAvatarPath := FilePath;
SaveConfig;
end;
end;
end;
procedure TBarevClient.ClearMyAvatar;
begin
FAvatarManager.ClearMyAvatar;
if Assigned(FConfig) then
begin
FConfig.UserAvatarPath := '';
SaveConfig;
end;
end;
function TBarevClient.GetMyAvatarHash: string;
begin
Result := FAvatarManager.MyAvatarHash;
end;
function TBarevClient.RequestBuddyAvatar(const BuddyJID: string): Boolean;
var
Buddy: TBarevBuddy;
IQ, VCardReq: string;
IQ_ID: string;
begin
Result := False;
Buddy := FindBuddyByJID(BuddyJID);
if not Assigned(Buddy) then
Exit;
if not Assigned(Buddy.Connection) then
Exit;
// Check if connection is authenticated (csOnline might not be set in all cases)
if not (Buddy.Connection.State in [csAuthenticated, csOnline]) then
Exit;
IQ_ID := GenerateID('vcard');
IQ := '<iq type=''get'' to=''' + XMLEscape(BuddyJID) + ''' id=''' + IQ_ID + '''>' +
'<vCard xmlns=''vcard-temp''/>' +
'</iq>';
Result := SendToBuddy(Buddy, IQ);
if Result then
Log('INFO', 'Requested avatar from ' + BuddyJID);
end;
// typing
function TBarevClient.SendTyping(const BuddyJID: string): Boolean;
var
Buddy: TBarevBuddy;
Stanza: string;
begin
Result := False;
if not FTypingNotificationsEnabled then
Exit;
Buddy := FindBuddyByJID(BuddyJID);
if not Assigned(Buddy) then
Exit;
Stanza := TBarevChatStates.GenerateChatState(csComposing, BuddyJID);
Result := SendToBuddy(Buddy, Stanza);
end;
function TBarevClient.SendPaused(const BuddyJID: string): Boolean;
var
Buddy: TBarevBuddy;
Stanza: string;
begin
Result := False;
if not FTypingNotificationsEnabled then
Exit;
Buddy := FindBuddyByJID(BuddyJID);
if not Assigned(Buddy) then
Exit;
// Bonjour compatibility: send 'active' instead of 'paused'
// Pidgins Bonjour implementation only recognizes composing and active
Stanza := TBarevChatStates.GenerateChatState(csActive, BuddyJID);
Result := SendToBuddy(Buddy, Stanza);
end;
// file transfers
function TBarevClient.StripLeadingXMLDecl(const S: string): string;
var
P: SizeInt;
begin
Result := S;
{ Strip '<?xml ... ?>' if it is at the start }
if Pos('<?xml', Result) = 1 then
begin
P := Pos('?>', Result);
if P > 0 then
begin
Delete(Result, 1, P + 2); { remove through '?>' }
{ trim leading whitespace/newlines after the declaration }
while (Length(Result) > 0) and (Result[1] in [#9, #10, #13, ' ']) do
Delete(Result, 1, 1);
end;
end;
end;
function TBarevClient.StripXMLDeclForStanza(const S: string): string;
begin
{ Keep XML declaration ONLY for the opening stream header.
Everything else (iq/message/presence/stream end) must NOT include it. }
if (Pos('<?xml', S) = 1) and (Pos('<stream:stream', S) = 0) then
Result := StripLeadingXMLDecl(S)
else
Result := S;
end;
function TBarevClient.SendToBuddy(Buddy: TBarevBuddy; const Stanza: string): Boolean;
begin
Result := False;
if (Buddy = nil) or (Buddy.Connection = nil) then Exit;
Result := FSocketManager.SendData(Buddy.Connection.Socket, Stanza) > 0;
end;
procedure TBarevClient.HandleIQ(Buddy: TBarevBuddy; const XML: string);
var
Clean: string;
IQType, IQ_ID: string;
VCardXML: string;
AvatarData, MimeType, AvatarHash: string;
SavePath: string;
begin
Clean := StripLeadingXMLDecl(XML);
Log('DEBUG', 'HandleIQ from ' + Buddy.Nick + ': ' + Clean);
// Check for vCard requests FIRST (before file transfer)
if (Pos('<vCard xmlns=''vcard-temp''', Clean) > 0) or
(Pos('<vCard xmlns="vcard-temp"', Clean) > 0) then
begin
Log('DEBUG', 'Detected vCard request');
IQType := ExtractIQAttribute(Clean, 'type');
IQ_ID := ExtractIQAttribute(Clean, 'id');
Log('DEBUG', 'vCard IQType=' + IQType + ' ID=' + IQ_ID);
if IQType = 'get' then
begin
// Send our vCard
VCardXML := '<iq type=''result'' to=''' + XMLEscape(Buddy.JID) + ''' id=''' + IQ_ID + '''>' +
FAvatarManager.GenerateMyVCard +
'</iq>';
SendToBuddy(Buddy, VCardXML);
Log('INFO', 'Sent vCard to ' + Buddy.Nick);
end
else if IQType = 'result' then
begin
Log('DEBUG', 'Processing vCard result');
// Parse received vCard
if FAvatarManager.ParseVCardAvatar(Clean, AvatarData, MimeType, AvatarHash) then
begin
Log('DEBUG', 'ParseVCardAvatar succeeded: hash=' + AvatarHash);
// Save avatar
Buddy.AvatarData := AvatarData;
Buddy.AvatarMimeType := MimeType;
Buddy.AvatarHash := AvatarHash;
SavePath := FAvatarManager.SaveBuddyAvatar(Buddy.Nick, Buddy.IPv6Address,
AvatarData, MimeType);
if SavePath <> '' then
begin
Buddy.AvatarPath := SavePath;
Log('INFO', 'Saved avatar for ' + Buddy.Nick + ' to ' + SavePath)
end
else
begin
Log('WARN', 'Failed to save avatar for ' + Buddy.Nick);
end
end
else
begin
Log('WARN', 'ParseVCardAvatar failed for ' + Buddy.Nick);
end;
end
else
begin
Log('WARN', 'vCard with unhandled type: ' + IQType);
end;
Exit;
end;
// Check for ping/pong (standard XMPP IQ)
if Pos('<ping xmlns=''urn:xmpp:ping''', Clean) > 0 then
begin
// This is a ping, handle it
IQ_ID := ExtractIQAttribute(Clean, 'id');
VCardXML := '<iq type=''result'' to=''' + XMLEscape(Buddy.JID) + ''' id=''' + IQ_ID + '''/>';
SendToBuddy(Buddy, VCardXML);
Log('DEBUG', 'Responded to ping from ' + Buddy.Nick);
Exit;
end;
// Now check file transfer
if Assigned(FFileTransfer) then
begin
FFileTransfer.HandleIQ(Buddy, Clean);
// Don't exit - FT handler will log if unhandled
end;
end;
function TBarevClient.GetMyJID_Internal: string;
begin
Result := FMyJID;
end;
function TBarevClient.GetMyIPv6_Internal: string;
begin
Result := FMyIPv6;
end;
procedure TBarevClient.SendRawToBuddy(Buddy: TBarevBuddy; const Data: string);
var
OutData: string;
begin
if (Buddy = nil) or (Buddy.Connection = nil) then
Exit;
{ Prevent sending XML declarations inside an established stream }
OutData := StripXMLDeclForStanza(Data);
FSocketManager.SendData(Buddy.Connection.Socket, OutData);
end;
procedure TBarevClient.Log(const Level, Message: string);
begin
if Assigned(FOnLog) then
FOnLog(Level, Message);
end;
function TBarevClient.Start: Boolean;
begin
if FRunning then
begin
Log('WARN', 'Client already running');
Exit(True);
end;
Log('INFO', 'Starting Barev client as ' + FMyJID);
if not FSocketManager.StartListening then
begin
Log('ERROR', 'Failed to start listening');
Exit(False);
end;
FRunning := True;
Log('INFO', 'Barev client started successfully');
Result := True;
end;
procedure TBarevClient.Stop;
begin
if not FRunning then Exit;
Log('INFO', 'Stopping Barev client');
FSocketManager.StopListening;
FRunning := False;
Log('INFO', 'Barev client stopped');
end;
procedure TBarevClient.Process;
var
i: Integer;
Buddy: TBarevBuddy;
CurrentTime: TDateTime;
begin
if not FRunning then Exit;
// Check for incoming connections
HandleIncomingConnection;
// Process each buddy connection
for i := 0 to FBuddies.Count - 1 do
begin
Buddy := TBarevBuddy(FBuddies[i]);
if Assigned(Buddy.Connection) then
HandleBuddyConnection(Buddy)
else
begin
// Try to auto-connect to offline buddies
CurrentTime := Now;
if SecondsBetween(CurrentTime, Buddy.LastActivity) > RECONNECT_INTERVAL then
begin
Buddy.LastActivity := CurrentTime;
if Buddy.Status = bsOffline then
ConnectToBuddy(Buddy.JID);
end;
end;
end;
end;
procedure TBarevClient.HandleIncomingConnection;
var
NewSocket: TSocket;
ClientAddr: string;
ClientPort: Word;
Buddy: TBarevBuddy;
Conn: TBarevConnection;
begin
NewSocket := FSocketManager.AcceptConnection(ClientAddr, ClientPort);
if NewSocket < 0 then Exit;
Log('INFO', 'Incoming connection from ' + ClientAddr + ':' + IntToStr(ClientPort));
// SECURITY: Find buddy by BOTH IP and Port
// Buddy := FindBuddyByIPAndPort(ClientAddr, ClientPort);
// Silly me! Above does not make sense because source port is randomly chosen by the OS.
Buddy := FindBuddyByIP(ClientAddr);
Log('INFO', 'Incoming connection from ' + ClientAddr + ':' + IntToStr(ClientPort) +
' buddy=' + BoolToStr(Assigned(Buddy), True));
if not Assigned(Buddy) then
begin
Log('WARN', 'Security: Connection from unknown IP:Port ' + ClientAddr + ':' +
IntToStr(ClientPort) + ', closing');
CloseSocket(NewSocket);
Exit;
end;
// If buddy already has a connection, close the old one
if Assigned(Buddy.Connection) then
begin
Log('INFO', 'Replacing existing connection for ' + Buddy.JID);
Conn := Buddy.Connection;
Buddy.Connection := nil;
Conn.Free;
end;
// Create new connection
Conn := TBarevConnection.Create(Buddy, NewSocket, False);
Buddy.Connection := Conn;
Buddy.Status := bsAvailable;
Buddy.LastActivity := Now;
Buddy.PingFailures := 0;
TriggerConnectionState(Buddy, csConnecting);
end;
procedure TBarevClient.HandleBuddyConnection(Buddy: TBarevBuddy);
var
Data: string;
BytesRead: Integer;
Conn: TBarevConnection;
begin
if not Assigned(Buddy.Connection) then Exit;
Conn := Buddy.Connection;
// Check if socket is readable
if not FSocketManager.IsSocketReadable(Conn.Socket, 0) then
begin
// Check for ping timeout
if (Conn.LastPingTime > 0) and
(SecondsBetween(Now, Conn.LastPingTime) > PING_TIMEOUT) then
begin
Buddy.PingFailures := Buddy.PingFailures + 1;
Conn.LastPingTime := 0;
if Buddy.PingFailures >= MAX_PING_FAILURES then
begin
Log('WARN', 'Buddy ' + Buddy.JID + ' failed ping checks, disconnecting');
Conn := Buddy.Connection;
Buddy.Connection := nil;
Conn.Free;
TriggerBuddyStatus(Buddy, Buddy.Status, bsOffline);
Buddy.Status := bsOffline;
end;
end;
Exit;
end;
// Read data
BytesRead := FSocketManager.ReceiveData(Conn.Socket, Data);
if BytesRead < 0 then
begin
// Socket error
Log('ERROR', 'Socket error for ' + Buddy.JID);
Conn := Buddy.Connection;
Buddy.Connection := nil;
Conn.Free;
TriggerBuddyStatus(Buddy, Buddy.Status, bsOffline);
Buddy.Status := bsOffline;
Exit;
end
else if BytesRead = 0 then
begin
// Connection closed
Log('INFO', 'Connection closed by ' + Buddy.JID);
Conn := Buddy.Connection;
Buddy.Connection := nil;
Conn.Free;
TriggerBuddyStatus(Buddy, Buddy.Status, bsOffline);
Buddy.Status := bsOffline;
Exit;
end;
// Process received data
Buddy.LastActivity := Now;
Buddy.PingFailures := 0; // Reset on any activity
ProcessReceivedData(Buddy, Data);
end;
procedure TBarevClient.ProcessReceivedData(Buddy: TBarevBuddy; const Data: string);
var
Conn: TBarevConnection;
CompleteXML: string;
StreamStart: string;
TempBuffer: string;
begin
if not Assigned(Buddy.Connection) then Exit;
Conn := Buddy.Connection;
// Add to receive buffer
Conn.RecvBuffer := Conn.RecvBuffer + Data;
// Process complete XML stanzas
TempBuffer := Conn.RecvBuffer;
while Pos('<', TempBuffer) > 0 do
begin
// Check for stream start
if not Conn.StreamStartReceived then
begin
if IsStreamStart(TempBuffer) then
begin
HandleStreamStart(Buddy, TempBuffer);
// Remove processed part (stream header is not a complete element)
if Pos('>', TempBuffer) > 0 then
Delete(TempBuffer, 1, Pos('>', TempBuffer));
Conn.RecvBuffer := TempBuffer;
Continue;
end;
end;
// Check for stream end
if IsStreamEnd(TempBuffer) then
begin
Log('INFO', 'Stream end received from ' + Buddy.JID);
Conn := Buddy.Connection;
Buddy.Connection := nil;
Conn.Free;
TriggerBuddyStatus(Buddy, Buddy.Status, bsOffline);
Buddy.Status := bsOffline;
Exit;
end;
// Try to extract complete stanza
if Pos('<presence', TempBuffer) > 0 then
begin
if (Pos('/>', TempBuffer) > 0) or (Pos('</presence>', TempBuffer) > 0) then
begin
if Pos('/>', TempBuffer) > 0 then
CompleteXML := Copy(TempBuffer, 1, Pos('/>', TempBuffer) + 1)
else
CompleteXML := Copy(TempBuffer, 1, Pos('</presence>', TempBuffer) + 10);
//HandlePresence(Buddy, CompleteXML);
//HandleMessage(Buddy, StripLeadingXMLDecl(CompleteXML));
HandlePresence(Buddy, StripLeadingXMLDecl(CompleteXML));
Delete(TempBuffer, 1, Length(CompleteXML));
Conn.RecvBuffer := TempBuffer;
Continue;
end;
end;
if Pos('<message', TempBuffer) > 0 then
begin
if Pos('</message>', TempBuffer) > 0 then
begin
CompleteXML := Copy(TempBuffer, 1, Pos('</message>', TempBuffer) + 9);
HandleMessage(Buddy, CompleteXML);
Delete(TempBuffer, 1, Length(CompleteXML));
Conn.RecvBuffer := TempBuffer;
Continue;
end;
end;
if Pos('<iq', TempBuffer) > 0 then
begin
if (Pos('/>', TempBuffer) > 0) or (Pos('</iq>', TempBuffer) > 0) then
begin
if Pos('/>', TempBuffer) > 0 then
CompleteXML := Copy(TempBuffer, 1, Pos('/>', TempBuffer) + 1)
else
CompleteXML := Copy(TempBuffer, 1, Pos('</iq>', TempBuffer) + 4);
//if IsPing(CompleteXML) then
// HandlePing(Buddy, CompleteXML)
//else if IsPong(CompleteXML, Conn.LastPingID) then
// HandlePong(Buddy, CompleteXML);
if IsPing(CompleteXML) then
HandlePing(Buddy, CompleteXML)
else if IsPong(CompleteXML, Conn.LastPingID) then
HandlePong(Buddy, CompleteXML)
//else if Assigned(FFileTransfer) then
// FFileTransfer.HandleIQ(Buddy, CompleteXML);
//else if Pos('<iq', StripLeadingXMLDecl(CompleteXML)) = 1 then
else
HandleIQ(Buddy, CompleteXML);
Delete(TempBuffer, 1, Length(CompleteXML));
Conn.RecvBuffer := TempBuffer;
Continue;
end;
end;
// If we cannot process anything, wait for more data
Break;
end;
// Write back any remaining buffer
Conn.RecvBuffer := TempBuffer;
end;
procedure TBarevClient.HandleStreamStart(Buddy: TBarevBuddy; const XML: string);
var
Conn: TBarevConnection;
FromJID: string;
Response: string;
begin
if not Assigned(Buddy.Connection) then Exit;
Conn := Buddy.Connection;
FromJID := ExtractAttribute(XML, 'from');
Log('INFO', 'Stream start received from ' + FromJID);
// SECURITY: Validate that the JID in the stream header matches expected buddy
// Normalize both JIDs to handle IPv6 case differences and leading zeros
if NormalizeJID(FromJID) <> NormalizeJID(Buddy.JID) then
begin
Log('ERROR', 'Security: JID mismatch! Expected ' + Buddy.JID + ' but got ' + FromJID);
Log('ERROR', 'Security: Rejecting connection from ' + FromJID);
Conn := Buddy.Connection;
Buddy.Connection := nil;
Conn.Free;
Exit;
end;
Conn.StreamStartReceived := True;
// If we haven not sent our stream start yet, send it now
if not Conn.StreamStartSent then
begin
Response := BuildStreamHeader(FMyJID, Buddy.JID);
FSocketManager.SendData(Conn.Socket, Response);
Conn.StreamStartSent := True;
Log('INFO', 'Sent stream header to ' + Buddy.JID);
end;
// Stream is now established
Conn.State := csAuthenticated;
TriggerConnectionState(Buddy, csAuthenticated);
// Send presence
SendPresenceToBuddy(Buddy.JID, bsAvailable, '');
end;
procedure TBarevClient.HandlePresence(Buddy: TBarevBuddy; const XML: string);
var
PresenceType: string;
ShowElement: string;
StatusElement: string;
OldStatus: TBuddyStatus;
PhotoHash: string;
PhotoStart, PhotoEnd: Integer;
begin
OldStatus := Buddy.Status;
PresenceType := ExtractAttribute(XML, 'type');
if PresenceType = 'unavailable' then
begin
Log('INFO', Buddy.JID + ' is now offline');
TriggerBuddyStatus(Buddy, OldStatus, bsOffline);
Buddy.Status := bsOffline;
Exit;
end;
// Extract show element
ShowElement := ExtractElementContent(XML, 'show');
StatusElement := ExtractElementContent(XML, 'status');
if ShowElement <> '' then
Buddy.Status := StringToStatus(ShowElement)
else
Buddy.Status := bsAvailable;
Buddy.StatusMessage := StatusElement;
Log('INFO', Buddy.JID + ' is now ' + StatusToString(Buddy.Status));
TriggerBuddyStatus(Buddy, OldStatus, Buddy.Status);
if Pos('<x xmlns="' + VCARD_UPDATE_NAMESPACE + '"', XML) > 0 then
begin
PhotoStart := Pos('<photo>', XML);
PhotoEnd := Pos('</photo>', XML);
if (PhotoStart > 0) and (PhotoEnd > 0) then
begin
PhotoHash := Copy(XML, PhotoStart + 7, PhotoEnd - PhotoStart - 7);
// If hash changed and is not empty, request the avatar
if (PhotoHash <> '') and (PhotoHash <> Buddy.AvatarHash) then
begin
Log('INFO', 'Avatar update detected for ' + Buddy.Nick + ', requesting...');
RequestBuddyAvatar(Buddy.JID);
end;
end;
end;
end;
procedure TBarevClient.HandleMessage(Buddy: TBarevBuddy; const XML: string);
var
Body: string;
ChatState: TChatState;
IsTyping: Boolean;
begin
Body := ExtractElementContent(XML, 'body');
if Body <> '' then
begin
Log('INFO', 'Message from ' + Buddy.JID + ': ' + Body);
TriggerMessageReceived(Buddy, Body);
end;
// Process chat state notifications if enabled
if FTypingNotificationsEnabled then
begin
ChatState := TBarevChatStates.ParseChatState(XML);
if ChatState = csComposing then
begin
IsTyping := True;
if Assigned(FOnTypingNotification) then
FOnTypingNotification(Buddy, IsTyping);
end
else if ChatState = csPaused then
begin
IsTyping := False;
if Assigned(FOnTypingNotification) then
FOnTypingNotification(Buddy, IsTyping);
end;
end;
end;
procedure TBarevClient.HandlePing(Buddy: TBarevBuddy; const XML: string);
var
PingID: string;
Pong: string;
begin
PingID := ExtractAttribute(XML, 'id');
Log('DEBUG', 'Ping received from ' + Buddy.JID + ', ID: ' + PingID);
// Send pong
Pong := BuildPong(Buddy.JID, PingID);
FSocketManager.SendData(Buddy.Connection.Socket, Pong);
Log('DEBUG', 'Sent pong to ' + Buddy.JID);
end;
procedure TBarevClient.HandlePong(Buddy: TBarevBuddy; const XML: string);
begin
Log('DEBUG', 'Pong received from ' + Buddy.JID);
Buddy.Connection.LastPingTime := 0; // Clear ping timeout
Buddy.PingFailures := 0;
end;
function TBarevClient.FindBuddyByJID(const JID: string): TBarevBuddy;
var
i: Integer;
NormalizedSearchJID: string;
begin
Result := nil;