Repository navigation
Expand file tree
/
Copy pathstompy.c
More file actions
2397 lines (2155 loc) · 69 KB
/
Copy pathstompy.c
File metadata and controls
2397 lines (2155 loc) · 69 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
/*
Copyright (C) 2014, 2015, 2016 Phil Wieland
This program 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 3 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, see <http://www.gnu.org/licenses/>.
phil@philwieland.com
*/
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <sys/sysinfo.h>
#include <netinet/in.h>
#include <errno.h>
#include <netdb.h>
#include <dirent.h>
#include "misc.h"
#define NAME "stompy"
#define BUILD "X328"
static void perform(void);
static void set_up_server_sockets(void);
static void stomp_write(void);
static void stomp_read(void);
static void client_write(const int s);
static void client_read(const int s);
static void client_accept(const int s);
static void user_command(void);
static void send_subscribes(void);
static void handle_shutdown(word report);
static void full_shutdown(void);
enum stomp_manager_event {SM_START, SM_ERROR, SM_FAIL, SM_TIMEOUT, SM_TX_DONE, SM_RX_DONE, SM_SHUTDOWN, SM_EVENTS};
static void stomp_manager(const enum stomp_manager_event event, const char * const headers);
static void stomp_queue_tx(const char * const d, const ssize_t l);
static void report_stats(void);
static void report_alarms(void);
static void report_rates(const char * const m);
static void next_stats(void);
static void next_alarms(void);
static void report_status(void);
static void dump_headers(const char * const h);
static void init_buffers_queues(void);
static struct frame_buffer * new_buffer(void);
static void free_buffer(struct frame_buffer * const b);
static void enqueue(const word s, struct frame_buffer * const b);
static struct frame_buffer * dequeue(const word s);
static struct frame_buffer * queue_front(const word s);
static word queue_length(const word s);
static void dump_buffer_to_disc(const word s, struct frame_buffer * const b);
static word dump_queue_to_disc(const word s);
static int is_a_buffer(const struct dirent *d);
static word load_queue_from_disc(const word s);
static int disc_queue_length(const word s);
static qword disc_queue_oldest(const word s);
static void log_message(const word s);
static word count_messages(const struct frame_buffer * const b);
static void heartbeat_tx(void);
static word debug, run, interrupt, sigusr1, controlled_shutdown;
static char zs[4096];
// STOMP manager
static enum {SM_AWAIT_CONNECTED, SM_RUN, SM_SEND_DISCO, SM_HOLD, SM_STATES} stomp_manager_state;
// STOMP RX
static enum {STOMP_IDLE, STOMP_HEADER, STOMP_BODY, STOMP_FAIL} stomp_read_state;
static struct frame_buffer * stomp_read_buffer;
// STOMP TX Queue
#define STOMP_TX_QUEUE_SIZE 32768
static char stomp_tx_queue[STOMP_TX_QUEUE_SIZE];
static ssize_t stomp_tx_queue_on, stomp_tx_queue_off;
#define BASE_PORT 55840
#define STOMP_HOST "datafeeds.networkrail.co.uk"
#define STOMP_PORT 61618
// Select timeout period in seconds
#define SELECT_TIMEOUT 2
// Sockets
static fd_set read_sockets, write_sockets, active_read_sockets, active_write_sockets;
static int s_stomp;
static byte s_stream[FD_SETSIZE];
#define STREAMS 4
#define STOMP STREAMS
static byte s_type[FD_SETSIZE];
enum s_types {CLIENT, SERVER, TYPES};
static int s_number[STREAMS][TYPES];
// Stream modes
static enum {STREAM_DISC, STREAM_RUN, STREAM_LOCK} stream_state[STREAMS];
static char * stomp_topics[STREAMS];
static char * stomp_topic_names[STREAMS];
static word stomp_topic_log[STREAMS];
static char topics[1024];
// Stats
static time_t start_time;
enum stats_categories {StompBytes, ConnectAttempt, StompMessage, BaseStreamFrameSent,
DiscWrite = BaseStreamFrameSent + STREAMS, DiscRead, MAXstats
};
static qword stats[MAXstats];
static qword grand_stats[MAXstats];
static const char * stats_category[MAXstats] =
{
"STOMP Bytes", "STOMP Connect Attempt", "STOMP Message", "", "", "", "",
"Frame Disc Write", "Frame Disc Read",
};
static qword stats_longest;
static qword grand_stats_longest;
#define RATES_AVERAGE_OVER 16
static word rates_count[STREAMS][RATES_AVERAGE_OVER];
static word rates_index, rates_start;
// Timers
static time_t now;
// Time in hours (local) when daily statistical report is produced.
#define REPORT_HOUR 4
// STOMP timeout in seconds
#define STOMP_TIMEOUT 64
// server socket retry time in seconds
#define SERVER_SOCKET_RETRY 32
// Heartbeat TX interval in seconds
#define HEARTBEAT_TX 16
static time_t stats_due, alarms_due, server_sockets_due, stomp_timeout, rates_due, heartbeat_tx_due;
// STOMP controls
static word stomp_holdoff;
// Disc spool
// This and sub-directories will be created if required.
#define STOMPY_SPOOL "/var/spool/stompy"
// Command file
#define COMMAND_FILE "/tmp/stompy.cmd"
// Message rates log file
#define RATES_FILE "/var/log/garner/stompy.rates"
// Message log
#define MESSAGE_LOG_FILEPATH "/var/log/garner/stompy.messagelog"
// Frame buffers and queues thereof
#define BUFFERS 32
#define FRAME_SIZE 64000
static struct frame_buffer
{
char frame[FRAME_SIZE];
qword stamp;
struct frame_buffer * next;
} buffers[BUFFERS];
static struct frame_buffer * empty_list, * stream_q_on[STREAMS], * stream_q_off[STREAMS];
// Client interface
static ssize_t client_length[STREAMS], client_index[STREAMS];
static struct frame_buffer * client_buffer[STREAMS];
static enum { CLIENT_IDLE, CLIENT_AWAIT_ACK, CLIENT_RUN} client_state[STREAMS];
// Signal handling
void termination_handler(int signum)
{
if(signum == SIGUSR1)
{
sigusr1 = true;
}
else if(signum != SIGHUP)
{
interrupt = true;
}
}
int main(int argc, char *argv[])
{
int c;
char config_file_path[256];
word usage = false;
strcpy(config_file_path, "/etc/openrail.conf");
while ((c = getopt (argc, argv, ":c:")) != -1)
{
switch (c)
{
case 'c':
strcpy(config_file_path, optarg);
break;
case ':':
break;
case '?':
default:
usage = true;
break;
}
}
char * config_fail;
if((config_fail = load_config(config_file_path)))
{
printf("Failed to read config file \"%s\": %s\n", config_file_path, config_fail);
usage = true;
}
debug = *conf[conf_debug];
if(usage)
{
printf("\tUsage: %s [-c /path/to/config/file.conf]\n\n", argv[0] );
exit(1);
}
{
// Parse subscriptions from config
strcpy(topics, conf[conf_stomp_topics]);
char * p = topics;
char * q;
char * e = p + strlen(p);
int i;
for(i = 0; i < STREAMS; i++)
{
q = strchr(p, ';');
if(q)
{
stomp_topics[i] = p;
*q = '\0';
p = q + 1;
}
else
{
stomp_topics[i] = p;
p = e;
}
if(!strcasecmp(stomp_topics[i], "void")) stomp_topics[i][0] = '\0';
}
p = e + 1;
strcpy(p, conf[conf_stomp_topic_names]);
e = p + strlen(p);
for(i = 0; i < STREAMS; i++)
{
q = strchr(p, ';');
if(q)
{
stomp_topic_names[i] = p;
*q = '\0';
p = q + 1;
}
else
{
stomp_topic_names[i] = p;
p = e;
}
}
for(i = 0; i < STREAMS; i++)
{
stomp_topic_log[i] = false;
}
{
char temp[2048];
strcpy(temp, conf[conf_stomp_topic_log]);
p = temp;
for(i = 0; i < STREAMS; i++)
{
q = strchr(p, ';');
if(q)
{
*q = '\0';
stomp_topic_log[i] = !strcasecmp(p, "true");
p = q + 1;
}
}
}
}
int lfp = 0;
now = start_time = time(NULL);
// Set up log
_log_init(debug?"/tmp/stompy.log":"/var/log/garner/stompy.log", debug?1:0);
_log(GENERAL, "");
_log(GENERAL, "%s %s", NAME, BUILD);
// Enable core dumps
struct rlimit limit;
if(!getrlimit(RLIMIT_CORE, &limit))
{
limit.rlim_cur = RLIM_INFINITY;
setrlimit(RLIMIT_CORE, &limit);
}
// Create spool directories
{
word s;
struct stat b;
char d[256];
if(stat(STOMPY_SPOOL, &b))
{
if(mkdir(STOMPY_SPOOL, 0777))
{
_log(CRITICAL, "Failed to create spool directory \"%s\". Error %d %s", STOMPY_SPOOL, errno, strerror(errno));
}
else
{
_log(GENERAL, "Created spool directory \"%s\".", STOMPY_SPOOL);
}
if(chmod(STOMPY_SPOOL, 0777))
{
_log(CRITICAL, "Failed to chmod spool directory \"%s\". Error %d %s", STOMPY_SPOOL, errno, strerror(errno));
}
}
if(stat(STOMPY_SPOOL, &b))
{
_log(CRITICAL, "Spool directory \"%s\" missing. Error %d %s. Fatal.", STOMPY_SPOOL, errno, strerror(errno));
exit(1);
}
for(s = 0; s < STREAMS; s++)
{
sprintf(d, "%s/%s%d", STOMPY_SPOOL, debug?"d-":"", s);
if(stat(d, &b))
{
if(mkdir(d, 0777))
{
_log(CRITICAL, "Failed to create spool directory \"%s\". Error %d %s", d, errno, strerror(errno));
}
else
{
_log(GENERAL, "Created spool directory \"%s\".", d);
}
if(chmod(d, 0777))
{
_log(CRITICAL, "Failed to chmod spool directory \"%s\". Error %d %s", d, errno, strerror(errno));
}
}
if(disc_queue_length(s) < 0)
{
_log(CRITICAL, "Spool directory missing for stream %d. Fatal.", s);
exit(1);
}
}
}
// DAEMONISE
if(debug != 1)
{
int i=fork();
if (i<0)
{
/* fork error */
_log(CRITICAL, "fork() error. Aborting.");
exit(1);
}
if (i>0) exit(0); /* parent exits */
/* child (daemon) continues */
pid_t sid = setsid(); /* obtain a new process group */
if(sid < 0)
{
/* setsid error */
_log(CRITICAL, "setsid() error. Aborting.");
exit(1);
}
for (i=getdtablesize(); i>=0; --i) close(i); /* close all descriptors */
umask(022); // Created files will be rw for owner, r for all others
i = chdir("/var/run/");
if(i < 0)
{
/* chdir error */
_log(CRITICAL, "chdir() error. Aborting.");
exit(1);
}
if((lfp = open("/var/run/stompy.pid", O_RDWR|O_CREAT, 0640)) < 0)
{
_log(CRITICAL, "Unable to open pid file \"/var/run/stompy.pid\". Aborting.");
exit(1); /* can not open */
}
if (lockf(lfp,F_TLOCK,0)<0)
{
_log(CRITICAL, "Failed to obtain lock. Aborting.");
exit(1); /* can not lock */
}
char str[128];
sprintf(str, "%d\n", getpid());
i = write(lfp, str, strlen(str)); /* record pid to lockfile */
_log(GENERAL, "Running as daemon.");
}
else
{
_log(GENERAL, "Running in local mode.");
}
// Check core dumps
if(prctl(PR_GET_DUMPABLE, 0, 0, 0, 0) != 1)
{
_log(MAJOR, "PR_GET_DUMPABLE not 1.");
}
else
{
_log(DEBUG, "PR_GET_DUMPABLE is 1.");
}
if(!getrlimit(RLIMIT_CORE, &limit))
{
if(limit.rlim_cur != RLIM_INFINITY)
{
_log(MAJOR, "RLIMIT_CORE not RLIM_INFINITY.");
}
else
{
_log(DEBUG, "RLIMIT_CORE is RLIM_INFINITY.");
}
}
else
{
_log(MAJOR, "Unable to determine RLIMIT_CORE.");
}
run = true;
interrupt = false;
if(signal(SIGTERM, termination_handler) == SIG_IGN) signal(SIGTERM, SIG_IGN);
if(signal(SIGINT, termination_handler) == SIG_IGN) signal(SIGINT, SIG_IGN);
if(signal(SIGHUP, termination_handler) == SIG_IGN) signal(SIGHUP, SIG_IGN);
if(signal(SIGUSR1, termination_handler) == SIG_IGN) signal(SIGUSR1, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
if(!debug) signal(SIGCHLD, SIG_IGN); /* ignore child */
if(!debug) signal(SIGTSTP, SIG_IGN); /* ignore tty signals */
if(!debug) signal(SIGTTOU, SIG_IGN);
if(!debug) signal(SIGTTIN, SIG_IGN);
// Zero the stats
{
word i;
for(i=0; i < MAXstats; i++)
{
stats[i] = 0;
grand_stats[i] = 0;
}
}
stats_longest = grand_stats_longest = 0;
// Remove any user commands lying around.
unlink(COMMAND_FILE);
// Report subscriptions
{
word stream;
_log(GENERAL, "Configured STOMP topics:");
for(stream = 0; stream < STREAMS; stream++)
if(stomp_topics[stream][0])
{
_log(GENERAL, " %d: \"%s\" (%s) Logging %s.", stream, stomp_topics[stream], stomp_topic_names[stream], stomp_topic_log[stream]?"enabled":"disabled");
}
else
{
_log(GENERAL, " %d: Not used.", stream);
}
if(*conf[conf_stompy_bin]) _log(CRITICAL, "All received data will be discarded due to stompy_bin option.");
}
// Startup delay. Only applied immediately after system boot
{
struct sysinfo info;
word logged = false;
word i;
while(run && !debug && (sysinfo(&info) || info.uptime < 32))
{
if(!logged) _log(GENERAL, "Startup delay...");
logged = true;
for(i = 0; i < 8 && run; i++) sleep(1);
}
}
perform();
if(lfp) close(lfp);
return 0;
}
static void perform(void)
{
int s;
word stream, type;
struct timeval wait_time;
// Initialise queues
stomp_tx_queue_on = stomp_tx_queue_off = 0;
init_buffers_queues();
// Initialise all socket settings.
FD_ZERO (&read_sockets);
FD_ZERO (&write_sockets);
s_stomp = -1;
for(stream = 0; stream < STREAMS; stream++)
{
for(type = 0; type < TYPES; type++)
{
s_number[stream][type] = -1;
}
client_state[stream] = CLIENT_IDLE;
client_buffer[stream] = NULL;
stream_state[stream] = STREAM_DISC;
}
run = true;
interrupt = false;
sigusr1 = false;
controlled_shutdown = false;
report_rates(NULL);
// Set up timers
next_stats();
next_alarms();
stomp_timeout = stomp_holdoff = server_sockets_due = rates_due = heartbeat_tx_due = 0;
// Set up STOMP interface
stomp_read_state = STOMP_IDLE;
stomp_read_buffer = NULL;
stomp_manager(SM_START, NULL);
while(run)
{
now = time(NULL);
// Check each timer for expiry
if(now > heartbeat_tx_due) heartbeat_tx();
if(now > server_sockets_due && !controlled_shutdown) set_up_server_sockets();
if(now > stats_due) report_stats();
if(now > alarms_due) report_alarms();
if(now > rates_due) report_rates("");
if(now > stomp_timeout) stomp_manager(SM_TIMEOUT, NULL);
if(controlled_shutdown)
{
wait_time.tv_sec = 0;
wait_time.tv_usec = 0x40000L;
}
else
{
wait_time.tv_sec = SELECT_TIMEOUT;
wait_time.tv_usec = 0;
}
active_read_sockets = read_sockets;
active_write_sockets = write_sockets;
int result = select(FD_SETSIZE, &active_read_sockets, &active_write_sockets, NULL, &wait_time);
if(result < 0)
{
// Error
if(errno == EINTR)
{
}
else
{
_log(CRITICAL, "Select returns error %d %s. Fatal.", errno, strerror(errno));
run = false;
}
}
else if (result == 0)
{
// Select has timed out
if(controlled_shutdown) handle_shutdown(true);
}
else
{
// Got some activity.
for(s = 0; s < FD_SETSIZE; s++)
{
if(FD_ISSET(s, &active_write_sockets))
{
if(s_stream[s] == STOMP) stomp_write();
else client_write(s);
}
if(FD_ISSET(s, &active_read_sockets))
{
if(s_type[s] == SERVER) client_accept(s);
else if(s_stream[s] == STOMP) stomp_read();
else client_read(s);
}
}
}
if(sigusr1) user_command();
sigusr1 = false;
if(interrupt) full_shutdown();
interrupt = false;
}
report_status();
report_stats();
}
static void set_up_server_sockets(void)
{
//
int s;
word stream;
struct sockaddr_in server_addr;
_log(PROC, "set_up_server_sockets()");
server_sockets_due = 0x7fffffff;
if(controlled_shutdown) return;
for(stream = 0; stream < STREAMS; stream++)
{
if(stomp_topics[stream][0] && s_number[stream][SERVER] < 0)
{
s = socket(AF_INET, SOCK_STREAM, 0);
if (s < 0)
{
_log(CRITICAL, "Failed to create server socket for stream %d. Error %d %s. Fatal.", stream, errno, strerror(errno));
exit(1);
}
memset((void *) &server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(BASE_PORT + stream);
if(bind(s, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0)
{
_log(MAJOR, "Failed to bind to socket %d. Error %d %s.", BASE_PORT + stream, errno, strerror(errno));
server_sockets_due = now + SERVER_SOCKET_RETRY;
close(s);
return;
}
// Make it non-blocking
int oldflags = fcntl(s, F_GETFL, 0);
oldflags |= O_NONBLOCK;
fcntl(s, F_SETFL, oldflags);
if (listen (s, 1) < 0)
{
_log(CRITICAL, "Failed to listen on socket %d, port %d, error %d %s. Fatal.", s, BASE_PORT + stream, errno, strerror(errno));
exit(1);
}
FD_SET (s, &read_sockets);
s_type[s] = SERVER;
s_stream[s] = stream;
s_number[stream][SERVER] = s;
_log(DEBUG, "Server socket %d for stream %d set up.", s, stream);
}
}
_log(GENERAL, "All server sockets have been set up.");
}
static void stomp_write(void)
{
// Send anything in the STOMP TX queue.
// Note - This is NOT a proper circular buffer.
_log(PROC, "stomp_write()");
if(stomp_tx_queue_on != stomp_tx_queue_off)
{
ssize_t sent = write(s_stomp, stomp_tx_queue + stomp_tx_queue_off, stomp_tx_queue_on - stomp_tx_queue_off);
if(sent < 0)
{
_log(MAJOR, "Failed to write to STOMP server. Error %d %s", errno, strerror(errno));
stomp_manager(SM_FAIL, NULL);
}
stomp_tx_queue_off += sent;
_log(DEBUG, "stomp_write(): Sent %d bytes. Last byte 0x%02x.", sent, stomp_tx_queue[stomp_tx_queue_off-1]);
}
if(stomp_tx_queue_on == stomp_tx_queue_off)
{
stomp_tx_queue_on = stomp_tx_queue_off = 0;
FD_CLR(s_stomp, &write_sockets);
_log(DEBUG, "stomp_write(): Queue now empty.");
if(controlled_shutdown && stomp_read_state == STOMP_IDLE)
{
stomp_manager(SM_FAIL, NULL);
}
else
{
stomp_manager(SM_TX_DONE, NULL);
}
}
}
static void stomp_read(void)
{
#define MAX_HEADER 1024
static char headers[MAX_HEADER];
static ssize_t stomp_read_h_i, stomp_read_b_i;
static char * mid, * s, * body;
static word stream;
_log(PROC, "stomp_read()");
// N.B. Handling of stomp_read_buffer
// If a receive is interrupted by an error, stomp_read_buffer remains pointing to a buffer (which contains
// garbage). This will be re-used for the next frame.
char d[1024];
ssize_t l = read(s_stomp, d, 1024);
if(l < 0)
{
_log(MAJOR, "STOMP read error %d %s", errno, strerror(errno));
stomp_manager(SM_FAIL, NULL);
return;
}
if(!l)
{
_log(MAJOR, "STOMP read error. End of file.");
stomp_manager(SM_FAIL, NULL);
return;
}
_log(DEBUG, "stomp_read(): Received %d characters.", l);
stats[StompBytes] += l;
ssize_t i;
for(i=0; i < l; i++)
{
switch(stomp_read_state)
{
case STOMP_IDLE: // Start
stomp_read_h_i = stomp_read_b_i = 0;
// First character - could be a heartbeat
if(d[i] == '\n')
{
// Heartbeat
_log(DEBUG, "STOMP heartbeat received.");
stomp_read_state = STOMP_IDLE;
stomp_manager(SM_RX_DONE, NULL);
}
else
{
headers[stomp_read_h_i++] = d[i];
stomp_read_state = STOMP_HEADER;
}
break;
case STOMP_HEADER: // Header
if(stomp_read_h_i >= MAX_HEADER)
{
_log(MAJOR, "Received STOMP headers too long. Frame discarded.");
stomp_read_state = STOMP_FAIL;
}
else
{
if(d[i] == '\n' && headers[stomp_read_h_i - 1] == '\n')
{
// End of header
headers[stomp_read_h_i++] = '\0';
if(debug)
{
_log(DEBUG, "Headers received:");
dump_headers(headers);
}
stomp_read_state = STOMP_BODY;
stomp_read_b_i = 0;
}
else
{
if(stomp_read_h_i < MAX_HEADER - 2)
{
headers[stomp_read_h_i++] = d[i];
}
else
{
_log(MAJOR, "Received STOMP headers too long. Frame discarded.");
stomp_read_state = STOMP_FAIL;
}
}
}
break;
case STOMP_BODY: // Body
if(stomp_manager_state == SM_AWAIT_CONNECTED)
{
// In this case we don't care about the body contents
// Discard until we get the terminating NULL
if(d[i] == '\0')
{
stomp_read_state = STOMP_IDLE;
stomp_manager(SM_RX_DONE, headers);
}
}
else
{
if(stomp_read_b_i == 0 && d[i] == '\0')
{
_log(MAJOR, "STOMP frame received has an empty body. Discarded. Headers:");
dump_headers(headers);
stomp_read_state = STOMP_IDLE;
stomp_manager(SM_RX_DONE, headers);
}
else if(stomp_read_b_i == 0)
{
if(!strstr(headers, "MESSAGE"))
{
_log(MAJOR, "STOMP frame received is not a MESSAGE. Discarded. Headers:");
dump_headers(headers);
stomp_read_state = STOMP_FAIL;
}
else
{
// Find which stream
s = strstr(headers, "subscription:");
if(s)
{
s += 13;
_log(DEBUG, "Stream id %c.", *s);
}
else
{
_log(MAJOR, "STOMP MESSAGE received with no subscription value. Discarded. Headers:");
dump_headers(headers);
stomp_read_state = STOMP_FAIL;
}
}
if(stomp_read_state == STOMP_BODY)
{
mid = strstr(headers, "message-id:");
if(mid)
{
mid += 11;
}
else
{
_log(MAJOR, "STOMP MESSAGE received with no message id. Discarded. Headers:");
dump_headers(headers);
stomp_read_state = STOMP_FAIL;
}
}
// Set up where it's going, and get a queue entry if appropriate
if(stomp_read_state == STOMP_BODY)
{
switch(*s)
{
case '0': case '1': case '2': case '3':
stream = *s - '0';
// Note the following code allows one stream to hog all the buffers. Is that a good idea?
if(!stomp_read_buffer) stomp_read_buffer = new_buffer();
if(stomp_read_buffer)
{
body = stomp_read_buffer->frame;
}
else
{
// Handle run out of buffers: Dump queue to disc, switch to disc mode ask for a buffer again.
_log(GENERAL, "No buffers available for stream %d (%s). Saving to disc.", stream, stomp_topic_names[stream]);
if(!dump_queue_to_disc(stream))
{
// None in our queue, find some elsewhere
word s;
for(s = 0; s < STREAMS; s++)
{
if(dump_queue_to_disc(s))
{
// Found some!
if(stream_state[s] == STREAM_RUN) stream_state[s] = STREAM_DISC;
_log(GENERAL, "Dumped queue to disc and switched to disc mode on stream %d (%s) to free space.", s, stomp_topic_names[s]);
s = STREAMS;
}
}
}
if(stream_state[stream] == STREAM_RUN) stream_state[stream] = STREAM_DISC;
stomp_read_buffer = new_buffer();
if(!stomp_read_buffer)
{
_log(CRITICAL, "Failed to find a free buffer. STOMP MESSAGE discarded.");
stomp_read_state = STOMP_FAIL;
body = NULL;
}
else
body = stomp_read_buffer->frame;
}
break;
default: _log(MAJOR, "STOMP MESSAGE received with unrecognised subscription value \"%c\".", *s);
stomp_read_state = STOMP_FAIL;
body = NULL;
break;
}
}
}
if(stomp_read_state == STOMP_BODY)
{
// Stick character in buffer
stomp_read_b_i++;
if(body) *body++ = d[i];
if(body && !d[i])
{
// Deal with frame
_log(DEBUG, "Got end of message frame. Processing...");
if(stomp_read_b_i > stats_longest) stats_longest = stomp_read_b_i;
stomp_read_buffer->stamp = time_us();
_log(DEBUG, "Stamp is %lld.", stomp_read_buffer->stamp);
rates_count[stream][rates_index] += count_messages(stomp_read_buffer);
if(!(*conf[conf_stompy_bin]))
{
if(stream_state[stream] == STREAM_RUN)
{
enqueue(stream, stomp_read_buffer);
}
else
{
// write buffer to disc and free it
dump_buffer_to_disc(stream, stomp_read_buffer);
}
stomp_read_buffer = NULL; // Buffer has been emptied or recorded in the queue, so we no longer own it.
}
stats[StompMessage]++;
if(s_number[stream][CLIENT] >= 0 && client_state[stream] != CLIENT_AWAIT_ACK)
{
FD_SET(s_number[stream][CLIENT], &write_sockets);
}
// Send ACK
{
char ack_h[1024];
sprintf(ack_h, "ACK\nsubscription:%c\nmessage-id:", *s);
ssize_t i = strlen(ack_h);
while((ack_h[i++] = *mid++) != '\n');
ack_h[i++] = '\n';
ack_h[i++] = '\0';
if(debug)
{
_log(DEBUG, "Ack message headers:");
dump_headers(ack_h);
}
stomp_queue_tx(ack_h, i);
}
// All done
stomp_read_state = STOMP_IDLE;
stomp_manager(SM_RX_DONE, NULL);
}
}
}
break;
case STOMP_FAIL: // Just bin data until the end of the STOMP frame.
if(d[i] == '\0')
{
stomp_read_state = STOMP_IDLE;
stomp_manager(SM_RX_DONE, NULL);
}
break;
}
}
if(controlled_shutdown && stomp_read_state == STOMP_IDLE && stomp_tx_queue_on == 0)
{
stomp_manager(SM_FAIL, NULL);
}
}
static void client_write(const int s)
{
word stream = s_stream[s];
_log(PROC, "client_write(%d): Stream %d, client state %d", s, stream, client_state[stream]);
ssize_t l;