summaryrefslogtreecommitdiffstats
path: root/src/libply/ply-event-loop.c
blob: 4c84f9d082f1fce9778b9dc442c130539f385a6b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
/* ply-event-loop.c - small epoll based event loop
 *
 * Copyright (C) 2007 Red Hat, Inc.
 *
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * Written by: Ray Strode <rstrode@redhat.com>
 */
#include "config.h"
#include "ply-event-loop.h"

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <signal.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/termios.h>
#include <unistd.h>

#include "ply-logger.h"
#include "ply-list.h"
#include "ply-utils.h"

#ifndef PLY_EVENT_LOOP_NUM_EVENT_HANDLERS
#define PLY_EVENT_LOOP_NUM_EVENT_HANDLERS 64
#endif

#ifndef PLY_EVENT_LOOP_NO_TIMED_WAKEUP
#define PLY_EVENT_LOOP_NO_TIMED_WAKEUP 0.0
#endif

typedef struct
{
  int fd;
  ply_list_t *destinations;
  ply_list_t *fd_watches;
  uint32_t is_getting_polled : 1;
  uint32_t is_disconnected : 1;
} ply_event_source_t;

typedef struct
{
  ply_event_source_t *source;

  ply_event_loop_fd_status_t status;
  ply_event_handler_t status_met_handler;
  ply_event_handler_t disconnected_handler;
  void *user_data;
} ply_event_destination_t;

struct _ply_fd_watch
{
  ply_event_destination_t *destination;
};

typedef struct
{
  int signal_number;
  ply_event_handler_t handler;
  void *user_data;

  sighandler_t old_posix_signal_handler;
} ply_signal_source_t;

static int ply_signal_dispatcher_sender_fd = -1,
           ply_signal_dispatcher_receiver_fd = -1;

typedef struct
{
  ply_list_t *sources;
} ply_signal_dispatcher_t;

typedef struct
{
  ply_event_loop_exit_handler_t  handler;
  void                          *user_data;
} ply_event_loop_exit_closure_t;

typedef struct
{
  double timeout;
  ply_event_loop_timeout_handler_t  handler;
  void                             *user_data;
} ply_event_loop_timeout_watch_t;

struct _ply_event_loop
{
  int epoll_fd;
  int exit_code;
  double wakeup_time;

  ply_list_t *sources;
  ply_list_t *exit_closures;
  ply_list_t *timeout_watches;

  ply_signal_dispatcher_t *signal_dispatcher;

  uint32_t should_exit : 1;
};

static void ply_event_loop_process_pending_events (ply_event_loop_t *loop);
static void ply_event_loop_remove_source (ply_event_loop_t    *loop,
                                          ply_event_source_t *source);
static ply_list_node_t *ply_event_loop_find_source_node (ply_event_loop_t *loop,
                                                         int               fd);

static ply_list_node_t *
ply_signal_dispatcher_find_source_node (ply_signal_dispatcher_t *dispatcher,
                                        int                      signal_number);


static ply_signal_source_t *
ply_signal_source_new (int                  signal_number,
                       ply_event_handler_t  signal_handler,
                       void                *user_data)
{
  ply_signal_source_t *source;

  source = calloc (1, sizeof (ply_signal_source_t));
  source->signal_number = signal_number;
  source->handler = signal_handler;
  source->user_data = user_data;
  source->old_posix_signal_handler = NULL;

  return source;
}

static void
ply_signal_source_free (ply_signal_source_t *handler)
{
  if (handler == NULL)
    return;

  free (handler);
}

static ply_signal_dispatcher_t *
ply_signal_dispatcher_new (void)
{
  ply_signal_dispatcher_t *dispatcher;

  if (!ply_open_unidirectional_pipe (&ply_signal_dispatcher_sender_fd,
                                     &ply_signal_dispatcher_receiver_fd))
    return NULL;

  dispatcher = calloc (1, sizeof (ply_signal_dispatcher_t));

  dispatcher->sources = ply_list_new ();

  return dispatcher;
}

static void
ply_signal_dispatcher_free (ply_signal_dispatcher_t *dispatcher)
{
  ply_list_node_t *node;

  if (dispatcher == NULL)
    return;

  close (ply_signal_dispatcher_receiver_fd);
  ply_signal_dispatcher_receiver_fd = -1;
  close (ply_signal_dispatcher_sender_fd);
  ply_signal_dispatcher_sender_fd = -1;

  node = ply_list_get_first_node (dispatcher->sources);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_signal_source_t *source;

      source = (ply_signal_source_t *) ply_list_node_get_data (node);

      next_node = ply_list_get_next_node (dispatcher->sources, node);

      ply_signal_source_free (source);

      node = next_node;
    }

  ply_list_free (dispatcher->sources);

  free (dispatcher);
}

