Repository navigation
Expand file tree
/
Copy pathntripclient.c
More file actions
2097 lines (1981 loc) · 71.9 KB
/
Copy pathntripclient.c
File metadata and controls
2097 lines (1981 loc) · 71.9 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
/*
NTRIP client for POSIX.
$Id: ntripclient.c,v 1.51 2009/09/11 09:49:19 stoecker Exp $
Copyright (C) 2003-2008 by Dirk Stöcker <soft@dstoecker.de>
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 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
or read http://www.gnu.org/licenses/gpl.txt
*/
#include <ctype.h>
#include <getopt.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <poll.h>
#include <curl/curl.h>
#include "serial.c"
#define STDIN_FD (0) // stdin file descriptor
#define SLEEP_MS(ms) usleep(ms * 1000)
#define HTTP_EOL_STR "\r\n"
#define HTTP_EOL_LEN strlen(HTTP_EOL_STR)
#ifdef WINDOWSVERSION
#include <winsock.h>
typedef SOCKET sockettype;
typedef u_long in_addr_t;
typedef size_t socklen_t;
void myperror(char *s)
{
fprintf(stderr, "%s: %d\n", s, WSAGetLastError());
}
#else
typedef int sockettype;
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define closesocket(sock) close(sock)
/* Backstop only (OS-556): the data watchdog below is the primary stall detector. */
#define ALARMTIME (30)
#define myperror perror
#endif
/* Stall detection / reconnect tuning (OS-556) */
#define RECV_POLL_TIMEOUT_MS 1000 /* max time a single recv waits for data */
#define DATA_WATCHDOG_SEC 10 /* no RTCM for this long -> reconnect */
#define HEADER_TIMEOUT_SEC 10 /* max wait for the HTTP response header */
#define CONNECT_TIMEOUT_SEC 10
#define RECONNECT_BACKOFF_MIN 1 /* seconds, doubles per failed session, capped */
#define RECONNECT_BACKOFF_MAX 8
#define RECV_NO_DATA (-2) /* curl_recv_(): nothing within RECV_POLL_TIMEOUT_MS */
/* Monotonic seconds for timeouts: immune to wall-clock steps when NTP/GPS sets the time after boot. */
static time_t mono_sec(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec;
}
#ifdef NTRIPCLIENT_DEBUG_LOG
static FILE *flogfile = NULL;
#endif
/* UTC-timestamped line to stderr (and the debug log in the debug build). */
static void log_msg(const char *fmt, ...)
{
char ts[32];
time_t now = time(0);
struct tm tmv;
gmtime_r(&now, &tmv);
strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%SZ", &tmv);
va_list ap;
va_start(ap, fmt);
fprintf(stderr, "%s ntripclient: ", ts);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
va_end(ap);
#ifdef NTRIPCLIENT_DEBUG_LOG
if(flogfile)
{
va_start(ap, fmt);
fprintf(flogfile, "%s ", ts);
vfprintf(flogfile, fmt, ap);
fprintf(flogfile, "\n");
fflush(flogfile);
va_end(ap);
}
#endif
}
#ifndef COMPILEDATE
#define COMPILEDATE " built " __DATE__
#endif
/* The string, which is send as agent in HTTP request */
#define AGENTSTRING "NTRIP NtripClientPOSIX"
#define TIME_RESOLUTION 125
#define MAXDATASIZE 1000 /* max number of bytes we can get at once */
/* CVS revision and version */
static char revisionstr[] = "$Revision: 1.7.0 $";
static char datestr[] = "$Date: 2026/10/21 00:00:00 $";
enum MODE { HTTP = 1, RTSP = 2, NTRIP1 = 3, AUTO = 4, UDP = 5, HTTPS = 6, END };
typedef struct
{
bool valid;
bool received_ok;
bool content_type_gnss_data;
bool ntrip_v2;
bool chunky_mode;
} HttpHeader;
struct Args
{
const char *server;
const char *port;
const char *user;
const char *proxyhost;
const char *proxyport;
const char *password;
const char *nmea;
const char *data;
int bitrate;
int mode;
int udpport;
int initudp;
enum SerialBaud baud;
enum SerialDatabits databits;
enum SerialStopbits stopbits;
enum SerialParity parity;
enum SerialProtocol protocol;
const char *serdevice;
const char *serlogfile;
};
/* option parsing */
#ifdef NO_LONG_OPTS
#define LONG_OPT(a)
#else
#define LONG_OPT(a) a
static struct option opts[] = {
{ "bitrate", no_argument, 0, 'b'},
{ "data", required_argument, 0, 'd'}, /* compatibility */
{ "mountpoint", required_argument, 0, 'm'},
{ "initudp", no_argument, 0, 'I'},
{ "udpport", required_argument, 0, 'P'},
{ "server", required_argument, 0, 's'},
{ "password", required_argument, 0, 'p'},
{ "port", required_argument, 0, 'r'},
{ "proxyport", required_argument, 0, 'R'},
{ "proxyhost", required_argument, 0, 'S'},
{ "user", required_argument, 0, 'u'},
{ "nmea", required_argument, 0, 'n'},
{ "mode", required_argument, 0, 'M'},
{ "serdevice", required_argument, 0, 'D'},
{ "baud", required_argument, 0, 'B'},
{ "stopbits", required_argument, 0, 'T'},
{ "protocol", required_argument, 0, 'C'},
{ "parity", required_argument, 0, 'Y'},
{ "databits", required_argument, 0, 'A'},
{ "serlogfile", required_argument, 0, 'l'},
{ "help", no_argument, 0, 'h'},
{0,0,0,0}};
#endif
#define ARGOPT "-d:m:bhp:r:s:u:n:S:R:M:IP:D:B:T:C:Y:A:l:"
int stop = 0;
#ifndef WINDOWSVERSION
int sigstop = 0;
#ifdef __GNUC__
static __attribute__ ((noreturn)) void sighandler_alarm(
int sig __attribute__((__unused__)))
#else /* __GNUC__ */
static void sighandler_alarm(int sig)
#endif /* __GNUC__ */
{
/* Only async-signal-safe calls here: fixed message via write(2), then _exit(). */
static const char msg_alarm[] = "ntripclient: ERROR: backstop alarm, no activity, exiting\n";
static const char msg_break[] = "ntripclient: ERROR: user break, exiting\n";
ssize_t r = sigstop ? write(2, msg_break, sizeof(msg_break) - 1) : write(2, msg_alarm, sizeof(msg_alarm) - 1);
(void)r;
_exit(1);
}
#ifdef __GNUC__
static void sighandler_int(int sig __attribute__((__unused__)))
#else /* __GNUC__ */
static void sighandler_alarm(int sig)
#endif /* __GNUC__ */
{
sigstop = 1;
alarm(2);
stop = 1;
}
#endif /* WINDOWSVERSION */
static const char *encodeurl(const char *req)
{
char *h = "0123456789abcdef";
static char buf[128];
char *urlenc = buf;
char *bufend = buf + sizeof(buf) - 3;
while(*req && urlenc < bufend)
{
if(isalnum(*req)
|| *req == '-' || *req == '_' || *req == '.')
*urlenc++ = *req++;
else
{
*urlenc++ = '%';
*urlenc++ = h[*req >> 4];
*urlenc++ = h[*req & 0x0f];
req++;
}
}
*urlenc = 0;
return buf;
}
static const char *geturl(const char *url, struct Args *args)
{
static char buf[1000];
static char *Buffer = buf;
static char *Bufend = buf+sizeof(buf);
char *h = "0123456789abcdef";
if(strncmp("ntrip:", url, 6))
return "URL must start with 'ntrip:'.";
url += 6; /* skip ntrip: */
if(*url != '@' && *url != '/')
{
/* scan for mountpoint */
args->data = Buffer;
if(*url != '?')
{
while(*url && *url != '@' && *url != ';' && *url != '/' && Buffer != Bufend)
*(Buffer++) = *(url++);
}
else
{
while(*url && *url != '@' && *url != '/' && Buffer != Bufend)
{
if(isalnum(*url) || *url == '-' || *url == '_' || *url == '.')
*Buffer++ = *url++;
else
{
*Buffer++ = '%';
*Buffer++ = h[*url >> 4];
*Buffer++ = h[*url & 0x0f];
url++;
}
}
}
if(Buffer == args->data)
return "Mountpoint required.";
else if(Buffer >= Bufend-1)
return "Parsing buffer too short.";
*(Buffer++) = 0;
}
if(*url == '/') /* username and password */
{
++url;
args->user = Buffer;
while(*url && *url != '@' && *url != ';' && *url != ':' && Buffer != Bufend)
*(Buffer++) = *(url++);
if(Buffer == args->user)
return "Username cannot be empty.";
else if(Buffer >= Bufend-1)
return "Parsing buffer too short.";
*(Buffer++) = 0;
if(*url == ':') ++url;
args->password = Buffer;
while(*url && *url != '@' && *url != ';' && Buffer != Bufend)
*(Buffer++) = *(url++);
if(Buffer == args->password)
return "Password cannot be empty.";
else if(Buffer >= Bufend-1)
return "Parsing buffer too short.";
*(Buffer++) = 0;
}
if(*url == '@') /* server */
{
++url;
if(*url != '@' && *url != ':')
{
args->server = Buffer;
while(*url && *url != '@' && *url != ':' && *url != ';' && Buffer != Bufend)
*(Buffer++) = *(url++);
if(Buffer == args->server)
return "Servername cannot be empty.";
else if(Buffer >= Bufend-1)
return "Parsing buffer too short.";
*(Buffer++) = 0;
}
if(*url == ':')
{
++url;
args->port = Buffer;
while(*url && *url != '@' && *url != ';' && Buffer != Bufend)
*(Buffer++) = *(url++);
if(Buffer == args->port)
return "Port cannot be empty.";
else if(Buffer >= Bufend-1)
return "Parsing buffer too short.";
*(Buffer++) = 0;
}
if(*url == '@') /* proxy */
{
++url;
args->proxyhost = Buffer;
while(*url && *url != ':' && *url != ';' && Buffer != Bufend)
*(Buffer++) = *(url++);
if(Buffer == args->proxyhost)
return "Proxy servername cannot be empty.";
else if(Buffer >= Bufend-1)
return "Parsing buffer too short.";
*(Buffer++) = 0;
if(*url == ':')
{
++url;
args->proxyport = Buffer;
while(*url && *url != ';' && Buffer != Bufend)
*(Buffer++) = *(url++);
if(Buffer == args->proxyport)
return "Proxy port cannot be empty.";
else if(Buffer >= Bufend-1)
return "Parsing buffer too short.";
*(Buffer++) = 0;
}
}
}
if(*url == ';') /* NMEA */
{
args->nmea = ++url;
while(*url)
++url;
}
return *url ? "Garbage at end of server string." : 0;
}
static int getargs(int argc, char **argv, struct Args *args)
{
int res = 1;
int getoptr;
char *a;
int i = 0, help = 0;
args->server = "www.euref-ip.net";
args->port = "2101";
args->user = "";
args->password = "";
args->nmea = 0;
args->data = 0;
args->bitrate = 0;
args->proxyhost = 0;
args->proxyport = "2101";
args->mode = AUTO;
args->initudp = 0;
args->udpport = 0;
args->protocol = SPAPROTOCOL_NONE;
args->parity = SPAPARITY_NONE;
args->stopbits = SPASTOPBITS_1;
args->databits = SPADATABITS_8;
args->baud = SPABAUD_9600;
args->serdevice = 0;
args->serlogfile = 0;
help = 0;
do
{
#ifdef NO_LONG_OPTS
switch((getoptr = getopt(argc, argv, ARGOPT)))
#else
switch((getoptr = getopt_long(argc, argv, ARGOPT, opts, 0)))
#endif
{
case 's': args->server = optarg; break;
case 'u': args->user = optarg; break;
case 'p': args->password = optarg; break;
case 'd': /* legacy option, may get removed in future */
fprintf(stderr, "Option -d or --data is deprecated. Use -m instead.\n");
case 'm':
if(optarg && *optarg == '?')
args->data = encodeurl(optarg);
else
args->data = optarg;
break;
case 'B':
{
int i = strtol(optarg, 0, 10);
switch(i)
{
case 50: args->baud = SPABAUD_50; break;
case 110: args->baud = SPABAUD_110; break;
case 300: args->baud = SPABAUD_300; break;
case 600: args->baud = SPABAUD_600; break;
case 1200: args->baud = SPABAUD_1200; break;
case 2400: args->baud = SPABAUD_2400; break;
case 4800: args->baud = SPABAUD_4800; break;
case 9600: args->baud = SPABAUD_9600; break;
case 19200: args->baud = SPABAUD_19200; break;
case 38400: args->baud = SPABAUD_38400; break;
case 57600: args->baud = SPABAUD_57600; break;
case 115200: args->baud = SPABAUD_115200; break;
default:
fprintf(stderr, "Baudrate '%s' unknown\n", optarg);
res = 0;
break;
}
}
break;
case 'T':
if(!strcmp(optarg, "1")) args->stopbits = SPASTOPBITS_1;
else if(!strcmp(optarg, "2")) args->stopbits = SPASTOPBITS_2;
else
{
fprintf(stderr, "Stopbits '%s' unknown\n", optarg);
res = 0;
}
break;
case 'A':
if(!strcmp(optarg, "5")) args->databits = SPADATABITS_5;
else if(!strcmp(optarg, "6")) args->databits = SPADATABITS_6;
else if(!strcmp(optarg, "7")) args->databits = SPADATABITS_7;
else if(!strcmp(optarg, "8")) args->databits = SPADATABITS_8;
else
{
fprintf(stderr, "Databits '%s' unknown\n", optarg);
res = 0;
}
break;
case 'C':
{
int i = 0;
args->protocol = SerialGetProtocol(optarg, &i);
if(!i)
{
fprintf(stderr, "Protocol '%s' unknown\n", optarg);
res = 0;
}
}
break;
case 'Y':
{
int i = 0;
args->parity = SerialGetParity(optarg, &i);
if(!i)
{
fprintf(stderr, "Parity '%s' unknown\n", optarg);
res = 0;
}
}
break;
case 'D': args->serdevice = optarg; break;
case 'l': args->serlogfile = optarg; break;
case 'I': args->initudp = 1; break;
case 'P': args->udpport = strtol(optarg, 0, 10); break;
case 'n': args->nmea = optarg; break;
case 'b': args->bitrate = 1; break;
case 'h': help=1; break;
case 'r': args->port = optarg; break;
case 'S': args->proxyhost = optarg; break;
case 'R': args->proxyport = optarg; break;
case 'M':
args->mode = 0;
if (!strcmp(optarg,"n") || !strcmp(optarg,"ntrip1"))
args->mode = NTRIP1;
else if(!strcmp(optarg,"h") || !strcmp(optarg,"http"))
args->mode = HTTP;
else if(!strcmp(optarg,"H") || !strcmp(optarg,"https"))
args->mode = HTTPS;
else if(!strcmp(optarg,"r") || !strcmp(optarg,"rtsp"))
args->mode = RTSP;
else if(!strcmp(optarg,"u") || !strcmp(optarg,"udp"))
args->mode = UDP;
else if(!strcmp(optarg,"a") || !strcmp(optarg,"auto"))
args->mode = AUTO;
else args->mode = atoi(optarg);
if((args->mode == 0) || (args->mode >= END))
{
fprintf(stderr, "Mode %s unknown\n", optarg);
res = 0;
}
break;
case 1:
{
const char *err;
if((err = geturl(optarg, args)))
{
fprintf(stderr, "%s\n\n", err);
res = 0;
}
}
break;
case -1: break;
}
} while(getoptr != -1 && res);
// Use HTTPS/TLS if mode is auto and port is 2102
if ((args->mode == AUTO) && (strcmp(args->port, "2102") == 0))
{
args->mode = HTTPS;
}
for(a = revisionstr+11; *a && *a != ' '; ++a)
revisionstr[i++] = *a;
revisionstr[i] = 0;
datestr[0] = datestr[7];
datestr[1] = datestr[8];
datestr[2] = datestr[9];
datestr[3] = datestr[10];
datestr[5] = datestr[12];
datestr[6] = datestr[13];
datestr[8] = datestr[15];
datestr[9] = datestr[16];
datestr[4] = datestr[7] = '-';
datestr[10] = 0;
if(!res || help)
{
fprintf(stderr, "Version %s (%s) GPL" COMPILEDATE "\nUsage:\n%s -s server -u user ...\n"
" -m " LONG_OPT("--mountpoint ") "the requested data set or sourcetable filtering criteria\n"
" -s " LONG_OPT("--server ") "the server name or address\n"
" -p " LONG_OPT("--password ") "the login password\n"
" -r " LONG_OPT("--port ") "the server port number (default 2101)\n"
" -u " LONG_OPT("--user ") "the user name\n"
" -M " LONG_OPT("--mode ") "mode for data request\n"
" Valid modes are:\n"
" 1, h, http NTRIP Version 2.0 Caster in TCP/IP mode\n"
" 2, r, rtsp NTRIP Version 2.0 Caster in RTSP/RTP mode\n"
" 3, n, ntrip1 NTRIP Version 1.0 Caster\n"
" 4, a, auto automatic detection (default)\n"
" 5, u, udp NTRIP Version 2.0 Caster in UDP mode\n"
" 6, H, https NTRIP Version 2.0 Caster in TCP/IP with TLS mode\n"
"or using an URL:\n%s ntrip:mountpoint[/user[:password]][@[server][:port][@proxyhost[:proxyport]]][;nmea]\n"
"\nExpert options:\n"
" -n " LONG_OPT("--nmea ") "NMEA string for sending to server\n"
" -b " LONG_OPT("--bitrate ") "output bitrate\n"
" -I " LONG_OPT("--initudp ") "send initial UDP packet for firewall handling\n"
" -P " LONG_OPT("--udpport ") "set the local UDP port\n"
" -S " LONG_OPT("--proxyhost ") "proxy name or address\n"
" -R " LONG_OPT("--proxyport ") "proxy port, optional (default 2101)\n"
"\nSerial input/output:\n"
" -D " LONG_OPT("--serdevice ") "serial device for output\n"
" -B " LONG_OPT("--baud ") "baudrate for serial device\n"
" -T " LONG_OPT("--stopbits ") "stopbits for serial device\n"
" -C " LONG_OPT("--protocol ") "protocol for serial device\n"
" -Y " LONG_OPT("--parity ") "parity for serial device\n"
" -A " LONG_OPT("--databits ") "databits for serial device\n"
" -l " LONG_OPT("--serlogfile ") "logfile for serial data\n"
, revisionstr, datestr, argv[0], argv[0]);
exit(1);
}
return res;
}
static const char encodingTable [64] = {
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f',
'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/'
};
/* does not buffer overrun, but breaks directly after an error */
/* returns the number of required bytes */
static int encode(char *buf, int size, const char *user, const char *pwd)
{
unsigned char inbuf[3];
char *out = buf;
int i, sep = 0, fill = 0, bytes = 0;
while(*user || *pwd)
{
i = 0;
while(i < 3 && *user) inbuf[i++] = *(user++);
if(i < 3 && !sep) {inbuf[i++] = ':'; ++sep; }
while(i < 3 && *pwd) inbuf[i++] = *(pwd++);
while(i < 3) {inbuf[i++] = 0; ++fill; }
if(out-buf < size-1)
*(out++) = encodingTable[(inbuf [0] & 0xFC) >> 2];
if(out-buf < size-1)
*(out++) = encodingTable[((inbuf [0] & 0x03) << 4)
| ((inbuf [1] & 0xF0) >> 4)];
if(out-buf < size-1)
{
if(fill == 2)
*(out++) = '=';
else
*(out++) = encodingTable[((inbuf [1] & 0x0F) << 2)
| ((inbuf [2] & 0xC0) >> 6)];
}
if(out-buf < size-1)
{
if(fill >= 1)
*(out++) = '=';
else
*(out++) = encodingTable[inbuf [2] & 0x3F];
}
bytes += 4;
}
if(out-buf < size)
*out = 0;
return bytes;
}
static ssize_t curl_send_(CURL *curl, const void *buf, size_t len, int flags)
{
(void)flags; // not used
size_t bytes_sent = 0;
CURLcode result = curl_easy_send(curl, buf, len, &bytes_sent);
return (result == CURLE_OK) ? (ssize_t)bytes_sent : -1;
}
// Bounded receive (OS-556). Returns bytes received, 0 on close, -1 on error, or
// RECV_NO_DATA if nothing arrived within RECV_POLL_TIMEOUT_MS so the caller keeps
// control. Previously this spun on CURLE_AGAIN forever.
static ssize_t curl_recv_(CURL *curl, void *buf, size_t len, int flags)
{
(void)flags; // not used
size_t bytes_recv = 0;
CURLcode result = curl_easy_recv(curl, buf, len, &bytes_recv);
if (result == CURLE_OK)
return (ssize_t)bytes_recv;
if (result != CURLE_AGAIN)
return -1;
curl_socket_t sockfd = CURL_SOCKET_BAD;
if (curl_easy_getinfo(curl, CURLINFO_ACTIVESOCKET, &sockfd) != CURLE_OK || sockfd == CURL_SOCKET_BAD)
return -1;
struct pollfd pfd = { sockfd, POLLIN, 0 };
int rc = poll(&pfd, 1, RECV_POLL_TIMEOUT_MS);
if (rc < 0)
return (errno == EINTR) ? RECV_NO_DATA : -1;
if (rc == 0)
return RECV_NO_DATA;
// Readable (or error/hangup): let curl report the actual condition.
result = curl_easy_recv(curl, buf, len, &bytes_recv);
if (result == CURLE_OK)
return (ssize_t)bytes_recv;
return (result == CURLE_AGAIN) ? RECV_NO_DATA : -1;
}
static bool parse_http_header(CURL *curl, HttpHeader *hdr)
{
char buf[MAXDATASIZE];
int total_bytes = 0;
bool hdr_done = false;
memset((void*)hdr, 0, sizeof(HttpHeader));
time_t deadline = mono_sec() + HEADER_TIMEOUT_SEC;
while (hdr_done == false)
{
// Read more data into the buffer; append to existing data if any.
ssize_t bytes_read = curl_recv_(curl, buf + total_bytes, MAXDATASIZE - total_bytes - 1, 0);
if (bytes_read == RECV_NO_DATA)
{
if (mono_sec() >= deadline)
{
log_msg("no HTTP response header within %d s", HEADER_TIMEOUT_SEC);
return false;
}
continue;
}
if (bytes_read <= 0)
return false;
total_bytes += bytes_read;
buf[total_bytes] = 0;
// Extract each line
int bytes_consumed = 0;
while (total_bytes > 0)
{
int line_len = 0;
const char *line = buf + bytes_consumed;
// Get length of line
char *eol = strstr(line, HTTP_EOL_STR);
if (eol)
{
*eol = 0; // Mark end of line
line_len = eol - line + HTTP_EOL_LEN;
bytes_consumed += line_len;
}
else
{
break; // No more lines; go read more data from socket.
}
// Set flags based on the line string.
if (strncmp(line, "", line_len) == 0)
{
// End of header; exit function
hdr_done = true;
break;
}
else if (strncmp(line, "HTTP/1.1 200 OK", line_len) == 0 ||
strncmp(line, "HTTP/1.0 200 OK", line_len) == 0)
{
hdr->received_ok = true;
}
else if (strncmp(line, "Ntrip-Version: Ntrip/2.0", line_len) == 0)
{
hdr->ntrip_v2 = true;
}
else if (strncmp(line, "Content-Type: gnss/data", line_len) == 0)
{
hdr->content_type_gnss_data = true;
}
else if (strncmp(line, "Transfer-Encoding: chunked", line_len) == 0)
{
hdr->chunky_mode = true;
}
}
// shift unused bytes to the beginning of the array.
total_bytes -= bytes_consumed;
memmove(buf, buf + bytes_consumed, total_bytes);
}
return true;
}
int main(int argc, char **argv)
{
struct Args args;
setbuf(stdout, 0);
setbuf(stdin, 0);
setbuf(stderr, 0);
#ifndef WINDOWSVERSION
signal(SIGALRM,sighandler_alarm);
signal(SIGINT,sighandler_int);
alarm(ALARMTIME);
#else
WSADATA wsaData;
if(WSAStartup(MAKEWORD(1,1),&wsaData))
{
fprintf(stderr, "Could not init network access.\n");
return 20;
}
#endif
// setup reading from stdin (IPC pipe) to non-blocking
int flags = fcntl(STDIN_FD, F_GETFL);
fcntl(STDIN_FD, F_SETFL, flags | O_NONBLOCK);
#ifdef NTRIPCLIENT_DEBUG_LOG
// Append so a restart does not wipe the evidence of why the previous instance died.
flogfile = fopen("/home/debian/ntripclient/ntripclient.log", "a");
if (!flogfile) {
return 20;
}
fprintf(flogfile, "args...\n");
for (int idx = 0; idx < argc; idx++) {
fprintf(flogfile, "%s ", argv[idx]);
}
fprintf(flogfile, "\n");
fflush(flogfile);
unsigned int count = 0;
#endif // NTRIPCLIENT_DEBUG_LOG
if(getargs(argc, argv, &args))
{
struct serial sx;
FILE *ser = 0;
char nmeabuffer[200] = "$GPGGA,"; /* our start string */
size_t nmeabufpos = 0;
size_t nmeastarpos = 0;
char last_gga[sizeof(nmeabuffer)]; /* newest GGA sent, re-sent on (re)connect */
size_t last_gga_len = 0;
int reconnect_backoff = 0; /* seconds before the next session attempt */
if(args.serdevice)
{
const char *e = SerialInit(&sx, args.serdevice, args.baud,
args.stopbits, args.protocol, args.parity, args.databits, 1);
if(e)
{
fprintf(stderr, "%s\n", e);
return 20;
}
if(args.serlogfile)
{
if(!(ser = fopen(args.serlogfile, "a+")))
{
SerialFree(&sx);
fprintf(stderr, "Could not open serial logfile.\n");
return 20;
}
}
}
do
{
int error = 0;
sockettype sockfd = 0;
int numbytes;
char buf[MAXDATASIZE]; // multipurpose buffer for I/O with the socket or IPC
struct sockaddr_in their_addr; /* connector's address information */
struct hostent *he;
struct servent *se;
const char *server, *port, *proxyserver = 0;
char proxyport[6];
char *b;
long i;
long session_rtcm_bytes = 0;
if(reconnect_backoff)
{
log_msg("reconnecting in %d s", reconnect_backoff);
#ifdef WINDOWSVERSION
Sleep(reconnect_backoff*1000);
#else
sleep(reconnect_backoff);
#endif
}
#ifndef WINDOWSVERSION
alarm(ALARMTIME);
#endif
// set up server and port
if(args.proxyhost)
{
int p;
if((i = strtol(args.port, &b, 10)) && (!b || !*b))
p = i;
else if(!(se = getservbyname(args.port, 0)))
{
fprintf(stderr, "Can't resolve port %s.", args.port);
stop = 1;
}
else
{
p = ntohs(se->s_port);
}
if(!stop && !error)
{
snprintf(proxyport, sizeof(proxyport), "%d", p);
port = args.proxyport;
proxyserver = args.server;
server = args.proxyhost;
}
}
else
{
server = args.server;
port = args.port;
}
// create socket to NTRIP caster/server
if(!stop && !error)
{
memset(&their_addr, 0, sizeof(struct sockaddr_in));
if((i = strtol(port, &b, 10)) && (!b || !*b))
their_addr.sin_port = htons(i);
else if(!(se = getservbyname(port, 0)))
{
fprintf(stderr, "Can't resolve port %s.", port);
stop = 1;
}
else
{
their_addr.sin_port = se->s_port;
}
if(!stop && !error)
{
if(!(he=gethostbyname(server)))
{
fprintf(stderr, "Server name lookup failed for '%s'.\n", server);
error = 1;
}
else if((sockfd = socket(AF_INET, (args.mode == UDP ? SOCK_DGRAM :
SOCK_STREAM), 0)) == -1)
{
myperror("socket");
error = 1;
}
else
{
their_addr.sin_family = AF_INET;
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
}
}
}
// this block of code is very long and difficult to read. I'll attempt
// to summarize here.
//
// There are three major sections below. Use the text below as search
// strings to jump to the specific section:
// Handle UDP mode
// Handle RTSP mode
// Handle all other modes
//
// In all cases, an http request for RTCM data is sent, an http response
// is expected/processed. In addition for the other modes, NMEA GGA
// sentences are received from a GGA source and sent to the NTRIP
// caster/server. The GGA source can be either a serial device (e.g.
// GPS receiver) or an IPC pipe (e.g MATE).
if(!stop && !error)
{
// Handle UDP mode
if(args.mode == UDP)
{
unsigned int session;
int tim, seq, init;
char rtpbuf[1526];
int i=12, j;
init = time(0);
srand(init);
session = rand();
tim = rand();
seq = rand();
rtpbuf[0] = (char)(2<<6);
/* padding, extension, csrc are empty */
rtpbuf[1] = 97;
/* marker is empty */
rtpbuf[2] = (seq>>8)&0xFF;
rtpbuf[3] = (seq)&0xFF;
rtpbuf[4] = (tim>>24)&0xFF;
rtpbuf[5] = (tim>>16)&0xFF;
rtpbuf[6] = (tim>>8)&0xFF;
rtpbuf[7] = (tim)&0xFF;
/* sequence and timestamp are empty */
rtpbuf[8] = (session>>24)&0xFF;
rtpbuf[9] = (session>>16)&0xFF;
rtpbuf[10] = (session>>8)&0xFF;
rtpbuf[11] = (session)&0xFF;
++seq;
j = snprintf(rtpbuf+i, sizeof(rtpbuf)-i-40, /* leave some space for login */
"GET /%s HTTP/1.1\r\n"
"Host: %s\r\n"
"Ntrip-Version: Ntrip/2.0\r\n"
"User-Agent: %s/%s\r\n"
"%s%s%s"
"Connection: close%s",
args.data ? args.data : "", args.server, AGENTSTRING, revisionstr,
args.nmea ? "Ntrip-GGA: " : "", args.nmea ? args.nmea : "",
args.nmea ? "\r\n" : "",
(*args.user || *args.password) ? "\r\nAuthorization: Basic " : "");
i += j;
if(i > (int)sizeof(rtpbuf)-40 || j < 0) /* second check for old glibc */
{
fprintf(stderr, "Requested data too long\n");
stop = 1;
}
else
{
i += encode(rtpbuf+i, sizeof(rtpbuf)-i-4, args.user, args.password);
if(i > (int)sizeof(rtpbuf)-4)
{
fprintf(stderr, "Username and/or password too long\n");
stop = 1;
}
else
{
struct sockaddr_in local;
socklen_t len;