-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsrvfns.c
More file actions
1997 lines (1870 loc) · 72.8 KB
/
srvfns.c
File metadata and controls
1997 lines (1870 loc) · 72.8 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
/* -*- Mode: C; Character-encoding: utf-8; -*- */
/* Copyright (C) 2004-2019 beingmeta, inc.
Copyright (C) 2020-2022 Kenneth Haase (ken.haase@alum.mit.edu)
This file is part of the libu8 UTF-8 unicode library.
This program comes with absolutely NO WARRANTY, including implied
warranties of merchantability or fitness for any particular
purpose.
Use, modification, and redistribution of this program is permitted
under any of the licenses found in the the 'licenses' directory
accompanying this distribution, including the GNU General Public License
(GPL) Version 2 or the GNU Lesser General Public License.
*/
#define U8_LOGLEVEL (u8_merge_loglevels(local_loglevel,u8_server_loglevel))
#include "libu8/u8source.h"
#include "libu8/libu8.h"
/* #define _GNU_SOURCE */
#ifndef _FILEINFO
#define _FILEINFO __FILE__
#endif
/* Use the default loglevel */
int u8_server_loglevel = -1;
static int local_loglevel = -1;
#include "libu8/libu8io.h"
#include "libu8/u8filefns.h"
#include "libu8/u8netfns.h"
#include "libu8/u8srvfns.h"
#include "libu8/u8timefns.h"
#include "libu8/u8logging.h"
#include <unistd.h>
#include <limits.h>
#if HAVE_POLL_H
#include <poll.h>
#elif HAVE_SYS_POLL_H
#include <sys/poll.h>
#endif
#ifdef POLLRDHUP
#define HUPFLAGS POLLHUP|POLLRDHUP
#else
#define HUPFLAGS POLLHUP
#endif
#define POLLIN_EVENTS (POLLIN|POLLPRI|HUPFLAGS)
#define POLLOUT_EVENTS (POLLOUT|POLLPRI|HUPFLAGS)
static u8_condition ClosedClient=_("ClientClosed");
static u8_condition ServerShutdown=_("ServerShutdown");
static u8_condition NewServer=_("NewListenerPort");
static u8_condition NewClient=_("NewConnection");
static u8_condition RejectedConnection=_("RejectedConnection");
static u8_condition ClientRequest=_("ClientRequest");
static u8_condition Inconsistency=_("InternalInconsistency");
/* Prototypes for some static definitions */
static int close_client_core(u8_client cl,int server_locked,u8_context caller);
static int finish_closing_client(u8_client cl);
static void update_client_stats(u8_client cl,long long cur,int done);
static void update_server_stats(u8_client cl);
static int push_task(struct U8_SERVER *server,u8_client cl,u8_context cxt);
static int add_client(struct U8_SERVER *server,u8_client client);
static int free_client(struct U8_SERVER *server,u8_client cl,u8_context caller);
/* Helpful functions */
static char *get_client_state(u8_client cl,char *buf)
{
char *write=buf;
*write++='t';
if (cl->started>0) *write++='s';
if (cl->active>0) *write++='a';
if (cl->queued>0) *write++='q';
if (cl->reading>0) *write++='r';
if (cl->writing>0) *write++='w';
if (cl->running>0) *write++='x';
*write++='\0';
return buf;
}
/* Sockaddr functions */
static struct sockaddr *get_sockaddr_in
(int family,int port,char *addr,int addr_len)
{
if (family==AF_INET) {
struct sockaddr_in *sockaddr=u8_alloc(struct sockaddr_in);
memset(sockaddr,0,sizeof(struct sockaddr_in));
sockaddr->sin_port=htons((short)port);
sockaddr->sin_family=family;
memcpy((char *)&(sockaddr->sin_addr),addr,addr_len);
return (struct sockaddr *)sockaddr;}
#ifdef AF_INET6
else if (family==AF_INET6) {
struct sockaddr_in6 *sockaddr=u8_alloc(struct sockaddr_in6);
memset(sockaddr,0,sizeof(struct sockaddr_in6));
sockaddr->sin6_port=htons((short)port);
sockaddr->sin6_family=family;
memcpy((char *)&(sockaddr->sin6_addr),addr,addr_len);
return (struct sockaddr *)sockaddr;}
#endif
else return NULL;
}
static struct sockaddr *get_sockaddr_file(u8_string string)
{
#if HAVE_SYS_UN_H
struct sockaddr_un *sockaddr=u8_alloc(struct sockaddr_un);
sockaddr->sun_family=AF_LOCAL;
strcpy(sockaddr->sun_path,string);
return (struct sockaddr *)sockaddr;
#else
return NULL;
#endif
}
static int sockaddr_samep(struct sockaddr *s1,struct sockaddr *s2)
{
if (s1->sa_family != s2->sa_family) return 0;
else if (s1->sa_family==AF_INET) {
struct sockaddr_in *a1=(struct sockaddr_in *)s1;
struct sockaddr_in *a2=(struct sockaddr_in *)s2;
if (a1->sin_port!=a2->sin_port) return 0;
else return ((memcmp(&(a1->sin_addr),&(a2->sin_addr),4))==0);}
#if HAVE_SYS_UN_H
else if (s1->sa_family==AF_UNIX)
return ((strcmp(((struct sockaddr_un *)s1)->sun_path,
((struct sockaddr_un *)s2)->sun_path))==0);
#endif
#ifdef AF_INET6
else if (s1->sa_family==AF_INET6) {
struct sockaddr_in6 *a1=(struct sockaddr_in6 *)s1;
struct sockaddr_in6 *a2=(struct sockaddr_in6 *)s2;
if (a1->sin6_port!=a2->sin6_port) return 0;
else return ((memcmp(&(a1->sin6_addr),&(a2->sin6_addr),8))==0);}
#endif
else return 0;
}
/* Servers */
/* This provides a generic server loop which is customized by
functions for accepting, servicing, and closing remote clients.
The application conses client objects whose first few fields are
reserved for used by the server. */
static void init_server_socket(u8_socket socket_id);
U8_EXPORT
/* u8_init_client:
Arguments: a pointer to a client
Returns: void
Initializes the client structure.
@arg client a pointer to a client stucture, or NULL if one is to be consed
@arg len the length of the structure, as allocated or to be consed
@arg sock a socket (or -1) for the client
@arg server the server of which the client will be a part
Returns: a pointer to a client structure, consed if not provided.
*/
u8_client u8_init_client(u8_client client,size_t len,
struct sockaddr *addrbuf,size_t addrlen,
u8_socket sock,u8_server srv)
{
if (!(client)) client=u8_malloc(len);
memset(client,0,len);
client->socket=sock;
client->server=srv;
client->started=client->queued=client->active=0;
client->reading=client->writing=-1;
client->off=client->len=client->buflen=client->delta=0;
if ((srv->flags)&U8_SERVER_ASYNC)
client->flags=client->flags|U8_CLIENT_ASYNC;
client->client_loglevel = -1;
return client;
}
/* Reading and writing from clients */
U8_EXPORT int u8_client_finished(u8_client cl)
{
if ((cl->reading>0)||(cl->writing>0))
if (cl->off<cl->len) return 0;
else if (cl->reading>0) {
long long rtime=u8_microtime()-cl->reading;
cl->stats.rsum+=rtime; cl->stats.rsum2+=(rtime*rtime);
if (rtime>cl->stats.rmax) cl->stats.rmax=rtime;
cl->stats.rcount++;
cl->reading=0;
return 1;}
else if (cl->writing>0) {
long long wtime=u8_microtime()-cl->writing;
cl->stats.wsum+=wtime; cl->stats.wsum2+=(wtime*wtime);
if (wtime>cl->stats.wmax) cl->stats.wmax=wtime;
cl->stats.wcount++;
cl->writing=0;
return 1;}
else return 1;
else return 1;
}
U8_EXPORT unsigned char *u8_client_read
(u8_client cl,unsigned char *buf,size_t n,size_t off)
{
char statebuf[16];
u8_server server=cl->server;
int local_loglevel = (cl->client_loglevel>=0) ? (cl->client_loglevel) :
(server->server_loglevel);
if (((server->flags)&(U8_SERVER_LOG_TRANSACT))||
((cl->flags)&(U8_CLIENT_LOG_TRANSACT)))
u8_logf(LOG_INFO,"Reading/request",
"%d bytes for @x%lx#%d.%d[%s/%d](%s%:hs) 0x%lx+%d<%d",
n,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
(unsigned long)cl->buf,cl->off,cl->len);
if ((cl->reading>0)&&
(cl->buf==buf)&&(cl->len==n)&&(cl->off>=cl->len)) {
cl->reading=0; return cl->buf;}
else if (cl->reading>0) {
u8_logf(LOG_WARNING,"u8_client_read",
"Client @x%lx#%d.%d[%s/%d](%s%:hs) is already reading %ld bytes",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
((long)cl->len));
return NULL;}
else if (cl->writing>0) {
u8_logf(LOG_WARNING,"u8_client_read",
"Client @x%lx#%d.%d[%s/%d](%s%:hs) is still writing %ld bytes",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
((long)cl->len));
return NULL;}
else if (off<n) {
cl->reading=u8_microtime();
cl->buflen=cl->len=n; cl->buf=buf; cl->off=off;
return NULL;}
else return buf;
}
U8_EXPORT unsigned char *u8_client_write_x
(u8_client cl,unsigned char *buf,size_t n,size_t off,int flags)
{
char statebuf[16];
u8_server server=cl->server;
int local_loglevel = (cl->client_loglevel>=0) ? (cl->client_loglevel) :
(server->server_loglevel);
if (((server->flags)&(U8_SERVER_LOG_TRANSACT))||
((cl->flags)&(U8_CLIENT_LOG_TRANSACT)))
u8_logf(LOG_INFO,"Writing/request",
"%d bytes for @x%lx#%d.%d[%s/%d](%s%:hs) 0x%lx+%d<%d",
n,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
(unsigned long)cl->buf,cl->off,cl->len);
if ((cl->writing>0)&&(cl->buf==buf)&&(cl->len==n)) {
/* We're already writing this */
if (cl->off<cl->len) return NULL;
else {
/* And we're done */
cl->writing=0; return cl->buf;}}
else if (cl->writing>0) {
u8_logf(LOG_WARNING,"u8_client_write",
"Client @x%lx#%d.%d[%s/%d](%s%:hs) is already writing %ld bytes",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
((long)cl->len));
return NULL;}
else if (cl->reading>0) {
u8_logf(LOG_WARNING,"u8_client_write",
"Write to @x%lx#%d.%d[%s/%d](%s%:hs) with %d unread bytes",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
((long)cl->len));
cl->reading=0;
return NULL;}
else if (off<n) {
if ((cl->buf)&&(cl->ownsbuf)&&(buf!=cl->buf)) {
u8_free(cl->buf); cl->buf=NULL; cl->ownsbuf=0;}
cl->writing=u8_microtime(); cl->reading=-1;
cl->buflen=cl->len=n; cl->buf=buf; cl->off=off;
cl->ownsbuf=((flags&U8_CLIENT_WRITE_OWNBUF)!=0);
return NULL;}
else return buf;
}
U8_EXPORT unsigned char *u8_client_write
(u8_client cl,unsigned char *buf,size_t n,size_t off)
{
return u8_client_write_x(cl,buf,n,off,0);
}
/* Declaring a client done with a transaction (and available for another) */
U8_EXPORT
/* u8_client_done:
Arguments: a pointer to a client
Returns: void
Marks the client's current task as done, updating server data structures
appropriately. */
int u8_client_done(u8_client cl)
{
U8_SERVER *server=cl->server; char statebuf[16];
int local_loglevel = (cl->client_loglevel>=0) ? (cl->client_loglevel) :
(server->server_loglevel);
int clientid=cl->clientid;
if (cl->started>0) {
if (server->donefn) {
int retval=server->donefn(cl);
if (retval<0) {
u8_logf(LOG_ERR,"u8_client_done",
"Error finishing transaction on @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,cl->n_trans,
cl->idstring,cl->status);
u8_clear_errors(1);}}
update_client_stats(cl,u8_microtime(),1);
cl->writing=cl->reading=0;
if (cl->queued>0) {
u8_logf(LOG_WARNING,"u8_client_done",
"Finishing transaction on queued client @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,cl->n_trans,
cl->idstring,cl->status);
cl->queued=0;}
if (cl->socket>0) {
struct pollfd *pfd=&(server->sockets[clientid]);
cl->reading=u8_microtime();
pfd->events=((short)(POLLIN_EVENTS));}
u8_lock_mutex(&(server->lock));
if (cl->started>0) {
server->n_busy--;
cl->started=0;}
server->n_trans++;
u8_unlock_mutex(&(server->lock));
return 1;}
else {
u8_logf(LOG_WARNING,"u8_client_done",
"Declaring done on idle client @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
return 0;}
}
/* Closing clients */
U8_EXPORT
/* u8_close_client:
Arguments: a pointer to a client
Returns: int
Marks the client's current task as done, updating server data structures
appropriately, and ending by closing the client close function.
If a busy client is closed, it has its U8_CLIENT_CLOSING flag set.
This tells the event loop to finish closing the client when it actually
completes the current transaction.
*/
int u8_close_client(u8_client cl)
{
U8_SERVER *server=cl->server; char statebuf[16];
int local_loglevel = (cl->client_loglevel>=0) ? (cl->client_loglevel) :
(server->server_loglevel);
if ((cl->flags&U8_CLIENT_CLOSED)==0) {
int retval;
u8_lock_mutex(&(server->lock));
/* Catch race conditions */
if (cl->flags&U8_CLIENT_CLOSED) {
u8_unlock_mutex(&(server->lock));
return 0;}
cl->flags|=U8_CLIENT_CLOSING;
u8_unlock_mutex(&(server->lock));
/* If the task is in the middle of a transaction,
don't close it right away. */
if (cl->started>0) {
if (server->flags&U8_SERVER_LOG_CONNECT)
u8_logf(LOG_INFO,"u8_close_client",
"Deferring closing of @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
return 0;}
retval=close_client_core(cl,0,"u8_close_client");
return retval;}
else {
u8_logf(LOG_WARNING,"u8_close_client",
"Closing already closed socket @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
u8_unlock_mutex(&(server->lock));
return 0;}
}
U8_EXPORT
/* u8_client_closed:
Arguments: a pointer to a client
Returns: int
Indicates that the other end has closed the connection. This can generate
an indication of its own and then closes the client on this end
*/
int u8_client_closed(u8_client cl)
{
char statebuf[16];
U8_SERVER *server=cl->server;
int local_loglevel = (cl->client_loglevel>=0) ? (cl->client_loglevel) :
(server->server_loglevel);
if ((cl->server->flags)&(U8_SERVER_LOG_CONNECT))
u8_logf(LOG_INFO,"u8_client_closed",
"Other end closed @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
return u8_client_close(cl);
}
U8_EXPORT
/* u8_shutdown_client:
Arguments: a pointer to a client
Returns: int
Marks the client's current task as done, updating server data structures
appropriately, and ending by closing the client close function.
This will shutdown an active client.
*/
int u8_shutdown_client(u8_client cl)
{
U8_SERVER *server=cl->server; char statebuf[16];
int local_loglevel = (cl->client_loglevel>=0) ? (cl->client_loglevel) :
(server->server_loglevel);
if ((cl->flags&U8_CLIENT_CLOSED)==0) {
int retval;
u8_lock_mutex(&(server->lock));
/* Catch race conditions */
if (cl->flags&U8_CLIENT_CLOSED) {
u8_unlock_mutex(&(server->lock));
return 0;}
cl->flags|=U8_CLIENT_CLOSING;
u8_unlock_mutex(&(server->lock));
retval=close_client_core(cl,0,"u8_shutdown_client");
return retval;}
else {
u8_logf(LOG_WARNING,"u8_shutdown_client",
"Closing already closed socket @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
u8_unlock_mutex(&(server->lock));
return 0;}
}
/* This is the internal version used when shutting down a server.
We dont wait for anything. */
static int client_close_for_shutdown(u8_client cl)
{
if ((cl->flags&U8_CLIENT_CLOSED)==0) {
if (cl->started>0) {
/* It's in the middle of something, so we just flag it as closing. */
cl->flags|=U8_CLIENT_CLOSING;
return 0;}
else return close_client_core(cl,1,"client_close_for_shutdown");}
else return 0;
}
/* This is used when a transaction finishes and the socket has been
closed during shutdown. */
static int close_client_core(u8_client cl,int server_locked,u8_context caller)
{
if (!(caller)) caller="close_client_core";
if (cl->flags&U8_CLIENT_CLOSED) return 0;
else {
U8_SERVER *server=cl->server; int retval=0;
int local_loglevel = (cl->client_loglevel>=0) ? (cl->client_loglevel) :
(server->server_loglevel);
/* We grab idstring, because our code allocated it but we will use it
only after the closefn has freed the client object. */
long long cur=u8_microtime();
char statebuf[16];
if (!(server_locked)) u8_lock_mutex(&(server->lock));
if (server->flags&U8_SERVER_LOG_CONNECT)
u8_logf(LOG_INFO,"u8_close_client",
"Closing (%s) @x%lx#%d.%d[%s/%d](%s%:hs)",
caller,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
/* Update run stats for one last time */
if (cl->started>0) {
u8_logf(LOG_WARNING,"close_client_core",
"Closing (%s) running client @x%lx#%d.%d[%s/%d](%s%:hs)",
caller,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
server->n_busy--;}
update_client_stats(cl,cur,1);
cl->running=cl->reading=cl->writing=cl->started=0;
if (server->closefn)
retval=server->closefn(cl);
else if (cl->socket>0)
retval=close(cl->socket);
else retval=0;
cl->flags|=U8_CLIENT_CLOSED;
cl->socket=-1;
if (cl->server->flags&U8_SERVER_LOG_CONNECT)
u8_logf(LOG_INFO,ClosedClient,"Closed (%s) @x%lx#%d.%d[%s/%d](%s%:hs)",
caller,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
if (cl->queued>0) {
long long interval=cur-cl->queued;
if ((cl->reading>0)||(cl->writing>0))
u8_logf(LOG_WARNING,"close_client_core",
"Closing (%s) a queued client @x%lx#%d.%d[%s/%d](%s%:hs)",
caller,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
cl->stats.qsum+=interval;
cl->stats.qsum2+=(interval*interval);
if (interval>cl->stats.qmax) cl->stats.qmax=interval;
cl->stats.qcount++;}
free_client(server,cl,"close_client_core");
if (!(server_locked)) u8_unlock_mutex(&(server->lock));
return retval;}
}
static int finish_closing_client(u8_client cl)
{
U8_SERVER *server=cl->server;
if ((cl->flags&U8_CLIENT_CLOSED)==0) {
int retval;
u8_lock_mutex(&(server->lock));
/* Catch race conditions */
if (cl->flags&U8_CLIENT_CLOSED) {
u8_unlock_mutex(&(server->lock));
return 0;}
u8_unlock_mutex(&(server->lock));
retval=close_client_core(cl,0,"finish_closing_client");
return retval;}
else return 0;
}
static void update_client_stats(u8_client cl,long long cur,int done)
{
long long interval=cur-cl->active;
/* read/write/execute */
if (cl->running) {
interval=cur-cl->running;
cl->stats.xsum+=interval;
cl->stats.xsum2+=(interval*interval);
if (interval>cl->stats.xmax) cl->stats.xmax=interval;
cl->stats.xcount++;}
if (done) {
if (cl->started>0){
interval=cur-cl->started;
cl->stats.tsum+=interval;
cl->stats.tsum2+=(interval*interval);
if (interval>cl->stats.tmax) cl->stats.tmax=interval;
cl->stats.tcount++;}}
}
static void update_server_stats(u8_client cl)
{
u8_server server=cl->server;
/* Transfer all the client statistics to the server */
server->aggrestats.tsum+=cl->stats.tsum;
server->aggrestats.tsum2+=cl->stats.tsum2;
server->aggrestats.tcount+=cl->stats.tcount;
if (cl->stats.tmax>server->aggrestats.tmax)
server->aggrestats.tmax=cl->stats.tmax;
server->aggrestats.qsum+=cl->stats.qsum;
server->aggrestats.qsum2+=cl->stats.qsum2;
server->aggrestats.qcount+=cl->stats.qcount;
if (cl->stats.qmax>server->aggrestats.qmax)
server->aggrestats.qmax=cl->stats.qmax;
server->aggrestats.rsum+=cl->stats.rsum;
server->aggrestats.rsum2+=cl->stats.rsum2;
server->aggrestats.rcount+=cl->stats.rcount;
if (cl->stats.rmax>server->aggrestats.rmax)
server->aggrestats.rmax=cl->stats.rmax;
server->aggrestats.wsum+=cl->stats.wsum;
server->aggrestats.wsum2+=cl->stats.wsum2;
server->aggrestats.wcount+=cl->stats.wcount;
if (cl->stats.wmax>server->aggrestats.wmax)
server->aggrestats.wmax=cl->stats.wmax;
server->aggrestats.xsum+=cl->stats.xsum;
server->aggrestats.xsum2+=cl->stats.xsum2;
server->aggrestats.xcount+=cl->stats.xcount;
if (cl->stats.xmax>server->aggrestats.xmax)
server->aggrestats.xmax=cl->stats.xmax;
server->n_errs+=cl->n_errs;
}
/* Maintaining the task/event/client queue */
#if U8_THREADS_ENABLED
static u8_client pop_task(struct U8_SERVER *server)
{
u8_client task=NULL; char statebuf[16]; int slot;
int local_loglevel = server->server_loglevel;
if ( (server->flags) & (U8_SERVER_CLOSED|U8_SERVER_CLOSING) )
return NULL;
u8_lock_mutex(&(server->lock));
while ((server->n_queued == 0) &&
(((server->flags)&(U8_SERVER_CLOSED|U8_SERVER_CLOSING))==0))
u8_condvar_wait(&(server->empty),&(server->lock));
if ((server->flags)&(U8_SERVER_CLOSED|U8_SERVER_CLOSING)) {}
else if (server->n_queued) {
slot=server->queue_head;
task=server->queue[server->queue_head];
server->queue[server->queue_head]=NULL;
server->queue_head++;
if (server->queue_head>=server->queue_len) server->queue_head=0;
server->n_queued--;}
else NO_ELSE;
if (!(task)) {}
else if (task->active>0) {
/* This should probably never happen */
u8_logf(LOG_CRIT,"pop_task(u8)",
"popping (%d) active task @x%lx#%d.%d[%s/%d](%s%:hs)",
slot,((unsigned long)task),task->clientid,task->socket,
get_client_state(task,statebuf),
task->n_trans,task->idstring,task->status);
/* If this ever happened, not freeing the client would be a leak. However,
if it did happen, we'd screw up other logic, so we risk the leak. */
task->queued=-1; task=NULL;}
else if ((task->flags&U8_CLIENT_CLOSED)||(task->socket<0)) {
if (((server->flags)&(U8_SERVER_LOG_QUEUE))||
((task->flags)&(U8_CLIENT_LOG_QUEUE)))
u8_logf(LOG_DEBUG,"pop_task(u8)",
"Final pop (%d) of closed task @x%lx#%d.%d[%s/%d](%s%:hs)",
slot,((unsigned long)task),task->clientid,task->socket,
get_client_state(task,statebuf),
task->n_trans,task->idstring,task->status);
free_client(task->server,task,"pop_task/closed");
task=NULL;}
else {
u8_utime curtime=u8_microtime();
long long qtime=curtime-task->queued;
task->stats.qsum+=qtime; task->stats.qsum2+=(qtime*qtime);
task->stats.qcount++;
if (qtime>task->stats.qmax) task->stats.qmax=qtime;
task->queued=0; task->active=curtime;
if (((server->flags)&(U8_SERVER_LOG_QUEUE))||
((task->flags)&(U8_CLIENT_LOG_QUEUE)))
u8_logf(LOG_DEBUG,"pop_task(u8)",
"Popped (%d) task @x%lx#%d.%d[%s/%d](%s%:hs)",
slot,((unsigned long)task),task->clientid,task->socket,
get_client_state(task,statebuf),
task->n_trans,task->idstring,task->status);
if (task->started<=0) {
task->started=curtime;
server->n_busy++;}}
u8_unlock_mutex(&(server->lock));
return task;
}
static int push_task(struct U8_SERVER *server,u8_client cl,u8_context cxt)
{
u8_utime cur=u8_microtime(); char statebuf[16];
int local_loglevel = server->server_loglevel;
if (server->n_queued >= server->max_queued) return 0;
if (cl->queued>0) return 0;
if (cl->clientid<0) return 0;
if (((server->flags)&(U8_SERVER_LOG_QUEUE))||
((cl->flags)&(U8_CLIENT_LOG_QUEUE)))
u8_logf(LOG_DEBUG,cxt,"Queueing (%d) client @x%lx#%d.%d[%s/%d](%s%:hs)",
server->queue_tail,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
cl->queued=cur;
server->queue[server->queue_tail++]=cl;
if (server->queue_tail>=server->queue_len) server->queue_tail=0;
server->n_queued++;
server->sockets[cl->clientid].events=((short)0);
u8_condvar_signal(&(server->empty));
return 1;
}
/* The main event loop */
static void *event_loop(void *thread_arg)
{
char statebuf[16];
struct U8_SERVER_THREAD *sthread=(struct U8_SERVER_THREAD *)thread_arg;
struct U8_SERVER *server=sthread->u8st_server;
U8_SET_STACK_BASE();
if (sthread->u8st_threadid<0)
sthread->u8st_threadid=u8_threadid();
/* Check for additional thread init functions */
while ((server->flags&U8_SERVER_CLOSED) == 0) {
u8_client cl; int dobreak=0; int result=0, closed=0;
u8_utime cur;
/* Check that this thread's init functions are up to date */
u8_threadcheck();
cl=pop_task(server);
if (!(cl)) continue;
else if ((cl->socket<=0)||((cl->flags)&U8_CLIENT_CLOSED)) {
cl->active=0; cl->threadnum=-1; sthread->u8st_client=-1;
if (server->xclientfn) server->xclientfn(cl);
continue;}
else cur=u8_microtime();
int local_loglevel = (cl->client_loglevel>=0) ? (cl->client_loglevel) :
(server->server_loglevel);
if (((server->flags)&(U8_SERVER_LOG_TRANSACT))||
((cl->flags)&(U8_CLIENT_LOG_TRANSACT)))
u8_logf(LOG_DEBUG,ClientRequest,
"Handling activity on @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
cl->threadnum=sthread->u8st_slotno;
sthread->u8st_client=cl->clientid;
if ((cl->reading>0)||(cl->writing>0)) {
/* We're in the middle of reading or writing a chunk of data,
so we try to read/write another chunk. */
ssize_t delta;
if (cl->off<cl->len) { /* We're not done */
if (cl->writing>0)
delta=write(cl->socket,cl->buf+cl->off,cl->len-cl->off);
else delta=read(cl->socket,cl->buf+cl->off,cl->len-cl->off);
if (((server->flags)&(U8_SERVER_LOG_TRANSFER))||
((cl->flags)&(U8_CLIENT_LOG_TRANSFER)))
u8_logf(LOG_DEBUG,((cl->writing>0)?("Writing"):("Reading")),
"%d bytes for @x%lx#%d.%d[%s/%d](%s%:hs) 0x%lx+%d<%d",
delta,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
(unsigned long)cl->buf,cl->off,cl->len);
if (delta>0) cl->off=cl->off+delta;}
/* If we've still got data to read/write, we update the poll
structure to keep listening and continue in the event loop. */
if (cl->off<cl->len) {
/* u8_lock_mutex(&server->lock); */
if (cl->writing>0)
server->sockets[cl->clientid].events=((short)(POLLOUT_EVENTS));
else server->sockets[cl->clientid].events=((short)(POLLIN_EVENTS));
cl->active=0; sthread->u8st_client=-1; cl->threadnum=-1;
if (server->xclientfn) server->xclientfn(cl);
continue;}
else {
/* Otherwise, we're done with whatever reading or writing we
were doing, so we record stats. */
u8_utime now=u8_microtime();
if (cl->writing>0) {
long long wtime=now-cl->writing;
cl->stats.wsum+=wtime;
cl->stats.wsum2+=(wtime*wtime);
if (wtime>cl->stats.wmax) cl->stats.wmax=wtime;
cl->stats.wcount++;}
else {
long long rtime=now-cl->reading;
cl->stats.rsum+=rtime;
cl->stats.rsum2+=(rtime*rtime);
if (rtime>cl->stats.rmax) cl->stats.rmax=rtime;
cl->stats.rcount++;}
if ((((server->flags)&(U8_SERVER_LOG_TRANSACT))||
((cl->flags)&(U8_CLIENT_LOG_TRANSACT)))&&
(cl->len>0))
u8_logf(LOG_DEBUG,
((cl->writing>0)?
("event_loop/write"):
(cl->reading>0)?
("event_loop/read"):
("event_loop/weird")),
"All %d bytes for @x%lx#%d.%d[%s/%d](%s%:hs) 0x%lx+%d<%d",
cl->len,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
(unsigned long)cl->buf,cl->off,cl->len);
cl->off=cl->len=0;}
}
/* Unless there's an I/O error, call the handler */
if ((cl->flags)&(U8_CLIENT_CLOSED|U8_CLIENT_CLOSING)) {
u8_logf(LOG_WARN,"event_loop/closed",
"Client @x%lx#%d.%d[%s/%d] (%s%:hs) asynchronously closed",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);}
else if (result>=0) {
long long xtime;
cl->running=cur=u8_microtime();
if (cl->callback) {
void *state=cl->cbstate;
u8_client_callback callback=cl->callback;
cl->callback=NULL; cl->cbstate=NULL;
if (((server->flags)&(U8_SERVER_LOG_TRANSACT))||
((cl->flags)&(U8_CLIENT_LOG_TRANSACT))) {
u8_logf(LOG_WARN,"event_loop/callback",
"Client @x%lx#%d.%d[%s/%d] (%s%:hs) callback",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);}
result=callback(cl,state);}
else {
if (((server->flags)&(U8_SERVER_LOG_TRANSACT))||
((cl->flags)&(U8_CLIENT_LOG_TRANSACT))) {
u8_logf(LOG_WARN,"event_loop/servefn",
"Client @x%lx#%d.%d[%s/%d] (%s%:hs) servefn",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);}
result=server->servefn(cl);}
cl->running=0;
/* Record execution stats */
xtime=u8_microtime()-cur;
cl->stats.xsum+=xtime;
cl->stats.xsum2+=(xtime*xtime);
if (xtime>cl->stats.xmax) cl->stats.xmax=xtime;
cl->stats.xcount++;}
if (result<0) {
u8_exception ex=u8_current_exception;
u8_logf(LOG_ERR,"event_loop",
"Error result from client @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
if (cl->flags&U8_CLIENT_CLOSED) closed=1;
else if (cl->flags&U8_CLIENT_CLOSING) {
update_client_stats(cl,u8_microtime(),1);
cl->active=0; finish_closing_client(cl); closed=1;
if ((cl->buf)&&(cl->ownsbuf)) u8_free(cl->buf);
cl->buf=NULL; cl->off=cl->len=cl->buflen=0; cl->ownsbuf=0;}
else if (cl->active>0) u8_client_done(cl);
else NO_ELSE;
if (ex) {
u8_logf(LOG_WARN,ClientRequest,
"Error during activity on @x%lx#%d.%d[%s/%d](%s%:hs) %s",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
u8_errstring(ex));
u8_clear_errors(1);
close_client_core(cl,1,"event_loop/error");
closed=1;}
cl->n_errs++;}
else if (result==0) {
u8_utime cur=u8_microtime();
/* Request is completed */
if (((server->flags)&U8_SERVER_LOG_TRANSACT)||
((cl->flags)&U8_CLIENT_LOG_TRANSACT))
u8_logf(LOG_DEBUG,ClientRequest,
"Completed transaction with @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
cl->n_trans++;
if (server->flags&U8_SERVER_CLOSED) dobreak=1;
if (cl->flags&U8_CLIENT_CLOSED) {
u8_logf(LOG_CRIT,Inconsistency,
"Result returned from closed client @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);
if (cl->started>0) {
update_client_stats(cl,cur,1);
server->n_busy--; cl->started=0;}
closed=1; if ((cl->buf)&&(cl->ownsbuf)) u8_free(cl->buf);
cl->buf=NULL; cl->off=cl->len=cl->buflen=0; cl->ownsbuf=0;}
else if (cl->flags&U8_CLIENT_CLOSING) {
if (cl->started>0) {
update_client_stats(cl,cur,1);
server->n_busy--; cl->started=0;}
cl->active=0; finish_closing_client(cl); closed=1;
if ((cl->buf)&&(cl->ownsbuf)) u8_free(cl->buf);
cl->buf=NULL; cl->off=cl->len=cl->buflen=0; cl->ownsbuf=0;}
else {
if (cl->active>0) u8_client_done(cl);
if ((cl->buf)&&(cl->ownsbuf)) u8_free(cl->buf);
cl->buf=NULL; cl->off=cl->len=cl->buflen=0; cl->ownsbuf=0;}}
else if (((cl->reading>0)||(cl->writing>0))&&(cl->buf!=NULL)) {
/* The execution function queued some data to read or write.
We give it an initial try and push the task (in some cases,
the operating system will just take it all and we can finish
up. */
ssize_t delta;
if (cl->writing>0)
delta=write(cl->socket,cl->buf+cl->off,((size_t)(cl->len-cl->off)));
else delta=read(cl->socket,cl->buf+cl->off,((size_t)(cl->len-cl->off)));
if (((server->flags)&(U8_SERVER_LOG_TRANSFER))||
((cl->flags)&(U8_CLIENT_LOG_TRANSFER)))
u8_logf(LOG_DEBUG,((cl->writing>0)?("Writing"):("Reading")),
"%d bytes for @x%lx#%d.%d[%s/%d](%s%:hs) 0x%lx+%d<%d",
delta,((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status,
(unsigned long)(cl->buf),cl->off,cl->len);
if (delta>0) cl->off=cl->off+delta;
/* If we've still got data to read/write, we continue,
otherwise, we fall through */
if (cl->off<cl->len) {
/* Keep listening */
if (cl->writing>0)
server->sockets[cl->clientid].events=((short)(POLLOUT|HUPFLAGS));
else server->sockets[cl->clientid].events=((short)(POLLIN|HUPFLAGS));}
else if ((cl->len>0)&&((cl->writing>0)||(cl->reading>0))) {
int cid=cl->clientid;
cl->active=0;
if (cl->writing>0)
server->sockets[cid].events=((short)(POLLOUT|HUPFLAGS));
else server->sockets[cid].events=((short)(POLLIN|HUPFLAGS));
sthread->u8st_client=-1; cl->threadnum=-1;
u8_push_task(server,cl,((cl->writing)?("event_loop/w"):("event_loop/r")));
if (server->xclientfn) server->xclientfn(cl);
continue;}
else NO_ELSE;}
else {
/* Request is not yet completed, but we're not waiting
on input or output. */
if (((server->flags)&U8_SERVER_LOG_TRANSACT)||
((cl->flags)&U8_CLIENT_LOG_TRANSACT))
u8_logf(LOG_INFO,ClientRequest,
"Yield during request for @x%lx#%d.%d[%s/%d](%s%:hs)",
((unsigned long)cl),cl->clientid,cl->socket,
get_client_state(cl,statebuf),
cl->n_trans,cl->idstring,cl->status);}
if (cl->active>0) {
cl->active=0;
if (dobreak) break;
if (!(closed)) {
/* Start listening again (it was stopped by pop_task() */
if (cl->writing>0)
server->sockets[cl->clientid].events=((short)(POLLOUT|HUPFLAGS));
else server->sockets[cl->clientid].events=((short)(POLLIN|HUPFLAGS));}}
sthread->u8st_client=-1; cl->threadnum=-1;
if (server->xclientfn) server->xclientfn(cl);}
u8_threadexit();
return NULL;
}
#endif
/* Creating/initializing servers */
U8_EXPORT
struct U8_SERVER *u8_init_server
(struct U8_SERVER *server,
u8_client (*acceptfn)(u8_server,u8_socket,struct sockaddr *,size_t),
int (*servefn)(u8_client),
int (*donefn)(u8_client),
int (*closefn)(u8_client),
...)
{
int i=0;
int flags=0, init_clients=DEFAULT_INIT_CLIENTS, n_threads=DEFAULT_NTHREADS;
int max_backlog=MAX_BACKLOG, max_queue=DEFAULT_MAX_QUEUE;
int max_clients=DEFAULT_MAX_CLIENTS, timeout=DEFAULT_TIMEOUT;
va_list args; int prop;
if (server==NULL) server=u8_alloc(struct U8_SERVER);
memset(server,0,sizeof(struct U8_SERVER));
va_start(args,closefn);
while ((prop=va_arg(args,int))>0) {
switch (prop) {
case U8_SERVER_FLAGS:
flags=flags|(va_arg(args,int)); continue;
case U8_SERVER_NTHREADS:
n_threads=(va_arg(args,int)); continue;
case U8_SERVER_INIT_CLIENTS:
init_clients=(va_arg(args,int)); continue;
case U8_SERVER_MAX_QUEUE:
max_queue=(va_arg(args,int)); continue;
case U8_SERVER_MAX_CLIENTS:
max_clients=(va_arg(args,int)); continue;
case U8_SERVER_BACKLOG:
max_backlog=(va_arg(args,int)); continue;
case U8_SERVER_TIMEOUT:
timeout=(va_arg(args,int)); continue;
case U8_SERVER_LOGLEVEL: {
int level=(va_arg(args,int));
if (level>3) flags|=U8_SERVER_LOG_TRANSFER;
if (level>2) flags|=U8_SERVER_LOG_TRANSACT;
if (level>1) flags|=U8_SERVER_LOG_CONNECT;
if (level>0) flags|=U8_SERVER_LOG_LISTEN;
server->server_loglevel = level;