static void
ply_signal_dispatcher_posix_signal_handler (int signal_number)
{
  if (ply_signal_dispatcher_sender_fd < 0)
    return;

  ply_write (ply_signal_dispatcher_sender_fd, &signal_number,
             sizeof (signal_number));
}

static int
ply_signal_dispatcher_get_next_signal_from_pipe (ply_signal_dispatcher_t *dispatcher)
{
  int signal_number;

  if (!ply_read (ply_signal_dispatcher_receiver_fd, &signal_number,
                 sizeof (signal_number)))
    signal_number = 0;

  return signal_number;
}

static void
ply_signal_dispatcher_dispatch_signal (ply_signal_dispatcher_t *dispatcher,
                                       int                      fd)
{
  ply_list_node_t *node;
  int signal_number;

  assert (fd == ply_signal_dispatcher_receiver_fd);

  signal_number = ply_signal_dispatcher_get_next_signal_from_pipe (dispatcher);

  node = ply_list_get_first_node (dispatcher->sources);
  while (node != NULL)
    {
      ply_signal_source_t *source;

      source = (ply_signal_source_t *) ply_list_node_get_data (node);

      if (source->signal_number == signal_number)
        {
          if (source->handler != NULL)
            source->handler (source->user_data, signal_number);
        }

      node = ply_list_get_next_node (dispatcher->sources, node);
    }
}

static void
ply_signal_dispatcher_reset_signal_sources (ply_signal_dispatcher_t *dispatcher,
                                            int                      fd)
{
  ply_list_node_t *node;

  node = ply_list_get_first_node (dispatcher->sources);
  while (node != NULL)
    {
      ply_signal_source_t *handler;

      handler = (ply_signal_source_t *) ply_list_node_get_data (node);

      signal (handler->signal_number,
              handler->old_posix_signal_handler != NULL?
              handler->old_posix_signal_handler : SIG_DFL);

      node = ply_list_get_next_node (dispatcher->sources, node);
    }
}

static ply_event_destination_t *
ply_event_destination_new (ply_event_loop_fd_status_t     status,
                           ply_event_handler_t            status_met_handler,
                           ply_event_handler_t            disconnected_handler,
                           void                          *user_data)
{
  ply_event_destination_t *destination;

  destination = calloc (1, sizeof (ply_event_destination_t));

  destination->source = NULL;
  destination->status = status;
  destination->status_met_handler = status_met_handler;
  destination->disconnected_handler = disconnected_handler;
  destination->user_data = user_data;

  return destination;
}

static void
ply_event_destination_free (ply_event_destination_t *destination)
{
  if (destination == NULL)
    return;

  free (destination);
}

static ply_fd_watch_t *
ply_fd_watch_new (ply_event_destination_t *destination)
{
  ply_fd_watch_t *watch;

  watch = calloc (1, sizeof (ply_fd_watch_t));
  watch->destination = destination;

  return watch;
}

static void
ply_fd_watch_free (ply_fd_watch_t *watch)
{
  watch->destination = NULL;
  free (watch);
}

static ply_event_source_t *
ply_event_source_new (int fd)
{
  ply_event_source_t *source;

  source = calloc (1, sizeof (ply_event_source_t));

  source->fd = fd;
  source->destinations = ply_list_new ();
  source->fd_watches = ply_list_new ();
  source->is_getting_polled = false;
  source->is_disconnected = false;

  return source;
}

static void
ply_event_source_free (ply_event_source_t *source)
{
  if (source == NULL)
    return;

  assert (ply_list_get_length (source->destinations) == 0);

  ply_list_free (source->destinations);
  ply_list_free (source->fd_watches);
  free (source);
}

