4 uses MemStream
,NetAddr
,UnixType
;
13 stream
: tMemoryStream
;
16 type tMessageHandler
=procedure(msg
:tSMsg
);
17 procedure SetMsgHandler(OpCode
:byte; handler
:tMessageHandler
);
18 procedure SetHiMsgHandler(handler
:tMessageHandler
);
20 procedure SendMessage(const data
; len
:word; const rcpt
:tNetAddr
);
21 {procedure SendReply(const data; len:word; const rcpt:tSMsg );}
22 procedure SendMessage(const data
; len
:word; const rcpt
:tNetAddr
; channel
:word );
24 {#Sheduling and watching#}
25 type tFDEventHandler
=procedure(ev
:Word) of object;
26 type tOnTimer
=procedure of object;
27 procedure WatchFD(fd
:tHandle
; h
:tFDEventHandler
);
28 procedure Shedule(timeout
{ms}: LongWord
; h
:tOnTimer
);
29 procedure UnShedule(h
:tOnTimer
);
30 {note unshed will fail when called from OnTimer proc}
32 type tObjMessageHandler
=procedure(msg
:tSMsg
) of object;
33 {deliver message from peer to the object}
34 procedure SetMsgHandler(OpCode
:byte; from
:tNetAddr
; handler
:tObjMessageHandler
);
35 function IsMsgHandled(OpCode
:byte; from
:tNetAddr
):boolean;
37 function OptIndex(o
:string):word;
38 function OptParamCount(o
:word):word;
40 type tTimeVal
=UnixType
.timeval
;
45 USES SysUtils
,Sockets
,BaseUnix
49 {aim for most simple implementation, since could be extended anytime}
54 var pollArr
: packed array [tPollTop
] of tPollFd
;
56 cb
: tFDEventHandler
; {proc+object}
58 var pollHnd
: array [tPollTop
] of tFdHndDsc
;
59 var pollTop
: tPollTop
;
61 var hnd
: array [1..36] of tMessageHandler
;
62 var HiHnd
: tMessageHandler
;
64 type tSheduled_ptr
=^tSheduled
; tSheduled
=record
69 var ShedTop
: ^tSheduled
;
70 var ShedUU
: ^tSheduled
;
71 var LastShed
: UnixType
.timeval
;
72 var PollTimeout
:LongInt;
74 procedure SC(fn
:pointer; retval
:cint
);
76 if retval
< 0 then begin
77 raise eXception
.Create(Format('Socket error %d operation %P',[SocketError
,fn
]));
81 procedure s_SetupInet
;
82 var bind_addr
:tInetSockAddr
;
86 with bind_addr
do begin
88 oi
:=OptIndex('-port');
89 if oi
=0 then sin_port
:=htons(3511)
91 assert(OptParamCount(oi
)=1);
92 sin_port
:=htons(StrToInt(paramstr(oi
+1)));
94 sin_addr
.s_addr
:=0; {any}
95 s_inet
:=fpSocket(sin_family
,SOCK_DGRAM
,IPPROTO_UDP
);
97 turnon
:=IP_PMTUDISC_DO
;
98 SC(@fpsetsockopt
,fpsetsockopt(s_inet
, IPPROTO_IP
, IP_MTU_DISCOVER
, @turnon
, sizeof(turnon
)));
100 SC(@fpBind
,fpBind(s_inet
,@bind_addr
,sizeof(bind_addr
)));
101 with PollArr
[0] do begin
108 var Terminated
:boolean=false;
110 procedure SendMessage(const data
; len
:word; const rcpt
:tSockAddrL
);
112 {SC(@fpsendto,}fpsendto(s_inet
,@data
,len
,0,@rcpt
,sizeof(sockaddr_in
)){)};
114 procedure SendMessage(const data
; len
:word; const rcpt
:tNetAddr
);
118 SendMessage(data
,len
,sa
);
120 procedure SendMessage(const data
; len
:word; const rcpt
:tNetAddr
; channel
:word );
122 SendMessage(data
,len
,rcpt
);
123 {todo: optimization??}
126 procedure SignalHandler(sig
:cint
);CDecl;
129 if terminated
then raise eControlC
.Create('CtrlC DoubleTap') ;
131 writeln('Shutdown requested');
134 {index=iphash+opcode}
135 type tPeerTableBucket
=record
138 handler
:tObjMessageHandler
;
140 var PT
:array [0..255] of ^tPeerTableBucket
;
141 var PT_opcodes
: set of 1..high(hnd
);
143 function FindPT(opcode
:byte; addr
:tNetAddr
):Word; { $FFFF=fail}
146 i
:=(addr
.hash
+opcode
) mod high(PT
); {0..63}
147 for o
:=0 to high(PT
) do begin
148 result
:=(i
+o
) mod high(PT
);
149 if not assigned(PT
[result
]) then break
;
150 if (PT
[result
]^.opcode
=opcode
) and (PT
[result
]^.remote
=addr
) then exit
;
155 function IsMsgHandled(OpCode
:byte; from
:tNetAddr
):boolean;
156 begin result
:=FindPT(opcode
,from
)<>$FFFF end;
158 procedure UnSetMsgHandler(const from
:tNetAddr
; opcode
:byte);
161 h
:=FindPT(opcode
,from
);
162 if h
=$FFFF then exit
;
165 {go reverse exit on null, hash them, match: move to H and stop}
167 while (i
<>h
)and assigned(PT
[i
]) do begin
168 if (PT
[i
]^.remote
.hash
+PT
[i
]^.opcode
)=h
then begin
173 if i
=0 then i
:=high(PT
) else dec(i
);
177 procedure SetMsgHandler(OpCode
:byte; from
:tNetAddr
; handler
:tObjMessageHandler
);
180 UnSetMsgHandler(from
,opcode
);
181 if handler
=nil then exit
;
182 h
:=(from
.hash
+opcode
) mod high(PT
);
183 for o
:=0 to high(PT
) do begin
184 i
:=(h
+o
) mod high(PT
);
185 if not assigned(PT
[i
]) then break
;
188 PT
[i
]^.opcode
:=OpCode
;
190 PT
[i
]^.handler
:=handler
;
191 if opcode
<=high(hnd
) then Include(PT_opcodes
,opcode
);
194 {do not waste stack on statics}
195 var EventsCount
:integer;
196 var Buffer
:array [1..1024] of byte;
198 var From
:tSockAddrL
; {use larger struct so everything fits}
199 var FromLen
:LongWord
;
201 var curhnd
:tMessageHandler
;
202 var curhndo
:tObjMessageHandler
;
206 function DoSock(var p
:tPollFD
):boolean;
213 if (p
.revents
and pollIN
)=0 then exit
else result
:=true;
214 FromLen
:=sizeof(From
);
215 pkLen
:=fprecvfrom(p
.FD
,@Buffer
,sizeof(Buffer
),0,@from
,@fromlen
);
216 SC(@fprecvfrom
,pkLen
);
218 FromG
.FromSocket(from
);
219 Msg
.Source
:=@FromG
; {!thread}
221 Msg
.Data
:=@Buffer
; {!thread}
222 Msg
.stream
.Init(@Buffer
,pkLen
,sizeof(Buffer
));
223 Msg
.channel
:=0; {!multisocket}
224 if Buffer
[1]>=128 then curhnd
:=HiHnd
else if Buffer
[1]<=high(hnd
) then curhnd
:=hnd
[Buffer
[1]];
225 if (Buffer
[1]>high(hnd
))or(Buffer
[1] in PT_opcodes
) then begin
226 ptidx
:=FindPT(Buffer
[1],FromG
);
227 if ptidx
<$FFFF then curhndo
:=PT
[ptidx
]^.handler
;
234 var now
:UnixType
.timeval
absolute iNow
;
236 var olTop
:^tSheduled
;
242 ShedTop
:=nil; {unlink the current shed list}
243 fpgettimeofday(@Now
,nil);
244 delta
:=(Now
.tv_sec
-LastShed
.tv_sec
);
245 if delta
>6 then delta
:=5000 else delta
:=(delta
*1000)+((Now
.tv_usec
-LastShed
.tv_usec
) div 1000);
247 //writeln('DeltaTime: ',delta);
248 while assigned(cur
) do begin
249 if (cur
^.left
<=delta
)or(cur
^.left
=0) then begin
256 DEC(cur
^.left
,delta
);
257 //writeln('Left: ',cur^.left);
258 if pollTimeOut
>cur
^.left
then PollTimeOut
:=cur
^.left
;
263 pcur
^:=ShedTop
; {append newly added tasks to end of untriggererd list}
264 ShedTop
:=olTop
; {link in the untriggered tasks}
266 while assigned(cur
) do begin
267 if cur
^.left
<PollTimeout
then PollTimeout
:=cur
^.left
;
270 if pollTimeout
=0 then pollTimeOut
:=1;
276 while not terminated
do begin
279 EventsCount
:=fpPoll(@PollArr
[0],PollTop
,PollTimeout
);
281 if (eventscount
=-1)and terminated
then break
;
282 if eventscount
=-1 then break
; {fixme: print error}
283 if eventscount
=0 then continue
else begin
285 if DoSock(PollArr
[0]) then
286 if assigned(curhndo
) then curhndo(msg
)
287 else if assigned(curhnd
) then curhnd(msg
)
288 else raise eXception
.Create('No handler for opcode '+IntToStr(Buffer
[1]));
291 for tp
:=1 to pollTop
do if PollArr
[tp
].revents
>0 then begin
292 PollHnd
[tp
].CB(PollArr
[tp
].rEvents
);
293 PollArr
[tp
].revents
:=0;
297 write('Loop broken [');
302 procedure SetMsgHandler(OpCode
:byte; handler
:tMessageHandler
);
303 begin assert(hnd
[OpCode
]=nil); hnd
[OpCode
]:=handler
; end;
304 procedure SetHiMsgHandler(handler
:tMessageHandler
);
305 begin Hihnd
:=handler
; end;
307 procedure WatchFD(fd
:tHandle
; h
:tFDEventHandler
);
310 if assigned(h
) then begin
311 PollHnd
[pollTop
].CB
:=h
;
312 PollArr
[pollTop
].fd
:=fd
;
313 PollArr
[pollTop
].events
:=POLLERR
or POLLHUP
or POLLIN
or POLLPRI
or
314 POLLRDBAND
or POLLRDNORM
;
315 PollArr
[pollTop
].revents
:=0;
316 //writeln('Add watch ',pollTop,' on ',fd,' to ',IntToHex(qword(@h),8));
318 end else for opt
:=0 to high(opt
) do if PollArr
[opt
].fd
=fd
then begin
319 if (pollTop
-1)>opt
then begin
320 PollArr
[opt
]:=PollArr
[pollTop
-1];
321 PollHnd
[opt
]:=PollHnd
[pollTop
-1];
324 PollArr
[pollTop
].fd
:=-1;
325 PollArr
[pollTop
].events
:=0;
326 PollArr
[pollTop
].revents
:=0;
331 procedure Shedule(timeout
{ms}: LongWord
; h
:tOnTimer
);
335 if Assigned(ShedUU
) then begin
337 ShedUU
:=ShedUU
^.next
;
338 end else New(ShedTop
);
339 ShedTop
^.Left
:=timeout
;
344 procedure UnShedule(h
:tOnTimer
);
350 while assigned(cur
) do begin
351 if cur
^.cb
=h
then begin
352 pcur
^:=cur
^.next
; {unlink from main list}
353 cur
^.next
:=ShedUU
; ShedUU
:=cur
; {link to unused}
362 function OptIndex(o
:string):word;
365 while result
>0 do begin
366 if o
=system
.paramstr(result
) then break
;
371 function OptParamCount(o
:word):word;
375 if o
>0 then for i
:=o
+1 to paramcount
do begin
376 if paramstr(i
)[1]<>'-' then inc(result
)
384 fpSignal(SigInt
,@SignalHandler
);
385 fpSignal(SigTerm
,@SignalHandler
);
386 for i
:=1 to high(hnd
) do hnd
[i
]:=nil;
387 for i
:=1 to high(PT
) do PT
[i
]:=nil;
389 pollTop
:=1; {1 for basic listen}
391 ShedUU
:=nil; {todo: allocate a few to improve paging}
392 fpgettimeofday(@LastShed
,nil);