ummgr print client address and bug found
[brdnet.git] / ServerLoop.pas
blob07ff1e8ab8f10469f7b01ee514a04689ec6cfa8f
1 UNIT ServerLoop;
3 INTERFACE
4 uses MemStream,NetAddr,UnixType;
6 procedure Main;
8 {#Message handling#}
9 type tSMsg=object
10 Source: ^tNetAddr;
11 Length: {Long}Word;
12 Data: pointer;
13 stream: tMemoryStream;
14 channel: word;
15 end;
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;
41 type tMTime=DWORD;
42 var iNow:tTimeVal;
43 var mNow:tMTime; { miliseconds since start }
44 {overflows in hunderd hours }
46 IMPLEMENTATION
48 USES SysUtils,Sockets,BaseUnix
49 ,Unix
52 {aim for most simple implementation, since could be extended anytime}
54 var s_inet:tSocket;
56 type tPollTop=0..7;
57 var pollArr: packed array [tPollTop] of tPollFd;
58 type tFdHndDsc=record
59 cb: tFDEventHandler; {proc+object}
60 end;
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
68 left:LongWord;
69 cb:tOnTimer;
70 next:tSheduled_ptr;
71 end;
72 var ShedTop: ^tSheduled;
73 var ShedUU: ^tSheduled;
74 var LastShed: UnixType.timeval;
75 var PollTimeout:LongInt;
76 var umNow:integer;
78 procedure SC(fn:pointer; retval:cint);
79 begin
80 if retval < 0 then begin
81 raise eXception.Create(Format('Socket error %d operation %P',[SocketError,fn]));
82 end;
83 end;
85 procedure s_SetupInet;
86 var bind_addr:tInetSockAddr;
87 var turnon:cint;
88 var oi:word;
89 begin
90 with bind_addr do begin
91 sin_family:=AF_INET;
92 oi:=OptIndex('-port');
93 if oi=0 then sin_port:=htons(3511)
94 else begin
95 assert(OptParamCount(oi)=1);
96 sin_port:=htons(StrToInt(paramstr(oi+1)));
97 end;
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)));
103 end;
104 SC(@fpBind,fpBind(s_inet,@bind_addr,sizeof(bind_addr)));
105 with PollArr[0] do begin
106 fd:=s_inet;
107 events:=pollIN;
108 revents:=0;
109 end;
110 end;
112 var Terminated:boolean=false;
114 procedure SendMessage(const data; len:word; const rcpt:tSockAddrL );
115 begin
116 {SC(@fpsendto,}fpsendto(s_inet,@data,len,0,@rcpt,sizeof(sockaddr_in)){)};
117 end;
118 procedure SendMessage(const data; len:word; const rcpt:tNetAddr );
119 var sa:tSockAddrL;
120 begin
121 rcpt.ToSocket(sa);
122 SendMessage(data,len,sa);
123 end;
124 procedure SendMessage(const data; len:word; const rcpt:tNetAddr; channel:word );
125 begin
126 SendMessage(data,len,rcpt);
127 {todo: optimization??}
128 end;
130 procedure SignalHandler(sig:cint);CDecl;
131 begin
132 writeln;
133 if terminated then raise eControlC.Create('CtrlC DoubleTap') ;
134 Terminated:=true;
135 end;
137 {index=iphash+opcode}
138 type tPeerTableBucket=record
139 opcode:byte;
140 remote:tNetAddr;
141 handler:tObjMessageHandler;
142 end;
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}
147 var i,o:word;
148 begin
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;
154 end;
155 result:=$FFFF;
156 end;
158 function IsMsgHandled(OpCode:byte; from:tNetAddr):boolean;
159 begin result:=FindPT(opcode,from)<>$FFFF end;
161 procedure UnSetMsgHandler(const from:tNetAddr; opcode:byte);
162 var i,h:word;
163 begin
164 h:=FindPT(opcode,from);
165 if h=$FFFF then exit;
166 Dispose(PT[h]);
167 PT[h]:=nil;
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
172 PT[h]:=PT[i];
173 PT[i]:=nil;
174 break;
175 end;
176 if i=0 then i:=high(PT) else dec(i);
177 end;
178 end;
180 procedure SetMsgHandler(OpCode:byte; from:tNetAddr; handler:tObjMessageHandler);
181 var h,o,i:word;
182 begin
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;
189 end;
190 New(PT[i]);
191 PT[i]^.opcode:=OpCode;
192 PT[i]^.remote:=from;
193 PT[i]^.handler:=handler;
194 if opcode<=high(hnd) then Include(PT_opcodes,opcode);
195 end;
197 {do not waste stack on statics}
198 var EventsCount:integer;
199 var Buffer:array [1..4096] of byte;
200 var pkLen:LongWord;
201 var From:tSockAddrL; {use larger struct so everything fits}
202 var FromLen:LongWord;
203 var FromG:tNetAddr;
204 var curhnd:tMessageHandler;
205 var curhndo:tObjMessageHandler;
206 var Msg:tSMsg;
207 var tp:tPollTop;
209 function DoSock(var p:tPollFD):boolean;
210 var ptidx:word;
211 begin
212 curhnd:=nil;
213 curhndo:=nil;
214 result:=false;
215 ptidx:=$FFFF;
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);
220 p.revents:=0;
221 FromG.FromSocket(from);
222 Msg.Source:=@FromG; {!thread}
223 Msg.Length:=pkLen;
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;
231 end;
232 end;
234 procedure ShedRun;
235 var cur:^tSheduled;
236 var pcur:^pointer;
237 var now:UnixType.timeval{ absolute iNow};
238 var delta:LongWord;
239 var delta_us:LongInt;
240 var tasks:word;
241 begin
242 {Sheduling}
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;
250 LastShed:=Now;
251 mNow:=mNow+Delta;
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}
256 tasks:=0;
257 cur:=ShedTop;
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;
263 end;
264 {count tasks here}
265 inc(tasks);
266 cur:=cur^.next;
267 end;
268 {correct floating-point glitch}
269 if pollTimeout=0 then pollTimeOut:=1;
270 {run first runnable task}
271 pcur:=@ShedTop;
272 cur:=pcur^;
273 while assigned(cur) do begin
274 if cur^.left=0 then begin
275 {unlink}
276 pcur^:=cur^.next;
277 {link to unused}
278 cur^.next:=ShedUU;
279 ShedUU:=cur;
280 {call}
281 cur^.cb;
282 {do rest later}
283 pollTimeout:=0;
284 break;
285 end;
286 pcur:=@cur^.next;
287 cur:=cur^.next;
288 end;
289 end;
291 procedure Main;
292 begin
293 s_setupInet;
294 while not terminated do begin
295 PollTimeout:=5000;
296 ShedRun;
297 EventsCount:=fpPoll(@PollArr[0],PollTop,PollTimeout);
298 ShedRun;
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
302 {INET socket}
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]));
307 {INET6...}
308 {Generic}
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;
312 end;
313 end;
314 end;
315 write('Loop broken [');
316 CloseSocket(s_inet);
317 writeln(']');
318 end;
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);
326 var opt: tPollTop;
327 begin
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));
335 Inc(PollTop);
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];
340 end;
341 dec(pollTop);
342 PollArr[pollTop].fd:=-1;
343 PollArr[pollTop].events:=0;
344 PollArr[pollTop].revents:=0;
345 break;
346 end;
347 end;
349 procedure Shedule(timeout{ms}: LongWord; h:tOnTimer);
350 var old:^tSheduled;
351 begin
352 old:=ShedTop;
353 if Assigned(ShedUU) then begin
354 ShedTop:=ShedUU;
355 ShedUU:=ShedUU^.next;
356 end else New(ShedTop);
357 ShedTop^.Left:=timeout;
358 ShedTop^.CB:=h;
359 ShedTop^.Next:=old;
360 end;
362 procedure UnShedule(h:tOnTimer);
363 var cur:^tSheduled;
364 var pcur:^pointer;
365 begin
366 //if ShedTop=nil then AbstractError;
367 pcur:=@ShedTop;
368 cur:=pcur^;
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}
373 cur:=pcur^;
374 end else begin
375 pcur:=@cur^.next;
376 cur:=pcur^;
377 end;
378 end;
379 end;
381 function OptIndex(o:string):word;
382 begin
383 result:=paramcount;
384 while result>0 do begin
385 if o=system.paramstr(result) then break;
386 dec(result);
387 end;
388 end;
390 function OptParamCount(o:word):word;
391 var i:word;
392 begin
393 result:=0;
394 if o>0 then for i:=o+1 to paramcount do begin
395 if paramstr(i)[1]<>'-' then inc(result)
396 else break;
397 end;
398 end;
400 var i:byte;
401 BEGIN
402 mNow:=0;
403 umNow:=0;
404 Randomize;
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;
409 PT_opcodes:=[];
410 pollTop:=1; {1 for basic listen}
411 ShedTop:=nil;
412 ShedUU:=nil; {todo: allocate a few to improve paging}
413 fpgettimeofday(@LastShed,nil);
414 END.