static void
ply_event_loop_update_source_event_mask (ply_event_loop_t   *loop,
                                         ply_event_source_t *source)
{
  ply_list_node_t *node;
  struct epoll_event event = { 0 };
  int status;

  assert (loop != NULL);
  assert (source != NULL);
  assert (source->destinations != NULL);

  event.events = EPOLLERR | EPOLLHUP;

  node = ply_list_get_first_node (source->destinations);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_destination_t *destination;

      destination = (ply_event_destination_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (source->destinations, node);

      if (destination->status & PLY_EVENT_LOOP_FD_STATUS_HAS_DATA)
          event.events |= EPOLLIN;

      if (destination->status & PLY_EVENT_LOOP_FD_STATUS_HAS_CONTROL_DATA)
          event.events |= EPOLLPRI;

      if (destination->status & PLY_EVENT_LOOP_FD_STATUS_CAN_TAKE_DATA)
          event.events |= EPOLLOUT;

      node = next_node;
    }
  event.data.ptr = source;

  if (source->is_getting_polled)
    {
      status = epoll_ctl (loop->epoll_fd, EPOLL_CTL_MOD, source->fd, &event);
    }
}

static ply_fd_watch_t *
ply_event_loop_add_destination_for_source (ply_event_loop_t        *loop,
                                           ply_event_destination_t *destination,
                                           ply_event_source_t      *source)
{
  ply_list_node_t *destination_node;
  ply_fd_watch_t *watch;

  assert (loop != NULL);
  assert (destination != NULL);
  assert (destination->source == NULL);
  assert (source != NULL);

  destination->source = source;
  destination_node = ply_list_append_data (source->destinations, destination);
  assert (destination_node != NULL);
  assert (destination->source == source);

  ply_event_loop_update_source_event_mask (loop, source);

  watch = ply_fd_watch_new (destination);

  ply_list_append_data (source->fd_watches, watch);

  return watch;
}

static ply_event_destination_t *
ply_event_loop_get_destination_from_fd_watch (ply_event_loop_t *loop,
                                              ply_fd_watch_t   *watch)
{
   ply_event_destination_t *destination;

   assert (loop != NULL);
   assert (watch != NULL);
   assert (watch->destination != NULL);

   destination = watch->destination;

   return destination;
}

static void
ply_event_loop_remove_destination_by_fd_watch (ply_event_loop_t *loop,
                                               ply_fd_watch_t   *watch)
{
  ply_event_destination_t *destination;
  ply_event_source_t *source;

  assert (loop != NULL);
  assert (watch != NULL);

  destination = ply_event_loop_get_destination_from_fd_watch (loop, watch);
  assert (destination != NULL);

  source = destination->source;
  assert (source != NULL);

  ply_list_remove_data (source->destinations, destination);
  assert (ply_list_find_node (source->destinations, destination) == NULL);
  ply_event_loop_update_source_event_mask (loop, source);
}

ply_event_loop_t *
ply_event_loop_new (void)
{
  ply_event_loop_t *loop;

  loop = calloc (1, sizeof (ply_event_loop_t));

  loop->epoll_fd = epoll_create (PLY_EVENT_LOOP_NUM_EVENT_HANDLERS);
  loop->wakeup_time = PLY_EVENT_LOOP_NO_TIMED_WAKEUP;

  assert (loop->epoll_fd >= 0);

  loop->should_exit = false;
  loop->exit_code = 0;

  loop->sources = ply_list_new ();
  loop->exit_closures = ply_list_new ();
  loop->timeout_watches = ply_list_new ();

  loop->signal_dispatcher = ply_signal_dispatcher_new ();

  if (loop->signal_dispatcher == NULL)
    return NULL;

  ply_event_loop_watch_fd (loop,
                           ply_signal_dispatcher_receiver_fd,
                           PLY_EVENT_LOOP_FD_STATUS_HAS_DATA,
                           (ply_event_handler_t)
                           ply_signal_dispatcher_dispatch_signal,
                           (ply_event_handler_t)
                           ply_signal_dispatcher_reset_signal_sources,
                           loop->signal_dispatcher);

  return loop;
}

static void
ply_event_loop_free_exit_closures (ply_event_loop_t *loop)
{
  ply_list_node_t *node;

  node = ply_list_get_first_node (loop->exit_closures);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_loop_exit_closure_t *closure;

      closure = (ply_event_loop_exit_closure_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (loop->exit_closures, node);
      free (closure);

      node = next_node;
    }
  ply_list_free (loop->exit_closures);
}

static void
ply_event_loop_run_exit_closures (ply_event_loop_t *loop)
{
  ply_list_node_t *node;

  node = ply_list_get_first_node (loop->exit_closures);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_loop_exit_closure_t *closure;

      closure = (ply_event_loop_exit_closure_t *) ply_list_node_get_data (node);

      assert (closure->handler != NULL);
      next_node = ply_list_get_next_node (loop->exit_closures, node);

      closure->handler (closure->user_data, loop->exit_code, loop);

      node = next_node;
    }
}

