-
Notifications
You must be signed in to change notification settings - Fork 7
/
slutils.c
1968 lines (1718 loc) · 62.3 KB
/
slutils.c
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
/***************************************************************************
* slutils.c
*
* Routines for managing a connection with a SeedLink server
*
* This file is part of the SeedLink Library.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (C) 2024:
* @author Chad Trabant, EarthScope Data Services
***************************************************************************/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include "globmatch.h"
#include "libslink.h"
#include "mseedformat.h"
/* Function(s) only used in this source file */
static int receive_header (SLCD *slconn, uint8_t *buffer, uint32_t bytesavailable);
static int64_t receive_payload (SLCD *slconn, char *plbuffer, uint32_t plbuffersize,
uint8_t *buffer, uint32_t bytesavailable);
static int update_stream (SLCD *slconn, const char *payload);
static int64_t detect (const char *record, uint64_t recbuflen, char *payloadformat);
/* Initialize the global termination handler */
SLCD *global_termination_SLCD = NULL;
/**********************************************************************/ /**
* @brief Managage a connection to a SeedLink server and collect packets
*
* Designed to run in a loop of a client program, this function manages
* the connection to the server and returns received packets. This
* routine will send keepalives if configured for the connection and
* can operate in blocking or non-blocking mode.
*
* The returned \a packetinfo contains the details including: sequence
* number, payload length, payload type, and how much of the payload
* has been returned so far.
*
* If the \a slconn.noblock flags is set, the function will return
* quickly even if no data are available. If the flag is not set,
* the function will block and only return if data are available.
*
* If \a SLTOOLARGE is returned, the \a plbuffer is not large enough to
* hold the payload. The payload length is available at
* \a packetinfo.payloadlength and the caller may choose to reallocate
* the buffer to accommodate the payload. Note that buffer may contain
* partial payload data and should be preserved if reallocated,
* specifically the first \a packetinfo.payloadcollected bytes.
*
* @param[in] slconn SeedLink connection description
* @param[out] packetinfo Pointer to pointer to ::SLpacketinfo describing payload
* @param[out] plbuffer Destination buffer for packet payload
* @param[in] plbuffersize Length of destination buffer
*
* @returns @ref collect-status
* @retval SLPACKET Complete packet returned
* @retval SLTERMINATE Connection termination or error
* @retval SLNOPACKET No packet available, call again
* @retval SLTOOLARGE Payload is larger than allowed maximum
***************************************************************************/
int
sl_collect (SLCD *slconn, const SLpacketinfo **packetinfo,
char *plbuffer, uint32_t plbuffersize)
{
int64_t bytesread;
int64_t current_time;
uint32_t bytesconsumed;
uint32_t bytesavailable;
int poll_state;
if (!slconn || !packetinfo || (plbuffersize > 0 && !plbuffer))
return SLTERMINATE;
while (slconn->terminate < 2)
{
current_time = sl_nstime();
if (slconn->link == -1)
{
slconn->stat->conn_state = DOWN;
}
/* Throttle the loop while delaying */
if (slconn->stat->conn_state == DOWN &&
slconn->stat->netdly_time &&
slconn->stat->netdly_time > current_time)
{
sl_usleep (500000);
}
/* Connect to server if disconnected */
if (slconn->stat->conn_state == DOWN &&
slconn->stat->netdly_time < current_time)
{
if (sl_connect (slconn, 1) != -1)
{
slconn->stat->conn_state = UP;
}
slconn->stat->netto_time = 0;
slconn->stat->netdly_time = 0;
slconn->stat->keepalive_time = 0;
}
/* Negotiate/configure the connection */
if (slconn->stat->conn_state == UP)
{
if (slconn->streams)
{
if (sl_configlink (slconn) == -1)
{
sl_log_r (slconn, 2, 0, "[%s] %s(): negotiation with server failed\n",
slconn->sladdr, __func__);
slconn->link = sl_disconnect (slconn);
slconn->stat->netdly_time = 0;
}
}
slconn->stat->conn_state = STREAMING;
}
/* Send INFO request if one not in progress */
if (slconn->stat->conn_state == STREAMING &&
slconn->stat->query_state == NoQuery &&
slconn->info)
{
if (sl_send_info (slconn, slconn->info, 1) != -1)
{
slconn->stat->query_state = InfoQuery;
}
else
{
slconn->stat->query_state = NoQuery;
}
free (slconn->info);
slconn->info = NULL;
}
/* Read incoming data stream */
if (slconn->stat->conn_state == STREAMING)
{
/* Receive data into internal buffer */
if (slconn->terminate == 0)
{
bytesread = sl_recvdata (slconn,
slconn->recvbuffer + slconn->recvdatalen,
sizeof (slconn->recvbuffer) - slconn->recvdatalen,
slconn->sladdr);
if (bytesread < 0)
{
break;
}
else if (bytesread > 0)
{
slconn->recvdatalen += bytesread;
}
else if (slconn->recvdatalen == 0) /* bytesread == 0 */
{
/* Wait up to 1/2 second when blocking, otherwise 1 millisecond */
poll_state = sl_poll (slconn, 1, 0, (slconn->noblock) ? 1 : 500);
if (poll_state < 0 && slconn->terminate == 0)
{
sl_log_r (slconn, 2, 0, "[%s] %s(): polling error: %s\n",
slconn->sladdr, __func__, sl_strerror ());
break;
}
}
}
/* Process data in internal buffer */
bytesconsumed = 0;
/* Check for special cases of the server reporting end of streaming or errors
* while awaiting a header (i.e. in between packets) */
if (slconn->stat->stream_state == HEADER)
{
if (slconn->recvdatalen - bytesconsumed >= 3 &&
memcmp (slconn->recvbuffer + bytesconsumed, "END", 3) == 0)
{
sl_log_r (slconn, 1, 1, "[%s] End of selected time window or stream (FETCH/dial-up mode)\n",
slconn->sladdr);
bytesconsumed += 3;
break;
}
if (slconn->recvdatalen - bytesconsumed >= 5 &&
memcmp (slconn->recvbuffer + bytesconsumed, "ERROR", 5) == 0)
{
sl_log_r (slconn, 2, 0, "[%s] Server reported an error with the last command\n",
slconn->sladdr);
bytesconsumed += 5;
break;
}
}
/* Read next header */
if (slconn->stat->stream_state == HEADER)
{
bytesavailable = slconn->recvdatalen - bytesconsumed;
if ((slconn->protocol & SLPROTO3X && bytesavailable >= SLHEADSIZE_V3) ||
(slconn->protocol & SLPROTO40 && bytesavailable >= SLHEADSIZE_V4))
{
bytesread = receive_header (slconn,
slconn->recvbuffer + bytesconsumed,
bytesavailable);
if (bytesread < 0)
{
break;
}
else if (bytesread > 0)
{
/* Set state for station ID or payload collection */
if (slconn->stat->packetinfo.stationidlength > 0)
{
slconn->stat->packetinfo.stationid[0] = '\0';
slconn->stat->stream_state = STATIONID;
}
else
{
slconn->stat->packetinfo.payloadcollected = 0;
slconn->stat->stream_state = PAYLOAD;
}
bytesconsumed += bytesread;
}
}
} /* Done reading header */
/* Read station ID */
if (slconn->stat->stream_state == STATIONID &&
slconn->stat->packetinfo.stationidlength > 0 &&
(slconn->recvdatalen - bytesconsumed) >= slconn->stat->packetinfo.stationidlength)
{
if (slconn->stat->packetinfo.stationidlength > (sizeof (slconn->stat->packetinfo.stationid) - 1))
{
sl_log_r (slconn, 2, 0,
"[%s] %s() received station ID is too large (%u) for buffer (%zu)\n",
slconn->sladdr, __func__,
slconn->stat->packetinfo.stationidlength,
sizeof (slconn->stat->packetinfo.stationid) - 1);
break;
}
else
{
memcpy (slconn->stat->packetinfo.stationid,
slconn->recvbuffer + bytesconsumed,
slconn->stat->packetinfo.stationidlength);
slconn->stat->packetinfo.stationid[slconn->stat->packetinfo.stationidlength] = '\0';
/* Set state for payload collection */
slconn->stat->packetinfo.payloadcollected = 0;
slconn->stat->stream_state = PAYLOAD;
bytesconsumed += slconn->stat->packetinfo.stationidlength;
}
} /* Done reading station ID */
/* Read payload */
if (slconn->stat->stream_state == PAYLOAD)
{
bytesavailable = slconn->recvdatalen - bytesconsumed;
/* If payload length is known, return SLTOOLARGE if buffer is not sufficient */
if (slconn->stat->packetinfo.payloadlength > 0 &&
slconn->stat->packetinfo.payloadlength > plbuffersize)
{
/* Shift any remaining data in the buffer to the start */
if (bytesconsumed > 0 && bytesconsumed < slconn->recvdatalen)
{
memmove (slconn->recvbuffer,
slconn->recvbuffer + bytesconsumed,
slconn->recvdatalen - bytesconsumed);
}
slconn->recvdatalen -= bytesconsumed;
bytesconsumed = 0;
*packetinfo = &slconn->stat->packetinfo;
return SLTOOLARGE;
}
bytesread = receive_payload (slconn, plbuffer, plbuffersize,
slconn->recvbuffer + bytesconsumed,
bytesavailable);
if (bytesread < 0)
{
break;
}
if (bytesread > 0)
{
slconn->stat->netto_time = 0;
slconn->stat->keepalive_time = 0;
bytesconsumed += bytesread;
}
/* Payload is complete */
if (slconn->stat->packetinfo.payloadlength > 0 &&
slconn->stat->packetinfo.payloadcollected == slconn->stat->packetinfo.payloadlength)
{
/* Shift any remaining data in the buffer to the start */
if (bytesconsumed > 0 && bytesconsumed < slconn->recvdatalen)
{
memmove (slconn->recvbuffer,
slconn->recvbuffer + bytesconsumed,
slconn->recvdatalen - bytesconsumed);
}
slconn->recvdatalen -= bytesconsumed;
bytesconsumed = 0;
/* Set state for header collection if payload is complete */
slconn->stat->stream_state = HEADER;
/* V3 Keepalive INFO responses are not returned to the caller */
if (slconn->stat->query_state == KeepAliveQuery &&
(slconn->stat->packetinfo.payloadformat == SLPAYLOAD_MSEED2INFOTERM ||
slconn->stat->packetinfo.payloadformat == SLPAYLOAD_MSEED2INFO))
{
if (slconn->stat->packetinfo.payloadformat == SLPAYLOAD_MSEED2INFOTERM)
{
sl_log_r (slconn, 1, 2, "[%s] Keepalive message received\n", slconn->sladdr);
slconn->stat->query_state = NoQuery;
}
}
/* V4 Keepalive INFO responses are not returned to caller */
else if (slconn->stat->query_state == KeepAliveQuery &&
slconn->stat->packetinfo.payloadformat == SLPAYLOAD_JSON &&
slconn->stat->packetinfo.payloadsubformat == SLPAYLOAD_JSON_INFO)
{
sl_log_r (slconn, 1, 2, "[%s] Keepalive message received\n", slconn->sladdr);
slconn->stat->query_state = NoQuery;
}
/* All other payloads are returned to the caller */
else
{
/* Update streaming tracking */
if (update_stream (slconn, plbuffer) == -1)
{
sl_log_r (slconn, 2, 0, "[%s] %s(): cannot update stream tracking\n",
slconn->sladdr, __func__);
return -1;
}
*packetinfo = &slconn->stat->packetinfo;
return SLPACKET;
}
}
} /* Done reading payload */
/* If a viable amount of data exists but has not been consumed something is wrong with the stream */
if (slconn->recvdatalen > SL_MIN_PAYLOAD && bytesconsumed == 0)
{
sl_log_r (slconn, 2, 0, "[%s] %s(): cannot process received data, terminating.\n",
slconn->sladdr, __func__);
sl_log_r (slconn, 2, 0, "[%s] recvdatalen: %u, stream_state: %d, bytesconsumed: %u\n",
slconn->sladdr, slconn->recvdatalen, slconn->stat->stream_state, bytesconsumed);
break;
}
/* Shift any remaining data in the buffer to the start */
if (bytesconsumed > 0 && bytesconsumed < slconn->recvdatalen)
{
memmove (slconn->recvbuffer,
slconn->recvbuffer + bytesconsumed,
slconn->recvdatalen - bytesconsumed);
}
slconn->recvdatalen -= bytesconsumed;
bytesconsumed = 0;
/* Set termination flag to level 2 if less than viable number of bytes in buffer */
if (slconn->terminate == 1 && slconn->recvdatalen < SL_MIN_PAYLOAD)
{
slconn->terminate = 2;
}
} /* Done reading data in STREAMING state */
/* Update timing variables */
current_time = sl_nstime ();
/* Check for network idle timeout */
if (slconn->stat->conn_state == STREAMING &&
slconn->netto && slconn->stat->netto_time &&
slconn->stat->netto_time < current_time)
{
sl_log_r (slconn, 1, 0, "[%s] network timeout (%ds), reconnecting in %ds\n",
slconn->sladdr, slconn->netto, slconn->netdly);
sl_disconnect (slconn);
slconn->link = -1;
slconn->stat->conn_state = DOWN;
slconn->stat->netto_time = 0;
slconn->stat->netdly_time = 0;
}
/* Check if keepalive packet needs to be sent */
if (slconn->stat->conn_state == STREAMING &&
slconn->stat->query_state == NoQuery &&
slconn->keepalive && slconn->stat->keepalive_time &&
slconn->stat->keepalive_time < current_time)
{
sl_log_r (slconn, 1, 2, "[%s] Sending keepalive message\n", slconn->sladdr);
if (sl_send_info (slconn, "ID", 3) == -1)
{
break;
}
slconn->stat->query_state = KeepAliveQuery;
slconn->stat->keepalive_time = 0;
}
/* Network timeout */
if (slconn->netto && slconn->stat->netto_time == 0)
{
slconn->stat->netto_time = current_time + SL_EPOCH2SLTIME (slconn->netto);
}
/* Network connection delay */
if (slconn->netdly && slconn->stat->netdly_time == 0)
{
slconn->stat->netdly_time = current_time + SL_EPOCH2SLTIME (slconn->netdly);
}
/* Keepalive/heartbeat interval */
if (slconn->keepalive && slconn->stat->keepalive_time == 0)
{
slconn->stat->keepalive_time = current_time + SL_EPOCH2SLTIME (slconn->keepalive);
}
/* Return if not waiting for data and no data in internal buffer */
if (slconn->noblock && slconn->recvdatalen == 0)
{
*packetinfo = NULL;
return SLNOPACKET;
}
/* Termination in any connection state but UP is immediate */
if (slconn->terminate && slconn->stat->conn_state != UP)
{
break;
}
} /* End of primary loop */
/* Terminating */
sl_disconnect (slconn);
slconn->link = -1;
*packetinfo = NULL;
return SLTERMINATE;
} /* End of sl_collect() */
/***************************************************************************
* receive_header:
*
* Receive packet header.
*
* Returns:
* bytes : Size of header read
* -1 : on error
***************************************************************************/
static int
receive_header (SLCD *slconn, uint8_t *buffer, uint32_t bytesavailable)
{
uint32_t bytesread = 0;
char sequence[7] = {0};
char *tail = NULL;
if (!slconn)
return -1;
/* Zero the destination packet info structure */
memset (&slconn->stat->packetinfo, 0, sizeof (SLpacketinfo));
if (slconn->protocol & SLPROTO3X && bytesavailable >= SLHEADSIZE_V3)
{
/* Parse v3 INFO header */
if (memcmp (buffer, INFOSIGNATURE, 6) == 0)
{
slconn->stat->packetinfo.seqnum = SL_UNSETSEQUENCE;
slconn->stat->packetinfo.payloadlength = 0;
slconn->stat->packetinfo.payloadformat = (buffer[SLHEADSIZE_V3 - 1] == '*') ? SLPAYLOAD_MSEED2INFO : SLPAYLOAD_MSEED2INFOTERM;
}
/* Parse v3 data header */
else if (memcmp (buffer, SIGNATURE_V3, 2) == 0)
{
memcpy (sequence, buffer + 2, 6);
slconn->stat->packetinfo.seqnum = strtoul (sequence, &tail, 16);
if (*tail)
{
sl_log_r (slconn, 2, 0, "[%s] %s() cannot parse sequence number from v3 header: %8.8s\n",
slconn->sladdr, __func__, buffer + 2);
return -1;
}
slconn->stat->packetinfo.payloadlength = 0;
slconn->stat->packetinfo.payloadformat = SLPAYLOAD_UNKNOWN;
}
else
{
sl_log_r (slconn, 2, 0, "[%s] %s(): unexpected V3 header signature found: %2.2s)\n",
slconn->sladdr, __func__, buffer);
return -1;
}
bytesread = SLHEADSIZE_V3;
}
else if (slconn->protocol & SLPROTO40 && bytesavailable >= SLHEADSIZE_V4)
{
/* Parse v4 header */
if (memcmp (buffer, SIGNATURE_V4, 2) == 0)
{
slconn->stat->packetinfo.payloadformat = buffer[2];
slconn->stat->packetinfo.payloadsubformat = buffer[3];
memcpy (&slconn->stat->packetinfo.payloadlength, buffer + 4, 4);
memcpy (&slconn->stat->packetinfo.seqnum, buffer + 8, 8);
memcpy (&slconn->stat->packetinfo.stationidlength, buffer + 16, 1);
if (!sl_littleendianhost ())
{
sl_gswap8 (&slconn->stat->packetinfo.seqnum);
sl_gswap4 (&slconn->stat->packetinfo.payloadlength);
}
}
else
{
sl_log_r (slconn, 2, 0, "[%s] %s(): unexpected V4 header signature found: %2.2s)\n",
slconn->sladdr, __func__, buffer);
return -1;
}
bytesread = SLHEADSIZE_V4;
}
else
{
sl_log_r (slconn, 2, 0, "[%s] %s(): unexpected header signature found (instead: %2.2s)\n",
slconn->sladdr, __func__, buffer);
return -1;
}
return bytesread;
} /* End of receive_header() */
/***************************************************************************
* receive_payload:
*
* Copy payload data to supplied buffer.
*
* The supplied buffer must be large enough for payload detection,
* defined as SL_MIN_PAYLOAD bytes.
*
* Returns
* bytes : Number of bytes consumed on success
* -1 : on error
***************************************************************************/
int64_t
receive_payload (SLCD *slconn, char *plbuffer, uint32_t plbuffersize,
uint8_t *buffer, uint32_t bytesavailable)
{
SLpacketinfo *packetinfo = NULL;
uint32_t bytestoconsume = 0;
int64_t detectedlength;
char payloadformat = SLPAYLOAD_UNKNOWN;
if (!slconn || !plbuffer)
return -1;
packetinfo = &slconn->stat->packetinfo;
/* Return for more data if the minimum for detection is not available */
if (packetinfo->payloadlength == 0 && bytesavailable < SL_MIN_PAYLOAD)
{
return 0;
}
/* If payload length is unknown, consume up to 128 bytes */
if (packetinfo->payloadlength == 0)
{
bytestoconsume = (bytesavailable < 128) ? bytesavailable : 128;
}
/* If remaining payload is smaller than available, consume remaining */
else if ((packetinfo->payloadlength - packetinfo->payloadcollected) < bytesavailable)
{
bytestoconsume = packetinfo->payloadlength - packetinfo->payloadcollected;
}
/* Otherwise, all available data is payload */
else
{
bytestoconsume = bytesavailable;
}
if (bytestoconsume > plbuffersize - packetinfo->payloadcollected)
{
sl_log_r (slconn, 2, 0, "[%s] %s(): provided buffer size (%u) is insufficient for payload (%u)\n",
slconn->sladdr, __func__, plbuffersize,
(packetinfo->payloadlength == 0) ? bytestoconsume : packetinfo->payloadlength);
return -1;
}
/* Copy payload data from internal buffer to payload buffer */
memcpy (plbuffer + packetinfo->payloadcollected, buffer, bytestoconsume);
packetinfo->payloadcollected += bytestoconsume;
/* If payload length is not yet known for V3, try to detect from payload */
if (slconn->protocol & SLPROTO3X && packetinfo->payloadlength == 0)
{
detectedlength = detect (plbuffer, packetinfo->payloadcollected, &payloadformat);
/* Return error if no recognized payload detected */
if (detectedlength < 0)
{
sl_log_r (slconn, 2, 0,
"[%s] %s(): non-miniSEED packet received for v3 protocol! Terminating.\n",
slconn->sladdr, __func__);
return -1;
}
/* Update packet info if length detected */
else if (detectedlength > 0)
{
if (packetinfo->payloadformat == SLPAYLOAD_UNKNOWN)
{
packetinfo->payloadformat = payloadformat;
}
packetinfo->payloadlength = detectedlength;
}
}
return bytestoconsume;
} /* End of receive_payload() */
/***************************************************************************
* update_stream:
*
* Update the appropriate stream list entries. Length of the payload
* must be at least enough to determine stream details.
*
* The slconn->stat->packetinfo.stationid value is also populated from
* the payload if not already set.
*
* Returns 0 if successfully updated and -1 if not found or error.
***************************************************************************/
static int
update_stream (SLCD *slconn, const char *payload)
{
SLpacketinfo *packetinfo = NULL;
SLstream *curstream;
int updates = 0;
char timestamp[32] = {0};
char sourceid[64] = {0};
char *cp;
size_t count;
if (!slconn || !payload)
return -1;
packetinfo = &slconn->stat->packetinfo;
/* No updates for info and error packets */
if (packetinfo->payloadformat == SLPAYLOAD_MSEED2INFO ||
packetinfo->payloadformat == SLPAYLOAD_MSEED2INFOTERM ||
(packetinfo->payloadformat == SLPAYLOAD_JSON &&
(packetinfo->payloadsubformat == SLPAYLOAD_JSON_INFO ||
packetinfo->payloadsubformat == SLPAYLOAD_JSON_ERROR)))
{
return 0;
}
/* Extract start time stamp and source ID (if needed) from payload if miniSEED */
if (packetinfo->payloadformat == SLPAYLOAD_MSEED2 ||
packetinfo->payloadformat == SLPAYLOAD_MSEED3)
{
if (sl_payload_info (slconn->log, packetinfo,
payload, packetinfo->payloadlength,
(packetinfo->stationidlength == 0) ? sourceid : NULL, sizeof (sourceid),
timestamp, sizeof (timestamp),
NULL, NULL) == -1)
{
sl_log_r (slconn, 2, 0, "[%s] %s(): cannot extract payload info for miniSEED\n",
slconn->sladdr, __func__);
return -1;
}
/* Set station ID if it was not included in SeedLink header (e.g. v3 protocol) */
if (packetinfo->stationidlength == 0)
{
/* Extract NET_STA from FDSN Source Identifier returned by sl_payload_info() */
if (strlen (sourceid) >= 8 && strncmp (sourceid, "FDSN:", 5) == 0)
{
/* Copy from ':' to 2nd '_' from "FDSN:NET_STA_LOC_B_S_SS" */
if ((cp = strchr (sourceid + 5, '_')))
{
if ((cp = strchr (cp + 1, '_')))
{
count = (cp - sourceid) - 5;
if (count >= sizeof (packetinfo->stationid))
{
sl_log_r (slconn, 2, 0, "[%s] %s(): extracted NET_STA ID from miniSEED is too large (%zu)\n",
slconn->sladdr, __func__, count);
return -1;
}
memcpy (packetinfo->stationid, sourceid + 5, sizeof (packetinfo->stationid));
packetinfo->stationid[count] = '\0';
packetinfo->stationidlength = count;
}
}
}
}
}
curstream = slconn->streams;
/* For all-station mode */
if (curstream != NULL &&
strcmp (curstream->stationid, "*") == 0)
{
curstream->seqnum = packetinfo->seqnum;
strcpy (curstream->timestamp, timestamp);
return 0;
}
/* For multi-station mode, search the stream list and update all matching entries */
while (curstream != NULL)
{
/* Use glob matching to match wildcarded station ID codes */
if (sl_globmatch (packetinfo->stationid, curstream->stationid))
{
curstream->seqnum = packetinfo->seqnum;
strcpy (curstream->timestamp, timestamp);
updates++;
}
curstream = curstream->next;
}
/* If no updates then no match was found */
if (updates == 0)
sl_log_r (slconn, 2, 0, "[%s] unexpected data received: %s\n",
slconn->sladdr, packetinfo->stationid);
return (updates == 0) ? -1 : 0;
} /* End of update_stream() */
/**********************************************************************/ /**
* @brief Initialize a new ::SLCD
*
* Allocate a new ::SLCD and set default values.
*
* The \a clientname must be specified and should be a string
* describing the name of the client program. The \a clientversion is
* optional and should be the version of the client program. These
* values are passed directly to sl_set_clientname().
*
* @param[in] clientname Name of the client program
* @param[in] clientversion Version of the client program
*
* @returns An initialized ::SLCD on success, NULL on error.
***************************************************************************/
SLCD *
sl_initslcd (const char *clientname, const char *clientversion)
{
SLCD *slconn;
slconn = (SLCD *)malloc (sizeof (SLCD));
if (slconn == NULL)
{
sl_log_r (NULL, 2, 0, "%s(): error allocating memory\n", __func__);
return NULL;
}
memset (slconn, 0, sizeof (SLCD));
/* Set defaults */
slconn->sladdr = NULL;
slconn->slhost = NULL;
slconn->slport = NULL;
slconn->clientname = NULL;
slconn->clientversion = NULL;
slconn->start_time = NULL;
slconn->end_time = NULL;
slconn->keepalive = 0;
slconn->iotimeout = 60;
slconn->netto = 600;
slconn->netdly = 30;
slconn->auth_value = NULL;
slconn->auth_finish = NULL;
slconn->auth_data = NULL;
slconn->streams = NULL;
slconn->info = NULL;
slconn->noblock = 0;
slconn->dialup = 0;
slconn->batchmode = 0;
slconn->lastpkttime = 1;
slconn->terminate = 0;
slconn->resume = 1;
slconn->multistation = 0;
slconn->link = -1;
slconn->protocol = UNSET_PROTO;
slconn->server_protocols = 0;
slconn->capabilities = NULL;
slconn->caparray = NULL;
slconn->tls = 0;
slconn->tlsctx = NULL;
/* Allocate the associated persistent state struct */
if ((slconn->stat = (SLstat *)malloc (sizeof (SLstat))) == NULL)
{
sl_log_r (NULL, 2, 0, "%s(): error allocating memory\n", __func__);
free (slconn);
return NULL;
}
memset (slconn->stat, 0, sizeof (SLstat));
slconn->stat->packetinfo.seqnum = SL_UNSETSEQUENCE;
slconn->stat->packetinfo.payloadlength = 0;
slconn->stat->packetinfo.payloadcollected = 0;
slconn->stat->packetinfo.payloadformat = SLPAYLOAD_UNKNOWN;
slconn->stat->netto_time = 0;
slconn->stat->netdly_time = 0;
slconn->stat->keepalive_time = 0;
slconn->stat->conn_state = DOWN;
slconn->stat->stream_state = HEADER;
slconn->stat->query_state = NoQuery;
slconn->log = NULL;
slconn->recvdatalen = 0;
/* Store copies of client name and version */
if (clientname && sl_set_clientname (slconn, clientname, clientversion))
{
sl_freeslcd (slconn);
return NULL;
}
return slconn;
} /* End of sl_newslcd() */
/**********************************************************************/ /**
* @brief Free all memory associated with a ::SLCD
*
* Free all memory associated with a SLCD struct including the
* associated stream list and persistent connection state.
*
* @param[in] slconn SeedLink connection description to free
***************************************************************************/
void
sl_freeslcd (SLCD *slconn)
{
SLstream *curstream;
SLstream *nextstream;
curstream = slconn->streams;
/* Traverse the stream list and free memory */
while (curstream != NULL)
{
nextstream = curstream->next;
if (curstream->selectors != NULL)
free (curstream->selectors);
free (curstream);
curstream = nextstream;
}
free (slconn->sladdr);
free (slconn->slhost);
free (slconn->slport);
free (slconn->start_time);
free (slconn->end_time);
free (slconn->capabilities);
free (slconn->caparray);
free (slconn->clientname);
free (slconn->clientversion);
free (slconn->stat);
free (slconn->log);
free (slconn);
} /* End of sl_freeslcd() */
/**********************************************************************/ /**
* @brief Set client name and version reported to server (v4 only)
*
* Set the program name and, optionally, version that will be send to
* the server in protocol v4 version. These values will be combined
* into a value with the pattern:
* NAME[/VERSION]
*
* @param[in] slconn SeedLink connection description
* @param[in] name Name of the client program
* @param[in] version Version of the client program
*
* @retval 0 : success
* @retval -1 : error
***************************************************************************/
int
sl_set_clientname (SLCD *slconn, const char *name, const char *version)
{
if (!slconn || !name)
return -1;
free (slconn->clientname);
free (slconn->clientversion);
slconn->clientname = strdup (name);
if (slconn->clientname == NULL)
{
sl_log_r (NULL, 2, 0, "%s(): error allocating memory\n", __func__);
return -1;
}
if (version)
{
slconn->clientversion = strdup (version);
if (slconn->clientversion == NULL)
{
sl_log_r (NULL, 2, 0, "%s(): error allocating memory\n", __func__);
return -1;
}
}
return 0;
} /* End of sl_set_clientname() */
/**********************************************************************/ /**
* @brief Set SeedLink server address (and port)
*
* Set the address (and port) of the SeedLink server to connect to. The
* \p server_address string should be in the following format:
*
* \c HOST:PORT
*
* where \c HOST and \c PORT are both optional. If \c HOST is not
* specified the value of \a SL_DEFAULT_HOST (usually "localhost") will
* be used. If \c PORT is not specified the value of \a SL_DEFAULT_PORT
* (usually "18000") will be used.
*
* The \c HOST value can be an IPv4 or IPv6 address, or a hostname. The
* \c PORT value must be a valid port number.
*
* The following variations are supported:
* ```
* 192.168.0.1
* :18000
* 192.168.0.1:18000
* seedlink.datacenter.org:18500
* 2607:f8b0:400a:805::200e
* [2607:f8b0:400a:805::200e]:18000
* ```
*
* This routine will also set the \a tls flag if the port is the default
* for a secure connection, aka \a SL_SECURE_PORT.
*
* @param slconn SeedLink connection description
* @param server_address Server address in \c HOST:PORT format
*
* @retval 0 : success
* @retval -1 : error