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
); overload
;
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
;
43 var mNow
:tMTime
; { miliseconds since start }
44 {overflows in hunderd hours }
48 USES SysUtils
,Sockets
,BaseUnix
52 {aim for most simple implementation, since could be extended anytime}
57 var pollArr
: packed array [tPollTop
] of tPollFd
;
59 cb
: tFDEventHandler
; {proc+object}
61 var pollHnd
: array [tPollTop
] of tFdHndDsc
;
62 var pollTop
: tPollTop
;
64 var hnd
: array [1..36] of tMessageHandler
;
65 var HiHnd
: tMessageHandler
;
67 type tSheduled_ptr
=^tSheduled
; tSheduled
=record
72 var ShedTop
: ^tSheduled
;
73 var ShedUU
: ^tSheduled
;
74 var LastShed
: UnixType
.timeval
;
75 var PollTimeout
:LongInt;
78 procedure SC(fn
:pointer; retval
:cint
);
80 if retval
< 0 then begin
81 raise eXception
.Create(Format('Socket error %d operation %P',[SocketError
,fn
]));
85 procedure s_SetupInet
;
86 var bind_addr
:tInetSockAddr
;
90 with bind_addr
do begin
92 oi
:=OptIndex('-port');
93 if oi
=0 then sin_port
:=htons(3511)
95 assert(OptParamCount(oi
)=1);
96 sin_port
:=htons(StrToInt(paramstr(oi
+1)));
98 sin_addr
.s_addr
:=0; {any}
99 s_inet
:=fpSocket(sin_family
,SOCK_DGRAM
,IPPROTO_UDP
);
100 SC(@fpSocket
,s_inet
);
101 turnon
:=IP_PMTUDISC_DO
;
102 SC(@fpsetsockopt
,fpsetsockopt(s_inet
, IPPROTO_IP
, IP_MTU_DISCOVER
, @turnon
, sizeof(turnon
)));
104 SC(@fpBind
,fpBind(s_inet
,@bind_addr
,sizeof(bind_addr
)));
105 with PollArr
[0] do begin
112 var Terminated
:boolean=false;
114 procedure SendMessage(const data
; len
:word; const rcpt
:tSockAddrL
);
116 {SC(@fpsendto,}fpsendto(s_inet
,@data
,len
,0,@rcpt
,sizeof(sockaddr_in
)){)};
118 procedure SendMessage(const data
; len
:word; const rcpt
:tNetAddr
);
122 SendMessage(data
,len
,sa
);
124 procedure SendMessage(const data
; len
:word; const rcpt
:tNetAddr
; channel
:word );
126 SendMessage(data
,len
,rcpt
);
127 {todo: optimization??}
130 procedure SignalHandler(sig
:cint
);CDecl;
133 if terminated
then raise eControlC
.Create('CtrlC DoubleTap') ;
137 {index=iphash+opcode}
138 type tPeerTableBucket
=record
141 handler
:tObjMessageHandler
;
143 var PT
:array [0..255] of ^tPeerTableBucket
;
144 var PT_opcodes
: set of 1..high(hnd
);
146 function FindPT(opcode
:byte; addr
:tNetAddr
):Word; { $FFFF=fail}
149 i
:=(addr
.hash
+opcode
) mod high(PT
); {0..63}
150 for o
:=0 to high(PT
) do begin
151 result
:=(i
+o
) mod high(PT
);
152 if not assigned(PT
[result
]) then break
;
153 if (PT
[result
]^.opcode
=opcode
) and (PT
[result
]^.remote
=addr
) then exit
;
158 function IsMsgHandled(OpCode
:byte; from
:tNetAddr
):boolean;
159 begin result
:=FindPT(opcode
,from
)<>$FFFF end;
161 procedure UnSetMsgHandler(const from
:tNetAddr
; opcode
:byte);
164 h
:=FindPT(opcode
,from
);
165 if h
=$FFFF then exit
;
168 {go reverse exit on null, hash them, match: move to H and stop}
169 if h
=0 then i
:=high(PT
) else i
:=h
-1;
170 while (i
<>h
)and assigned(PT
[i
]) do begin
171 if (PT
[i
]^.remote
.hash
+PT
[i
]^.opcode
)=h
then begin
176 if i
=0 then i
:=high(PT
) else dec(i
);
180 procedure SetMsgHandler(OpCode
:byte; from
:tNetAddr
; handler
:tObjMessageHandler
);
183 UnSetMsgHandler(from
,opcode
);
184 if handler
=nil then exit
;
185 h
:=(from
.hash
+opcode
) mod high(PT
);
186 for o
:=0 to high(PT
) do begin
187 i
:=(h
+o
) mod high(PT
);
188 if not assigned(PT
[i
]) then break
;
191 PT
[i
]^.opcode
:=OpCode
;
193 PT
[i
]^.handler
:=handler
;
194 if opcode
<=high(hnd
) then Include(PT_opcodes
,opcode
);
197 {do not waste stack on statics}
198 var EventsCount
:integer;
199 var Buffer
:array [1..4096] of byte;
201 var From
:tSockAddrL
; {use larger struct so everything fits}
202 var FromLen
:LongWord
;
204 var curhnd
:tMessageHandler
;
205 var curhndo
:tObjMessageHandler
;
209 function DoSock(var p
:tPollFD
):boolean;
216 if (p
.revents
and pollIN
)=0 then exit
else result
:=true;
217 FromLen
:=sizeof(From
);
218 pkLen
:=fprecvfrom(p
.FD
,@Buffer
,sizeof(Buffer
),0,@from
,@fromlen
);
219 SC(@fprecvfrom
,pkLen
);
221 FromG
.FromSocket(from
);
222 Msg
.Source
:=@FromG
; {!thread}
224 Msg
.Data
:=@Buffer
; {!thread}
225 Msg
.stream
.Init(@Buffer
,pkLen
,sizeof(Buffer
));
226 Msg
.channel
:=0; {!multisocket}
227 if Buffer
[1]>=128 then curhnd
:=HiHnd
else if Buffer
[1]<=high(hnd
) then curhnd
:=hnd
[Buffer
[1]];
228 if (Buffer
[1]>high(hnd
))or(Buffer
[1] in PT_opcodes
) then begin
229 ptidx
:=FindPT(Buffer
[1],FromG
);
230 if ptidx
<$FFFF then curhndo
:=PT
[ptidx
]^.handler
;
237 var now
:UnixType
.timeval
{ absolute iNow};
239 var delta_us
:LongInt;
243 {gmagic with delta-time, increment mNow, ...}
244 fpgettimeofday(@Now
,nil);
245 delta
:=(Now
.tv_sec
-LastShed
.tv_sec
);
246 delta_us
:=Now
.tv_usec
-LastShed
.tv_usec
;
247 delta
:=(delta
*1000)+(delta_us
div 1000);
248 umNow
:=umNow
+(delta_us
mod 1000);
249 if delta
>6000 then delta
:=5000;
252 if umNow
>1000 then begin inc(mNow
); dec(umNow
,1000) end;
253 if umNow
<-1000 then begin dec(mNow
); inc(umNow
,1000) end;
254 //writeln('DeltaTime: ',delta);
255 {first tick all tasks}
258 while assigned(cur
) do begin
259 if cur
^.left
<=delta
then cur
^.left
:=0 else begin
260 dec(cur
^.left
,delta
);
261 {also set next wake time}
262 if cur
^.left
<PollTimeout
then PollTimeout
:=cur
^.left
;
268 {correct floating-point glitch}
269 if pollTimeout
=0 then pollTimeOut
:=1;
270 {run first runnable task}
273 while assigned(cur
) do begin
274 if cur
^.left
=0 then begin
294 while not terminated
do begin
297 EventsCount
:=fpPoll(@PollArr
[0],PollTop
,PollTimeout
);
299 if (eventscount
=-1)and terminated
then break
;
300 if eventscount
=-1 then break
; {fixme: print error}
301 if eventscount
=0 then continue
else begin
303 if DoSock(PollArr
[0]) then
304 if assigned(curhndo
) then curhndo(msg
)
305 else if assigned(curhnd
) then curhnd(msg
)
306 else raise eXception
.Create('No handler for opcode '+IntToStr(Buffer
[1]));
309 for tp
:=1 to pollTop
do if PollArr
[tp
].revents
>0 then begin
310 PollHnd
[tp
].CB(PollArr
[tp
].rEvents
);
311 PollArr
[tp
].revents
:=0;
315 write('Loop broken [');
320 procedure SetMsgHandler(OpCode
:byte; handler
:tMessageHandler
);
321 begin assert(hnd
[OpCode
]=nil); hnd
[OpCode
]:=handler
; end;
322 procedure SetHiMsgHandler(handler
:tMessageHandler
);
323 begin Hihnd
:=handler
; end;
325 procedure WatchFD(fd
:tHandle
; h
:tFDEventHandler
);
328 if assigned(h
) then begin
329 PollHnd
[pollTop
].CB
:=h
;
330 PollArr
[pollTop
].fd
:=fd
;
331 PollArr
[pollTop
].events
:=POLLERR
or POLLHUP
or POLLIN
or POLLPRI
or
332 POLLRDBAND
or POLLRDNORM
;
333 PollArr
[pollTop
].revents
:=0;
334 //writeln('Add watch ',pollTop,' on ',fd,' to ',IntToHex(qword(@h),8));
336 end else for opt
:=0 to high(opt
) do if PollArr
[opt
].fd
=fd
then begin
337 if (pollTop
-1)>opt
then begin
338 PollArr
[opt
]:=PollArr
[pollTop
-1];
339 PollHnd
[opt
]:=PollHnd
[pollTop
-1];
342 PollArr
[pollTop
].fd
:=-1;
343 PollArr
[pollTop
].events
:=0;
344 PollArr
[pollTop
].revents
:=0;
349 procedure Shedule(timeout
{ms}: LongWord
; h
:tOnTimer
);
353 if Assigned(ShedUU
) then begin
355 ShedUU
:=ShedUU
^.next
;
356 end else New(ShedTop
);
357 ShedTop
^.Left
:=timeout
;
362 procedure UnShedule(h
:tOnTimer
);
366 //if ShedTop=nil then AbstractError;
369 while assigned(cur
) do begin
370 if 0=CompareByte(cur
^.cb
,h
,sizeof(h
)) then begin
371 pcur
^:=cur
^.next
; {unlink from main list}
372 cur
^.next
:=ShedUU
; ShedUU
:=cur
; {link to unused}
381 function OptIndex(o
:string):word;
384 while result
>0 do begin
385 if o
=system
.paramstr(result
) then break
;
390 function OptParamCount(o
:word):word;
394 if o
>0 then for i
:=o
+1 to paramcount
do begin
395 if paramstr(i
)[1]<>'-' then inc(result
)
405 fpSignal(SigInt
,@SignalHandler
);
406 fpSignal(SigTerm
,@SignalHandler
);
407 for i
:=1 to high(hnd
) do hnd
[i
]:=nil;
408 for i
:=1 to high(PT
) do PT
[i
]:=nil;
410 pollTop
:=1; {1 for basic listen}
412 ShedUU
:=nil; {todo: allocate a few to improve paging}
413 fpgettimeofday(@LastShed
,nil);