void
ply_event_loop_free (ply_event_loop_t *loop)
{
  if (loop == NULL)
    return;

  assert (ply_list_get_length (loop->sources) == 0);
  assert (ply_list_get_length (loop->timeout_watches) == 0);

  ply_signal_dispatcher_free (loop->signal_dispatcher);
  ply_event_loop_free_exit_closures (loop);

  ply_list_free (loop->sources);
  ply_list_free (loop->timeout_watches);

  close (loop->epoll_fd);
  free (loop);
}

static ply_list_node_t *
ply_event_loop_find_source_node (ply_event_loop_t *loop,
                                 int               fd)
{
  ply_list_node_t *node;

  node = ply_list_get_first_node (loop->sources);
  while (node != NULL)
    {
      ply_event_source_t *source;

      source = (ply_event_source_t *) ply_list_node_get_data (node);

      if (source->fd == fd)
        break;

      node = ply_list_get_next_node (loop->sources, node);
    }

  return node;
}

static void
ply_event_loop_add_source (ply_event_loop_t    *loop,
                           ply_event_source_t  *source)
{
  struct epoll_event event = { 0 };
  int status;

  assert (ply_event_loop_find_source_node (loop, source->fd) == NULL);
  assert (source->is_getting_polled == false);

  event.events = EPOLLERR | EPOLLHUP;
  event.data.ptr = source;

  status = epoll_ctl (loop->epoll_fd, EPOLL_CTL_ADD, source->fd, &event);
  assert (status == 0);

  source->is_getting_polled = true;

  ply_list_append_data (loop->sources, source);
}

static void
ply_event_loop_remove_source_node (ply_event_loop_t *loop,
                                   ply_list_node_t  *source_node)
{
  ply_event_source_t *source;
  int status;

  source = (ply_event_source_t *) ply_list_node_get_data (source_node);

  assert (source != NULL);

  if (source->is_getting_polled)
    {
      status = epoll_ctl (loop->epoll_fd, EPOLL_CTL_DEL, source->fd, NULL);
      source->is_getting_polled = false;
    }

  ply_list_remove_node (loop->sources, source_node);
}

static void
ply_event_loop_remove_source (ply_event_loop_t   *loop,
                              ply_event_source_t *source)
{
  ply_list_node_t *source_node;
  assert (ply_list_get_length (source->destinations) == 0);

  source_node = ply_list_find_node (loop->sources, source);

  assert (source_node != NULL);

  ply_event_loop_remove_source_node (loop, source_node);
}

void
ply_event_loop_free_sources (ply_event_loop_t *loop)
{
  ply_list_node_t *node;

  node = ply_list_get_first_node (loop->sources);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_source_t *source;

      source = (ply_event_source_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (loop->sources, node);
      ply_event_loop_remove_source_node (loop, node);
      node = next_node;
    }
}

static bool
ply_event_loop_fd_status_is_valid (ply_event_loop_fd_status_t status)
{
  return (status & ~(PLY_EVENT_LOOP_FD_STATUS_NONE
                     | PLY_EVENT_LOOP_FD_STATUS_HAS_DATA
                     | PLY_EVENT_LOOP_FD_STATUS_HAS_CONTROL_DATA
                     | PLY_EVENT_LOOP_FD_STATUS_CAN_TAKE_DATA)) == 0;

}

static ply_event_source_t *
ply_event_loop_get_source_from_fd (ply_event_loop_t *loop,
                                   int               fd)
{
  ply_list_node_t *source_node;
  ply_event_source_t *source;

  source_node = ply_event_loop_find_source_node (loop, fd);

  if (source_node == NULL)
    {
      source = ply_event_source_new (fd);
      ply_event_loop_add_source (loop, source);

      source_node = ply_list_get_last_node (loop->sources);
      assert (source_node != NULL);
    }

  source = (ply_event_source_t *) ply_list_node_get_data (source_node);
  assert (source->fd == fd);

  return source;
}

ply_fd_watch_t *
ply_event_loop_watch_fd (ply_event_loop_t           *loop,
                         int                         fd,
                         ply_event_loop_fd_status_t  status,
                         ply_event_handler_t         status_met_handler,
                         ply_event_handler_t         disconnected_handler,
                         void                       *user_data)
{

  ply_event_source_t *source;
  ply_event_destination_t *destination;
  ply_fd_watch_t *watch;

  assert (loop != NULL);
  assert (fd >= 0);
  assert (ply_event_loop_fd_status_is_valid (status));
  assert (status != PLY_EVENT_LOOP_FD_STATUS_NONE || status_met_handler == NULL);

  source = ply_event_loop_get_source_from_fd (loop, fd);
  assert (source != NULL);

  destination = ply_event_destination_new (status, status_met_handler,
                                           disconnected_handler, user_data);
  watch = ply_event_loop_add_destination_for_source (loop, destination, source);

  return watch;
}

void
ply_event_loop_stop_watching_fd (ply_event_loop_t *loop,
                                 ply_fd_watch_t   *watch)
{
  ply_event_destination_t *destination;
  ply_event_source_t *source;

  destination = ply_event_loop_get_destination_from_fd_watch (loop, watch);
  assert (destination != NULL);

  source = destination->source;
  assert (source != NULL);
  assert (source->fd >= 0);

  /* if we're already disconnected then the watch is already scheduled
   * to be removed by ply_event_loop_disconnect_source
   */
  if (source->is_disconnected)
    {
      ply_list_remove_data (source->fd_watches, watch);
      ply_fd_watch_free (watch);
      return;
    }

  ply_event_loop_remove_destination_by_fd_watch (loop, watch);

  ply_list_remove_data (source->fd_watches, watch);
  ply_fd_watch_free (watch);
  ply_event_destination_free (destination);

  if (ply_list_get_length (source->destinations) == 0)
    {
      ply_event_loop_remove_source (loop, source);
      ply_event_source_free (source);
    }
}

static ply_list_node_t *
ply_signal_dispatcher_find_source_node (ply_signal_dispatcher_t *dispatcher,
                                        int                 signal_number)
{
  ply_list_node_t *node;

  node = ply_list_get_first_node (dispatcher->sources);
  while (node != NULL)
    {
      ply_signal_source_t *handler;

      handler = (ply_signal_source_t *) ply_list_node_get_data (node);

      assert (handler != NULL);

      if (handler->signal_number == signal_number)
        break;

      node = ply_list_get_next_node (dispatcher->sources, node);
    }

  return node;
}

void
ply_event_loop_watch_signal (ply_event_loop_t   *loop,
                            int                  signal_number,
                            ply_event_handler_t  signal_handler,
                            void                *user_data)
{
  ply_signal_source_t *source;

  source = ply_signal_source_new (signal_number,
                                  signal_handler,
                                  user_data);

  source->old_posix_signal_handler =
      signal (signal_number, ply_signal_dispatcher_posix_signal_handler);
  ply_list_append_data (loop->signal_dispatcher->sources, source);
}

static void
ply_signal_dispatcher_remove_source_node (ply_signal_dispatcher_t  *dispatcher,
                                          ply_list_node_t          *node)
{
  ply_signal_source_t *source;

  source = (ply_signal_source_t *) ply_list_node_get_data (node);

  signal (source->signal_number,
          source->old_posix_signal_handler != NULL?
          source->old_posix_signal_handler : SIG_DFL);

  ply_list_remove_node (dispatcher->sources, node);
}

void
ply_event_loop_stop_watching_signal (ply_event_loop_t *loop,
                                     int               signal_number)
{
  ply_list_node_t *node;

  node = ply_signal_dispatcher_find_source_node (loop->signal_dispatcher,
                                                 signal_number);

  assert (node != NULL);

  ply_signal_dispatcher_remove_source_node (loop->signal_dispatcher, node);
}

void
ply_event_loop_watch_for_exit (ply_event_loop_t              *loop,
                               ply_event_loop_exit_handler_t  exit_handler,
                               void                          *user_data)
{
  ply_event_loop_exit_closure_t *closure;

  assert (loop != NULL);
  assert (exit_handler != NULL);

  closure = calloc (1, sizeof (ply_event_loop_exit_closure_t));
  closure->handler = exit_handler;
  closure->user_data = user_data;

  ply_list_append_data (loop->exit_closures, closure);
}

void
ply_event_loop_stop_watching_for_exit (ply_event_loop_t *loop,
                                       ply_event_loop_exit_handler_t exit_handler,
                                       void             *user_data)
{
  ply_list_node_t *node;

  node = ply_list_get_first_node (loop->exit_closures);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_loop_exit_closure_t *closure;

      closure = (ply_event_loop_exit_closure_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (loop->exit_closures, node);

      if (closure->handler == exit_handler &&
          closure->user_data == user_data) {
              ply_list_remove_node (loop->exit_closures, node);
              free (closure);
      }

      node = next_node;
    }
}

void
ply_event_loop_watch_for_timeout (ply_event_loop_t    *loop,
                                  double               seconds,
                                  ply_event_loop_timeout_handler_t timeout_handler,
                                  void                *user_data)
{
  ply_event_loop_timeout_watch_t *timeout_watch;

  assert (loop != NULL);
  assert (timeout_handler != NULL);
  assert (seconds > 0.0);

  timeout_watch = calloc (1, sizeof (ply_event_loop_timeout_watch_t));
  timeout_watch->timeout = ply_get_timestamp () + seconds;
  timeout_watch->handler = timeout_handler;
  timeout_watch->user_data = user_data;

  if (fabs (loop->wakeup_time - PLY_EVENT_LOOP_NO_TIMED_WAKEUP) <= 0)
    loop->wakeup_time = timeout_watch->timeout;
  else
    loop->wakeup_time = MIN (loop->wakeup_time, timeout_watch->timeout);

  ply_list_append_data (loop->timeout_watches, timeout_watch);
}

void
ply_event_loop_stop_watching_for_timeout (ply_event_loop_t *loop,
                                          ply_event_loop_timeout_handler_t timeout_handler,
                                          void             *user_data)
{
  ply_list_node_t *node;

  node = ply_list_get_first_node (loop->timeout_watches);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_loop_timeout_watch_t *timeout_watch;

      timeout_watch = (ply_event_loop_timeout_watch_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (loop->timeout_watches, node);

      if (timeout_watch->handler == timeout_handler &&
          timeout_watch->user_data == user_data) {
              ply_list_remove_node (loop->timeout_watches, node);
              free (timeout_watch);
      }

      node = next_node;
    }
}

static ply_event_loop_fd_status_t
ply_event_loop_get_fd_status_from_poll_mask (uint32_t mask)
{
  ply_event_loop_fd_status_t status;

  status = PLY_EVENT_LOOP_FD_STATUS_NONE;

  if (mask & EPOLLIN)
    status |= PLY_EVENT_LOOP_FD_STATUS_HAS_DATA;

  if (mask & EPOLLPRI)
    status |= PLY_EVENT_LOOP_FD_STATUS_HAS_CONTROL_DATA;

  if (mask & EPOLLOUT)
    status |= PLY_EVENT_LOOP_FD_STATUS_CAN_TAKE_DATA;

  return status;
}

static bool
ply_event_loop_source_has_met_status (ply_event_source_t         *source,
                                      ply_event_loop_fd_status_t  status)
{
  ply_list_node_t *node;

  assert (source != NULL);
  assert (ply_event_loop_fd_status_is_valid (status));

  node = ply_list_get_first_node (source->destinations);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_destination_t *destination;

      destination = (ply_event_destination_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (source->destinations, node);

      if (((destination->status & status) != 0)
          && (destination->status_met_handler != NULL))
        return true;

      node = next_node;
    }
  return false;
}

static void
ply_event_loop_handle_met_status_for_source (ply_event_loop_t           *loop,
                                             ply_event_source_t         *source,
                                             ply_event_loop_fd_status_t  status)
{
  ply_list_node_t *node;

  assert (loop != NULL);
  assert (source != NULL);
  assert (ply_event_loop_fd_status_is_valid (status));

  node = ply_list_get_first_node (source->destinations);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_destination_t *destination;

      destination = (ply_event_destination_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (source->destinations, node);

      if (((destination->status & status) != 0)
          && (destination->status_met_handler != NULL))
        destination->status_met_handler (destination->user_data, source->fd);

      node = next_node;
    }
}

static void
ply_event_loop_handle_disconnect_for_source (ply_event_loop_t   *loop,
                                             ply_event_source_t *source)
{
  ply_list_node_t *node;

  assert (loop != NULL);
  assert (source != NULL);

  source->is_disconnected = true;
  node = ply_list_get_first_node (source->destinations);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_destination_t *destination;

      destination = (ply_event_destination_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (source->destinations, node);

      if (destination->disconnected_handler != NULL)
        destination->disconnected_handler (destination->user_data, source->fd);

      node = next_node;
    }
}

static void
ply_event_loop_free_watches_for_source (ply_event_loop_t   *loop,
                                        ply_event_source_t *source)
{
  ply_list_node_t *node;

  assert (loop != NULL);
  assert (source != NULL);

  node = ply_list_get_first_node (source->fd_watches);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_fd_watch_t *watch;

      next_node = ply_list_get_next_node (source->fd_watches, node);

      watch = (ply_fd_watch_t *) ply_list_node_get_data (node);

      assert (watch != NULL);
      ply_fd_watch_free (watch);
      ply_list_remove_node (source->fd_watches, node);
      node = next_node;
    }
}

static void
ply_event_loop_free_timeout_watches (ply_event_loop_t *loop)
{
  ply_list_node_t *node;
  double now;

  assert (loop != NULL);

  now = ply_get_timestamp ();
  node = ply_list_get_first_node (loop->timeout_watches);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_loop_timeout_watch_t *watch;

      watch = (ply_event_loop_timeout_watch_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (loop->timeout_watches, node);

      free (watch);
      ply_list_remove_node (loop->timeout_watches, node);

      node = next_node;
    }

  assert (ply_list_get_length (loop->timeout_watches) == 0);
  loop->wakeup_time = PLY_EVENT_LOOP_NO_TIMED_WAKEUP;
}

static void
ply_event_loop_free_destinations_for_source (ply_event_loop_t   *loop,
                                             ply_event_source_t *source)
{
  ply_list_node_t *node;

  assert (loop != NULL);
  assert (source != NULL);

  node = ply_list_get_first_node (source->destinations);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_destination_t *destination;

      next_node = ply_list_get_next_node (source->destinations, node);

      destination =
          (ply_event_destination_t *) ply_list_node_get_data (node);

      assert (destination != NULL);
      ply_event_destination_free (destination);
      ply_list_remove_node (source->destinations, node);
      node = next_node;
    }
}

static void
ply_event_loop_disconnect_source (ply_event_loop_t           *loop,
                                  ply_event_source_t         *source)
{
  ply_event_loop_handle_disconnect_for_source (loop, source);

  /* at this point, we've told the event loop users about the
   * fd disconnection, so we can invalidate any outstanding
   * watches and free the destinations.
   */
  ply_event_loop_free_watches_for_source (loop, source);
  ply_event_loop_free_destinations_for_source (loop, source);
  assert (ply_list_get_length (source->destinations) == 0);

  ply_event_loop_remove_source (loop, source);
  ply_event_source_free (source);
}

static void
ply_event_loop_handle_timeouts (ply_event_loop_t *loop)
{
  ply_list_node_t *node;
  double now;

  assert (loop != NULL);

  now = ply_get_timestamp ();
  node = ply_list_get_first_node (loop->timeout_watches);
  while (node != NULL)
    {
      ply_list_node_t *next_node;
      ply_event_loop_timeout_watch_t *watch;

      watch = (ply_event_loop_timeout_watch_t *) ply_list_node_get_data (node);
      next_node = ply_list_get_next_node (loop->timeout_watches, node);

      if (watch->timeout <= now)
        {
          assert (watch->handler != NULL);
          watch->handler (watch->user_data, loop);
          free (watch);
          ply_list_remove_node (loop->timeout_watches, node);
        }

      node = next_node;
    }

  if (ply_list_get_length (loop->timeout_watches) == 0)
    loop->wakeup_time = PLY_EVENT_LOOP_NO_TIMED_WAKEUP;
}

static void
ply_event_loop_process_pending_events (ply_event_loop_t *loop)
{
  int number_of_received_events, i;
  static struct epoll_event *events = NULL;

  assert (loop != NULL);

  if (events == NULL)
    events =
        malloc (PLY_EVENT_LOOP_NUM_EVENT_HANDLERS * sizeof (struct epoll_event));

  memset (events, -1,
          PLY_EVENT_LOOP_NUM_EVENT_HANDLERS * sizeof (struct epoll_event));

  do
   {
     int timeout;

     if (fabs (loop->wakeup_time - PLY_EVENT_LOOP_NO_TIMED_WAKEUP) <= 0)
       timeout = -1;
     else
       {
         timeout = (int) ((loop->wakeup_time - ply_get_timestamp ()) * 1000);
         timeout = MAX (timeout, 0);
       }

     number_of_received_events = epoll_wait (loop->epoll_fd, events,
                                             sizeof (events), timeout);

     ply_event_loop_handle_timeouts (loop);

     if (number_of_received_events < 0)
       {
         if (errno != EINTR)
           {
             ply_event_loop_exit (loop, 255);
             return;
           }
       }
    }
  while ((number_of_received_events < 0) && (errno == EINTR));

  for (i = 0; i < number_of_received_events; i++)
    {
      ply_event_source_t *source;
      ply_event_loop_fd_status_t status;
      bool is_disconnected;

      source = (ply_event_source_t *) (events[i].data.ptr);
      status = ply_event_loop_get_fd_status_from_poll_mask (events[i].events);

      is_disconnected = false;
      if ((events[i].events & EPOLLHUP) || (events[i].events & EPOLLERR))
        {
          int bytes_ready;

          bytes_ready = 0;
          if (ioctl (source->fd, FIONREAD, &bytes_ready) < 0)
            bytes_ready = 0;

          if (bytes_ready <= 0)
            is_disconnected = true;
        }

      if (is_disconnected)
        {
          source->is_getting_polled = false;
          ply_event_loop_disconnect_source (loop, source);
        }
      else if (ply_event_loop_source_has_met_status (source, status))
        ply_event_loop_handle_met_status_for_source (loop, source, status);

      if (loop->should_exit)
        break;
    }
}

void
ply_event_loop_exit (ply_event_loop_t *loop,
                     int               exit_code)
{
  assert (loop != NULL);

  loop->should_exit = true;
  loop->exit_code = exit_code;
}

int
ply_event_loop_run (ply_event_loop_t *loop)
{
  while (!loop->should_exit)
    ply_event_loop_process_pending_events (loop);

  ply_event_loop_run_exit_closures (loop);
  ply_event_loop_free_sources (loop);
  ply_event_loop_free_timeout_watches (loop);

  loop->should_exit = false;

  return loop->exit_code;
}

#ifdef PLY_EVENT_LOOP_ENABLE_TEST

static ply_event_loop_t *loop;

static void
alrm_signal_handler (void)
{
  write (1, "times up!\n", sizeof ("times up!\n") - 1);
  ply_event_loop_exit (loop, 0);
}

static void
usr1_signal_handler (void)
{
  write (1, "got sigusr1\n", sizeof ("got sigusr1\n") - 1);
}

static void
hangup_signal_handler (void)
{
  write (1, "got hangup\n", sizeof ("got hangup\n") - 1);
}

static void
terminate_signal_handler (void)
{
  write (1, "got terminate\n", sizeof ("got terminate\n") - 1);
  ply_event_loop_exit (loop, 0);
}

static void
line_received_handler (void)
{
  char line[512] = { 0 };
  printf ("Received line: ");
  fflush (stdout);

  fgets (line, sizeof (line), stdin);
  printf ("%s", line);
}

static void
on_timeout (ply_event_loop_t *loop)
{
  printf ("timeout elapsed\n");
}

int
main (int    argc,
      char **argv)
{
  int exit_code;

  loop = ply_event_loop_new ();

  ply_event_loop_watch_signal (loop, SIGHUP,
                             (ply_event_handler_t) hangup_signal_handler,
                             NULL);
  ply_event_loop_watch_signal (loop, SIGTERM,
                             (ply_event_handler_t)
                             terminate_signal_handler, NULL);
  ply_event_loop_watch_signal (loop, SIGUSR1,
                             (ply_event_handler_t)
                             usr1_signal_handler, NULL);
  ply_event_loop_watch_signal (loop, SIGALRM,
                             (ply_event_handler_t)
                             alrm_signal_handler, NULL);

  ply_event_loop_watch_for_timeout (loop, 2.0,
                                    (ply_event_loop_timeout_handler_t)
                                    on_timeout, loop);
  ply_event_loop_watch_fd (loop, 0, PLY_EVENT_LOOP_FD_STATUS_HAS_DATA,
                          (ply_event_handler_t) line_received_handler,
                          (ply_event_handler_t) line_received_handler,
                          NULL);

  alarm (5);
  exit_code = ply_event_loop_run (loop);

  ply_event_loop_free (loop);

  return exit_code;
}
#endif /* PLY_EVENT_LOOP_ENABLE_TEST */
/* vim: set ts=4 sw=4 expandtab autoindent cindent cino={.5s,(0: */